code stringlengths 2 1.05M |
|---|
/**
* add googlefont
*/
WebFontConfig = {
google: { families: [ 'Ubuntu:400,300,300italic,400italic,500,500italic,700,700italic:latin,latin-ext' ] }
};
(function() {
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
|
var siteListTable;
var siteListEditor;
var wordListTable;
$(document).ready(function () {
// First
generateSiteListTable();
// Second
generateWordsTable();
});
//Reload the page after user dismisses the modal (wrong URL alert)
$('#url-alert-modal').on('hidden.bs.modal', function(e){
location.reload();
});
function generateSiteListTable() {
siteListEditor = new $.fn.dataTable.Editor( {
ajax: function ( method, url, d, successCallback, errorCallback ) {
if ( d.action === 'create' ) {
//console.log(JSON.stringify(d.data[0]));
var data = d.data[0];
$.ajax({
type: "POST",
url: "./rest/website",
data: JSON.stringify(data),
success: successCallback,
error: errorCallback,
contentType: "application/json",
});
}
else if ( d.action === 'edit' ) {
console.log(JSON.stringify(d.data))
var data = d.data;
$.ajax({
type: "PUT",
url: "./rest/website",
data: JSON.stringify(data),
success: successCallback,
error: errorCallback,
contentType: "application/json",
});
}
else if ( d.action === 'remove' ) {
/*console.log(JSON.stringify(d.data))
$.ajax({
type: "DELETE",
url: "./rest/website",
data: JSON.stringify(d.data),
success: successCallback,
error: errorCallback,
contentType: "application/json",
});*/
}
},
idSrc: "id",
table: "#site-list-table",
fields: [ {
label: "Adress:",
name: "address"
}, {
label: "Description",
name: "description"
}, {
label: "Crawldepth",
name: "depth"
}, {
label: "Active",
name: "active",
type: "checkbox",
options: [
{ label: '', value: 1 }
]
}
]
} );
siteListEditor.on( 'preSubmit', function ( e, o, action ) {
console.log("Checking");
if ( action === 'create' ) {
console.log("in if");
var url = siteListEditor.field( 'address' );
var depth = siteListEditor.field('depth');
console.log(url.val());
//Beware of CORS ;)
/* $.ajax({ cache: false,
url: url.val(),
async: false
}).done(function (data) {
console.log("success");
}).fail(function (jqXHR, textStatus) {
url.error("Invalid URL: Maybe add slash at the end");
});*/
if(depth.val()<1){
depth.error("Depth must be at least 1");
}
// If any error was reported, cancel the submission so it can be corrected
if ( this.inError() ) {
console.log("inerror");
return false;
}
}
} );
//console.log(tableData);
siteListTable = $('#site-list-table').DataTable({
dom: "Bfrtip",
ajax: "./rest/website",
columns: [
{ data: "id" },
{ data: "address" },
{ data: "description" },
{ data: "depth" },
{ data: "active" },
{ data: "lCrawled"},
{ data: null }
//Renderfunction below
],
columnDefs:
[
{ render: function ( data, type, row ) {
return "<a class='btn btn-primary' href='./SiteOverview/"+row.id+"'>Details</a>"
},
targets: 6 },
{ orderable: false, targets: 6 },
{ searchable: false, targets: 6 }
],
select: 'single',
buttons: [
{ extend: "create", editor: siteListEditor },
{ extend: "edit", editor: siteListEditor }
// { extend: "remove", editor: siteListEditor }
]
} );
siteListEditor
.on( 'initEdit', function () { siteListEditor.disable( "address" ); siteListEditor.show( "active" ); } )
.on( 'initCreate', function () { siteListEditor.enable( "address" ); siteListEditor.hide( "active" ); } );
}
function generateWordsTable() {
wordListEditor = new $.fn.dataTable.Editor( {
ajax: function ( method, url, d, successCallback, errorCallback ) {
if ( d.action === 'create' ) {
//Not implemented
}
else if ( d.action === 'edit' ) {
console.log(JSON.stringify(d.data));
var data = d.data;
$.ajax({
type: "PUT",
url: "./rest/word",
data: JSON.stringify(data),
success: successCallback,
error: errorCallback,
contentType: "application/json",
});
}
else if ( d.action === 'remove' ) {
//Not implemented
}
},
idSrc: "word.word",
table: "#word-list-table",
fields: [
{
label: "Wordtype",
name: "word.wType",
type: "select",
placeholder: "Select Wordtype"
},{
label: "Active",
name: "word.active",
type: "checkbox",
options: [
{ label: '', value: 1 }
]
}
]
} );
wordListTable = $('#word-list-table').DataTable({
dom: "Bfrtip",
ajax: "./rest/word",
order: [[ 1, "desc" ]],
columns: [
{ data: "word.word" },
{ data: "word.amount" },
{ data: "wTypes.name"},
{ data: "word.active" },
{ data: null}
//Render Function below
],
columnDefs:
[
{ render: function ( data, type, row ) {
return "<a class='btn btn-primary' href='./WordOverview/"+row.word.word+"'>Details</a>"
},
targets: 4},
{ orderable: false, targets: 4 },
{ searchable: false, targets: 4 }
],
select: 'single',
buttons: [{ extend: "edit", editor: wordListEditor }]
} );
}
|
import React from 'react';
export default function TextInput(props) {
return (
<div className="text-input-container">
<input
name={props.name}
placeholder={props.placeholder}
value={props.text}
onChange={props.onChange}
type={props.type}
/>
</div>
);
}
|
exports.port = 3000;
exports.mysqlPassport = {
port : '3306',
username : 'root',
password : '',
}
exports.mysql = {
URL: 'mysql://root:@127.0.0.1:3306/foodsystem'
};
exports.companyName = 'Acme, Inc.';
exports.projectName = 'Drywall';
exports.systemEmail = 'your@email.addy'; |
var baseUrl = contextPath + "/rest/abtesting/1.0";
AJS.toInit(function() {
new AJS.RestfulTable({
autoFocus: true,
el: jQuery("#feature-battles-table"),
allowReorder: true,
resources: {
all: baseUrl + "/feature_battles",
self: baseUrl + "/feature_battle"
},
columns: [
{
id: "id",
header: ""
},
{
id: "threshold",
header: AJS.I18n.getText("feature.battle.threshold")
},
{
id: "goodOld",
header: AJS.I18n.getText("feature.battle.goodold")
},
{
id: "newAndShiny",
header: AJS.I18n.getText("feature.battle.newandshiny")
}
]
});
}); |
var indexSectionsWithContent =
{
0: "abcdefghiklmnprstuvwxy~",
1: "abgpstuw",
2: "abcdefgiklmprstuw~",
3: "abcdefhimnprstvwxy",
4: "n"
};
var indexSectionNames =
{
0: "all",
1: "classes",
2: "functions",
3: "variables",
4: "pages"
};
var indexSectionLabels =
{
0: "All",
1: "Classes",
2: "Functions",
3: "Variables",
4: "Pages"
};
|
'use strict';
var util = require('util');
var Matrix = require('./geometry/Matrix');
var Point = require('./geometry/Point');
var Polygon = require('./geometry/Polygon');
var Animation = require('./animation/Animation');
var Actor = function () {
/**
* The private width of this actor in its own coordinate system.
* @type {number}
*/
this.width = 1;
/**
* The private height of this actor in its own coordinate system.
* @type {number}
*/
this.height = 1;
/**
* The x position of the actor on a hypothetical Stage where 0,0 is the top left corner and the width is 1 unit.
* @type {Number}
*/
this.x = 0;
/**
* The y position of the actor on a hypothetical Stage where 0,0 is the top left corner and the height is 1 unit.
* @type {Number}
*/
this.y = 0;
/**
* The z-index of this Actors relative to the other Actors on the Stage.
* @type {Number}
*/
this.z = 0;
/**
* The scale of the actor where a scale of 1.0 will fill the entire stage.
* @type {Number}
*/
this.scale = 0.10;
/**
* The clockwise rotation of the actor on the Stage in degrees.
* @type {Number}
*/
this.rotate = 0;
/**
* If true, the bounding box will be visible.
* @type {Boolean}
*/
this.drawBoundingBox = false;
this.animations = {};
this.animation = null;
};
/**
* Adds an animation to this actor.
* @param name {string} The name of the animation.
* @param animation {Animation} The Animation object to add.
*/
Actor.prototype.addAnimation = function (name, animation) {
if (!name) {
throw Error('Actor.addAnimation requires a name argument.');
}
if(!animation) {
throw Error('Actor.addAnimation requires an animation argument.');
}
if(animation.constructor !== Animation) {
throw Error('The animation argument passed to Actor.addAnimation should be an Animation.');
}
this.animations[name] = animation;
};
/**
* Sets the active animation.
* @param name {string} The name of the animation.
* @param reset {boolean} If true, the animation will be forced, wven if it already active. This will cause it to start over.
*/
Actor.prototype.setActiveAnimation = function (name, reset) {
if (!this.animations[name]) {
throw Error('There is no animation called "' + name + '".');
}
if (reset || this.animation !== this.animations[name]) {
this.animation = this.animations[name];
this.animation.reset();
}
};
/**
* Update the Animation.
* @param game {object} A Game instance.
*/
Actor.prototype.update = function (game) {
if (this.animation) {
this.animation.update(game);
}
};
/**
* Draw the current animation frame.
* @param context {CanvasRenderingContext2D} A CanvasRenderingContext2D
*/
Actor.prototype.draw = function (context) {
if (this.animation) {
this.animation.draw(context);
}
};
/**
* The stage Matrix can be used to place this actor into the Stage coordinate system.
* @param canvas {HTMLCanvasElement} The stages HTMLCanvasElement.
* @returns {Matrix} A Matrix transformation.
*/
Actor.prototype.getStageMatrix = function (canvas) {
var x = this.x * canvas.width;
var y = this.y * canvas.height;
var width = this.scale * canvas.width;
var height = this.scale * canvas.height;
return new Matrix()
.translate(x, y)
.clockwise(this.rotate, width / 2, height / 2)
.scale(width / this.width , height / this.height);
};
/**
* Retrieve the bounding box for this actor in the stage coordinate system.
* @param canvas {HTMLCanvasElement} The stages HTMLCanvasElement.
* @returns {Polygon} A Polygon for the bounding box.
*/
Actor.prototype.getStageBounds = function (canvas) {
var matrix = this.getStageMatrix(canvas);
return new Polygon([
matrix.transform(new Point(0, 0)),
matrix.transform(new Point(0, this.height)),
matrix.transform(new Point(this.width, this.height)),
matrix.transform(new Point(this.width, 0))
]);
};
module.exports = Actor; |
/**
* @copyright 2015 Prometheus Research, LLC
*/
import addStyleToDOM from 'style-loader/addStyles';
import createHash from 'murmurhash-js/murmurhash3_gc';
import prefix from 'inline-style-prefix-all';
import CSSPropertyOperations from 'react-css-property-operations';
import isArray from 'lodash/isArray';
import toDashCase from 'lodash/kebabCase';
import isPlainObject from 'lodash/isPlainObject';
/**
* Special key which designates the rules which should be applied even if no
* variant is being active.
*/
const BASE = 'base';
/**
* Special key which is used to store className in mapping.
*/
const CLASSNAME = 'className';
/**
* Styles we want to be added to every CSS class.
*/
const DEFAULT_STYLE = {
boxSizing: 'border-box'
};
/**
* Variant names we want to see compiled as CSS pseudo classes.
*/
const SUPPORTED_PSEUDO_CLASSES = {
focus: true,
hover: true,
active: true,
checked: true,
default: true,
disabled: true,
empty: true,
enabled: true,
firstChild: true,
firstOfType: true,
fullscreen: true,
indeterminate: true,
invalid: true,
lastChild: true,
left: true,
link: true,
onlyChild: true,
optional: true,
required: true,
right: true,
root: true,
scope: true,
target: true,
valid: true,
visited: true,
};
/**
* Create a new stylesheet from stylesheet spec.
*/
export function create(spec, id = 'style') {
return new DOMStylesheet(parseSpecToStyle(spec), id);
}
/**
* Check if object is a valida stylesheet.
*/
export function isStylesheet(obj) {
return obj instanceof DOMStylesheet;
}
/**
* Produce a new stylesheet by overriding an existing one with a new stylesheet
* spec.
*/
function overrideStylesheet(stylesheet, override, id) {
override = isStylesheet(override) ?
override.style :
parseSpecToStyle(override);
if (id == null) {
id = stylesheet.id;
}
let style = overrideStyle(stylesheet.style, override);
return new DOMStylesheet(style, id);
}
function overrideStyle(style, override) {
let nextStyle = {...style};
for (let key in override) {
if (!override.hasOwnProperty(key)) {
continue;
}
if (key === BASE) {
nextStyle[key] = {...nextStyle[key], ...override[key]};
} else {
nextStyle[key] = overrideStyle(nextStyle[key], override[key]);
}
}
return nextStyle;
}
function sanitizeID(id) {
return id.replace(/[^0-9a-zA-Z\-_]/g, '_');
}
/**
* DOM stylesheet is a collection of classes which are applied to a single DOM
* element.
*/
class DOMStylesheet {
constructor(style, id) {
this.style = style;
this.id = sanitizeID(id);
this.hash = createHash(JSON.stringify(this.style), 42);
this.uid = `${this.id}--${this.hash}`;
this._refs = 0;
this._remove = null;
this._disposePerform = this._disposePerform.bind(this);
this._disposeTimer = null;
this._compiled_memoized = null;
}
get _compiled() {
if (this._compiled_memoized === null) {
let {css, mapping} = compileStyle(this.style, this.id, this.hash);
this._compiled_memoized = {css: css.join('\n'), mapping};
}
return this._compiled_memoized;
}
get css() {
return this._compiled.css;
}
get mapping() {
return this._compiled.mapping;
}
asClassName(variant = {}) {
return resolveVariantToClassName(this.mapping, variant).join(' ');
}
use() {
this._refs = this._refs + 1;
if (this._disposeTimer !== null) {
clearTimeout(this._disposeTimer);
this._disposeTimer = null;
}
if (this._remove === null) {
this._remove = addStyleToDOM([[this.uid, this.css]]);
}
return this;
}
dispose() {
this._refs = this._refs - 1;
if (this._disposeTimer === null) {
this._disposeTimer = setTimeout(this._disposePerform, 0);
}
return this;
}
_disposePerform() {
if (this._refs < 1) {
this._remove();
this._remove = null;
}
}
override(spec, id) {
return overrideStylesheet(this, spec, id);
}
}
/**
* Resolve variant to CSS class name.
*/
function resolveVariantToClassName(mapping, variant) {
let classList = [];
for (let key in mapping) {
if (key === CLASSNAME) {
classList.push(mapping[key]);
} else if (variant[key]) {
let subClassList = resolveVariantToClassName(mapping[key], variant);
for (let i = 0; i < subClassList.length; i++) {
classList.push(subClassList[i]);
}
}
}
return classList;
}
/**
* Parse style spec to style object.
*/
function parseSpecToStyle(spec, root = true) {
let styleBase = root ? {...DEFAULT_STYLE} : {};
let style = {[BASE]: styleBase};
for (let key in spec) {
if (!spec.hasOwnProperty(key)) {
continue;
}
let item = spec[key];
if (isPlainObject(item)) {
style[key] = parseSpecToStyle(item, false);
} else {
styleBase[key] = item; //compileValue(key, item);
}
}
style[BASE] = prefix(style[BASE]);
for (let key in style[BASE]) {
if (!style[BASE].hasOwnProperty(key)) {
continue;
}
style[BASE][key] = compileValue(key, style[BASE][key]);
}
return style;
}
/**
* Compile style into CSS string with mapping from variant names to CSS class
* names.
*/
function compileStyle(style, id, hash, variants = []) {
let mapping = {};
let css = [];
let variant = variants.length === 0 ? null : variants[variants.length - 1];
for (let key in style) {
if (!style.hasOwnProperty(key)) {
continue;
}
let value = style[key];
if (key === BASE) {
let selector = compileSelector(id, hash, variants);
let [className] = selector;
css.push(compileClass(selector, value));
if (variant !== null) {
mapping[variant] = mapping[variant] || {};
mapping[variant][CLASSNAME] = className;
} else {
mapping[CLASSNAME] = className;
}
} else {
let subResult = compileStyle(value, id, hash, variants.concat(key));
mapping[key] = subResult.mapping;
css = css.concat(subResult.css);
}
}
return {css, mapping};
}
/**
* Compile class name and rule set into CSS class.
*/
function compileClass(selector, ruleSet) {
let css = `${selector.map(item => '.' + item).join(', ')} { ${CSSPropertyOperations.createMarkupForStyles(ruleSet)} }`;
return css;
}
function compileSelector(id, hash, path) {
if (path.length === 0) {
return [`${id}--${hash}`];
}
if (!SUPPORTED_PSEUDO_CLASSES[path[path.length - 1]]) {
return [`${id}--${path.join('--')}--${hash}`];
}
let cutIndex = -1;
for (let i = path.length - 1; i >= 0; i--) {
if (!SUPPORTED_PSEUDO_CLASSES[path[i]]) {
cutIndex = i;
break;
}
}
let staticPath = path.slice(0, cutIndex + 1);
staticPath.unshift(id);
let variantPath = path.slice(cutIndex + 1);
let selector = [];
selector.push(`${staticPath.concat(variantPath).join('--')}--${hash}`);
for (let i = 0; i < variantPath.length; i++) {
let variant = variantPath.slice(i).map(toDashCase).join(':');
selector.push(`${staticPath.join('--')}--${hash}:${variant}`);
staticPath.push(variantPath[i]);
}
return selector;
}
// TODO: This is inefficient but we only hit this when we encounter arrays in
// values. Still this will be fixed when we port all packages which use
// react-dom-stylesheet to react-stylesheet.
function dangerousStyleValue(key, value) {
let markup = CSSPropertyOperations.createMarkupForStyles({[key]: value});
let [_key, styleValue] = markup.split(':');
return styleValue.slice(0, styleValue.length - 1);
}
function compileValue(key, value) {
let compiled = '';
if (isArray(value)) {
for (let i = 0; i < value.length; i++) {
if (i === 0) {
compiled += dangerousStyleValue(key, liftValue(value[i]));
} else {
compiled += ';' + key + ':' + dangerousStyleValue(key, liftValue(value[i]));
}
}
} else {
compiled = liftValue(value);
}
return compiled;
}
function liftValue(value) {
return value && value.toCSS ? value.toCSS() : value;
}
|
match.on('end', function() {
var players = match.getPlayers();
for (var i = 0; i < players.length; i++) {
if (players[i].getTeam() == null) {
continue;
}
var player = players[i];
var kill = player.getKills();
var death = player.getDeaths();
var jp_message = '`a----- `6試合統計 `a-----\n`aKills: `6' + kill + ' `aDeaths: `6' + death;
var message = '`a----- `6This game stats `a-----\n`aKills: `6' + kill + ' `aDeaths: `6' + death;
if (player.getLocale() == 'ja_JP') {
player.sendMessage(jp_message);
} else {
player.sendMessage(message);
}
player.playSound("LEVEL_UP", 1, 1);
}
});
|
/*!
今天,无意间看到这样一个面试题:
编写一个javscript函数 fn,该函数有一个参数 n(数字类型),其返回值是一个数组,该数组内是 n 个随机且不重复的整数,且整数取值范围是 [2, 32]。
那么,就试着写一下代码吧。
*/
function fn(n) {
// 对输入做要求过滤
if (typeof n !== 'number') {
return [];
}
var min = 2; // 定义下限
var max = 32; // 定义上限
// 强制转换为整数
n = parseInt(n, 10);
var i = 0; // 循环变量
var oArray = []; // 被提取的数组
// 生成被提取的数组
for (i = min; i <= max; i++) {
oArray.push(i);
}
// 输入的数值需落在1到提取数组的长度中
if (n < 1 || n > oArray.length) { // max - min
return [];
}
var ret = []; // 生成的目标数组
// 生成随机数并放入到目标数组中
for (i = 0; i < n; i++) {
var rnd = getRnd(0, oArray.length - 1);
// ret = ret.concat(oArray.splice(rnd, 1));
// 或者这样写:
ret.push(oArray.splice(rnd, 1)[0]);
}
return ret;
// 生成指定范围内的随机整数
function getRnd(a, b) {
var r = Math.random();
// 生成随机数的代码
// return a + Math.round((b - a) * r);
// 另一种随机数生成方式,该方法提升了边界值的几率
return Math.floor(r * (b - a + 1) + a);
}
}
// 临时测试代码
for (var i = 1; i <= 20; i++) {
console.log(i, fn(i));
}
|
'use strict';
var pathUtil = require('path');
var Q = require('q');
var gulp = require('gulp');
var rollup = require('rollup');
var less = require('gulp-less');
var jetpack = require('fs-jetpack');
var utils = require('./utils');
var generateSpecsImportFile = require('./generate_specs_import');
var projectDir = jetpack;
var srcDir = projectDir.cwd('./app');
var destDir = projectDir.cwd('./build');
var paths = {
copyFromAppDir: [
'./node_modules/**',
'./vendor/**',
'./lib/**',
'./**/*.html',
'./images/*'
]
};
// -------------------------------------
// Tasks
// -------------------------------------
gulp.task('clean', function(callback) {
return destDir.dirAsync('.', { empty: true });
});
var copyTask = function () {
return projectDir.copyAsync('app', destDir.path(), {
overwrite: true,
matching: paths.copyFromAppDir
});
};
gulp.task('copy', ['clean'], copyTask);
gulp.task('copy-watch', copyTask);
var bundle = function (src, dest) {
var deferred = Q.defer();
rollup.rollup({
entry: src
}).then(function (bundle) {
var jsFile = pathUtil.basename(dest);
var result = bundle.generate({
format: 'iife',
sourceMap: true,
sourceMapFile: jsFile
});
return Q.all([
destDir.writeAsync(dest, result.code + '\n//# sourceMappingURL=' + jsFile + '.map'),
destDir.writeAsync(dest + '.map', result.map.toString())
]);
}).then(function () {
deferred.resolve();
}).catch(function (err) {
console.error(err);
});
return deferred.promise;
};
var bundleApplication = function () {
return Q.all([
bundle(srcDir.path('background.js'), destDir.path('background.js')),
bundle(srcDir.path('app.js'), destDir.path('app.js'))
]);
};
var bundleSpecs = function () {
generateSpecsImportFile().then(function (specEntryPointPath) {
return Q.all([
bundle(srcDir.path('background.js'), destDir.path('background.js')),
bundle(specEntryPointPath, destDir.path('spec.js'))
]);
});
};
var bundleTask = function () {
if (utils.getEnvName() === 'test') {
return bundleSpecs();
}
return bundleApplication();
};
gulp.task('bundle', ['clean'], bundleTask);
gulp.task('bundle-watch', bundleTask);
var lessTask = function () {
return gulp.src('app/stylesheets/main.less')
.pipe(less())
.pipe(gulp.dest(destDir.path('stylesheets')));
};
gulp.task('less', ['clean'], lessTask);
gulp.task('less-watch', lessTask);
gulp.task('finalize', ['clean'], function () {
var manifest = srcDir.read('package.json', 'json');
// Add "dev" or "test" suffix to name, so Electron will write all data
// like cookies and localStorage in separate places for each environment.
switch (utils.getEnvName()) {
case 'development':
manifest.name += '-dev';
manifest.productName += ' Dev';
break;
case 'test':
manifest.name += '-test';
manifest.productName += ' Test';
break;
}
destDir.write('package.json', manifest);
var configFilePath = projectDir.path('config/env_' + utils.getEnvName() + '.json');
destDir.copy(configFilePath, 'env_config.json');
});
gulp.task('watch', function () {
gulp.watch('app/**/*.js', ['bundle-watch']);
gulp.watch(paths.copyFromAppDir, { cwd: 'app' }, ['copy-watch']);
gulp.watch('app/**/*.less', ['less-watch']);
});
gulp.task('build', ['bundle', 'less', 'copy', 'finalize']);
|
"use strict";
load.provide("quest.ui", function() {
load.require("dusk.sgui.FancyRect");
load.require("dusk.sgui.Grid");
load.require("dusk.sgui.PlusText");
load.require("dusk.sgui.FocusChecker");
load.require("dusk.sgui.FocusCheckerRect");
load.require("dusk.sgui.extras.MatchedSize");
load.require("dusk.sgui.FpsMeter");
var LayeredRoom = load.require("dusk.rooms.sgui.LayeredRoom");
var RegionDisplay = load.require("dusk.tiles.sgui.RegionDisplay");
load.require("dusk.sgui.Feed");
load.require("dusk.sgui.extras.Die");
load.require("dusk.sgui.extras.Fade");
var dusk = load.require("dusk");
var c = load.require("dusk.sgui.c");
var sgui = load.require("dusk.sgui");
var root = sgui.get("default", true);
root.mouseFocus = false;
root.allowMouse = true;
//Menu
root.get("menu", "Group").update({
"allowMouse":true,
"children":{
"back":{
"type":"FancyRect",
"width":0,
"height":0,
"x":50,
"y":50,
"back":"fancyRect/back.png",
"top":"fancyRect/top.png",
"bottom":"fancyRect/bottom.png",
"left":"fancyRect/left.png",
"right":"fancyRect/right.png",
"topLeft":"fancyRect/topLeft.png",
"topRight":"fancyRect/topRight.png",
"bottomLeft":"fancyRect/bottomLeft.png",
"bottomRight":"fancyRect/bottomRight.png",
"radius":2,
"extras":{
"size":{
"type":"MatchedSize",
"paddingTop":10,
"paddingBottom":10,
"paddingRight":10,
"paddingLeft":10,
"base":"../menu",
}
}
},
"menu":{
"type":"Grid",
"allowMouse":true,
"globals":{
"type":"PlusText",
"plusType":"FocusCheckerRect",
"behind":true,
"mouseCursor":"pointer",
"allowMouse":true,
"label":{
"colour":"#cccccc",
"size":16
},
"plus":{
"width":150,
"height":24,
"active":"",
"focused":"",
"inactive":"",
"colour":"",
"bInactive":"#000000",
"bFocused":"#000000",
"bActive":"#999900",
"bwActive":3,
"radius":3
}
},
"x":50,
"y":50,
"hspacing":5,
"visible":false
}
}
});
// FPS Meter
root.get("fps", "FpsMeter").update({
"type":"FpsMeter",
"xOrigin":"right",
"yOrigin":"bottom"
});
// Feed on right of screen
root.get("actionFeed", "Group").update({
"xDisplay":"expand",
"children":{
"feed":{
"type":"Feed",
"xOrigin":"right",
"x":-5,
"y":5,
"width":150,
"globals":{
"size":16,
"borderColour":"#ffffff",
"borderSize":3,
"height":22,
"type":"Label",
"colour":"#000000",
"extras":{
"fade":{
"type":"Fade",
"delay":60,
"on":true,
"then":"die",
"from":1.0,
"to":0.0,
"duration":30
},
"die":{
"type":"Die"
}
}
},
"append":[
{"text":"Started!"}
]
}
}
});
return root;
});
|
'use strict';
const postcss = require('postcss');
const DEFAULT_OPTIONS = {
display: 'block'
};
/**
* Clear: fix; rule handler
* @param {string} decl current decleration
*/
function clearFix(decl, opts) {
let origRule = decl.parent,
ruleSelectors = origRule.selectors,
newRule;
if (decl.value !== 'fix') {
return;
}
ruleSelectors = ruleSelectors
.map(ruleSelector => ruleSelector + ':after').join(',\n');
// Insert the :after rule before the original rule
newRule = origRule.cloneAfter({
selector: ruleSelectors
}).removeAll();
newRule.append({
prop: 'content',
value: '\'\'',
source: decl.source
}, {
prop: 'display',
value: opts.display,
source: decl.source
}, {
prop: 'clear',
value: 'both',
source: decl.source
});
// If the original rule only had clear:fix in it, remove the whole rule
if (decl.prev() === undefined && decl.next() === undefined) {
origRule.remove();
} else {
// Otherwise just remove the delcl
decl.remove();
}
}
module.exports = postcss.plugin('postcss-clearfix', function(opts) {
opts = opts || {};
opts = Object.assign({}, DEFAULT_OPTIONS, opts);
return function(css) {
css.walkDecls('clear', function(decl) {
clearFix(decl, opts);
});
};
});
|
// Imports
var bescribe = require('be-paige/bescribe'),
common = require('../common/common.js'),
data = require('../common/data.js'),
TheQuizPage = require('../../lib/the-quiz/the-quiz.js'),
SignUpPage = require('../../lib/sign-up/sign-up.js'),
MonthlyBoxPage = require('../../lib/monthly-box/monthly-box.js'),
CreateAccountPage = require('../../lib/customer/account/create.js'),
SignUpHelper = require('./sign-upHelper.js');
// Global variables
var signUpPageContext;
// Tests
bescribe("Sign up", common.config, function(context, describe, it) {
// Before each test, take the quizz and go the signup page
beforeEach(function() {
signUpPageContext = context.Page.build()
.redirectTo(TheQuizPage)
.goEndQuiz()
.clickYesShippingUsa()
.submitQuizForm()
.switchTo(SignUpPage);
});
describe("Accepted registration", function() {
it("Should sign up successfully", function() {
signUpPageContext
.createNewAccount(data.createNewAccount())
.switchTo(MonthlyBoxPage)
.onPage();
});
});
describe("Refused registration", function() {
it("Should refused the sign-up because the account already exists", function() {
signUpPageContext
.createNewAccount(data.account)
.switchTo(CreateAccountPage)
.onPage();
});
});
}); |
var site = (function() {
console.log('hello world!');
// Export as AMD module
if (typeof define === "function" && define.amd) {
define('site', [], function() { });
}
}()); |
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments)).next());
});
};
const Helpers_1 = require('../Common/Helpers');
const SearchResults_1 = require('./SearchResults');
var CodeAPI;
(function (CodeAPI) {
function search(what, page = 0) {
return __awaiter(this, void 0, void 0, function* () {
var options = {
search: what,
page: page,
pageSize: 1,
includePayload: true,
skipPreviousSnippetVersions: true
};
var jsonAsString = yield Helpers_1.Helpers.API.DownloadJson(`http://babylonjs-api.azurewebsites.net/api/search`, true, options);
var searchResults = new SearchResults_1.SearchResults.SearchResult();
var results = JSON.parse(jsonAsString);
//avoid duplicate (multiple versions in the search results)
if (results.snippets && results.snippets.length > 0) {
var snippet = results.snippets[0];
var code = snippet.JsonPayload.replace(/\\\"/g, "\"")
.replace(/\\r\\n/g, "\r\n")
.replace(/\\t/g, "\t")
.match(new RegExp("((\\r\\n)((?!\\r\\n).)*){2}" + what + "(((?!\\r\\n).)*(\\r\\n)){2}", "g"));
var res = new SearchResults_1.SearchResults.SearchResult();
searchResults.name = "Snippet " + snippet.Id;
searchResults.url = "http://www.babylonjs-playground.com/#" + snippet.Id;
searchResults.code = code && code.length > 0 ? code[0].replace(/\r\n/g, "\n\n").replace(/ +/g, ' ') : null;
searchResults.nextPage = page <= results.pageCount ? page + 1 : 0;
}
return new Promise(resolve => {
resolve(searchResults);
});
});
}
CodeAPI.search = search;
})(CodeAPI = exports.CodeAPI || (exports.CodeAPI = {}));
|
version https://git-lfs.github.com/spec/v1
oid sha256:0141d59c3009d8b8836ce619bca33e2927e291e20a3901696df3a21efd0ce65a
size 67695
|
/*
Copyright (c) 2011 Recoset <nicolas@recoset.com> <francois@recoset.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
times.sort();
var hostShare = function(t,h) { return data[t + ";" + h] != undefined ? data[t + ";" + h] : 0; };
var cpi = function(t) { return stats[t] != undefined ? stats[t].observedCPI : 0; };
var clicks = function(t) { return stats[t] != undefined ? stats[t].clicks : 0; };
var cpc = function(t) { return stats[t] != undefined ? stats[t].observedCPC : 0; };
var spent = function(t) { return stats[t] != undefined ? stats[t].total_spent : 0; };
var ctr = function(t) { return stats[t] != undefined ? stats[t].observedCTR : 0; };
var imp = function(t) { return stats[t] != undefined ? stats[t].impressions : 0; };
var gimp = function(t) { return stats[t] != undefined ? (stats[t].ghostImpressions/(stats[t].impressions+stats[t].ghostImpressions)*100).toFixed(2) : 0; };
var gimpAbs = function(t) { return stats[t] != undefined ? stats[t].ghostImpressions : 0; };
var maxImp = pv.max(times.map(imp));
var maxCTR = pv.max(times.map(ctr));
var maxCPI = pv.max(times.map(cpi));
var maxCPC = pv.max(times.map(cpc));
var w = times.length*20,
h = document.body.clientHeight*0.95,
streamGraphHeight = h/3,
x = pv.Scale.ordinal(times).splitBanded(0, w),
y = pv.Scale.linear(0, 1).range(0, streamGraphHeight),
yIMP = pv.Scale.linear(0, maxImp).range(0, h/20)
yGIMP = pv.Scale.linear(0, 100).range(0, h/20)
yCTR = pv.Scale.linear(0, maxCTR).range(0, h/20)
yCPI = pv.Scale.linear(0, maxCPI).range(0, h/20),
yCPC = pv.Scale.linear(0, maxCPC).range(0, h/20),
c= pv.Colors.category19(hosts);
var vis = new pv.Panel()
.width(w)
.height(h);
if (w < document.body.clientWidth) {
vis.left((document.body.clientWidth-w)/2)
.right((document.body.clientWidth-w)/2);
}
vis.add(pv.Bar)
.data(times)
.bottom(9*h/10)
.height(function(d) {return yIMP(imp(d));})
.left( x )
.width( x.range().band )
.fillStyle("#9467bd")
.title(function(d) {return imp(d) + " impressions at " + d + " ($" + (spent(d)/1000000).toFixed(2) + " spent)"});
vis.add(pv.Label).bottom(9.5*h/10).text("Impressions");
vis.add(pv.Bar)
.data(times)
.bottom(8*h/10)
.height(function(d) {return yGIMP(gimp(d));})
.left( x )
.width( x.range().band )
.fillStyle("#aaa")
.title(function(d) {return gimp(d) + "% ghost impressions at " + d + " (abs:"+gimpAbs(d)+")"});
vis.add(pv.Label).bottom(8.5*h/10).text("Ghosts");
vis.add(pv.Bar)
.data(times)
.bottom(7*h/10)
.height(function(d) {return yCPC(cpc(d));})
.left( x )
.width( x.range().band )
.fillStyle("#1f77b4")
.title(function(d) {return "$" + (cpc(d)/1000000).toFixed(2) + " CPC at " + d + " (" + clicks(d) + " clicks)"});
vis.add(pv.Label).bottom(7.5*h/10).text("CPC");
vis.add(pv.Bar)
.data(times)
.bottom(2.5*h/10)
.height(function(d) {return yCTR(ctr(d))})
.left( x )
.width( x.range().band )
.fillStyle("#637939")
.title(function(d) {return (100*ctr(d)).toFixed(3) + "% CTR at " + d + " (" + clicks(d) + " clicks)"});
vis.add(pv.Label).bottom(3*h/10).text("CTR");
vis.add(pv.Bar)
.data(times)
.bottom(1.5*h/10)
.height(function(d) { return yCPI(cpi(d))})
.left( x )
.width( x.range().band )
.fillStyle("#843c39")
.title(function(d) {return "$" + (cpi(d)/1000).toFixed(2) + " CPM at " + d});
vis.add(pv.Label).bottom(2*h/10).text("CPM");
vis.add(pv.Bar).bottom(h/2 - streamGraphHeight/2).left(0).width(w).height(streamGraphHeight).fillStyle("#eee");
vis.add(pv.Layout.Stack)
.layers(hosts)
.values(times)
.order("inside-out")
.offset("silohouette")
.x( function(t) {return x(t) + x.range().band/2 })
.y( function(t, h) {return y(hostShare(t,h)) })
.layer.add(pv.Area)
.fillStyle(function(t,h) {return c(h)})
.title(function(t,h) {return h});
vis.add(pv.Rule)
.data(times)
.left( x )
.strokeStyle(function(s) {return s.indexOf("00") != -1 ? "rgba(233, 233, 233, .9)":"rgba(255, 255, 255, .2)"})
.anchor("right").add(pv.Label)
.visible(function(s) {return s.indexOf("00") != -1})
.text(function(s) {return s})
.textAngle(-Math.PI / 2);
vis.render();
|
/* global Dropkick */
import Ember from 'ember';
import XSelectComponent from 'emberx-select/components/x-select';
export default XSelectComponent.extend({
_dk: null,
settings: {},
createDk: Ember.on('didInsertElement', function() {
this._dk = new Dropkick(this.get('element'), this.get('settings'));
}),
destroyDk: Ember.on('willDestroyElement', function() {
if (this._dk !== null) {
this._dk.dispose();
}
})
});
|
/***********
* Spinner *
***********/
var cursor = require('ansi')(process.stdout);
var spinner = (function() {
var sequence = ["|","/","-","\\"]; //[".", "o", "0", "@", "*"];
var index = 0;
var timer;
var opts = {};
function start(inv, options) {
options = options || {};
opts = options;
if(options.hideCursor) {
cursor.hide();
}
inv = inv || 250;
index = 0;
process.stdout.write(sequence[index]);
timer = setInterval(function() {
process.stdout.write(sequence[index].replace(/./g,"\b"));
index = (index < sequence.length - 1) ? index + 1 : 0;
process.stdout.write(sequence[index]);
},inv);
if(options.doNotBlock) {
timer.unref();
}
}
function stop() {
clearInterval(timer);
if(opts.hideCursor) {
cursor.show();
}
process.stdout.write(sequence[index].replace(/./g,"\b"));
}
function change_sequence(seq) {
if(Array.isArray(seq)) {
sequence = seq;
}
}
return {
start: start,
stop: stop,
change_sequence: change_sequence
};
})();
module.exports = spinner;
|
import React, { Component, Children } from 'react'
import PropTypes from 'prop-types'
import { head, body } from '../utils/gtm'
class ReactGTMProvider extends Component {
constructor(props, context) {
super(props, context)
if (typeof window === 'undefined') {
return
}
this.dataLayer = window.dataLayer || props.dataLayer || []
window.dataLayer = this.dataLayer
}
// componentDidMount() {
// const headElement = document.head || document.querySelector('head')
// const bodyElement = document.body || document.querySelector('body')
// headElement.innerHTML += head(this.props.id)
// bodyElement.innerHTML += body(this.props.id)
// }
getChildContext() {
const { props: { id }, dataLayer } = this
return { id, dataLayer }
}
render() {
return Children.only(this.props.children)
}
}
ReactGTMProvider.propTypes = {
id: PropTypes.string.isRequired,
children: PropTypes.node,
dataLayer: PropTypes.array
}
ReactGTMProvider.defaultProps = {
id: undefined,
children: undefined,
dataLayer: undefined
}
ReactGTMProvider.childContextTypes = {
id: PropTypes.string.isRequired,
dataLayer: PropTypes.array.isRequired
}
export default ReactGTMProvider
|
// Activities service used to communicate Activities REST endpoints
(function () {
'use strict';
angular
.module('activities')
.factory('ActivitiesService', ActivitiesService);
ActivitiesService.$inject = ['$resource'];
function ActivitiesService($resource) {
return $resource('api/activities/:activityId', {
activityId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
}());
|
/**
* DevExtreme (data/data_source/data_source.js)
* Version: 16.2.6
* Build date: Tue Mar 28 2017
*
* Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED
* EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml
*/
"use strict";
var $ = require("jquery"),
Class = require("../../core/class"),
commonUtils = require("../../core/utils/common"),
dataUtils = require("../utils"),
Store = require("../abstract_store"),
ArrayStore = require("../array_store"),
CustomStore = require("../custom_store"),
EventsMixin = require("../../core/events_mixin"),
errors = require("../errors").errors,
array = require("../../core/utils/array"),
queue = require("../../core/utils/queue"),
when = require("../../integration/jquery/deferred").when,
__isString = commonUtils.isString,
__isNumber = commonUtils.isNumber,
__isBoolean = commonUtils.isBoolean,
__isDefined = commonUtils.isDefined;
var CANCELED_TOKEN = "canceled";
function OperationManager() {
this._counter = -1;
this._deferreds = {}
}
OperationManager.prototype.constructor = OperationManager;
OperationManager.prototype.add = function(deferred) {
this._counter += 1;
this._deferreds[this._counter] = deferred;
return this._counter
};
OperationManager.prototype.remove = function(operationId) {
return delete this._deferreds[operationId]
};
OperationManager.prototype.cancel = function(operationId) {
if (operationId in this._deferreds) {
this._deferreds[operationId].reject(CANCELED_TOKEN);
return true
}
return false
};
var operationManager = new OperationManager;
function isPending(deferred) {
return "pending" === deferred.state()
}
function normalizeDataSourceOptions(options) {
var store;
function createCustomStoreFromLoadFunc() {
var storeConfig = {};
$.each(["useDefaultSearch", "key", "load", "loadMode", "cacheRawData", "byKey", "lookup", "totalCount", "insert", "update", "remove"], function() {
storeConfig[this] = options[this];
delete options[this]
});
return new CustomStore(storeConfig)
}
function createStoreFromConfig(storeConfig) {
var alias = storeConfig.type;
delete storeConfig.type;
return Store.create(alias, storeConfig)
}
function createCustomStoreFromUrl(url) {
return new CustomStore({
load: function() {
return $.getJSON(url)
}
})
}
if ("string" === typeof options) {
options = {
paginate: false,
store: createCustomStoreFromUrl(options)
}
}
if (void 0 === options) {
options = []
}
if ($.isArray(options) || options instanceof Store) {
options = {
store: options
}
} else {
options = $.extend({}, options)
}
if (void 0 === options.store) {
options.store = []
}
store = options.store;
if ("load" in options) {
store = createCustomStoreFromLoadFunc()
} else {
if ($.isArray(store)) {
store = new ArrayStore(store)
} else {
if ($.isPlainObject(store)) {
store = createStoreFromConfig($.extend({}, store))
}
}
}
options.store = store;
return options
}
function normalizeStoreLoadOptionAccessorArguments(originalArguments) {
switch (originalArguments.length) {
case 0:
return;
case 1:
return originalArguments[0]
}
return $.makeArray(originalArguments)
}
function generateStoreLoadOptionAccessor(optionName) {
return function() {
var args = normalizeStoreLoadOptionAccessorArguments(arguments);
if (void 0 === args) {
return this._storeLoadOptions[optionName]
}
this._storeLoadOptions[optionName] = args
}
}
function mapDataRespectingGrouping(items, mapper, groupInfo) {
function mapRecursive(items, level) {
if (!commonUtils.isArray(items)) {
return items
}
return level ? mapGroup(items, level) : $.map(items, mapper)
}
function mapGroup(group, level) {
return $.map(group, function(item) {
var result = {
key: item.key,
items: mapRecursive(item.items, level - 1)
};
if ("aggregates" in item) {
result.aggregates = item.aggregates
}
return result
})
}
return mapRecursive(items, groupInfo ? dataUtils.normalizeSortingInfo(groupInfo).length : 0)
}
var DataSource = Class.inherit({
ctor: function(options) {
var that = this;
options = normalizeDataSourceOptions(options);
this._store = options.store;
this._storeLoadOptions = this._extractLoadOptions(options);
this._mapFunc = options.map;
this._postProcessFunc = options.postProcess;
this._pageIndex = void 0 !== options.pageIndex ? options.pageIndex : 0;
this._pageSize = void 0 !== options.pageSize ? options.pageSize : 20;
this._loadingCount = 0;
this._loadQueue = this._createLoadQueue();
this._searchValue = "searchValue" in options ? options.searchValue : null;
this._searchOperation = options.searchOperation || "contains";
this._searchExpr = options.searchExpr;
this._paginate = options.paginate;
$.each(["onChanged", "onLoadError", "onLoadingChanged", "onCustomizeLoadResult", "onCustomizeStoreLoadOptions"], function(_, optionName) {
if (optionName in options) {
that.on(optionName.substr(2, 1).toLowerCase() + optionName.substr(3), options[optionName])
}
});
this._init()
},
_init: function() {
this._items = [];
this._userData = {};
this._totalCount = -1;
this._isLoaded = false;
if (!__isDefined(this._paginate)) {
this._paginate = !this.group()
}
this._isLastPage = !this._paginate
},
dispose: function() {
this._disposeEvents();
delete this._store;
if (this._delayedLoadTask) {
this._delayedLoadTask.abort()
}
this._disposed = true
},
_extractLoadOptions: function(options) {
var result = {},
names = ["sort", "filter", "select", "group", "requireTotalCount"],
customNames = this._store._customLoadOptions();
if (customNames) {
names = names.concat(customNames)
}
$.each(names, function() {
result[this] = options[this]
});
return result
},
loadOptions: function() {
return this._storeLoadOptions
},
items: function() {
return this._items
},
pageIndex: function(newIndex) {
if (!__isNumber(newIndex)) {
return this._pageIndex
}
this._pageIndex = newIndex;
this._isLastPage = !this._paginate
},
paginate: function(value) {
if (!__isBoolean(value)) {
return this._paginate
}
if (this._paginate !== value) {
this._paginate = value;
this.pageIndex(0)
}
},
pageSize: function(value) {
if (!__isNumber(value)) {
return this._pageSize
}
this._pageSize = value
},
isLastPage: function() {
return this._isLastPage
},
sort: generateStoreLoadOptionAccessor("sort"),
filter: function() {
var newFilter = normalizeStoreLoadOptionAccessorArguments(arguments);
if (void 0 === newFilter) {
return this._storeLoadOptions.filter
}
this._storeLoadOptions.filter = newFilter;
this.pageIndex(0)
},
group: generateStoreLoadOptionAccessor("group"),
select: generateStoreLoadOptionAccessor("select"),
requireTotalCount: function(value) {
if (!__isBoolean(value)) {
return this._storeLoadOptions.requireTotalCount
}
this._storeLoadOptions.requireTotalCount = value
},
searchValue: function(value) {
if (arguments.length < 1) {
return this._searchValue
}
this._searchValue = value;
this.pageIndex(0)
},
searchOperation: function(op) {
if (!__isString(op)) {
return this._searchOperation
}
this._searchOperation = op;
this.pageIndex(0)
},
searchExpr: function(expr) {
var argc = arguments.length;
if (0 === argc) {
return this._searchExpr
}
if (argc > 1) {
expr = $.makeArray(arguments)
}
this._searchExpr = expr;
this.pageIndex(0)
},
store: function() {
return this._store
},
key: function() {
return this._store && this._store.key()
},
totalCount: function() {
return this._totalCount
},
isLoaded: function() {
return this._isLoaded
},
isLoading: function() {
return this._loadingCount > 0
},
_createLoadQueue: function() {
return queue.create()
},
_changeLoadingCount: function(increment) {
var newLoading, oldLoading = this.isLoading();
this._loadingCount += increment;
newLoading = this.isLoading();
if (oldLoading ^ newLoading) {
this.fireEvent("loadingChanged", [newLoading])
}
},
_scheduleLoadCallbacks: function(deferred) {
var that = this;
that._changeLoadingCount(1);
deferred.always(function() {
that._changeLoadingCount(-1)
})
},
_scheduleFailCallbacks: function(deferred) {
var that = this;
deferred.fail(function() {
if (arguments[0] === CANCELED_TOKEN) {
return
}
that.fireEvent("loadError", arguments)
})
},
_scheduleChangedCallbacks: function(deferred) {
var that = this;
deferred.done(function() {
that.fireEvent("changed")
})
},
loadSingle: function(propName, propValue) {
var that = this;
var d = $.Deferred(),
key = this.key(),
store = this._store,
options = this._createStoreLoadOptions(),
handleDone = function(data) {
if (!__isDefined(data) || array.isEmpty(data)) {
d.reject(new errors.Error("E4009"))
} else {
d.resolve(that._applyMapFunction($.makeArray(data))[0])
}
};
this._scheduleFailCallbacks(d);
if (arguments.length < 2) {
propValue = propName;
propName = key
}
delete options.skip;
delete options.group;
delete options.refresh;
delete options.pageIndex;
delete options.searchString;
function shouldForceByKey() {
return store instanceof CustomStore && !store._byKeyViaLoad()
}(function() {
if (propName === key || shouldForceByKey()) {
return store.byKey(propValue, options)
}
options.take = 1;
options.filter = options.filter ? [options.filter, [propName, propValue]] : [propName, propValue];
return store.load(options)
})().fail(d.reject).done(handleDone);
return d.promise()
},
load: function() {
var loadOperation, that = this,
d = $.Deferred();
function loadTask() {
if (that._disposed) {
return
}
if (!isPending(d)) {
return
}
return that._loadFromStore(loadOperation, d)
}
this._scheduleLoadCallbacks(d);
this._scheduleFailCallbacks(d);
this._scheduleChangedCallbacks(d);
loadOperation = this._createLoadOperation(d);
this.fireEvent("customizeStoreLoadOptions", [loadOperation]);
this._loadQueue.add(function() {
if ("number" === typeof loadOperation.delay) {
that._delayedLoadTask = commonUtils.executeAsync(loadTask, loadOperation.delay)
} else {
loadTask()
}
return d.promise()
});
return d.promise({
operationId: loadOperation.operationId
})
},
_createLoadOperation: function(deferred) {
var id = operationManager.add(deferred),
options = this._createStoreLoadOptions();
deferred.always(function() {
operationManager.remove(id)
});
return {
operationId: id,
storeLoadOptions: options
}
},
reload: function() {
this._init();
return this.load()
},
cancel: function(operationId) {
return operationManager.cancel(operationId)
},
_addSearchOptions: function(storeLoadOptions) {
if (this._disposed) {
return
}
if (this.store()._useDefaultSearch) {
this._addSearchFilter(storeLoadOptions)
} else {
storeLoadOptions.searchOperation = this._searchOperation;
storeLoadOptions.searchValue = this._searchValue;
storeLoadOptions.searchExpr = this._searchExpr
}
},
_createStoreLoadOptions: function() {
var result = $.extend({}, this._storeLoadOptions);
this._addSearchOptions(result);
if (this._paginate) {
if (this._pageSize) {
result.skip = this._pageIndex * this._pageSize;
result.take = this._pageSize
}
}
result.userData = this._userData;
return result
},
_addSearchFilter: function(storeLoadOptions) {
var value = this._searchValue,
op = this._searchOperation,
selector = this._searchExpr,
searchFilter = [];
if (!value) {
return
}
if (!selector) {
selector = "this"
}
if (!$.isArray(selector)) {
selector = [selector]
}
$.each(selector, function(i, item) {
if (searchFilter.length) {
searchFilter.push("or")
}
searchFilter.push([item, op, value])
});
if (storeLoadOptions.filter) {
storeLoadOptions.filter = [searchFilter, storeLoadOptions.filter]
} else {
storeLoadOptions.filter = searchFilter
}
},
_loadFromStore: function(loadOptions, pendingDeferred) {
var that = this;
function handleSuccess(data, extra) {
function processResult() {
var loadResult;
if (data && !$.isArray(data) && data.data) {
extra = data;
data = data.data
}
if (!$.isArray(data)) {
data = $.makeArray(data)
}
loadResult = $.extend({
data: data,
extra: extra
}, loadOptions);
that.fireEvent("customizeLoadResult", [loadResult]);
when(loadResult.data).done(function(data) {
loadResult.data = data;
that._processStoreLoadResult(loadResult, pendingDeferred)
}).fail(pendingDeferred.reject)
}
if (that._disposed) {
return
}
if (!isPending(pendingDeferred)) {
return
}
processResult()
}
if (loadOptions.data) {
return $.Deferred().resolve(loadOptions.data).done(handleSuccess)
}
return this.store().load(loadOptions.storeLoadOptions).done(handleSuccess).fail(pendingDeferred.reject)
},
_processStoreLoadResult: function(loadResult, pendingDeferred) {
var that = this,
data = loadResult.data,
extra = loadResult.extra,
storeLoadOptions = loadResult.storeLoadOptions;
function resolvePendingDeferred() {
that._isLoaded = true;
that._totalCount = isFinite(extra.totalCount) ? extra.totalCount : -1;
return pendingDeferred.resolve(data, extra)
}
function proceedLoadingTotalCount() {
that.store().totalCount(storeLoadOptions).done(function(count) {
extra.totalCount = count;
resolvePendingDeferred()
}).fail(pendingDeferred.reject)
}
if (that._disposed) {
return
}
data = that._applyPostProcessFunction(that._applyMapFunction(data));
if (!$.isPlainObject(extra)) {
extra = {}
}
that._items = data;
if (!data.length || !that._paginate || that._pageSize && data.length < that._pageSize) {
that._isLastPage = true
}
if (storeLoadOptions.requireTotalCount && !isFinite(extra.totalCount)) {
proceedLoadingTotalCount()
} else {
resolvePendingDeferred()
}
},
_applyMapFunction: function(data) {
if (this._mapFunc) {
return mapDataRespectingGrouping(data, this._mapFunc, this.group())
}
return data
},
_applyPostProcessFunction: function(data) {
if (this._postProcessFunc) {
return this._postProcessFunc(data)
}
return data
}
}).include(EventsMixin);
exports.DataSource = DataSource;
exports.normalizeDataSourceOptions = normalizeDataSourceOptions;
|
/**
* Policy Mappings
* (sails.config.policies)
*
* Policies are simple functions which run **before** your controllers.
* You can apply one or more policies to a given controller, or protect
* its actions individually.
*
* Any policy file (e.g. `api/policies/authenticated.js`) can be accessed
* below by its filename, minus the extension, (e.g. "authenticated")
*
* For more information on how policies work, see:
* http://sailsjs.org/#/documentation/concepts/Policies
*
* For more information on configuring policies, check out:
* http://sailsjs.org/#/documentation/reference/sails.config/sails.config.policies.html
*/
module.exports.policies = {
/***************************************************************************
* *
* Default policy for all controllers and actions (`true` allows public *
* access) *
* *
***************************************************************************/
'*': 'sessionAuth',
'auth': {
'*': true
},
'home': {
'index': true
}
/***************************************************************************
* *
* Here's an example of mapping some policies to run before a controller *
* and its actions *
* *
***************************************************************************/
// RabbitController: {
// Apply the `false` policy as the default for all of RabbitController's actions
// (`false` prevents all access, which ensures that nothing bad happens to our rabbits)
// '*': false,
// For the action `nurture`, apply the 'isRabbitMother' policy
// (this overrides `false` above)
// nurture : 'isRabbitMother',
// Apply the `isNiceToAnimals` AND `hasRabbitFood` policies
// before letting any users feed our rabbits
// feed : ['isNiceToAnimals', 'hasRabbitFood']
// }
};
|
(function (angular) {
'use strict';
angular.module('ac.url', [])
.filter('urlencode', [function () {
return function (string) {
if (!!string) {
return encodeURIComponent(string);
}
};
}])
.filter('urldecode', [function () {
return function (string) {
if (!!string) {
return decodeURIComponent(string);
}
};
}])
.filter('tabloBaseUrl', [function () {
return function (tabloIp) {
if (!!tabloIp) {
return 'http://' + tabloIp + ':18080';
}
};
}]);
})(window.angular); |
app.controller('userdashboard', function($scope, $http){
$http.get('/cafeinfos2').then(function (res) {
console.log(res)
})
}) |
module.exports = function(grunt) {
grunt.initConfig({
nodeunit: {
tests: 'test/release_test.js'
},
npmrelease: {
options: {
push: true,
bump : true,
pushTags: true,
npm: true,
npmtag: false,
silent : false,
commitMessage : 'bump version to %s'
}
},
setup: {
test: {
}
},
remove: {
test : {
fileList: ['test/output.json']
}
}
});
grunt.loadTasks('tasks');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-remove');
grunt.registerTask('test', [
'setup',
'npmrelease',
'nodeunit',
'remove'
]);
grunt.registerMultiTask('setup', 'Setup test fixtures', function() {
var commands = [
'npm version patch -m "bump version to %s"',
'git push',
'git push --tags',
'npm publish --tag testTag'
];
var mockery = require('mockery');
mockery.enable({ useCleanCache: true, warnOnUnregistered: false });
mockery.registerMock('shelljs', {
exec : function(command) {
var index = commands.indexOf(command);
if (index > -1) {
commands.splice(index, 1);
}
var fs = require('fs');
fs.writeFileSync('test/output.json', JSON.stringify({commands : commands}, null, 2));
return {
code : 0
}
}
});
grunt.config.set('npmrelease.options.npmtag', 'testTag');
});
};
|
var annotated =
[
[ "DAction", "struct_d_action.html", "struct_d_action" ],
[ "DArena", "struct_d_arena.html", "struct_d_arena" ],
[ "DBattery", "struct_d_battery.html", "struct_d_battery" ],
[ "DCamera", "struct_d_camera.html", "struct_d_camera" ],
[ "DImage", "struct_d_image.html", "struct_d_image" ],
[ "DJpegimage", "struct_d_jpegimage.html", "struct_d_jpegimage" ],
[ "DMessage", "struct_d_message.html", "struct_d_message" ],
[ "DMission", "struct_d_mission.html", "struct_d_mission" ],
[ "DMovement", "struct_d_movement.html", "struct_d_movement" ],
[ "DPosition", "struct_d_position.html", "struct_d_position" ],
[ "DRobot", "struct_d_robot.html", "struct_d_robot" ],
[ "DServer", "struct_d_server.html", "struct_d_server" ]
]; |
/*
* Globalize Culture es-PR
*
* http://github.com/jquery/globalize
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* This file was generated by the Globalize Culture Generator
* Translation: bugs found in this file need to be fixed in the generator * Portions (c) Corporate Web Solutions Ltd.
*/
(function( window, undefined ) {
var Globalize;
if ( typeof require !== "undefined" &&
typeof exports !== "undefined" &&
typeof module !== "undefined" ) {
// Assume CommonJS
Globalize = require( "globalize" );
} else {
// Global variable
Globalize = window.Globalize;
}
Globalize.addCultureInfo( "es-PR", "default", {
name: "es-PR",
englishName: "Spanish (Puerto Rico)",
nativeName: "Español (Puerto Rico)",
language: "es",
numberFormat: {
"NaN": "NeuN",
negativeInfinity: "-Infinito",
positiveInfinity: "Infinito",
currency: {
pattern: ["($ n)","$ n"],
groupSizes: [3,0]
}
},
calendars: {
standard: {
days: {
names: ["domingo","lunes","martes","miércoles","jueves","viernes","sábado"],
namesAbbr: ["dom","lun","mar","mié","jue","vie","sáb"],
namesShort: ["do","lu","ma","mi","ju","vi","sá"]
},
months: {
names: ["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre",""],
namesAbbr: ["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic",""]
},
AM: ["a.m.","a.m.","A.M."],
PM: ["p.m.","p.m.","P.M."],
eras: [{"name":"d.C.","start":null,"offset":0}],
patterns: {
d: "dd/MM/yyyy",
D: "dddd, dd' de 'MMMM' de 'yyyy",
t: "hh:mm tt",
T: "hh:mm:ss tt",
f: "dddd, dd' de 'MMMM' de 'yyyy hh:mm tt",
F: "dddd, dd' de 'MMMM' de 'yyyy hh:mm:ss tt",
M: "dd MMMM",
Y: "MMMM' de 'yyyy"
}
}
}
});
}( this ));
|
import { hop } from '../constants'
/**
* Returns an object's own keys as an array of strings. It uses a for-in loop in the back in combination with hasOwnProperty.
* @param { object } obj
* @return { [string] }
*/
export function keys(obj) {
const objKeys = []
for (var key in obj) {
if (hop(obj, key)) {
objKeys.push(key)
}
}
return objKeys
}
/**
* Returns an object's own values as an array. It uses a for-in loop in the back in combination with hasOwnProperty.
* @param { object } obj
* @return { [*] }
*/
export function values(obj) {
const objValues = []
for (var key in obj) {
if (hop(obj, key)) {
objValues.push(obj[key])
}
}
return objValues
} |
"use strict";
class Registration {
constructor(username, password, email) {
this.Username = username;
this.Password = password;
this.Email = email;
}
}
exports.Registration = Registration;
|
/* eslint-env node */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
rootURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
},
EXTEND_PROTOTYPES: {
// Prevent Ember Data from overriding Date.parse.
Date: false
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
ENV.locationType = 'hash';
ENV.rootURL = '/ember-concurrency-ajax/';
ENV['ember-cli-mirage'] = {
enabled: true
};
}
return ENV;
};
|
/* */
var split = require('../index');
var test = require('tape');
test('split', function(t) {
t.deepEqual(split('a b c d', ' '), ['a', 'b', 'c', 'd'], 'basic use');
t.deepEqual(split('a b c d', ' ', 2), ['a', 'b'], 'with limit');
t.deepEqual(split('..word1 word2..', /([a-z]+)(\d+)/i), ['..', 'word', '1', ' ', 'word', '2', '..'], 'backreferences in result array');
t.end();
});
|
var whoAmI = require('./whoAmI');
var config = require('../config');
var logData = require('./logData');
var logEvent = require('./logEvent');
var register = require('./register');
var getEvents = require('./getEvents');
var getDevice = require('./getDevice');
var getDevices = require('./getDevices');
var authDevice = require('./authDevice');
var bindSocket = require('./bindSocket');
var unregister = require('./unregister');
var claimDevice = require('./claimDevice');
var securityImpl = require('./getSecurityImpl');
var updateSocketId = require('./updateSocketId');
var updatePresence = require('./updatePresence');
var getLocalDevices = require('./getLocalDevices');
var getSystemStatus = require('./getSystemStatus');
function socketLogic (socket, secure, skynet){
console.log('socket connected...');
var ipAddress = socket.handshake.address.address;
// socket.limiter = new RateLimiter(1, "second", true);
console.log('Websocket connection detected. Requesting identification from socket id: ', socket.id);
logEvent(100, {"socketid": socket.id, "protocol": "websocket"});
socket.emit('identify', { socketid: socket.id });
socket.on('identity', function (data) {
console.log('identity received', data);
data.socketid = socket.id;
data.ipAddress = ipAddress;
data.secure = secure;
if(!data.protocol){
data.protocol = "websocket";
}
console.log('Identity received: ', JSON.stringify(data));
// logEvent(101, data);
updateSocketId(data, function(auth){
if (auth.status == 201){
socket.skynetDevice = auth.device;
socket.emit('ready', {"api": "connect", "status": auth.status, "socketid": socket.id, "uuid": auth.device.uuid, "token": auth.device.token});
// Have device join its uuid room name so that others can subscribe to it
console.log('subscribe: ' + auth.device.uuid);
//make sure not in there already:
try{
socket.leave(auth.device.uuid);
}catch(lexp){
console.log('error leaving room', lexp);
}
socket.join(auth.device.uuid);
} else {
socket.emit('notReady', {"api": "connect", "status": auth.status, "uuid": data.uuid});
}
whoAmI(data.uuid, false, function(results){
data.auth = auth;
// results._id.toString();
// delete results._id;
data.fromUuid = results;
logEvent(101, data);
});
});
});
socket.on('disconnect', function (data) {
console.log('Presence offline for socket id: ', socket.id);
updatePresence(socket.id);
// Emit API request from device to room for subscribers
getDevice(socket, function(err, device){
device = device || null;
logEvent(102, {api: "disconnect", socketid: socket.id, device: device});
});
});
// Is this API still needed with MQTT?
socket.on('subscribe', function(data, fn) {
if(data.uuid && data.uuid.length > 30 && !data.token){
//no token provided, attempt to only listen for public broadcasts FROM this uuid
whoAmI(data.uuid, false, function(results){
if(results.error){
fn(results);
}else{
socket.join(data.uuid + "_bc");
fn({"api": "subscribe", "result": true});
}
data.toUuid = results;
logEvent(204, data);
});
}else{
//token provided, attempt to listen to any broadcast FOR this uuid
authDevice(data.uuid, data.token, function(auth){
if (auth.authenticate){
console.log('joining room ', data.uuid);
socket.join(data.uuid);
// Emit API request from device to room for subscribers
getDevice(socket, function(err, device){
if(err){ return; }
var results = {"api": "subscribe", "socketid": socket.id, "fromUuid": device.uuid, "toUuid": data.uuid};
whoAmI(data.uuid, false, function(toCheck){
data.auth = auth;
data.fromUuid = device;
data.toUuid = toCheck;
logEvent(204, data);
});
try{
fn(results);
} catch (e){
console.log(e);
}
});
} else {
console.log('subscribe failed for room ', data.uuid);
var results = {"api": "subscribe", "uuid": data.uuid, "result": false};
// socket.broadcast.to(uuid).emit('message', results);
logEvent(204, results);
console.log(results);
try{
fn(results);
} catch (e){
console.log(e);
}
}
});
}
});
// Is this API still needed with MQTT?
socket.on('unsubscribe', function(data, fn) {
console.log('leaving room ', data.uuid);
socket.leave(data.uuid);
// Emit API request from device to room for subscribers
getDevice(socket, function(err, device){
if(err){ return; }
var results = {"api": "unsubscribe", "socketid": socket.id, "uuid": device.uuid};
// socket.broadcast.to(uuid).emit('message', results);
whoAmI(data.uuid, false, function(toCheck){
data.fromUuid = device;
data.toUuid = toCheck;
logEvent(205, data);
});
try{
fn(results);
} catch (e){
console.log(e);
}
});
});
// APIs
socket.on('status', function (fn) {
skynet.throttles.query.rateLimit(socket.id, function (err, limited) {
if(limited){
console.log('status throttled', socket.id);
}else{
// Emit API request from device to room for subscribers
getDevice(socket, function(err, device){
if(err){ return; }
// socket.broadcast.to(uuid).emit('message', {"api": "status"});
getSystemStatus(function(results){
results.fromUuid = device;
logEvent(200, results);
console.log(results);
try{
fn(results);
} catch (e){
console.log(e);
}
});
});
}
});
});
socket.on('devices', function (data, fn) {
skynet.throttles.query.rateLimit(socket.id, function (err, limited) {
if(limited){
console.log('query throttled', socket.id);
}else{
if(!data || (typeof data != 'object')){
data = {};
}
// Emit API request from device to room for subscribers
getDevice(socket, function(err, device){
if(err){ return; }
var reqData = data;
getDevices(device, data, false, function(results){
results.fromUuid = device;
logEvent(403, results);
console.log(results);
try{
fn(results);
} catch (e){
console.log(e);
}
});
});
}
});
});
socket.on('localDevices', function (data, fn) {
skynet.throttles.query.rateLimit(socket.id, function (err, limited) {
if(limited){
console.log('query throttled', socket.id);
}else{
if(!data || (typeof data != 'object')){
data = {};
}
// Emit API request from device to room for subscribers
getDevice(socket, function(err, device){
if(err){ return; }
getLocalDevices(device, false, function(results){
results.fromUuid = device;
logEvent(403, results);
console.log(results);
try{
fn(results);
} catch (e){
console.log(e);
}
});
});
}
});
});
socket.on('claimDevice', function (data, fn) {
skynet.throttles.query.rateLimit(socket.id, function (err, limited) {
if(limited){
console.log('query throttled', socket.id);
}else{
if(!data || (typeof data != 'object')){
data = {};
}
// Emit API request from device to room for subscribers
getDevice(socket, function(err, device){
if(err){ return; }
claimDevice(device, data.claimUuid, function(err, results){
logEvent(403, {error: err, results: results, fromUuid: device});
console.log('claimed', err, results);
try{
fn(results);
} catch (e){
console.log(e);
}
});
});
}
});
});
socket.on('whoami', function (data, fn) {
skynet.throttles.whoami.rateLimit(socket.id, function (err, limited) {
if(limited){
console.log('whoami throttled', socket.id);
}else{
if(!data){
data = "";
} else {
data = data.uuid;
}
// Emit API request from device to room for subscribers
getDevice(socket, function(err, device){
if(err){ return; }
var reqData = data;
whoAmI(data, false, function(results){
results.fromUuid = device;
logEvent(500, results);
try{
fn(results);
} catch (e){
console.log(e);
}
});
});
}
});
});
//tell skynet to forward plain text to another socket
socket.on('bindSocket', function (data, fn) {
var target;
function bindReply(result){
if(result == 'ok' || (result && result.result == 'ok')){
bindSocket.connect(socket.id, target.socketid, function(err, val){
if(err){
fn(err);
}else{
fn(result);
}
});
}else{
fn(result);
}
}
if(!data){
return fn({error: 'invalid request'});
}
getDevice(socket, function(err, device){
if(err){ return fn({error: 'invalid client'}); }
whoAmI(data.uuid, false, function(check){
if(!check.error){
target = check;
if(target.socketid && securityImpl.canSend(device, target)){
if(target.secure && config.tls){
skynet.ios.sockets.socket(target.socketid).emit("bindSocket", {fromUuid: device.uuid}, bindReply);
} else {
skynet.io.sockets.socket(target.socketid).emit("bindSocket", {fromUuid: device.uuid}, bindReply);
}
}else{
console.log('client target',device.uuid, target);
return fn({error: 'invalid client or target'});
}
}
});
});
});
socket.on('register', function (data, fn) {
if(!data){
data = {};
}
data.socketid = socket.id;
register(data, function(results){
whoAmI(data.uuid, false, function(check){
results.fromUuid = check;
if(!check.error){
socket.skynetDevice = check;
}
logEvent(400, results);
});
try{
fn(results);
} catch (e){
console.log(e);
}
});
});
socket.on('update', function (data, fn) {
if(!data){
data = {};
}
// Emit API request from device to room for subscribers
getDevice(socket, function(err, fromDevice){
if(err){ return; }
skynet.handleUpdate(fromDevice, data, fn);
});
});
socket.on('unregister', function (data, fn) {
if(!data){
data = {};
}
// Emit API request from device to room for subscribers
getDevice(socket, function(err, device){
if(err){ return; }
var reqData = data;
unregister(data.uuid, data, function(results){
console.log(results);
results.fromUuid = device;
logEvent(402, results);
try{
fn(results);
} catch (e){
console.log(e);
}
});
});
});
socket.on('events', function(data, fn) {
authDevice(data.uuid, data.token, function(auth){
// Emit API request from device to room for subscribers
getDevice(socket, function(err, device){
if(err){ return; }
var reqData = data;
reqData.api = "events";
if (auth.authenticate){
getEvents(data.uuid, function(results){
console.log(results);
try{
fn(results);
} catch (e){
console.log(e);
}
});
} else {
console.log('UUID not found or invalid token ', data.uuid);
var results = {"api": "events", "result": false};
console.log(results);
try{
fn(results);
} catch (e){
console.log(e);
}
}
});
});
});
socket.on('authenticate', function(data, fn) {
authDevice(data.uuid, data.token, function(auth){
var results;
if (auth.authenticate){
results = {"uuid": data.uuid, "authentication": true};
socket.emit('ready', {"api": "connect", "status": 201, "socketid": socket.id, "uuid": data.uuid});
console.log('subscribe: ' + data.uuid);
socket.join(data.uuid);
try{
fn(results);
} catch (e){
console.log(e);
}
} else {
results = {"uuid": data.uuid, "authentication": false};
try{
fn(results);
} catch (e){
console.log(e);
}
}
require('./lib/whoAmI')(data.uuid, false, function(check){
// check._id.toString();
// delete check._id;
results.toUuid = check;
logEvent(102, results);
});
});
});
socket.on('data', function (messageX, fn) {
skynet.throttles.data.rateLimit(socket.id, function (err, limited) {
if(limited){
console.log('data throttled', socket.id);
}else{
var data = messageX;
authDevice(data.uuid, data.token, function(auth){
getDevice(socket, function(err, fromDevice){
if(err){ return; }
delete data.token;
var reqData = data;
reqData.api = "data";
if (auth.authenticate){
logData(data, function(results){
console.log(results);
// Send messsage regarding data update
var message = {};
message.payload = data;
message.devices = data.uuid;
console.log('message: ' + JSON.stringify(message));
skynet.sendMessage(fromDevice, message);
try{
fn(results);
} catch (e){
console.log(e);
}
});
} else {
console.log('UUID not found or invalid token ', data.uuid);
var results = {"api": "data", "result": false};
console.log(results);
try{
fn(results);
} catch (e){
console.log(e);
}
}
});
});
}
});
});
socket.on('gatewayConfig', function(data, fn) {
skynet.gatewayConfig(data, fn);
});
socket.on('message', function (messageX, fn) {
// socket.limiter.removeTokens(1, function(err, remainingRequests) {
skynet.throttles.message.rateLimit(socket.id, function (err, limited) {
var message = messageX;
if (limited) {
// response.writeHead(429, {'Content-Type': 'text/plain;charset=UTF-8'});
// response.end('429 Too Many Requests - your IP is being rate limited');
// TODO: Emit rate limit exceeded message
console.log("Rate limit exceeded for socket:", socket.id);
console.log("message", message);
} else {
console.log("Sending message for socket:", socket.id, message);
if(!message){
return;
} else if (typeof message == 'string'){
bindSocket.getTarget(socket.id, function(err, target){
if(target){
socket._unboundTarget = 0;
// Determine is socket is secure
getDevice(socket, function(err, device){
if(device.secure){
if(config.tls){
skynet.ios.sockets.socket(target).send(message);
}
} else {
//console.log('socket lookup', io.sockets.socket(target));
skynet.io.sockets.socket(target).send(message);
}
});
//async update for TTL
bindSocket.connect(socket.id, target);
}else{
//no longer bound, start checking for unbound repeats
if(!socket._unboundTarget){
socket._unboundTarget = 1;
}else{
socket._unboundTarget += 1;
}
if(socket._unboundTarget > 2){
console.log('sending unbind message', socket.id);
socket.emit('unboundSocket', {error : 'unbound from remote uuid'});
socket._unboundTarget = 0;
}
}
});
}else{
// Broadcast to room for pubsub
getDevice(socket, function(err, fromDevice){
if(fromDevice){
message.api = "message";
skynet.sendMessage(fromDevice, message, fn);
}
});
}
}
});
});
}
module.exports = socketLogic;
|
/*jslint browser: true, devel: true, node: true, sloppy: true, plusplus: true*/
/*global require, cordova */
/*
The MIT License (MIT)
Copyright (c) 2015 Axel Napolitano, Napolitano Business Solutions - axel@napolitano.de
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var exec = require('cordova/exec');
function FileOpener3() {}
FileOpener3.prototype.open = function (fileName, contentType, callbackContext) {
callbackContext = callbackContext || {};
exec(callbackContext.success || null, callbackContext.error || null, 'FileOpener3', 'open', [fileName, contentType]);
};
FileOpener3.prototype.uninstall = function (packageId, callbackContext) {
callbackContext = callbackContext || {};
exec(callbackContext.success || null, callbackContext.error || null, 'FileOpener3', 'uninstall', [packageId]);
};
FileOpener3.prototype.appIsInstalled = function (packageId, callbackContext) {
callbackContext = callbackContext || {};
exec(callbackContext.success || null, callbackContext.error || null, 'FileOpener3', 'appIsInstalled', [packageId]);
};
module.exports = new FileOpener3(); |
// >>> WARNING THIS PAGE WAS AUTO-GENERATED - DO NOT EDIT!!! <<<
import QuestionPage from '../../question.page'
class VisitorAddressPage extends QuestionPage {
constructor() {
super('visitor-address')
}
setVisitorAddressAnswerBuilding(value) {
browser.setValue('[name="visitor-address-answer-building"]', value)
return this
}
getVisitorAddressAnswerBuilding(value) {
return browser.element('[name="visitor-address-answer-building"]').getValue()
}
setVisitorAddressAnswerStreet(value) {
browser.setValue('[name="visitor-address-answer-street"]', value)
return this
}
getVisitorAddressAnswerStreet(value) {
return browser.element('[name="visitor-address-answer-street"]').getValue()
}
setVisitorAddressAnswerCity(value) {
browser.setValue('[name="visitor-address-answer-city"]', value)
return this
}
getVisitorAddressAnswerCity(value) {
return browser.element('[name="visitor-address-answer-city"]').getValue()
}
setVisitorAddressAnswerCounty(value) {
browser.setValue('[name="visitor-address-answer-county"]', value)
return this
}
getVisitorAddressAnswerCounty(value) {
return browser.element('[name="visitor-address-answer-county"]').getValue()
}
setVisitorAddressAnswerPostcode(value) {
browser.setValue('[name="visitor-address-answer-postcode"]', value)
return this
}
getVisitorAddressAnswerPostcode(value) {
return browser.element('[name="visitor-address-answer-postcode"]').getValue()
}
}
export default new VisitorAddressPage()
|
let AccountsCategoriesTest = function () {
function AccountsCategoriesTest (client, testdata) {
this.client = client
this.testdata = testdata
}
/*
Testing for accounts_categories is more complex because accounts_categories must have
foreign references to accounts and categories.
1. Brainwipe
2.1 POST /categories categoryAsset
2.2 POST /categories categoryAssetLiquid
2.3 POST /categories categoryExpense
2.4 POST /categories categoryExpenseRent
3.1 POST /accounts accountsBank, pointing to no categories
3.2 GET /accounts/:accountsBank. Verify that the account's categories and accounts_categories is an empty array.
3.3 PUT /accounts accountsBank, pointing to categoryExpense
3.4 GET /accounts/:accountsBank. Verify that the account points to categoryExpense.
4.1 PUT /accounts accountsBank, pointing to categoryAsset and categoryLiquid.
4.2 GET /accounts/:accountsBank. Verify that the account points to categoryAsset and categoryLiquid.
5.1 PUT /accounts accountsExpenseRent, pointing to categoryExpense and categoryExpenseRent.
5.2 GET /accounts/:accountsExpenseRent. Verify that the account points to categoryExpense and categoryExpenseRent.
6. GET /accounts. Verify that each account has two account_category.
7.1 DELETE /accounts/:accountsExpenseRent.
7.2 Verify that accounts_categories no longer has any documents pointing to accountsExpenseRent.
*/
AccountsCategoriesTest.prototype.testRunner = function (pn, testdata) {
// Phase I Setup
let collectionPlural
let priorResults = {}
// 1. Brainwipe
return new Promise((resolve, reject) => {
let url = '/brainwipe'
console.log('P%s.6 PUT %s', pn, url)
this.client.put(url, function (err, req, res, obj) {
if (err) reject(err)
console.log('P%s.9 %j', pn, obj)
resolve(priorResults)
})
})
// 2. POST four documents to categories
.then(priorResults => {
collectionPlural = 'categories'
priorResults[collectionPlural] = {}
return this.post(testdata.categoryAsset, collectionPlural, pn, true, priorResults, 'categoryAsset') // expect success
})
.then(priorResults => {
return this.post(testdata.categoryAssetLiquid, collectionPlural, pn, true, priorResults, 'categoryAssetLiquid') // expect success
})
.then(priorResults => {
return this.post(testdata.categoryExpense, collectionPlural, pn, true, priorResults, 'categoryExpense') // expect success
})
.then(priorResults => {
return this.post(testdata.categoryExpenseRent, collectionPlural, pn, true, priorResults, 'categoryExpenseRent') // expect success
})
// 3.1 POST /accounts accountsBank, pointing to no categories
.then(priorResults => {
collectionPlural = 'accounts'
priorResults[collectionPlural] = {}
let account = JSON.parse(JSON.stringify(testdata.accountBank))
return this.post(account, collectionPlural, pn, true, priorResults, 'accountBank') // expect success
})
// 3.2 GET /accounts/:accountsBank. Verify that the account's accounts_categories is an empty array.
.then(priorResults => {
let accountId = priorResults.accounts.accountBank._id
return this.getOne(accountId, collectionPlural, pn, true, priorResults, 'accountBank') // expect success
})
.then(priorResults => {
return new Promise((resolve, reject) => {
let account = priorResults.accounts.accountBank
if (account.accounts_categories) {
if (account.accounts_categories.length > 0) {
reject('account should not have any accounts_categories')
} else {
resolve(priorResults)
}
} else {
resolve(priorResults)
}
})
})
// 3.3 PUT /accounts accountsBank, pointing to categoryExpense
.then(priorResults => {
let account = priorResults.accounts.accountBank
let accountId = account._id
delete account._id
account.categories = [priorResults.categories.categoryExpense._id]
return this.put(accountId, account, collectionPlural, pn, true, priorResults, 'accountBank') // expect success
})
// 3.4 GET /accounts/:accountsBank. Verify that the account points to categoryExpense.
.then(priorResults => {
let accountId = priorResults.accounts.accountBank._id
return this.getOne(accountId, collectionPlural, pn, true, priorResults, 'accountBank') // expect success
})
.then(priorResults => {
return new Promise((resolve, reject) => {
let account = priorResults.accounts.accountBank
if (account.categories) {
if (account.categories.length !== 1) {
reject('account should only have one category')
} else {
resolve(priorResults)
}
} else {
reject('account should have one category')
}
})
})
// 4.1 PUT /accounts accountsBank, pointing to categoryAsset and categoryLiquid.
// 4.2 GET /accounts/:accountsBank. Verify that the account points to categoryAsset and categoryLiquid.
// 5.1 PUT /accounts accountsExpenseRent, pointing to categoryExpense and categoryExpenseRent.
// 5.2 GET /accounts/:accountsExpenseRent. Verify that the account points to categoryExpense and categoryExpenseRent.
// 6. GET /accounts. Verify that each account has two account_category.
// 7.1 DELETE /accounts/:accountsExpenseRent.
// 7.2 Verify that accounts_categories no longer has any documents pointing to accountsExpenseRent.
}
// GET /{collectionPlural}/:account_category_id
AccountsCategoriesTest.prototype.getOne = function (accountsCategoriesId, collectionPlural, pn, fExpectSuccess, priorResults, prKey) {
return new Promise((resolve, reject) => {
let url = '/' + collectionPlural + '/' + accountsCategoriesId
console.log('P%s.3 GET %s', pn, url)
this.client.get(url, function (err, req, res, obj) {
if (err) reject(err)
if (!fExpectSuccess && !obj.error) reject('this test must generate an error')
if (fExpectSuccess && !obj._id) reject('this test must return an _id')
console.log('P%s.3 %j', pn, obj)
resolve(priorResults)
if (prKey) {
priorResults[collectionPlural][prKey] = obj
}
priorResults.mostRecentResult = obj
})
})
}
// POST /{collectionPlural}
AccountsCategoriesTest.prototype.post = function (document, collectionPlural, pn, fExpectSuccess, priorResults, prKey) {
return new Promise((resolve, reject) => {
let url = '/' + collectionPlural
console.log('P%s.2 POST %s %j', pn, url, document)
this.client.post(url, document, function (err, req, res, obj) {
if (err) reject(err)
if (!fExpectSuccess && !obj.error) reject('this test must generate an error')
if (fExpectSuccess && !obj._id) reject('this test must generate an _id')
console.log('P%s.2 %j', pn, obj)
if (prKey) {
priorResults[collectionPlural][prKey] = obj
}
priorResults.mostRecentResult = obj
resolve(priorResults)
})
})
}
// PUT /{collectionPlural}/:account_category_id
// We cannot rely on the document to contain the account_category_id. So therefore send the id seperately.
AccountsCategoriesTest.prototype.put = function (accountsCategoriesId, document, collectionPlural, pn, fExpectSuccess, priorResults, prKey) {
return new Promise((resolve, reject) => {
let url = '/' + collectionPlural + '/' + accountsCategoriesId
console.log('P%s.4 PUT %s %j', pn, url, document)
this.client.put(url, document, function (err, req, res, obj) {
if (err) reject(err)
if (!fExpectSuccess && !obj.error) reject('this test must generate an error')
if (fExpectSuccess && !obj._id) reject('this test must generate an _id')
console.log('P%s.4 %j', pn, obj)
if (prKey) {
priorResults[collectionPlural][prKey] = obj
}
priorResults.mostRecentResult = obj
resolve(priorResults)
})
})
}
// DELETE /{collectionPlural}/:id
AccountsCategoriesTest.prototype.delete = function (id, collectionPlural, pn, fExpectSuccess, priorResults) {
return new Promise((resolve, reject) => {
let url = '/' + collectionPlural + '/' + id
console.log('P%s.5 DELETE %s', pn, url)
this.client.del(url, function (err, req, res, obj) {
if (err) reject(err)
if (!fExpectSuccess && !obj.error) reject('this test must generate an error')
console.log('P%s.5 %j', pn, obj)
resolve(priorResults)
})
})
}
return AccountsCategoriesTest
}
module.exports = AccountsCategoriesTest()
|
var $ = require('jquery');
function Light(x, y, board, lit) {
this.board = board;
this.x = x;
this.y = y;
this.lit = lit || false;
this.hinted = false;
this.render().bindClick().appendTo(this.board.element);
}
Light.prototype.isLitJSON = function() {
return this.lit ? 1 : 0;
};
Light.prototype.render = function() {
this.element = $(this.template());
this.setLit();
this.setHinted();
return this;
};
Light.prototype.setLit = function() {
if(this.lit) {
this.element.find('.light').addClass('lit');
}
};
Light.prototype.setHinted = function() {
if(this.hinted) {
this.element.find('.light').addClass('next-move');
}
};
Light.prototype.rerender = function() {
this.element.replaceWith(this.render().bindClick().element);
return this;
};
Light.prototype.bindClick = function() {
this.element.find('.light')
.on('click', function () {
this.flipSwitch().rerender();
this.board.updateNeighbors(this);
}.bind(this));
return this;
};
Light.prototype.flipSwitch = function() {
this.lit = !(this.lit);
return this;
};
Light.prototype.flipHinted = function() {
this.hinted = !(this.hinted);
return this;
};
Light.prototype.template = function() {
return `
<div class="cell">
<div class="light hvr-grow">
</div>
</div>
`;
};
Light.prototype.appendTo = function(target) {
this.element.appendTo(target);
return this;
};
module.exports = Light;
|
"use strict";
var useStrict = require("../helpers/use-strict");
var _ = require("lodash");
// Priority:
//
// - 0 We want this to be at the **very** bottom
// - 1 Default node position
// - 2 Priority over normal nodes
// - 3 We want this to be at the **very** top
exports.BlockStatement =
exports.Program = {
exit: function (node) {
var hasChange = false;
for (var i = 0; i < node.body.length; i++) {
var bodyNode = node.body[i];
if (bodyNode && bodyNode._blockHoist != null) hasChange = true;
}
if (!hasChange) return;
useStrict.wrap(node, function () {
var nodePriorities = _.groupBy(node.body, function (bodyNode) {
var priority = bodyNode._blockHoist;
if (priority == null) priority = 1;
if (priority === true) priority = 2;
return priority;
});
node.body = _.flatten(_.values(nodePriorities).reverse());
});
}
};
|
'use strict';
angular.module('myApp')
.controller('EventosController', ['$scope', '$timeout', 'wdkFunctions', function($scope, $timeout, wdkFunctions){
}]);
|
/* w2ui-fields.js 1.5.x (nightly), part of w2ui (c) http://w2ui.com, vitmalina@gmail.com */
var w2ui = w2ui || {};
var w2obj = w2obj || {}; // expose object to be able to overwrite default functions
/************************************************
* Library: Web 2.0 UI for jQuery
* - Following objects are defines
* - w2ui - object that will contain all widgets
* - w2obj - object with widget prototypes
* - w2utils - basic utilities
* - $().w2render - common render
* - $().w2destroy - common destroy
* - $().w2marker - marker plugin
* - $().w2tag - tag plugin
* - $().w2overlay - overlay plugin
* - $().w2menu - menu plugin
* - w2utils.event - generic event object
* - Dependencies: jQuery
*
* == NICE TO HAVE ==
* - overlay should be displayed where more space (on top or on bottom)
* - write and article how to replace certain framework functions
* - add maxHeight for the w2menu
* - add time zone
* - TEST On IOS
* - $().w2marker() -- only unmarks first instance
* - subitems for w2menus()
* - add w2utils.lang wrap for all captions in all buttons.
* - add isDateTime()
* - remove momentjs
* - $().w2date(), $().w2dateTime()
*
* == 1.5 changes
* - date has problems in FF new Date('yyyy-mm-dd') breaks
* - bug: w2utils.formatDate('2011-31-01', 'yyyy-dd-mm'); - wrong foratter
* - format date and time is buggy
* - added decimalSymbol
* - renamed size() -> formatSize()
* - added cssPrefix()
* - added w2utils.settings.weekStarts
* - onComplete should pass widget as context (this)
* - hidden and disabled in menus
* - added menu.item.tooltip for overlay menus
* - added w2tag options.id, options.left, options.top
* - added w2tag options.position = top|bottom|left|right - default is right
* - added $().w2color(color, callBack)
* - added custom colors
* - added w2menu.options.type = radio|check
* - added w2menu items.hotkey
* - added options.contextMenu for w2overlay()
* - added options.noTip for w2overlay()
* - added options.overlayStyle for w2overlay()
* - added options.selectable
* - Refactored w2tag
* - added options.style for w2tag
* - added options.hideOnKeyPress for w2tag
* - added options.hideOnBlur for w2tag
* - events 'eventName:after' syntax
* - deprecated onComplete, introduced event.done(func) - can have multiple handlers
*
************************************************/
var w2utils = (function ($) {
var tmp = {}; // for some temp variables
var obj = {
version : '1.5.x',
settings : {
"locale" : "en-us",
"date_format" : "m/d/yyyy",
"time_format" : "hh:mi pm",
"currencyPrefix" : "$",
"currencySuffix" : "",
"currencyPrecision" : 2,
"groupSymbol" : ",",
"decimalSymbol" : ".",
"shortmonths" : ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
"fullmonths" : ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
"shortdays" : ["M", "T", "W", "T", "F", "S", "S"],
"fulldays" : ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
"weekStarts" : "M", // can be "M" for Monday or "S" for Sunday
"dataType" : 'HTTP', // can be HTTP, RESTFULL, RESTFULLJSON, JSON (case sensitive)
"phrases" : {}, // empty object for english phrases
"dateStartYear" : 1950, // start year for date-picker
"dateEndYear" : 2020 // end year for date picker
},
isBin : isBin,
isInt : isInt,
isFloat : isFloat,
isMoney : isMoney,
isHex : isHex,
isAlphaNumeric : isAlphaNumeric,
isEmail : isEmail,
isDate : isDate,
isTime : isTime,
isDateTime : isDateTime,
age : age,
date : date,
formatSize : formatSize,
formatNumber : formatNumber,
formatDate : formatDate,
formatTime : formatTime,
formatDateTime : formatDateTime,
stripTags : stripTags,
encodeTags : encodeTags,
escapeId : escapeId,
base64encode : base64encode,
base64decode : base64decode,
md5 : md5,
transition : transition,
lock : lock,
unlock : unlock,
lang : lang,
locale : locale,
getSize : getSize,
getStrWidth : getStrWidth,
scrollBarSize : scrollBarSize,
checkName : checkName,
checkUniqueId : checkUniqueId,
parseRoute : parseRoute,
cssPrefix : cssPrefix,
// some internal variables
isIOS : ((navigator.userAgent.toLowerCase().indexOf('iphone') != -1 ||
navigator.userAgent.toLowerCase().indexOf('ipod') != -1 ||
navigator.userAgent.toLowerCase().indexOf('ipad') != -1)
? true : false),
isIE : ((navigator.userAgent.toLowerCase().indexOf('msie') != -1 ||
navigator.userAgent.toLowerCase().indexOf('trident') != -1 )
? true : false),
use_momentjs : ((typeof moment === 'function') && (typeof moment.version === 'string'))
};
return obj;
function isBin (val) {
var re = /^[0-1]+$/;
return re.test(val);
}
function isInt (val) {
var re = /^[-+]?[0-9]+$/;
return re.test(val);
}
function isFloat (val) {
if (typeof val == 'string') val = val.replace(/\s+/g, '').replace(w2utils.settings.groupSymbol, '').replace(w2utils.settings.decimalSymbol, '.');
return (typeof val === 'number' || (typeof val === 'string' && val !== '')) && !isNaN(Number(val));
}
function isMoney (val) {
var se = w2utils.settings;
var re = new RegExp('^'+ (se.currencyPrefix ? '\\' + se.currencyPrefix + '?' : '') +
'[-+]?'+ (se.currencyPrefix ? '\\' + se.currencyPrefix + '?' : '') +
'[0-9]*[\\'+ se.decimalSymbol +']?[0-9]+'+ (se.currencySuffix ? '\\' + se.currencySuffix + '?' : '') +'$', 'i');
if (typeof val === 'string') {
val = val.replace(new RegExp(se.groupSymbol, 'g'), '');
}
if (typeof val === 'object' || val === '') return false;
return re.test(val);
}
function isHex (val) {
var re = /^[a-fA-F0-9]+$/;
return re.test(val);
}
function isAlphaNumeric (val) {
var re = /^[a-zA-Z0-9_-]+$/;
return re.test(val);
}
function isEmail (val) {
var email = /^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return email.test(val);
}
function isDate (val, format, retDate) {
if (!val) return false;
var dt = 'Invalid Date';
var month, day, year;
if (format == null) format = w2utils.settings.date_format;
if (typeof val.getUTCFullYear === 'function' && typeof val.getUTCMonth === 'function' && typeof val.getUTCDate === 'function') {
year = val.getUTCFullYear();
month = val.getUTCMonth();
day = val.getUTCDate();
} else if (typeof val.getFullYear === 'function' && typeof val.getMonth === 'function' && typeof val.getDate === 'function') {
year = val.getFullYear();
month = val.getMonth();
day = val.getDate();
} else {
val = String(val);
// convert month formats
if (new RegExp('mon', 'ig').test(format)) {
format = format.replace(/month/ig, 'm').replace(/mon/ig, 'm').replace(/dd/ig, 'd').replace(/[, ]/ig, '/').replace(/\/\//g, '/').toLowerCase();
val = val.replace(/[, ]/ig, '/').replace(/\/\//g, '/').toLowerCase();
for (var m = 0, len = w2utils.settings.fullmonths.length; m < len; m++) {
var t = w2utils.settings.fullmonths[m];
val = val.replace(new RegExp(t, 'ig'), (parseInt(m) + 1)).replace(new RegExp(t.substr(0, 3), 'ig'), (parseInt(m) + 1));
}
}
// format date
var tmp = val.replace(/-/g, '/').replace(/\./g, '/').toLowerCase().split('/');
var tmp2 = format.replace(/-/g, '/').replace(/\./g, '/').toLowerCase();
if (tmp2 === 'mm/dd/yyyy') { month = tmp[0]; day = tmp[1]; year = tmp[2]; }
if (tmp2 === 'm/d/yyyy') { month = tmp[0]; day = tmp[1]; year = tmp[2]; }
if (tmp2 === 'dd/mm/yyyy') { month = tmp[1]; day = tmp[0]; year = tmp[2]; }
if (tmp2 === 'd/m/yyyy') { month = tmp[1]; day = tmp[0]; year = tmp[2]; }
if (tmp2 === 'yyyy/dd/mm') { month = tmp[2]; day = tmp[1]; year = tmp[0]; }
if (tmp2 === 'yyyy/d/m') { month = tmp[2]; day = tmp[1]; year = tmp[0]; }
if (tmp2 === 'yyyy/mm/dd') { month = tmp[1]; day = tmp[2]; year = tmp[0]; }
if (tmp2 === 'yyyy/m/d') { month = tmp[1]; day = tmp[2]; year = tmp[0]; }
if (tmp2 === 'mm/dd/yy') { month = tmp[0]; day = tmp[1]; year = tmp[2]; }
if (tmp2 === 'm/d/yy') { month = tmp[0]; day = tmp[1]; year = parseInt(tmp[2]) + 1900; }
if (tmp2 === 'dd/mm/yy') { month = tmp[1]; day = tmp[0]; year = parseInt(tmp[2]) + 1900; }
if (tmp2 === 'd/m/yy') { month = tmp[1]; day = tmp[0]; year = parseInt(tmp[2]) + 1900; }
if (tmp2 === 'yy/dd/mm') { month = tmp[2]; day = tmp[1]; year = parseInt(tmp[0]) + 1900; }
if (tmp2 === 'yy/d/m') { month = tmp[2]; day = tmp[1]; year = parseInt(tmp[0]) + 1900; }
if (tmp2 === 'yy/mm/dd') { month = tmp[1]; day = tmp[2]; year = parseInt(tmp[0]) + 1900; }
if (tmp2 === 'yy/m/d') { month = tmp[1]; day = tmp[2]; year = parseInt(tmp[0]) + 1900; }
}
if (!isInt(year)) return false;
if (!isInt(month)) return false;
if (!isInt(day)) return false;
year = +year;
month = +month;
day = +day;
dt = new Date(year, month - 1, day);
// do checks
if (month == null) return false;
if (String(dt) == 'Invalid Date') return false;
if ((dt.getMonth() + 1 !== month) || (dt.getDate() !== day) || (dt.getFullYear() !== year)) return false;
if (retDate === true) return dt; else return true;
}
function isTime (val, retTime) {
// Both formats 10:20pm and 22:20
if (val == null) return false;
var max, pm;
// -- process american format
val = String(val);
val = val.toUpperCase();
pm = val.indexOf('PM') >= 0;
var ampm = (pm || val.indexOf('AM') >= 0);
if (ampm) max = 12; else max = 24;
val = val.replace('AM', '').replace('PM', '');
val = $.trim(val);
// ---
var tmp = val.split(':');
var h = parseInt(tmp[0] || 0), m = parseInt(tmp[1] || 0), s = parseInt(tmp[2] || 0);
// accept edge case: 3PM is a good timestamp, but 3 (without AM or PM) is NOT:
if ((!ampm || tmp.length !== 1) && tmp.length !== 2 && tmp.length !== 3) { return false; }
if (tmp[0] === '' || h < 0 || h > max || !this.isInt(tmp[0]) || tmp[0].length > 2) { return false; }
if (tmp.length > 1 && (tmp[1] === '' || m < 0 || m > 59 || !this.isInt(tmp[1]) || tmp[1].length !== 2)) { return false; }
if (tmp.length > 2 && (tmp[2] === '' || s < 0 || s > 59 || !this.isInt(tmp[2]) || tmp[2].length !== 2)) { return false; }
// check the edge cases: 12:01AM is ok, as is 12:01PM, but 24:01 is NOT ok while 24:00 is (midnight; equivalent to 00:00).
// meanwhile, there is 00:00 which is ok, but 0AM nor 0PM are okay, while 0:01AM and 0:00AM are.
if (!ampm && max === h && (m !== 0 || s !== 0)) { return false; }
if (ampm && tmp.length === 1 && h === 0) { return false; }
if (retTime === true) {
if (pm) h += 12;
return {
hours: h,
minutes: m,
seconds: s
};
}
return true;
}
function isDateTime (val, format, retDate) {
if(w2utils.use_momentjs) {
var dt = moment(val, format);
var valid = dt.isValid();
if (valid && (retDate === true)){
return dt.clone().toDate();
}
return valid;
}
// TODO: perform time check, too
format = format.split('|')[0];
val = val.split(' ')[0];
//console.log("isDateTime() - " + val + " / " + format);
return isDate(val, format, retDate);
}
function age (dateStr) {
if (dateStr === '' || dateStr == null || (typeof dateStr == 'object' && !dateStr.getMonth)) return '';
var d1 = new Date(dateStr);
if (w2utils.isInt(dateStr)) d1 = new Date(Number(dateStr)); // for unix timestamps
if (String(d1) == 'Invalid Date') return '';
var d2 = new Date();
var sec = (d2.getTime() - d1.getTime()) / 1000;
var amount = '';
var type = '';
if (sec < 0) {
amount = '<span style="color: #aaa">0 sec</span>';
type = '';
} else if (sec < 60) {
amount = Math.floor(sec);
type = 'sec';
if (sec < 0) { amount = 0; type = 'sec'; }
} else if (sec < 60*60) {
amount = Math.floor(sec/60);
type = 'min';
} else if (sec < 24*60*60) {
amount = Math.floor(sec/60/60);
type = 'hour';
} else if (sec < 30*24*60*60) {
amount = Math.floor(sec/24/60/60);
type = 'day';
} else if (sec < 365*24*60*60) {
amount = Math.floor(sec/30/24/60/60*10)/10;
type = 'month';
} else if (sec < 365*4*24*60*60) {
amount = Math.floor(sec/365/24/60/60*10)/10;
type = 'year';
} else if (sec >= 365*4*24*60*60) {
// factor in leap year shift (only older then 4 years)
amount = Math.floor(sec/365.25/24/60/60*10)/10;
type = 'year';
}
return amount + ' ' + type + (amount > 1 ? 's' : '');
}
function date (dateStr) {
if (dateStr === '' || dateStr == null || (typeof dateStr == 'object' && !dateStr.getMonth)) return '';
var d1 = new Date(dateStr);
if (w2utils.isInt(dateStr)) d1 = new Date(Number(dateStr)); // for unix timestamps
if (String(d1) == 'Invalid Date') return '';
var months = w2utils.settings.shortmonths;
var d2 = new Date(); // today
var d3 = new Date();
d3.setTime(d3.getTime() - 86400000); // yesterday
var dd1 = months[d1.getMonth()] + ' ' + d1.getDate() + ', ' + d1.getFullYear();
var dd2 = months[d2.getMonth()] + ' ' + d2.getDate() + ', ' + d2.getFullYear();
var dd3 = months[d3.getMonth()] + ' ' + d3.getDate() + ', ' + d3.getFullYear();
var time = (d1.getHours() - (d1.getHours() > 12 ? 12 :0)) + ':' + (d1.getMinutes() < 10 ? '0' : '') + d1.getMinutes() + ' ' + (d1.getHours() >= 12 ? 'pm' : 'am');
var time2= (d1.getHours() - (d1.getHours() > 12 ? 12 :0)) + ':' + (d1.getMinutes() < 10 ? '0' : '') + d1.getMinutes() + ':' + (d1.getSeconds() < 10 ? '0' : '') + d1.getSeconds() + ' ' + (d1.getHours() >= 12 ? 'pm' : 'am');
var dsp = dd1;
if (dd1 === dd2) dsp = time;
if (dd1 === dd3) dsp = w2utils.lang('Yesterday');
return '<span title="'+ dd1 +' ' + time2 +'">'+ dsp +'</span>';
}
function formatSize (sizeStr) {
if (!w2utils.isFloat(sizeStr) || sizeStr === '') return '';
sizeStr = parseFloat(sizeStr);
if (sizeStr === 0) return 0;
var sizes = ['Bt', 'KB', 'MB', 'GB', 'TB'];
var i = parseInt( Math.floor( Math.log(sizeStr) / Math.log(1024) ) );
return (Math.floor(sizeStr / Math.pow(1024, i) * 10) / 10).toFixed(i === 0 ? 0 : 1) + ' ' + sizes[i];
}
function formatNumber (val, fraction, useGrouping) {
return parseFloat(val).toLocaleString(w2utils.settings.locale, { minimumFractionDigits: fraction, useGrouping : useGrouping });
}
function formatDate (dateStr, format) { // IMPORTANT dateStr HAS TO BE valid JavaScript Date String
if (!format) format = this.settings.date_format;
if (dateStr === '' || dateStr == null || (typeof dateStr == 'object' && !dateStr.getMonth)) return '';
var dt = new Date(dateStr);
if (w2utils.isInt(dateStr)) dt = new Date(Number(dateStr)); // for unix timestamps
if (String(dt) == 'Invalid Date') return '';
var year = dt.getFullYear();
var month = dt.getMonth();
var date = dt.getDate();
return format.toLowerCase()
.replace('month', w2utils.settings.fullmonths[month])
.replace('mon', w2utils.settings.shortmonths[month])
.replace(/yyyy/g, year)
.replace(/yyy/g, year)
.replace(/yy/g, year > 2000 ? 100 + parseInt(String(year).substr(2)) : String(year).substr(2))
.replace(/(^|[^a-z$])y/g, '$1' + year) // only y's that are not preceded by a letter
.replace(/mm/g, (month + 1 < 10 ? '0' : '') + (month + 1))
.replace(/dd/g, (date < 10 ? '0' : '') + date)
.replace(/th/g, (date == 1 ? 'st' : 'th'))
.replace(/th/g, (date == 2 ? 'nd' : 'th'))
.replace(/th/g, (date == 3 ? 'rd' : 'th'))
.replace(/(^|[^a-z$])m/g, '$1' + (month + 1)) // only y's that are not preceded by a letter
.replace(/(^|[^a-z$])d/g, '$1' + date); // only y's that are not preceded by a letter
}
function formatTime (dateStr, format) { // IMPORTANT dateStr HAS TO BE valid JavaScript Date String
var months = w2utils.settings.shortmonths;
var fullMonths = w2utils.settings.fullmonths;
if (!format) format = this.settings.time_format;
if (dateStr === '' || dateStr == null || (typeof dateStr == 'object' && !dateStr.getMonth)) return '';
var dt = new Date(dateStr);
if (w2utils.isInt(dateStr)) dt = new Date(Number(dateStr)); // for unix timestamps
if (w2utils.isTime(dateStr)) {
var tmp = w2utils.isTime(dateStr, true);
dt = new Date();
dt.setHours(tmp.hours);
dt.setMinutes(tmp.minutes);
}
if (String(dt) == 'Invalid Date') return '';
var type = 'am';
var hour = dt.getHours();
var h24 = dt.getHours();
var min = dt.getMinutes();
var sec = dt.getSeconds();
if (min < 10) min = '0' + min;
if (sec < 10) sec = '0' + sec;
if (format.indexOf('am') !== -1 || format.indexOf('pm') !== -1) {
if (hour >= 12) type = 'pm';
if (hour > 12) hour = hour - 12;
}
return format.toLowerCase()
.replace('am', type)
.replace('pm', type)
.replace('hhh', (hour < 10 ? '0' + hour : hour))
.replace('hh24', (h24 < 10 ? '0' + h24 : h24))
.replace('h24', h24)
.replace('hh', hour)
.replace('mm', min)
.replace('mi', min)
.replace('ss', sec)
.replace(/(^|[^a-z$])h/g, '$1' + hour) // only y's that are not preceded by a letter
.replace(/(^|[^a-z$])m/g, '$1' + min) // only y's that are not preceded by a letter
.replace(/(^|[^a-z$])s/g, '$1' + sec); // only y's that are not preceded by a letter
}
function formatDateTime(dateStr, format) {
var fmt;
if (dateStr === '' || dateStr == null || (typeof dateStr == 'object' && !dateStr.getMonth)) return '';
if (typeof format !== 'string') {
fmt = [this.settings.date_format, this.settings.time_format];
} else {
fmt = format.split('|');
}
// older formats support
if (fmt[1] == 'h12') fmt[1] = 'h:m pm';
if (fmt[1] == 'h24') fmt[1] = 'h24:m';
return this.formatDate(dateStr, fmt[0]) + ' ' + this.formatTime(dateStr, fmt[1]);
}
function stripTags (html) {
if (html == null) return html;
switch (typeof html) {
case 'number':
break;
case 'string':
html = $.trim(String(html).replace(/(<([^>]+)>)/ig, ""));
break;
case 'object':
// does not modify original object, but creates a copy
if (Array.isArray(html)) {
html = $.extend(true, [], html);
for (var i = 0; i < html.length; i++) html[i] = this.stripTags(html[i]);
} else {
html = $.extend(true, {}, html);
for (var i in html) html[i] = this.stripTags(html[i]);
}
break;
}
return html;
}
function encodeTags (html) {
if (html == null) return html;
switch (typeof html) {
case 'number':
break;
case 'string':
html = String(html).replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, """);
break;
case 'object':
// does not modify original object, but creates a copy
if (Array.isArray(html)) {
html = $.extend(true, [], html);
for (var i = 0; i < html.length; i++) html[i] = this.encodeTags(html[i]);
} else {
html = $.extend(true, {}, html);
for (var i in html) html[i] = this.encodeTags(html[i]);
}
break;
}
return html;
}
function escapeId (id) {
if (id === '' || id == null) return '';
return String(id).replace(/([;&,\.\+\*\~'`:"\!\^#$%@\[\]\(\)=<>\|\/? {}\\])/g, '\\$1');
}
function base64encode (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
input = 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 + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);
}
function utf8_encode (string) {
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;
}
return output;
}
function base64decode (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = keyStr.indexOf(input.charAt(i++));
enc2 = keyStr.indexOf(input.charAt(i++));
enc3 = keyStr.indexOf(input.charAt(i++));
enc4 = 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 = utf8_decode(output);
function utf8_decode (utftext) {
var string = "";
var i = 0;
var c = 0, c2, c3;
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;
}
return output;
}
function md5(input) {
/*
* Based on http://pajhome.org.uk/crypt/md5
*/
var hexcase = 0;
var b64pad = "";
function __pj_crypt_hex_md5(s) {
return __pj_crypt_rstr2hex(__pj_crypt_rstr_md5(__pj_crypt_str2rstr_utf8(s)));
}
function __pj_crypt_b64_md5(s) {
return __pj_crypt_rstr2b64(__pj_crypt_rstr_md5(__pj_crypt_str2rstr_utf8(s)));
}
function __pj_crypt_any_md5(s, e) {
return __pj_crypt_rstr2any(__pj_crypt_rstr_md5(__pj_crypt_str2rstr_utf8(s)), e);
}
function __pj_crypt_hex_hmac_md5(k, d)
{
return __pj_crypt_rstr2hex(__pj_crypt_rstr_hmac_md5(__pj_crypt_str2rstr_utf8(k), __pj_crypt_str2rstr_utf8(d)));
}
function __pj_crypt_b64_hmac_md5(k, d)
{
return __pj_crypt_rstr2b64(__pj_crypt_rstr_hmac_md5(__pj_crypt_str2rstr_utf8(k), __pj_crypt_str2rstr_utf8(d)));
}
function __pj_crypt_any_hmac_md5(k, d, e)
{
return __pj_crypt_rstr2any(__pj_crypt_rstr_hmac_md5(__pj_crypt_str2rstr_utf8(k), __pj_crypt_str2rstr_utf8(d)), e);
}
/*
* Calculate the MD5 of a raw string
*/
function __pj_crypt_rstr_md5(s)
{
return __pj_crypt_binl2rstr(__pj_crypt_binl_md5(__pj_crypt_rstr2binl(s), s.length * 8));
}
/*
* Calculate the HMAC-MD5, of a key and some data (raw strings)
*/
function __pj_crypt_rstr_hmac_md5(key, data)
{
var bkey = __pj_crypt_rstr2binl(key);
if (bkey.length > 16)
bkey = __pj_crypt_binl_md5(bkey, key.length * 8);
var ipad = Array(16), opad = Array(16);
for (var i = 0; i < 16; i++)
{
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = __pj_crypt_binl_md5(ipad.concat(__pj_crypt_rstr2binl(data)), 512 + data.length * 8);
return __pj_crypt_binl2rstr(__pj_crypt_binl_md5(opad.concat(hash), 512 + 128));
}
/*
* Convert a raw string to a hex string
*/
function __pj_crypt_rstr2hex(input)
{
try {
hexcase
} catch (e) {
hexcase = 0;
}
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var output = "";
var x;
for (var i = 0; i < input.length; i++)
{
x = input.charCodeAt(i);
output += hex_tab.charAt((x >>> 4) & 0x0F)
+ hex_tab.charAt(x & 0x0F);
}
return output;
}
/*
* Convert a raw string to a base-64 string
*/
function __pj_crypt_rstr2b64(input)
{
try {
b64pad
} catch (e) {
b64pad = '';
}
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var output = "";
var len = input.length;
for (var i = 0; i < len; i += 3)
{
var triplet = (input.charCodeAt(i) << 16)
| (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0)
| (i + 2 < len ? input.charCodeAt(i + 2) : 0);
for (var j = 0; j < 4; j++)
{
if (i * 8 + j * 6 > input.length * 8)
output += b64pad;
else
output += tab.charAt((triplet >>> 6 * (3 - j)) & 0x3F);
}
}
return output;
}
/*
* Convert a raw string to an arbitrary string encoding
*/
function __pj_crypt_rstr2any(input, encoding)
{
var divisor = encoding.length;
var i, j, q, x, quotient;
/* Convert to an array of 16-bit big-endian values, forming the dividend */
var dividend = Array(Math.ceil(input.length / 2));
for (i = 0; i < dividend.length; i++)
{
dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1);
}
/*
* Repeatedly perform a long division. The binary array forms the dividend,
* the length of the encoding is the divisor. Once computed, the quotient
* forms the dividend for the next step. All remainders are stored for later
* use.
*/
var full_length = Math.ceil(input.length * 8 /
(Math.log(encoding.length) / Math.log(2)));
var remainders = Array(full_length);
for (j = 0; j < full_length; j++)
{
quotient = Array();
x = 0;
for (i = 0; i < dividend.length; i++)
{
x = (x << 16) + dividend[i];
q = Math.floor(x / divisor);
x -= q * divisor;
if (quotient.length > 0 || q > 0)
quotient[quotient.length] = q;
}
remainders[j] = x;
dividend = quotient;
}
/* Convert the remainders to the output string */
var output = "";
for (i = remainders.length - 1; i >= 0; i--)
output += encoding.charAt(remainders[i]);
return output;
}
/*
* Encode a string as utf-8.
* For efficiency, this assumes the input is valid utf-16.
*/
function __pj_crypt_str2rstr_utf8(input)
{
var output = "";
var i = -1;
var x, y;
while (++i < input.length)
{
/* Decode utf-16 surrogate pairs */
x = input.charCodeAt(i);
y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
if (0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF)
{
x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
i++;
}
/* Encode output as utf-8 */
if (x <= 0x7F)
output += String.fromCharCode(x);
else if (x <= 0x7FF)
output += String.fromCharCode(0xC0 | ((x >>> 6) & 0x1F),
0x80 | (x & 0x3F));
else if (x <= 0xFFFF)
output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),
0x80 | ((x >>> 6) & 0x3F),
0x80 | (x & 0x3F));
else if (x <= 0x1FFFFF)
output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),
0x80 | ((x >>> 12) & 0x3F),
0x80 | ((x >>> 6) & 0x3F),
0x80 | (x & 0x3F));
}
return output;
}
/*
* Encode a string as utf-16
*/
function __pj_crypt_str2rstr_utf16le(input)
{
var output = "";
for (var i = 0; i < input.length; i++)
output += String.fromCharCode(input.charCodeAt(i) & 0xFF,
(input.charCodeAt(i) >>> 8) & 0xFF);
return output;
}
function __pj_crypt_str2rstr_utf16be(input)
{
var output = "";
for (var i = 0; i < input.length; i++)
output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF,
input.charCodeAt(i) & 0xFF);
return output;
}
/*
* Convert a raw string to an array of little-endian words
* Characters >255 have their high-byte silently ignored.
*/
function __pj_crypt_rstr2binl(input)
{
var output = Array(input.length >> 2);
for (var i = 0; i < output.length; i++)
output[i] = 0;
for (var i = 0; i < input.length * 8; i += 8)
output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32);
return output;
}
/*
* Convert an array of little-endian words to a string
*/
function __pj_crypt_binl2rstr(input)
{
var output = "";
for (var i = 0; i < input.length * 32; i += 8)
output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF);
return output;
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length.
*/
function __pj_crypt_binl_md5(x, len)
{
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for (var i = 0; i < x.length; i += 16)
{
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = __pj_crypt_md5_ff(a, b, c, d, x[i + 0], 7, -680876936);
d = __pj_crypt_md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
c = __pj_crypt_md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
b = __pj_crypt_md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
a = __pj_crypt_md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
d = __pj_crypt_md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
c = __pj_crypt_md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
b = __pj_crypt_md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
a = __pj_crypt_md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
d = __pj_crypt_md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
c = __pj_crypt_md5_ff(c, d, a, b, x[i + 10], 17, -42063);
b = __pj_crypt_md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
a = __pj_crypt_md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
d = __pj_crypt_md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
c = __pj_crypt_md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
b = __pj_crypt_md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);
a = __pj_crypt_md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
d = __pj_crypt_md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
c = __pj_crypt_md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
b = __pj_crypt_md5_gg(b, c, d, a, x[i + 0], 20, -373897302);
a = __pj_crypt_md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
d = __pj_crypt_md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
c = __pj_crypt_md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
b = __pj_crypt_md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
a = __pj_crypt_md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
d = __pj_crypt_md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
c = __pj_crypt_md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
b = __pj_crypt_md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
a = __pj_crypt_md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
d = __pj_crypt_md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
c = __pj_crypt_md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
b = __pj_crypt_md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);
a = __pj_crypt_md5_hh(a, b, c, d, x[i + 5], 4, -378558);
d = __pj_crypt_md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
c = __pj_crypt_md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
b = __pj_crypt_md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
a = __pj_crypt_md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
d = __pj_crypt_md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
c = __pj_crypt_md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
b = __pj_crypt_md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
a = __pj_crypt_md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
d = __pj_crypt_md5_hh(d, a, b, c, x[i + 0], 11, -358537222);
c = __pj_crypt_md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
b = __pj_crypt_md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
a = __pj_crypt_md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
d = __pj_crypt_md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
c = __pj_crypt_md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
b = __pj_crypt_md5_hh(b, c, d, a, x[i + 2], 23, -995338651);
a = __pj_crypt_md5_ii(a, b, c, d, x[i + 0], 6, -198630844);
d = __pj_crypt_md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
c = __pj_crypt_md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
b = __pj_crypt_md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
a = __pj_crypt_md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
d = __pj_crypt_md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
c = __pj_crypt_md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
b = __pj_crypt_md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
a = __pj_crypt_md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
d = __pj_crypt_md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
c = __pj_crypt_md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
b = __pj_crypt_md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
a = __pj_crypt_md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
d = __pj_crypt_md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
c = __pj_crypt_md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
b = __pj_crypt_md5_ii(b, c, d, a, x[i + 9], 21, -343485551);
a = __pj_crypt_safe_add(a, olda);
b = __pj_crypt_safe_add(b, oldb);
c = __pj_crypt_safe_add(c, oldc);
d = __pj_crypt_safe_add(d, oldd);
}
return Array(a, b, c, d);
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function __pj_crypt_md5_cmn(q, a, b, x, s, t)
{
return __pj_crypt_safe_add(__pj_crypt_bit_rol(__pj_crypt_safe_add(__pj_crypt_safe_add(a, q), __pj_crypt_safe_add(x, t)), s), b);
}
function __pj_crypt_md5_ff(a, b, c, d, x, s, t)
{
return __pj_crypt_md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function __pj_crypt_md5_gg(a, b, c, d, x, s, t)
{
return __pj_crypt_md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function __pj_crypt_md5_hh(a, b, c, d, x, s, t)
{
return __pj_crypt_md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function __pj_crypt_md5_ii(a, b, c, d, x, s, t)
{
return __pj_crypt_md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function __pj_crypt_safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function __pj_crypt_bit_rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}
return __pj_crypt_hex_md5(input);
}
function transition (div_old, div_new, type, callBack) {
var width = $(div_old).width();
var height = $(div_old).height();
var time = 0.5;
if (!div_old || !div_new) {
console.log('ERROR: Cannot do transition when one of the divs is null');
return;
}
div_old.parentNode.style.cssText += 'perspective: 700; overflow: hidden;';
div_old.style.cssText += '; position: absolute; z-index: 1019; backface-visibility: hidden';
div_new.style.cssText += '; position: absolute; z-index: 1020; backface-visibility: hidden';
switch (type) {
case 'slide-left':
// init divs
div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0)';
div_new.style.cssText += 'overflow: hidden; transform: translate3d('+ width + 'px, 0, 0)';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; transform: translate3d(0, 0, 0)';
div_old.style.cssText += 'transition: '+ time +'s; transform: translate3d(-'+ width +'px, 0, 0)';
}, 1);
break;
case 'slide-right':
// init divs
div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0)';
div_new.style.cssText += 'overflow: hidden; transform: translate3d(-'+ width +'px, 0, 0)';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; transform: translate3d(0px, 0, 0)';
div_old.style.cssText += 'transition: '+ time +'s; transform: translate3d('+ width +'px, 0, 0)';
}, 1);
break;
case 'slide-down':
// init divs
div_old.style.cssText += 'overflow: hidden; z-index: 1; transform: translate3d(0, 0, 0)';
div_new.style.cssText += 'overflow: hidden; z-index: 0; transform: translate3d(0, 0, 0)';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; transform: translate3d(0, 0, 0)';
div_old.style.cssText += 'transition: '+ time +'s; transform: translate3d(0, '+ height +'px, 0)';
}, 1);
break;
case 'slide-up':
// init divs
div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0)';
div_new.style.cssText += 'overflow: hidden; transform: translate3d(0, '+ height +'px, 0)';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; transform: translate3d(0, 0, 0)';
div_old.style.cssText += 'transition: '+ time +'s; transform: translate3d(0, 0, 0)';
}, 1);
break;
case 'flip-left':
// init divs
div_old.style.cssText += 'overflow: hidden; transform: rotateY(0deg)';
div_new.style.cssText += 'overflow: hidden; transform: rotateY(-180deg)';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; transform: rotateY(0deg)';
div_old.style.cssText += 'transition: '+ time +'s; transform: rotateY(180deg)';
}, 1);
break;
case 'flip-right':
// init divs
div_old.style.cssText += 'overflow: hidden; transform: rotateY(0deg)';
div_new.style.cssText += 'overflow: hidden; transform: rotateY(180deg)';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; transform: rotateY(0deg)';
div_old.style.cssText += 'transition: '+ time +'s; transform: rotateY(-180deg)';
}, 1);
break;
case 'flip-down':
// init divs
div_old.style.cssText += 'overflow: hidden; transform: rotateX(0deg)';
div_new.style.cssText += 'overflow: hidden; transform: rotateX(180deg)';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; transform: rotateX(0deg)';
div_old.style.cssText += 'transition: '+ time +'s; transform: rotateX(-180deg)';
}, 1);
break;
case 'flip-up':
// init divs
div_old.style.cssText += 'overflow: hidden; transform: rotateX(0deg)';
div_new.style.cssText += 'overflow: hidden; transform: rotateX(-180deg)';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; transform: rotateX(0deg)';
div_old.style.cssText += 'transition: '+ time +'s; transform: rotateX(180deg)';
}, 1);
break;
case 'pop-in':
// init divs
div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0)';
div_new.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0); transform: scale(.8); opacity: 0;';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; transform: scale(1); opacity: 1;';
div_old.style.cssText += 'transition: '+ time +'s;';
}, 1);
break;
case 'pop-out':
// init divs
div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0); transform: scale(1); opacity: 1;';
div_new.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0); opacity: 0;';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; opacity: 1;';
div_old.style.cssText += 'transition: '+ time +'s; transform: scale(1.7); opacity: 0;';
}, 1);
break;
default:
// init divs
div_old.style.cssText += 'overflow: hidden; transform: translate3d(0, 0, 0)';
div_new.style.cssText += 'overflow: hidden; translate3d(0, 0, 0); opacity: 0;';
$(div_new).show();
// -- need a timing function because otherwise not working
window.setTimeout(function() {
div_new.style.cssText += 'transition: '+ time +'s; opacity: 1;';
div_old.style.cssText += 'transition: '+ time +'s';
}, 1);
break;
}
setTimeout(function () {
if (type === 'slide-down') {
$(div_old).css('z-index', '1019');
$(div_new).css('z-index', '1020');
}
if (div_new) {
$(div_new).css({ 'opacity': '1' }).css(w2utils.cssPrefix({
'transition': '',
'transform' : ''
}));
}
if (div_old) {
$(div_old).css({ 'opacity': '1' }).css(w2utils.cssPrefix({
'transition': '',
'transform' : ''
}));
}
if (typeof callBack === 'function') callBack();
}, time * 1000);
}
function lock (box, msg, spinner) {
var options = {};
if (typeof msg === 'object') {
options = msg;
} else {
options.msg = msg;
options.spinner = spinner;
}
if (!options.msg && options.msg !== 0) options.msg = '';
w2utils.unlock(box);
$(box).prepend(
'<div class="w2ui-lock"></div>'+
'<div class="w2ui-lock-msg"></div>'
);
var $lock = $(box).find('.w2ui-lock');
var mess = $(box).find('.w2ui-lock-msg');
if (!options.msg) mess.css({ 'background-color': 'transparent', 'border': '0px' });
if (options.spinner === true) options.msg = '<div class="w2ui-spinner" '+ (!options.msg ? 'style="width: 35px; height: 35px"' : '') +'></div>' + options.msg;
if (options.opacity != null) $lock.css('opacity', options.opacity);
if (typeof $lock.fadeIn == 'function') {
$lock.fadeIn(200);
mess.html(options.msg).fadeIn(200);
} else {
$lock.show();
mess.html(options.msg).show(0);
}
// hide all tags (do not hide overlays as the form can be in overlay)
$().w2tag();
}
function unlock (box, speed) {
if (isInt(speed)) {
$(box).find('.w2ui-lock').fadeOut(speed);
setTimeout(function () {
$(box).find('.w2ui-lock').remove();
$(box).find('.w2ui-lock-msg').remove();
}, speed);
} else {
$(box).find('.w2ui-lock').remove();
$(box).find('.w2ui-lock-msg').remove();
}
}
function getSize (el, type) {
var $el = $(el);
var bwidth = {
left : parseInt($el.css('border-left-width')) || 0,
right : parseInt($el.css('border-right-width')) || 0,
top : parseInt($el.css('border-top-width')) || 0,
bottom : parseInt($el.css('border-bottom-width')) || 0
};
var mwidth = {
left : parseInt($el.css('margin-left')) || 0,
right : parseInt($el.css('margin-right')) || 0,
top : parseInt($el.css('margin-top')) || 0,
bottom : parseInt($el.css('margin-bottom')) || 0
};
var pwidth = {
left : parseInt($el.css('padding-left')) || 0,
right : parseInt($el.css('padding-right')) || 0,
top : parseInt($el.css('padding-top')) || 0,
bottom : parseInt($el.css('padding-bottom')) || 0
};
switch (type) {
case 'top' : return bwidth.top + mwidth.top + pwidth.top;
case 'bottom' : return bwidth.bottom + mwidth.bottom + pwidth.bottom;
case 'left' : return bwidth.left + mwidth.left + pwidth.left;
case 'right' : return bwidth.right + mwidth.right + pwidth.right;
case 'width' : return bwidth.left + bwidth.right + mwidth.left + mwidth.right + pwidth.left + pwidth.right + parseInt($el.width());
case 'height' : return bwidth.top + bwidth.bottom + mwidth.top + mwidth.bottom + pwidth.top + pwidth.bottom + parseInt($el.height());
case '+width' : return bwidth.left + bwidth.right + mwidth.left + mwidth.right + pwidth.left + pwidth.right;
case '+height' : return bwidth.top + bwidth.bottom + mwidth.top + mwidth.bottom + pwidth.top + pwidth.bottom;
}
return 0;
}
function getStrWidth (str, styles) {
var w, html = '<div id="_tmp_width" style="position: absolute; top: -900px;'+ styles +'">'+ str +'</div>';
$('body').append(html);
w = $('#_tmp_width').width();
$('#_tmp_width').remove();
return w;
}
function lang (phrase) {
var translation = this.settings.phrases[phrase];
if (translation == null) return phrase; else return translation;
}
function locale (locale) {
if (!locale) locale = 'en-us';
// if the locale is an object, not a string, than we assume it's a
if(typeof locale !== "string" ) {
w2utils.settings = $.extend(true, w2utils.settings, locale);
return
}
if (locale.length === 5) locale = 'locale/'+ locale +'.json';
// clear phrases from language before
w2utils.settings.phrases = {};
// load from the file
$.ajax({
url : locale,
type : "GET",
dataType : "JSON",
async : false,
cache : false,
success : function (data, status, xhr) {
w2utils.settings = $.extend(true, w2utils.settings, data);
},
error : function (xhr, status, msg) {
console.log('ERROR: Cannot load locale '+ locale);
}
});
}
function scrollBarSize () {
if (tmp.scrollBarSize) return tmp.scrollBarSize;
var html =
'<div id="_scrollbar_width" style="position: absolute; top: -300px; width: 100px; height: 100px; overflow-y: scroll;">'+
' <div style="height: 120px">1</div>'+
'</div>';
$('body').append(html);
tmp.scrollBarSize = 100 - $('#_scrollbar_width > div').width();
$('#_scrollbar_width').remove();
if (String(navigator.userAgent).indexOf('MSIE') >= 0) tmp.scrollBarSize = tmp.scrollBarSize / 2; // need this for IE9+
return tmp.scrollBarSize;
}
function checkName (params, component) { // was w2checkNameParam
if (!params || params.name == null) {
console.log('ERROR: The parameter "name" is required but not supplied in $().'+ component +'().');
return false;
}
if (w2ui[params.name] != null) {
console.log('ERROR: The parameter "name" is not unique. There are other objects already created with the same name (obj: '+ params.name +').');
return false;
}
if (!w2utils.isAlphaNumeric(params.name)) {
console.log('ERROR: The parameter "name" has to be alpha-numeric (a-z, 0-9, dash and underscore). ');
return false;
}
return true;
}
function checkUniqueId (id, items, itemsDecription, objName) { // was w2checkUniqueId
if (!$.isArray(items)) items = [items];
for (var i = 0; i < items.length; i++) {
if (items[i].id === id) {
console.log('ERROR: The parameter "id='+ id +'" is not unique within the current '+ itemsDecription +'. (obj: '+ objName +')');
return false;
}
}
return true;
}
function parseRoute(route) {
var keys = [];
var path = route
.replace(/\/\(/g, '(?:/')
.replace(/\+/g, '__plus__')
.replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, function(_, slash, format, key, capture, optional) {
keys.push({ name: key, optional: !! optional });
slash = slash || '';
return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')' + (optional || '');
})
.replace(/([\/.])/g, '\\$1')
.replace(/__plus__/g, '(.+)')
.replace(/\*/g, '(.*)');
return {
path : new RegExp('^' + path + '$', 'i'),
keys : keys
};
}
function cssPrefix(field, value, returnString) {
var css = {};
var newCSS = {};
var ret = '';
if (!$.isPlainObject(field)) {
css[field] = value;
} else {
css = field;
if (value === true) returnString = true;
}
for (var c in css) {
newCSS[c] = css[c];
newCSS['-webkit-'+c] = css[c];
newCSS['-moz-'+c] = css[c].replace('-webkit-', '-moz-');
newCSS['-ms-'+c] = css[c].replace('-webkit-', '-ms-');
newCSS['-o-'+c] = css[c].replace('-webkit-', '-o-');
}
if (returnString === true) {
for (var c in newCSS) {
ret += c + ': ' + newCSS[c] + '; ';
}
} else {
ret = newCSS;
}
return ret;
}
})(jQuery);
/***********************************************************
* Generic Event Object
* --- This object is reused across all other
* --- widgets in w2ui.
*
*********************************************************/
w2utils.event = {
on: function (edata, handler) {
// allow 'eventName:after' syntax
if (typeof edata == 'string' && edata.indexOf(':') != -1) {
var tmp = edata.split(':');
if (['complete', 'done'].indexOf(edata[1]) != -1) edata[1] = 'after';
edata = {
type : tmp[0],
execute : tmp[1]
};
}
if (!$.isPlainObject(edata)) edata = { type: edata };
edata = $.extend({ type: null, execute: 'before', target: null, onComplete: null }, edata);
// errors
if (!edata.type) { console.log('ERROR: You must specify event type when calling .on() method of '+ this.name); return; }
if (!handler) { console.log('ERROR: You must specify event handler function when calling .on() method of '+ this.name); return; }
if (!$.isArray(this.handlers)) this.handlers = [];
this.handlers.push({ edata: edata, handler: handler });
},
off: function (edata, handler) {
// allow 'eventName:after' syntax
if (typeof edata == 'string' && edata.indexOf(':') != -1) {
var tmp = edata.split(':');
if (['complete', 'done'].indexOf(edata[1]) != -1) edata[1] = 'after';
edata = {
type : tmp[0],
execute : tmp[1]
}
}
if (!$.isPlainObject(edata)) edata = { type: edata };
edata = $.extend({}, { type: null, execute: 'before', target: null, onComplete: null }, edata);
// errors
if (!edata.type) { console.log('ERROR: You must specify event type when calling .off() method of '+ this.name); return; }
if (!handler) { handler = null; }
// remove handlers
var newHandlers = [];
for (var h = 0, len = this.handlers.length; h < len; h++) {
var t = this.handlers[h];
if ((t.edata.type === edata.type || edata.type === '*') &&
(t.edata.target === edata.target || edata.target == null) &&
(t.edata.execute === edata.execute || edata.execute == null) &&
(t.handler === handler || handler == null))
{
// match
} else {
newHandlers.push(t);
}
}
this.handlers = newHandlers;
},
trigger: function (edata) {
var edata = $.extend({ type: null, phase: 'before', target: null, doneHandlers: [] }, edata, {
isStopped : false,
isCancelled : false,
done : function (handler) { this.doneHandlers.push(handler); },
preventDefault : function () { this.isCancelled = true; },
stopPropagation : function () { this.isStopped = true; }
});
if (edata.phase === 'before') edata.onComplete = null;
var args, fun, tmp;
if (edata.target == null) edata.target = null;
if (!$.isArray(this.handlers)) this.handlers = [];
// process events in REVERSE order
for (var h = this.handlers.length-1; h >= 0; h--) {
var item = this.handlers[h];
if ((item.edata.type === edata.type || item.edata.type === '*') &&
(item.edata.target === edata.target || item.edata.target == null) &&
(item.edata.execute === edata.phase || item.edata.execute === '*' || item.edata.phase === '*'))
{
edata = $.extend({}, item.edata, edata);
// check handler arguments
args = [];
tmp = new RegExp(/\((.*?)\)/).exec(item.handler);
if (tmp) args = tmp[1].split(/\s*,\s*/);
if (args.length === 2) {
item.handler.call(this, edata.target, edata); // old way for back compatibility
} else {
item.handler.call(this, edata); // new way
}
if (edata.isStopped === true || edata.stop === true) return edata; // back compatibility edata.stop === true
}
}
// main object events
var funName = 'on' + edata.type.substr(0,1).toUpperCase() + edata.type.substr(1);
if (edata.phase === 'before' && typeof this[funName] === 'function') {
fun = this[funName];
// check handler arguments
args = [];
tmp = new RegExp(/\((.*?)\)/).exec(fun);
if (tmp) args = tmp[1].split(/\s*,\s*/);
if (args.length === 2) {
fun.call(this, edata.target, edata); // old way for back compatibility
} else {
fun.call(this, edata); // new way
}
if (edata.isStopped === true || edata.stop === true) return edata; // back compatibility edata.stop === true
}
// item object events
if (edata.object != null && edata.phase === 'before' &&
typeof edata.object[funName] === 'function')
{
fun = edata.object[funName];
// check handler arguments
args = [];
tmp = new RegExp(/\((.*?)\)/).exec(fun);
if (tmp) args = tmp[1].split(/\s*,\s*/);
if (args.length === 2) {
fun.call(this, edata.target, edata); // old way for back compatibility
} else {
fun.call(this, edata); // new way
}
if (edata.isStopped === true || edata.stop === true) return edata;
}
// execute onComplete
if (edata.phase === 'after') {
if (typeof edata.onComplete === 'function') edata.onComplete.call(this, edata);
for (var i = 0; i < edata.doneHandlers.length; i++) {
if (typeof edata.doneHandlers[i] == 'function') {
edata.doneHandlers[i].call(this, edata);
}
}
}
return edata;
}
};
/***********************************************************
* Commonly used plugins
* --- used primarily in grid and form
*
*********************************************************/
(function ($) {
$.fn.w2render = function (name) {
if ($(this).length > 0) {
if (typeof name === 'string' && w2ui[name]) w2ui[name].render($(this)[0]);
if (typeof name === 'object') name.render($(this)[0]);
}
};
$.fn.w2destroy = function (name) {
if (!name && this.length > 0) name = this.attr('name');
if (typeof name === 'string' && w2ui[name]) w2ui[name].destroy();
if (typeof name === 'object') name.destroy();
};
$.fn.w2marker = function () {
var str = Array.prototype.slice.call(arguments, 0);
if (str.length == 0 || !str[0]) { // remove marker
return $(this).each(clearMarkedText);
} else { // add marker
return $(this).each(function (index, el) {
clearMarkedText(index, el);
for (var s = 0; s < str.length; s++) {
var tmp = str[s];
if (typeof tmp !== 'string') tmp = String(tmp);
// escape regex special chars
tmp = tmp.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&").replace(/&/g, '&').replace(/</g, '>').replace(/>/g, '<');
var regex = new RegExp(tmp + '(?!([^<]+)?>)', "gi"); // only outside tags
el.innerHTML = el.innerHTML.replace(regex, replaceValue);
}
function replaceValue(matched) { // mark new
return '<span class="w2ui-marker">' + matched + '</span>';
}
});
}
function clearMarkedText(index, el) {
while (el.innerHTML.indexOf('<span class="w2ui-marker">') != -1) {
el.innerHTML = el.innerHTML.replace(/\<span class=\"w2ui\-marker\"\>(.*)\<\/span\>/ig, '$1'); // unmark
}
}
};
// -- w2tag - there can be multiple on screen at a time
$.fn.w2tag = function (text, options) {
// only one argument
if (arguments.length == 1 && typeof text == 'object') {
options = text;
if (options.html != null) text = options.html;
}
// default options
options = $.extend({
id : null, // id for the tag, otherwise input id is used
html : text, // or html
position : 'right', // can be left, right, top, bottom
left : 0, // delta for left coordinate
top : 0, // delta for top coordinate
style : '', // adition style for the tag
css : {}, // add css for input when tag is shown
className : '', // add class bubble
inputClass : '', // add class for input when tag is shown
onShow : null, // callBack when shown
onHide : null, // callBack when hidden
hideOnKeyPress : true, // hide tag if key pressed
hideOnBlur : false // hide tag on blur
}, options);
// for backward compatibility
if (options['class'] != '' && options.inputClass == '') options.inputClass = options['class'];
// remove all tags
if ($(this).length === 0) {
$('.w2ui-tag').each(function (index, el) {
var opt = $(el).data('options');
if (opt == null) opt = {};
$($(el).data('taged-el')).removeClass(opt.inputClass);
clearInterval($(el).data('timer'));
$(el).remove();
});
return;
}
return $(this).each(function (index, el) {
// show or hide tag
var origID = (options.id ? options.id : el.id);
var tagID = w2utils.escapeId(origID);
var $tags = $('#w2ui-tag-'+tagID);
if (text === '' || text == null) {
// remmove element
$tags.css('opacity', 0);
clearInterval($tags.data('timer'));
$tags.remove();
return;
} else if ($tags.length != 0) {
// if already present
options = $.extend($tags.data('options'), options);
$tags.data('options', options);
$tags.find('.w2ui-tag-body')
.attr('style', options.style)
.addClass(options.className)
.html(options.html);
} else {
var originalCSS = '';
if ($(el).length > 0) originalCSS = $(el)[0].style.cssText;
// insert
$('body').append(
'<div id="w2ui-tag-'+ origID +'" class="w2ui-tag '+ ($(el).parents('.w2ui-popup').length > 0 ? 'w2ui-tag-popup' : '') + '">'+
' <div style="margin: -2px 0px 0px -2px; white-space: nowrap;">'+
' <div class="w2ui-tag-body '+ options.className +'" style="'+ (options.style || '') +'">'+ text +'</div>'+
' </div>' +
'</div>');
$tags = $('#w2ui-tag-'+tagID);
$(el).data('w2tag', $tags.get(0));
}
// need time out to allow tag to be rendered
setTimeout(function () {
if (!$(el).offset()) return;
var pos = checkIfMoved();
$tags.css({
opacity : '1',
left : pos.left + 'px',
top : pos.top + 'px'
})
.data('options', options)
.data('taged-el', el)
.data('position', pos.left + 'x' + pos.top)
.data('timer', setInterval(checkIfMoved, 100))
.find('.w2ui-tag-body').addClass(pos['posClass']);
$(el).css(options.css)
.off('.w2tag')
.addClass(options.inputClass);
if (options.hideOnKeyPress) {
$(el).on('keypress.w2tag', hideTag)
}
if (options.hideOnBlur) {
$(el).on('blur.w2tag', hideTag)
}
if (typeof options.onShow === 'function') options.onShow();
}, 1);
// bind event to hide it
function hideTag() {
$tags = $('#w2ui-tag-'+tagID);
if ($tags.length <= 0) return;
clearInterval($tags.data('timer'));
$tags.remove();
$(el).off('.w2tag', hideTag)
.removeClass(options.inputClass)
.removeData('w2tag');
if ($(el).length > 0) $(el)[0].style.cssText = originalCSS;
if (typeof options.onHide === 'function') options.onHide();
}
function checkIfMoved() {
// monitor if destroyed
var offset = $(el).offset();
if ($(el).length === 0 || (offset.left === 0 && offset.top === 0) || $tags.find('.w2ui-tag-body').length == 0) {
clearInterval($tags.data('timer'));
hideTag();
return;
}
// monitor if moved
var posClass = 'w2ui-tag-right';
var posLeft = parseInt($(el).offset().left + el.offsetWidth + (options.left ? options.left : 0));
var posTop = parseInt($(el).offset().top + (options.top ? options.top : 0));
var tagBody = $tags.find('.w2ui-tag-body');
var width = tagBody[0].offsetWidth;
var height = tagBody[0].offsetHeight;
if (options.position == 'top') {
posClass = 'w2ui-tag-top';
posLeft = parseInt($(el).offset().left + (options.left ? options.left : 0)) - 14;
posTop = parseInt($(el).offset().top + (options.top ? options.top : 0)) - height - 10;
}
if (options.position == 'bottom') {
posClass = 'w2ui-tag-bottom';
posLeft = parseInt($(el).offset().left + (options.left ? options.left : 0)) - 14;
posTop = parseInt($(el).offset().top + el.offsetHeight + (options.top ? options.top : 0)) + 10;
}
if (options.position == 'left') {
posClass = 'w2ui-tag-left';
posLeft = parseInt($(el).offset().left + (options.left ? options.left : 0)) - width - 20;
posTop = parseInt($(el).offset().top + (options.top ? options.top : 0));
}
if ($tags.data('position') !== posLeft + 'x' + posTop) {
$tags.css(w2utils.cssPrefix({ 'transition': '.2s' })).css({
left: posLeft + 'px',
top : posTop + 'px'
}).data('position', posLeft + 'x' + posTop);
}
return { left: posLeft, top: posTop, posClass: posClass };
}
});
};
// w2overlay - appears under the element, there can be only one at a time
$.fn.w2overlay = function (html, options) {
var obj = this;
var name = '';
var defaults = {
name : null, // it not null, then allows multiple concurrent overlays
html : '', // html text to display
align : 'none', // can be none, left, right, both
left : 0, // offset left
top : 0, // offset top
tipLeft : 30, // tip offset left
noTip : false, // if true - no tip will be displayed
selectable : false,
width : 0, // fixed width
height : 0, // fixed height
maxWidth : null, // max width if any
maxHeight : null, // max height if any
contextMenu : false, // if true, it will be opened at mouse position
style : '', // additional style for main div
'class' : '', // additional class name for main div
overlayStyle: '',
onShow : null, // event on show
onHide : null, // event on hide
openAbove : false, // show above control
tmp : {}
};
if (arguments.length == 1) {
if (typeof html == 'object') {
options = html;
} else {
options = { html: html };
}
}
if (arguments.length == 2) options.html = html;
if (!$.isPlainObject(options)) options = {};
options = $.extend({}, defaults, options);
if (options.name) name = '-' + options.name;
// hide
var tmp_hide;
if (this.length == 0 || options.html === '' || options.html == null) {
if ($('#w2ui-overlay'+ name).length > 0) {
tmp_hide = $('#w2ui-overlay'+ name)[0].hide;
if (typeof tmp_hide === 'function') tmp_hide();
} else {
$('#w2ui-overlay'+ name).remove();
}
return $(this);
}
// hide previous if any
if ($('#w2ui-overlay'+ name).length > 0) {
tmp_hide = $('#w2ui-overlay'+ name)[0].hide;
$(document).off('click', tmp_hide);
if (typeof tmp_hide === 'function') tmp_hide();
}
if (obj.length > 0 && (obj[0].tagName == null || obj[0].tagName.toUpperCase() == 'BODY')) options.contextMenu = true;
if (options.contextMenu && options.originalEvent == null) {
console.log('ERROR: for context menu you need to pass options.originalEvent.');
}
// append
$('body').append(
'<div id="w2ui-overlay'+ name +'" style="display: none; left: 0px; top: 0px; '+ options.overlayStyle +'"'+
' class="w2ui-reset w2ui-overlay '+ ($(this).parents('.w2ui-popup, .w2ui-overlay-popup').length > 0 ? 'w2ui-overlay-popup' : '') +'">'+
' <style></style>'+
' <div style="min-width: 100%; '+ options.style +'" class="'+ options['class'] +'"></div>'+
'</div>'
);
// init
var div1 = $('#w2ui-overlay'+ name);
var div2 = div1.find(' > div');
div2.html(options.html);
// pick bg color of first div
var bc = div2.css('background-color');
if (bc != null && bc !== 'rgba(0, 0, 0, 0)' && bc !== 'transparent') div1.css({ 'background-color': bc, 'border-color': bc });
var offset = $(obj).offset() || {};
div1.data('element', obj.length > 0 ? obj[0] : null)
.data('options', options)
.data('position', offset.left + 'x' + offset.top)
.fadeIn('fast')
.on('click', function (event) {
// if there is label for input, it will produce 2 click events
if (event.target.tagName.toUpperCase() == 'LABEL') event.stopPropagation();
})
.on('mousedown', function (event) {
$('#w2ui-overlay'+ name).data('keepOpen', true);
if (['INPUT', 'TEXTAREA', 'SELECT'].indexOf(event.target.tagName.toUpperCase()) == -1 && !options.selectable) {
event.preventDefault();
}
});
div1[0].hide = hide;
div1[0].resize = resize;
// need time to display
setTimeout(function () {
resize();
$(document).off('click', hide).on('click', hide);
if (typeof options.onShow === 'function') options.onShow();
}, 10);
monitor();
return $(this);
// monitor position
function monitor() {
var tmp = $('#w2ui-overlay'+ name);
if (tmp.data('element') !== obj[0]) return; // it if it different overlay
if (tmp.length === 0) return;
var offset = $(obj).offset() || {};
var pos = offset.left + 'x' + offset.top;
if (tmp.data('position') !== pos) {
hide();
} else {
setTimeout(monitor, 250);
}
}
// click anywhere else hides the drop down
function hide(event) {
if (event && event.button != 0) return; // only for left click button
var div1 = $('#w2ui-overlay'+ name);
if (div1.data('keepOpen') === true) {
div1.removeData('keepOpen');
return;
}
var result;
if (typeof options.onHide === 'function') result = options.onHide();
if (result === false) return;
div1.remove();
$(document).off('click', hide);
clearInterval(div1.data('timer'));
}
function resize () {
var div1 = $('#w2ui-overlay'+ name);
var div2 = div1.find(' > div');
// if goes over the screen, limit height and width
if (div1.length > 0) {
div2.height('auto').width('auto');
// width/height
var overflowX = false;
var overflowY = false;
var h = div2.height();
var w = div2.width();
if (options.width && options.width < w) w = options.width;
if (w < 30) w = 30;
// if content of specific height
if (options.tmp.contentHeight) {
h = parseInt(options.tmp.contentHeight);
div2.height(h);
setTimeout(function () {
var $div = div2.find('div.menu > table');
if (h > $div.height()) {
div2.find('div.menu').css('overflow-y', 'hidden');
}
}, 1);
setTimeout(function () {
var $div = div2.find('div.menu');
if ($div.css('overflow-y') != 'auto') {
$div.css('overflow-y', 'auto');
}
}, 10);
}
if (options.tmp.contentWidth) {
w = parseInt(options.tmp.contentWidth);
div2.width(w);
setTimeout(function () {
if (w > div2.find('div.menu > table').width()) {
div2.find('div.menu').css('overflow-x', 'hidden');
}
}, 1);
setTimeout(function () { div2.find('div.menu').css('overflow-x', 'auto'); }, 10);
}
// adjust position
var tmp = (w - 17) / 2;
var boxLeft = options.left;
var boxWidth = options.width;
var tipLeft = options.tipLeft;
// alignment
switch (options.align) {
case 'both':
boxLeft = 17 + parseInt(options.left);
if (options.width === 0) options.width = w2utils.getSize($(obj), 'width');
if (options.maxWidth && options.width > options.maxWidth) options.width = options.maxWidth;
break;
case 'left':
boxLeft = 17 + parseInt(options.left);
break;
case 'right':
boxLeft = w2utils.getSize($(obj), 'width') - w + 14 + parseInt(options.left);
tipLeft = w - 40;
break;
}
if (w === 30 && !boxWidth) boxWidth = 30; else boxWidth = (options.width ? options.width : 'auto');
if (tmp < 25) {
boxLeft = 25 - tmp;
tipLeft = Math.floor(tmp);
}
// Y coord
var X, Y, offsetTop;
if (options.contextMenu) { // context menu
X = options.originalEvent.pageX + 8;
Y = options.originalEvent.pageY - 0;
offsetTop = options.originalEvent.pageY;
} else {
var offset = obj.offset() || {};
X = ((offset.left > 25 ? offset.left : 25) + boxLeft);
Y = (offset.top + w2utils.getSize(obj, 'height') + options.top + 7);
offsetTop = offset.top;
}
div1.css({
left : X + 'px',
top : Y + 'px',
'min-width' : boxWidth,
'min-height': (options.height ? options.height : 'auto')
});
// $(window).height() - has a problem in FF20
var offset = div2.offset() || {};
var maxHeight = window.innerHeight + $(document).scrollTop() - offset.top - 7;
var maxWidth = window.innerWidth + $(document).scrollLeft() - offset.left - 7;
if (options.contextMenu) { // context menu
maxHeight = window.innerHeight - options.originalEvent.pageY - 15;
maxWidth = window.innerWidth - options.originalEvent.pageX;
}
if ((maxHeight > -50 && maxHeight < 210) || options.openAbove === true) {
var tipOffset;
// show on top
if (options.contextMenu) { // context menu
maxHeight = options.originalEvent.pageY - 7;
tipOffset = 5;
} else {
maxHeight = offset.top - $(document).scrollTop() - 7;
tipOffset = 24;
}
if (options.maxHeight && maxHeight > options.maxHeight) maxHeight = options.maxHeight;
if (h > maxHeight) {
overflowY = true;
div2.height(maxHeight).width(w).css({ 'overflow-y': 'auto' });
h = maxHeight;
}
div1.addClass('bottom-arrow');
div1.css('top', (offsetTop - h - tipOffset + options.top) + 'px');
div1.find('>style').html(
'#w2ui-overlay'+ name +':before { margin-left: '+ parseInt(tipLeft) +'px; }'+
'#w2ui-overlay'+ name +':after { margin-left: '+ parseInt(tipLeft) +'px; }'
);
} else {
// show under
if (options.maxHeight && maxHeight > options.maxHeight) maxHeight = options.maxHeight;
if (h > maxHeight) {
overflowY = true;
div2.height(maxHeight).width(w).css({ 'overflow-y': 'auto' });
}
div1.addClass('top-arrow');
div1.find('>style').html(
'#w2ui-overlay'+ name +':before { margin-left: '+ parseInt(tipLeft) +'px; }'+
'#w2ui-overlay'+ name +':after { margin-left: '+ parseInt(tipLeft) +'px; }'
);
}
// check width
w = div2.width();
maxWidth = window.innerWidth + $(document).scrollLeft() - offset.left - 7;
if (options.maxWidth && maxWidth > options.maxWidth) maxWidth = options.maxWidth;
if (w > maxWidth && options.align !== 'both') {
options.align = 'right';
setTimeout(function () { resize(); }, 1);
}
// don't show tip
if (options.contextMenu || options.noTip) { // context menu
div1.find('>style').html(
'#w2ui-overlay'+ name +':before { display: none; }'+
'#w2ui-overlay'+ name +':after { display: none; }'
);
}
// check scroll bar (needed to avoid horizontal scrollbar)
if (overflowY && options.align != 'both') div2.width(w + w2utils.scrollBarSize() + 2);
}
}
};
$.fn.w2menu = function (menu, options) {
/*
ITEM STRUCTURE
item : {
id : null,
text : '',
style : '',
img : '',
icon : '',
count : '',
hidden : false,
checked : null,
disabled : false
...
}
*/
var defaults = {
type : 'normal', // can be normal, radio, check
index : null, // current selected
items : [],
render : null,
msgNoItems : 'No items',
onSelect : null,
tmp : {}
};
var obj = this;
var name = '';
if (menu === 'refresh') {
// if not show - call blur
if ($('#w2ui-overlay'+ name).length > 0) {
options = $.extend($.fn.w2menuOptions, options);
var scrTop = $('#w2ui-overlay'+ name +' div.menu').scrollTop();
$('#w2ui-overlay'+ name +' div.menu').html(getMenuHTML());
$('#w2ui-overlay'+ name +' div.menu').scrollTop(scrTop);
setTimeout(function () { mresize(); }, 1);
} else {
$(this).w2menu(options);
}
} else if (menu === 'refresh-index') {
var $menu = $('#w2ui-overlay'+ name +' div.menu');
var cur = $menu.find('tr[index='+ options.index +']');
var scrTop = $menu.scrollTop();
$menu.find('tr.w2ui-selected').removeClass('w2ui-selected'); // clear all
cur.addClass('w2ui-selected'); // select current
// scroll into view
if (cur.length > 0) {
var top = cur[0].offsetTop - 5; // 5 is margin top
var height = $menu.height();
$menu.scrollTop(scrTop);
if (top < scrTop || top + cur.height() > scrTop + height) {
$menu.animate({ 'scrollTop': top - (height - cur.height() * 2) / 2 }, 200, 'linear');
}
}
return;
} else {
if (arguments.length === 1) options = menu; else options.items = menu;
if (typeof options !== 'object') options = {};
options = $.extend({}, defaults, options);
$.fn.w2menuOptions = options;
if (options.name) name = '-' + options.name;
if (typeof options.select === 'function' && typeof options.onSelect !== 'function') options.onSelect = options.select;
if (typeof options.onRender === 'function' && typeof options.render !== 'function') options.render = options.onRender;
// since only one overlay can exist at a time
$.fn.w2menuClick = function (event, index) {
if (['radio', 'check'].indexOf(options.type) != -1) {
// move checkbox
$(event.target).parents('tr').find('.w2ui-icon')
.removeClass('w2ui-icon-empty')
.addClass('w2ui-icon-check');
}
if (typeof options.onSelect === 'function') {
// need time so that menu first hides
setTimeout(function () {
options.onSelect({
index : index,
item : options.items[index],
originalEvent: event
});
}, 10);
}
// do not uncomment (or enum search type is not working in grid)
// setTimeout(function () { $(document).click(); }, 50);
// -- hide
var div = $('#w2ui-overlay'+ name);
if (typeof div[0].hide === 'function') {
div.removeData('keepOpen');
div[0].hide();
}
};
$.fn.w2menuDown = function (event, index) {
var $el = $(event.target).parents('tr');
var tmp = $el.find('.w2ui-icon');
if (tmp.hasClass('w2ui-icon-empty')) {
if (options.type == 'radio') {
tmp.parents('table').find('.w2ui-icon')
.removeClass('w2ui-icon-check')
.addClass('w2ui-icon-empty');
}
tmp.removeClass('w2ui-icon-empty').addClass('w2ui-icon-check');
} else if (tmp.hasClass('w2ui-icon-check') && (options.type == 'check')) {
tmp.removeClass('w2ui-icon-check').addClass('w2ui-icon-empty');
}
$el.parent().find('tr').removeClass('w2ui-selected');
$el.addClass('w2ui-selected');
$.fn.w2menuTmp = $el;
};
$.fn.w2menuOut = function (event, index) {
var $tmp = $($.fn.w2menuTmp);
if ($tmp.length > 0) {
$tmp.removeClass('w2ui-selected');
$tmp.find('.w2ui-icon').removeClass('w2ui-icon-check');
delete $.fn.w2menuTmp;
}
};
var html = '';
if (options.search) {
html +=
'<div style="position: absolute; top: 0px; height: 40px; left: 0px; right: 0px; border-bottom: 1px solid silver; background-color: #ECECEC; padding: 8px 5px;">'+
' <div class="w2ui-icon icon-search" style="position: absolute; margin-top: 4px; margin-left: 6px; width: 11px; background-position: left !important;"></div>'+
' <input id="menu-search" type="text" style="width: 100%; outline: none; padding-left: 20px;" onclick="event.stopPropagation();"/>'+
'</div>';
options.style += ';background-color: #ECECEC';
options.index = 0;
for (var i = 0; i < options.items.length; i++) options.items[i].hidden = false;
}
html += '<div class="menu" style="position: absolute; top: '+ (options.search ? 40 : 0) + 'px; bottom: 0px; width: 100%; overflow: auto;">' +
getMenuHTML() +
'</div>';
var ret = $(this).w2overlay(html, options);
setTimeout(function () {
$('#w2ui-overlay'+ name +' #menu-search')
.on('keyup', change)
.on('keydown', function (event) {
// cancel tab key
if (event.keyCode === 9) { event.stopPropagation(); event.preventDefault(); }
});
if (options.search) {
if (['text', 'password'].indexOf($(obj)[0].type) != -1 || $(obj)[0].tagName.toUpperCase() == 'TEXTAREA') return;
$('#w2ui-overlay'+ name +' #menu-search').focus();
}
}, 200);
mresize();
return ret;
}
function mresize() {
setTimeout(function () {
// show selected
$('#w2ui-overlay'+ name +' tr.w2ui-selected').removeClass('w2ui-selected');
var cur = $('#w2ui-overlay'+ name +' tr[index='+ options.index +']');
var scrTop = $('#w2ui-overlay'+ name +' div.menu').scrollTop();
cur.addClass('w2ui-selected');
if (options.tmp) options.tmp.contentHeight = $('#w2ui-overlay'+ name +' table').height() + (options.search ? 50 : 10);
if (options.tmp) options.tmp.contentWidth = $('#w2ui-overlay'+ name +' table').width();
if ($('#w2ui-overlay'+ name).length > 0) $('#w2ui-overlay'+ name)[0].resize();
// scroll into view
if (cur.length > 0) {
var top = cur[0].offsetTop - 5; // 5 is margin top
var el = $('#w2ui-overlay'+ name +' div.menu');
var height = el.height();
$('#w2ui-overlay'+ name +' div.menu').scrollTop(scrTop);
if (top < scrTop || top + cur.height() > scrTop + height) {
$('#w2ui-overlay'+ name +' div.menu').animate({ 'scrollTop': top - (height - cur.height() * 2) / 2 }, 200, 'linear');
}
}
}, 1);
}
function change(event) {
var search = this.value;
var key = event.keyCode;
var cancel = false;
switch (key) {
case 13: // enter
$('#w2ui-overlay'+ name).remove();
$.fn.w2menuClick(event, options.index);
break;
case 9: // tab
case 27: // escape
$('#w2ui-overlay'+ name).remove();
$.fn.w2menuClick(event, -1);
break;
case 38: // up
options.index = w2utils.isInt(options.index) ? parseInt(options.index) : 0;
options.index--;
while (options.index > 0 && options.items[options.index].hidden) options.index--;
if (options.index === 0 && options.items[options.index].hidden) {
while (options.items[options.index] && options.items[options.index].hidden) options.index++;
}
if (options.index < 0) options.index = 0;
cancel = true;
break;
case 40: // down
options.index = w2utils.isInt(options.index) ? parseInt(options.index) : 0;
options.index++;
while (options.index < options.items.length-1 && options.items[options.index].hidden) options.index++;
if (options.index === options.items.length-1 && options.items[options.index].hidden) {
while (options.items[options.index] && options.items[options.index].hidden) options.index--;
}
if (options.index >= options.items.length) options.index = options.items.length - 1;
cancel = true;
break;
}
// filter
if (!cancel) {
var shown = 0;
for (var i = 0; i < options.items.length; i++) {
var item = options.items[i];
var prefix = '';
var suffix = '';
if (['is', 'begins with'].indexOf(options.match) !== -1) prefix = '^';
if (['is', 'ends with'].indexOf(options.match) !== -1) suffix = '$';
try {
var re = new RegExp(prefix + search + suffix, 'i');
if (re.test(item.text) || item.text === '...') item.hidden = false; else item.hidden = true;
} catch (e) {}
// do not show selected items
if (obj.type === 'enum' && $.inArray(item.id, ids) !== -1) item.hidden = true;
if (item.hidden !== true) shown++;
}
options.index = 0;
while (options.index < options.items.length-1 && options.items[options.index].hidden) options.index++;
if (shown <= 0) options.index = -1;
}
$(obj).w2menu('refresh', options);
mresize();
}
function getMenuHTML () {
if (options.spinner) {
return '<table class="w2ui-drop-menu"><tbody><tr><td style="padding: 5px 10px 10px 10px; text-align: center">'+
' <div class="w2ui-spinner" style="width: 18px; height: 18px; position: relative; top: 5px;"></div> '+
' <div style="display: inline-block; padding: 3px; color: #999;">'+ w2utils.lang('Loading...') +'</div>'+
'</td></tr></tbody></table>';
}
var count = 0;
var menu_html = '<table cellspacing="0" cellpadding="0" class="w2ui-drop-menu"><tbody>';
var img = null, icon = null;
for (var f = 0; f < options.items.length; f++) {
var mitem = options.items[f];
if (typeof mitem === 'string') {
mitem = { id: mitem, text: mitem };
} else {
if (mitem.text != null && mitem.id == null) mitem.id = mitem.text;
if (mitem.text == null && mitem.id != null) mitem.text = mitem.id;
if (mitem.caption != null) mitem.text = mitem.caption;
img = mitem.img;
icon = mitem.icon;
if (img == null) img = null;
if (icon == null) icon = null;
}
if (['radio', 'check'].indexOf(options.type) != -1) {
if (mitem.checked === true) icon = 'w2ui-icon-check'; else icon = 'w2ui-icon-empty';
}
if (mitem.hidden !== true) {
var imgd = '';
var txt = mitem.text;
if (typeof options.render === 'function') txt = options.render(mitem, options);
if (img) imgd = '<td class="menu-icon"><div class="w2ui-tb-image w2ui-icon '+ img +'"></div></td>';
if (icon) imgd = '<td class="menu-icon" align="center"><span class="w2ui-icon '+ icon +'"></span></td>';
// render only if non-empty
if (txt != null && txt !== '' && !(/^-+$/.test(txt))) {
var bg = (count % 2 === 0 ? 'w2ui-item-even' : 'w2ui-item-odd');
if (options.altRows !== true) bg = '';
var colspan = 1;
if (imgd == '') colspan++;
if (mitem.count == null && mitem.hotkey == null) colspan++;
if (mitem.tooltip == null && mitem.hint != null) mitem.tooltip = mitem.hint; // for backward compatibility
menu_html +=
'<tr index="'+ f + '" style="'+ (mitem.style ? mitem.style : '') +'" '+ (mitem.tooltip ? 'title="'+ mitem.tooltip +'"' : '') +
' class="'+ bg +' '+ (options.index === f ? 'w2ui-selected' : '') + ' ' + (mitem.disabled === true ? 'w2ui-disabled' : '') +'"'+
' onmousedown="if ('+ (mitem.disabled === true ? 'true' : 'false') + ') return;'+
' $.fn.w2menuDown(event, \''+ f +'\');"'+
' onmouseout="if ('+ (mitem.disabled === true ? 'true' : 'false') + ') return;'+
' $.fn.w2menuOut(event, \''+ f +'\');"'+
' onclick="event.stopPropagation(); '+
' if ('+ (mitem.disabled === true ? 'true' : 'false') + ') return;'+
' $.fn.w2menuClick(event, \''+ f +'\');">'+
imgd +
' <td class="menu-text" colspan="'+ colspan +'">'+ txt +'</td>'+
' <td class="menu-count">'+
(mitem.count != null ? '<span>' + mitem.count + '</span>' : '') +
(mitem.hotkey != null ? '<span class="hotkey">' + mitem.hotkey + '</span>' : '') +
'</td>' +
'</tr>';
count++;
} else {
// horizontal line
menu_html += '<tr><td colspan="3" style="padding: 6px; pointer-events: none"><div style="border-top: 1px solid silver;"></div></td></tr>';
}
}
options.items[f] = mitem;
}
if (count === 0) {
menu_html += '<tr><td style="padding: 13px; color: #999; text-align: center">'+ options.msgNoItems +'</div></td></tr>';
}
menu_html += "</tbody></table>";
return menu_html;
}
};
$.fn.w2color = function (color, callBack) {
var obj = this;
var el = $(this)[0];
var index = [-1, -1];
if ($.fn.w2colorPalette == null) {
$.fn.w2colorPalette = [
['000000', '888888', 'BBBBBB', 'DDDDDD', 'EEEEEE', 'F7F7F7', 'FFFFFF', ''],
['FF011B', 'FF9838', 'FFFD59', '01FD55', '00FFFE', '006CE7', '9B24F4', 'FF21F5'],
['FFEAEA', 'FCEFE1', 'FCF5E1', 'EBF7E7', 'E9F3F5', 'ECF4FC', 'EAE6F4', 'F5E7ED'],
['F4CCCC', 'FCE5CD', 'FFF2CC', 'D9EAD3', 'D0E0E3', 'CFE2F3', 'D9D1E9', 'EAD1DC'],
['EA9899', 'F9CB9C', 'FEE599', 'B6D7A8', 'A2C4C9', '9FC5E8', 'B4A7D6', 'D5A6BD'],
['E06666', 'F6B26B', 'FED966', '93C47D', '76A5AF', '6FA8DC', '8E7CC3', 'C27BA0'],
['CC0814', 'E69138', 'F1C232', '6AA84F', '45818E', '3D85C6', '674EA7', 'A54D79'],
['99050C', 'B45F17', 'BF901F', '37761D', '124F5C', '0A5394', '351C75', '741B47'],
// ['660205', '783F0B', '7F6011', '274E12', '0C343D', '063762', '20124D', '4C1030'],
['F2F2F2', 'F2F2F2', 'F2F2F2', 'F2F2F2', 'F2F2F2'] // custom colors (up to 4)
];
}
var pal = $.fn.w2colorPalette;
if (typeof color != 'string') color = '';
if (color) color = String(color).toUpperCase();
if ($('#w2ui-overlay').length == 0) {
$(el).w2overlay(getColorHTML(color), {
onHide: function () {
if (typeof callBack == 'function') callBack($(el).data('_color'));
$(el).removeData('_color');
}
});
} else { // only refresh contents
$('#w2ui-overlay .w2ui-color').parent().html(getColorHTML(color));
}
// bind events
$('#w2ui-overlay .color')
.on('mousedown', function (event) {
var color = $(event.originalEvent.target).attr('name');
index = $(event.originalEvent.target).attr('index').split(':');
$(el).data('_color', color);
})
.on('mouseup', function () {
setTimeout(function () {
if ($("#w2ui-overlay").length > 0) $('#w2ui-overlay').removeData('keepOpen')[0].hide();
}, 10);
});
$('#w2ui-overlay input')
.on('mousedown', function (event) {
$('#w2ui-overlay').data('keepOpen', true);
setTimeout(function () { $('#w2ui-overlay').data('keepOpen', true); }, 10);
event.stopPropagation();
})
.on('keyup', function (event) {
if (this.value != '' && this.value[0] != '#') this.value = '#' + this.value;
})
.on('change', function (event) {
var tmp = this.value;
if (tmp.substr(0, 1) == '#') tmp = tmp.substr(1);
if (tmp.length != 6) {
$(this).w2tag('Invalid color.');
return;
}
$.fn.w2colorPalette[pal.length - 1].unshift(tmp.toUpperCase());
$(el).w2color(color, callBack);
setTimeout(function() { $('#w2ui-overlay input')[0].focus(); }, 100);
})
.w2field('hex');
el.nav = function (direction) {
switch (direction) {
case 'up':
index[0]--;
break;
case 'down':
index[0]++;
break;
case 'right':
index[1]++;
break;
case 'left':
index[1]--;
break;
}
if (index[0] < 0) index[0] = 0;
if (index[0] > pal.length - 2) index[0] = pal.length - 2;
if (index[1] < 0) index[1] = 0;
if (index[1] > pal[0].length - 1) index[1] = pal[0].length - 1;
color = pal[index[0]][index[1]];
$(el).data('_color', color);
return color;
};
function getColorHTML(color) {
var html = '<div class="w2ui-color">'+
'<table cellspacing="5"><tbody>';
for (var i = 0; i < pal.length - 1; i++) {
html += '<tr>';
for (var j = 0; j < pal[i].length; j++) {
html += '<td>'+
' <div class="color '+ (pal[i][j] == '' ? 'no-color' : '') +'" style="background-color: #'+ pal[i][j] +';" ' +
' name="'+ pal[i][j] +'" index="'+ i + ':' + j +'">'+ (color == pal[i][j] ? '•' : ' ') +
' </div>'+
'</td>';
if (color == pal[i][j]) index = [i, j];
}
html += '</tr>';
if (i < 2) html += '<tr><td style="height: 8px" colspan="8"></td></tr>';
}
var tmp = pal[pal.length - 1];
html += '<tr><td style="height: 8px" colspan="8"></td></tr>'+
'<tr>'+
' <td colspan="4" style="text-align: left"><input placeholder="#FFF000" style="margin-left: 1px; width: 74px" maxlength="7"/></td>'+
' <td><div class="color" style="background-color: #'+ tmp[0] +';" name="'+ tmp[0] +'" index="8:0">'+ (color == tmp[0] ? '•' : ' ') +'</div></td>'+
' <td><div class="color" style="background-color: #'+ tmp[1] +';" name="'+ tmp[1] +'" index="8:0">'+ (color == tmp[1] ? '•' : ' ') +'</div></td>'+
' <td><div class="color" style="background-color: #'+ tmp[2] +';" name="'+ tmp[2] +'" index="8:0">'+ (color == tmp[2] ? '•' : ' ') +'</div></td>'+
' <td><div class="color" style="background-color: #'+ tmp[3] +';" name="'+ tmp[3] +'" index="8:0">'+ (color == tmp[3] ? '•' : ' ') +'</div></td>'+
'</tr>'+
'<tr><td style="height: 4px" colspan="8"></td></tr>';
html += '</tbody></table></div>';
return html;
}
};
})(jQuery);
/************************************************************************
* Library: Web 2.0 UI for jQuery (using prototypical inheritance)
* - Following objects defined
* - w2field - various field controls
* - $().w2field - jQuery wrapper
* - Dependencies: jQuery, w2utils
*
* == NICE TO HAVE ==
* - upload (regular files)
* - BUG with prefix/postfix and arrows (test in different contexts)
* - prefix and suffix are slow (100ms or so)
* - multiple date selection
* - month selection, year selections
* - arrows no longer work (for int)
* - form to support custom types
* - rewrite suffix and prefix positioning with translateY()
* - MultiSelect - Allow Copy/Paste for single and multi values
* - add routeData to list/enum
* - for type: list -> read value from attr('value')
* - ENUM, LIST: should be able to define which is ID field and which is TEXT
* - ENUM, LIST: same data structure as grid
* - ENUM, LIST: should have same as grid (limit, offset, search, sort)
* - ENUM, LIST: should support wild cars
*
* == 1.5 changes
* - added support decimalSymbol (added options.decimalSymbol)
* - $('#id').w2field() - will return w2field object (same as $('#id').data('w2field'))
* - added resize() function and automatic watching for size
* - bug: if input is hidden and then enum is applied, then when it becomes visible, it will be 110px
* - deprecate placeholder, read it from input
* - added get(), set(), setIndex() for fields
* - added options.compare function for list, combo, enum
* - added options.filter for list, combo, enum
* - added selection for the current date in the calendar
* - added for enum options.onScroll
* - modified clearCache()
* - changed onSearch - happens when search input changes
* - added options.method - for combo/list/enum if url is defined
* - options.items can be a function now
* - options.maxDropWidth
*
************************************************************************/
(function ($) {
var w2field = function (options) {
// public properties
this.el = null;
this.helpers = {}; // object or helper elements
this.type = options.type || 'text';
this.options = $.extend(true, {}, options);
this.onSearch = options.onSearch || null;
this.onRequest = options.onRequest || null;
this.onLoad = options.onLoad || null;
this.onError = options.onError || null;
this.onClick = options.onClick || null;
this.onAdd = options.onAdd || null;
this.onNew = options.onNew || null;
this.onRemove = options.onRemove || null;
this.onMouseOver = options.onMouseOver || null;
this.onMouseOut = options.onMouseOut || null;
this.onIconClick = options.onIconClick || null;
this.onScroll = options.onScroll || null;
this.tmp = {}; // temp object
// clean up some options
delete this.options.type;
delete this.options.onSearch;
delete this.options.onRequest;
delete this.options.onLoad;
delete this.options.onError;
delete this.options.onClick;
delete this.options.onMouseOver;
delete this.options.onMouseOut;
delete this.options.onIconClick;
delete this.options.onScroll;
// extend with defaults
$.extend(true, this, w2obj.field);
};
// ====================================================
// -- Registers as a jQuery plugin
$.fn.w2field = function (method, options) {
// call direct
if (this.length == 0) {
var pr = w2field.prototype;
if (pr[method]) {
return pr[method].apply(pr, Array.prototype.slice.call(arguments, 1));
}
} else {
// if without arguments - return the object
if (arguments.length == 0) {
var obj = $(this).data('w2field');
return obj;
}
if (typeof method == 'string' && typeof options == 'object') {
method = $.extend(true, {}, options, { type: method });
}
if (typeof method == 'string' && options == null) {
method = { type: method };
}
method.type = String(method.type).toLowerCase();
return this.each(function (index, el) {
var obj = $(el).data('w2field');
// if object is not defined, define it
if (obj == null) {
var obj = new w2field(method);
$.extend(obj, { handlers: [] });
if (el) obj.el = $(el)[0];
obj.init();
$(el).data('w2field', obj);
return obj;
} else { // fully re-init
obj.clear();
if (method.type == 'clear') return;
var obj = new w2field(method);
$.extend(obj, { handlers: [] });
if (el) obj.el = $(el)[0];
obj.init();
$(el).data('w2field', obj);
return obj;
}
return null;
});
}
};
// ====================================================
// -- Implementation of core functionality
/* To add custom types
$().w2field('addType', 'myType', function (options) {
$(this.el).on('keypress', function (event) {
if (event.metaKey || event.ctrlKey || event.altKey
|| (event.charCode != event.keyCode && event.keyCode > 0)) return;
var ch = String.fromCharCode(event.charCode);
if (ch != 'a' && ch != 'b' && ch != 'c') {
if (event.stopPropagation) event.stopPropagation(); else event.cancelBubble = true;
return false;
}
});
$(this.el).on('blur', function (event) { // keyCode & charCode differ in FireFox
var ch = this.value;
if (ch != 'a' && ch != 'b' && ch != 'c') {
$(this).w2tag(w2utils.lang("Not a single character from the set of 'abc'"));
}
});
});
*/
w2field.prototype = {
custom: {}, // map of custom types
addType: function (type, handler) {
type = String(type).toLowerCase();
this.custom[type] = handler;
return true;
},
removeType: function (type) {
type = String(type).toLowerCase();
if (!this.custom[type]) return false;
delete this.custom[type];
return true;
},
init: function () {
var obj = this;
var options = this.options;
var defaults;
// Custom Types
if (typeof this.custom[this.type] == 'function') {
this.custom[this.type].call(this, options);
return;
}
// only for INPUT or TEXTAREA
if (['INPUT', 'TEXTAREA'].indexOf(this.el.tagName.toUpperCase()) == -1) {
console.log('ERROR: w2field could only be applied to INPUT or TEXTAREA.', this.el);
return;
}
switch (this.type) {
case 'text':
case 'int':
case 'float':
case 'money':
case 'currency':
case 'percent':
case 'alphanumeric':
case 'bin':
case 'hex':
defaults = {
min : null,
max : null,
step : 1,
autoFormat : true,
currencyPrefix : w2utils.settings.currencyPrefix,
currencySuffix : w2utils.settings.currencySuffix,
currencyPrecision : w2utils.settings.currencyPrecision,
decimalSymbol : w2utils.settings.decimalSymbol,
groupSymbol : w2utils.settings.groupSymbol,
arrows : false,
keyboard : true,
precision : null,
silent : true,
prefix : '',
suffix : ''
};
this.options = $.extend(true, {}, defaults, options);
options = this.options; // since object is re-created, need to re-assign
options.numberRE = new RegExp('['+ options.groupSymbol + ']', 'g');
options.moneyRE = new RegExp('['+ options.currencyPrefix + options.currencySuffix + options.groupSymbol +']', 'g');
options.percentRE = new RegExp('['+ options.groupSymbol + '%]', 'g');
// no keyboard support needed
if (['text', 'alphanumeric', 'hex', 'bin'].indexOf(this.type) != -1) {
options.arrows = false;
options.keyboard = false;
}
this.addPrefix(); // only will add if needed
this.addSuffix();
break;
case 'color':
defaults = {
prefix : '#',
suffix : '<div style="width: '+ (parseInt($(this.el).css('font-size')) || 12) +'px"> </div>',
arrows : false,
keyboard : false
};
$.extend(options, defaults);
this.addPrefix(); // only will add if needed
this.addSuffix(); // only will add if needed
// additional checks
$(this.el).attr('maxlength', 6);
if ($(this.el).val() != '') setTimeout(function () { obj.change(); }, 1);
break;
case 'date':
defaults = {
format : w2utils.settings.date_format, // date format
keyboard : true,
silent : true,
start : '', // string or jquery object
end : '', // string or jquery object
blocked : {}, // { '4/11/2011': 'yes' }
colored : {} // { '4/11/2011': 'red:white' }
};
this.options = $.extend(true, {}, defaults, options);
options = this.options; // since object is re-created, need to re-assign
if ($(this.el).attr('placeholder') == null) $(this.el).attr('placeholder', options.format);
break;
case 'time':
defaults = {
format : w2utils.settings.time_format,
keyboard : true,
silent : true,
start : '',
end : ''
};
this.options = $.extend(true, {}, defaults, options);
options = this.options; // since object is re-created, need to re-assign
if ($(this.el).attr('placeholder') == null) $(this.el).attr('placeholder', options.format);
break;
case 'datetime':
defaults = {
format : w2utils.settings.date_format + '|hh24:mm',
keyboard : true,
silent : true,
start : '', // string or jquery object or Date object
end : '', // string or jquery object or Date object
blocked : [], // [ '4/11/2011', '4/12/2011' ] or [ new Date(2011, 4, 11), new Date(2011, 4, 12) ]
colored : {}, // { '12/17/2014': 'blue:green', '12/18/2014': 'gray:white' }; // key has be be formatted with w2utils.settings.date_format
placeholder : null, // optional. will fall back to this.format if not specified. Only used if this.el has no placeholder attribute.
format_mjs : 'M/D/YYYY HH:mm', // date format for moment.js, should be equal to "this.format" translated to ISO 8601, see http://momentjs.com/docs/#/parsing/string-format
btn_now : true // show/hide the use-current-date-and-time button
};
this.options = $.extend(true, {}, defaults, options);
options = this.options; // since object is re-created, need to re-assign
if ($(this.el).attr('placeholder') == null) $(this.el).attr('placeholder', options.placeholder || options.format);
break;
case 'list':
case 'combo':
defaults = {
items : [],
selected : {},
url : null, // url to pull data from
method : null, // default comes from w2utils.settings.dataType
interval : 350, // number of ms to wait before sending server call on search
postData : {},
minLength : 1,
cacheMax : 250,
maxDropHeight : 350, // max height for drop down menu
maxDropWidth : null, // if null then auto set
match : 'begins', // ['contains', 'is', 'begins', 'ends']
silent : true,
icon : null,
iconStyle : '',
onSearch : null, // when search needs to be performed
onRequest : null, // when request is submitted
onLoad : null, // when data is received
onError : null, // when data fails to load due to server error or other failure modes
onIconClick : null,
renderDrop : null, // render function for drop down item
compare : null, // compare function for filtering
filter : true, // weather to filter at all
prefix : '',
suffix : '',
openOnFocus : false, // if to show overlay onclick or when typing
markSearch : false
};
options.items = this.normMenu(options.items); // need to be first
if (this.type == 'list') {
// defaults.search = (options.items && options.items.length >= 10 ? true : false);
defaults.openOnFocus = true;
defaults.suffix = '<div class="arrow-down" style="margin-top: '+ ((parseInt($(this.el).height()) - 6) / 2) +'px;"></div>';
$(this.el).addClass('w2ui-select');
// if simple value - look it up
if (!$.isPlainObject(options.selected) && options.items) {
for (var i = 0; i< options.items.length; i++) {
var item = options.items[i];
if (item && item.id == options.selected) {
options.selected = $.extend(true, {}, item);
break;
}
}
}
this.watchSize();
}
options = $.extend({}, defaults, options, {
align : 'both', // same width as control
altRows : true // alternate row color
});
this.options = options;
if (!$.isPlainObject(options.selected)) options.selected = {};
$(this.el).data('selected', options.selected);
if (options.url) this.request(0);
if (this.type == 'list') this.addFocus();
this.addPrefix();
this.addSuffix();
setTimeout(function () { obj.refresh(); }, 10); // need this for icon refresh
$(this.el).attr('autocomplete', 'off');
if (options.selected.text != null) $(this.el).val(options.selected.text);
break;
case 'enum':
defaults = {
items : [],
selected : [],
max : 0, // max number of selected items, 0 - unlim
url : null, // not implemented
interval : 350, // number of ms to wait before sending server call on search
method : null, // default comes from w2utils.settings.dataType
postData : {},
minLength : 1,
cacheMax : 250,
maxWidth : 250, // max width for a single item
maxHeight : 350, // max height for input control to grow
maxDropHeight : 350, // max height for drop down menu
maxDropWidth : null, // if null then auto set
match : 'contains', // ['contains', 'is', 'begins', 'ends']
silent : true,
openOnFocus : false, // if to show overlay onclick or when typing
markSearch : true,
renderDrop : null, // render function for drop down item
renderItem : null, // render selected item
compare : null, // compare function for filtering
filter : true, // alias for compare
style : '', // style for container div
onSearch : null, // when search needs to be performed
onRequest : null, // when request is submitted
onLoad : null, // when data is received
onError : null, // when data fails to load due to server error or other failure modes
onClick : null, // when an item is clicked
onAdd : null, // when an item is added
onNew : null, // when new item should be added
onRemove : null, // when an item is removed
onMouseOver : null, // when an item is mouse over
onMouseOut : null, // when an item is mouse out
onScroll : null // when div with selected items is scrolled
};
options = $.extend({}, defaults, options, {
align : 'both', // same width as control
suffix : '',
altRows : true // alternate row color
});
options.items = this.normMenu(options.items);
options.selected = this.normMenu(options.selected);
this.options = options;
if (!$.isArray(options.selected)) options.selected = [];
$(this.el).data('selected', options.selected);
if (options.url) this.request(0);
this.addSuffix();
this.addMulti();
this.watchSize();
break;
case 'file':
defaults = {
selected : [],
max : 0,
maxSize : 0, // max size of all files, 0 - unlim
maxFileSize : 0, // max size of a single file, 0 -unlim
maxWidth : 250, // max width for a single item
maxHeight : 350, // max height for input control to grow
maxDropHeight : 350, // max height for drop down menu
maxDropWidth : null, // if null then auto set
silent : true,
renderItem : null, // render selected item
style : '', // style for container div
onClick : null, // when an item is clicked
onAdd : null, // when an item is added
onRemove : null, // when an item is removed
onMouseOver : null, // when an item is mouse over
onMouseOut : null // when an item is mouse out
};
options = $.extend({}, defaults, options, {
align : 'both', // same width as control
altRows : true // alternate row color
});
this.options = options;
if (!$.isArray(options.selected)) options.selected = [];
$(this.el).data('selected', options.selected);
if ($(this.el).attr('placeholder') == null) {
$(this.el).attr('placeholder', w2utils.lang('Attach files by dragging and dropping or Click to Select'));
}
this.addMulti();
this.watchSize();
break;
}
// attach events
this.tmp = {
onChange : function (event) { obj.change.call(obj, event); },
onClick : function (event) { obj.click.call(obj, event); },
onFocus : function (event) { obj.focus.call(obj, event); },
onBlur : function (event) { obj.blur.call(obj, event); },
onKeydown : function (event) { obj.keyDown.call(obj, event); },
onKeyup : function (event) { obj.keyUp.call(obj, event); },
onKeypress : function (event) { obj.keyPress.call(obj, event); }
};
$(this.el)
.addClass('w2field')
.data('w2field', this)
.on('change', this.tmp.onChange)
.on('click', this.tmp.onClick) // ignore click because it messes overlays
.on('focus', this.tmp.onFocus)
.on('blur', this.tmp.onBlur)
.on('keydown', this.tmp.onKeydown)
.on('keyup', this.tmp.onKeyup)
.on('keypress', this.tmp.onKeypress)
.css(w2utils.cssPrefix('box-sizing', 'border-box'));
// format initial value
this.change($.Event('change'));
},
watchSize: function () {
var obj = this;
var tmp = $(obj.el).data('tmp') || {};
tmp.sizeTimer = setInterval(function () {
if ($(obj.el).parents('body').length > 0) {
obj.resize();
} else {
clearInterval(tmp.sizeTimer);
}
}, 200);
$(obj.el).data('tmp', tmp);
},
get: function () {
var ret;
if (['list', 'enum', 'file'].indexOf(this.type) != -1) {
ret = $(this.el).data('selected');
} else {
ret = $(this.el).val();
}
return ret;
},
set: function (val) {
if (['list', 'enum', 'file'].indexOf(this.type) != -1) {
$(this.el).data('selected', val).change();
this.refresh();
} else {
$(this.el).val(val);
}
},
setIndex: function (ind) {
var items = this.options.items;
if (items && items[ind]) {
$(this.el).data('selected', items[ind]).change();
this.refresh();
return true;
}
return false;
},
clear: function () {
var obj = this;
var options = this.options;
// if money then clear value
if (['money', 'currency'].indexOf(this.type) != -1) {
$(this.el).val($(this.el).val().replace(options.moneyRE, ''));
}
if (this.type == 'percent') {
$(this.el).val($(this.el).val().replace(/%/g, ''));
}
if (this.type == 'color') {
$(this.el).removeAttr('maxlength');
}
if (this.type == 'list') {
$(this.el).removeClass('w2ui-select');
}
this.type = 'clear';
var tmp = $(this.el).data('tmp');
if (!this.tmp) return;
// restore paddings
if (tmp != null) {
$(this.el).height('auto');
if (tmp && tmp['old-padding-left']) $(this.el).css('padding-left', tmp['old-padding-left']);
if (tmp && tmp['old-padding-right']) $(this.el).css('padding-right', tmp['old-padding-right']);
if (tmp && tmp['old-background-color']) $(this.el).css('background-color', tmp['old-background-color']);
if (tmp && tmp['old-border-color']) $(this.el).css('border-color', tmp['old-border-color']);
// remove resize watcher
clearInterval(tmp.sizeTimer);
}
// remove events and (data)
$(this.el)
.val(this.clean($(this.el).val()))
.removeClass('w2field')
.removeData() // removes all attached data
.off('change', this.tmp.onChange)
.off('click', this.tmp.onClick)
.off('focus', this.tmp.onFocus)
.off('blur', this.tmp.onBlur)
.off('keydown', this.tmp.onKeydown)
.off('keyup', this.tmp.onKeyup)
.off('keypress', this.tmp.onKeypress);
// remove helpers
for (var h in this.helpers) $(this.helpers[h]).remove();
this.helpers = {};
},
refresh: function () {
var obj = this;
var options = this.options;
var selected = $(this.el).data('selected');
var time = (new Date()).getTime();
// enum
if (['list'].indexOf(this.type) != -1) {
$(obj.el).parent().css('white-space', 'nowrap'); // needs this for arrow always to appear on the right side
// hide focus and show text
if (obj.helpers.prefix) obj.helpers.prefix.hide();
setTimeout(function () {
if (!obj.helpers.focus) return;
// if empty show no icon
if (!$.isEmptyObject(selected) && options.icon) {
options.prefix = '<span class="w2ui-icon '+ options.icon +'"style="cursor: pointer; font-size: 14px;' +
' display: inline-block; margin-top: -1px; color: #7F98AD;'+ options.iconStyle +'">'+
'</span>';
obj.addPrefix();
} else {
options.prefix = '';
obj.addPrefix();
}
// focus helper
var focus = obj.helpers.focus.find('input');
if ($(focus).val() == '') {
$(focus).css('text-indent', '-9999em').prev().css('opacity', 0);
$(obj.el).val(selected && selected.text != null ? selected.text : '');
} else {
$(focus).css('text-indent', 0).prev().css('opacity', 1);
$(obj.el).val('');
setTimeout(function () {
if (obj.helpers.prefix) obj.helpers.prefix.hide();
var tmp = 'position: absolute; opacity: 0; margin: 4px 0px 0px 2px; background-position: left !important;';
if (options.icon) {
$(focus).css('margin-left', '17px');
$(obj.helpers.focus).find('.icon-search').attr('style', tmp + 'width: 11px !important; opacity: 1');
} else {
$(focus).css('margin-left', '0px');
$(obj.helpers.focus).find('.icon-search').attr('style', tmp + 'width: 0px !important; opacity: 0');
}
}, 1);
}
// if readonly or disabled
if ($(obj.el).prop('readonly') || $(obj.el).prop('disabled')) {
setTimeout(function () {
$(obj.helpers.prefix).css('opacity', '0.6');
$(obj.helpers.suffix).css('opacity', '0.6');
}, 1);
} else {
setTimeout(function () {
$(obj.helpers.prefix).css('opacity', '1');
$(obj.helpers.suffix).css('opacity', '1');
}, 1);
}
}, 1);
}
if (['enum', 'file'].indexOf(this.type) != -1) {
var html = '';
for (var s in selected) {
var it = selected[s];
var ren = '';
if (typeof options.renderItem == 'function') {
ren = options.renderItem(it, s, '<div class="w2ui-list-remove" title="'+ w2utils.lang('Remove') +'" index="'+ s +'">  </div>');
} else {
ren = '<div class="w2ui-list-remove" title="'+ w2utils.lang('Remove') +'" index="'+ s +'">  </div>'+
(obj.type == 'enum' ? it.text : it.name + '<span class="file-size"> - '+ w2utils.formatSize(it.size) +'</span>');
}
html += '<li index="'+ s +'" style="max-width: '+ parseInt(options.maxWidth) + 'px; '+ (it.style ? it.style : '') +'">'+
ren +'</li>';
}
var div = obj.helpers.multi;
var ul = div.find('ul');
div.attr('style', div.attr('style') + ';' + options.style);
$(obj.el).css('z-index', '-1');
if ($(obj.el).prop('readonly') || $(obj.el).prop('disabled')) {
setTimeout(function () {
div[0].scrollTop = 0; // scroll to the top
div.addClass('w2ui-readonly')
.find('li').css('opacity', '0.9')
.parent().find('li.nomouse').hide()
.find('input').prop('readonly', true)
.parents('ul')
.find('.w2ui-list-remove').hide();
}, 1);
} else {
setTimeout(function () {
div.removeClass('w2ui-readonly')
.find('li').css('opacity', '1')
.parent().find('li.nomouse').show()
.find('input').prop('readonly', false)
.parents('ul')
.find('.w2ui-list-remove').show();
}, 1);
}
// clean
div.find('.w2ui-enum-placeholder').remove();
ul.find('li').not('li.nomouse').remove();
// add new list
if (html != '') {
ul.prepend(html);
} else if ($(obj.el).attr('placeholder') != null && div.find('input').val() == '') {
var style =
'padding-top: ' + $(this.el).css('padding-top') + ';'+
'padding-left: ' + $(this.el).css('padding-left') + '; ' +
'box-sizing: ' + $(this.el).css('box-sizing') + '; ' +
'line-height: ' + $(this.el).css('line-height') + '; ' +
'font-size: ' + $(this.el).css('font-size') + '; ' +
'font-family: ' + $(this.el).css('font-family') + '; ';
div.prepend('<div class="w2ui-enum-placeholder" style="'+ style +'">'+ $(obj.el).attr('placeholder') +'</div>');
}
// ITEMS events
div.off('scroll.w2field').on('scroll.w2field', function (event) {
var eventData = obj.trigger({ phase: 'before', type: 'scroll', target: obj.el, originalEvent: event });
if (eventData.isCancelled === true) return;
// event after
obj.trigger($.extend(eventData, { phase: 'after' }));
})
.find('li')
.data('mouse', 'out')
.on('click', function (event) {
var target = (event.target.tagName.toUpperCase() == 'LI' ? event.target : $(event.target).parents('LI'));
var item = selected[$(target).attr('index')];
if ($(target).hasClass('nomouse')) return;
event.stopPropagation();
// trigger event
var eventData = obj.trigger({ phase: 'before', type: 'click', target: obj.el, originalEvent: event.originalEvent, item: item });
if (eventData.isCancelled === true) return;
// default behavior
if ($(event.target).hasClass('w2ui-list-remove')) {
if ($(obj.el).attr('readonly') || $(obj.el).attr('disabled')) return;
// trigger event
var eventData = obj.trigger({ phase: 'before', type: 'remove', target: obj.el, originalEvent: event.originalEvent, item: item });
if (eventData.isCancelled === true) return;
// default behavior
$().w2overlay();
selected.splice($(event.target).attr('index'), 1);
$(obj.el).trigger('change');
$(event.target).parent().fadeOut('fast');
setTimeout(function () {
obj.refresh();
// event after
obj.trigger($.extend(eventData, { phase: 'after' }));
}, 300);
}
if (obj.type == 'file' && !$(event.target).hasClass('w2ui-list-remove')) {
var preview = '';
if ((/image/i).test(item.type)) { // image
preview = '<div style="padding: 3px;">'+
' <img src="'+ (item.content ? 'data:'+ item.type +';base64,'+ item.content : '') +'" style="max-width: 300px;" '+
' onload="var w = $(this).width(); var h = $(this).height(); '+
' if (w < 300 & h < 300) return; '+
' if (w >= h && w > 300) $(this).width(300);'+
' if (w < h && h > 300) $(this).height(300);"'+
' onerror="this.style.display = \'none\'"'+
' >'+
'</div>';
}
var td1 = 'style="padding: 3px; text-align: right; color: #777;"';
var td2 = 'style="padding: 3px"';
preview += '<div style="padding: 8px;">'+
' <table cellpadding="2"><tbody>'+
' <tr><td '+ td1 +'>'+ w2utils.lang('Name') +':</td><td '+ td2 +'>'+ item.name +'</td></tr>'+
' <tr><td '+ td1 +'>'+ w2utils.lang('Size') +':</td><td '+ td2 +'>'+ w2utils.formatSize(item.size) +'</td></tr>'+
' <tr><td '+ td1 +'>'+ w2utils.lang('Type') +':</td><td '+ td2 +'>' +
' <span style="width: 200px; display: block-inline; overflow: hidden; text-overflow: ellipsis; white-space: nowrap="nowrap";">'+ item.type +'</span>'+
' </td></tr>'+
' <tr><td '+ td1 +'>'+ w2utils.lang('Modified') +':</td><td '+ td2 +'>'+ w2utils.date(item.modified) +'</td></tr>'+
' </tbody></table>'+
'</div>';
$('#w2ui-overlay').remove();
$(target).w2overlay(preview);
}
// event after
obj.trigger($.extend(eventData, { phase: 'after' }));
})
.on('mouseover', function (event) {
var target = (event.target.tagName.toUpperCase() == 'LI' ? event.target : $(event.target).parents('LI'));
if ($(target).hasClass('nomouse')) return;
if ($(target).data('mouse') == 'out') {
var item = selected[$(event.target).attr('index')];
// trigger event
var eventData = obj.trigger({ phase: 'before', type: 'mouseOver', target: obj.el, originalEvent: event.originalEvent, item: item });
if (eventData.isCancelled === true) return;
// event after
obj.trigger($.extend(eventData, { phase: 'after' }));
}
$(target).data('mouse', 'over');
})
.on('mouseout', function (event) {
var target = (event.target.tagName.toUpperCase() == 'LI' ? event.target : $(event.target).parents('LI'));
if ($(target).hasClass('nomouse')) return;
$(target).data('mouse', 'leaving');
setTimeout(function () {
if ($(target).data('mouse') == 'leaving') {
$(target).data('mouse', 'out');
var item = selected[$(event.target).attr('index')];
// trigger event
var eventData = obj.trigger({ phase: 'before', type: 'mouseOut', target: obj.el, originalEvent: event.originalEvent, item: item });
if (eventData.isCancelled === true) return;
// event after
obj.trigger($.extend(eventData, { phase: 'after' }));
}
}, 0);
});
// adjust height
$(this.el).height('auto');
var cntHeight = $(div).find('> div.w2ui-multi-items').height() + w2utils.getSize(div, '+height') * 2;
if (cntHeight < 26) cntHeight = 26;
if (cntHeight > options.maxHeight) cntHeight = options.maxHeight;
if (div.length > 0) div[0].scrollTop = 1000;
var inpHeight = w2utils.getSize($(this.el), 'height') - 2;
if (inpHeight > cntHeight) cntHeight = inpHeight;
$(div).css({ 'height': cntHeight + 'px', overflow: (cntHeight == options.maxHeight ? 'auto' : 'hidden') });
if (cntHeight < options.maxHeight) $(div).prop('scrollTop', 0);
$(this.el).css({ 'height' : (cntHeight + 2) + 'px' });
// update size
if (obj.type == 'enum') {
var tmp = obj.helpers.multi.find('input');
tmp.width(((tmp.val().length + 2) * 8) + 'px');
}
}
return (new Date()).getTime() - time;
},
reset: function () {
var obj = this;
var type = this.type;
this.clear();
this.type = type;
this.init();
},
// resizing width of list, enum, file controls
resize: function () {
var obj = this;
var new_width = $(obj.el).width();
var new_height = $(obj.el).height();
if (obj.tmp.current_width == new_width && new_height > 0) return;
var focus = this.helpers.focus;
var multi = this.helpers.multi;
var suffix = this.helpers.suffix;
var prefix = this.helpers.prefix;
// resize helpers
if (focus) {
focus.width($(obj.el).width());
}
if (multi) {
var width = (w2utils.getSize(obj.el, 'width')
- parseInt($(obj.el).css('margin-left'), 10)
- parseInt($(obj.el).css('margin-right'), 10));
$(multi).width(width);
}
if (suffix) {
obj.options.suffix = '<div class="arrow-down" style="margin-top: '+ ((parseInt($(obj.el).height()) - 6) / 2) +'px;"></div>';
obj.addSuffix();
}
if (prefix) {
obj.addPrefix();
}
// remember width
obj.tmp.current_width = new_width;
},
clean: function (val) {
//issue #499
if(typeof val == 'number'){
return val;
}
var options = this.options;
val = String(val).trim();
// clean
if (['int', 'float', 'money', 'currency', 'percent'].indexOf(this.type) != -1) {
if (typeof val == 'string') {
if (options.autoFormat && ['money', 'currency'].indexOf(this.type) != -1) val = String(val).replace(options.moneyRE, '');
if (options.autoFormat && this.type == 'percent') val = String(val).replace(options.percentRE, '');
if (options.autoFormat && ['int', 'float'].indexOf(this.type) != -1) val = String(val).replace(options.numberRE, '');
val = val.replace(/\s+/g, '').replace(w2utils.settings.groupSymbol, '').replace(w2utils.settings.decimalSymbol, '.');
}
if (parseFloat(val) == val) {
if (options.min != null && val < options.min) { val = options.min; $(this.el).val(options.min); }
if (options.max != null && val > options.max) { val = options.max; $(this.el).val(options.max); }
}
if (val !== '' && w2utils.isFloat(val)) val = Number(val); else val = '';
}
return val;
},
format: function (val) {
var options = this.options;
// autoformat numbers or money
if (options.autoFormat && val != '') {
switch (this.type) {
case 'money':
case 'currency':
val = w2utils.formatNumber(val, options.currencyPrecision, options.groupSymbol);
if (val != '') val = options.currencyPrefix + val + options.currencySuffix;
break;
case 'percent':
val = w2utils.formatNumber(val, options.precision, options.groupSymbol);
if (val != '') val += '%';
break;
case 'float':
val = w2utils.formatNumber(val, options.precision, options.groupSymbol);
break;
case 'int':
val = w2utils.formatNumber(val, 0, options.groupSymbol);
break;
}
}
return val;
},
change: function (event) {
var obj = this;
var options = obj.options;
// numeric
if (['int', 'float', 'money', 'currency', 'percent'].indexOf(this.type) != -1) {
// check max/min
var val = $(this.el).val();
var new_val = this.format(this.clean($(this.el).val()));
// if was modified
if (val != '' && val != new_val) {
$(this.el).val(new_val).change();
// cancel event
event.stopPropagation();
event.preventDefault();
return false;
}
}
// color
if (this.type == 'color') {
var color = '#' + $(this.el).val();
if ($(this.el).val().length != 6 && $(this.el).val().length != 3) color = '';
$(this.el).next().find('div').css('background-color', color);
if ($(obj.el).is(':focus')) this.updateOverlay();
}
// list, enum
if (['list', 'enum', 'file'].indexOf(this.type) != -1) {
obj.refresh();
// need time out to show icon indent properly
setTimeout(function () { obj.refresh(); }, 5);
}
// date, time
if (['date', 'time', 'datetime'].indexOf(this.type) != -1) {
// convert linux timestamps
var tmp = parseInt(obj.el.value);
if (w2utils.isInt(obj.el.value) && tmp > 3000) {
if (this.type == 'time') $(obj.el).val(w2utils.formatTime(new Date(tmp), options.format)).change();
if (this.type == 'date') $(obj.el).val(w2utils.formatDate(new Date(tmp), options.format)).change();
if (this.type == 'datetime') $(obj.el).val(w2utils.formatDateTime(new Date(tmp), options.format)).change();
}
}
},
click: function (event) {
event.stopPropagation();
// lists
if (['list', 'combo', 'enum'].indexOf(this.type) != -1) {
if (!$(this.el).is(':focus')) this.focus(event);
}
// other fields with drops
if (['date', 'time', 'color', 'datetime'].indexOf(this.type) != -1) {
this.updateOverlay();
}
},
focus: function (event) {
var obj = this;
var options = this.options;
// color, date, time
if (['color', 'date', 'time', 'datetime'].indexOf(obj.type) !== -1) {
if ($(obj.el).attr('readonly') || $(obj.el).attr('disabled')) return;
if ($("#w2ui-overlay").length > 0) $('#w2ui-overlay')[0].hide();
setTimeout(function () { obj.updateOverlay(); }, 150);
}
// menu
if (['list', 'combo', 'enum'].indexOf(obj.type) != -1) {
if ($(obj.el).attr('readonly') || $(obj.el).attr('disabled')) return;
if ($("#w2ui-overlay").length > 0) $('#w2ui-overlay')[0].hide();
obj.resize();
setTimeout(function () {
if (obj.type == 'list' && $(obj.el).is(':focus')) {
$(obj.helpers.focus).find('input').focus();
return;
}
obj.search();
setTimeout(function () { obj.updateOverlay(); }, 1);
}, 1);
}
// file
if (obj.type == 'file') {
$(obj.helpers.multi).css({ 'outline': 'auto 5px #7DB4F3', 'outline-offset': '-2px' });
}
},
blur: function (event) {
var obj = this;
var options = obj.options;
var val = $(obj.el).val().trim();
// hide overlay
if (['color', 'date', 'time', 'list', 'combo', 'enum', 'datetime'].indexOf(obj.type) != -1) {
if ($("#w2ui-overlay").length > 0) $('#w2ui-overlay')[0].hide();
}
if (['int', 'float', 'money', 'currency', 'percent'].indexOf(obj.type) != -1) {
if (val !== '' && !obj.checkType(val)) {
$(obj.el).val('').change();
if (options.silent === false) {
$(obj.el).w2tag('Not a valid number');
setTimeout(function () { $(obj.el).w2tag(''); }, 3000);
}
}
}
// date or time
if (['date', 'time', 'datetime'].indexOf(obj.type) != -1) {
// check if in range
if (val !== '' && !obj.inRange(obj.el.value)) {
$(obj.el).val('').removeData('selected').change();
if (options.silent === false) {
$(obj.el).w2tag('Not in range');
setTimeout(function () { $(obj.el).w2tag(''); }, 3000);
}
} else {
if (obj.type == 'date' && val !== '' && !w2utils.isDate(obj.el.value, options.format)) {
$(obj.el).val('').removeData('selected').change();
if (options.silent === false) {
$(obj.el).w2tag('Not a valid date');
setTimeout(function () { $(obj.el).w2tag(''); }, 3000);
}
}
else if (obj.type == 'time' && val !== '' && !w2utils.isTime(obj.el.value)) {
$(obj.el).val('').removeData('selected').change();
if (options.silent === false) {
$(obj.el).w2tag('Not a valid time');
setTimeout(function () { $(obj.el).w2tag(''); }, 3000);
}
}
else if (obj.type == 'datetime' && val !== '' && !(options.use_moment_js ? w2utils.isDateTime(obj.el.value, options.format_mjs) : w2utils.isDateTime(obj.el.value, options.format))) {
$(obj.el).val('').removeData('selected').change();
if (options.silent === false) {
$(obj.el).w2tag('Not a valid date');
setTimeout(function () { $(obj.el).w2tag(''); }, 3000);
}
}
}
}
// clear search input
if (obj.type == 'enum') {
$(obj.helpers.multi).find('input').val('').width(20);
}
// file
if (obj.type == 'file') {
$(obj.helpers.multi).css({ 'outline': 'none' });
}
},
keyPress: function (event) {
var obj = this;
var options = obj.options;
// ignore wrong pressed key
if (['int', 'float', 'money', 'currency', 'percent', 'hex', 'bin', 'color', 'alphanumeric'].indexOf(obj.type) != -1) {
// keyCode & charCode differ in FireFox
if (event.metaKey || event.ctrlKey || event.altKey || (event.charCode != event.keyCode && event.keyCode > 0)) return;
var ch = String.fromCharCode(event.charCode);
if (!obj.checkType(ch, true) && event.keyCode != 13) {
event.preventDefault();
if (event.stopPropagation) event.stopPropagation(); else event.cancelBubble = true;
return false;
}
}
// update date popup
if (['date', 'time', 'datetime'].indexOf(obj.type) != -1) {
setTimeout(function () { obj.updateOverlay(); }, 1);
}
},
keyDown: function (event, extra) {
var obj = this;
var options = obj.options;
var key = event.keyCode || (extra && extra.keyCode);
// numeric
if (['int', 'float', 'money', 'currency', 'percent'].indexOf(obj.type) != -1) {
if (!options.keyboard || $(obj.el).attr('readonly')) return;
var cancel = false;
var val = parseFloat($(obj.el).val().replace(options.moneyRE, '')) || 0;
var inc = options.step;
if (event.ctrlKey || event.metaKey) inc = 10;
switch (key) {
case 38: // up
if (event.shiftKey) break; // no action if shift key is pressed
$(obj.el).val((val + inc <= options.max || options.max == null ? Number((val + inc).toFixed(12)) : options.max)).change();
cancel = true;
break;
case 40: // down
if (event.shiftKey) break; // no action if shift key is pressed
$(obj.el).val((val - inc >= options.min || options.min == null ? Number((val - inc).toFixed(12)) : options.min)).change();
cancel = true;
break;
}
if (cancel) {
event.preventDefault();
setTimeout(function () {
// set cursor to the end
obj.el.setSelectionRange(obj.el.value.length, obj.el.value.length);
}, 0);
}
}
// date
if (obj.type == 'date') {
if (!options.keyboard || $(obj.el).attr('readonly')) return;
var cancel = false;
var daymil = 24*60*60*1000;
var inc = 1;
if (event.ctrlKey || event.metaKey) inc = 10;
var dt = w2utils.isDate($(obj.el).val(), options.format, true);
if (!dt) { dt = new Date(); daymil = 0; }
switch (key) {
case 38: // up
if (event.shiftKey) break; // no action if shift key is pressed
var newDT = w2utils.formatDate(dt.getTime() + daymil, options.format);
if (inc == 10) newDT = w2utils.formatDate(new Date(dt.getFullYear(), dt.getMonth()+1, dt.getDate()), options.format);
$(obj.el).val(newDT).change();
cancel = true;
break;
case 40: // down
if (event.shiftKey) break; // no action if shift key is pressed
var newDT = w2utils.formatDate(dt.getTime() - daymil, options.format);
if (inc == 10) newDT = w2utils.formatDate(new Date(dt.getFullYear(), dt.getMonth()-1, dt.getDate()), options.format);
$(obj.el).val(newDT).change();
cancel = true;
break;
}
if (cancel) {
event.preventDefault();
setTimeout(function () {
// set cursor to the end
obj.el.setSelectionRange(obj.el.value.length, obj.el.value.length);
obj.updateOverlay();
}, 0);
}
}
// time
if (obj.type == 'time') {
if (!options.keyboard || $(obj.el).attr('readonly')) return;
var cancel = false;
var inc = (event.ctrlKey || event.metaKey ? 60 : 1);
var val = $(obj.el).val();
var time = obj.toMin(val) || obj.toMin((new Date()).getHours() + ':' + ((new Date()).getMinutes() - 1));
switch (key) {
case 38: // up
if (event.shiftKey) break; // no action if shift key is pressed
time += inc;
cancel = true;
break;
case 40: // down
if (event.shiftKey) break; // no action if shift key is pressed
time -= inc;
cancel = true;
break;
}
if (cancel) {
$(obj.el).val(obj.fromMin(time)).change();
event.preventDefault();
setTimeout(function () {
// set cursor to the end
obj.el.setSelectionRange(obj.el.value.length, obj.el.value.length);
}, 0);
}
}
// datetime
if (obj.type == 'datetime') {
if (!options.keyboard || $(obj.el).attr('readonly')) return;
var cancel = false;
var daymil = 24*60*60*1000;
var inc = 1;
if (event.ctrlKey || event.metaKey) inc = 10;
var str = $(obj.el).val();
var dt = (w2utils.use_momentjs ? w2utils.isDateTime(str, this.options.format_mjs, true) : w2utils.isDateTime(str, this.options.format, true));
if (!dt) { dt = new Date(); daymil = 0; }
switch (key) {
case 38: // up
if (event.shiftKey) break; // no action if shift key is pressed
var newDT = w2utils.formatDateTime(dt.getTime() + daymil, options.format);
if (inc == 10) newDT = w2utils.formatDateTime(new Date(dt.getFullYear(), dt.getMonth()+1, dt.getDate()), options.format);
$(obj.el).val(newDT).change();
cancel = true;
break;
case 40: // down
if (event.shiftKey) break; // no action if shift key is pressed
var newDT = w2utils.formatDateTime(dt.getTime() - daymil, options.format);
if (inc == 10) newDT = w2utils.formatDateTime(new Date(dt.getFullYear(), dt.getMonth()-1, dt.getDate()), options.format);
$(obj.el).val(newDT).change();
cancel = true;
break;
}
if (cancel) {
event.preventDefault();
setTimeout(function () {
// set cursor to the end
obj.el.setSelectionRange(obj.el.value.length, obj.el.value.length);
obj.updateOverlay();
}, 0);
}
}
// color
if (obj.type == 'color') {
if ($(obj.el).attr('readonly')) return;
// paste
if (event.keyCode == 86 && (event.ctrlKey || event.metaKey)) {
$(obj.el).prop('maxlength', 7);
setTimeout(function () {
var val = $(obj).val();
if (val.substr(0, 1) == '#') val = val.substr(1);
if (!w2utils.isHex(val)) val = '';
$(obj).val(val).prop('maxlength', 6).change();
}, 20);
}
if ((event.ctrlKey || event.metaKey) && !event.shiftKey) {
var dir = null;
var newColor = null;
switch (key) {
case 38: // up
dir = 'up';
break;
case 40: // down
dir = 'down';
break;
case 39: // right
dir = 'right';
break;
case 37: // left
dir = 'left';
break;
}
if (obj.el.nav && dir != null) {
newColor = obj.el.nav(dir);
$(obj.el).val(newColor).change();
event.preventDefault();
}
}
}
// list/select/combo
if (['list', 'combo', 'enum'].indexOf(obj.type) != -1) {
if ($(obj.el).attr('readonly')) return;
var selected = $(obj.el).data('selected');
var focus = $(obj.el);
var indexOnly = false;
if (['list', 'enum'].indexOf(obj.type) != -1) {
if (obj.type == 'list') {
focus = $(obj.helpers.focus).find('input');
}
if (obj.type == 'enum') {
focus = $(obj.helpers.multi).find('input');
}
// not arrows - refresh
if ([37, 38, 39, 40].indexOf(key) == -1) {
setTimeout(function () { obj.refresh(); }, 1);
}
// paste
if (event.keyCode == 86 && (event.ctrlKey || event.metaKey)) {
setTimeout(function () {
obj.refresh();
obj.search();
obj.request();
}, 50);
}
}
// apply arrows
switch (key) {
case 27: // escape
if (obj.type == 'list') {
if (focus.val() != '') focus.val('');
event.stopPropagation(); // escape in field should not close popup
}
break;
case 37: // left
case 39: // right
// indexOnly = true;
break;
case 13: // enter
if ($('#w2ui-overlay').length == 0) break; // no action if overlay not open
var item = options.items[options.index];
if (obj.type == 'enum') {
if (item != null) {
// trigger event
var eventData = obj.trigger({ phase: 'before', type: 'add', target: obj.el, originalEvent: event.originalEvent, item: item });
if (eventData.isCancelled === true) return;
item = eventData.item; // need to reassign because it could be recreated by user
// default behavior
if (selected.length >= options.max && options.max > 0) selected.pop();
delete item.hidden;
delete obj.tmp.force_open;
selected.push(item);
$(obj.el).change();
focus.val('').width(20);
obj.refresh();
// event after
obj.trigger($.extend(eventData, { phase: 'after' }));
} else {
// trigger event
item = { id: focus.val(), text: focus.val() };
var eventData = obj.trigger({ phase: 'before', type: 'new', target: obj.el, originalEvent: event.originalEvent, item: item });
if (eventData.isCancelled === true) return;
item = eventData.item; // need to reassign because it could be recreated by user
// default behavior
if (typeof obj.onNew == 'function') {
if (selected.length >= options.max && options.max > 0) selected.pop();
delete obj.tmp.force_open;
selected.push(item);
$(obj.el).change();
focus.val('').width(20);
obj.refresh();
}
// event after
obj.trigger($.extend(eventData, { phase: 'after' }));
}
} else {
if (item) $(obj.el).data('selected', item).val(item.text).change();
if ($(obj.el).val() == '' && $(obj.el).data('selected')) $(obj.el).removeData('selected').val('').change();
if (obj.type == 'list') {
focus.val('');
obj.refresh();
}
// hide overlay
obj.tmp.force_hide = true;
}
break;
case 8: // backspace
case 46: // delete
if (obj.type == 'enum' && key == 8) {
if (focus.val() == '' && selected.length > 0) {
var item = selected[selected.length - 1];
// trigger event
var eventData = obj.trigger({ phase: 'before', type: 'remove', target: obj.el, originalEvent: event.originalEvent, item: item });
if (eventData.isCancelled === true) return;
// default behavior
selected.pop();
$(obj.el).trigger('change');
obj.refresh();
// event after
obj.trigger($.extend(eventData, { phase: 'after' }));
}
}
if (obj.type == 'list' && focus.val() == '') {
$(obj.el).data('selected', {}).change();
obj.refresh();
}
break;
case 38: // up
options.index = w2utils.isInt(options.index) ? parseInt(options.index) : 0;
options.index--;
while (options.index > 0 && options.items[options.index].hidden) options.index--;
if (options.index == 0 && options.items[options.index].hidden) {
while (options.items[options.index] && options.items[options.index].hidden) options.index++;
}
indexOnly = true;
break;
case 40: // down
options.index = w2utils.isInt(options.index) ? parseInt(options.index) : -1;
options.index++;
while (options.index < options.items.length-1 && options.items[options.index].hidden) options.index++;
if (options.index == options.items.length-1 && options.items[options.index].hidden) {
while (options.items[options.index] && options.items[options.index].hidden) options.index--;
}
// show overlay if not shown
if (focus.val() == '' && $('#w2ui-overlay').length == 0) {
obj.tmp.force_open = true;
} else {
indexOnly = true;
}
break;
}
if (indexOnly) {
if (options.index < 0) options.index = 0;
if (options.index >= options.items.length) options.index = options.items.length -1;
obj.updateOverlay(indexOnly);
// cancel event
event.preventDefault();
setTimeout(function () {
// set cursor to the end
if (obj.type == 'enum') {
var tmp = focus.get(0);
tmp.setSelectionRange(tmp.value.length, tmp.value.length);
} else if (obj.type == 'list') {
var tmp = focus.get(0);
tmp.setSelectionRange(tmp.value.length, tmp.value.length);
} else {
obj.el.setSelectionRange(obj.el.value.length, obj.el.value.length);
}
}, 0);
return;
}
// expand input
if (obj.type == 'enum') {
focus.width(((focus.val().length + 2) * 8) + 'px');
}
// run search
if ([16, 17, 18, 20, 37, 39, 91].indexOf(key) == -1) { // no refresh on crtl, shift, left/right arrows, etc
// run search
setTimeout(function () {
// trigger event
var eventData = obj.trigger({ phase: 'before', type: 'search', originalEvent: event, target: focus, search: focus.val() });
if (eventData.isCancelled === true) return;
// default action
if (!obj.tmp.force_hide) obj.request();
obj.search();
// event after
obj.trigger($.extend(eventData, { phase: 'after' }));
}, 1);
}
}
},
keyUp: function (event) {
var obj = this;
if (this.type == 'color') {
if (event.keyCode == 86 && (event.ctrlKey || event.metaKey)) {
$(this).prop('maxlength', 6);
}
}
},
clearCache: function () {
var options = this.options;
options.items = [];
this.tmp.xhr_loading = false;
this.tmp.xhr_search = '';
this.tmp.xhr_total = -1;
},
request: function (interval) {
var obj = this;
var options = this.options;
var search = $(obj.el).val() || '';
// if no url - do nothing
if (!options.url) return;
// --
if (obj.type == 'enum') {
var tmp = $(obj.helpers.multi).find('input');
if (tmp.length == 0) search = ''; else search = tmp.val();
}
if (obj.type == 'list') {
var tmp = $(obj.helpers.focus).find('input');
if (tmp.length == 0) search = ''; else search = tmp.val();
}
if (options.minLength != 0 && search.length < options.minLength) {
options.items = []; // need to empty the list
this.updateOverlay();
return;
}
if (interval == null) interval = options.interval;
if (obj.tmp.xhr_search == null) obj.tmp.xhr_search = '';
if (obj.tmp.xhr_total == null) obj.tmp.xhr_total = -1;
// check if need to search
if (options.url && $(obj.el).prop('readonly') != true && (
(options.items.length === 0 && obj.tmp.xhr_total !== 0) ||
(obj.tmp.xhr_total == options.cacheMax && search.length > obj.tmp.xhr_search.length) ||
(search.length >= obj.tmp.xhr_search.length && search.substr(0, obj.tmp.xhr_search.length) != obj.tmp.xhr_search) ||
(search.length < obj.tmp.xhr_search.length)
)) {
// empty list
if (obj.tmp.xhr) obj.tmp.xhr.abort();
obj.tmp.xhr_loading = true;
obj.search();
// timeout
clearTimeout(obj.tmp.timeout);
obj.tmp.timeout = setTimeout(function () {
// trigger event
var url = options.url;
var postData = {
search : search,
max : options.cacheMax
};
$.extend(postData, options.postData);
var eventData = obj.trigger({ phase: 'before', type: 'request', target: obj.el, url: url, postData: postData });
if (eventData.isCancelled === true) return;
url = eventData.url;
postData = eventData.postData;
var ajaxOptions = {
type : 'GET',
url : url,
data : postData,
dataType : 'JSON' // expected from server
};
if (options.method) ajaxOptions.type = options.method;
if (w2utils.settings.dataType == 'JSON') {
ajaxOptions.type = 'POST';
ajaxOptions.data = JSON.stringify(ajaxOptions.data);
ajaxOptions.contentType = 'application/json';
}
if (options.method != null) ajaxOptions.type = options.method;
obj.tmp.xhr = $.ajax(ajaxOptions)
.done(function (data, status, xhr) {
// trigger event
var eventData2 = obj.trigger({ phase: 'before', type: 'load', target: obj.el, search: postData.search, data: data, xhr: xhr });
if (eventData2.isCancelled === true) return;
// default behavior
data = eventData2.data;
if (typeof data == 'string') data = JSON.parse(data);
if (data.status != 'success') {
console.log('ERROR: server did not return proper structure. It should return', { status: 'success', items: [{ id: 1, text: 'item' }] });
return;
}
// remove all extra items if more then needed for cache
if (data.items.length > options.cacheMax) data.items.splice(options.cacheMax, 100000);
// remember stats
obj.tmp.xhr_loading = false;
obj.tmp.xhr_search = search;
obj.tmp.xhr_total = data.items.length;
options.items = obj.normMenu(data.items);
if (search == '' && data.items.length == 0) obj.tmp.emptySet = true; else obj.tmp.emptySet = false;
obj.search();
// event after
obj.trigger($.extend(eventData2, { phase: 'after' }));
})
.fail(function (xhr, status, error) {
// trigger event
var errorObj = { status: status, error: error, rawResponseText: xhr.responseText };
var eventData2 = obj.trigger({ phase: 'before', type: 'error', target: obj.el, search: search, error: errorObj, xhr: xhr });
if (eventData2.isCancelled === true) return;
// default behavior
if (status != 'abort') {
var data;
try { data = $.parseJSON(xhr.responseText); } catch (e) {}
console.log('ERROR: Server communication failed.',
'\n EXPECTED:', { status: 'success', items: [{ id: 1, text: 'item' }] },
'\n OR:', { status: 'error', message: 'error message' },
'\n RECEIVED:', typeof data == 'object' ? data : xhr.responseText);
}
// reset stats
obj.clearCache();
obj.search();
// event after
obj.trigger($.extend(eventData2, { phase: 'after' }));
});
// event after
obj.trigger($.extend(eventData, { phase: 'after' }));
}, interval);
}
},
search: function () {
var obj = this;
var options = this.options;
var search = $(obj.el).val();
var target = obj.el;
var ids = [];
var selected = $(obj.el).data('selected');
if (obj.type == 'enum') {
target = $(obj.helpers.multi).find('input');
search = target.val();
for (var s in selected) { if (selected[s]) ids.push(selected[s].id); }
}
if (obj.type == 'list') {
target = $(obj.helpers.focus).find('input');
search = target.val();
for (var s in selected) { if (selected[s]) ids.push(selected[s].id); }
}
if (obj.tmp.xhr_loading !== true) {
var shown = 0;
for (var i = 0; i < options.items.length; i++) {
var item = options.items[i];
if (options.compare != null) {
if (typeof options.compare == 'function') {
item.hidden = (options.compare.call(this, item, search) === false ? true : false);
}
} else {
var prefix = '';
var suffix = '';
if (['is', 'begins'].indexOf(options.match) != -1) prefix = '^';
if (['is', 'ends'].indexOf(options.match) != -1) suffix = '$';
try {
var re = new RegExp(prefix + search + suffix, 'i');
if (re.test(item.text) || item.text == '...') item.hidden = false; else item.hidden = true;
} catch (e) {}
}
if (options.filter === false) item.hidden = false;
// do not show selected items
if (obj.type == 'enum' && $.inArray(item.id, ids) != -1) item.hidden = true;
if (item.hidden !== true) { shown++; delete item.hidden; }
}
// preselect first item
options.index = 0;
while (options.items[options.index] && options.items[options.index].hidden) options.index++;
if (shown <= 0) options.index = -1;
options.spinner = false;
obj.updateOverlay();
setTimeout(function () {
var html = $('#w2ui-overlay').html() || '';
if (options.markSearch && html.indexOf('$.fn.w2menuHandler') != -1) { // do not highlight when no items
$('#w2ui-overlay').w2marker(search);
}
}, 1);
} else {
options.items.splice(0, options.cacheMax);
options.spinner = true;
obj.updateOverlay();
}
},
updateOverlay: function (indexOnly) {
var obj = this;
var options = this.options;
// color
if (this.type == 'color') {
if ($(obj.el).attr('readonly')) return;
$(this.el).w2color($(this.el).val(), function (color) {
if (color == null) return;
$(obj.el).val(color).change();
});
}
// date
if (this.type == 'date') {
if ($(obj.el).attr('readonly')) return;
if ($('#w2ui-overlay').length == 0) {
$(obj.el).w2overlay('<div class="w2ui-reset w2ui-calendar" onclick="event.stopPropagation();"></div>', {
css: { "background-color": "#f5f5f5" }
});
}
var month, year;
var dt = w2utils.isDate($(obj.el).val(), obj.options.format, true);
if (dt) { month = dt.getMonth() + 1; year = dt.getFullYear(); }
(function refreshCalendar(month, year) {
$('#w2ui-overlay > div > div').html(obj.getMonthHTML(month, year, $(obj.el).val()));
$('#w2ui-overlay .w2ui-calendar-title')
.on('mousedown', function () {
if ($(this).next().hasClass('w2ui-calendar-jump')) {
$(this).next().remove();
} else {
var selYear, selMonth;
$(this).after('<div class="w2ui-calendar-jump" style=""></div>');
$(this).next().hide().html(obj.getYearHTML()).fadeIn(200);
setTimeout(function () {
$('#w2ui-overlay .w2ui-calendar-jump')
.find('.w2ui-jump-month, .w2ui-jump-year')
.on('click', function () {
if ($(this).hasClass('w2ui-jump-month')) {
$(this).parent().find('.w2ui-jump-month').removeClass('selected');
$(this).addClass('selected');
selMonth = $(this).attr('name');
}
if ($(this).hasClass('w2ui-jump-year')) {
$(this).parent().find('.w2ui-jump-year').removeClass('selected');
$(this).addClass('selected');
selYear = $(this).attr('name');
}
if (selYear != null && selMonth != null) {
$('#w2ui-overlay .w2ui-calendar-jump').fadeOut(100);
setTimeout(function () { refreshCalendar(parseInt(selMonth)+1, selYear); }, 100);
}
});
$('#w2ui-overlay .w2ui-calendar-jump >:last-child').prop('scrollTop', 2000);
}, 1);
}
});
$('#w2ui-overlay .w2ui-date')
.on('mousedown', function () {
var day = $(this).attr('date');
$(obj.el).val(day).change();
$(this).css({ 'background-color': '#B6D5FB', 'border-color': '#aaa' });
})
.on('mouseup', function () {
setTimeout(function () {
if ($("#w2ui-overlay").length > 0) $('#w2ui-overlay').removeData('keepOpen')[0].hide();
}, 10);
});
$('#w2ui-overlay .previous').on('mousedown', function () {
var tmp = obj.options.current.split('/');
tmp[0] = parseInt(tmp[0]) - 1;
refreshCalendar(tmp[0], tmp[1]);
});
$('#w2ui-overlay .next').on('mousedown', function () {
var tmp = obj.options.current.split('/');
tmp[0] = parseInt(tmp[0]) + 1;
refreshCalendar(tmp[0], tmp[1]);
});
}) (month, year);
}
// time
if (this.type == 'time') {
if ($(obj.el).attr('readonly')) return;
if ($('#w2ui-overlay').length == 0) {
$(obj.el).w2overlay('<div class="w2ui-reset w2ui-calendar-time" onclick="event.stopPropagation();"></div>', {
css: { "background-color": "#fff" }
});
}
var h24 = (this.options.format == 'h24');
$('#w2ui-overlay > div').html(obj.getHourHTML());
$('#w2ui-overlay .w2ui-time')
.on('mousedown', function (event) {
$(this).css({ 'background-color': '#B6D5FB', 'border-color': '#aaa' });
var hour = $(this).attr('hour');
$(obj.el).val((hour > 12 && !h24 ? hour - 12 : hour) + ':00' + (!h24 ? (hour < 12 ? ' am' : ' pm') : '')).change();
})
.on('mouseup', function () {
var hour = $(this).attr('hour');
if ($("#w2ui-overlay").length > 0) $('#w2ui-overlay')[0].hide();
$(obj.el).w2overlay('<div class="w2ui-reset w2ui-calendar-time"></div>', { css: { "background-color": "#fff" } });
$('#w2ui-overlay > div').html(obj.getMinHTML(hour));
$('#w2ui-overlay .w2ui-time')
.on('mousedown', function () {
$(this).css({ 'background-color': '#B6D5FB', 'border-color': '#aaa' });
var min = $(this).attr('min');
$(obj.el).val((hour > 12 && !h24 ? hour - 12 : hour) + ':' + (min < 10 ? 0 : '') + min + (!h24 ? (hour < 12 ? ' am' : ' pm') : '')).change();
})
.on('mouseup', function () {
setTimeout(function () { if ($("#w2ui-overlay").length > 0) $('#w2ui-overlay').removeData('keepOpen')[0].hide(); }, 10);
});
});
}
// datetime
if (this.type == 'datetime') {
if ($(obj.el).attr('readonly')) return;
// hide overlay if we are in the time selection
if ($("#w2ui-overlay .w2ui-time").length > 0) $('#w2ui-overlay')[0].hide();
if ($('#w2ui-overlay').length == 0) {
$(obj.el).w2overlay('<div class="w2ui-reset w2ui-calendar" onclick="event.stopPropagation();"></div>', {
css: { "background-color": "#f5f5f5" }
});
}
var month, year;
var dt = w2utils.isDate($(obj.el).val(), obj.options.format, true);
if (dt) { month = dt.getMonth() + 1; year = dt.getFullYear(); }
var selDate = null;
(function refreshCalendar(month, year) {
$('#w2ui-overlay > div > div').html(obj.getMonthHTML(month, year, $(obj.el).val()));
// add "now" button
if(obj.options.btn_now) {
$('#w2ui-overlay > div > div .w2ui-calendar-previous.previous').after('<div class="w2ui-calendar-previous now"></div>');
// openclipart 194286
var bg_image = "url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAAJiS0dEAP+Hj8y/AAAACXBIWXMAAAsTAAALEwEAmpwYAAABDUlEQVQoz23QzyuDARgH8E+0hsSi6aWGklrz42CUiJVcFuXCmDZZKYZyQEocnDnt6B9xWXJ4/4CVUsp/4uLwbkX2fG/P93N4emg3I6aN62zbGXTkxqq8U5P/627nAs+G0ONYKlrHxZtgVc6AvCpIKkXrgt0mKCmriHkVA2c8CtXUhEKhL8+ehL692IzAu4Q9RYlmtlQkvEnJCRRooEuvwKCkMb1G9asL9KkajgBJd0rKHky7llNXUTVOC8QtSEvLGjAjUJfVEd3dsObWonv7DtyY8mBTXdB6TUPGnkkFK5ZtSNkx9xdkFWWUbMk7M6Fs6S+Yd2LWhV3bLqWdWP8NPl21yYe+Fsg6bJOlVv0DQzw+zwokgrkAAAAASUVORK5CYII=)";
$('#w2ui-overlay div div.w2ui-calendar-previous.now').css({
'width': '20px', 'text-align': 'center', 'vertical-align': 'middle', 'background-repeat': 'no-repeat', 'background-position': 'center', 'background-image': bg_image,
});
}
$('#w2ui-overlay .w2ui-calendar-title')
.on('mousedown', function () {
if ($(this).next().hasClass('w2ui-calendar-jump')) {
$(this).next().remove();
} else {
var selYear, selMonth;
$(this).after('<div class="w2ui-calendar-jump" style=""></div>');
$(this).next().hide().html(obj.getYearHTML()).fadeIn(200);
setTimeout(function () {
$('#w2ui-overlay .w2ui-calendar-jump')
.find('.w2ui-jump-month, .w2ui-jump-year')
.on('click', function () {
if ($(this).hasClass('w2ui-jump-month')) {
$(this).parent().find('.w2ui-jump-month').removeClass('selected');
$(this).addClass('selected');
selMonth = $(this).attr('name');
}
if ($(this).hasClass('w2ui-jump-year')) {
$(this).parent().find('.w2ui-jump-year').removeClass('selected');
$(this).addClass('selected');
selYear = $(this).attr('name');
}
if (selYear != null && selMonth != null) {
$('#w2ui-overlay .w2ui-calendar-jump').fadeOut(100);
setTimeout(function () { refreshCalendar(parseInt(selMonth)+1, selYear); }, 100);
}
});
$('#w2ui-overlay .w2ui-calendar-jump >:last-child').prop('scrollTop', 2000);
}, 1);
}
});
$('#w2ui-overlay .w2ui-date')
.on('mousedown', function () {
var day = $(this).attr('date');
$(obj.el).val(day).change();
$(this).css({ 'background-color': '#B6D5FB', 'border-color': '#aaa' });
selDate = new Date($(this).attr('data-date'));
})
.on('mouseup', function () {
/*setTimeout(function () {
if ($("#w2ui-overlay").length > 0) $('#w2ui-overlay').removeData('keepOpen')[0].hide();
}, 10);*/
// continue with time picker
var selHour, selMin;
if ($("#w2ui-overlay").length > 0) $('#w2ui-overlay')[0].hide();
$(obj.el).w2overlay('<div class="w2ui-reset w2ui-calendar-time"></div>', { css: { "background-color": "#fff" } });
var h24 = (obj.options.format == 'h24');
$('#w2ui-overlay > div').html(obj.getHourHTML());
$('#w2ui-overlay .w2ui-time')
.on('mousedown', function (event) {
$(this).css({ 'background-color': '#B6D5FB', 'border-color': '#aaa' });
selHour = $(this).attr('hour');
selDate.setHours(selHour);
var txt = w2utils.formatDateTime(selDate, obj.options.format);
$(obj.el).val(txt).change();
//$(obj.el).val((hour > 12 && !h24 ? hour - 12 : hour) + ':00' + (!h24 ? (hour < 12 ? ' am' : ' pm') : '')).change();
})
.on('mouseup', function () {
var hour = $(this).attr('hour');
if ($("#w2ui-overlay").length > 0) $('#w2ui-overlay')[0].hide();
$(obj.el).w2overlay('<div class="w2ui-reset w2ui-calendar-time"></div>', { css: { "background-color": "#fff" } });
$('#w2ui-overlay > div').html(obj.getMinHTML(hour));
$('#w2ui-overlay .w2ui-time')
.on('mousedown', function () {
$(this).css({ 'background-color': '#B6D5FB', 'border-color': '#aaa' });
selMin = $(this).attr('min');
selDate.setHours(selHour, selMin);
var txt = w2utils.formatDateTime(selDate, obj.options.format);
$(obj.el).val(txt).change();
//$(obj.el).val((hour > 12 && !h24 ? hour - 12 : hour) + ':' + (min < 10 ? 0 : '') + min + (!h24 ? (hour < 12 ? ' am' : ' pm') : '')).change();
})
.on('mouseup', function () {
setTimeout(function () { if ($("#w2ui-overlay").length > 0) $('#w2ui-overlay').removeData('keepOpen')[0].hide(); }, 10);
});
});
});
$('#w2ui-overlay .previous').on('mousedown', function () {
var tmp = obj.options.current.split('/');
tmp[0] = parseInt(tmp[0]) - 1;
refreshCalendar(tmp[0], tmp[1]);
});
$('#w2ui-overlay .next').on('mousedown', function () {
var tmp = obj.options.current.split('/');
tmp[0] = parseInt(tmp[0]) + 1;
refreshCalendar(tmp[0], tmp[1]);
});
// "now" button
$('#w2ui-overlay .now')
.on('mousedown', function () {
// this currently ignores blocked days or start / end dates!
var day = w2utils.formatDateTime(new Date(), obj.options.format);
$(obj.el).val(day).change();
//$(this).css({ 'background-color': '#B6D5FB', 'border-color': '#aaa' });
return false;
})
.on('mouseup', function () {
setTimeout(function () {
if ($("#w2ui-overlay").length > 0) $('#w2ui-overlay').removeData('keepOpen')[0].hide();
}, 10);
});
}) (month, year);
}
// list
if (['list', 'combo', 'enum'].indexOf(this.type) != -1) {
var el = this.el;
var input = this.el;
if (this.type == 'enum') {
el = $(this.helpers.multi);
input = $(el).find('input');
}
if (this.type == 'list') {
input = $(this.helpers.focus).find('input');
}
if ($(input).is(':focus')) {
if (options.openOnFocus === false && $(input).val() == '' && obj.tmp.force_open !== true) {
$().w2overlay();
return;
}
if (obj.tmp.force_hide) {
$().w2overlay();
setTimeout(function () {
delete obj.tmp.force_hide;
}, 1);
return;
}
if ($(input).val() != '') delete obj.tmp.force_open;
var msgNoItems = w2utils.lang('No matches');
if (options.url != null && $(input).val().length < options.minLength && obj.tmp.emptySet !== true) msgNoItems = options.minLength + ' ' + w2utils.lang('letters or more...');
if (options.url != null && $(input).val() == '' && obj.tmp.emptySet !== true) msgNoItems = w2utils.lang('Type to search...');
$(el).w2menu((!indexOnly ? 'refresh' : 'refresh-index'), $.extend(true, {}, options, {
search : false,
render : options.renderDrop,
maxHeight : options.maxDropHeight,
maxWidth : options.maxDropWidth,
msgNoItems : msgNoItems,
// selected with mouse
onSelect: function (event) {
if (obj.type == 'enum') {
var selected = $(obj.el).data('selected');
if (event.item) {
// trigger event
var eventData = obj.trigger({ phase: 'before', type: 'add', target: obj.el, originalEvent: event.originalEvent, item: event.item });
if (eventData.isCancelled === true) return;
// default behavior
if (selected.length >= options.max && options.max > 0) selected.pop();
delete event.item.hidden;
selected.push(event.item);
$(obj.el).data('selected', selected).change();
$(obj.helpers.multi).find('input').val('').width(20);
obj.refresh();
if ($("#w2ui-overlay").length > 0) $('#w2ui-overlay')[0].hide();
// event after
obj.trigger($.extend(eventData, { phase: 'after' }));
}
} else {
$(obj.el).data('selected', event.item).val(event.item.text).change();
if (obj.helpers.focus) obj.helpers.focus.find('input').val('');
}
}
}));
}
}
},
inRange: function (str) {
var inRange = false;
if (this.type == 'date') {
var dt = w2utils.isDate(str, this.options.format, true);
if (dt) {
// enable range
if (this.options.start || this.options.end) {
var st = (typeof this.options.start == 'string' ? this.options.start : $(this.options.start).val());
var en = (typeof this.options.end == 'string' ? this.options.end : $(this.options.end).val());
var start = w2utils.isDate(st, this.options.format, true);
var end = w2utils.isDate(en, this.options.format, true);
var current = new Date(dt);
if (!start) start = current;
if (!end) end = current;
if (current >= start && current <= end) inRange = true;
} else {
inRange = true;
}
// block predefined dates
if (this.options.blocked && $.inArray(str, this.options.blocked) != -1) inRange = false;
}
}
else if (this.type == 'time') {
if (this.options.start || this.options.end) {
var tm = this.toMin(str);
var tm1 = this.toMin(this.options.start);
var tm2 = this.toMin(this.options.end);
if (!tm1) tm1 = tm;
if (!tm2) tm2 = tm;
if (tm >= tm1 && tm <= tm2) inRange = true;
} else {
inRange = true;
}
}
else if (this.type == 'datetime') {
var dt = (w2utils.use_momentjs ? w2utils.isDateTime(str, this.options.format_mjs, true) : w2utils.isDateTime(str, this.options.format, true));
if (dt) {
// enable range
if (this.options.start || this.options.end) {
var start, end;
if(typeof this.options.start == 'object' && this.options.start instanceof Date) {
start = this.options.start;
} else {
var st = (typeof this.options.start == 'string' ? this.options.start : $(this.options.start).val());
start = (w2utils.use_momentjs ? w2utils.isDateTime(st, this.options.format_mjs, true) : w2utils.isDateTime(st, this.options.format, true));
}
if(typeof this.options.end == 'object' && this.options.end instanceof Date) {
end = this.options.end;
} else {
var en = (typeof this.options.end == 'string' ? this.options.end : $(this.options.end).val());
end = (w2utils.use_momentjs ? w2utils.isDateTime(en, this.options.format_mjs, true) : w2utils.isDateTime(en, this.options.format, true));
}
var current = dt; // new Date(dt);
if (!start) start = current;
if (!end) end = current;
if (current >= start && current <= end) inRange = true;
} else {
inRange = true;
}
// block predefined dates
if (inRange && this.options.blocked) {
for (var i=0; i<this.options.blocked.length; i++) {
var blocked = this.options.blocked[i];
if(typeof blocked == 'string') {
// convert string to Date object
blocked = (w2utils.use_momentjs ? w2utils.isDateTime(blocked, this.options.format_mjs, true) : w2utils.isDateTime(blocked, this.options.format, true));
}
// check for Date object with the same day
if(typeof blocked == 'object' && blocked instanceof Date && (blocked.getFullYear() == dt.getFullYear() && blocked.getMonth() == dt.getMonth() && blocked.getDate() == dt.getDate())) {
inRange = false;
break;
}
}
}
}
}
return inRange;
},
/*
* INTERNAL FUNCTIONS
*/
checkType: function (ch, loose) {
var obj = this;
switch (obj.type) {
case 'int':
if (loose && ['-', obj.options.groupSymbol].indexOf(ch) != -1) return true;
return w2utils.isInt(ch.replace(obj.options.numberRE, ''));
case 'percent':
ch = ch.replace(/%/g, '');
case 'float':
if (loose && ['-', w2utils.settings.decimalSymbol, obj.options.groupSymbol].indexOf(ch) != -1) return true;
return w2utils.isFloat(ch.replace(obj.options.numberRE, ''));
case 'money':
case 'currency':
if (loose && ['-', obj.options.decimalSymbol, obj.options.groupSymbol, obj.options.currencyPrefix, obj.options.currencySuffix].indexOf(ch) != -1) return true;
return w2utils.isFloat(ch.replace(obj.options.moneyRE, ''));
case 'bin':
return w2utils.isBin(ch);
case 'hex':
case 'color':
return w2utils.isHex(ch);
case 'alphanumeric':
return w2utils.isAlphaNumeric(ch);
}
return true;
},
addPrefix: function () {
var obj = this;
setTimeout(function () {
if (obj.type === 'clear') return;
var helper;
var tmp = $(obj.el).data('tmp') || {};
if (tmp['old-padding-left']) $(obj.el).css('padding-left', tmp['old-padding-left']);
tmp['old-padding-left'] = $(obj.el).css('padding-left');
$(obj.el).data('tmp', tmp);
// remove if already displaed
if (obj.helpers.prefix) $(obj.helpers.prefix).remove();
if (obj.options.prefix !== '') {
// add fresh
$(obj.el).before(
'<div class="w2ui-field-helper">'+
obj.options.prefix +
'</div>'
);
helper = $(obj.el).prev();
helper
.css({
'color' : $(obj.el).css('color'),
'font-family' : $(obj.el).css('font-family'),
'font-size' : $(obj.el).css('font-size'),
'padding-top' : $(obj.el).css('padding-top'),
'padding-bottom' : $(obj.el).css('padding-bottom'),
'padding-left' : $(obj.el).css('padding-left'),
'padding-right' : 0,
'margin-top' : (parseInt($(obj.el).css('margin-top'), 10) + 2) + 'px',
'margin-bottom' : (parseInt($(obj.el).css('margin-bottom'), 10) + 1) + 'px',
'margin-left' : $(obj.el).css('margin-left'),
'margin-right' : 0
})
.on('click', function (event) {
if (obj.options.icon && typeof obj.onIconClick == 'function') {
// event before
var eventData = obj.trigger({ phase: 'before', type: 'iconClick', target: obj.el, el: $(this).find('span.w2ui-icon')[0] });
if (eventData.isCancelled === true) return;
// intentionally empty
// event after
obj.trigger($.extend(eventData, { phase: 'after' }));
} else {
if (obj.type == 'list') {
$(obj.helpers.focus).find('input').focus();
} else {
$(obj.el).focus();
}
}
});
$(obj.el).css('padding-left', (helper.width() + parseInt($(obj.el).css('padding-left'), 10)) + 'px');
// remember helper
obj.helpers.prefix = helper;
}
}, 1);
},
addSuffix: function () {
var obj = this;
var helper, pr;
setTimeout(function () {
if (obj.type === 'clear') return;
var tmp = $(obj.el).data('tmp') || {};
if (tmp['old-padding-right']) $(obj.el).css('padding-right', tmp['old-padding-right']);
tmp['old-padding-right'] = $(obj.el).css('padding-right');
$(obj.el).data('tmp', tmp);
pr = parseInt($(obj.el).css('padding-right'), 10);
if (obj.options.arrows) {
// remove if already displaed
if (obj.helpers.arrows) $(obj.helpers.arrows).remove();
// add fresh
$(obj.el).after(
'<div class="w2ui-field-helper" style="border: 1px solid transparent"> '+
' <div class="w2ui-field-up" type="up">'+
' <div class="arrow-up" type="up"></div>'+
' </div>'+
' <div class="w2ui-field-down" type="down">'+
' <div class="arrow-down" type="down"></div>'+
' </div>'+
'</div>');
var height = w2utils.getSize(obj.el, 'height');
helper = $(obj.el).next();
helper.css({
'color' : $(obj.el).css('color'),
'font-family' : $(obj.el).css('font-family'),
'font-size' : $(obj.el).css('font-size'),
'height' : ($(obj.el).height() + parseInt($(obj.el).css('padding-top'), 10) + parseInt($(obj.el).css('padding-bottom'), 10) ) + 'px',
'padding' : 0,
'margin-top' : (parseInt($(obj.el).css('margin-top'), 10) + 1) + 'px',
'margin-bottom' : 0,
'border-left' : '1px solid silver'
})
.css('margin-left', '-'+ (helper.width() + parseInt($(obj.el).css('margin-right'), 10) + 12) + 'px')
.on('mousedown', function (event) {
var body = $('body');
body.on('mouseup', tmp);
body.data('_field_update_timer', setTimeout(update, 700));
update(false);
// timer function
function tmp() {
clearTimeout(body.data('_field_update_timer'));
body.off('mouseup', tmp);
}
// update function
function update(notimer) {
$(obj.el).focus();
obj.keyDown($.Event("keydown"), {
keyCode : ($(event.target).attr('type') == 'up' ? 38 : 40)
});
if (notimer !== false) $('body').data('_field_update_timer', setTimeout(update, 60));
}
});
pr += helper.width() + 12;
$(obj.el).css('padding-right', pr + 'px');
// remember helper
obj.helpers.arrows = helper;
}
if (obj.options.suffix !== '') {
// remove if already displayed
if (obj.helpers.suffix) $(obj.helpers.suffix).remove();
// add fresh
$(obj.el).after(
'<div class="w2ui-field-helper">'+
obj.options.suffix +
'</div>');
helper = $(obj.el).next();
helper
.css({
'color' : $(obj.el).css('color'),
'font-family' : $(obj.el).css('font-family'),
'font-size' : $(obj.el).css('font-size'),
'padding-top' : $(obj.el).css('padding-top'),
'padding-bottom' : $(obj.el).css('padding-bottom'),
'padding-left' : '3px',
'padding-right' : $(obj.el).css('padding-right'),
'margin-top' : (parseInt($(obj.el).css('margin-top'), 10) + 2) + 'px',
'margin-bottom' : (parseInt($(obj.el).css('margin-bottom'), 10) + 1) + 'px'
})
.on('click', function (event) {
if (obj.type == 'list') {
$(obj.helpers.focus).find('input').focus();
} else {
$(obj.el).focus();
}
});
helper.css('margin-left', '-'+ (w2utils.getSize(helper, 'width') + parseInt($(obj.el).css('margin-right'), 10) + 2) + 'px');
pr += helper.width() + 3;
$(obj.el).css('padding-right', pr + 'px');
// remember helper
obj.helpers.suffix = helper;
}
}, 1);
},
addFocus: function () {
var obj = this;
var options = this.options;
var width = 0; // 11 - show search icon, 0 do not show
var pholder;
// clean up & init
$(obj.helpers.focus).remove();
// remember original tabindex
var tabIndex = $(obj.el).attr('tabIndex');
if (tabIndex && tabIndex != -1) obj.el._tabIndex = tabIndex;
if (obj.el._tabIndex) tabIndex = obj.el._tabIndex;
// build helper
var html =
'<div class="w2ui-field-helper">'+
' <div class="w2ui-icon icon-search" style="opacity: 0"></div>'+
' <input type="text" autocomplete="off" tabIndex="'+ tabIndex +'"/>'+
'</div>';
$(obj.el).attr('tabindex', -1).before(html);
var helper = $(obj.el).prev();
obj.helpers.focus = helper;
helper.css({
width : $(obj.el).width(),
"margin-top" : $(obj.el).css('margin-top'),
"margin-left" : (parseInt($(obj.el).css('margin-left')) + parseInt($(obj.el).css('padding-left'))) + 'px',
"margin-bottom" : $(obj.el).css('margin-bottom'),
"margin-right" : $(obj.el).css('margin-right')
})
.find('input')
.css({
cursor : 'default',
width : '100%',
outline : 'none',
opacity : 1,
margin : 0,
border : '1px solid transparent',
padding : $(obj.el).css('padding-top'),
"padding-left" : 0,
"margin-left" : (width > 0 ? width + 6 : 0),
"background-color" : 'transparent'
});
// INPUT events
helper.find('input')
.on('click', function (event) {
if ($('#w2ui-overlay').length == 0) obj.focus(event);
event.stopPropagation();
})
.on('focus', function (event) {
pholder = $(obj.el).attr('placeholder');
$(obj.el).css({ 'outline': 'auto 5px #7DB4F3', 'outline-offset': '-2px' });
$(this).val('');
$(obj.el).triggerHandler('focus');
if (event.stopPropagation) event.stopPropagation(); else event.cancelBubble = true;
})
.on('blur', function (event) {
$(obj.el).css('outline', 'none');
$(this).val('');
obj.refresh();
$(obj.el).triggerHandler('blur');
if (event.stopPropagation) event.stopPropagation(); else event.cancelBubble = true;
if (pholder != null) $(obj.el).attr('placeholder', pholder);
})
.on('keydown', function (event) {
var el = this;
obj.keyDown(event);
setTimeout(function () {
if (el.value == '') $(obj.el).attr('placeholder', pholder); else $(obj.el).attr('placeholder', '');
}, 10);
})
.on('keyup', function (event) { obj.keyUp(event); })
.on('keypress', function (event) { obj.keyPress(event); });
// MAIN div
helper.on('click', function (event) { $(this).find('input').focus(); });
obj.refresh();
},
addMulti: function () {
var obj = this;
var options = this.options;
// clean up & init
$(obj.helpers.multi).remove();
// build helper
var html = '';
var margin =
'margin-top : 0px; ' +
'margin-bottom : 0px; ' +
'margin-left : ' + $(obj.el).css('margin-left') + '; ' +
'margin-right : ' + $(obj.el).css('margin-right') + '; '+
'width : ' + (w2utils.getSize(obj.el, 'width')
- parseInt($(obj.el).css('margin-left'), 10)
- parseInt($(obj.el).css('margin-right'), 10))
+ 'px;';
if (obj.type == 'enum') {
html = '<div class="w2ui-field-helper w2ui-list" style="'+ margin + '; box-sizing: border-box">'+
' <div style="padding: 0px; margin: 0px; display: inline-block" class="w2ui-multi-items">'+
' <ul>'+
' <li style="padding-left: 0px; padding-right: 0px" class="nomouse">'+
' <input type="text" style="width: 20px; margin: -3px 0 0; padding: 2px 0; border-color: white" autocomplete="off" '+ ($(obj.el).attr('readonly') ? 'readonly': '') + '/>'+
' </li>'+
' </ul>'+
' </div>'+
'</div>';
}
if (obj.type == 'file') {
html = '<div class="w2ui-field-helper w2ui-list" style="'+ margin + '; box-sizing: border-box">'+
' <div style="position: absolute; left: 0px; right: 0px; top: 0px; bottom: 0px;">'+
' <input class="file-input" type="file" style="width: 100%; height: 100%; opacity: 0;" name="attachment" multiple tabindex="-1"/>'+
' </div>'+
' <div style="position: absolute; padding: 0px; margin: 0px; display: inline-block" class="w2ui-multi-items">'+
' <ul><li style="padding-left: 0px; padding-right: 0px" class="nomouse"></li></ul>'+
' </div>'+
'</div>';
}
// old bg and boder
var tmp = $(obj.el).data('tmp') || {};
tmp['old-background-color'] = $(obj.el).css('background-color');
tmp['old-border-color'] = $(obj.el).css('border-color');
$(obj.el).data('tmp', tmp);
$(obj.el)
.before(html)
.css({
'background-color' : 'transparent',
'border-color' : 'transparent'
});
var div = $(obj.el).prev();
obj.helpers.multi = div;
if (obj.type == 'enum') {
$(obj.el).attr('tabindex', -1);
// INPUT events
div.find('input')
.on('click', function (event) {
if ($('#w2ui-overlay').length == 0) obj.focus(event);
$(obj.el).triggerHandler('click');
})
.on('focus', function (event) {
$(div).css({ 'outline': 'auto 5px #7DB4F3', 'outline-offset': '-2px' });
$(obj.el).triggerHandler('focus');
if (event.stopPropagation) event.stopPropagation(); else event.cancelBubble = true;
})
.on('blur', function (event) {
$(div).css('outline', 'none');
$(obj.el).triggerHandler('blur');
if (event.stopPropagation) event.stopPropagation(); else event.cancelBubble = true;
})
.on('keyup', function (event) { obj.keyUp(event); })
.on('keydown', function (event) { obj.keyDown(event); })
.on('keypress', function (event) { obj.keyPress(event); });
// MAIN div
div.on('click', function (event) { $(this).find('input').focus(); });
}
if (obj.type == 'file') {
$(obj.el).css('outline', 'none');
div.on('click', function (event) {
$(obj.el).focus();
if ($(obj.el).attr('readonly')) return;
obj.blur(event);
obj.resize();
setTimeout(function () { div.find('input').click(); }, 10); // needed this when clicked on items div
})
.on('dragenter', function (event) {
if ($(obj.el).attr('readonly')) return;
$(div).addClass('w2ui-file-dragover');
})
.on('dragleave', function (event) {
if ($(obj.el).attr('readonly')) return;
var tmp = $(event.target).parents('.w2ui-field-helper');
if (tmp.length == 0) $(div).removeClass('w2ui-file-dragover');
})
.on('drop', function (event) {
if ($(obj.el).attr('readonly')) return;
$(div).removeClass('w2ui-file-dragover');
var files = event.originalEvent.dataTransfer.files;
for (var i = 0, l = files.length; i < l; i++) obj.addFile.call(obj, files[i]);
// cancel to stop browser behaviour
event.preventDefault();
event.stopPropagation();
})
.on('dragover', function (event) {
// cancel to stop browser behaviour
event.preventDefault();
event.stopPropagation();
});
div.find('input')
.on('click', function (event) {
event.stopPropagation();
})
.on('change', function () {
if (typeof this.files !== "undefined") {
for (var i = 0, l = this.files.length; i < l; i++) {
obj.addFile.call(obj, this.files[i]);
}
}
});
}
obj.refresh();
},
addFile: function (file) {
var obj = this;
var options = this.options;
var selected = $(obj.el).data('selected');
var newItem = {
name : file.name,
type : file.type,
modified : file.lastModifiedDate,
size : file.size,
content : null,
file : file
};
var size = 0;
var cnt = 0;
var err;
for (var s in selected) {
// check for dups
if (selected[s].name == file.name && selected[s].size == file.size) return;
size += selected[s].size; cnt++;
}
// trigger event
var eventData = obj.trigger({ phase: 'before', type: 'add', target: obj.el, file: newItem, total: cnt, totalSize: size });
if (eventData.isCancelled === true) return;
// check params
if (options.maxFileSize !== 0 && newItem.size > options.maxFileSize) {
err = 'Maximum file size is '+ w2utils.formatSize(options.maxFileSize);
if (options.silent === false) $(obj.el).w2tag(err);
console.log('ERROR: '+ err);
return;
}
if (options.maxSize !== 0 && size + newItem.size > options.maxSize) {
err = 'Maximum total size is '+ w2utils.formatSize(options.maxSize);
if (options.silent === false) $(obj.el).w2tag(err);
console.log('ERROR: '+ err);
return;
}
if (options.max !== 0 && cnt >= options.max) {
err = 'Maximum number of files is '+ options.max;
if (options.silent === false) $(obj.el).w2tag(err);
console.log('ERROR: '+ err);
return;
}
selected.push(newItem);
// read file as base64
if (typeof FileReader !== "undefined") {
var reader = new FileReader();
// need a closure
reader.onload = (function () {
return function (event) {
var fl = event.target.result;
var ind = fl.indexOf(',');
newItem.content = fl.substr(ind+1);
obj.refresh();
$(obj.el).trigger('change');
// event after
obj.trigger($.extend(eventData, { phase: 'after' }));
};
})();
reader.readAsDataURL(file);
} else {
obj.refresh();
$(obj.el).trigger('change');
}
},
normMenu: function (menu) {
if ($.isArray(menu)) {
for (var m = 0; m < menu.length; m++) {
if (typeof menu[m] == 'string') {
menu[m] = { id: menu[m], text: menu[m] };
} else {
if (menu[m].text != null && menu[m].id == null) menu[m].id = menu[m].text;
if (menu[m].text == null && menu[m].id != null) menu[m].text = menu[m].id;
if (menu[m].caption != null) menu[m].text = menu[m].caption;
}
}
return menu;
} else if (typeof menu == 'function') {
return this.normMenu(menu());
} else if (typeof menu == 'object') {
var tmp = [];
for (var m in menu) tmp.push({ id: m, text: menu[m] });
return tmp;
}
},
getMonthHTML: function (month, year, selected) {
var td = new Date();
var months = w2utils.settings.fullmonths;
var daysCount = ['31', '28', '31', '30', '31', '30', '31', '31', '30', '31', '30', '31'];
var today = td.getFullYear() + '/' + (Number(td.getMonth()) + 1) + '/' + td.getDate();
var days = w2utils.settings.fulldays.slice(); // creates copy of the array
var sdays = w2utils.settings.shortdays.slice(); // creates copy of the array
if (w2utils.settings.weekStarts != 'M') {
days.unshift(days.pop());
sdays.unshift(sdays.pop());
}
var options = this.options;
if (options == null) options = {};
// normalize date
year = w2utils.isInt(year) ? parseInt(year) : td.getFullYear();
month = w2utils.isInt(month) ? parseInt(month) : td.getMonth() + 1;
if (month > 12) { month -= 12; year++; }
if (month < 1 || month === 0) { month += 12; year--; }
if (year/4 == Math.floor(year/4)) { daysCount[1] = '29'; } else { daysCount[1] = '28'; }
options.current = month + '/' + year;
// start with the required date
td = new Date(year, month-1, 1);
var weekDay = td.getDay();
var dayTitle = '';
for (var i = 0; i < sdays.length; i++) dayTitle += '<td title="'+ days[i] +'">' + sdays[i] + '</td>';
var html =
'<div class="w2ui-calendar-title title">'+
' <div class="w2ui-calendar-previous previous"> <div></div> </div>'+
' <div class="w2ui-calendar-next next"> <div></div> </div> '+
months[month-1] +', '+ year +
'</div>'+
'<table class="w2ui-calendar-days" cellspacing="0"><tbody>'+
' <tr class="w2ui-day-title">' + dayTitle + '</tr>'+
' <tr>';
var day = 1;
if (w2utils.settings.weekStarts != 'M') weekDay++;
if(this.type === 'datetime') {
var dt_sel = (w2utils.use_momentjs ? w2utils.isDateTime(selected, options.format_mjs, true) : w2utils.isDateTime(selected, options.format, true));
selected = w2utils.formatDate(dt_sel, w2utils.settings.date_format);
}
for (var ci = 1; ci < 43; ci++) {
if (weekDay === 0 && ci == 1) {
for (var ti = 0; ti < 6; ti++) html += '<td class="w2ui-day-empty"> </td>';
ci += 6;
} else {
if (ci < weekDay || day > daysCount[month-1]) {
html += '<td class="w2ui-day-empty"> </td>';
if ((ci) % 7 === 0) html += '</tr><tr>';
continue;
}
}
var dt = year + '/' + month + '/' + day;
var DT = new Date(dt);
var className = '';
if (DT.getDay() == 6) className = ' w2ui-saturday';
if (DT.getDay() == 0) className = ' w2ui-sunday';
if (dt == today) className += ' w2ui-today';
var dspDay = day;
var col = '';
var bgcol = '';
var tmp_dt, tmp_dt_fmt;
if(this.type === 'datetime') {
tmp_dt = w2utils.formatDateTime(dt, options.format);
tmp_dt_fmt = w2utils.formatDate(dt, w2utils.settings.date_format);
} else {
tmp_dt = w2utils.formatDate(dt, options.format);
tmp_dt_fmt = tmp_dt;
}
if (options.colored && options.colored[tmp_dt_fmt] !== undefined) { // if there is predefined colors for dates
var tmp = options.colored[tmp_dt_fmt].split(':');
bgcol = 'background-color: ' + tmp[0] + ';';
col = 'color: ' + tmp[1] + ';';
}
html += '<td class="'+ (this.inRange(tmp_dt) ? 'w2ui-date ' + (tmp_dt_fmt == selected ? 'w2ui-date-selected' : '') : 'w2ui-blocked') + className + '" '+
' style="'+ col + bgcol + '" date="'+ tmp_dt +'" data-date="'+ DT +'">'+
dspDay +
'</td>';
if (ci % 7 === 0 || (weekDay === 0 && ci == 1)) html += '</tr><tr>';
day++;
}
html += '</tr></tbody></table>';
return html;
},
getYearHTML: function () {
var months = w2utils.settings.shortmonths;
var start_year = w2utils.settings.dateStartYear;
var end_year = w2utils.settings.dateEndYear;
var mhtml = '';
var yhtml = '';
for (var m = 0; m < months.length; m++) {
mhtml += '<div class="w2ui-jump-month" name="'+ m +'">'+ months[m] + '</div>';
}
for (var y = start_year; y <= end_year; y++) {
yhtml += '<div class="w2ui-jump-year" name="'+ y +'">'+ y + '</div>';
}
return '<div>'+ mhtml +'</div><div>'+ yhtml +'</div>';
},
getHourHTML: function () {
var tmp = [];
var options = this.options;
if (options == null) options = { format: w2utils.settings.time_format };
var h24 = (options.format.indexOf('h24') > -1);
for (var a = 0; a < 24; a++) {
var time = (a >= 12 && !h24 ? a - 12 : a) + ':00' + (!h24 ? (a < 12 ? ' am' : ' pm') : '');
if (a == 12 && !h24) time = '12:00 pm';
if (!tmp[Math.floor(a/8)]) tmp[Math.floor(a/8)] = '';
var tm1 = this.fromMin(this.toMin(time));
var tm2 = this.fromMin(this.toMin(time) + 59);
tmp[Math.floor(a/8)] += '<div class="'+ ((this.type === 'datetime') || this.inRange(tm1) || this.inRange(tm2) ? 'w2ui-time ' : 'w2ui-blocked') + '" hour="'+ a +'">'+ time +'</div>';
}
var html =
'<div class="w2ui-calendar-time"><table><tbody><tr>'+
' <td>'+ tmp[0] +'</td>' +
' <td>'+ tmp[1] +'</td>' +
' <td>'+ tmp[2] +'</td>' +
'</tr></tbody></table></div>';
return html;
},
getMinHTML: function (hour) {
if (hour == null) hour = 0;
var options = this.options;
if (options == null) options = { format: w2utils.settings.time_format };
var h24 = (options.format.indexOf('h24') > -1);
var tmp = [];
for (var a = 0; a < 60; a += 5) {
var time = (hour > 12 && !h24 ? hour - 12 : hour) + ':' + (a < 10 ? 0 : '') + a + ' ' + (!h24 ? (hour < 12 ? 'am' : 'pm') : '');
var ind = a < 20 ? 0 : (a < 40 ? 1 : 2);
if (!tmp[ind]) tmp[ind] = '';
tmp[ind] += '<div class="'+ ((this.type === 'datetime') || this.inRange(time) ? 'w2ui-time ' : 'w2ui-blocked') + '" min="'+ a +'">'+ time +'</div>';
}
var html =
'<div class="w2ui-calendar-time"><table><tbody><tr>'+
' <td>'+ tmp[0] +'</td>' +
' <td>'+ tmp[1] +'</td>' +
' <td>'+ tmp[2] +'</td>' +
'</tr></tbody></table></div>';
return html;
},
toMin: function (str) {
if (typeof str != 'string') return null;
var tmp = str.split(':');
if (tmp.length == 2) {
tmp[0] = parseInt(tmp[0]);
tmp[1] = parseInt(tmp[1]);
if (str.indexOf('pm') != -1 && tmp[0] != 12) tmp[0] += 12;
} else {
return null;
}
return tmp[0] * 60 + tmp[1];
},
fromMin: function (time) {
var ret = '';
if (time >= 24 * 60) time = time % (24 * 60);
if (time < 0) time = 24 * 60 + time;
var hour = Math.floor(time/60);
var min = ((time % 60) < 10 ? '0' : '') + (time % 60);
var options = this.options;
if (options == null) options = { format: w2utils.settings.time_format };
if (options.format.indexOf('h24') != -1) {
ret = hour + ':' + min;
} else {
ret = (hour <= 12 ? hour : hour - 12) + ':' + min + ' ' + (hour >= 12 ? 'pm' : 'am');
}
return ret;
}
};
$.extend(w2field.prototype, w2utils.event);
w2obj.field = w2field;
}) (jQuery);
|
/**
* Default model configuration
* (sails.config.models)
*
* Unless you override them, the following properties will be included
* in each of your models.
*
* For more info on Sails models, see:
* http://sailsjs.org/#!/documentation/concepts/ORM
*/
module.exports.models = {
/***************************************************************************
* *
* Your app's default connection. i.e. the name of one of your app's *
* connections (see `config/connections.js`) *
* *
***************************************************************************/
// connection: 'localDiskDb',
/***************************************************************************
* *
* How and whether Sails will attempt to automatically rebuild the *
* tables/collections/etc. in your schema. *
* *
* See http://sailsjs.org/#!/documentation/concepts/ORM/model-settings.html *
* *
***************************************************************************/
autoPK: false,
migrate: 'drop'
};
|
/*jslint indent: 4, nomen: true */
/*global require, module, exports, process */
(function () {
'use strict';
var Path = require('path'),
utils = {
dirname: function (base, sep) {
if (arguments.length < 2) {
base = Path.normalize(base);
}
sep = sep || Path.sep;
var result, reg,
ps = (sep === '\\') ? '\\\\' : '/';
reg = new RegExp(ps + '(?:.(?!' + ps + '))+$', 'gi');
result = base.match(reg);
return result[0].replace(sep, '');
},
stats: function (stats) {
return {
dev: stats.dev,
ino: stats.ino,
uid: stats.uid,
gid: stats.gid,
rdev: stats.rdev,
size: stats.size,
mode: stats.mode,
nlink: stats.nlink,
blocks: stats.blocks || false,
blksize: stats.blksize || false,
atime: Date.parse(stats.atime),
mtime: Date.parse(stats.mtime),
ctime: Date.parse(stats.ctime),
birthtime: Date.parse(stats.birthtime)
};
}
};
module.exports = utils;
}());
|
'use strict'
const api = require('../api')
const { logger, Maybe } = require('../utils')
const getProject = async projectSlugOrId => {
const project = await api.projects.find(projectSlugOrId)
if (!project.hasValue) {
logger.error(`Project '${projectSlugOrId}' not found`)
return Maybe.none()
}
const { id: projectId, name: projectName, variableSetId, deploymentProcessId } = project.value
if (!variableSetId) {
logger.error(`VariableSetId is not set on project '${projectId}' (${projectName})`)
return Maybe.none()
}
if (!deploymentProcessId) {
logger.error(`DeploymentProcessId is not set on project '${projectId}' (${projectName})`)
return Maybe.none()
}
logger.info(`Found project '${projectId}' (${projectName})`)
return project
}
module.exports.execute = getProject
|
const plugin = () => {
return {
fieldLabel: field => {
if (!field.label) {
return field.key;
}
return field.label;
},
};
};
//CUT
console.info(plugin);
//CUT
|
(function(){
'use strict';
var app = angular.module('users');
app.component('changePasswordComponent', {
bindings: {},
templateUrl: 'modules/users/client/views/settings/change-password.client.view.html',
controller: changePasswordComponent
});
changePasswordComponent.$inject = ['$scope', '$http', '$state', '$timeout',
'Authentication', 'PasswordValidator', 'SendMailService', 'CommonService'];
function changePasswordComponent($scope, $http, $state, $timeout,
Authentication, PasswordValidator, SendMailService, CommonService) {
var sendMail = SendMailService.sendMail;
var logger = CommonService.printToLogger;
$scope.user = Authentication.user;
$scope.popoverMsg = PasswordValidator.getPopoverMsg();
$scope.isGuest = false;
if (Authentication.user && Authentication.user.roles.indexOf('user') === -1) {
$scope.passwordDetails = { currentPassword: '' };
$scope.isGuest = true;
}
// Change user password
$scope.changeUserPassword = function (isValid) {
$scope.success = $scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'passwordForm');
return false;
}
$http.post('/api/users/password', $scope.passwordDetails).success(function (response) {
// If successful show success message and clear form
$scope.$broadcast('show-errors-reset', 'passwordForm');
$scope.success = true;
$scope.passwordDetails = null;
if ($scope.isGuest) {
$timeout(function () {
// Update user authentication
$http.get('/api/users/me', $scope.user).success(function (response) {
// If successful we assign the response to the global user model
$scope.user = Authentication.user = response;
sendMailToUser();
// Do not redirect to the password page
if ($state.first.state.name !== 'settings.password'){
$state.go($state.first.state.name , $state.first.params);
} else {
// And redirect to the previous state or home page
$state.go($state.previous.state.name || 'home', $state.previous.params);
}
}).error(function (response) {
$scope.error = response.message;
});
}, 2000);
}
}).error(function (response) {
$scope.error = response.message;
});
};
function sendMailToUser() {
// Prepare the mail details
// you can send a full email template through 'html' property or
// an email content that generated by the server
var mailContent = {
mailTo: Authentication.user.email,
subject: 'Welcome to TomMMS',
name: Authentication.user.displayName,
content: 'Welcome to TomMMS! ' +
'Thanks so much for joining us. ' +
'You are on your way to super-productivity and beyond!'
};
// Send the mail
sendMail(mailContent);
}
}
})();
|
var sleep = require('sleep');
var gpio = require("gpio");
var intervalTimer;
buzzer = gpio.export(17, {
// When you export a pin, the default direction is out. This allows you to set
// the pin value to either LOW or HIGH (3.3V) from your program.
direction: 'out',
// set the time interval (ms) between each read when watching for value changes
// note: this is default to 100, setting value too low will cause high CPU usage
interval: 200,
// Due to the asynchronous nature of exporting a header, you may not be able to
// read or write to the header right away. Place your logic in this ready
// function to guarantee everything will get fired properly
ready: function() {
intervalTimer = setInterval(function() {
buzzer.set();
console.log("buzzing!!!");
setTimeout(function() {
console.log("silent");
buzzer.reset();
}, 500);
}, 1000);
}
});
// reset the headers and unexport after 10 seconds
setTimeout(function() {
clearInterval(intervalTimer); // stops the voltage cycling
buzzer.removeAllListeners('change'); // unbinds change event
buzzer.reset(); // sets header to low
buzzer.unexport(function() {
console.log("exit");
// unexport takes a callback which gets fired as soon as unexporting is done
process.exit(); // exits your node program
});
}, 10000) |
(function() {
"use strict";
var AmCharts = window.AmCharts;
AmCharts.Cuboid = AmCharts.Class({
construct: function(container, width, height, dx, dy, colors, alpha, bwidth, bcolor, balpha, gradientRotation, cornerRadius, rotate, dashLength, pattern, topRadius, bcn) {
var _this = this;
_this.set = container.set();
_this.container = container;
_this.h = Math.round(height);
_this.w = Math.round(width);
_this.dx = dx;
_this.dy = dy;
_this.colors = colors;
_this.alpha = alpha;
_this.bwidth = bwidth;
_this.bcolor = bcolor;
_this.balpha = balpha;
_this.dashLength = dashLength;
_this.topRadius = topRadius;
_this.pattern = pattern;
_this.rotate = rotate;
_this.bcn = bcn;
if (rotate) {
if (width < 0 && gradientRotation === 0) {
gradientRotation = 180;
}
} else {
if (height < 0) {
if (gradientRotation == 270) {
gradientRotation = 90;
}
}
}
_this.gradientRotation = gradientRotation;
if (dx === 0 && dy === 0) {
_this.cornerRadius = cornerRadius;
}
_this.draw();
},
draw: function() {
var _this = this;
var set = _this.set;
set.clear();
var container = _this.container;
var chart = container.chart;
var w = _this.w;
var h = _this.h;
var dx = _this.dx;
var dy = _this.dy;
var colors = _this.colors;
var alpha = _this.alpha;
var bwidth = _this.bwidth;
var bcolor = _this.bcolor;
var balpha = _this.balpha;
var gradientRotation = _this.gradientRotation;
var cornerRadius = _this.cornerRadius;
var dashLength = _this.dashLength;
var pattern = _this.pattern;
var topRadius = _this.topRadius;
var bcn = _this.bcn;
// bot
var firstColor = colors;
var lastColor = colors;
if (typeof(colors) == "object") {
firstColor = colors[0];
lastColor = colors[colors.length - 1];
}
var bottom;
var back;
var backBorders;
var lside;
var rside;
var rsideBorders;
var top;
var topBorders;
var bottomBorders;
// if dx or dx > 0, draw other sides
var tempAlpha = alpha;
if (pattern) {
alpha = 0;
}
var brX;
var brY;
var trX;
var trY;
var rotate = _this.rotate;
if (Math.abs(dx) > 0 || Math.abs(dy) > 0) {
// cylinder
if (!isNaN(topRadius)) {
var bx;
var by;
var tx;
var ty;
if (rotate) {
by = h / 2;
bx = dx / 2;
ty = h / 2;
tx = w + dx / 2;
brY = Math.abs(h / 2);
brX = Math.abs(dx / 2);
} else {
bx = w / 2;
by = dy / 2;
tx = w / 2;
ty = h + dy / 2 + 1;
brX = Math.abs(w / 2);
brY = Math.abs(dy / 2);
}
trX = brX * topRadius;
trY = brY * topRadius;
// draw bottom and top elipses
if (brX > 0.1 && brX > 0.1) {
bottom = AmCharts.circle(container, brX, firstColor, alpha, bwidth, bcolor, balpha, false, brY);
bottom.translate(bx, by);
}
if (trX > 0.1 && trX > 0.1) {
top = AmCharts.circle(container, trX, AmCharts.adjustLuminosity(firstColor, 0.5), alpha, bwidth, bcolor, balpha, false, trY);
top.translate(tx, ty);
}
}
// cuboid
else {
var bc = lastColor;
var ccc = AmCharts.adjustLuminosity(firstColor, -0.2);
var tc = firstColor;
ccc = AmCharts.adjustLuminosity(tc, -0.2);
bottom = AmCharts.polygon(container, [0, dx, w + dx, w, 0], [0, dy, dy, 0, 0], ccc, alpha, 1, bcolor, 0, gradientRotation);
if (balpha > 0) {
bottomBorders = AmCharts.line(container, [0, dx, w + dx], [0, dy, dy], bcolor, balpha, bwidth, dashLength);
}
// back
back = AmCharts.polygon(container, [0, 0, w, w, 0], [0, h, h, 0, 0], ccc, alpha, 1, bcolor, 0, gradientRotation);
back.translate(dx, dy);
// back borders
if (balpha > 0) {
backBorders = AmCharts.line(container, [dx, dx], [dy, dy + h], bcolor, balpha, bwidth, dashLength);
}
// left side
lside = AmCharts.polygon(container, [0, 0, dx, dx, 0], [0, h, h + dy, dy, 0], ccc, alpha, 1, bcolor, 0, gradientRotation);
// right side
rside = AmCharts.polygon(container, [w, w, w + dx, w + dx, w], [0, h, h + dy, dy, 0], ccc, alpha, 1, bcolor, 0, gradientRotation);
// right side borders
if (balpha > 0) {
rsideBorders = AmCharts.line(container, [w, w + dx, w + dx, w], [0, dy, h + dy, h], bcolor, balpha, bwidth, dashLength);
}
//}
ccc = AmCharts.adjustLuminosity(bc, 0.2);
top = AmCharts.polygon(container, [0, dx, w + dx, w, 0], [h, h + dy, h + dy, h, h], ccc, alpha, 1, bcolor, 0, gradientRotation);
// bot borders
if (balpha > 0) {
topBorders = AmCharts.line(container, [0, dx, w + dx], [h, h + dy, h + dy], bcolor, balpha, bwidth, dashLength);
}
}
}
alpha = tempAlpha;
if (Math.abs(h) < 1) {
h = 0;
}
if (Math.abs(w) < 1) {
w = 0;
}
var front;
// cylinder
if (!isNaN(topRadius) && (Math.abs(dx) > 0 || Math.abs(dy) > 0)) {
colors = [firstColor];
var attr = {
"fill": colors,
"stroke": bcolor,
"stroke-width": bwidth,
"stroke-opacity": balpha,
"fill-opacity": alpha
};
var comma = ",";
var path;
var tCenter;
var gradAngle;
var al;
if (rotate) {
tCenter = (h / 2 - h / 2 * topRadius);
path = "M" + 0 + comma + 0 + " L" + w + comma + tCenter;
al = " B";
if (w > 0) {
al = " A";
}
if (AmCharts.VML) {
path += al + Math.round(w - trX) + comma + Math.round(h / 2 - trY) + comma + Math.round(w + trX) + comma + Math.round(h / 2 + trY) + comma + w + comma + 0 + comma + w + comma + h;
path += " L" + 0 + comma + h;
path += al + Math.round(-brX) + comma + Math.round(h / 2 - brY) + comma + Math.round(brX) + comma + Math.round(h / 2 + brY) + comma + 0 + comma + h + comma + 0 + comma + 0;
} else {
path += "A" + trX + comma + trY + comma + 0 + comma + 0 + comma + 0 + comma + w + comma + (h - h / 2 * (1 - topRadius)) + "L" + 0 + comma + h;
path += "A" + brX + comma + brY + comma + 0 + comma + 0 + comma + 1 + comma + 0 + comma + 0;
}
gradAngle = 90;
} else {
tCenter = (w / 2 - w / 2 * topRadius);
path = "M" + 0 + comma + 0 + " L" + tCenter + comma + h;
if (AmCharts.VML) {
path = "M" + 0 + comma + 0 + " L" + tCenter + comma + h;
al = " B";
if (h < 0) {
al = " A";
}
path += al + Math.round(w / 2 - trX) + comma + Math.round(h - trY) + comma + Math.round(w / 2 + trX) + comma + Math.round(h + trY) + comma + 0 + comma + h + comma + w + comma + h;
path += " L" + w + comma + 0;
path += al + Math.round(w / 2 + brX) + comma + Math.round(brY) + comma + Math.round(w / 2 - brX) + comma + Math.round(-brY) + comma + w + comma + 0 + comma + 0 + comma + 0;
} else {
path += "A" + trX + comma + trY + comma + 0 + comma + 0 + comma + 0 + comma + (w - w / 2 * (1 - topRadius)) + comma + h + "L" + w + comma + 0;
path += "A" + brX + comma + brY + comma + 0 + comma + 0 + comma + 1 + comma + 0 + comma + 0;
}
gradAngle = 180;
}
front = container.path(path).attr(attr);
front.gradient("linearGradient", [firstColor, AmCharts.adjustLuminosity(firstColor, -0.3), AmCharts.adjustLuminosity(firstColor, -0.3), firstColor], gradAngle);
if (rotate) {
front.translate(dx / 2, 0);
} else {
front.translate(0, dy / 2);
}
} else {
if (h === 0) {
front = AmCharts.line(container, [0, w], [0, 0], bcolor, balpha, bwidth, dashLength);
} else if (w === 0) {
front = AmCharts.line(container, [0, 0], [0, h], bcolor, balpha, bwidth, dashLength);
} else {
if (cornerRadius > 0) {
front = AmCharts.rect(container, w, h, colors, alpha, bwidth, bcolor, balpha, cornerRadius, gradientRotation, dashLength);
} else {
front = AmCharts.polygon(container, [0, 0, w, w, 0], [0, h, h, 0, 0], colors, alpha, bwidth, bcolor, balpha, gradientRotation, false, dashLength);
}
}
}
var elements;
if (!isNaN(topRadius)) {
if (rotate) {
if (w > 0) {
elements = [bottom, front, top];
} else {
elements = [top, front, bottom];
}
} else {
if (h < 0) {
elements = [bottom, front, top];
} else {
elements = [top, front, bottom];
}
}
} else {
if (h < 0) {
elements = [bottom, bottomBorders, back, backBorders, lside, rside, rsideBorders, top, topBorders, front];
} else {
elements = [top, topBorders, back, backBorders, lside, rside, bottom, bottomBorders, rsideBorders, front];
}
}
AmCharts.setCN(chart, front, bcn + "front");
AmCharts.setCN(chart, back, bcn + "back");
AmCharts.setCN(chart, top, bcn + "top");
AmCharts.setCN(chart, bottom, bcn + "bottom");
AmCharts.setCN(chart, lside, bcn + "left");
AmCharts.setCN(chart, rside, bcn + "right");
var i;
for (i = 0; i < elements.length; i++) {
var el = elements[i];
if (el) {
set.push(el);
AmCharts.setCN(chart, el, bcn + "element");
}
}
if (pattern) {
front.pattern(pattern, NaN, chart.path);
}
},
width: function(v) {
if (isNaN(v)) {
v = 0;
}
var _this = this;
_this.w = Math.round(v);
_this.draw();
},
height: function(v) {
if (isNaN(v)) {
v = 0;
}
var _this = this;
_this.h = Math.round(v);
_this.draw();
},
animateHeight: function(duration, easingFunction) {
var _this = this;
_this.animationFinished = false;
_this.easing = easingFunction;
_this.totalFrames = duration * AmCharts.updateRate;
_this.rh = _this.h;
_this.frame = 0;
_this.height(1);
setTimeout(function() {
_this.updateHeight.call(_this);
}, 1000 / AmCharts.updateRate);
},
updateHeight: function() {
var _this = this;
_this.frame++;
var totalFrames = _this.totalFrames;
if (_this.frame <= totalFrames) {
var value = _this.easing(0, _this.frame, 1, _this.rh - 1, totalFrames);
_this.height(value);
if (window.requestAnimationFrame) {
window.requestAnimationFrame(function() {
_this.updateHeight.call(_this);
});
} else {
setTimeout(function() {
_this.updateHeight.call(_this);
}, 1000 / AmCharts.updateRate);
}
} else {
_this.height(_this.rh);
_this.animationFinished = true;
}
},
animateWidth: function(duration, easingFunction) {
var _this = this;
_this.animationFinished = false;
_this.easing = easingFunction;
_this.totalFrames = duration * AmCharts.updateRate;
_this.rw = _this.w;
_this.frame = 0;
_this.width(1);
setTimeout(function() {
_this.updateWidth.call(_this);
}, 1000 / AmCharts.updateRate);
},
updateWidth: function() {
var _this = this;
_this.frame++;
var totalFrames = _this.totalFrames;
if (_this.frame <= totalFrames) {
var value = _this.easing(0, _this.frame, 1, _this.rw - 1, totalFrames);
_this.width(value);
if (window.requestAnimationFrame) {
window.requestAnimationFrame(function() {
_this.updateWidth.call(_this);
});
} else {
setTimeout(function() {
_this.updateWidth.call(_this);
}, 1000 / AmCharts.updateRate);
}
} else {
_this.width(_this.rw);
_this.animationFinished = true;
}
}
});
})(); |
'use strict';
/**
* @ngdoc function
* @name wwwApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the wwwApp
*/
angular.module('myApp')
.controller('TreeCtrl', function () {
this.treeOptions = {
accept: function(sourceNodeScope, destNodesScope, destIndex) {
return true;
}
};
this.treeConfig = {
defaultCollapsed : false
}
this.toggle = function (scope) {
scope.toggle();
};
this.list =[
{
title:"Dossier 1",
items:[
{title:"Dossier 1.1"},
{title:"Dossier 1.2"},
{title:"Dossier 1.3"}
]
},
{title:"Dossier 2",
items:[
{title:"Dossier 2.1",
items:[
{title:"Dossier 2.1.1"},
{title:"Dossier 2.1.2"},
{title:"Dossier 2.1.3"}
]},
{title:"Dossier 2.2"},
{title:"Dossier 2.3"}
]
},
{title:"Dossier 3"}
];
this.nodes =[
{
title:"Dossier 1",
nodes:[
{title:"Dossier 1.1"},
{title:"Dossier 1.2"},
{title:"Dossier 1.3"}
]
},
{title:"Dossier 2",
nodes:[
{title:"Dossier 2.1",
nodes:[
{title:"Dossier 2.1.1"},
{title:"Dossier 2.1.2"},
{title:"Dossier 2.1.3"}
]},
{title:"Dossier 2.2"},
{title:"Dossier 2.3"}
]
},
{title:"Dossier 3"}
];
// alert(JSON.stringify(this));
});
|
/**
* Enemy Entity
*/
game.EnemyEntity = me.ObjectEntity.extend(
{
init: function (x, y, settings)
{
// define this here instead of tiled
settings.image = "wheelie_right";
settings.spritewidth = 32;
// call the parent constructor
this.parent(x, y , settings);
this.startX = x;
this.endX = x+settings.width - settings.spritewidth; // size of sprite
// make him start from the right
this.pos.x = x + settings.width - settings.spritewidth;
this.walkLeft = true;
// walking & jumping speed
this.setVelocity(1, 6);
// make it collidable
this.collidable = true;
this.type = me.game.ENEMY_OBJECT;
// bounding box
//this.updateColRect(-1,0,4,20);
},
onCollision : function (res, obj)
{
// res.y >0 means touched by something on the bottom
// which mean at top position for this one
if (this.alive && (res.y > 0) && obj.falling)
{
//this.renderable.flicker(20);
}
},
// manage the enemy movement
update : function ()
{
// do nothing if not in viewport
if (!this.inViewport)
return false;
if (this.alive)
{
if (this.walkLeft && this.pos.x <= this.startX)
{
this.walkLeft = false;
}
else if (!this.walkLeft && this.pos.x >= this.endX)
{
this.walkLeft = true;
}
this.flipX(this.walkLeft);
this.vel.x += (this.walkLeft) ? -this.accel.x * me.timer.tick : this.accel.x * me.timer.tick;
}
else
{
this.vel.x = 0;
}
// check & update movement
this.updateMovement();
if (this.vel.x!=0 ||this.vel.y!=0)
{
// update the object animation
this.parent();
return true;
}
return false;
}
}); |
'use strict';
var RSVP = require('rsvp');
module.exports = RefCollector;
function RefCollector(excludes) {
if (!(this instanceof RefCollector)) {
return new RefCollector(excludes);
}
this.excludes = excludes || [];
this.selector = null;
this.refAttr = null;
}
RefCollector.prototype.exclude = function(ref) {
return this.excludes.some(function(exclude) {
return exclude.test(ref);
});
};
RefCollector.prototype.process = function(ref, refs) {
if (!this.exclude(ref)) {
refs[ref] = true;
}
};
RefCollector.prototype.collect = function($) {
var refs = {};
return new RSVP.Promise(function(resolve) {
$(this.selector).each(function(index, el) {
var ref = $(el).attr(this.refAttr);
this.process(ref, refs);
}.bind(this));
resolve(Object.keys(refs));
}.bind(this));
};
|
var helpers = require('./helpers'),
ProvidePlugin = require('webpack/lib/ProvidePlugin'),
DefinePlugin = require('webpack/lib/DefinePlugin');
const ENV = process.env.ENV = process.env.NODE_ENV = 'test';
module.exports = {
devtool: 'source-map',
resolve: {
extensions: ['', '.ts', '.js'],
root: helpers.root('src')
},
module: {
preLoaders: [
{ test: /\.ts$/, loader: 'tslint-loader', exclude: [helpers.root('node_modules')] },
{ test: /\.js$/, loader: "source-map-loader", exclude: [helpers.root('node_modules/rxjs')] }
],
loaders: [
{
test: /\.ts$/,
loader: 'awesome-typescript-loader',
query: {
'compilerOptions': {
'removeComments': true
}
},
exclude: [/\.e2e\.ts$/]
},
{ test: /\.json$/, loader: 'json-loader', exclude: [helpers.root('src/index.html')] },
{ test: /\.html$/, loader: 'raw-loader', exclude: [helpers.root('src/index.html')] },
{ test: /\.css$/, loader: 'raw-loader', exclude: [helpers.root('src/index.html')] }
],
postLoaders: [
{
test: /\.(js|ts)$/,
loader: 'istanbul-instrumenter-loader',
include: helpers.root('src'),
exclude: [/\.(e2e|spec)\.ts$/, /node_modules/]
}
]
},
plugins: [new DefinePlugin({ 'ENV': JSON.stringify(ENV), 'HMR': false })],
tslint: {
emitErrors: false,
failOnHint: false,
resourcePath: 'src'
},
node: {
global: 'window',
process: false,
crypto: 'empty',
module: false,
clearImmediate: false,
setImmediate: false
}
}; |
'use strict';
/* App Module */
var phonecatApp = angular.module('phonecatApp', [
'ngRoute',
'phonecatAnimations',
'phonecatControllers',
'phonecatFilters',
'phonecatServices'
]);
phonecatApp.config(['$routeProvider',
function($routeProvider){
$routeProvider.
when('/phones',{
templateUrl: 'partials/phone-list.html',
controller: 'PhoneListCtrl'
}).
when('/phones/:phoneId',{
templateUrl:'partials/phone-detail.html',
controller:'PhoneDetailCtrl'
}).
otherwise({
redirectTo: '/phones'
});
}]); |
$(function () {
var nextRowNum = 1
loadCCs()
$('body').on('change', '.college-select', function () {
clearRows()
loadYears(loadUnis)
nextRowNum = 1
})
$('body').on('change', '.year-select', function () {
clearRows()
loadUnis()
nextRowNum = 1
})
$('body').on('change', '.uni-select', function () {
var rowNum = $(this).attr('class').split('row-')[1].split(' ')[0]
loadMajors(rowNum)
})
$('body').on('click', '.x-container', function () {
var rowNum = $(this).attr('class').split('row-')[1].split(' ')[0]
$('.row-' + rowNum).remove()
})
$('.plus').click(function () {
addRow(nextRowNum++)
loadUnis()
})
$('.find-plan-btn').click(function () {
$('.course-boxes').empty()
addCourses()
$('.courses').css('display', 'inline-block')
})
})
function loadOptions (loadUrl, addSelect, addCondition) {
var selects = $(addSelect)
selects.empty()
if (addCondition) {
selects.append('<option value=""></option>')
$.ajax({
url: loadUrl,
type: 'GET'
}).done(function (data) {
var html = ''
Object.keys(data).forEach(function (key) {
html += '<option value="' + key + '">' + data[key] + '</option>'
})
selects.append(html)
})
}
}
function loadCCs () {
// endpoint for cc list is /ccs/, add items to college select box,
// there is no condition to be met to add the ccs
loadOptions('/ccs/', '.college-select', true)
}
function loadUnis () {
// endpoint for uni list is /unis/cc/, add items to uni select box
// add options only if the non-blank cc option was selected
var url = '/unis/' + $('.college-select').val() + '/' + $('.year-select').val() + '/'
loadOptions(url,
'.uni .select:last-of-type select',
$('.college-select').val() !== ''
)
}
function loadYears (cb) {
var college = $('.college-select').val()
$('.year-select').empty()
if (college === '') {
return
}
$.ajax({
url: '/years/' + college,
type: 'GET'
}).done(function (data) {
var html = ''
data.forEach(function (yr) {
html += '<option value="' + yr + '">' + yr + '</option>'
})
$('.year-select').append(html)
cb()
})
}
function loadMajors (rowNum) {
// accepts a jquery selector for the row
// endpoint for majors is /majors/cc/uni/, add items to major select box
// add options only if non-blank cc and unis were selected
var majorSelect, uniSelect, collegeSelect, yearSelect, url
yearSelect = $('.year-select')
collegeSelect = $('.college-select')
majorSelect = $('.major .row-' + rowNum + ' select')
uniSelect = $('.uni .row-' + rowNum + ' select')
url = '/majors/' + collegeSelect.val() + '/' + yearSelect.val() + '/' +
uniSelect.val()
loadOptions(url,
majorSelect,
$('.college-select').val() !== '' && uniSelect.val() !== ''
)
}
function addRow (rowNum) {
$('.uni').append(
'<div class="x-container row-' + rowNum + '">' +
'<div class="x"> x </div>' +
'</div>' +
'<div class="select row-' + rowNum + '">' +
'<select class="uni-select row-' + rowNum + '"></select>' +
'</div>' +
'</div>' +
'<br class=row-' + rowNum + '>'
)
$('.major').append(
'<div class="select row-' + rowNum + '">' +
'<select class="major-select row-' + rowNum + '"></select>' +
'</div>' +
'<br class=row-' + rowNum + '>'
)
}
function addCourses () {
var uniMajors = ''
$('.uni .select select').each(function () {
var rowNum = $(this).parent().attr('class').split('-')[1]
var uni, major
uni = $(this).val()
major = $('.major .row-' + rowNum + ' select').val()
if (uni !== '' && major !== '') {
uniMajors += uni + ',' + major + '/'
}
})
if (uniMajors !== '') {
var url = '/plan/' + $('.college-select').val() + '/' +
$('.year-select').val() + '/' + uniMajors
$.ajax({
url: url,
type: 'GET'
}).done(function (data) {
keySort(data).forEach(function (crs) {
var units, unis
units = data['courses'][crs]['units']
unis = data['courses'][crs]['unis']
addBox(units, crs, unis)
})
})
}
}
function keySort (data) {
return Object.keys(data['courses']).sort(function (k1, k2) {
// first sort by number of unis requiring the course
if (data['courses'][k1]['unis'].length < data['courses'][k2]['unis'].length) {
return 1
}
if (data['courses'][k1]['unis'].length > data['courses'][k2]['unis'].length) {
return -1
}
// if # of unis is same, sort alphanumerically ('A1' < 'A2' < 'B1')
if (k1 < k2) {
return -1
}
if (k1 > k2) {
return 1
}
return 0
})
}
function addBox (units, name, unis) {
var html =
'<div class="box">' +
'<ul>' +
'<li class="units">' + units + '</li>' +
'<li class="name">' + name + '</li>' +
'<li class="logos">'
unis.forEach(function (uni) {
html += '<img height="25px" src="/logos/' + uni + '.png"></img>'
})
html += '</li></ul></div>'
$('.course-boxes').append(html)
}
function clearRows () {
$('.x-container').remove()
$('.uni-major .select').remove()
$('.uni-major br').remove()
addRow(0)
}
|
/*
Copyright (C) 2016 Adrien THIERRY
http://seraum.com
*/
module.exports = httpRouteEngine;
function httpRouteEngine()
{
var wf = WF();
this.code = function(req, res)
{
var route = wf.Router.match(req);
if(route && route.fn)
{
req.continue = false;
req.param = route.param;
req.splat = route.splat;
var l = route.fn.length;
for(var i = 0; i < l; i++)
route.fn[i](req, res);
}
else if(req.loop == (req.app.length - 1))
{
req.continue = false;
res.end();
}
};
} |
var oo = (function(document){
'use strict';
var _serviceEndpoint = undefined;
var _apiKey = undefined;
var _defaultTimelineOptions = {};
var _defaultPieOptions = {};
var _defaultTableOptions = {};
var _defaultBarOptions = {};
var _defaultColumnOptions = {};
/*
* Binds OOcharts Objects to DOM Elements based on HTML attributes
*/
var _autoBuild = function(){
/*
* Gets all elements containing value for specified attribute
* @param {String} attribute
* @return {Array} matchingElements
*/
var getAllElementsWithAttribute = function(attribute){
var matchingElements = [];
var allElements = document.getElementsByTagName('*');
for (var i = 0; i < allElements.length; i++){
if (allElements[i].getAttribute(attribute)){
matchingElements.push(allElements[i]);
}
}
return matchingElements;
};
// find all oocharts elements
var elements = getAllElementsWithAttribute('data-oochart');
for(var e = 0; e < elements.length; e++){
var _element = elements[e];
//get oocharts data
var type = _element.getAttribute('data-oochart');
var startDate = _element.getAttribute('data-oochart-start-date');
var endDate = _element.getAttribute('data-oochart-end-date');
var profile = _element.getAttribute('data-oochart-profile');
var metric, metricString, metrics, dimension, dimensions, dimensionString, m, d;
// if metric
if(type.toLowerCase() === 'metric'){
metric = new _Metric(profile, startDate, endDate);
metric.setMetric(_element.getAttribute('data-oochart-metric'));
metric.draw(_element);
//if column
} else if (type.toLowerCase() === 'column'){
var column = new _Column(profile, startDate, endDate);
metricString = _element.getAttribute('data-oochart-metrics');
metrics = metricString.split(',');
for(m = 0; m < metrics.length; m++){
column.addMetric(metrics[m], metrics[m+1]);
m=m+1;
}
dimension = _element.getAttribute('data-oochart-dimension');
column.setDimension(dimension);
column.draw(_element);
//if timeline
} else if (type.toLowerCase() === 'timeline'){
var timeline = new _Timeline(profile, startDate, endDate);
metricString = _element.getAttribute('data-oochart-metrics');
metrics = metricString.split(',');
for(m = 0; m < metrics.length; m++){
timeline.addMetric(metrics[m], metrics[m+1]);
m=m+1;
}
timeline.draw(_element);
} else if (type.toLowerCase() === 'bar' ) {
var bar = new _Bar(profile, startDate, endDate);
metricString = _element.getAttribute('data-oochart-metrics');
metrics = metricString.split(',');
for(m = 0; m < metrics.length; m++){
bar.addMetric(metrics[m], metrics[m+1]);
m=m+1;
}
dimension = _element.getAttribute('data-oochart-dimension');
bar.setDimension(dimension);
bar.draw(_element);
//if pie
} else if (type.toLowerCase() === 'pie'){
var pie = new _Pie(profile, startDate, endDate);
metricString = _element.getAttribute('data-oochart-metric');
dimension = _element.getAttribute('data-oochart-dimension');
metric = metricString.split(',');
pie.setMetric(metric[0], metric[1]);
pie.setDimension(dimension);
pie.draw(_element);
//if table
} else if (type.toLowerCase() === 'table'){
var table = new _Table(profile, startDate, endDate);
metricString = _element.getAttribute('data-oochart-metrics');
dimensionString = _element.getAttribute('data-oochart-dimensions');
metrics = metricString.split(',');
dimensions = dimensionString.split(',');
for(m = 0; m < metrics.length; m++){
table.addMetric(metrics[m], metrics[m+1]);
m += 1;
}
for(d = 0; d < dimensions.length; d++){
table.addDimension(dimensions[d], dimensions[d+1]);
d += 1;
}
table.draw(_element);
}
//else ignore and continue
}
};
/*
* Loads OOcharts dependencies
* @param {Function} callback
*/
var _load = function(callback){
if(!_apiKey) throw "Set APIKey with oo.setAPIKey before calling load";
// load Google Visualization
var load_visualization = function (callback) {
if (typeof google.visualization === 'undefined') {
google.load("visualization", "1", { packages: ['corechart', 'table'], 'callback': callback });
}
else {
var necpac = [];
if (typeof google.visualization.corechart === 'undefined') {
necpac.push('corechart');
}
if (typeof google.visualization.table === 'undefined') {
necpac.push('table');
}
if (necpac.length > 0) {
google.load("visualization", "1", { packages: necpac, 'callback': callback });
}
}
};
var cb = callback;
load_visualization(function () {
if(cb) cb();
// run autobuild
_autoBuild();
});
};
/*
* Sets API Key
* @param {String} key
*/
var _setAPIKey = function(key){
_apiKey = key;
};
/*
* Sets API Key
* @param {String} key
*/
var _setAPIEndpoint = function(ep){
_serviceEndpoint = ep;
};
/*
* Sets Column chart default options
* @param {Object} opts
*/
var _setColumnDefaults = function(opts){
_defaultColumnOptions = opts;
};
/*
* Sets Bar chart default options
* @param {Object} opts
*/
var _setBarDefaults = function(opts){
_defaultBarOptions = opts;
};
/*
* Sets Timeline chart default options
* @param {Object} opts
*/
var _setTimelineDefaults = function(opts){
_defaultTimelineOptions = opts;
};
/*
* Sets Pie chart default options
* @param {Object} opts
*/
var _setPieDefaults = function(opts){
_defaultPieOptions = opts;
};
/*
* Sets Table chart default options
* @param {Object} opts
*/
var _setTableDefaults = function(opts){
_defaultTableOptions = opts;
};
/*
* Helper to format Data object to GA standards
* @param {Date} date
* @returns {String} formatted date (YYYY-MM-DD)
*/
var _formatDate = function(date){
var year = date.getFullYear().toString();
var month = (date.getMonth() + 1).toString();
var date = date.getDate().toString();
if(month.length === 1) month = "0" + month;
if(date.length === 1) date = "0" + date;
return year + '-' + month + '-' + date;
};
/*
* Helper to parse GA date to date object
* @param {String} val
* @returns {Date} parsed Date
*/
var _parseDate = function(val){
val = val.split('-');
var newDate = new Date();
newDate.setFullYear(val[0], val[1]-1, val[2]);
newDate.setHours(0,0,0,0);
return newDate;
};
/*------------------------------------------------------------
Query (Core OOcharts Object)
-------------------------------------------------------------*/
/*
* Query constructor
* @param {String} profile
* @param {Date or String} startDate
* @param {Date or String} endDate
*/
var _Query = function(profile, startDate, endDate) {
this.metrics = [];
this.dimensions = [];
if(!profile) throw new Error("Profile argument required");
this.profile = profile;
// validate dates
startDate = startDate || new Date();
endDate = endDate || new Date();
if(startDate instanceof Date){
startDate = _formatDate(startDate);
}
if(endDate instanceof Date){
endDate = _formatDate(endDate);
}
var _isRelativeDate = function(val){ return /^[0-9]+(m|d|w|y)$/.test(val); };
var _isValidDate = function(val){ return /^([0-9]{4}-[0-9]{2}-[0-9]{2})$|^[0-9]+(m|d|w|y)$/.test(val); };
if(!_isRelativeDate(startDate) && !_isValidDate(startDate)){
throw new Error("startDate parameter invalid" );
}
if(!_isRelativeDate(endDate) && !_isValidDate(endDate)){
throw new Error("endDate parameter invalid" );
}
if(_isRelativeDate(startDate) && _isRelativeDate(endDate)){
throw new Error("startDate and endDate cannot both be relative dates");
}
this.startDate = startDate;
this.endDate = endDate;
};
/*
* Clears all metrics on Query
*/
_Query.prototype.clearMetrics = function(){
this.metrics = [];
};
/*
* Clears all dimensions on Query
*/
_Query.prototype.clearDimensions = function(){
this.dimensions = [];
};
/*
* Adds a metric to Query
* @param {String} metric
*/
_Query.prototype.addMetric = function(metric){
this.metrics.push(metric);
};
/*
* Adds a dimension to Query
* @param {String} dimension
*/
_Query.prototype.addDimension = function(dimension){
this.dimensions.push(dimension);
};
/*
* Sets filters string for Query
* @param {String} filters
*/
_Query.prototype.setFilter = function(filters){
this.filters = filters;
};
/*
* Sets sort string for Query
* @param {String} sort
*/
_Query.prototype.setSort = function(sort){
this.sort = sort;
};
/*
* Sets segment string for Query
* @param {String} segment
*/
_Query.prototype.setSegment = function(segment){
this.segment = segment;
};
/*
* Sets the beginning index for Query
* @param {Number or String} index
*/
_Query.prototype.setIndex = function(index){
this.index = index;
};
/*
* Sets max results for Query
* @param {Number or String} maxResults
*/
_Query.prototype.setMaxResults = function(maxResults){
this.maxResults = maxResults;
};
/*
* Executes query through JSONP
* @param {Function} callback(data)
*/
_Query.prototype.execute = function(callback){
var query = {};
query.key = _apiKey;
query.profile = this.profile;
if(this.metrics.length === 0) throw new Error("At least one metric is required");
query.metrics = this.metrics.toString();
query.start = this.startDate;
query.end = this.endDate;
if(this.dimensions.length > 0){
query.dimensions = this.dimensions.toString();
}
if(this.filters){
query.filters = this.filters;
}
if(this.sort){
query.sort = this.sort;
}
if(this.index){
query.index = this.index;
}
if(this.segment){
query.segment = this.segment;
}
if(this.maxResults){
query.maxResults = this.maxResults;
}
JSONP.get(_serviceEndpoint, query, function(data){
if(data.rows.length === 0){
data.rows = [[]];
}
callback(data);
});
};
/*------------------------------------------------------------
Metric
-------------------------------------------------------------*/
/*
* Metric constructor
* @param {String} profile
* @param {Date or String} startDate
* @param {Date or String} endDate
*/
var _Metric = function(profile, startDate, endDate){
this.query = new _Query(profile, startDate, endDate);
};
/*
* Sets the metric
* @param {String} metric
*/
_Metric.prototype.setMetric = function(metric){
this.query.clearMetrics();
this.query.addMetric(metric);
};
/*
* Draws metric result in container element
* @param {Element or String} container (or id of container element)
* @param {Function} fn
*/
_Metric.prototype.draw = function(container, fn){
this.query.execute(function(response){
var element;
if(typeof container === 'string'){
element = document.getElementById(container);
} else {
element = container;
}
if(typeof response.rows[0][0] !== 'undefined'){
element.innerHTML = response.rows[0][0].toString();
}
else {
element.innerHTML = "0";
}
if(typeof fn !== 'undefined'){
fn();
}
});
};
/*------------------------------------------------------------
Column
-------------------------------------------------------------*/
/*
* Column constructor
* @param {String} profile
* @param {Date or String} startDate
* @param {Date or String} endDate
*/
var _Column = function(profile, startDate, endDate){
this.query = new _Query(profile, startDate, endDate);
this.metricLabels = [];
this.options = _defaultColumnOptions;
};
/*
* Override default options
* @param {Object} opts
*/
_Column.prototype.setOptions = function(opts){
this.options = opts;
};
/*
* Adds a metric to Column
* @param {String} metric
* @param {String} label
*/
_Column.prototype.addMetric = function(metric, label){
this.metricLabels.push(label);
this.query.addMetric(metric);
};
/*
* Set dimension of Column
* @param {String} dimension
*/
_Column.prototype.setDimension = function(dimension){
this.query.clearDimensions();
this.query.dimensions.push(dimension);
this.dimensionLabel = dimension;
};
/*
* Draws Column in container element
* @param {Element or String} container (or id of container element)
* @param {Function} fn
*/
_Column.prototype.draw = function(container, fn){
var b = this;
this.query.execute(function (response) {
var data = response.rows;
var dt = new google.visualization.DataTable();
dt.addColumn('string', b.dimensionLabel);
// Add data column labels
for (var l = 0; l < b.metricLabels.length; l++) {
dt.addColumn('number', b.metricLabels[l]);
}
// add data
dt.addRows(data);
var element;
if(typeof container === 'string'){
element = document.getElementById(container);
} else {
element = container;
}
var chart = new google.visualization.ColumnChart(element);
chart.draw(dt, b.options);
if (typeof fn != 'undefined') {
fn();
}
});
};
/*------------------------------------------------------------
Timeline
-------------------------------------------------------------*/
/*
* Timeline constructor
* @param {String} profile
* @param {Date or String} startDate
* @param {Date or String} endDate
*/
var _Timeline = function(profile, startDate, endDate){
this.query = new _Query(profile, startDate, endDate);
this.query.addDimension('ga:date');
this.labels = [];
this.options = _defaultTimelineOptions;
};
/*
* Override default options
* @param {Object} opts
*/
_Timeline.prototype.setOptions = function(opts){
this.options = opts;
};
/*
* Adds a metric to Timeline
* @param {String} metric
* @param {String} label
*/
_Timeline.prototype.addMetric = function(metric, label){
this.labels.push(label);
this.query.addMetric(metric);
};
/*
* Draws timeline in container element
* @param {Element or String} container (or id of container element)
* @param {Function} fn
*/
_Timeline.prototype.draw = function(container, fn){
var t = this;
this.query.execute(function (response) {
var data = response.rows;
//Turn analytics date strings into date
for (var r = 0; r < data.length; r++) {
data[r][0] =_parseDate(data[r][0]);
}
var dt = new google.visualization.DataTable();
dt.addColumn('date', 'Date');
// Add data column labels
for (var l = 0; l < t.labels.length; l++) {
dt.addColumn('number', t.labels[l]);
}
// add data
dt.addRows(data);
var element;
if(typeof container === 'string'){
element = document.getElementById(container);
} else {
element = container;
}
var chart = new google.visualization.LineChart(element);
chart.draw(dt, t.options);
if (typeof fn != 'undefined') {
fn();
}
});
};
/*------------------------------------------------------------
Bar
-------------------------------------------------------------*/
/*
* Bar constructor
* @param {String} profile
* @param {Date or String} startDate
* @param {Date or String} endDate
*/
var _Bar = function(profile, startDate, endDate){
this.query = new _Query(profile, startDate, endDate);
this.metricLabels = [];
this.options = _defaultBarOptions;
};
/*
* Override default options
* @param {Object} opts
*/
_Bar.prototype.setOptions = function(opts){
this.options = opts;
};
/*
* Adds a metric to Bar
* @param {String} metric
* @param {String} label
*/
_Bar.prototype.addMetric = function(metric, label){
this.metricLabels.push(label);
this.query.addMetric(metric);
};
/*
* Set dimension of Bar
* @param {String} dimension
*/
_Bar.prototype.setDimension = function(dimension){
this.query.clearDimensions();
this.query.dimensions.push(dimension);
this.dimensionLabel = dimension;
};
/*
* Draws Bar in container element
* @param {Element or String} container (or id of container element)
* @param {Function} fn
*/
_Bar.prototype.draw = function(container, fn){
var b = this;
this.query.execute(function (response) {
var data = response.rows;
var dt = new google.visualization.DataTable();
dt.addColumn('string', b.dimensionLabel);
// Add data column labels
for (var l = 0; l < b.metricLabels.length; l++) {
dt.addColumn('number', b.metricLabels[l]);
}
// add data
dt.addRows(data);
var element;
if(typeof container === 'string'){
element = document.getElementById(container);
} else {
element = container;
}
var chart = new google.visualization.BarChart(element);
chart.draw(dt, b.options);
if (typeof fn != 'undefined') {
fn();
}
});
};
/*------------------------------------------------------------
Pie
-------------------------------------------------------------*/
/*
* Pie constructor
* @param {String} profile
* @param {Date or String} startDate
* @param {Date or String} endDate
*/
var _Pie = function(profile, startDate, endDate){
this.query = new _Query(profile, startDate, endDate);
this.options = _defaultPieOptions;
};
/*
* Set metric for Pie
* @param {String} metric
* @param {String} label
*/
_Pie.prototype.setMetric = function(metric, label){
this.metricLabel = label;
this.query.clearMetrics();
this.query.addMetric(metric);
};
/*
* Set dimension for Pie
* @param {String} dimension
*/
_Pie.prototype.setDimension = function(dimension){
this.query.clearDimensions();
this.query.dimensionLabel = dimension;
this.query.addDimension(dimension);
};
/*
* Override default pie options
* @param {Object} opts
*/
_Pie.prototype.setOptions = function(opts){
this.options = opts;
};
/*
* Draws pie in container element
* @param {Element or String} container (or id of container element)
* @param {Function} fn
*/
_Pie.prototype.draw = function(container, fn){
var p = this;
this.query.execute(function(response){
var data = response.rows;
var dt = new google.visualization.DataTable();
dt.addColumn('string', p.dimensionLabel);
dt.addColumn('number', p.metricLabel);
dt.addRows(data);
var element;
if(typeof container === 'string'){
element = document.getElementById(container);
} else {
element = container;
}
var chart = new google.visualization.PieChart(element);
chart.draw(dt, p.options);
if (typeof fn != 'undefined') {
fn();
}
});
};
/*------------------------------------------------------------
Table
-------------------------------------------------------------*/
/*
* Table constructor
* @param {String} profile
* @param {Date or String} startDate
* @param {Date or String} endDate
*/
var _Table = function(profile, startDate, endDate){
this.query = new _Query(profile, startDate, endDate);
this.metricLabels = [];
this.dimensionLabels = [];
this.options = _defaultTableOptions;
};
/*
* Adds a metric to table
* @param {String} metric
* @param {String} label
*/
_Table.prototype.addMetric = function(metric, label){
this.query.addMetric(metric);
this.metricLabels.push(label);
};
/*
* Adds a dimension to table
* @param {String} dimension
* @param {String} label
*/
_Table.prototype.addDimension = function(dimension, label){
this.query.addDimension(dimension);
this.dimensionLabels.push(label);
};
/*
* Override default table options
* @param {Object} opts
*/
_Table.prototype.setOptions = function(opts){
this.options = opts;
};
/*
* Draws table in container element
* @param {Element or String} container (or id of container element)
* @param {Function} fn
*/
_Table.prototype.draw = function(container, fn){
var t = this;
this.query.execute(function (result) {
var data = result.rows;
var labelRow = [];
for (var d = 0; d < t.dimensionLabels.length; d++) {
labelRow.push(t.dimensionLabels[d]);
}
for (var m = 0; m < t.metricLabels.length; m++) {
labelRow.push(t.metricLabels[m]);
}
data.splice(0, 0, labelRow);
var dt = google.visualization.arrayToDataTable(data);
var element;
if(typeof container === 'string'){
element = document.getElementById(container);
} else {
element = container;
}
var chart = new google.visualization.Table(element);
chart.draw(dt, t.options);
if (typeof fn != 'undefined') {
fn();
}
});
};
/*------------------------------------------------------------
Exports
-------------------------------------------------------------*/
return {
Query : _Query,
Timeline : _Timeline,
Column : _Column,
Bar : _Bar,
Metric : _Metric,
Pie : _Pie,
Table : _Table,
load : _load,
formatDate : _formatDate,
parseDate : _parseDate,
setAPIKey : _setAPIKey,
setAPIEndpoint : _setAPIEndpoint,
setBarDefaults : _setBarDefaults,
setColumnDefaults : _setColumnDefaults,
setTimelineDefaults : _setTimelineDefaults,
setPieDefaults : _setPieDefaults,
setTableDefaults : _setTableDefaults
};
})(document);
/**
* simple JSONP support
*
* JSONP.get('https://api.github.com/gists/1431613', function (data) { console.log(data); });
* JSONP.get('https://api.github.com/gists/1431613', {}, function (data) { console.log(data); });
*
* gist: https://gist.github.com/gists/1431613
*/
var JSONP = (function (document) {
var requests = 0,
callbacks = {};
return {
/**
* makes a JSONP request
*
* @param {String} src
* @param {Object} data
* @param {Function} callback
*/
get: function (src, data, callback) {
// check if data was passed
if (!arguments[2]) {
callback = arguments[1];
data = {};
}
// determine if there already are params
src += (src.indexOf('?')+1 ? '&' : '?');
var head = document.getElementsByTagName('head')[0],
script = document.createElement('script'),
params = [],
requestId = requests,
param;
// increment the requests
requests++;
// create external callback name
data.callback = 'JSONP.callbacks.request_' + requestId;
// set callback function
callbacks['request_' + requestId] = function (data) {
// clean up
head.removeChild(script);
delete callbacks['request_' + requestId];
// fire callback
callback(data);
};
// traverse data
for (param in data) {
params.push(param + '=' + encodeURIComponent(data[param]));
}
// generate params
src += params.join('&');
// set script attributes
script.type = 'text/javascript';
script.src = src;
// add to the DOM
head.appendChild(script);
},
/**
* keeps a public reference of the callbacks object
*/
callbacks: callbacks
};
}(document));
|
/* jshint maxlen:false */
var j = require("joi");
var package = require("./package.js").order;
var stakeholder = require("./stakeholder.js").order;
var version = require("../../package.json").version;
module.exports = j.object().keys({
platform: j.string().default("api"),
platform_version: j.string(),
module_version: j.string().default(version),
collecte: j.string().isoDate().required(),
courriers: j.array().includes(package).required(),
code_contenu: j.number().integer().required(),
delai: j.string().valid("aucun", "minimum", "course").required(),
destinataire: stakeholder.required(),
expediteur: stakeholder.required(),
url_tracking: j.string(),
operateur: j.string().required(),
service: j.string().required(),
disponibilite: j.object().keys({
HDE: j.string().regex(/^([01][0-9]|2[0-3]):[0-5][0-9]$/),
HLE: j.string().regex(/^([01][0-9]|2[0-3]):[0-5][0-9]$/)
}),
assurance: j.object().keys({
emballage: j.string().valid("Boîte", "Caisse", "Bac", "Emballage isotherme", "Etui", "Malle", "Sac", "Tube"),
fermeture: j.string().valid("Fermeture autocollante", "Ruban adhésif", "Agrafes", "Clous", "Collage", "Ruban de cerclage", "Sangle ou feuillard", "Agraphes et cerclage", "Clous et cerclage"),
fixation: j.string().valid("Sans système de stabilisation", "Film transparent", "Film opaque", "Film opaque et sangles", "Film transparent et sangles", "Sangle ou feuillard uniquement"),
materiau: j.string().valid("Carton", "Bois", "Carton blindé", "Film opaque", "Film transparent", "Métal", "Papier", "Papier armé", "Plastique et carton", "Plastique", "Plastique opaque", "Plastique transparent", "Polystyrène"),
nombre: j.number().integer(),
protection: j.string().valid("Sans protection particulière", "Calage papier", "Bulles plastiques", "Carton antichoc", "Coussin air", "Coussin mousse", "Manchon carton (bouteille)", "Manchon mousse (bouteille)", "Matelassage", "Plaque mousse", "Polystyrène", "Coussin de calage", "Sachet bulles"),
selection: j.boolean()
}),
"contre-remboursement": j.object().keys({
selection: j.boolean(),
valeur: j.number()
}),
depot: j.object().keys({
pointrelais: j.string()
}),
livraison_imperative: j.object().keys({
DIL: j.string().regex(/^(0[1-9]|[12][0-9]|3[01])[-](0[1-9]|1[012])[-](20)\d\d$/)
}),
retrait: j.object().keys({
pointrelais: j.string()
}),
type_emballage: j.object().keys({
emballage: j.string()
})
});
|
notifi = {
success: function (text) {
$.notify({
message: text
}, {
type: "success", timer: 4000, placement: {from: "top", align: "center"}
});
},
danger: function (text) {
$.notify({
message: text
}, {
type: "danger", timer: 8000, placement: {from: "top", align: "center"}
});
},
successAll: function (messages) {
if (messages)
messages.forEach(function (item) {
notifi.success(item);
});
},
dangerAll: function (messages) {
if (messages)
messages.forEach(function (item) {
notifi.danger(item);
});
},
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:51dc8aab107d8f37e1bc87dbfc4913deb3b33519ee0bad8e1331629048b40bc7
size 8279
|
var express = require('express');
const Board = require('../models/Board');
const BoardSquare = require('../models/BoardSquare');
const Square = require('../models/Square');
var router = express.Router();
router.get('/', (req, res) => {
console.log('req.headers.email', req.headers.userID)
// if (!req.header.email)
Board
.query({where: {userID: req.headers.userID}})
.fetchAll({
withRelated: ['gameType', 'boardSquares']
})
.then(boards => {
console.log('hai')
console.log(JSON.stringify(boards));
res.json(boards);
})
.catch(err => {
console.log(err)
res.status(500).json(err);
})
});
router.get('/:boardID', (req, res) => {
Board
.query({where: {id: req.params.boardID}})
.fetch({
withRelated: [{
'boardSquares': function(qb) {
qb.orderBy("order");
}
},
'boardSquares.square', 'gameType']
})
.then(board => {
// console.log(JSON.stringify(board));
res.json(board);
})
.catch(err => {
console.log(err)
res.status(500).json(err);
})
});
router.post('/:gameTypeID', (req, res) => {
const newBoard = new Board ({
userID: req.headers.userID,
gameTypeID: req.params.gameTypeID
});
newBoard.save()
.then((newBoard) => {
Square.query({where: {gameTypeID: req.params.gameTypeID}})
.fetchAll()
.then((squares) => {
if (squares.models.length < 25) {
res.json({status: 'not enough'});
}
let boardSquares = [];
for (var i = 0; i < 25; i++) {
let randIndex = Math.floor(Math.random() * squares.models.length);
boardSquares.push(new BoardSquare ({
boardID: newBoard.id,
squareID: squares.models[randIndex].id,
order: i
}))
squares.models.splice(randIndex, 1)
}
let savePromises = boardSquares.map((bs) => {
return bs.save();
})
Promise.all(savePromises)
.then((saveResults) => {
res.json({id: newBoard.id})
});
})
})
})
router.put('/boardID', (req, res) => {
console.log(req.params);
Board
.query({where: {id: req.params.boardID}})
.fetch()
.then((board) => {
board.set(req.body)
.save()
.then((result) => {
res.json(board);
})
})
})
router.delete('/:boardID', (req, res) => {
Board
.query({where: {id: req.params.boardID}})
.fetch()
.then((board) => {
board.destroy()
.then((result) => {
res.json({success: true});
})
})
})
module.exports = router; |
app.controller('searchController', ["$http", "$scope","$location","$rootScope", "Post","User", "login", function($http,$scope,$location,$rootScope, Post, User, login){
$scope.isCollapsed = true;
$scope.SearchError = false;
$scope.searchSubmit = function(){
if(login.user._id) {
var regExpSearchString = new RegExp($scope.searchString,"i");
// get the posts that matches the string in the search bar
Post.get({_all: regExpSearchString, _populate:"author"}, function(data){
var ids = [];
if(data.length && $scope.searchString){
for (var i = 0; i < data.length; i++) {
ids.push(data[i]._id);
}
console.log("FOUND:",data);
$rootScope.searchResult = data;
// change location to /search
$scope.SearchError = false;
}else if(!$scope.searchString){
$scope.SearchError = true;
}else{
// change location to /search
$location.url("/search");
console.log("OBS!!! No data found...");
$rootScope.searchResult = data;
// change location to /search
$location.url("/search");
}
User.get({_all: regExpSearchString}, function(users){
users.forEach(function(user, index) {
Post.get({author: user._id, _populate: "author"}, function(posts){
posts.forEach(function(post, index) {
var searchResultIndex = ids.indexOf(post._id);
if(searchResultIndex == -1) {
$rootScope.searchResult.push(post);
}
});
});
});
$location.url("/search");
});
});
}
};
$scope.searchForPostFromTag = function(tag) {
if(login.user._id) {
// get the posts that matches the tag that the user clicked on
Post.get({tags: new RegExp(tag,"i"), _populate:"author"}, function(data){
$rootScope.searchResult = data;
if(data.length && tag){
console.log("FOUND:",data);
// change location to /search
$location.url("/search");
}else{
console.log("OBS!!! No data found...");
// change location to /search
$location.url("/search");
}
});
}
};
}]);
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.add10 = exports.x = undefined;
exports.f = f;
exports.negiate = negiate;
var _String = require("fable-core/umd/String");
var _List = require("fable-core/umd/List");
var _Seq = require("fable-core/umd/Seq");
var _module = require("./module");
(0, _String.fsFormat)("hello, fable")(function (x) {
console.log(x);
});
var x = exports.x = 10;
(0, _String.fsFormat)("x=%A")(function (x) {
console.log(x);
})(x);
function f(x_1, y) {
return x_1 + y;
}
(0, _String.fsFormat)("x+y=%A")(function (x) {
console.log(x);
})(f(10, 20));
var add10 = exports.add10 = function () {
var x_1 = 10;
return function (y) {
return f(x_1, y);
};
}();
(0, _String.fsFormat)("50 add 10 = %A")(function (x) {
console.log(x);
})(add10(50));
function negiate(x_1) {
return -x_1;
}
(0, _String.fsFormat)("20 add 10 and negiate=%A")(function (x) {
console.log(x);
})(function ($var2) {
return function (value) {
return String(value);
}(function ($var1) {
return function (x_1) {
return negiate(x_1);
}(add10($var1));
}($var2));
}(20));
(0, _String.fsFormat)("%A")(function (x) {
console.log(x);
})(function (list) {
return (0, _List.map)(add10, list);
}((0, _Seq.toList)((0, _Seq.range)(1, 50))));
(0, _String.fsFormat)("50^2 = %A")(function (x) {
console.log(x);
})((0, _module.square)(50)); |
export default {
experiment: {
stage: '0',
experiment_id: '1',
custom_language: false,
language: false,
tags: [],
team: null,
links: [],
show_in: false,
funding: null
},
experiment_preview: {
stage: '0',
experiment_id: '1',
image: null,
owner_name: '',
title: 'Experiment title',
short_description: 'Short description.'
},
acl: ['view'],
profile: {
user_id: 1,
first_name: '',
last_name: '',
short_description: '',
long_description: '',
phone: '',
document_number: '',
tags: [],
links: [],
experiments: []
},
profile_preview: {
user_id: 1,
first_name: '',
last_name: '',
short_description: '',
image: null,
links: [],
tags: []
},
supportedEditors: [
'sirtrevor',
'quill'
],
defaultPlaceholderImageUrl: '/img/placeholder.png',
defaultPlaceholderVideoUrl: '/img/placeholder_video.png',
defaultPlaceholderProfileUrl: '/img/placeholder_profile.png'
}
|
var xtend = require('xtend')
var Prometheus = require('prometheus-client-js')
var HTTPMetrics = module.exports = function HTTPMetrics(client, opts) {
if (!(this instanceof HTTPMetrics)) {
return new HTTPMetrics(client, opts)
}
if (!(client instanceof Prometheus)) {
if (typeof client == 'object') {
opts = client
client = null
}
}
this.opts = opts
this.client = client || new Prometheus(this.opts)
var metrics = {
requests: this.client.createCounter({
name: 'http_requests_total',
subsystem: 'http',
help: 'The total number of http requests'
}),
connections: this.client.createGauge({
name: 'connections_total',
subsystem: 'http',
help: 'The current number of http connections'
}),
responseTime: this.client.createHistogram({
name: 'http_response_times',
subsystem: 'http',
help: 'The response times of http requests'
}),
}
return this
}
HTTPMetrics.prototype.attach = function(server) {
var self = this
server.on('connection', function() {
self.metrics.connections.set(server._connections)
})
server.on('disconnect', function() {
self.metrics.connections.set(server._connections)
})
server.on('request', function(req, res) {
req.responseStartTime = process.hrtime()
req.on('end', function() {
var endTime = process.hrtime(req.responseStartTime)
var responseTime = endTime[1] / 1000000
var parsed = parseUrl(req.url, true)
self.metrics.requests.increment({path: parsed.pathname, status: res.statusCode, method: req.method})
self.metrics.responseTime.observe(responseTime)
})
})
}
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014-2022 Mickael Jeanroy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import {isFunction} from './is-function.js';
import {isPrimitive} from './is-primitive.js';
/**
* Check that a given value is sealed: an object is sealed if it is not
* extensible and if all its properties are non-configurable and therefore not
* removable (but not necessarily non-writable).
*
* This function use internally `Object.isSealed` (supported in Chrome, Firefox,
* Safari and IE >= 9). If `Object.isSealed` is not supported, this function
* returns `false`.
*
* **Important**: This function (as ES6 specification) treat primitive
* (`null`, `undefined`, numbers, strings and booleans) as sealed object.
*
* See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isSealed
*
* @param {*} obj Value to check.
* @return {boolean} `true` if `obj` is sealed, `false` otherwise.
*/
export function isSealed(obj) {
// Primitive values are frozen in ES6 (not in ES5).
if (isPrimitive(obj)) {
return true;
}
// If Object.sealed is not supported, return `false` by default.
if (!isFunction(Object.isSealed)) {
return false;
}
return Object.isSealed(obj);
}
|
var assert = require('assert')
, options = require('./options')
, gbgcity = require('./../lib/gbgcity')(options);
function reportError(test, message) {
console.log(test + " : \033[22;31mERROR: " + message + "\x1B[0m");
}
function ok(test) {
console.log(test + " : \033[22;32mOK\x1B[0m");
}
function TestSuite() {
var Tests = {
"WaterFlow" : {},
"Parking" : {},
"StyrOchStall": {},
"TravelTime": {},
"AirQuality": {}
};
Tests.WaterFlow.getMeasureStations = function() {
var test = "gbgcity.WaterFlow.getMeasureStations(latitude=57.710383, longitude=11.945057)";
gbgcity.WaterFlow.getMeasureStations(57.710383, 11.945057, null, function(error, result) {
if(error) {
reportError(test, error.message);
} else {
try {
assert.ok(result);
assert.equal(result[0].Id, "Gotaalvbron.iFix.Analog.VattenNiva");
ok(test);
} catch (e) {
reportError(test, e);
}
}
});
};
Tests.WaterFlow.getWaterLevel = function() {
var test = "gbgcity.WaterFlow.getWaterLevel(stationId=Gotaalvbron.iFix.Analog.VattenNiva)";
gbgcity.WaterFlow.getWaterLevel('Gotaalvbron.iFix.Analog.VattenNiva', '2011-09-23T14:11', '2011-09-23T14:20', null, function(error, result) {
if(error) {
reportError(test, error.message);
} else {
try {
assert.ok(result);
assert.equal(result.StationId, 'Gotaalvbron.iFix.Analog.VattenNiva');
assert.equal(result.Values[0].Level, 1042);
ok(test);
} catch (e) {
reportError(test, e);
}
}
});
};
Tests.Parking.getParkings = function() {
var test = "gbgcity.Parking.getParkings(latitude=57.714348, longitude=11.933275, radius=100, type=bus)";
gbgcity.Parking.getParkings(57.714348, 11.933275, 100, 'bus', null, function(error, result){
if(error) {
reportError(test, error.message);
} else {
try {
assert.ok(result);
assert.equal(result[0].Id, '1480 2008-03758');
ok(test);
} catch (e) {
reportError(test, e);
}
}
});
};
Tests.Parking.getPublicPayMachines = function() {
var test = "gbgcity.Parking.getPublicPayMachines(latitude=57.720084, longitude=11.944586, radius=100)";
gbgcity.Parking.getPublicPayMachines(57.720084, 11.944586, 100, null, function(error, result){
if(error) {
reportError(test, error.message);
} else {
try {
assert.ok(result);
assert.equal(result[0].Id, '1227');
ok(test);
} catch (e) {
reportError(test, e);
}
}
});
};
Tests.Parking.getParkingOwners = function() {
var test = "gbgcity.Parking.getParkingOwners()";
gbgcity.Parking.getParkingOwners(null, function(error, result){
if(error) {
reportError(test, error.message);
} else {
try {
assert.ok(result);
assert.ok(result.length > 0);
ok(test);
} catch (e) {
reportError(test, e);
}
}
});
};
Tests.StyrOchStall.getBikeStations = function() {
var test = "gbgcity.StyrOchStall.getBikeStations(latitude=57.720084, longitude=11.944586, radius=100)";
gbgcity.StyrOchStall.getBikeStations(57.720084, 11.944586, 100, null, function(error, result){
if(error) {
reportError(test, error.message);
} else {
try {
assert.ok(result);
assert.ok(result.Stations.length > 0);
ok(test);
} catch (e) {
reportError(test, e);
}
}
});
};
Tests.StyrOchStall.getBikeStation = function() {
var test = "gbgcity.StyrOchStall.getBikeStation(id=1)";
gbgcity.StyrOchStall.getBikeStation(1, null, function(error, result){
if(error) {
reportError(test, error.message);
} else {
try {
assert.ok(result);
assert.equal(result.Stations[0].Label, 'LILLA BOMMEN');
ok(test);
} catch (e) {
reportError(test, e);
}
}
});
};
Tests.TravelTime.getRoutes = function() {
var test = "gbgcity.TravelTime.getRoutes()";
gbgcity.TravelTime.getRoutes(null, function(error, result){
if(error) {
reportError(test, error.message);
} else {
try{
assert.ok(result);
assert.ok(result.length > 0);
ok(test);
} catch (e) {
reportError(test, e);
}
}
});
};
Tests.TravelTime.getRoute = function() {
var test = "gbgcity.TravelTime.getRoute(id=20104)";
gbgcity.TravelTime.getRoute(20104, null, function(error, result){
if(error) {
reportError(test, error.message);
} else {
try{
assert.ok(result);
assert.equal(result.Length, 6239);
ok(test);
} catch (e) {
reportError(test, e);
}
}
});
};
Tests.TravelTime.getLatestTravelTimes = function() {
var test = "gbgcity.TravelTime.getLatestTravelTimes()";
gbgcity.TravelTime.getLatestTravelTimes(null, function(error, result){
if(error) {
reportError(test, error.message);
} else {
try{
assert.ok(result);
assert.ok(result.length > 0);
ok(test);
} catch (e) {
reportError(test, e);
}
}
});
};
Tests.TravelTime.getLatestTravelTime = function() {
var test = "gbgcity.TravelTime.getLatestTravelTime(id=20104)";
gbgcity.TravelTime.getLatestTravelTime(20104, null, function(error, result){
if(error) {
reportError(test, error.message);
} else {
try{
assert.ok(result);
assert.equal(result.RouteID, 20104);
ok(test);
} catch (e) {
reportError(test, e);
}
}
});
};
Tests.AirQuality.getLatestMeasurement = function() {
var test = "gbgcity.AirQuality.getLatestMeasurement()";
gbgcity.AirQuality.getLatestMeasurement(null, function(error, result){
if(error) {
reportError(test, error.message);
} else {
try{
assert.ok(result);
assert.ok(result.AirQuality);
ok(test);
} catch (e) {
reportError(test, e);
}
}
});
};
Tests.AirQuality.getMeasurements = function() {
var test = "gbgcity.AirQuality.getMeasurements()";
gbgcity.AirQuality.getMeasurements(null, null, null, function(error, result){
if(error) {
reportError(test, error.message);
} else {
try{
assert.ok(result);
assert.ok(result.length > 0);
assert.ok(result[0].AirQuality);
ok(test);
} catch (e) {
reportError(test, e);
}
}
});
};
return {
"Tests" : Tests,
"execute" : function(testGroup, testName) {
for(var group in Tests) {
if(!testGroup || (testGroup && testGroup == group)) {
for(var test in Tests[group]) {
if(!testName ||(testName && testName == test)) {
var t = Tests[group][test];
if(t && typeof(t) == "function") {
console.log("Running: " + test);
t.call(this);
}
}
}
}
}
}
}
}
TestSuite().execute(); |
var mongoose = require('mongoose');
var offerSchema = new mongoose.Schema({
provider: {type: String, default: ''},
heading: {type: String, default: ''},
description: {type: String, default: ''},
startDate: {type: Date, default: ''},
endDate: {type: Date, default: ''},
streetOne: {type: String, default: ''},
streetTwo: {type: String, default: ''},
city: {type: String, default: ''},
state: {type: String, default: ''},
pin: {type: String, default: ''},
email: {type: String, default: ''},
phoneOne: {type: String, default: ''},
phoneTwo: {type: String, default: ''},
url: {type: String, default: ''},
loc: {
type: {type: String},
coordinates: {type: [Number], index: '2dsphere'}
}
});
exports = module.exports = mongoose.model('Offer', offerSchema); |
/**
* Created by jerry on 15/9/17.
*/
module.exports = {
current:'production.js'
}; |
VerticalBarChart = function (aGraphObject) {
//graphObject.valueColors = {
// type: "discrete",
// entries: [{ min: 0, max: 20, color: "#FF0000" }, { min: 20, max: 50, color: "#FE642E" }, { min: 50, max: 70, color: "#F7FE2E" }, { min: 70, max: 100, color: "#00FF00" }],
// //entries: [{ value: 0, color: "#FF0000" }, { value: 8, color: "#FE642E" }, { value: 17, color: "#F7FE2E" }, { value: 25, color: "#00FF00" }],
// minColor: "#FF0000",
// maxColor: "#00FF00",
// defaultColor: "#666666"
//}
//parameters
this.graphObject = aGraphObject;
this.visible = false;
this.graphObject.preview = {};
this.graphID = this.graphObject.id;
this.previewDiv = null;
this.colors = {};
//this.refColors = {};
this.setColors = this.graphObject.colors ? this.graphObject.colors : {};
this.seriesNames = [],
this.dc20 = d3.scale.category20();
this.labelDiv = null;
this.labelVisible = true;
this.converted = false;
this.titleMargin = 30;
this.valueColors = this.graphObject.valueColors;
this.groupFilter = {};
//public functions
this.Initialize = function (container) {
container.graph = this;
this.container = container;
container.style.width = this.graphObject.width + "px";
container.style.height = this.graphObject.height + "px";
var svg = this.svg = d3.select(container).append("svg")
.attr("width", this.graphObject.width)
.attr("height", this.graphObject.height);
svg.className = "graph-svg";
this.graphGroup = svg.append("g")
.attr("class", "graph-g")
.attr("transform", "translate(" + GraphManager.defaultValues.graphPadding.left + ", " + GraphManager.defaultValues.graphPadding.top + ")");
this.dataGroup = this.graphGroup.append("g")
.attr("class", "graph-data-g")
.attr("transform", "translate(" + this.graphObject.yAxisMargin + ", 0)");
this.xAxisGroup = this.graphGroup.append("g")
.attr("class", "axis xAxis");
this.yLeftAxisGroup = this.graphGroup.append("g")
.attr("class", "axis yAxis");
if (typeof this.graphObject.title !== "undefined") {
this.titleStroke = svg.append("text")
.attr("x", (this.graphObject.width / 2))
.attr("y", 20)
.attr("dy", 3)
.attr("text-anchor", "middle")
.attr("pointer-events", "none")
.attr("class", "graph-title-text")
.style("font-size", "16px")
.style("stroke", "rgba(255, 255, 255, 0.6)")
.style("stroke-width", "3px")
.text(this.graphObject.title)
.call(this._wrapTitleLetters, this.graphObject.width - this.titleMargin);
this.titleText = svg.append("text")
.attr("x", (this.graphObject.width / 2))
.attr("y", 20)
.attr("dy", 3)
.attr("text-anchor", "middle")
.attr("pointer-events", "none")
.attr("class", "graph-title-text")
.style("font-size", "16px")
.text(this.graphObject.title)
.call(this._wrapTitleLetters, this.graphObject.width - this.titleMargin);
}
var labelDiv = this.labelDiv = container.appendChild(document.createElement("div"));
labelDiv.className = "bar-label-div";
labelDiv.style.left = (this.graphObject.width + 5) + "px";
labelDiv.style.top = "0px";
this._updateLabels();
if (this.converted) {
this.graphObject.data = this._convertOldData(this.graphObject.data);
if (this.graphObject.ref)
this.graphObject.ref.data = this._convertOldData(this.graphObject.ref.data);
}
// check if ref data should be converted
this.Update();
container.style.visibility = "hidden";
};
this.Reset = function () {
this.graphObject.data = [];
this.Update();
};
this.GetPreview = function (container) {
if (this.previewDiv != null)
return container.appendChild(this.previewDiv);
var previewDiv = this.previewDiv = document.createElement("div");
previewDiv.className = "detailContainer graphDetails";
previewDiv.style.width = DataManager.detailsInfo.chartWidth + "px";
previewDiv.graph = this;
previewDiv.addEventListener("click", this._clickEvent);
var title = previewDiv.appendChild(document.createElement("h4"));
title.className = "detailTitle graphDetailTitle";
title.textContent = this.graphObject.title;
title.style.width = DataManager.detailsInfo.elementWidth + "px";
var svgContainer = previewDiv.appendChild(document.createElement("div"));
svgContainer.className = "preview-svg-container";
svgContainer.style.width = DataManager.detailsInfo.chartWidth + "px";
svgContainer.style.height = DataManager.detailsInfo.chartHeight + "px";
var svg = d3.select(svgContainer).append("svg")
.attr("width", DataManager.detailsInfo.chartWidth)
.attr("height", DataManager.detailsInfo.chartHeight);
svg.className = "graph-svg-preview";
var graphGroup = svg.append("g")
graphGroup.className = "graph-g-preview";
this.preview = {
svg: svg,
graphGroup: graphGroup,
container: previewDiv
};
this._updatePreview();
container.appendChild(previewDiv);
return previewDiv;
};
this.ReInit = function (aGraphObject) {
//remove the old unconverted data
delete this._unconvertedData;
delete this._unconvertedRefData;
// re-do init stuff
this.graphObject = aGraphObject;
if (this.graphObject.axis)
this._convertFromOldBar();
// check if ref data should be converted
if (this.converted) {
this.graphObject.data = this._convertOldData(this.graphObject.data);
if (this.graphObject.ref)
this.graphObject.ref.data = this._convertOldData(this.graphObject.ref.data, true);
}
this.Update();
};
this.Update = function (data) {
if (typeof data != "undefined") {
// new data, check if needs to be converted
if (this.converted)
data = this._convertOldData(data);
// store new (converted) data
this.graphObject.data = data;
}
// use existing data but create deep copy
data = JSON.parse(JSON.stringify(this.graphObject.data));
if (this.graphObject.ref && this.graphObject.ref.data) {
rdata = this.graphObject.ref.data;
// merge this.refData into data
for (var d1 = 0; d1 < data.length; d1++) {
for (var r1 = 0; r1 < rdata.length; r1++) {
if (rdata[r1].title === data[d1].title) {
for (var r2 = rdata[r1].data.length - 1; r2 >= 0; r2--) {
var rdata_copy = JSON.parse(JSON.stringify(rdata[r1].data[r2]));
data[d1].data.splice(r2 + 1, 0, rdata_copy); // insert at position after current data ie zip sets together
for (var _d3 = 0; _d3 < data[d1].data[r2 + 1].data.length; _d3++)
data[d1].data[r2 + 1].data[_d3].series += "-ref";
}
break;
}
}
}
}
var categoryWidth = this.categoryWidth = data.length > 0 ? this._getCategoryWidth(data[0].data) : 0; //every category needs to be the same width
var barWidth = this.barWidth = 1 + this.graphObject.barMargin;
var categoryMargin = this.categoryMargin = this.graphObject.categoryMargin;
var barMargin = this.barMargin = this.graphObject.barMargin;
var axisCount = this.axisCount = this._getXAxisAmount(data); //rewrite to use series?
var divWidth = parseFloat(this.container.style.width);
var divHeight = parseFloat(this.container.style.height);
var graphWidth = divWidth - (GraphManager.defaultValues.graphPadding.left + GraphManager.defaultValues.graphPadding.right);
var graphHeight = divHeight - (GraphManager.defaultValues.graphPadding.top + GraphManager.defaultValues.graphPadding.bottom);
var dataWidth = graphWidth - (axisCount * this.graphObject.yAxisMargin);
var dataHeight = graphHeight - this.graphObject.xAxisMargin;
var maxY = this.maxY = this._getMaxY(data);
var minY = this.minY = this._getMinY(data);
var yScale = d3.scale.linear()
.range([dataHeight, 0])
.domain([minY, maxY]);
var barsWidth = this.barsWidth = this._getWidthInBars(data);
var xScale = d3.scale.linear()
.range([0, dataWidth])
.domain([0, barsWidth]);
var barPixelWidth = xScale(1);
this.svg
.attr("width", divWidth)
.attr("height", divHeight);
if (typeof this.graphObject.title !== "undefined") {
this.titleStroke
.attr("x", (divWidth / 2))
.text(this.graphObject.title)
.call(this._wrapTitleLetters, divWidth - this.titleMargin);
this.titleText
.attr("x", (divWidth / 2))
.text(this.graphObject.title)
.call(this._wrapTitleLetters, divWidth - this.titleMargin);
}
this.graphGroup
.attr("width", graphWidth)
.attr("height", graphHeight);
this.dataGroup
.attr("width", dataWidth)
.attr("height", dataHeight);
//Generate left y-axis
var yLeftAxis = d3.svg.axis().scale(yScale).orient("left").ticks(5);
this.yLeftAxisGroup
.attr("width", this.graphObject.yAxisMargin)
.attr("height", dataHeight)
.attr("transform", "translate(" + this.graphObject.yAxisMargin + ", 0)");
this.yLeftAxisGroup.call(yLeftAxis);
//generate and position x-axis
this.xAxisGroup
.attr("width", dataWidth)
.attr("height", this.graphObject.xAxisMargin)
.attr("transform", "translate(" + this.graphObject.yAxisMargin + "," + dataHeight + ")");
var label
if (this.graphObject.clickable == clickOptions.labels) {
var graphObject = this.graphObject;
label = this.xAxisGroup.selectAll("text")
.data(data)
.attr("x", function (d, i) { return xScale((i + 0.5) * categoryWidth); })
.attr("y", 0)
.attr("dy", "1.1em")
.attr("text-anchor", "middle")
.attr("class", "graph-title-text")
.style("font-size", "12px")
.style("cursor", "pointer")
.on('click', function (d, i) {
wsSend({
"type": "graphLabelClick",
"payload": {
"graphID": graphObject.id,
"labelTitle": d.title
}
});
})
.text(function (d) { return d.title })
.call(this._wrapLetters, xScale(categoryWidth) - 5);
label.enter().append("text")
.attr("x", function (d, i) { return xScale((i + 0.5) * categoryWidth); })
.attr("y", 0)
.attr("dy", "1.1em")
.attr("text-anchor", "middle")
.attr("class", "graph-title-text")
.style("font-size", "12px")
.style("cursor", "pointer")
.on('click', function (d, i) {
wsSend({
"type": "graphLabelClick",
"payload": {
"graphID": graphObject.id,
"labelTitle": d.title
}
});
})
.text(function (d) { return d.title })
.call(this._wrapLetters, xScale(categoryWidth) - 5);
}
else {
label = this.xAxisGroup.selectAll("text")
.data(data)
.attr("x", function (d, i) { return xScale((i + 0.5) * categoryWidth); })
.attr("y", 0)
.attr("dy", "1.1em")
.attr("text-anchor", "middle")
.attr("pointer-events", "none")
.attr("class", "graph-title-text")
.style("font-size", "12px")
.text(function (d) { return d.title })
.call(this._wrapLetters, xScale(categoryWidth) - 5);
label.enter().append("text")
.attr("x", function (d, i) { return xScale((i + 0.5) * categoryWidth); })
.attr("y", 0)
.attr("dy", "1.1em")
.attr("text-anchor", "middle")
.attr("pointer-events", "none")
.attr("class", "graph-title-text")
.style("font-size", "12px")
.text(function (d) { return d.title })
.call(this._wrapLetters, xScale(categoryWidth) - 5);
}
label.exit().remove();
//generate bars
var column = this.dataGroup.selectAll(".barColumn")
.data(data)
.attr("transform", function (d, i) { return "translate(" + xScale(((i * categoryWidth) + (0.5 * categoryMargin))) + ")"; });
column.enter().append("g")
.attr("class", "barColumn")
.attr("transform", function (d, i) { return "translate(" + xScale(((i * categoryWidth) + (0.5 * categoryMargin))) + ")"; });
column.exit().remove();
var bar = column.selectAll("g")
.data(function (d) { return d.data; });
bar.exit()
.remove();
bar.attr("transform", function (d, i) { return "translate(" + xScale((i * barWidth)) + ")"; });
bar.enter().append("g")
.attr("transform", function (d, i) { return "translate(" + xScale((i * barWidth)) + ")"; })
var getColor = this._getColor.bind(this);
var rect = bar.selectAll("rect")
.data(function (d) { return d.data; });
rect.exit()
.remove();
rect.attr("y", function (d) { return Math.min(yScale(d.start + d.value), yScale(d.start)); })
.attr("height", function (d) { return Math.abs(yScale(d.start + d.value) - yScale(d.start)); })
.attr("width", barPixelWidth)
.attr("fill", function (d) { return getColor(d.series, d.start + d.value); });
rect.enter().append("rect")
.attr("y", function (d) { return Math.min(yScale(d.start + d.value), yScale(d.start)); })
.attr("height", function (d) { return Math.abs(yScale(d.start + d.value) - yScale(d.start)); })
.attr("width", barPixelWidth)
.attr("fill", function (d) { return getColor(d.series, d.start + d.value); });
this.labelDiv.style.left = (divWidth + 5) + "px";
if ((this.seriesNames.length > 1 || typeof this.valueColors != "undefined") && this.labelVisible)
this.labelDiv.style.visibility = "inherit";
else
this.labelDiv.style.visibility = "hidden";
};
this._closeGraph = function () {
this.HideGraph();
}
this._openGraph = function () {
this.ShowGraph();
}
this.ShowGraph = function () {
this.visible = true;
this._resetSize();
GraphManager.AddGraph(this.container);
if (this.previewDiv)
L.DomUtil.addClass(this.previewDiv, "chartPreviewActive");
};
this.HideGraph = function () {
this.visible = false;
GraphManager.RemoveGraph(this.graphID)
if (this.previewDiv)
L.DomUtil.removeClass(this.previewDiv, "chartPreviewActive");
};
//private functions
this._updatePreview = function () {
if (this.previewDiv == null || typeof this.categoryWidth == "undefined")
return;
var data = this.graphObject.data;
var width = DataManager.detailsInfo.chartWidth;
var height = DataManager.detailsInfo.chartHeight;
var margin = DataManager.detailsInfo.graphMargin;
var categoryWidth = this.categoryWidth;
var categoryMargin = this.categoryMargin;
var barWidth = this.barWidth;
var graphWidth = width - (2 * margin);
var graphHeight = height - (2 * margin);
var yScale = d3.scale.linear()
.range([graphHeight, 0])
.domain([this.minY, this.maxY]);
var xScale = d3.scale.linear()
.range([0, graphWidth])
.domain([0, this.barsWidth]);
var barPixelWidth = xScale(1);
this.preview.graphGroup
.attr("width", graphWidth)
.attr("height", graphHeight)
.attr("transform", "translate(" + margin + "," + margin + ")");
var column = this.preview.graphGroup.selectAll(".barColumn")
.data(data)
.attr("transform", function (d, i) { return "translate(" + xScale(((i * categoryWidth) + (0.5 * categoryMargin))) + ")"; });
column.enter().append("g")
.attr("class", "barColumn")
.attr("transform", function (d, i) { return "translate(" + xScale(((i * categoryWidth) + (0.5 * categoryMargin))) + ")"; });
column.exit().remove();
var bar = column.selectAll("g")
.data(function (d) { return d.data; });
bar.exit()
.remove();
bar.attr("transform", function (d, i) { return "translate(" + xScale((i * barWidth)) + ")"; });
bar.enter().append("g")
.attr("transform", function (d, i) { return "translate(" + xScale((i * barWidth)) + ")"; })
var getColor = this._getColor.bind(this);
var rect = bar.selectAll("rect")
.data(function (d) { return d.data; });
rect.exit()
.remove();
rect.attr("y", function (d) { return Math.min(yScale(d.start + d.value), yScale(d.start)); })
.attr("height", function (d) { return Math.abs(yScale(d.start + d.value) - yScale(d.start)); })
.attr("width", barPixelWidth)
.attr("fill", function (d) { return getColor(d.series, d.start + d.value); });
rect.enter().append("rect")
.attr("y", function (d) { return Math.min(yScale(d.start + d.value), yScale(d.start)); })
.attr("height", function (d) { return Math.abs(yScale(d.start + d.value) - yScale(d.start)); })
.attr("width", barPixelWidth)
.attr("fill", function (d) { return getColor(d.series, d.start + d.value); });
}
this._getWidthInBars = function (categories) {
if (categories.length > 0)
return (this._getCategoryWidth(categories[0].data) * categories.length);
return this.graphObject.categoryMargin;
}
this._getCategoryWidth = function (bars) {
return this.graphObject.categoryMargin + (bars.length * (1 + this.graphObject.barMargin)) - (bars.length > 0 ? this.graphObject.barMargin : 0);
}
this._getMaxY = function (data) {
return d3.max(data, function (d) { return d3.max(d.data, function (d) { return d3.max(d.data, function (d) { return Math.max(d.start + d.value, d.start); }); }); });
}
this._getMinY = function (data) {
return d3.min(data, function (d) { return d3.min(d.data, function (d) { return d3.min(d.data, function (d) { return Math.min(d.start + d.value, d.start); }); }); });
}
this._getXAxisAmount = function (data) {
for (var i = 0; i < data.length; i++)
for (var j = 0; j < data[i].data.length; j++)
if (!data[i].data[j].leftAxis)
return 2;
return 1;
}
this._seriesToColor = function (series) {
if (typeof this.colors[series] == "undefined") {
if (typeof this.setColors[series] != "undefined")
{
this.colors[series] = this.setColors[series];
this.colors[series+"-ref"] = chroma(this.setColors[series]).brighten(2).desaturate(0.5).hex(); // calculate lighter version of color
}
else
{
this.colors[series] = this.dc20(series);
this.colors[series+"-ref"] = this.dc20(series+"-ref");
}
this.seriesNames.push(series);
this._updateLabels();
}
return this.colors[series];
}
this._getColor = function (series, value) {
if (this.valueColors)
return this._valueToColor(value);
return this._seriesToColor(series);
}
this._valueToColor = function (value) {
if (this.valueColors.type == "discrete")
{
for (var i = 0; i < this.valueColors.entries.length; i++)
if (value >= this.valueColors.entries[i].min && value <= this.valueColors.entries[i].max)
return this.valueColors.entries[i].color;
return this.valueColors.defaultColor;
}
else //ramp
{
if (typeof this.colorInterpolations == "undefined")
{
this.colorInterpolations = [];
for (var i = 0; i < this.valueColors.entries.length - 1; i++)
{
var value1 = this.valueColors.entries[i].value;
var value2 = this.valueColors.entries[i + 1].value;
var color1 = this.valueColors.entries[i].color;
var color2 = this.valueColors.entries[i + 1].color;
this.colorInterpolations.push({ min: value1, max: value2, interpolation: d3.scale.linear().domain([value1, value2]).interpolate(d3.interpolateRgb).range([d3.rgb(color1), d3.rgb(color2)]) });
}
}
if (this.colorInterpolations.length == 0)
return this.valueColors.defaultColor;
if (value < this.colorInterpolations[0].min)
return this.valueColors.minColor ? this.valueColors.minColor : this.valueColors.defaultColor;
for (var i = 0; i < this.colorInterpolations.length; i++)
if (value >= this.colorInterpolations[i].min && value <= this.colorInterpolations[i].max)
return this.colorInterpolations[i].interpolation(value);
return this.valueColors.maxColor ? this.valueColors.maxColor : this.valueColors.defaultColor;
}
}
this._clickEvent = (function (e) {
if (this.visible) {
this._closeGraph();
}
else {
this._openGraph();
}
}).bind(this);
this._resetSize = function () {
var changed = false
if (parseInt(this.container.style.width) != this.graphObject.width) {
this.container.style.width = this.graphObject.width + "px";
changed = true;
}
if (parseInt(this.container.style.height) != this.graphObject.height) {
this.container.style.height = this.graphObject.height + "px";
changed = true;
}
if (changed)
this.Update();
}
this._showLabels = function () {
this.labelDiv.visibility = "visible";
}
this._hideLabels = function () {
this.labelDiv.visiblilty = "hidden";
}
this._updateLabels = function () {
this.labelDiv.innerHTML = "";
if (this.valueColors)
{
if (this.valueColors.type == "discrete") {
var table = this.labelDiv.appendChild(document.createElement("table"));
table.className = "bar-label-table";
for (var i = 0; i < this.valueColors.entries.length; i++) {
var row = table.appendChild(document.createElement("tr"));
row.className = "bar-label-row";
var colorField = row.appendChild(document.createElement("td"));
colorField.className = "bar-label-color-td";
colorField.style.backgroundColor = this.valueColors.entries[i].color;
var textField = row.appendChild(document.createElement("td"));
textField.className = "bar-label-text-td";
textField.innerHTML = this.valueColors.entries[i].min + " - " + this.valueColors.entries[i].max;
}
}
else //ramp
{
var table = this.labelDiv.appendChild(document.createElement("table"));
table.className = "bar-label-table";
for (var i = 0; i < this.valueColors.entries.length; i++) {
var row = table.appendChild(document.createElement("tr"));
row.className = "bar-label-row";
var colorField = row.appendChild(document.createElement("td"));
colorField.className = "bar-label-color-td";
colorField.style.backgroundColor = this.valueColors.entries[i].color;
var textField = row.appendChild(document.createElement("td"));
textField.className = "bar-label-text-td";
textField.innerHTML = name;
}
}
}
else if (this.seriesNames.length > 0)
{
var chart = this;
var table = this.labelDiv.appendChild(document.createElement("table"));
table.className = "bar-label-table";
for (var i = 0; i < this.seriesNames.length; i++) {
let name = this.seriesNames[i];
var row = table.appendChild(document.createElement("tr"));
row.className = "bar-label-row";
var colorField = row.appendChild(document.createElement("td"));
colorField.className = "bar-label-color-td";
if (!this.groupFilter[name])
colorField.style.backgroundColor = this._seriesToColor(this.seriesNames[i]);
else {
colorField.style.borderStyle = "solid";
colorField.style.borderColor = this._seriesToColor(this.seriesNames[i]);
colorField.style.borderWidth = "3px";
}
var textField = row.appendChild(document.createElement("td"));
textField.className = "bar-label-text-td";
textField.innerHTML = this.seriesNames[i];
row.addEventListener('click', function (e) {
if (chart.groupFilter[name]) {
chart.groupFilter[name] = false;
if (chart._unconvertedRefData && chart.graphObject.ref && chart.graphObject.ref.data)
chart.graphObject.ref.data = chart._convertOldData(chart._unconvertedRefData, true);
chart.Update(chart._unconvertedData);
chart._updateLabels();
}
else {
chart.groupFilter[name] = true;
if (chart._unconvertedRefData && chart.graphObject.ref && chart.graphObject.ref.data)
chart.graphObject.ref.data = chart._convertOldData(chart._unconvertedRefData, true);
chart.Update(chart._unconvertedData);
chart._updateLabels();
}
});
row.style.cursor = "pointer";
}
}
else
{
//todo: display no series?
}
}
//copied and adjusted from: https://bl.ocks.org/mbostock/7555321
//not used for now. todo: check graph loading speed when enabled
this._wrap = function (text, width) {
text.each(function () {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
x = text.attr("x"),
dy = parseFloat(text.attr("dy"));
tspan = text.text(null).append("tspan").attr("x", x).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width && line.length > 1) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", x).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
}
this._wrapLetters = function (text, width) {
text.each(function () {
var text = d3.select(this),
letters = text.text(),
letter,
done = false,
line = "",
lineNumber = 0,
lineHeight = 1.1, // ems
font = window.getComputedStyle(this, null).getPropertyValue('font-family'),
fontSize = window.getComputedStyle(this, null).getPropertyValue('font-size')
canvas = document.createElement("canvas"),
context = canvas.getContext("2d"),
y = text.attr("y"),
x = text.attr("x"),
dy = parseFloat(text.attr("dy"));
context.font = fontSize + " " + font;
tspan = text.text(null).append("tspan").attr("x", x).attr("y", y).attr("dy", dy + "em");
while (lineNumber < 2 && letters.length > 0) {
letter = letters[0];
if (context.measureText(line + letter).width > width) {
tspan.text(line);
if (lineNumber < 1) {
line = "";
tspan = text.append("tspan").attr("x", x).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(line);
}
else
return;
}
else
{
line = line + letter;
letters = letters.substr(1);
tspan.text(line);
}
}
});
}
this._wrapTitleLetters = function (text, width) {
text.each(function () {
var text = d3.select(this),
letters = text.text(),
letter,
done = false,
line = "",
lineNumber = 0,
lineHeight = 1.1, // ems
font = window.getComputedStyle(this, null).getPropertyValue('font-family'),
fontSize = window.getComputedStyle(this, null).getPropertyValue('font-size')
canvas = document.createElement("canvas"),
context = canvas.getContext("2d"),
y = text.attr("y"),
x = text.attr("x"),
dy = parseFloat(text.attr("dy"));
context.font = fontSize + " " + font;
tspan = text.text(null).append("tspan").attr("x", x).attr("y", y);
while (lineNumber < 2 && letters.length > 0) {
letter = letters[0];
if (context.measureText(line + letter).width > width /*&& line.length > 1*/) {
tspan.text(line);
if (lineNumber < 1) {
line = "";
tspan = text.append("tspan").attr("x", x).attr("y", y).attr("dy", ++lineNumber * lineHeight + "em").text(line);
}
else
return;
}
else {
line = line + letter;
letters = letters.substr(1);
tspan.text(line);
}
}
});
}
this._convertFromOldBar = function ()
{
this.graphObject.barMargin = 0.15;
this.graphObject.categoryMargin = 1;
this.graphObject.xAxisMargin = 30;
this.graphObject.yAxisMargin = 30;
this.converted = true;
}
this._convertOldData = function (data, isRef)
{
if (!isRef)
this._unconvertedData = JSON.parse(JSON.stringify(data)); //make deep copy!
else
this._unconvertedRefData = JSON.parse(JSON.stringify(data));
//todo:
//store unconverted data
//filter the categories according to legend toggles
//rest should work?
var newData = [];
if (data.columns.length == 0)
return newData;
var categoryCount = data.columns[0].length - 1;
for (var i = 0; i < categoryCount; i++)
{
newData.push({ title: data.columns[0][i + 1], data: [] });
}
//this.groupFilter[' Autosnelweg'] = true;
for (var i = data.columns.length - 1; i >= 0; i--)
{
if (this.groupFilter[data.columns[i][0]])
data.columns.splice(i, 1);
}
for (var i = data.groups.length - 1; i >= 0; i--)
for (var j = data.groups[i].length - 1; j >= 0; j--)
if (this.groupFilter[data.groups[i][j]]) {
data.groups[i].splice(j, 1);
if (data.groups[i].length == 0)
data.groups.splice(i, 1);
}
var stackbar = {};
var getStackGroup = function (series) {
if (typeof data.groups == "undefined")
return -1;
for (var i = 0; i < data.groups.length; i++)
for (var j = 0; j < data.groups[i].length; j++)
if (data.groups[i][j] == series)
return i;
return -1;
};
var AddStackedValue = function (groupNo, catNo, value, series)
{
var prev = stackbar[groupNo][catNo].data[stackbar[groupNo][catNo].data.length - 1];
stackbar[groupNo][catNo].data.push({ start: prev.start + prev.value, value: value, series: series });
}
for (var i = 1; i < data.columns.length; i++)
{
var series = data.columns[i][0];
var stackgroup = getStackGroup(series);
if (stackgroup == "no")
{
for (var j = 1; j < data.columns[i].length; j++) {
newData[j - 1].data.push({ leftAxis: true, data: [{ start: 0, value: data.columns[i][j], series: series }] });
}
}
else if (typeof stackbar[stackgroup] == "undefined")
{
stackbar[stackgroup] = [];
for (var j = 1; j < data.columns[i].length; j++) {
var bar = { leftAxis: true, data: [{ start: 0, value: data.columns[i][j], series: series }] };
newData[j - 1].data.push(bar);
stackbar[stackgroup].push(bar);
}
}
else
{
for (var j = 1; j < data.columns[i].length; j++) {
AddStackedValue(stackgroup, j - 1, data.columns[i][j], series);
}
}
}
return newData;
}
if (this.graphObject.axis)
this._convertFromOldBar();
}; |
let createCalculator = require('../summator').createCalculator;
let expect = require('chai').expect;
describe('Calculator', () =>{
let calc;
beforeEach(() => {
calc = createCalculator();
});
it('Should return an object', () =>{
expect(typeof calc).to.equal('object');
});
it('It should have 0 value when created', () =>{
expect(calc.get()).to.equal(0);
});
it('It should have 0 value when no inputvalue', () =>{
calc.add();
expect(calc.get()).to.be.NaN;
});
it('It should add', () =>{
calc.add(3);
calc.add(5);
expect(calc.get()).to.equal(8);
});
it('It should subtract', () =>{
calc.subtract(3);
calc.subtract(5);
expect(calc.get()).to.equal(-8);
});
it('It should work with fractions', () =>{
calc.add(3.14);
calc.subtract(1.13);
expect(calc.get()).to.be.closeTo(2.01, 0.001);
});
it('It should work with negative numbers', () =>{
calc.add(-3);
calc.subtract(-5);
expect(calc.get()).to.equal(2);
});
it('It should not add NaNs', () =>{
calc.add('pesho');
expect(calc.get()).to.be.NaN;
});
it('It should not subtract NaNs', () =>{
calc.subtract('pesho');
expect(calc.get()).to.be.NaN;
});
it('It should add strings as numbers', () =>{
calc.add('7');
expect(calc.get()).to.equal(7);
});
}); |
var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
// see this link for more info on what all of this means
// https://github.com/halt-hammerzeit/webpack-isomorphic-tools
module.exports = {
// when adding "js" extension to asset types
// and then enabling debug mode, it may cause a weird error:
//
// [0] npm run start-prod exited with code 1
// Sending SIGTERM to other processes..
//
// debug: true,
assets: {
images: {
extensions: [
'jpeg',
'jpg',
'png',
'gif'
],
parser: WebpackIsomorphicToolsPlugin.url_loader_parser
},
fonts: {
extensions: [
'woff',
'woff2',
'ttf',
'eot'
],
parser: WebpackIsomorphicToolsPlugin.url_loader_parser
},
svg: {
extension: 'svg',
parser: WebpackIsomorphicToolsPlugin.url_loader_parser
},
style_modules: {
extensions: ['less','scss'],
filter: function(module, regex, options, log) {
if (options.development) {
// in development mode there's webpack "style-loader",
// so the module.name is not equal to module.name
return WebpackIsomorphicToolsPlugin.style_loader_filter(module, regex, options, log);
} else {
// in production mode there's no webpack "style-loader",
// so the module.name will be equal to the asset path
return regex.test(module.name);
}
},
path: function(module, options, log) {
if (options.development) {
// in development mode there's webpack "style-loader",
// so the module.name is not equal to module.name
return WebpackIsomorphicToolsPlugin.style_loader_path_extractor(module, options, log);
} else {
// in production mode there's no webpack "style-loader",
// so the module.name will be equal to the asset path
return module.name;
}
},
parser: function(module, options, log) {
if (options.development) {
return WebpackIsomorphicToolsPlugin.css_modules_loader_parser(module, options, log);
} else {
// in production mode there's Extract Text Loader which extracts CSS text away
return module.source;
}
}
}
}
} |
import React from 'react';
import { StyleSheet, View } from 'react-native';
import { BlurView as ExpoBlurView } from 'expo';
import styled from '@ui/styled';
const FilledBlurView = styled(StyleSheet.absoluteFill)(ExpoBlurView);
const BlurView = ({
intensity, tint, children, ...viewProps
}) => (
<View {...viewProps}>
{children}
<FilledBlurView intensity={intensity} tint={tint} />
</View>
);
BlurView.propTypes = {
...ExpoBlurView.propTypes,
...View.propTypes,
};
export default BlurView;
|
export const isString = (val) => typeof val === 'string'
export const isObject = (val) => val && typeof val === 'object'
export const isFunction = (val) => typeof val === 'function'
export const isPromise = (val) => isObject(val) && isFunction(val.then)
|
/*
* Webpack Requires
*/
var webpack = require('webpack');
var fs = require('fs');
var UglifyJsPlugin = webpack.optimize.UglifyJsPlugin;
var path = require('path');
var env = require('yargs').argv.mode;
var SharedSettings = require('./../shared');
/*
* Webpack Variables
*/
/**
* The library name
* @type {string}
*/
var libraryName = SharedSettings.libraryName;
var libraryFullName = SharedSettings.libraryFullName;
var versionNumber = SharedSettings.versionNumber;
var versionName = SharedSettings.versionName;
var buildNumber = SharedSettings.buildNumber;
var binName = 'compiled';
/*
* Webpack Plugin config
*/
var plugins = [
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
__LIB_NAME__: JSON.stringify(libraryName),
__LIB_FULL_NAME__: JSON.stringify(libraryFullName),
__VERSION__: JSON.stringify(versionNumber),
__VERSION_ID__: JSON.stringify(buildNumber),
__VERSION_NAME__: JSON.stringify(versionName),
__VERSION_STRING__: JSON.stringify(versionNumber + ' Build: ' + buildNumber + ' - ' + versionName)
})
], outputFile;
/*
* Set the project output filename for the build
*/
if (env === 'build') plugins.push(new UglifyJsPlugin({ minimize: true }));
outputFile = binName + '.js';
/*
* Imports the node modules for compiling server side
*/
var nodeModules = {
};
var StatusServiceConfig = {
stats: {
colors: true
},
entry: {
StatusService: './src/service/status/src/modules/init.js'
},
debug: false,
cache: false,
target: 'web',
output: {
path: './src/service/status/public/js',
filename: binName + '.js',
publicPath: '/js',
libraryTarget: 'var'
},
module: {
loaders: [
{
test: /\.js$/,
loader: "babel-loader",
}
]
},
resolve: {
root: path.resolve('./src/service/status/src/modules'),
extensions: ['', '.js']
},
plugins: plugins,
externals: nodeModules,
devtool: 'source-map',
};
/*
* Export webpack configs
*/
module.exports = [
StatusServiceConfig
];
|
var express = require("express");
var router = express.Router();
var dbHelper = require("../helpers/dbHelper")
router.route("/")
.post(dbHelper.create)
.get(dbHelper.getAll)
router.route("/:id")
.put(dbHelper.update)
.delete(dbHelper.delete)
.get(dbHelper.get);
module.exports = router; |
$(function(){
}) |
/**
* We declare the collection just like meteor default way
* but changing Meteor.Collection to orion.collection.
*
* We can set options to that new collection, like which fields
* we will show in the index of the collection in the admin
*/
Categories = new orion.collection('categories', {
singularName: orion.helpers.getTranslation('categories.singularName'), // The name of one of this items
pluralName: orion.helpers.getTranslation('categories.pluralName'), // The name of more than one of this items
title: orion.helpers.getTranslation('categories.title'), // The title of the page
link: {
/**
* The text that you want to show in the sidebar.
* The default value is the name of the collection, so
* in this case is not necesary
*/
// title: orion.helpers.getTranslation('categories.title')
title: "目录"
},
/**
* Tabular settings for this collection
*/
tabular: {
columns: [
{data: 'name', title: orion.helpers.getTranslation('categories.schema.name')},
{data: 'namezh', title: '名称'},
// { data: 'photo', title: '图片' },
/**
* If you want to show a custom orion attribute in
* the index table you must call this function
* orion.attributeColumn(attributeType, key, label)
*/
orion.attributeColumn('image', 'image', orion.helpers.getTranslation('categories.schema.image')),
orion.attributeColumn('createdBy', 'createdBy', orion.helpers.getTranslation('categories.schema.createdBy')),
orion.attributeColumn('createdAt', 'createdAt', orion.helpers.getTranslation('categories.schema.createdAt'))
]
}
});
|
var payoffDatabase = require('./payoffDatabase');
var storesManager = require('./storesManager');
var loginSession = require('./loginSession');
module.exports = {
add: function(req, data, callback) {
var anyError = chceckBasicErrors(data);
if(anyError) {
var messages = prepareErrorMessages(errors);
return callback({error: true, messages: messages});
}
//convert string to float
data.ammount = parseFloat(data.ammount);
if(isNaN(data.ammount)) {
return callback({error: true, messages: ["Suma musi być liczbą."]});
}
//add receipt to database
payoffDatabase.addReceipt(req, data, function(result) {
return callback(result);
});
},
get: function(req, storeId, callback) {
payoffDatabase.getReceipts(req, storeId, true, function(result) {
return callback(result);
});
},
getWithIds: function(req, storeId, callback) {
payoffDatabase.getReceipts(req, storeId, false, function(result) {
return callback(result);
});
},
delete: function(req, data, callback) {
payoffDatabase.deleteReceipt(req, data, function(result) {
return callback(result);
});
},
calculatePayoffs: function (req, data, callback) {
var payoffsModule = this;
//get all users
storesManager.getUsers(req, data.storeId, function(usersResponse) {
if (usersResponse.error == true)
return callback(usersResponse);
var users = usersResponse.array;
payoffsModule.getWithIds(req, data.storeId, function(receiptsResponse) {
if(receiptsResponse.error || receiptsResponse.empty)
return callback(receiptsResponse);
var receipts = receiptsResponse.receipts;
var transfers = receiptsResponse.transfers;
var activeUserId = loginSession.getId(req);
prepareUserObjects(users);
addSpendingsToUserObjects(users, receipts);
splitSpendingsToActiveUser(users, activeUserId);
//consult transfers and alter users array
console.log(users);
var toReturn = prepareToReturnObject(users, activeUserId);
return callback(toReturn);
});
});
}
};
function chceckBasicErrors(data) {
//server side verification
var regexes = {
title: new RegExp('^[^"\']+$'),
ammount: new RegExp('^([1-9]{1,1}[0-9]*)([\.,]{1,1}[0-9]{1,2}){0,1}$')
};
var errors = {
titleErr: !regexes.title.test(data.title),
ammountErr: !regexes.ammount.test(data.ammount),
descriptionErr: !regexes.title.test(data.description)
};
return function() {
for(x in errors) {
if(errors[x] == true) return true;
}
return false;
}();
}
function prepareErrorMessages(errors) {
var err = [];
if(errors.titleErr) {
err.push("Niepoprawny format tytułu.");
}
if(errors.ammountErr) {
err.push("Suma musi być liczbą dodatnią oraz zawierać maksymalnie dwie cyfry rozwinięcia dziesiętnego.");
}
if(errors.descriptionErr) {
err.push("Niepoprawny opis.");
}
return err;
}
//calculation functions
function prepareUserObjects(users) {
for(var i = 0; i < users.length; i++) {
users[i].spendings = 0;
users[i].toReturn = 0;
}
}
function addSpendingsToUserObjects(users, receipts) {
for(var i = 0; i < receipts.length; i++) {
for(var j = 0; j < users.length; j++) {
if(users[j].id == receipts[i].ownerId) {
users[j].spendings += receipts[i].ammount;
}
}
}
}
function subtractLowestSpending(users) {
var ammount = findLowestSpending(users);
subtractAmmountFromSpendings(users, ammount);
}
function subtractAmmountFromSpendings(users, ammount) {
for(var i = 0; i < users.length; i++) {
users[i].spendings -= ammount;
}
}
function findLowestSpending(users) {
if(users.length == 0)
return 0;
var lowest = users[0].spendings;
for(var i = 1; i < users.length; i++) {
if(users[i].spendings < lowest) {
lowest = users[i].spendings;
}
}
return lowest;
}
function splitSpendingsToActiveUser(users, activeUserId) {
var usersSpendings = getActiveUserSpending(users, activeUserId);
subtractAmmountFromSpendings(users, usersSpendings);
accumulateToReturn(users, activeUserId);
}
function getActiveUserSpending(users, activeUserId) {
for(var i = 0; i < users.length; i++) {
if(users[i].id == activeUserId) {
return users[i].spendings;
}
}
return -1;
}
function accumulateToReturn(users, activeUserId) {
for(var i = 0; i < users.length; i++) {
if(users[i].spendings > 0) {
var ammount = calculateToReturn(users, users[i].spendings);
addToReturn(users, users[i].id, ammount);
}
}
}
function calculateToReturn(users, ammount) {
return ammount/users.length;
}
function addToReturn(users, userId, ammount) {
for(var i = 0; i < users.length; i++) {
if(users[i].id == userId) {
users[i].toReturn += ammount;
return;
}
}
}
function prepareToReturnObject(users, activeUserId) {
for(var i = 0; i < users.length; i++) {
if(users[i].id == activeUserId) {
users.splice(i, 1);
}
else {
delete users[i].spendings;
users[i].toReturn = roundToMoneyValue(users[i].toReturn);
}
}
return {
error: false,
empty: false,
users: users
};
}
function roundToMoneyValue(number) {
return number.toFixed(2);
} |
// Test the rectangle element
var Title = Chart.registry.getPlugin('title')._element;
describe('Plugin.title', function() {
describe('auto', jasmine.fixture.specs('plugin.title'));
it('Should have the correct default config', function() {
expect(Chart.defaults.plugins.title).toEqual({
align: 'center',
color: Chart.defaults.color,
display: false,
position: 'top',
fullSize: true,
weight: 2000,
font: {
weight: 'bold'
},
padding: 10,
text: ''
});
});
it('should update correctly', function() {
var chart = {
options: Chart.helpers.clone(Chart.defaults)
};
var options = Chart.helpers.clone(Chart.defaults.plugins.title);
options.text = 'My title';
var title = new Title({
chart: chart,
options: options
});
title.update(400, 200);
expect(title.width).toEqual(0);
expect(title.height).toEqual(0);
// Now we have a height since we display
title.options.display = true;
title.update(400, 200);
expect(title.width).toEqual(400);
expect(title.height).toEqual(34.4);
});
it('should update correctly when vertical', function() {
var chart = {
options: Chart.helpers.clone(Chart.defaults)
};
var options = Chart.helpers.clone(Chart.defaults.plugins.title);
options.text = 'My title';
options.position = 'left';
var title = new Title({
chart: chart,
options: options
});
title.update(200, 400);
expect(title.width).toEqual(0);
expect(title.height).toEqual(0);
// Now we have a height since we display
title.options.display = true;
title.update(200, 400);
expect(title.width).toEqual(34.4);
expect(title.height).toEqual(400);
});
it('should have the correct size when there are multiple lines of text', function() {
var chart = {
options: Chart.helpers.clone(Chart.defaults)
};
var options = Chart.helpers.clone(Chart.defaults.plugins.title);
options.text = ['line1', 'line2'];
options.position = 'left';
options.display = true;
options.font.lineHeight = 1.5;
var title = new Title({
chart: chart,
options: options
});
title.update(200, 400);
expect(title.width).toEqual(56);
expect(title.height).toEqual(400);
});
it('should draw correctly horizontally', function() {
var chart = {
options: Chart.helpers.clone(Chart.defaults)
};
var context = window.createMockContext();
var options = Chart.helpers.clone(Chart.defaults.plugins.title);
options.text = 'My title';
var title = new Title({
chart: chart,
options: options,
ctx: context
});
title.update(400, 200);
title.draw();
expect(context.getCalls()).toEqual([]);
// Now we have a height since we display
title.options.display = true;
title.update(400, 200);
title.top = 50;
title.left = 100;
title.bottom = title.top + title.height;
title.right = title.left + title.width;
title.draw();
expect(context.getCalls()).toEqual([{
name: 'save',
args: []
}, {
name: 'setFont',
args: ["normal bold 12px 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"],
}, {
name: 'translate',
args: [300, 67.2]
}, {
name: 'rotate',
args: [0]
}, {
name: 'setFillStyle',
args: ['#666']
}, {
name: 'setTextAlign',
args: ['center'],
}, {
name: 'setTextBaseline',
args: ['middle'],
}, {
name: 'fillText',
args: ['My title', 0, 0, 400]
}, {
name: 'restore',
args: []
}]);
});
it ('should draw correctly vertically', function() {
var chart = {
options: Chart.helpers.clone(Chart.defaults)
};
var context = window.createMockContext();
var options = Chart.helpers.clone(Chart.defaults.plugins.title);
options.text = 'My title';
options.position = 'left';
var title = new Title({
chart: chart,
options: options,
ctx: context
});
title.update(200, 400);
title.draw();
expect(context.getCalls()).toEqual([]);
// Now we have a height since we display
title.options.display = true;
title.update(200, 400);
title.top = 50;
title.left = 100;
title.bottom = title.top + title.height;
title.right = title.left + title.width;
title.draw();
expect(context.getCalls()).toEqual([{
name: 'save',
args: []
}, {
name: 'setFont',
args: ["normal bold 12px 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"],
}, {
name: 'translate',
args: [117.2, 250]
}, {
name: 'rotate',
args: [-0.5 * Math.PI]
}, {
name: 'setFillStyle',
args: ['#666']
}, {
name: 'setTextAlign',
args: ['center'],
}, {
name: 'setTextBaseline',
args: ['middle'],
}, {
name: 'fillText',
args: ['My title', 0, 0, 400]
}, {
name: 'restore',
args: []
}]);
// Rotation is other way on right side
title.options.position = 'right';
// Reset call tracker
context.resetCalls();
title.update(200, 400);
title.top = 50;
title.left = 100;
title.bottom = title.top + title.height;
title.right = title.left + title.width;
title.draw();
expect(context.getCalls()).toEqual([{
name: 'save',
args: []
}, {
name: 'setFont',
args: ["normal bold 12px 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"],
}, {
name: 'translate',
args: [117.2, 250]
}, {
name: 'rotate',
args: [0.5 * Math.PI]
}, {
name: 'setFillStyle',
args: ['#666']
}, {
name: 'setTextAlign',
args: ['center'],
}, {
name: 'setTextBaseline',
args: ['middle'],
}, {
name: 'fillText',
args: ['My title', 0, 0, 400]
}, {
name: 'restore',
args: []
}]);
});
describe('config update', function() {
it ('should update the options', function() {
var chart = acquireChart({
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
data: [10, 20, 30, 100]
}]
},
options: {
plugins: {
title: {
display: true
}
}
}
});
expect(chart.titleBlock.options.display).toBe(true);
chart.options.plugins.title.display = false;
chart.update();
expect(chart.titleBlock.options.display).toBe(false);
});
it ('should update the associated layout item', function() {
var chart = acquireChart({
type: 'line',
data: {},
options: {
plugins: {
title: {
fullSize: true,
position: 'top',
weight: 150
}
}
}
});
expect(chart.titleBlock.fullSize).toBe(true);
expect(chart.titleBlock.position).toBe('top');
expect(chart.titleBlock.weight).toBe(150);
chart.options.plugins.title.fullSize = false;
chart.options.plugins.title.position = 'left';
chart.options.plugins.title.weight = 42;
chart.update();
expect(chart.titleBlock.fullSize).toBe(false);
expect(chart.titleBlock.position).toBe('left');
expect(chart.titleBlock.weight).toBe(42);
});
it ('should remove the title if the new options are false', function() {
var chart = acquireChart({
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
data: [10, 20, 30, 100]
}]
}
});
expect(chart.titleBlock).not.toBe(undefined);
chart.options.plugins.title = false;
chart.update();
expect(chart.titleBlock).toBe(undefined);
});
it ('should create the title if the title options are changed to exist', function() {
var chart = acquireChart({
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
data: [10, 20, 30, 100]
}]
},
options: {
plugins: {
title: false
}
}
});
expect(chart.titleBlock).toBe(undefined);
chart.options.plugins.title = {};
chart.update();
expect(chart.titleBlock).not.toBe(undefined);
expect(chart.titleBlock.options).toEqualOptions(Chart.defaults.plugins.title);
});
});
});
|
(function () {
'use strict';
angular
.module('courses.routes')
.config(routeConfig);
routeConfig.$inject = ['$stateProvider', '$urlRouterProvider'];
function routeConfig($stateProvider, $urlRouterProvider) {
$urlRouterProvider.rule(function ($injector, $location) {
var path = $location.path();
var hasTrailingSlash = path.length > 1 && path[path.length - 1] === '/';
if (hasTrailingSlash) {
// if last character is a slash, return the same url without the slash
var newPath = path.substr(0, path.length - 1);
$location.replace().path(newPath);
}
});
$stateProvider
.state('frontend.courses', {
abstract: true,
url: '/courses',
template: '<ui-view/>',
requiredRight: 'courses.view'
})
.state('frontend.courses.lessons', {
abstract: true
})
.state('frontend.courses.lessons.update', {
abstract: true
})
.state('frontend.courses.lessons.update.content', {
url: '/courses/:courseUrl/sections/:sectionUrl/lessons/:lessonId/update',
templateUrl: '/modules/courses/views/course-lesson-create-content.view.html',
controller: 'CourseLessonContentCreateCtrl',
controllerAs: 'vm',
parent: 'frontend',
needCourseRights:true
})
.state('frontend.courses.lessons.update.quiz', {
url: '/courses/:courseUrl/sections/:sectionUrl/lessons/:lessonId/update/quiz',
templateUrl: '/modules/courses/views/course-lesson-create-quiz.view.html',
controller: 'CourseLessonQuizCreateCtrl',
controllerAs: 'vm',
parent: 'frontend',
needCourseRights:true
})
.state('frontend.courses.lessons.update.automaton', {
url: '/courses/:courseUrl/sections/:sectionUrl/lessons/:lessonId/update/automaton',
templateUrl: '/modules/courses/views/course-lesson-create-automaton.view.html',
controller: 'CourseLessonAutomatonCreateCtrl',
controllerAs: 'vm',
parent: 'frontend',
needCourseRights:true
})
.state('frontend.courses.lessons.create', {
abstract: true
})
.state('frontend.courses.lessons.create.content', {
url: '/courses/:courseUrl/sections/:sectionUrl/lessons/create',
templateUrl: '/modules/courses/views/course-lesson-create-content.view.html',
controller: 'CourseLessonContentCreateCtrl',
controllerAs: 'vm',
parent: 'frontend',
needCourseRights:true
})
.state('frontend.courses.lessons.create.quiz', {
url: '/courses/:courseUrl/sections/:sectionUrl/lessons/create/quiz',
templateUrl: '/modules/courses/views/course-lesson-create-quiz.view.html',
controller: 'CourseLessonQuizCreateCtrl',
controllerAs: 'vm',
parent: 'frontend',
needCourseRights:true
})
.state('frontend.courses.lessons.create.automaton', {
url: '/courses/:courseUrl/sections/:sectionUrl/lessons/create/automaton',
templateUrl: '/modules/courses/views/course-lesson-create-automaton.view.html',
controller: 'CourseLessonAutomatonCreateCtrl',
controllerAs: 'vm',
parent: 'frontend',
needCourseRights:true
})
.state('frontend.courses.list', {
url: '',
templateUrl: '/modules/courses/views/list-courses.view.html',
controller: 'CoursesCtrl',
controllerAs: 'vm',
requiredRight: ['courses.view']
})
.state('frontend.courses.create', {
url: '/courses/create',
templateUrl: '/modules/courses/views/course-create.html',
controller: 'CourseCreateCtrl',
controllerAs: 'vm',
parent: 'frontend',
requiredRight: ['courses.create']
})
.state('frontend.courses.display', {
abstract: true,
url: '/:courseUrl',
templateUrl: '/modules/courses/views/course.template.view.html',
controller: 'CourseCtrl',
controllerAs: 'vm',
requiredRight: ['courses.view']
})
.state('frontend.courses.display.overview', {
url: '',
templateUrl: '/modules/courses/views/course-overview.view.html',
controller: 'CourseCtrl',
controllerAs: 'vm',
requiredRight: ['courses.view']
})
.state('frontend.courses.display.content', {
url: '/content',
templateUrl: '/modules/courses/views/course-content.view.html',
controller: 'CourseContentCtrl',
controllerAs: 'vm',
requiredRight: ['courses.view']
})
.state('frontend.courses.display.lesson', {
url: '/courses/:courseUrl/lessons/:lessonId',
templateUrl: '/modules/courses/views/course-lesson.view.html',
controller: 'LessonCtrl',
controllerAs: 'vm',
parent: 'frontend'
})
.state('frontend.courses.display.tools', {
url: '/tools',
templateUrl: '/modules/courses/views/course-tools.view.html',
controller: 'ToolsCtrl',
controllerAs: 'vm'
})
.state('frontend.courses.display.createQuestion', {
url: '/questions-and-answers/create',
templateUrl: '/modules/courses/views/course-create-question.html',
controller: 'QuestionCreateCtrl',
controllerAs: 'vm',
parent: 'frontend.courses.display'
})
.state('frontend.courses.display.questionsAndAnswers', {
url: '/questions-and-answers',
templateUrl: '/modules/courses/views/course-questions-and-answers.view.html',
controller: 'QuestionAndAnswersCtrl',
controllerAs: 'vm'
})
.state('frontend.courses.display.questionsAndAnswers.display', {
url: '/questions-and-answers/:questionId',
templateUrl: '/modules/courses/views/course-question-and-answers.view.html',
controller: 'QuestionAndAnswersCtrl',
controllerAs: 'vm',
parent: 'frontend.courses.display'
})
.state('frontend.courses.display.notifications', {
url: '/notifications',
templateUrl: '/modules/courses/views/course-notifications.view.html',
parent: 'frontend.courses.display'
})
.state('frontend.courses.display.createNotification', {
url: '/notifications/create',
templateUrl: '/modules/courses/views/course-create-notification.html',
controller: 'NotificationCreateCtrl',
controllerAs: 'vm',
parent: 'frontend.courses.display',
needCourseRights:true
})
.state('frontend.courses.display.updateNotifications', {
url: '/notifications/:notificationId',
templateUrl: '/modules/courses/views/course-create-notification.html',
controller: 'NotificationCreateCtrl',
controllerAs: 'vm',
parent: 'frontend.courses.display',
needCourseRights:true
})
.state('frontend.courses.display.edit', {
url: '/edit',
templateUrl: '/modules/courses/views/course-create.html',
controller: 'CourseCreateCtrl',
controllerAs: 'vm',
needCourseRights:true
});
}
}());
|
var gpio = require('onoff').Gpio;
var fs = require('fs');
var moment = require('moment');
var CronJob = require('cron').CronJob;
var input1 = new gpio(18, 'in', 'rising');
var input2 = new gpio(23, 'in', 'rising');
var input3 = new gpio(24, 'in', 'rising');
var led1 = new gpio(22, 'out');
var led2 = new gpio(27, 'out');
var pulseCount1 = 0;
var pulseCount2 = 0;
var pulseCount3 = 0;
var countSemaphore = require('semaphore')(1);
const filePath = '/home/pi/PiPulse/data/';
// Boot
console.error('LED on.');
led1.writeSync(1);
led2.writeSync(1);
setTimeout(function(){
led1.write(0);
led2.write(0);
console.error('LED off.');
},3000);
var blinkLED = function(){
led1.writeSync(1);
setTimeout(function() {led1.write(0)}, 100);
};
var job = new CronJob('01 * * * * * ',
function(){
var time = moment().subtract(1, 'seconds');
var v1, v2, v3;
countSemaphore.take(function(){
v1 = pulseCount1;
pulseCount1 = 0;
v2 = pulseCount2;
pulseCount2 = 0;
v3 = pulseCount3;
pulseCount3 = 0;
countSemaphore.leave();
});
var str = time.format('YYYY-MM-DD HH:mm');
str += ':00';
str += ',' + v1;
str += ',' + v2;
str += ',' + v3;
fs.appendFile(filePath + time.subtract(30, 'seconds').format('YYMMDD') + '.txt', str + '\n', function(err) {
if(err) console.error(err);
});
console.error(str);
},
null,
false,
'Asia/Tokyo');
setTimeout(function(){
input1.watch(function(err,val){
setImmediate(function() { console.error('Ch1 Pulse.'); blinkLED();});
countSemaphore.take(function(){
pulseCount1 += 1;
countSemaphore.leave();
});
});
input2.watch(function(err,val){
setImmediate(function() {console.error('Ch2 Pulse.'); blinkLED();});
countSemaphore.take(function(){
pulseCount2 += 1;
countSemaphore.leave();
});
});
input3.watch(function(err,val){
setImmediate(function() {console.error('Ch3 Pulse.'); blinkLED();});
countSemaphore.take(function(){
pulseCount3 += 1;
countSemaphore.leave();
});
});
job.start();
}, 3000);
|
const { description } = require('../../package');
const styles = require('@dicebear/collection');
const camelCaseToKebabCase = require('./utils/camelCaseToKebabCase');
const camelCaseToSpaceCase = require('./utils/camelCaseToSpaceCase');
const path = require('path');
module.exports = {
/**
* Ref:https://v1.vuepress.vuejs.org/config/#title
*/
title: 'DiceBear',
/**
* Ref:https://v1.vuepress.vuejs.org/config/#description
*/
description: description,
/**
* Extra tags to be injected to the page HTML `<head>`
*
* ref:https://v1.vuepress.vuejs.org/config/#head
*/
head: [
['meta', { name: 'theme-color', content: '#0284C7' }],
['meta', { name: 'apple-mobile-web-app-capable', content: 'yes' }],
['meta', { name: 'apple-mobile-web-app-status-bar-style', content: 'black' }],
],
/**
* Theme configuration, here is the default theme configuration for VuePress.
*
* ref:https://v1.vuepress.vuejs.org/theme/default-theme-config.html
*/
themeConfig: {
logo: '/logo.svg',
repo: 'dicebear/dicebear',
editLinks: true,
docsDir: 'website',
editLinkText: '',
lastUpdated: false,
search: false,
nav: [
{
text: 'Docs',
link: '/docs/',
},
{
text: 'Styles',
link: '/styles/',
},
{
text: 'Playground',
link: '/playground/',
},
],
sidebar: [
{
title: 'Docs',
collapsable: false,
children: [
{
title: 'Getting Started',
path: '/docs/',
},
{
title: 'Installation',
path: '/docs/installation/',
},
{
title: 'Options',
path: '/docs/options/',
},
{
title: 'HTTP-API',
path: '/docs/http-api/',
},
{
title: 'CLI',
path: '/docs/cli/',
},
{
title: 'How to contribute?',
path: '/docs/contribute/',
},
],
},
{
title: 'Frameworks',
collapsable: false,
children: [
{
title: 'React',
path: '/frameworks/react/',
},
{
title: 'Svelte',
path: '/frameworks/svelte/',
},
{
title: 'Vue',
path: '/frameworks/vue/',
},
],
},
{
title: 'Styles',
collapsable: false,
children: [
{
title: 'Create your own',
path: '/styles/create-your-own/',
collapsable: false,
initialOpenGroupIndex: -1,
children: [
{
title: 'With Figma',
path: '/styles/create-your-own/with-figma/',
},
{
title: 'From Scratch',
path: '/styles/create-your-own/from-scratch/',
},
],
},
{
title: 'Official Styles',
path: `/styles/`,
collapsable: false,
initialOpenGroupIndex: -1,
children: Object.keys(styles)
.sort()
.map((style) => {
return {
title: camelCaseToSpaceCase(style),
path: `/styles/${camelCaseToKebabCase(style)}/`,
};
}),
},
],
},
],
},
additionalPages: Object.keys(styles).map((style) => {
return {
path: `/styles/${camelCaseToKebabCase(style)}/`,
filePath: path.resolve(__dirname, 'pages/styles/[style].md'),
};
}),
/**
* Apply plugins,ref:https://v1.vuepress.vuejs.org/zh/plugin/
*/
plugins: ['@vuepress/plugin-back-to-top', '@vuepress/plugin-medium-zoom'],
};
|
var KS = {};
/**
* 工具函数包
* @file
* @module KS.utils
* @since 1.0.0
*/
/**
* 封装的静态工具函数
* @module KS.utils
* @unfile
*/
var utils = KS.utils = {
/**
* 用给定的迭代器遍历对象
* @method each
* @param { Object } obj 需要遍历的对象
* @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
* @example
* ```javascript
* var demoObj = {
* key1: 1,
* key2: 2
* };
*
* //output: key1: 1, key2: 2
* KS.utils.each( demoObj, funciton ( value, key ) {
*
* console.log( key + ":" + value );
*
* } );
* ```
*/
/**
* 用给定的迭代器遍历数组或类数组对象
* @method each
* @param { Array } array 需要遍历的数组或者类数组
* @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
* @example
* ```javascript
* var divs = document.getElmentByTagNames( "div" );
*
* //output: 0: DIV, 1: DIV ...
* KS.utils.each( divs, funciton ( value, key ) {
*
* console.log( key + ":" + value.tagName );
*
* } );
* ```
*/
each: function(obj, iterator, context) {
if (obj == null) return;
if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (iterator.call(context, obj[i], i, obj) === false)
return false;
}
} else {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (iterator.call(context, obj[key], key, obj) === false)
return false;
}
}
}
},
/**
* 移除数组array中所有的元素item
* @method removeItem
* @param { Array } array 要移除元素的目标数组
* @param { * } item 将要被移除的元素
* @remind 该方法的匹配过程使用的是恒等“===”
* @example
* ```javascript
* var arr = [ 4, 5, 7, 1, 3, 4, 6 ];
*
* KS.utils.removeItem( arr, 4 );
* //output: [ 5, 7, 1, 3, 6 ]
* console.log( arr );
*
* ```
*/
removeItem: function(array, item) {
for (var i = 0, l = array.length; i < l; i++) {
if (array[i] === item) {
array.splice(i, 1);
i--;
}
}
},
/**
* 删除字符串str的首尾空格
* @method trim
* @param { String } str 需要删除首尾空格的字符串
* @return { String } 删除了首尾的空格后的字符串
*/
trim: function(str) {
return str.replace(/(^[ \t\n\r]+)|([ \t\n\r]+$)/g, '');
},
/**
* 将str中的html符号转义,将转义“',&,<,",>”五个字符
* @method unhtml
* @param { String } str 需要转义的字符串
* @return { String } 转义后的字符串
* @example
* ```javascript
* var html = '<body>&</body>';
*
* //output: <body>&</body>
* console.log( KS.utils.unhtml( html ) );
*
* ```
*/
unhtml: function(str, reg) {
return str ? str.replace(reg || /[&<">'](?:(amp|lt|quot|gt|#39|nbsp|#\d+);)?/g, function(a, b) {
if (b) {
return a;
} else {
return {
'<': '<',
'&': '&',
'"': '"',
'>': '>',
"'": '''
}[a]
}
}) : '';
},
/**
* 将url中的html字符转义, 仅转义 ', ", <, > 四个字符
* @param { String } str 需要转义的字符串
* @param { RegExp } reg 自定义的正则
* @return { String } 转义后的字符串
*/
unhtmlForUrl: function(str, reg) {
return str ? str.replace(reg || /[<">']/g, function(a) {
return {
'<': '<',
'&': '&',
'"': '"',
'>': '>',
"'": ''',
'`': '`'
}[a]
}) : '';
},
/**
* 将str中的转义字符还原成html字符
* @see KS.utils.unhtml(String);
* @method html
* @param { String } str 需要逆转义的字符串
* @return { String } 逆转义后的字符串
* @example
* ```javascript
*
* var str = '<body>&</body>';
*
* //output: <body>&</body>
* console.log( KS.utils.html( str ) );
*
* ```
*/
html: function(str) {
return str ? str.replace(/&((g|l|quo)t|amp|#39|nbsp);/g, function(m) {
return {
'<': '<',
'&': '&',
'"': '"',
'>': '>',
''': "'",
' ': ' '
}[m]
}) : '';
},
/**
* 将css样式转换为驼峰的形式
* @method cssStyleToDomStyle
* @param { String } cssName 需要转换的css样式名
* @return { String } 转换成驼峰形式后的css样式名
* @example
* ```javascript
*
* var str = 'border-top';
*
* // output: borderTop
* console.log( KS.utils.cssStyleToDomStyle( str ) );
*
* ```
**/
cssStyleToDomStyle: function() {
cache = {};
return function(cssName) {
return cache[cssName] || (cache[cssName] = cssName.toLowerCase().replace(/-./g, function(match) {
return match.charAt(1).toUpperCase();
}));
};
}(),
/**
* 动态加载文件到doc中
* @method loadFile
* @param { DomDocument } document 需要加载资源文件的文档对象
* @param { Object } options 加载资源文件的属性集合, 取值请参考代码示例
* @example
* ```javascript
*
* KS.utils.loadFile( document, {
* src:"test.js",
* tag:"script",
* type:"text/javascript",
* defer:"defer"
* } );
*
* ```
*/
/**
* 动态加载文件到doc中,加载成功后执行的回调函数fn
* @method loadFile
* @param { DomDocument } doc 需要加载资源文件的文档对象
* @param { Object } options 加载资源文件的属性集合, 该集合支持的值是script标签和style标签支持的所有属性。
* @param { Function } fn 资源文件加载成功之后执行的回调
* @warning 对于在同一个文档中多次加载同一URL的文件, 该方法会在第一次加载之后缓存该请求,
* 在此之后的所有同一URL的请求, 将会直接触发回调。
* @example
* ```javascript
*
* KS.utils.loadFile( document, {
* src:"test.js",
* tag:"script",
* type:"text/javascript",
* defer:"defer"
* }, function () {
* console.log('加载成功');
* } );
*
* ```
*/
loadFile: function() {
var tmpList = [];
function getItem(doc, obj) {
for (var i = 0, ci; ci = tmpList[i++];) {
if (ci.doc === doc && ci.url == (obj.src || obj.href)) {
return ci;
}
}
}
return function(doc, obj, fn) {
var item = getItem(doc, obj);
if (item) {
if (item.ready) { //多次加载,后面的直接执行缓存里面的文件
fn && fn();
} else { //
item.funs.push(fn) //把传入的回调保存起来
}
return;
}
tmpList.push({
doc: doc,
url: obj.src || obj.href,
funs: [fn]
});
if (!doc.body) { //若没有body标签(不考虑dom性能)
var html = [];
for (var p in obj) { //给动态加载的标签添加属性
if (p == 'tag') continue;
html.push(p + '="' + obj[p] + '"')
}
//把添加的标签插入到html中
doc.write('<' + obj.tag + ' ' + html.join(' ') + ' ></' + obj.tag + '>');
return;
}
if (obj.id && doc.getElementById(obj.id)) { //传进来的标签的ID与页面已有标签ID冲突
return;
}
var element = doc.createElement(obj.tag); //有body标签,动态创建一个对应的标签
delete obj.tag;
for (var p in obj) { //添加属性
element.setAttribute(p, obj[p]);
}
element.onload = function() { //动态加载的标签加载完毕后触发此事件
item = getItem(doc, obj);
if (item.funs.length > 0) {
item.ready = 1;
for (var fi; fi = item.funs.pop();) {
fi();
}
}
};
element.onerror = function() {
throw Error('The load ' + (obj.href || obj.src) + ' fails ')
};
doc.getElementsByTagName("head")[0].appendChild(element);
}
}(),
/**
* 判断obj对象是否为空
* @method isEmptyObject
* @param { * } obj 需要判断的对象
* @remind 如果判断的对象是NULL, 将直接返回true, 如果是数组且为空, 返回true, 如果是字符串, 且字符串为空,
* 返回true, 如果是普通对象, 且该对象没有任何实例属性, 返回true
* @return { Boolean } 对象是否为空
* @example
* ```javascript
*
* //output: true
* console.log( KS.utils.isEmptyObject( {} ) );
*
* //output: true
* console.log( KS.utils.isEmptyObject( [] ) );
*
* //output: true
* console.log( KS.utils.isEmptyObject( "" ) );
*
* //output: false
* console.log( KS.utils.isEmptyObject( { key: 1 } ) );
*
* //output: false
* console.log( KS.utils.isEmptyObject( [1] ) );
*
* //output: false
* console.log( KS.utils.isEmptyObject( "1" ) );
*
* ```
*/
isEmptyObject: function(obj) {
if (obj == null) return true;
if (this.isArray(obj) || this.isString(obj)) return obj.length === 0;
for (var key in obj)
if (obj.hasOwnProperty(key)) return false;
return true;
},
/**
* 把rgb格式的颜色值转换成16进制格式
* @method fixColor
* @param { String } value rgb格式的颜色值
* @return { String }
* @example
* rgb(255,255,255) => "#ffffff"
*/
fixColor: function(value) {
if (/rgba?/.test(value)) {
var array = value.split(",");
if (array.length > 3)
return "";
value = "#";
for (var i = 0, color; color = array[i++];) {
color = parseInt(color.replace(/[^\d]/gi, ''), 10).toString(16);
value += color.length == 1 ? "0" + color : color;
}
value = value.toUpperCase();
}
return value;
},
/**
* 把cm/pt为单位的值转换为px为单位的值
* @method transUnitToPx
* @param { String } 待转换的带单位的字符串
* @return { String } 转换为px为计量单位的值的字符串
* @example
* ```javascript
*
* //output: 500px
* console.log( KS.utils.transUnitToPx( '20cm' ) );
*
* //output: 27px
* console.log( KS.utils.transUnitToPx( '20pt' ) );
*
* ```
*/
transUnitToPx: function(val) {
if (!/(pt|cm)/.test(val)) {
return val
}
var unit;
val.replace(/([\d.]+)(\w+)/, function(str, v, u) {
val = v;
unit = u;
});
switch (unit) {
case 'cm':
val = parseFloat(val) * 25;
break;
case 'pt':
val = Math.round(parseFloat(val) * 96 / 72);
}
return val + (val ? 'px' : '');
},
/**
* 在dom树ready之后执行给定的回调函数
* @method domReady
* @remind 如果在执行该方法的时候, dom树已经ready, 那么回调函数将立刻执行
* @param { Function } fn dom树ready之后的回调函数
* @example
* ```javascript
*
* KS.utils.domReady( function () {
*
* console.log('123');
*
* } );
*
* ```
*/
domReady: function() {
var fnArr = [];
function doReady(doc) {
//确保onready只执行一次
doc.isReady = true;
for (var ci; ci = fnArr.pop(); ci()) {}
}
return function(onready, win) {
win = win || window;
var doc = win.document;
onready && fnArr.push(onready);
//如果doReady执行过一次,后面再次调用该方法时直接执行
doc.isReady && doReady(doc);
doc.addEventListener("DOMContentLoaded", function() {
//doc.removeEventListener("DOMContentLoaded", arguments.callee, false);
doReady(doc);
}, false);
win.addEventListener('load', function() {
doReady(doc)
}, false);
}
}(),
//格式化url
formatUrl: function(url) {
var u = url.replace(/&&/g, '&');
u = u.replace(/\?&/g, '?');
u = u.replace(/&$/g, '');
u = u.replace(/&#/g, '#');
u = u.replace(/&+/g, '&');
return u;
},
clearEmptyAttrs: function(obj) {
for (var p in obj) {
if (obj[p] === '') {
delete obj[p]
}
}
return obj;
},
extend: function() { //from jq
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if (typeof target === "boolean") {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if (typeof target !== "object" && !KS.utils.isFunction(target)) {
target = {};
}
for (; i < length; i++) {
// Only deal with non-null/undefined values
if ((options = arguments[i]) != null) {
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target === copy) {
continue;
}
// Recurse if we're merging plain objects or arrays
if (deep && copy && (KS.utils.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && Array.isArray(src) ? src : [];
} else {
clone = src && KS.utils.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[name] = KS.utils.extend(deep, clone, copy);
// Don't bring in undefined values
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
// Return the modified object
return target;
},
isPlainObject: function(obj) {
if (!KS.utils.isObject(obj)) {
return false;
}
if (obj.constructor &&
!({}).hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf")) {
return false;
}
//如果函数执行到这里还没有return ,可以确定参数obj 是一个通过{}或者new Object构造的纯粹的对象
return true;
},
isEmptyObject: function(obj) {
var name;
for (name in obj) {
return false;
}
return true;
},
// 返回一个 [min, max] 范围内的任意整数
random: function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min + 1));
},
// 判断是否是有限的数字
isFinite: function(obj) {
//直接用现有方法
return isFinite(obj) && !KS.utils.isNaN(parseFloat(obj));
},
isNaN: function(obj) {
return KS.utils.isNumber(obj) && obj !== +obj;
},
isBoolean: function(obj) {
//前面两个子表达式是为了提高性能而已
return obj === true || obj === false || Object.prototype.toString.call(obj) === '[object Boolean]';
},
isWindow: function(obj) { //用Object.prototype.toString.call(obj)也是可以的,在ie9以及以上都是ok的,但这样性能更好
return obj != null && obj === obj.window;
},
// 判断是否是 null
isNull: function(obj) {
return obj === null;
},
// 判断是否是 undefined
// undefined 能被改写 (IE < 9)
// undefined 只是全局对象的一个属性
// 在局部环境能被重新定义
// 但是「void 0」始终是 undefined
isUndefined: function(obj) {
return obj === void 0;
},
// 判断对象中是否有指定 key
// own properties, not on a prototype
has: function(obj, key) {
// obj 不能为 null 或者 undefined
return obj != null && Object.prototype.hasOwnProperty.call(obj, key);
},
// 判断是否是 ArrayLike Object
// 类数组,即拥有 length 属性并且 length 属性值为 Number 类型的元素
// 包括数组、arguments、HTML Collection 以及 NodeList 等等
// 包括类似 {length: 10} 这样的对象
// 包括字符串、函数等
isArrayLike: function(collection) {
// 返回参数 collection 的 length 属性值
function property(key) {
return function(obj) {
return obj == null ? void 0 : obj[key];
};
}
// getLength 函数
// 该函数传入一个参数,返回参数的 length 属性值
// 用来获取 array 以及 arrayLike 元素的 length 属性值
var getLength = property('length');
// Math.pow(2, 53) - 1 是 JavaScript 中能精确表示的最大数字
var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
var length = getLength(collection);
return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
},
// 将一个对象的 key-value 键值对颠倒
// 即原来的 key 为 value 值,原来的 value 值为 key 值
// 需要注意的是,value 值不能重复(不然后面的会覆盖前面的)
// 且新构造的对象符合对象构造规则
// 并且返回新构造的对象
invert: function(obj) {
// 返回的新的对象
var result = {};
var keys = KS.utils.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
result[obj[keys[i]]] = keys[i];
}
return result;
},
// utils.keys({one: 1, two: 2, three: 3});
// => ["one", "two", "three"]
// ===== //
// 返回一个对象的 keys 组成的数组
// 仅返回 own enumerable properties 组成的数组
keys: function(obj) {
// 容错
// 如果传入的参数不是对象,则返回空数组
if (!KS.utils.isObject(obj)) return [];
// 如果浏览器支持 ES5 Object.keys() 方法
// 则优先使用该方法
if (Object.keys) return Object.keys(obj);
var keys = [];
// own enumerable properties
for (var key in obj)
// hasOwnProperty
if (KS.utils.has(obj, key)) keys.push(key);
return keys;
},
// 返回一个对象的 keys 数组
// 不仅仅是 own enumerable properties
// 还包括原型链上继承的属性
allKeys: function(obj) {
// 容错
// 不是对象,则返回空数组
if (!KS.utils.isObject(obj)) return [];
var keys = [];
for (var key in obj) keys.push(key);
return keys;
},
// utils.values({one: 1, two: 2, three: 3});
// => [1, 2, 3]
// ===== //
// 将一个对象的所有 values 值放入数组中
// 仅限 own properties 上的 values
// 不包括原型链上的
// 并返回该数组
values: function(obj) {
// 仅包括 own properties
var keys = KS.utils.keys(obj);
var length = keys.length;
var values = Array(length);
for (var i = 0; i < length; i++) {
values[i] = obj[keys[i]];
}
return values;
},
// attrs 参数为一个对象
// 判断 object 对象中是否有 attrs 中的所有 key-value 键值对
// 返回布尔值
isMatch: function(object, attrs) {
// 提取 attrs 对象的所有 keys
var keys = KS.utils.keys(attrs),
length = keys.length;
// 如果 object 为空
// 根据 attrs 的键值对数量返回布尔值
if (object == null) return !length;
var obj = Object(object);
// 遍历 attrs 对象键值对
for (var i = 0; i < length; i++) {
var key = keys[i];
// 如果 obj 对象没有 attrs 对象的某个 key
// 或者对于某个 key,它们的 value 值不同
// 则证明 object 并不拥有 attrs 的所有键值对
// 则返回 false
if (attrs[key] !== obj[key] || !(key in obj)) return false;
}
return true;
},
//传入参数可以说一个一个的数字,也可以是一个数组
max: function() {
if (arguments.length == 0) { return false }
if (arguments.length > 1) {
return Math.max.apply(Math, arguments)
} else {
if (KS.utils.isArray(arguments[0])) {
return Math.max.apply(Math, arguments[0])
}
return arguments[0]
}
},
min: function() {
if (arguments.length == 0) { return false }
if (arguments.length > 1) {
return Math.min.apply(Math, arguments)
} else {
if (KS.utils.isArray(arguments[0])) {
return Math.min.apply(Math, arguments[0])
}
return arguments[0]
}
},
// 判断是否为 DOM 元素
isElement: function(obj) {
// 确保 obj 不是 null, undefined 等假值
// 并且 obj.nodeType === 1
return !!(obj && obj.nodeType === 1);
},
// 将数组乱序
// 如果是对象,则返回一个数组,数组由对象 value 值构成
// Fisher-Yates shuffle 算法
// 最优的洗牌算法,复杂度 O(n)
// 乱序不要用 sort + Math.random(),复杂度 O(nlogn)
// 而且,并不是真正的乱序
shuffle: function(obj) {
// 如果是对象,则对 value 值进行乱序
var set = utils.isArrayLike(obj) ? obj : utils.values(obj);
var length = set.length;
// 乱序后返回的数组副本(参数是对象则返回乱序后的 value 数组)
var shuffled = Array(length);
// 枚举元素
for (var index = 0, rand; index < length; index++) {
// 将当前所枚举位置的元素和 `index=rand` 位置的元素交换
rand = utils.random(0, index);
if (rand !== index) shuffled[index] = shuffled[rand];
shuffled[rand] = set[index];
}
return shuffled;
},
// 随机返回数组或者对象中的一个元素
// 如果指定了参数 `n`,则随机返回 n 个元素组成的数组
// 如果参数是对象,则数组由 values 组成
sample: function(obj, n, guard) {
// 随机返回一个元素 null==undefined ==> true
if (n == null || guard) {
if (!utils.isArrayLike(obj)) obj = utils.values(obj);
return obj[utils.random(obj.length - 1)];
}
// 随机返回 n 个
return utils.shuffle(obj).slice(0, Math.max(0, n));
},
// 返回某一个范围内的数组成的数组
range: function(start, stop, step) {
if (stop == null) {
stop = start || 0;
start = 0;
}
step = step || 1;
// 返回数组的长度
var length = Math.max(Math.ceil((stop - start) / step), 0);
// 返回的数组
var range = Array(length);
for (var idx = 0; idx < length; idx++, start += step) {
range[idx] = start;
}
return range;
},
// 函数节流(如果有连续事件响应,则每间隔一定时间段触发)
// 每间隔 wait(Number) milliseconds 触发一次 func 方法
// 如果 options 参数传入 {leading: false}
// 那么不会马上触发(等待 wait milliseconds 后第一次触发 func)
// 如果 options 参数传入 {trailing: false}
// 那么最后一次回调不会被触发
// **Notice: options 不能同时设置 leading 和 trailing 为 false**
// 示例:
// var throttled = utils.throttle(updatePosition, 100);
// $(window).scroll(throttled);
// 调用方式(注意看 A 和 B console.log 打印的位置):
// utils.throttle(function, wait, [options])
// sample 1: utils.throttle(function(){}, 1000)
// print: A, B, B, B ...
// sample 2: utils.throttle(function(){}, 1000, {leading: false})
// print: B, B, B, B ...
// sample 3: utils.throttle(function(){}, 1000, {trailing: false})
// print: A, A, A, A ...
// ----------------------------------------- //
throttle: function(func, wait, options) {
var context, args, result;
// setTimeout 的 handler
var timeout = null;
// 标记时间戳
// 上一次执行回调的时间戳
var previous = 0;
// 如果没有传入 options 参数
// 则将 options 参数置为空对象
if (!options)
options = {};
var later = function() {
// 如果 options.leading === false
// 则每次触发回调后将 previous 置为 0
// 否则置为当前时间戳
previous = options.leading === false ? 0 : Date.now();
timeout = null;
// console.log('B')
result = func.apply(context, args);
// 这里的 timeout 变量一定是 null 了吧
// 是否没有必要进行判断?
if (!timeout)
context = args = null;
};
// 以滚轮事件为例(scroll)
// 每次触发滚轮事件即执行这个返回的方法
// utils.throttle 方法返回的函数
return function() {
// 记录当前时间戳
var now = Date.now();
// 第一次执行回调(此时 previous 为 0,之后 previous 值为上一次时间戳)
// 并且如果程序设定第一个回调不是立即执行的(options.leading === false)
// 则将 previous 值(表示上次执行的时间戳)设为 now 的时间戳(第一次触发时)
// 表示刚执行过,这次就不用执行了
if (!previous && options.leading === false)
previous = now;
// 距离下次触发 func 还需要等待的时间
var remaining = wait - (now - previous);
context = this;
args = arguments;
// 要么是到了间隔时间了,随即触发方法(remaining <= 0)
// 要么是没有传入 {leading: false},且第一次触发回调,即立即触发
// 此时 previous 为 0,wait - (now - previous) 也满足 <= 0
// 之后便会把 previous 值迅速置为 now
// ========= //
// remaining > wait,表示客户端系统时间被调整过
// 则马上执行 func 函数
// ========= //
// console.log(remaining) 可以打印出来看看
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
// 解除引用,防止内存泄露
timeout = null;
}
// 重置前一次触发的时间戳
previous = now;
// 触发方法
// result 为该方法返回值
// console.log('A')
result = func.apply(context, args);
// 引用置为空,防止内存泄露
// 感觉这里的 timeout 肯定是 null 啊?这个 if 判断没必要吧?
if (!timeout)
context = args = null;
} else if (!timeout && options.trailing !== false) { // 最后一次需要触发的情况
// 如果已经存在一个定时器,则不会进入该 if 分支
// 如果 {trailing: false},即最后一次不需要触发了,也不会进入这个分支
// 间隔 remaining milliseconds 后触发 later 方法
timeout = setTimeout(later, remaining);
}
// 回调返回值
return result;
};
},
// 函数去抖(连续事件触发结束后只触发一次)
// sample 1: utils.debounce(function(){}, 1000)
// 连续事件结束后的 1000ms 后触发
// sample 1: utils.debounce(function(){}, 1000, true)
// 连续事件触发后立即触发(此时会忽略第二个参数)
debounce: function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
var later = function() {
// 定时器设置的回调 later 方法的触发时间,和连续事件触发的最后一次时间戳的间隔
// 如果间隔为 wait(或者刚好大于 wait),则触发事件
var last = Date.now() - timestamp;
// 时间间隔 last 在 [0, wait) 中
// 还没到触发的点,则继续设置定时器
// last 值应该不会小于 0 吧?
if (last < wait && last >= 0) {
timeout = setTimeout(later, wait - last);
} else {
// 到了可以触发的时间点
timeout = null;
// 可以触发了
// 并且不是设置为立即触发的
// 因为如果是立即触发(callNow),也会进入这个回调中
// 主要是为了将 timeout 值置为空,使之不影响下次连续事件的触发
// 如果不是立即执行,随即执行 func 方法
if (!immediate) {
// 执行 func 函数
result = func.apply(context, args);
// 这里的 timeout 一定是 null 了吧
// 感觉这个判断多余了
if (!timeout)
context = args = null;
}
}
};
// 嗯,闭包返回的函数,是可以传入参数的
// 也是 DOM 事件所触发的回调函数
return function() {
// 可以指定 this 指向
context = this;
args = arguments;
// 每次触发函数,更新时间戳
// later 方法中取 last 值时用到该变量
// 判断距离上次触发事件是否已经过了 wait seconds 了
// 即我们需要距离最后一次事件触发 wait seconds 后触发这个回调方法
timestamp = Date.now();
// 立即触发需要满足两个条件
// immediate 参数为 true,并且 timeout 还没设置
// immediate 参数为 true 是显而易见的
// 如果去掉 !timeout 的条件,就会一直触发,而不是触发一次
// 因为第一次触发后已经设置了 timeout,所以根据 timeout 是否为空可以判断是否是首次触发
var callNow = immediate && !timeout;
// 设置 wait seconds 后触发 later 方法
// 无论是否 callNow(如果是 callNow,也进入 later 方法,去 later 方法中判断是否执行相应回调函数)
// 在某一段的连续触发中,只会在第一次触发时进入这个 if 分支中
if (!timeout)
// 设置了 timeout,所以以后不会进入这个 if 分支了
timeout = setTimeout(later, wait);
// 如果是立即触发
if (callNow) {
// func 可能是有返回值的
result = func.apply(context, args);
// 解除引用
context = args = null;
}
return result;
};
},
/**
* 创建延迟指定时间后执行的函数fn
* @method defer
* @param { Function } fn 需要延迟执行的函数对象
* @param { int } delay 延迟的时间, 单位是毫秒
* @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
* 而不能保证刚好到达延迟时间时执行。
* @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
* @example
* ```javascript
* var start = 0;
*
* function test(){
* console.log( new Date() - start );
* }
*
* var testDefer = KS.utils.defer( test, 1000 );
* //
* start = new Date();
* //output: (大约在1000毫秒之后输出) 1000
* testDefer();
* ```
*/
/**
* 创建延迟指定时间后执行的函数fn, 如果在延迟时间内再次执行该方法, 将会根据指定的exclusion的值,
* 决定是否取消前一次函数的执行, 如果exclusion的值为true, 则取消执行,反之,将继续执行前一个方法。
* @method defer
* @param { Function } fn 需要延迟执行的函数对象
* @param { int } delay 延迟的时间, 单位是毫秒
* @param { Boolean } exclusion 如果在延迟时间内再次执行该函数,该值将决定是否取消执行前一次函数的执行,
* 值为true表示取消执行, 反之则将在执行前一次函数之后才执行本次函数调用。
* @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
* 而不能保证刚好到达延迟时间时执行。
* @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
* @example
* ```javascript
*
* function test(){
* console.log(1);
* }
*
* var testDefer = KS.utils.defer( test, 1000, true );
*
* //output: (两次调用仅有一次输出) 1
* testDefer();
* testDefer();
* ```
*/
defer: function(fn, delay, exclusion) {
var timerID;
return function() {
if (exclusion) {
clearTimeout(timerID);
}
timerID = setTimeout(fn, delay);
};
},
/**
* 删除字符串str的首尾空格
* @method trim
* @param { String } str 需要删除首尾空格的字符串
* @return { String } 删除了首尾的空格后的字符串
* @example
* ```javascript
*
* var str = " KS ";
*
* //output: 9
* console.log( str.length );
*
* //output: 7
* console.log( KS.utils.trim( " KS " ).length );
*
* //output: 9
* console.log( str.length );
*
* ```
*/
trim: function(str) {
return str.replace(/(^[ \t\n\r]+)|([ \t\n\r]+$)/g, '');
},
/**
* 克隆对象
* @method clone
* @param { Object } source 源对象
* @return { Object } source的一个副本
*/
/**
* 深度克隆对象,将source的属性克隆到target对象, 会覆盖target重名的属性。
* @method clone
* @param { Object } source 源对象
* @param { Object } target 目标对象
* @return { Object } 附加了source对象所有属性的target对象
*/
clone: function(source, target) {
var tmp;
target = target || {};
for (var i in source) {
if (source.hasOwnProperty(i)) {
tmp = source[i];
if (typeof tmp == 'object') {
target[i] = utils.isArray(tmp) ? [] : {};
utils.clone(source[i], target[i])
} else {
target[i] = tmp;
}
}
}
return target;
},
isCrossDomainUrl: function(url) {
var a = document.createElement('a');
a.href = url;
if (browser.ie) {
a.href = a.href;
}
return !(a.protocol == location.protocol && a.hostname == location.hostname &&
(a.port == location.port || (a.port == '80' && location.port == '') || (a.port == '' && location.port == '80')));
},
// 将一个对象转换为元素为 [key, value] 形式的数组
// utils.pairs({one: 1, two: 2, three: 3});
// => [["one", 1], ["two", 2], ["three", 3]]
pairs: function(obj) {
var keys = utils.keys(obj);
var length = keys.length;
var pairs = Array(length);
for (var i = 0; i < length; i++) {
pairs[i] = [keys[i], obj[keys[i]]];
}
return pairs;
},
// attrs 参数为一个对象
// 判断 object 对象中是否有 attrs 中的所有 key-value 键值对
// 返回布尔值
isMatch: function(object, attrs) {
// 提取 attrs 对象的所有 keys
var keys = utils.keys(attrs),
length = keys.length;
// 如果 object 为空
// 根据 attrs 的键值对数量返回布尔值
if (object == null) return !length;
// 遍历 attrs 对象键值对
for (var i = 0; i < length; i++) {
var key = keys[i];
// 如果 obj 对象没有 attrs 对象的某个 key
// 或者对于某个 key,它们的 value 值不同
// 则证明 object 并不拥有 attrs 的所有键值对
// 则返回 false
if (attrs[key] !== object[key] || !(key in object)) return false;
}
return true;
},
// 如果是数组(类数组),返回长度(length 属性)
// 如果是对象,返回键值对数量
size: function(obj) {
if (obj == null) return 0;
return utils.isArrayLike(obj) ? obj.length : utils.keys(obj).length;
},
// 伪数组 -> 数组
// 对象 -> 提取 value 值组成数组
// 返回数组
toArray: function(obj) {
if (!obj) return [];
// 如果是数组,则返回副本数组
// 也可用 obj.concat()
if (utils.isArray(obj)) return Array.prototype.slice.call(obj);
// 如果是类数组,则重新构造新的数组
if (utils.isArrayLike(obj)) return Array.prototype.slice.call(obj);
// 如果是对象,则返回 values 集合
return utils.values(obj);
},
//闭包保存length,防止反复访问数组的length属性
getLength: function(key) {
return function(obj) {
return obj == null ? void 0 : obj[key];
};
}(length),
// 将嵌套的数组展开
// 如果参数 (shallow === true),则仅展开一层
// utils.flatten([1, [2], [3, [[4]]]]);
// => [1, 2, 3, 4];
// ====== //
// utils.flatten([1, [2], [3, [[4]]]], true);
// => [1, 2, 3, [[4]]];
flatten: function(array, shallow) {
// 递归调用数组,将数组展开
// 即 [1, 2, [3, 4]] => [1, 2, 3, 4]
// flatten(array, shallow, false)
// flatten(arguments, true, true, 1)
// flatten(arguments, true, true)
// flatten(arguments, false, false, 1)
// ===== //
// input => Array 或者 arguments
// shallow => 是否只展开一层
// strict === true,通常和 shallow === true 配合使用
// 表示只展开一层,但是不保存非数组元素(即无法展开的基础类型)
// flatten([[1, 2], 3, 4], true, true) => [1, 2]
// flatten([[1, 2], 3, 4], false, true) = > []
// startIndex => 从 input 的第几项开始展开
// ===== //
// 如果 strict 参数为 true,那么 shallow 也为 true
// 也就是展开一层,同时把非数组过滤
// [[1, 2], [3, 4], 5, 6] => [1, 2, 3, 4]
var flatten = function(input, shallow, strict, startIndex) {
// output 数组保存结果
// 即 flatten 方法返回数据
// idx 为 output 的累计数组下标
var output = [],
idx = 0;
// 根据 startIndex 变量确定需要展开的起始位置
for (var i = startIndex || 0, length = utils.getLength(input); i < length; i++) {
var value = input[i];
// 数组 或者 arguments
// 注意 isArrayLike 还包括 {length: 10} 这样的,过滤掉
if (utils.isArrayLike(value) && (utils.isArray(value) || utils.isArguments(value))) {
// flatten current level of array or arguments object
// (!shallow === true) => (shallow === false)
// 则表示需深度展开
// 继续递归展开
if (!shallow)
// flatten 方法返回数组
// 将上面定义的 value 重新赋值
value = flatten(value, shallow, strict);
// 递归展开到最后一层(没有嵌套的数组了)
// 或者 (shallow === true) => 只展开一层
// value 值肯定是一个数组
var j = 0,
len = value.length;
// 这一步貌似没有必要
// 毕竟 JavaScript 的数组会自动扩充
// 但是这样写,感觉比较好,对于元素的 push 过程有个比较清晰的认识
output.length += len;
// 将 value 数组的元素添加到 output 数组中
while (j < len) {
output[idx++] = value[j++];
}
} else if (!strict) {
// 如果是深度展开,即 shallow 参数为 false
// 那么当最后 value 不是数组,是基本类型时
// 肯定会走到这个 else-if 判断中
// 而如果此时 strict 为 true,则不能跳到这个分支内部
// 所以 shallow === false 如果和 strict === true 搭配
// 调用 flatten 方法得到的结果永远是空数组 []
output[idx++] = value;
}
}
return output;
};
// array => 需要展开的数组
// shallow => 是否只展开一层
// false 为 flatten 方法 strict 变量
return flatten(array, shallow, false);
},
// 将数组转化为对象
object: function(list, values) {
var result = {};
for (var i = 0, length = utils.getLength(list); i < length; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
},
// 指定一系列方法(methodNames)中的 this 指向(object)
// bindAll(object, *methodNames)
bindAll: function(obj) {
var i, length = arguments.length,
key;
// 如果只传入了一个参数(obj),没有传入 methodNames,则报错
if (length <= 1)
throw new Error('bindAll必须传入方法名');
// 遍历 methodNames
for (i = 1; i < length; i++) {
key = arguments[i];
// 逐个绑定
//obj[key] = Function.prototype.bind.call(obj[key],obj);
obj[key] = obj[key].bind(obj);
}
return obj;
},
//「记忆化」,存储中间运算结果,提高效率
// 参数 hasher 是个 function,用来计算 key
// 如果传入了 hasher,则用 hasher 来计算 key
// 否则用 key 参数直接当 key(即 memoize 方法传入的第一个参数)
// utils.memoize(function, [hashFunction])
// 适用于需要大量重复求值的场景
// 比如递归求解菲波那切数
memoize: function(func, hasher) {
var memoize = function(key) {
// 储存变量,方便使用
var cache = memoize.cache;
// 求 key
// 如果传入了 hasher,则用 hasher 函数来计算 key
// 否则用 参数 key(即 memoize 方法传入的第一个参数)当 key
var address = '' + (hasher ? hasher.apply(this, arguments) : key);
// 如果这个 key 还没被 hash 过(还没求过值)
if (!utils.has(cache, address))
cache[address] = func.apply(this, arguments);
// 返回
return cache[address];
};
// cache 对象被当做 key-value 键值对缓存中间运算结果
memoize.cache = {};
// 返回一个函数(经典闭包)
return memoize;
},
//获取数组中最大或者最小值,该方法适合一维或者多维数组求最大最小值的情况
maxAndMin: function(arr) {
return {
max: Math.max.apply(null, arr.join(',').split(',')),
min: Math.min.apply(null, arr.join(',').split(','))
}
},
//生成指定长度的随机字母数字字符串
getRandomStr: function(len) {
var str = "";
for (; str.length < len; str += Math.random().toString(36).substring(2));
return str.substring(0, len);
},
// 延迟触发某方法
// utils.delay(function, wait, *arguments)
// 如果传入了 arguments 参数,则会被当作 func 的参数在触发时调用
// 其实是封装了「延迟触发某方法」,使其复用
delay: function(func, wait) {
// 获取 *arguments
// 是 func 函数所需要的参数
var args = slice.call(arguments, 2);
return setTimeout(function() {
// 将参数赋予 func 函数
return func.apply(null, args);
}, wait);
},
// 第 times 触发执行 func(事实上之后的每次触发还是会执行 func)
// 有什么用呢?
// 如果有 N 个异步事件,所有异步执行完后执行该回调,即 func 方法(联想 eventproxy)
// utils.after 会返回一个函数
// 当这个函数第 times 被执行的时候
// 触发 func 方法
/**render在所有异步都保存成功后才执行
* var renderNotes = utils.after(notes.length, render);
utils.each(notes, function(note) {
note.asyncSave({success: renderNotes});
});
*/
after: function(times, func) {
return function() {
// 函数被触发了 times 了,则执行 func 函数
// 事实上 times 次后如果函数继续被执行,也会触发 func
if (--times < 1) {
return func.apply(this, arguments);
}
};
},
// 函数至多被调用 times - 1 次((but not including) the Nth call)
// func 函数会触发 time - 1 次(Creates a version of the function that can be called no more than count times)
// func 函数有个返回值,前 time - 1 次触发的返回值都是将参数代入重新计算的
// 第 times 开始的返回值为第 times - 1 次时的返回值(不重新计算)
// The result of the last function call is memoized and returned when count has been reached.
/* 创建一个函数,调用不超过count 次。 当count已经达到时,最后一个函数调用的结果 是被记住并返回 。
var monthlyMeeting = utils.before(3, askForRaise);
monthlyMeeting();
monthlyMeeting();
monthlyMeeting();
//所以monthlyMeeting第二次调用的和以后调用的结果一样
*/
before: function(times, func) {
var memo;
return function() {
if (--times > 0) {
// 缓存函数执行结果
memo = func.apply(this, arguments);
}
// func 引用置为空,其实不置为空也用不到 func 了
if (times <= 1)
func = null;
// 前 times - 1 次触发,memo 都是分别计算返回
// 第 times 次开始,memo 值同 times - 1 次时的 memo
return memo;
};
},
// 传入一个对象
// 遍历该对象的键值对(包括 own properties 以及 原型链上的)
// 如果某个 value 的类型是方法(function),则将该 key 存入数组
// 将该数组排序后返回,就是返回对象的方法名
methods: function(obj) {
// 返回的数组
var names = [];
for (var key in obj) {
// 如果某个 key 对应的 value 值类型是函数
// 则将这个 key 值存入数组
if (utils.isFunction(obj[key])) names.push(key);
}
// 返回排序后的数组
return names.sort();
},
//返回函数集 functions 组合后的复合函数, 也就是一个函数执行完之后把返回的结果再作为参数赋给下一个函数来执行. 以此类推. 在数学里, 把函数 f(), g(), 和 h() 组合起来可以得到复合函数 f(g(h()))。
/**
* var greet = function(name){ return "hi: " + name; };
var exclaim = function(statement){ return statement.toUpperCase() + "!"; };
var welcome = utils.compose(greet, exclaim);
welcome('moe');
=> 'hi: MOE!'
*/
compose: function() {
var args = arguments;
var start = args.length - 1;
return function() {
var i = start;
var result = args[start].apply(this, arguments);
while (i--) result = args[i].call(this, result);
return result;
};
},
// 判断两个对象是否一样
// new Boolean(true),true 被认为 equal
// [1, 2, 3], [1, 2, 3] 被认为 equal
// 0 和 -0 被认为 unequal
// NaN 和 NaN 被认为 equal
/* var a = Object.create(null);
a.x = 1;
var b = {x:1}; a,b被认为是equal
*/
isEqual: function(a, b) {
// isEqual方法的内部递归比较
// 该内部方法会被递归调用
var eq = function(a, b, aStack, bStack) {
//分析:为啥有两个stack,原因就判断那种自嵌套结构。由于是递归,得想办法把上一层对象传进来。不然怎么会知道是否自嵌套结构呢。
// a === b 时
// 需要注意 `0 === -0` 这个 special case
// 0 和 -0 被认为不相同(unequal)
// 至于原因可以参考上面的链接
if (a === b) return a !== 0 || 1 / a === 1 / b;
// null == undefined ==> true
// 如果 a 和 b 有一个为 null(或者 undefined)
// 判断 a === b
if (a == null || b == null) return a === b;
// 比较 `[[Class]]` names.
var className = Object.prototype.toString.call(a);
// 如果 a 和 b 类型不相同,则返回 false
if (className !== Object.prototype.toString.call(b)) return false;
switch (className) {
// Strings, numbers, regular expressions, dates, booleans可以直接根据其 value 值来比较是否相等
case '[object RegExp]':
// /ab/+""==="/ab/"
case '[object String]':
//"5" !=== new String(5) 但值相等,都是字符串“5”
// 转为 String 类型进行比较
return '' + a === '' + b;
// RegExp 和 String 可以看做一类
// 如果 obj 为 RegExp 或者 String 类型
// 那么 '' + obj 会将 obj 强制转为 String
// 根据 '' + a === '' + b 即可判断 a 和 b 是否相等
case '[object Number]':
// Object(NaN) is equivalent to NaN
// 如果 +a !== +a
// 那么 a 就是 NaN
// 判断 b 是否也是 NaN 即可
if (+a !== +a) return +b !== +b;
// An `egal` comparison is performed for other numeric values.
// 排除了 NaN 干扰
// 还要考虑 0 的干扰
// 用 +a 将 Number() 形式转为基本类型
// 即 +Number(1) ==> 1
// 0 需要特判
// 如果 a 为 0,判断 1 / +a === 1 / b
// 否则判断 +a === +b
return +a === 0 ? 1 / +a === 1 / b : +a === +b;
// 如果 a 为 Number 类型
// 要注意 NaN 这个 special number
// NaN 和 NaN 被认为 equal
// ================
case '[object Date]':
case '[object Boolean]':
return +a === +b;
// Date 和 Boolean 可以看做一类
// 如果 obj 为 Date 或者 Boolean
// 那么 +obj 会将 obj 转为 Number 类型
// 然后比较即可
// +new Date() 是当前时间距离 1970 年 1 月 1 日 0 点的毫秒数
// +true => 1
// +new Boolean(false) => 0
}
// 判断 a 是否是数组
var areArrays = className === '[object Array]';
// 如果 a 不是数组类型
if (!areArrays) {
// 如果 a 不是 object 或者 b 不是 object
// 则返回 false
if (typeof a != 'object' || typeof b != 'object') return false;
// 通过上个步骤的 if 过滤
// !!保证到此的 a 和 b 均为对象!!
// Object instance Object ==> true
/**
* 这个if主要针对对象的判断,进入此if的前提是a和b,都已经是对象了。逻辑是这样的,if里面返回的是false,即判断哪种情况下认为二者不等。
* 如果二者的constructor不等,一般认为对象不可能值相等。但有种情况例外,来自不同的iframe的Object实例,因为其构造器Object是属于不同window的函数Object,自然不等,但是有可能值相等。
* 所以要排除掉这种情况,utils.isFunction(aCtor) && aCtor instanceof aCtor 表示“一个函数是自己的实例”,如果该函数是Object,自然为true,因此前面取非表示排除了。
* 而后面'constructor' in a && 'constructor' in b,表示要求ab对象都有构造器属性。关于为啥有这一条。都有构造器,那没啥好说的。我们可以假设一下a没有,b有,
* 那么aCtor是undefined,则if是不进的,也就是说这种情况下也有可能认为ab相等,另外,来自不同iframe的对象实例,要使用firefox浏览器测试。chrome会报错。
*/
var aCtor = a.constructor,
bCtor = b.constructor;
if (aCtor !== bCtor && !(utils.isFunction(aCtor) && aCtor instanceof aCtor &&
utils.isFunction(bCtor) && bCtor instanceof bCtor) &&
('constructor' in a && 'constructor' in b)) {
return false;
}
}
// 第一次调用 eq() 函数,没有传入 aStack 和 bStack 参数
// 之后递归调用都会传入这两个参数
aStack = aStack || [];
bStack = bStack || [];
var length = aStack.length;
while (length--) {
/**自嵌套结构判断,如下面的a
*var a = {name : '11'};
*a.o = a;
*var c = a.o;
*alert(c.name);
*/
//如果a有嵌套现象,就看看b是否也有,注意a有,就返回了
if (aStack[length] === a) return bStack[length] === b;
}
//如果上面while中没有进if,这里把a和b放到栈里
aStack.push(a);
bStack.push(b);
// 递归比较对象和数组
// 将嵌套的对象和数组展开
// 如果 a 是数组
// 因为嵌套,所以需要展开深度比较
if (areArrays) {
// 根据 length 判断是否应该继续递归对比
length = a.length;
// 如果 a 和 b length 属性大小不同,返回false
if (length !== b.length) return false;
// //递归比较每个属性值是否相等
while (length--) {
// 递归
if (!eq(a[length], b[length], aStack, bStack)) return false;
}
} else {
// 如果 a 不是数组,这里的话即是对象
// 进入这个判断分支
// Deep compare objects.
// 两个对象的深度比较
var keys = utils.keys(a),
key;
length = keys.length;
// Ensure that both objects contain the same number of properties before comparing deep equality.
// a 和 b 对象的键数量不同
// 那还比较毛?
if (utils.keys(b).length !== length) return false;
while (length--) {
// Deep compare each member
// 递归比较
key = keys[length];
if (!(utils.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
}
}
// 与 aStack.push(a) 对应
// 此时 aStack 栈顶元素正是 a
// 而代码走到此步
// a 和 b isEqual 确认
// 所以 a,b 两个元素可以出栈
//移除栈里最新的元素。说明这层是相等的
aStack.pop();
bStack.pop();
// 深度搜索递归比较完毕
// 放心地 return true
return true;
};
return eq(a, b);
},
ajax: function(url, opts) {
var xhr = new XMLHttpRequest();
/**
* 将json参数转化成适合ajax提交的参数列表
* @param json
*/
function json2str(json) {
var strArr = [];
for (var i in json) {
//忽略默认的几个参数
if (i == "method" || i == "timeout" || i == "async" || i == "dataType" || i == "callback") continue;
//忽略控制
if (json[i] == undefined || json[i] == null) continue;
//传递过来的对象和函数不在提交之列
if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
strArr.push(encodeURIComponent(i) + "=" + encodeURIComponent(json[i]));
} else if (utils.isArray(json[i])) {
//支持传数组内容
for (var j = 0; j < json[i].length; j++) {
strArr.push(encodeURIComponent(i) + "[]=" + encodeURIComponent(json[i][j]));
}
}
}
return strArr.join("&");
}
function doAjax(url, ajaxOptions) {
//var xhr = creatAjaxRequest(),
//是否超时
timeIsOut = false,
//默认参数
defaultAjaxOptions = {
method: "POST",
timeout: 5000,
async: true,
data: {}, //需要传递对象的话只能覆盖
onsuccess: function() {},
onerror: function() {}
};
if (typeof url === "object") {
ajaxOptions = url;
url = ajaxOptions.url;
}
if (!xhr || !url) return;
var ajaxOpts = ajaxOptions ? utils.extend(defaultAjaxOptions, ajaxOptions) : defaultAjaxOptions;
var submitStr = json2str(ajaxOpts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
//如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
if (!utils.isEmptyObject(ajaxOpts.data)) {
submitStr += (submitStr ? "&" : "") + json2str(ajaxOpts.data);
}
//超时检测
var timerID = setTimeout(function() {
if (xhr.readyState != 4) {
timeIsOut = true;
xhr.abort();
clearTimeout(timerID);
}
}, ajaxOpts.timeout);
var method = ajaxOpts.method.toUpperCase();
var str = url + (url.indexOf("?") == -1 ? "?" : "&") + (method == "POST" ? "" : submitStr + "&noCache=" + +new Date);
xhr.open(method, str, ajaxOpts.async);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (!timeIsOut && xhr.status == 200) {
ajaxOpts.onsuccess(xhr);
} else {
ajaxOpts.onerror(xhr);
}
}
};
if (method == "POST") {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(submitStr);
} else {
xhr.send(null);
}
}
return doAjax(url, opts);
/**
* 根据给定的参数项,向指定的url发起一个ajax请求。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
* 成功, 则调用onsuccess回调, 失败则调用 onerror 回调
* @method request
* @param { URLString } url ajax请求的url地址
* @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
* @example
* ```javascript
* //向sayhello.php发起一个异步的Ajax GET请求, 请求超时时间为10s, 请求完成后执行相应的回调。
* utils.ajax( 'sayhello.php', {
*
* //请求方法。可选值: 'GET', 'POST',默认值是'POST'
* method: 'GET',
*
* //超时时间。 默认为5000, 单位是ms
* timeout: 10000,
*
* //是否是异步请求。 true为异步请求, false为同步请求
* async: true,
*
* //请求携带的数据。如果请求为GET请求, data会经过stringify后附加到请求url之后。
* data: {
* name: 'ueditor'
* },
*
* //请求成功后的回调, 该回调接受当前的XMLHttpRequest对象作为参数。
* onsuccess: function ( xhr ) {
* console.log( xhr.responseText );
* },
*
* //请求失败或者超时后的回调。
* onerror: function ( xhr ) {
* alert( 'Ajax请求失败' );
* }
*
* } );
* ```
*/
/**
* 根据给定的参数项发起一个ajax请求, 参数项里必须包含一个url地址。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
* 成功, 则调用onsuccess回调, 失败则调用 onerror 回调。
* @method request
* @warning 如果在参数项里未提供一个key为“url”的地址值,则该请求将直接退出。
* @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
* @example
* ```javascript
*
* //向sayhello.php发起一个异步的Ajax POST请求, 请求超时时间为5s, 请求完成后不执行任何回调。
* utils.ajax( 'sayhello.php', {
*
* //请求的地址, 该项是必须的。
* url: 'sayhello.php'
*
* } );
* ```
*/
}(url, opts),
randomAToZ: function(num) { //随机生成5个字母
var result = [];
var num = num || 6;
function getRanNum() {
result = [];
for (var i = 0; i < num; i++) {
var ranNum = Math.ceil(Math.random() * 25); //生成一个0到25的数字
//大写字母'A'的ASCII是65,A~Z的ASCII码就是65 + 0~25;然后调用String.fromCharCode()传入ASCII值返回相应的字符并push进数组里,a的ASCII码是97
result.push(String.fromCharCode(97 + ranNum));
}
return result.join("")
}
return getRanNum()
}
}
/**
* 判断给定的对象是否是字符串
* @method isString
* @param { * } object 需要判断的对象
* @return { Boolean } 给定的对象是否是字符串
*/
/**
* 判断给定的对象是否是数组
* @method isArray
* @param { * } object 需要判断的对象
* @return { Boolean } 给定的对象是否是数组
*/
/**
* 判断给定的对象是否是一个Function
* @method isFunction
* @param { * } object 需要判断的对象
* @return { Boolean } 给定的对象是否是Function
*/
/**
* 判断给定的对象是否是Number
* @method isNumber
* @param { * } object 需要判断的对象
* @return { Boolean } 给定的对象是否是Number
*/
/**
* 判断给定的对象是否是一个正则表达式
* @method isRegExp
* @param { * } object 需要判断的对象
* @return { Boolean } 给定的对象是否是正则表达式
*/
/**
* 判断给定的对象是否是一个普通对象
* @method isObject
* @param { * } object 需要判断的对象
* @return { Boolean } 给定的对象是否是普通对象
*/
// ['String', 'Function', 'Array', 'Number', 'RegExp', 'Object', 'Date'].forEach(function(v) {
// KS.utils['is' + v] = function(obj) {
// return Object.prototype.toString.apply(obj) == '[object ' + v + ']';
// }
// });
utils.each(['String', 'Function', 'Array', 'Number', 'RegExp', 'Object', 'Date', 'Arguments', 'Error'], function(v) {
KS.utils['is' + v] = function(obj) {
return Object.prototype.toString.apply(obj) == '[object ' + v + ']';
}
}); |
// Simple Set Clipboard System
// Author: Joseph Huckaby
var ZeroClipboard = {
version: "1.0.7",
clients: {}, // registered upload clients on page, indexed by id
moviePath: 'static/script/libs/ZeroClipboard.swf', // URL to movie
nextId: 1, // ID of next movie
$: function(thingy) {
// simple DOM lookup utility function
if (typeof(thingy) == 'string') thingy = document.getElementById(thingy);
if (!thingy.addClass) {
// extend element with a few useful methods
thingy.hide = function() { this.style.display = 'none'; };
thingy.show = function() { this.style.display = ''; };
thingy.addClass = function(name) { this.removeClass(name); this.className += ' ' + name; };
thingy.removeClass = function(name) {
var classes = this.className.split(/\s+/);
var idx = -1;
for (var k = 0; k < classes.length; k++) {
if (classes[k] == name) { idx = k; k = classes.length; }
}
if (idx > -1) {
classes.splice( idx, 1 );
this.className = classes.join(' ');
}
return this;
};
thingy.hasClass = function(name) {
return !!this.className.match( new RegExp("\\s*" + name + "\\s*") );
};
}
return thingy;
},
setMoviePath: function(path) {
// set path to ZeroClipboard.swf
this.moviePath = path;
},
dispatch: function(id, eventName, args) {
// receive event from flash movie, send to client
var client = this.clients[id];
if (client) {
client.receiveEvent(eventName, args);
}
},
register: function(id, client) {
// register new client to receive events
this.clients[id] = client;
},
getDOMObjectPosition: function(obj, stopObj) {
// get absolute coordinates for dom element
var info = {
left: 0,
top: 0,
width: obj.width ? obj.width : obj.offsetWidth,
height: obj.height ? obj.height : obj.offsetHeight
};
while (obj && (obj != stopObj)) {
info.left += obj.offsetLeft;
info.top += obj.offsetTop;
obj = obj.offsetParent;
}
return info;
},
Client: function(elem) {
// constructor for new simple upload client
this.handlers = {};
// unique ID
this.id = ZeroClipboard.nextId++;
this.movieId = 'ZeroClipboardMovie_' + this.id;
// register client with singleton to receive flash events
ZeroClipboard.register(this.id, this);
// create movie
if (elem) this.glue(elem);
}
};
ZeroClipboard.Client.prototype = {
id: 0, // unique ID for us
ready: false, // whether movie is ready to receive events or not
movie: null, // reference to movie object
clipText: '', // text to copy to clipboard
handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor
cssEffects: true, // enable CSS mouse effects on dom container
handlers: null, // user event handlers
glue: function(elem, appendElem, stylesToAdd) {
// glue to DOM element
// elem can be ID or actual DOM element object
this.domElement = ZeroClipboard.$(elem);
// float just above object, or zIndex 99 if dom element isn't set
var zIndex = 99;
if (this.domElement.style.zIndex) {
zIndex = parseInt(this.domElement.style.zIndex, 10) + 1;
}
if (typeof(appendElem) == 'string') {
appendElem = ZeroClipboard.$(appendElem);
}
else if (typeof(appendElem) == 'undefined') {
appendElem = document.getElementsByTagName('body')[0];
}
// find X/Y position of domElement
var box = ZeroClipboard.getDOMObjectPosition(this.domElement, appendElem);
// create floating DIV above element
this.div = document.createElement('div');
var style = this.div.style;
style.position = 'absolute';
style.left = '' + box.left + 'px';
style.top = '' + box.top + 'px';
style.width = '' + box.width + 'px';
style.height = '' + box.height + 'px';
style.zIndex = zIndex;
if (typeof(stylesToAdd) == 'object') {
for (addedStyle in stylesToAdd) {
style[addedStyle] = stylesToAdd[addedStyle];
}
}
// style.backgroundColor = '#f00'; // debug
appendElem.appendChild(this.div);
this.div.innerHTML = this.getHTML( box.width, box.height );
},
getHTML: function(width, height) {
// return HTML for movie
var html = '';
var flashvars = 'id=' + this.id +
'&width=' + width +
'&height=' + height;
if (navigator.userAgent.match(/MSIE/)) {
// IE gets an OBJECT tag
var protocol = location.href.match(/^https/i) ? 'https://' : 'http://';
html += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+width+'" height="'+height+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><param name="wmode" value="transparent"/></object>';
}
else {
// all other browsers get an EMBED tag
html += '<embed id="'+this.movieId+'" src="'+ZeroClipboard.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />';
}
return html;
},
hide: function() {
// temporarily hide floater offscreen
if (this.div) {
this.div.style.left = '-2000px';
}
},
show: function() {
// show ourselves after a call to hide()
this.reposition();
},
destroy: function() {
// destroy control and floater
if (this.domElement && this.div) {
this.hide();
this.div.innerHTML = '';
var body = document.getElementsByTagName('body')[0];
try { body.removeChild( this.div ); } catch(e) {;}
this.domElement = null;
this.div = null;
}
},
reposition: function(elem) {
// reposition our floating div, optionally to new container
// warning: container CANNOT change size, only position
if (elem) {
this.domElement = ZeroClipboard.$(elem);
if (!this.domElement) this.hide();
}
if (this.domElement && this.div) {
var box = ZeroClipboard.getDOMObjectPosition(this.domElement);
var style = this.div.style;
style.left = '' + box.left + 'px';
style.top = '' + box.top + 'px';
}
},
setText: function(newText) {
// set text to be copied to clipboard
this.clipText = newText;
if (this.ready) this.movie.setText(newText);
},
addEventListener: function(eventName, func) {
// add user event listener for event
// event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel
eventName = eventName.toString().toLowerCase().replace(/^on/, '');
if (!this.handlers[eventName]) this.handlers[eventName] = [];
this.handlers[eventName].push(func);
},
setHandCursor: function(enabled) {
// enable hand cursor (true), or default arrow cursor (false)
this.handCursorEnabled = enabled;
if (this.ready) this.movie.setHandCursor(enabled);
},
setCSSEffects: function(enabled) {
// enable or disable CSS effects on DOM container
this.cssEffects = !!enabled;
},
receiveEvent: function(eventName, args) {
// receive event from flash
eventName = eventName.toString().toLowerCase().replace(/^on/, '');
// special behavior for certain events
switch (eventName) {
case 'load':
// movie claims it is ready, but in IE this isn't always the case...
// bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function
this.movie = document.getElementById(this.movieId);
if (!this.movie) {
var self = this;
setTimeout( function() { self.receiveEvent('load', null); }, 1 );
return;
}
// firefox on pc needs a "kick" in order to set these in certain cases
if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) {
var self = this;
setTimeout( function() { self.receiveEvent('load', null); }, 100 );
this.ready = true;
return;
}
this.ready = true;
this.movie.setText( this.clipText );
this.movie.setHandCursor( this.handCursorEnabled );
break;
case 'mouseover':
if (this.domElement && this.cssEffects) {
this.domElement.addClass('hover');
if (this.recoverActive) this.domElement.addClass('active');
}
break;
case 'mouseout':
if (this.domElement && this.cssEffects) {
this.recoverActive = false;
if (this.domElement.hasClass('active')) {
this.domElement.removeClass('active');
this.recoverActive = true;
}
this.domElement.removeClass('hover');
}
break;
case 'mousedown':
if (this.domElement && this.cssEffects) {
this.domElement.addClass('active');
}
break;
case 'mouseup':
if (this.domElement && this.cssEffects) {
this.domElement.removeClass('active');
this.recoverActive = false;
}
break;
} // switch eventName
if (this.handlers[eventName]) {
for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) {
var func = this.handlers[eventName][idx];
if (typeof(func) == 'function') {
// actual function reference
func(this, args);
}
else if ((typeof(func) == 'object') && (func.length == 2)) {
// PHP style object + method, i.e. [myObject, 'myMethod']
func[0][ func[1] ](this, args);
}
else if (typeof(func) == 'string') {
// name of function
window[func](this, args);
}
} // foreach event handler defined
} // user defined handler for event
}
};
|
var searchData=
[
['f',['F',['../ripemd160_8c.html#a96d73bbd7af15cb1fc38c3f4a3bd82e9',1,'ripemd160.c']]],
['f1',['f1',['../aes_8c.html#af26abb8c819fd3cf4d6cb0711c80b9ee',1,'aes.c']]],
['f2',['f2',['../aes_8c.html#a5cd67c8452696b8eebb34709acc71f36',1,'aes.c']]],
['f3',['f3',['../aes_8c.html#abae335fbd04dfd4dfea78528d0ed5f38',1,'aes.c']]],
['f4',['f4',['../aes_8c.html#a4938c6d949d0932e1f2c149745618bb1',1,'aes.c']]],
['f8',['f8',['../aes_8c.html#a17724e8bbf2490d74b26829de5916cab',1,'aes.c']]],
['f9',['f9',['../aes_8c.html#a0250d3dc2d2afe1eb2054de3b86ecfd7',1,'aes.c']]],
['false',['false',['../btc_8h.html#a65e9886d74aaee76545e83dd09011727',1,'btc.h']]],
['fb',['fb',['../aes_8c.html#a15fd0649edbc944c71fd478892026f17',1,'aes.c']]],
['fd',['fd',['../aes_8c.html#a78eca4dcca91c6f7a65890d87d4795c5',1,'aes.c']]],
['fe',['fe',['../aes_8c.html#a590ce7a678e3262b26a62caddd445eef',1,'aes.c']]],
['ff',['FF',['../ripemd160_8c.html#a68b277395903afad5ec5fecb02c69cd7',1,'ripemd160.c']]],
['fff',['FFF',['../ripemd160_8c.html#a16acb7277e7c0ebc6b355243b8fb4fc7',1,'ripemd160.c']]],
['file_5frandom',['FILE_RANDOM',['../libbtc-config_8h.html#ab06b17faa30989345da832a81de2085d',1,'libbtc-config.h']]]
];
|
export function vert() {
return (
'precision highp float;' +
'precision highp int;' +
'uniform mat4 modelViewMatrix;' +
'uniform mat4 projectionMatrix;' +
'attribute vec3 position;' +
'varying vec3 vViewPosition;' +
'attribute vec3 color;' +
'varying vec3 vColor;' +
'void main() {' +
'vColor.rgb = color.rgb;' +
'vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);' +
'gl_Position = projectionMatrix * mvPosition;' +
'vViewPosition = -mvPosition.xyz;' +
'}'
);
}
export function frag(directionalLightCount) {
return (
'#extension GL_OES_standard_derivatives : enable' + '\n' +
'precision highp float;' +
'precision highp int;' + '\n' +
'#define RECIPROCAL_PI 0.31830988618' + '\n' +
'#define saturate(a) clamp(a, 0.0, 1.0)' + '\n' +
'uniform vec3 diffuse;' +
'uniform vec3 emissive;' +
'uniform vec3 specular;' +
'uniform float shininess;' +
'struct IncidentLight {' +
'vec3 color;' +
'vec3 direction;' +
'};' +
'struct ReflectedLight {' +
'vec3 directDiffuse;' +
'vec3 directSpecular;' +
'vec3 indirectDiffuse;' +
'vec3 indirectSpecular;' +
'};' +
'struct GeometricContext {' +
'vec3 position;' +
'vec3 normal;' +
'vec3 viewDir;' +
'};' +
'varying vec3 vColor;' +
'uniform vec3 fogColor;' +
'uniform float fogNear;' +
'uniform float fogFar;' +
'vec3 BRDF_Diffuse_Lambert(const in vec3 diffuseColor) {' +
'return RECIPROCAL_PI * diffuseColor;' +
'}' +
'vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {' +
'float fresnel = exp2((-5.55473 * dotLH - 6.98316) * dotLH);' +
'return (1.0 - specularColor) * fresnel + specularColor;' +
'}' +
'float G_BlinnPhong_Implicit() {' +
'return 0.25;' +
'}' +
'float D_BlinnPhong(const in float shininess, const in float dotNH) {' +
'return RECIPROCAL_PI * (shininess * 0.5 + 1.0) * pow(dotNH, shininess);' +
'}' +
'vec3 BRDF_Specular_BlinnPhong(const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess) {' +
'vec3 halfDir = normalize(incidentLight.direction + geometry.viewDir);' +
'float dotNH = saturate(dot(geometry.normal, halfDir));' +
'float dotLH = saturate(dot(incidentLight.direction, halfDir));' +
'vec3 F = F_Schlick(specularColor, dotLH);' +
'float G = G_BlinnPhong_Implicit();' +
'float D = D_BlinnPhong(shininess, dotNH);' +
'return F * (G * D);' +
'}' +
'uniform vec3 ambientLightColor;' +
'vec3 getAmbientLightIrradiance(const in vec3 ambientLightColor) {' +
'vec3 irradiance = ambientLightColor;' +
'return irradiance;' +
'}' +
'struct DirectionalLight {' +
'vec3 direction;' +
'vec3 color;' +
'};' +
'uniform DirectionalLight directionalLights[' + directionalLightCount + '];' +
'void getDirectionalDirectLightIrradiance(const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight) {' +
'directLight.color = directionalLight.color;' +
'directLight.direction = directionalLight.direction;' +
'}' +
'varying vec3 vViewPosition;' +
'struct BlinnPhongMaterial {' +
'vec3 diffuseColor;' +
'vec3 specularColor;' +
'float specularShininess;' +
'};' +
'void RE_Direct_BlinnPhong(const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight) {' +
'float dotNL = saturate(dot(geometry.normal, directLight.direction));' +
'vec3 irradiance = dotNL * directLight.color;' +
'reflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert(material.diffuseColor);' +
'reflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong(directLight, geometry, material.specularColor, material.specularShininess);' +
'}' +
'void RE_IndirectDiffuse_BlinnPhong(const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight) {' +
'reflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert(material.diffuseColor);' +
'}' +
'void main() {' +
'vec3 diffuseColor = diffuse;' +
'ReflectedLight reflectedLight = ReflectedLight(vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0));' +
'diffuseColor *= vColor;' +
'vec3 fdx = vec3(dFdx(vViewPosition.x), dFdx(vViewPosition.y), dFdx(vViewPosition.z));' +
'vec3 fdy = vec3(dFdy(vViewPosition.x), dFdy(vViewPosition.y), dFdy(vViewPosition.z));' +
'vec3 normal = normalize(cross(fdx, fdy));' +
'BlinnPhongMaterial material;' +
'material.diffuseColor = diffuseColor;' +
'material.specularColor = specular;' +
'material.specularShininess = shininess;' +
'GeometricContext geometry;' +
'geometry.position = -vViewPosition;' +
'geometry.normal = normal;' +
'geometry.viewDir = normalize(vViewPosition);' +
'IncidentLight directLight;' +
'DirectionalLight directionalLight;' +
(function() {
var chunk = '';
for (var i = 0; i < directionalLightCount; i++) {
chunk += (
'directionalLight = directionalLights[' + i + '];' +
'getDirectionalDirectLightIrradiance(directionalLight, geometry, directLight);' +
'RE_Direct_BlinnPhong(directLight, geometry, material, reflectedLight);'
);
}
return chunk;
}()) +
'vec3 irradiance = getAmbientLightIrradiance(ambientLightColor);' +
'RE_IndirectDiffuse_BlinnPhong(irradiance, geometry, material, reflectedLight);' +
'vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + emissive;' +
'gl_FragColor = vec4(outgoingLight, 1.0);' +
'float depth = gl_FragCoord.z / gl_FragCoord.w;' +
'float fogFactor = smoothstep(fogNear, fogFar, depth);' +
'gl_FragColor.rgb = mix(outgoingLight, fogColor, fogFactor);' +
'}'
);
}
|
import {
findTooltip,
findTooltipTarget,
getOppositeSide,
} from 'ember-tooltips/test-support/jquery';
/**
@method getPositionDifferences
@param String side The side the tooltip should be on relative to the target
Given a side, which represents the side of the target that
the tooltip should render, this method identifies whether
the tooltip or the target should be further away from the
top left of the window.
For example, if the side is 'top' then the target should
be further away from the top left of the window than the
tooltip because the tooltip should render above the target.
If the side is 'right' then the tooltip should be further
away from the top left of the window than the target
because the tooltip should render to the right of the
target.
This method then returns an object with two numbers:
- `expectedGreaterDistance` (expected greater number given the side)
- `expectedLesserDistance` (expected lesser number given the side)
These numbers can be used for calculations like determining
whether a tooltip is on the correct side of the target or
determining whether a tooltip is the correct distance from
the target on the given side.
*/
export default function getPositionDifferences(options = {}) {
const { targetPosition, tooltipPosition } =
getTooltipAndTargetPosition(options);
const { side } = options;
const distanceToTarget = targetPosition[side];
const distanceToTooltip = tooltipPosition[getOppositeSide(side)];
const shouldTooltipBeCloserThanTarget = side === 'top' || side === 'left';
const expectedGreaterDistance = shouldTooltipBeCloserThanTarget
? distanceToTarget
: distanceToTooltip;
const expectedLesserDistance = shouldTooltipBeCloserThanTarget
? distanceToTooltip
: distanceToTarget;
return { expectedGreaterDistance, expectedLesserDistance };
}
export function getTooltipAndTargetPosition(options = {}) {
const { selector, targetSelector } = options;
const [target] = findTooltipTarget(targetSelector);
const [tooltip] = findTooltip(selector, { targetSelector });
const targetPosition = target.getBoundingClientRect();
const tooltipPosition = tooltip.getBoundingClientRect();
return {
targetPosition,
tooltipPosition,
};
}
|
/**
* Module dependencies.
*/
var page = require('page');
var sidebar = require('sidebar');
var classes = require('classes');
var t = require('t');
var o = require('query');
var render = require('render');
var empty = require('empty');
var noLaws = require('./no-laws');
var bus = require('bus');
var log = require('debug')('democracyos:homepage');
// Routing.
page('/', function(ctx, next) {
sidebar.ready(onsidebarready);
function validUrl() {
var pathname = window.location.pathname;
return pathname == '/' || /^\/(law|proposal)/.test(pathname);
}
function onsidebarready() {
if (!validUrl()) return;
classes(document.body).add('browser-page');
var law = sidebar.items(0);
if (!law) {
var el = render.dom(noLaws);
empty(o('#browser .app-content')).appendChild(el);
return bus.emit('page:render');
}
log('render law %s', law.id);
ctx.path = '/law/' + law.id;
next();
}
}); |
var dir_a73ce79c6e07d884edc4fda711d4621f =
[
[ "fos.h", "_r___wrapper_2src__old_2_f_o_s_2fos_8h_source.html", null ],
[ "fos_imperative.h", "_r___wrapper_2src__old_2_f_o_s_2fos__imperative_8h_source.html", null ],
[ "perf_fos.h", "_r___wrapper_2src__old_2_f_o_s_2perf__fos_8h_source.html", null ],
[ "perf_fos_experimental.h", "_r___wrapper_2src__old_2_f_o_s_2perf__fos__experimental_8h_source.html", null ],
[ "test_fos.h", "_r___wrapper_2src__old_2_f_o_s_2test__fos_8h_source.html", null ],
[ "test_fos_experimental.h", "_r___wrapper_2src__old_2_f_o_s_2test__fos__experimental_8h_source.html", null ],
[ "x_fos.h", "_r___wrapper_2src__old_2_f_o_s_2x__fos_8h_source.html", null ]
]; |
/**
* Created by Administrator on 2016/7/14.
*/
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/wodertian"); //连接数据库
var db = {
Target:mongoose.model("Target",{
id:Number,
author:String,
target:String,
createTime:Date,
status:Number,
note:String
}),
Task:mongoose.model("Task",{
id:Number,
author:String,
task:String,
createTime:Date,
status:Number,
note:String,
priority:Number //优先级
}),
Weight:mongoose.model("Weight",{
date:String, //日期
timeStamp:Number, //时间戳
weight:Number
}),
Pv:mongoose.model("Pv",{
times:Number
}),
Book:mongoose.model("Book",{
id:Number,
name:String,
href:String,
state:Number
})
}
module.exports = db; |
document.addEventListener("deviceready", function () {
var appReference = document.getElementById('app');
var rootScopeReference = angular.element(appReference).scope();
navigator.globalization.getPreferredLanguage(
function (language) {
if (language.value === 'português') {
rootScopeReference.$apply(function () { rootScopeReference.setLanguage('pt'); });
} else {
rootScopeReference.$apply(function () { rootScopeReference.setLanguage('en'); });
}
},
function () {
// in case error getting the language, use English
rootScopeReference.$apply(function () { rootScopeReference.setLanguage('en'); });
}
);
}, false); |
angular.module('flapperNews').factory('posts', ['$http',
function($http) {
var o = {
posts: []
};
o.getAll = function() {
return $http.get('/posts.json').success(function(data) {
angular.copy(data, o.posts);
});
};
o.create = function(post) {
return $http.post('/posts.json', post).success(function(data) {
o.posts.push(data);
});
};
o.upvote = function(post) {
return $http.put('/posts/' + post.id + '/upvote.json')
.success(function(data) {
post.upvotes += 1;
});
};
o.get = function(id) {
return $http.get('/posts/' + id + '.json').then(function(res) {
return res.data;
});
};
o.addComment = function(id, comment) {
return $http.post('/posts/' + id + '/comments.json', comment);
};
o.upvoteComment = function(post, comment) {
return $http.put('/posts/' + post.id + '/comments/' + comment.id + '/upvote.json')
.success(function(data) {
comment.upvotes += 1;
});
};
return o;
}
]); |
import { cloneDeep } from 'lodash';
import defaultOrder from './default-order';
const byColumns = ({
sortingColumns,
sortingOrder = defaultOrder,
selectedColumn = -1
}) => {
let newSortingColumns = {};
if (selectedColumn < 0) {
return sortingColumns;
}
if (!sortingColumns) {
return {
[selectedColumn]: {
direction: sortingOrder.FIRST,
position: 0
}
};
} else if ({}.hasOwnProperty.call(sortingColumns, selectedColumn)) {
// Clone to avoid mutating the original structure
newSortingColumns = cloneDeep(sortingColumns);
const newSort = sortingOrder[newSortingColumns[selectedColumn].direction];
if (newSort) {
newSortingColumns[selectedColumn] = {
direction: newSort,
position: newSortingColumns[selectedColumn].position
};
} else {
const oldPosition = newSortingColumns[selectedColumn].position;
delete newSortingColumns[selectedColumn];
// Update position of columns after the deleted one
Object.keys(newSortingColumns).forEach((k) => {
const v = newSortingColumns[k];
if (v.position > oldPosition) {
v.position -= 1;
}
});
}
return newSortingColumns;
}
return {
...sortingColumns,
[selectedColumn]: {
direction: sortingOrder.FIRST,
position: Object.keys(sortingColumns).length
}
};
};
export default byColumns;
|
'use strict';
var should = require('should'),
parallel = require('mocha.parallel'),
nsmockup = require('../../../');
var base = __dirname + '/../../_input-files/record-data';
var validateCustomer = (customers, msg) => {
should(customers).have.length(1, msg);
let customer = customers[0];
should(customer.getId()).be.equal(4, msg);
should(customer.getValue('email')).be.equal('itil@sp.com.br', msg);
should(customer.getValue('companynameforsupportmessages', 'subsidiary')).be.equal('YYUHHHNN847293 - DEV', msg);
};
/**
* Test Suites
*/
describe('<Unit Test - Netsuite Search API>', function () {
this.timeout(5000);
before(done => {
let metadata = [
':customer',
':subsidiary'
],
records = {
'customer': `${base}/data/customer.json`,
'subsidiary': `${base}/data/subsidiary.json`
},
opts = {
general: {
dateFormat: 'DD-MM-YYYY',
timeFormat: 'HH:mm:ss'
},
metadata,
records
};
nsmockup.init(opts, done);
});
let recType = 'customer',
columns = [
['email'],
['companynameforsupportmessages', 'subsidiary']
].map(c => new nlobjSearchColumn(c[0], c[1]));
parallel('SuiteScript API - Search Utils - "operators" - DATE:', () => {
it('operator "after": customer by datecreated', done => {
let filters = [
['datecreated', null, 'after', '12-07-2015 12:34:23']
];
let customers = nlapiSearchRecord(recType, null, filters, columns);
validateCustomer(customers);
let oFilters = [
['datecreated', null, 'after', '14-07-2015 12:34:23']
],
empty = nlapiSearchRecord(recType, null, oFilters, columns);
should(empty).not.ok();
return done();
});
it('operator "before": customer by datecreated', done => {
let filters = [
['datecreated', null, 'before', '14-07-2015 12:34:23']
];
let customers = nlapiSearchRecord(recType, null, filters, columns);
validateCustomer(customers);
let oFilters = [
['datecreated', null, 'before', '12-07-2015 12:34:23']
],
empty = nlapiSearchRecord(recType, null, oFilters, columns);
should(empty).not.ok();
return done();
});
it('operator "notwithin": customer by datecreated', done => {
let filters = [
['datecreated', null, 'notwithin', '16-07-2015 18:36:23']
];
let customers = nlapiSearchRecord(recType, null, filters, columns);
validateCustomer(customers);
let oFilters = [
['datecreated', null, 'notwithin', '13-07-2015 14:39:00']
],
empty = nlapiSearchRecord(recType, null, oFilters, columns);
should(empty).not.ok();
return done();
});
it('operator "notafter": customer by datecreated', done => {
let filters = [
['datecreated', null, 'notafter', '14-07-2015']
];
let customers = nlapiSearchRecord(recType, null, filters, columns);
validateCustomer(customers);
let oFilters = [
['datecreated', null, 'notafter', '12-07-2015 12:34:23']
],
empty = nlapiSearchRecord(recType, null, oFilters, columns);
should(empty).not.ok();
return done();
});
it('operator "notbefore": customer by datecreated', done => {
let filters = [
['datecreated', null, 'notbefore', '12-07-2015']
];
let customers = nlapiSearchRecord(recType, null, filters, columns);
validateCustomer(customers);
let oFilters = [
['datecreated', null, 'notbefore', '14-07-2015 12:34:23']
],
empty = nlapiSearchRecord(recType, null, oFilters, columns);
should(empty).not.ok();
return done();
});
it('operator "noton": customer by datecreated', done => {
['12-07-2015 18:36:23', '14-07-2015 06:36:23', '10-07-2016', '02-01-2014'].forEach(function(date) {
let filters = [
['datecreated', null, 'noton', date]
];
let customers = nlapiSearchRecord(recType, null, filters, columns);
validateCustomer(customers, `invalid filter "${date}"`);
});
let oFilters = [
['datecreated', null, 'noton', '13-07-2015 14:39:00']
],
empty = nlapiSearchRecord(recType, null, oFilters, columns);
should(empty).not.ok();
return done();
});
it('operator "notonorafter": customer by datecreated', done => {
['12-07-2015 18:36:23', '10-07-2015', '02-01-2014'].forEach(function(date) {
let filters = [
['datecreated', null, 'notonorafter', date]
];
let customers = nlapiSearchRecord(recType, null, filters, columns);
validateCustomer(customers, `invalid filter "${date}"`);
});
['13-07-2015 14:39:00'].forEach(function(date) {
let oFilters = [
['datecreated', null, 'notonorafter', date]
],
empty = nlapiSearchRecord(recType, null, oFilters, columns);
should(empty).not.ok();
});
return done();
});
it('operator "notonorbefore": customer by datecreated', done => {
['14-07-2015 18:36:23', '17-07-2015', '02-01-2016'].forEach(function(date) {
let filters = [
['datecreated', null, 'notonorbefore', date]
];
let customers = nlapiSearchRecord(recType, null, filters, columns);
validateCustomer(customers, `invalid filter "${date}"`);
});
['13-07-2015 14:39:00'].forEach(function(date) {
let oFilters = [
['datecreated', null, 'notonorbefore', date]
],
empty = nlapiSearchRecord(recType, null, oFilters, columns);
should(empty).not.ok();
});
return done();
});
it('operator "on": customer by datecreated', done => {
let filters = [
['datecreated', null, 'on', '13-07-2015 14:39:00']
];
let customers = nlapiSearchRecord(recType, null, filters, columns);
validateCustomer(customers);
['13-07-2015 13:39:00', '16-03-2015', '12-07-2015'].forEach(function(date) {
let oFilters = [
['datecreated', null, 'on', date]
],
empty = nlapiSearchRecord(recType, null, oFilters, columns);
should(empty).not.ok();
});
return done();
});
it('operator "onorafter": customer by datecreated', done => {
['13-07-2015 14:39:00', '16-03-2015', '11-01-2012'].forEach(function(date) {
let filters = [
['datecreated', null, 'onorafter', date]
];
let customers = nlapiSearchRecord(recType, null, filters, columns);
validateCustomer(customers, `invalid filter "${date}"`);
});
let oFilters = [
['datecreated', null, 'onorafter', '12-08-2015 12:34:23']
],
empty = nlapiSearchRecord(recType, null, oFilters, columns);
should(empty).not.ok();
return done();
});
it('operator "onorbefore": customer by datecreated', done => {
['14-07-2015 18:36:23', '13-07-2015 14:39:00', '16-08-2016'].forEach(function(date) {
let filters = [
['datecreated', null, 'onorbefore', date]
];
let customers = nlapiSearchRecord(recType, null, filters, columns);
validateCustomer(customers, `invalid filter "${date}"`);
});
let oFilters = [
['datecreated', null, 'onorbefore', '12-07-2015 12:34:23']
],
empty = nlapiSearchRecord(recType, null, oFilters, columns);
should(empty).not.ok();
return done();
});
});
after(done => {
nsmockup.destroy(done);
});
});
|
"use strict";
module.exports = {
input : {
tag : "a",
attrs : {
href : "#"
},
content : [
"\n ",
{
tag : "span",
attrs : {
class : "animals__cat",
style : "background: url(cat.png)"
},
content : [ "Cat" ]
},
"\n"
],
pseudo : [ ":test" ]
},
expected : {
tag : "a",
attrs : {
class : ":test",
href : "#"
},
content : [
"\n ",
{
tag : "span",
attrs : {
class : "animals__cat",
style : "background: url(cat.png)"
},
content : [ "Cat" ]
},
"\n"
]
}
};
|
export default function sort(a) {
if (!a) {
return;
}
for (let i = 0; i < a.length - 1; i += 1) {
const j = smallest(a, i);
swap(a, i, j);
}
}
function smallest(a, start) {
let s = start;
for (let i = start + 1; i < a.length; i += 1) {
if (a[i] < a[s]) {
s = i;
}
}
return s;
}
function swap(a, i, j) {
const t = a[i];
a[i] = a[j];
a[j] = t;
}
|
'use strict';
export const _50_ = '#FAFAFA';
export const _100_ = '#F5F5F5';
export const _200_ = '#EEEEEE';
export const _300_ = '#E0E0E0';
export const _400_ = '#BDBDBD';
export const _500_ = '#9E9E9E';
export const _600_ = '#757575';
export const _700_ = '#616161';
export const _800_ = '#424242';
export const _900_ = '#212121';
export default _500_;
|
'use strict';
require('../bootstrap');
var Model = require('@hoist/model');
var Hapi = require('hapi');
var sinon = require('sinon');
var router = require('../../lib/routes');
var server = require('../../lib/server');
var expect = require('chai').expect;
var Bluebird = require('bluebird');
describe('BouncerServer', function () {
describe('#start', function () {
var mockHapiServer = {
connection: sinon.stub(),
start: sinon.stub().yields(),
state: sinon.stub(),
views: sinon.stub()
};
before(function (done) {
sinon.stub(Hapi, 'Server').returns(mockHapiServer);
sinon.stub(router, 'init');
sinon.stub(Model._mongoose, 'connect').yields();
server.start().then(done);
});
after(function () {
Hapi.Server.restore();
router.init.restore();
Model._mongoose.connect.restore();
});
it('creates state for token', function () {
return expect(mockHapiServer.state)
.to.have.been.calledWith('bouncer-token', {
domain: 'bouncer.hoist.local',
clearInvalid: true,
ignoreErrors: true,
encoding: 'iron',
isHttpOnly: true,
isSecure: true,
password: 'test_encryption_key',
autoValue: {},
path: '/'
});
});
it('creates a hapi server', function () {
return expect(mockHapiServer.connection)
.to.have.been
.calledWith({
host: '0.0.0.0',
port: 8000
});
});
it('starts server', function () {
return expect(mockHapiServer.start)
.to.have.been.called;
});
it('calls config', function () {
return expect(router.init)
.to.have.been
.calledWith(mockHapiServer);
});
it('connects mongoose', function () {
return expect(Model._mongoose.connect)
.to.have.been.called;
});
});
describe('#end', function () {
var mockHapiServer = {
stopAsync: sinon.stub().returns(Bluebird.resolve())
};
before(function (done) {
server.server = mockHapiServer;
sinon.stub(Model._mongoose, 'disconnect').yields();
server.end().then(done);
});
after(function () {
Model._mongoose.disconnect.restore();
});
it('stops hapi server', function () {
return expect(mockHapiServer.stopAsync)
.to.have.been.called;
});
it('disconnects mongoose', function () {
return expect(Model._mongoose.disconnect)
.to.have.been.called;
});
it('deletes server instance', function () {
return expect(server.server)
.to.not.exist;
});
});
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:0aada79e4710a341c4f633773a0b6a57555cf450ce75ca652b8caac3bf7e24b8
size 790
|
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.commons.RatingIndicator.
sap.ui.define(['jquery.sap.global', './library', 'sap/ui/core/Control', 'sap/ui/core/theming/Parameters'],
function(jQuery, library, Control, Parameters) {
"use strict";
/**
* Constructor for a new RatingIndicator.
*
* @param {string} [sId] ID for the new control, generated automatically if no ID is given
* @param {object} [mSettings] Initial settings for the new control
*
* @class
* RatingIndicator is used to let the user do some rating on a given topic. The amount of
* rating symbols can be specified, as well as the URIs to the image icons which shall be
* used as rating symbols. When the user performs a rating, an event is fired.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.32.10
*
* @constructor
* @public
* @alias sap.ui.commons.RatingIndicator
* @ui5-metamodel This control/element also will be described in the UI5 (legacy)
* designtime metamodel
*/
var RatingIndicator = Control.extend("sap.ui.commons.RatingIndicator", /** @lends sap.ui.commons.RatingIndicator.prototype */ { metadata : {
library : "sap.ui.commons",
properties : {
/**
* Determines if the rating symbols can be edited.
*/
editable : {type : "boolean", group : "Behavior", defaultValue : true},
/**
* Determines the number of displayed rating symbols
*/
maxValue : {type : "int", group : "Behavior", defaultValue : 5},
/**
* Determines the currently selected value. If value is set to sap.ui.commons.RatingIndicator.NoValue,
* the averageValue is shown.
*/
value : {type : "float", group : "Behavior", defaultValue : 0, bindable : "bindable"},
/**
* Determines the average value. This value is shown if no value is set.
* This can be used to display an average Value before the user votes.
*/
averageValue : {type : "float", group : "Behavior", defaultValue : 0},
/**
* The URI to the image which shall be displayed for all selected rating symbols.
* Note that when this attribute is used, also the other icon attributes need to be set.
*/
iconSelected : {type : "sap.ui.core.URI", group : "Behavior", defaultValue : null},
/**
* The URI to the image which shall be displayed for all unselected rating symbols.
* If this attribute is used, a requirement is that all custom icons need to have the same size.
* Note that when this attribute is used also the other icon attributes need to be set.
*/
iconUnselected : {type : "sap.ui.core.URI", group : "Behavior", defaultValue : null},
/**
* The URI to the image which is displayed when the mouse hovers onto a rating symbol.
* If used, a requirement is that all custom icons need to have the same size.
* Note that when this attribute is used also the other icon attributes need to be set.
*/
iconHovered : {type : "sap.ui.core.URI", group : "Behavior", defaultValue : null},
/**
* Defines how float values are visualized: Full, Half, Continuous
* (see enumeration RatingIndicatorVisualMode)
*/
visualMode : {type : "sap.ui.commons.RatingIndicatorVisualMode", group : "Behavior", defaultValue : sap.ui.commons.RatingIndicatorVisualMode.Half}
},
associations : {
/**
* Association to controls / ids which describe this control (see WAI-ARIA attribute aria-describedby).
*/
ariaDescribedBy : {type : "sap.ui.core.Control", multiple : true, singularName : "ariaDescribedBy"},
/**
* Association to controls / ids which label this control (see WAI-ARIA attribute aria-labelledby).
*/
ariaLabelledBy : {type : "sap.ui.core.Control", multiple : true, singularName : "ariaLabelledBy"}
},
events : {
/**
* The event is fired when the user has done a rating.
*/
change : {
parameters : {
/**
* The value of the user rating
*/
value : {type : "int"}
}
}
}
}});
RatingIndicator.NoValue = -9999;
/**
* Control Initialization
* @private
*/
RatingIndicator.prototype.init = function(){
this.iHoveredRating = -1;
};
/**
* Does all the cleanup when the RatingIndicator is to be destroyed.
* Called from Element's destroy() method.
* @private
*/
RatingIndicator.prototype.exit = function (){
// no super.exit() to call
};
/**
* Called when the theme is changed.
* @private
*/
RatingIndicator.prototype.onThemeChanged = function(oEvent){
if (this.getDomRef()) {
this.invalidate();
}
};
/**
* Avoid dragging the icons.
* @private
*/
RatingIndicator.prototype.ondragstart = function(oEvent){
oEvent.preventDefault();
};
/**
* Returns the value to be displayed, which is either a set value or (if no value is set) the
* averageValue
* @private
*/
RatingIndicator.prototype._getDisplayValue = function() {
var fValue = this.getValue();
if (fValue == RatingIndicator.NoValue) {
// If the value is set to sap.ui.commons.RatingIndicator.NoValue, show the averageValue
return this.getAverageValue();
} else {
return fValue;
}
};
/**
* Behavior implementation which is executed when the user presses Arrow Right (Left in RTL case) or Arrow Up.
*
* @param {jQuery.Event} oEvent
* @private
*/
RatingIndicator.prototype.onsapincrease = function(oEvent){
var iNewHoverValue = this.iHoveredRating;
if (iNewHoverValue == -1) {
iNewHoverValue = Math.round(this._getDisplayValue()) - 1;
if (iNewHoverValue == -1) {
iNewHoverValue = 0;
}
}
if (iNewHoverValue < this.getMaxValue()) {
iNewHoverValue = iNewHoverValue + 1;
} else {
iNewHoverValue = this.getMaxValue();
}
this.updateHoverState(oEvent, iNewHoverValue);
};
/**
* Behavior implementation which is executed when the user presses Arrow Left (Right in RTL case) or Arrow Down.
*
* @param {jQuery.Event} oEvent
* @private
*/
RatingIndicator.prototype.onsapdecrease = function(oEvent){
var iNewHoverValue = this.iHoveredRating;
if (iNewHoverValue == -1 && Math.round(this._getDisplayValue()) == 0) {
return;
}
if (iNewHoverValue == -1) {
iNewHoverValue = Math.round(this._getDisplayValue()) + 1;
}
if (iNewHoverValue > 1) {
iNewHoverValue = iNewHoverValue - 1;
} else {
iNewHoverValue = 1;
}
this.updateHoverState(oEvent, iNewHoverValue);
};
/**
* Behavior implementation which is executed when the user presses Home.
*
* @param {jQuery.Event} oEvent
* @private
*/
RatingIndicator.prototype.onsaphome = function(oEvent){
this.updateHoverState(oEvent, 1);
};
/**
* Behavior implementation which is executed when the user presses End.
*
* @param {jQuery.Event} oEvent
* @private
*/
RatingIndicator.prototype.onsapend = function(oEvent){
this.updateHoverState(oEvent, this.getMaxValue());
};
/**
* Behavior implementation which is executed when the user presses Enter or Space.
*
* @param {jQuery.Event} oEvent
* @private
*/
RatingIndicator.prototype.onsapselect = function(oEvent){
this.saveValue(oEvent, true, this.iHoveredRating);
};
/**
* Behavior implementation which is executed when the user presses Esc.
*
* @param {jQuery.Event} oEvent
* @private
*/
RatingIndicator.prototype.onsapescape = function(oEvent){
this.saveValue(oEvent, true, -1);
};
/**
* Behavior implementation which is executed when the control loses the focus.
*
* @param {jQuery.Event} oEvent
* @private
*/
RatingIndicator.prototype.onfocusout = function(oEvent){
//Do not react on focusouts of child DOM refs in IE
if (!!sap.ui.Device.browser.internet_explorer && oEvent.target != this.getDomRef()) {
return;
}
this.saveValue(oEvent, false, this.iHoveredRating);
};
/**
* Behavior implementation which is executed when the control gets the focus.
*
* @param {jQuery.Event} oEvent
* @private
*/
RatingIndicator.prototype.onfocusin = function(oEvent){
//Avoid focusing child DOM refs in IE
if (!!sap.ui.Device.browser.internet_explorer && oEvent.target != this.getDomRef()) {
this.getDomRef().focus();
}
};
/**
* Behavior implementation which is executed when the user clicks on a rating symbol.
*
* @param {jQuery.Event} oEvent
* @private
*/
RatingIndicator.prototype.onclick = function(oEvent){
this.saveValue(oEvent, true, this.getSymbolValue(oEvent));
};
/**
* Behavior implementation which is executed when the user moves the mouse on a rating symbol.
*
* @param {jQuery.Event} oEvent
* @private
*/
RatingIndicator.prototype.onmouseover = function(oEvent){
oEvent.preventDefault();
oEvent.stopPropagation();
if (!this.getEditable()) {
return;
}
this.iHoveredRating = -1;
var symbolValue = this.getSymbolValue(oEvent);
if (symbolValue == -1) {
return;
}
for (var i = 1; i <= symbolValue; i++) {
sap.ui.commons.RatingIndicatorRenderer.hoverRatingSymbol(i, this);
}
for (var i = symbolValue + 1; i <= this.getMaxValue(); i++) {
sap.ui.commons.RatingIndicatorRenderer.hoverRatingSymbol(i, this, true);
}
};
/**
* Behavior implementation which is executed when the user moves the mouse out of the rating symbol.
*
* @param {jQuery.Event} oEvent
* @private
*/
RatingIndicator.prototype.onmouseout = function(oEvent){
oEvent.preventDefault();
oEvent.stopPropagation();
if (!this.getEditable()) {
return;
}
if (jQuery.sap.checkMouseEnterOrLeave(oEvent, this.getDomRef())) {
this.iHoveredRating = -1;
for (var i = 1; i <= this.getMaxValue(); i++) {
sap.ui.commons.RatingIndicatorRenderer.unhoverRatingSymbol(i, this);
}
}
};
/**
* Returns the rating symbol value which is affected by the given event or -1
* if the event was not on a rating symbol.
*
* @param {jQuery.Event} oEvent
* @private
*/
RatingIndicator.prototype.getSymbolValue = function(oEvent){
var oSymbol = jQuery(oEvent.target);
if (oSymbol.hasClass("sapUiRatingItmImg") || oSymbol.hasClass("sapUiRatingItmOvrflw")) {
oSymbol = jQuery(oEvent.target.parentNode);
} else if (oSymbol.hasClass("sapUiRatingItmOvrflwImg")) {
oSymbol = jQuery(oEvent.target.parentNode.parentNode);
}
var itemvalue = oSymbol.attr("itemvalue");
if (itemvalue) {
return parseInt(itemvalue, 10);
}
return -1;
};
/**
* Updates the hover state according to the current pending keyboard input.
*
* @private
*/
RatingIndicator.prototype.updateKeyboardHoverState = function(bSkipHoverAfter){
for (var i = 1; i <= this.getMaxValue(); i++) {
sap.ui.commons.RatingIndicatorRenderer.unhoverRatingSymbol(i, this);
if (i <= this.iHoveredRating) {
sap.ui.commons.RatingIndicatorRenderer.hoverRatingSymbol(i, this);
} else if (!bSkipHoverAfter) {
sap.ui.commons.RatingIndicatorRenderer.hoverRatingSymbol(i, this, true);
}
}
this.setAriaState();
};
/**
* Called by the framework when rendering is completed.
*
* @private
*/
RatingIndicator.prototype.onAfterRendering = function() {
this.setAriaState();
};
/**
* Updates the ARIA state initially and in case of changes.
*
* @private
*/
RatingIndicator.prototype.setAriaState = function() {
var val = this.iHoveredRating == -1 ? this._getDisplayValue() : this.iHoveredRating;
this.$().attr("aria-valuenow", val).attr("aria-valuetext", this._getText("RATING_ARIA_VALUE" , [val])).attr("aria-label", this._getText("RATING_ARIA_NAME"));
};
/**
* Load language dependent texts.
*
* @private
*/
RatingIndicator.prototype._getText = function(sKey, aArgs) {
var rb = sap.ui.getCore().getLibraryResourceBundle("sap.ui.commons");
if (rb) {
return rb.getText(sKey, aArgs);
}
return sKey;
};
/**
* Helper function to save the value and fire the change event.
*
* @param {jQuery.Event} oEvent
* @param {boolean} bstopEvent
* @param {int} iNewValue
* @private
*/
RatingIndicator.prototype.saveValue = function(oEvent, bstopEvent, iNewValue) {
if (bstopEvent) {
oEvent.preventDefault();
// the control should not stop browser event propagation
// Example: table control needs to catch and handle the event as well
//oEvent.stopPropagation();
}
if (!this.getEditable()) {
return false;
}
this.iHoveredRating = -1;
if (iNewValue != -1 && iNewValue != this.getValue()) {
this.setValue(iNewValue);
this.fireChange({value:iNewValue});
return true;
} else {
//Update hover state only if value is not changed (otherwise rerendering is done anyway)
for (var i = 1; i <= this.getMaxValue(); i++) {
sap.ui.commons.RatingIndicatorRenderer.unhoverRatingSymbol(i, this);
}
this.setAriaState();
return false;
}
};
/**
* Helper function to update the hover state when keyboard is used.
*
* @param {jQuery.Event} oEvent
* @param {interger} iNewHoverValue
* @private
*/
RatingIndicator.prototype.updateHoverState = function(oEvent, iNewHoverValue) {
oEvent.preventDefault();
oEvent.stopPropagation();
if (!this.getEditable()) {
return;
}
this.iHoveredRating = iNewHoverValue;
this.updateKeyboardHoverState();
};
/**
* Setter for property <code>maxValue</code>.
*
* Default value is <code>5</code>
* Minimum value is <code>1</code>
*
* @param {int} iMaxValue new value for property <code>maxValue</code>
* @return {sap.ui.commons.RatingIndicator} <code>this</code> to allow method chaining
* @public
*/
RatingIndicator.prototype.setMaxValue = function(iMaxValue) {
if (iMaxValue < 1) {
iMaxValue = 1;
}
this.setProperty("maxValue", iMaxValue);
return this;
};
return RatingIndicator;
}, /* bExport= */ true);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.