code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
'use strict';
const Kind = require('./kind');
const extend = require('extend');
var customOperators = {};
var defaultOptions = {
skip: 0,
limit: Infinity,
plain: true,
log: false,
sort: false
};
var Query = function Query(target, query, options) {
this._targetModel = Kind.getSync(target);
this._options = extend({}, defaultOptions, options);
this._logs = [];
this._executionPromise = null;
this._target = target;
this._query = query;
this._executed = false;
};
Query.prototype._exec = function () {
if (this._executed) {
return;
}
this._executionPromise = handleQuery({
target: this._target,
query: this._query
}, this._logs);
this._executed = true;
};
Query.prototype._log = function (result) {
if (this._options.log) {
return {
result: result,
logs: this._logs
};
} else {
return result;
}
};
Query.prototype.count = function () {
this._exec();
var self = this;
return this._executionPromise.then(function (result) {
return self._log(result.length);
});
};
Query.prototype.all = function () {
this._exec();
var self = this;
return this._executionPromise.then(function (result) {
result = result.slice(self._options.skip, self._options.skip + self._options.limit);
var query = self._targetModel.find({
_id: {
$in: result
}
});
if (self._options.sort) {
query.sort(self._options.sort);
}
if (self._options.plain) {
query.lean();
}
return query.exec().then(function (res) {
return self._log(res);
});
});
};
Query.prototype.exec = function () {
throw new Error('Unimplemented exec');
// TODO iterator version
};
Query.createOperator = function (name, method) {
if (name[0] !== '$') {
name = '$' + name;
}
if (customOperators[name]) {
throw new Error('There is already an operator with name ' + name);
}
if (typeof method !== 'function') {
throw new Error('Provided operator is not a function');
}
if (method.length < 2) {
throw new Error('Operators require at least two parameters (target and query)');
}
customOperators[name] = method;
};
Query.apply = function (query, model) {
return new Promise(function (resolve, reject) {
var prom;
if (typeof model === 'string') {
prom = Kind.get(model);
} else {
prom = Promise.resolve(model);
}
prom.then(function (kindModel) {
kindModel.aggregate([
{
$match: query
},
{
$project: {
_id: 1
}
}
], function (err, result) {
if (err) {
return reject(err);
}
resolve(result.map(extractId))
});
}, reject);
});
};
/*
Full complex query example
{
target: "entry",
query: {
$and: [
{
kind: "bp",
query: {
low: {$gt: 50, $lt: 100}
}
},
{
kind: "iupac",
query: {
value: {$regex: "benzen"}
}
},
{
target: "ir",
query: {
kind: "irLine",
query: {
value: {$gt: 3490, $lt: 3500}
}
}
}
]
},
self: true,
skip: 5,
limit: 10
};
*/
function handleQuery(fullQuery, logs) {
return doQuery(fullQuery.target, fullQuery.query, logs);
}
function doQuery(target, query, logs) {
/*
Query can be one of :
- basic (kind)
- combination ($and, $or...)
- projection (target)
*/
var prom,
type,
logs2 = [];
var time = Date.now();
if (query.kind) {
prom = basicQuery(target, query);
type = 'basic';
}
if (query.target) {
prom = handleQuery(query, logs2).then(function (projectionResult) {
return basicQuery(target, {
kind: query.target,
query: {
_id: {
$in: projectionResult
}
}
}, true);
});
type = 'complex';
}
// Search for operator
for (var i in query) {
if (i[0] === '$' && customOperators[i]) {
prom = customOperators[i](target, query[i], logs2);
type = i;
}
}
if (prom) {
return prom.then(function (result) {
logs.push({
type: type,
target: target,
query: query,
time: Date.now() - time,
total: result.length,
logs: logs2
});
return result;
});
}
// Unable to process query
return Promise.reject('Query could not be processed: ', JSON.stringify(query));
}
function basicQuery(target, query, forceMatch) {
return new Promise(function (resolve, reject) {
var kindModel = Kind.getSync(query.kind);
var match = {
'_an.kind': target
};
for (var i in query.query) {
if (!forceMatch && i[0] === '_') {
return reject('Forbidden field in projection query : ' + i)
}
match[i] = query.query[i];
}
kindModel.aggregate([
{
$match: match
},
{
$project: {
_an: 1,
_id: 0
}
},
{
$unwind: '$_an'
},
{
$match: {
'_an.kind': target
}
},
{
$group: {
_id: '$_an.id'
}
}
], function (err, result) {
if (err) {
return reject(err);
}
resolve(result.map(extractId))
});
});
}
function combineQueryAnd(target, query, logs) {
return new Promise(function (resolve, reject) {
var results = new Array(query.length);
for (var i = 0; i < query.length; i++) {
results[i] = doQuery(target, query[i], logs);
}
Promise.all(results).then(function (results) {
results = results.map(toIdIn);
var targetModel = Kind.getSync(target);
targetModel.aggregate([
{
$match: {$and: results}
},
{
$project: {
_id: 1
}
}
], function (err, result) {
if (err) {
return reject(err);
}
resolve(result.map(extractId));
});
}, reject);
});
}
function combineQueryOr(target, query, logs) {
return new Promise(function (resolve, reject) {
var results = new Array(query.length);
for (var i = 0; i < query.length; i++) {
results[i] = doQuery(target, query[i], logs);
}
Promise.all(results).then(function (results) {
results = results.map(toIdIn);
var targetModel = Kind.getSync(target);
targetModel.aggregate([
{
$match: {$or: results}
},
{
$project: {
_id: 1
}
}
], function (err, result) {
if (err) {
return reject(err);
}
resolve(result.map(extractId));
});
}, reject);
});
}
function combineQueryElseOr(target, query, logs) {
return new Promise(function (resolve, reject) {
function tryNextQuery() {
var subQuery = query.shift();
if (subQuery) {
doQuery(target, subQuery, logs).then(function (result) {
if (result.length) {
resolve(result);
} else {
tryNextQuery();
}
}, reject);
} else {
resolve([]);
}
}
tryNextQuery();
});
}
function projectQuery(target, query) {
throw new Error('Unimplemented project entry')
} // TODO handle project query
function extractId(val) {
return val._id;
}
function toIdIn(result) {
return {
_id: {$in: result}
};
}
Query.createOperator('$and', combineQueryAnd);
Query.createOperator('$or', combineQueryOr);
Query.createOperator('$elseOr', combineQueryElseOr);
Query.createOperator('$project', projectQuery);
module.exports = Query;
| cheminfo/hds | src/query.js | JavaScript | mit | 8,885 |
if (FACEBOOK_APP_ID) {
window.fbAsyncInit = function() {
// init the FB JS SDK
Parse.FacebookUtils.init({
appId : FACEBOOK_APP_ID, // App ID from the app dashboard
channelUrl : '//YOUR.DOMAIN.COM/channel.html', // Channel file for x-domain comms
status : true, // Check Facebook Login status
cookie : true, // enable cookies to allow Parse to access the session
xfbml : true // Look for social plugins on the page
});
// Additional initialization code such as adding Event Listeners goes here
};
// Load the SDK asynchronously
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
}
| hacktoolkit/htk.js | facebook/init.js | JavaScript | mit | 968 |
'use strict';
angular.module('dndCharacterSheetApp')
.controller('AdminCtrl', function ($scope, $http, Auth, User) {
// Use the User $resource to fetch all users
$scope.users = User.query();
$scope.delete = function(user) {
User.remove({ id: user._id });
angular.forEach($scope.users, function(u, i) {
if (u === user) {
$scope.users.splice(i, 1);
}
});
};
});
| bryanlvenable/DnD-CharacterSheet | client/app/admin/admin.controller.js | JavaScript | mit | 427 |
// Parser will validate coherence whathever user inputs.
// This does not validate if the command seems logical or not, that's the oracle's job
import Dictionnary from './dictionnary.js';
import config from '../../config.js';
import { split, toLower, slice, size, filter, each, trim } from 'lodash';
module.exports = {
validate(source, content) {
// making content universal
let contentLowerCase = toLower(content);
// Chained commands will need to be splitted by | or && before next block of code
// extracting content
let splitContent = split(contentLowerCase, " ");
//Optimisization could be done here
// Trim excess spaces
splitContent = each(splitContent, (segment) => {
return trim(segment);
});
// Removing extra spaces
splitContent = filter(splitContent, (segment) => {
return segment !== "";
});
let command = splitContent[0];
// validating content
if (Dictionnary[command]) {
// extracting params and command
let params = slice(splitContent, 1);
let sizeParams = size(params);
let dictionnaryCommand = Dictionnary[command];
// validating params
if(sizeParams >= dictionnaryCommand.minParams && sizeParams <= dictionnaryCommand.maxParams) {
// HOTPATCH?
// If command is SAY, we should maintain case sensitivity
if(command === config.commandNames.SAY) {
splitContent = split(content, " ");
params = slice(splitContent, 1);
}
return {
validCommand: true,
broadcast: dictionnaryCommand.broadcast,
command,
params,
source,
};
}
return {
validCommand: false,
message: command + " command " + (sizeParams < dictionnaryCommand.minParams ? "needs at least " + dictionnaryCommand.minParams + " parameters" : "")
+ (sizeParams > dictionnaryCommand.maxParams ? "needs no more than " + dictionnaryCommand.maxParams + " parameters" : ""),
source,
};
}
return {
validCommand: false,
message: command + " command does not exist",
source,
};
},
};
| tiberiusuciu/rpg-io | app/modules/parser.js | JavaScript | mit | 2,019 |
import 'babel/polyfill';
import ReactDOM from 'react/lib/ReactDOM';
import FastClick from 'fastclick';
import router from './router';
import Dispatcher from './core/Dispatcher';
import Location from './core/Location';
import ActionTypes from './constants/ActionTypes';
const container = document.getElementById('app');
const context = {
onSetTitle: value => document.title = value,
onSetMeta: (name, content) => {
// Remove and create a new <meta /> tag in order to make it work
// with bookmarks in Safari
let elements = document.getElementsByTagName('meta');
[].slice.call(elements).forEach((element) => {
if (element.getAttribute('name') === name) {
element.parentNode.removeChild(element);
}
});
let meta = document.createElement('meta');
meta.setAttribute('name', name);
meta.setAttribute('content', content);
document.getElementsByTagName('head')[0].appendChild(meta);
}
};
function run() {
router.dispatch({ path: window.location.pathname, context }, (state, component) => {
ReactDOM.render(component, container, () => {
let css = document.getElementById('css');
css.parentNode.removeChild(css);
});
});
Dispatcher.register(action => {
if (action.type === ActionTypes.CHANGE_LOCATION) {
router.dispatch({ path: action.path, context }, (state, component) => {
ReactDOM.render(component, container);
});
}
});
}
function handlePopState(event) {
Location.navigateTo(window.location.pathname, { replace: !!event.state });
}
// Run the application when both DOM is ready
// and page content is loaded
new Promise(resolve => {
if (window.addEventListener) {
window.addEventListener('DOMContentLoaded', resolve);
window.addEventListener('popstate', handlePopState);
} else {
window.attachEvent('onload', resolve);
window.attachEvent('popstate', handlePopState);
}
}).then(() => FastClick.attach(document.body)).then(run);
| wachterjohannes/officular | src/app.js | JavaScript | mit | 2,111 |
'use strict';
var mongoose = require('mongoose'),
companyError = require('../../errors/company'),
signError = require('../../errors/apis/api.signature'),
appDb = require('../../../libraries/mongoose').appDb,
cryptoLib = require('../../libraries/crypto'),
User = appDb.model('User'),
CompanyKey = appDb.model('CompanyKey');
exports.validSignature = function (req, res, next) {
var signature = req.body.signature || req.query.signature;
var timestamp = req.body.timestamp || req.query.timestamp;
var company_id = req.body.company_id || req.query.company_id;
if (!signature) {
return res.send({err: signError.empty_signature});
}
if (!timestamp) {
return res.send({err: signError.empty_timestamp});
}
if (!company_id) {
return res.send({err: signError.empty_company_id});
}
CompanyKey.findOne({company: company_id}).populate('company').exec(function (err, companyKey) {
if (err) {
console.log(err);
return res.send({err: signError.internal_system_error});
}
if (!companyKey) {
return res.send({err: signError.invalid_company_id});
}
var sk = companyKey.secret_key;
var pk = companyKey.public_key;
var sign = cryptoLib.toMd5(sk + '&' + pk + '&' + timestamp);
if (signature !== sign) {
return res.send({err: signError.invalid_signature});
}
var company = companyKey.company;
var userId = company.creator || new mongoose.Types.ObjectId();
User.findOne({_id: userId}).populate("company").exec(function (err, user) {
if (err) {
return res.send({err: signError.internal_system_error});
}
req.user = user;
req.company = company;
return next();
});
});
}; | hardylake8020/youka-server | app/filters/apis/api.signature.server.filter.js | JavaScript | mit | 1,715 |
import React from 'react'
import { StackNavigator, DrawerNavigator } from 'react-navigation'
import Icon from 'react-native-vector-icons/FontAwesome'
import { color } from './styles'
import BurgerButton from './buttons/BurgerButton'
import GroceryButton from './buttons/GroceryButton'
import DrawerContent from './screens/DrawerContent'
import Home from './screens/Home'
import Basket from './screens/Basket'
import Search from './screens/Search'
import Login from './screens/Login'
import Register from './screens/Register'
import DetailProduct from './screens/DetailProduct'
import RouteResult from './screens/RouteResult'
const MainNavigator = StackNavigator({
Home: {
screen: Home,
navigationOptions: ({navigation}) => ({
headerLeft: <BurgerButton nav = {navigation} />,
headerRight: <GroceryButton nav = {navigation} />,
title: 'Price Police',
headerStyle: {
backgroundColor: color.lightBlue,
},
headerTitleStyle: {
color: color.white
},
})
},
Basket: {
screen: Basket,
navigationOptions: () => ({
title: 'Price Police',
headerStyle: {
backgroundColor: color.orange,
},
headerTitleStyle: {
color: color.white
},
})
},
Search: {
screen: Search,
navigationOptions: () => ({
header: null
})
},
DetailProduct: {
screen: DetailProduct,
navigationOptions: () => ({
title: 'Comparing',
headerStyle: {
backgroundColor: color.orange
},
headerTitleStyle: {
color: color.white
}
})
},
RouteResult: {
screen: RouteResult,
navigationOptions: () => ({
title: 'Route',
headerStyle: {
backgroundColor: '#6C7A89'
},
headerTitleStyle: {
color: color.white
}
})
}
}, { headerMode: 'screen' })
const Routing = DrawerNavigator({
Home: {
screen: MainNavigator,
navigationOptions: {
drawerLabel: 'Home',
drawerIcon: ({ tintColor }) => (
<Icon
name="home"
size={20}
style={{color: tintColor}} />
)
}
},
Login: {
screen: Login,
navigationOptions: {
drawerLabel: 'Login',
drawerIcon: ({ tintColor }) => (
<Icon
name="sign-in"
size={20}
style={{color: tintColor}} />
)
}
},
Register: {
screen: Register,
navigationOptions: {
drawerLabel: 'Register',
drawerIcon: ({ tintColor }) => (
<Icon
name="users"
size={20}
style={{color: tintColor}} />
)
}
}
},
{
contentOptions: {
activeTintColor: color.lightOrange,
activeBackgroundColor: color.black,
inactiveTintColor: color.black,
inactiveBackgroundColor: color.lightOrange,
},
contentComponent: props => <DrawerContent {...props} />,
}
)
export default Routing
| raynormw/bucket-list | client/BucketList/src/components/Routing.js | JavaScript | mit | 2,909 |
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var del = require('del');
var vinylPaths = require('vinyl-paths');
var typescript = require('gulp-typescript');
var concat = require('gulp-concat');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var wiredep = require('wiredep').stream;
var inject = require('gulp-inject');
var nodemon = require('gulp-nodemon');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var complexity = require('gulp-complexity');
var karma = require('karma').server;
var stylish = require('jshint-stylish');
var eslint = require('gulp-eslint');
var eslintPathFormatter = require('eslint-path-formatter');
var mocha = require('gulp-mocha');
var mochaLcovReporter = require('mocha-lcov-reporter');
var coverage = require('gulp-coverage');
var open = require('gulp-open');
var istanbul = require('gulp-istanbul');
var Promise = require('Bluebird');
var merge = require('gulp-merge');
var gutil = require('gulp-util');
var CONFIG = require('./build.config');
var BUILD_TYPE_DEVELOPMENT = "development";
var BUILD_TYPE_PRODUCTION = "production";
var BUILD_TYPE = BUILD_TYPE_DEVELOPMENT;
gulp.task('hello', function()
{
console.log('Waaazzuuuuuppp');
});
function onBuildError(reason)
{
gutil.log(reason);
process.exit(1);
}
function onBuildWarning(reason)
{
gutil.log(reason);
}
// tells you everything wrong with your code, quickly. Format, styling, and complexity.
gulp.task('analyze', function() {
return gulp.src(CONFIG.client.sourceFiles)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(jshint.reporter('fail'))
.on('error', function(e)
{
onBuildWarning('jshint failed.');
})
.pipe(jscs())
.on('error', function(e)
{
onBuildWarning('jscs failed');
})
.pipe(complexity(CONFIG.complexity)
)
.on('error', function(e)
{
onBuildWarning('complexity failed');
});
});
// Like analyze, but stops if something doesn't pass a quality gate.
gulp.task('analyzeStrict', function()
{
return gulp.src(CONFIG.client.sourceFiles)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(jshint.reporter('fail'))
.on('error', function(e)
{
onBuildError('jshint failed.');
})
.pipe(jscs())
.on('error', function(e)
{
onBuildError('jscs failed');
})
.pipe(complexity(CONFIG.complexity)
)
.on('error', function(e)
{
onBuildError('complexity failed');
});
});
// runs full unit tests on your code and outputs code coverage reports for client & ci server
gulp.task('test', function (done)
{
karma.start({
configFile: __dirname + '/' + CONFIG.karma.configFile,
singleRun: true
}, function()
{
done();
});
});
// shows your coverage
gulp.task('showCoverage', function()
{
gulp.src('./coverage/html/index.html')
.pipe(open());
});
// runs Karma in CI mode, and re-runs unit tests while you code. Made for uber-fast unit testing
// or hardercore refactoring runs.
gulp.task('testWhileICode', function(done)
{
karma.start({
configFile: __dirname + '/' + CONFIG.karma.configFile,
singleRun: false,
reporters: ['progress']
}, function()
{
done();
});
});
// cleans the build directories
gulp.task('clean', function(done)
{
del(CONFIG.buildFilesAndDirectoriesToClean, function()
{
console.log("clean done");
done();
});
});
// copies all the files you need for a dev build. Missing prod for now.
gulp.task('copy', ['clean'], function()
{
// NOTE: doesn't work, task never completes, I give up.
// All streams above work fine if you return individually,
// so it's something wrong with merge.
// return merge(htmlStream, jsStream, templateStream);
return new Promise(function(resolve, reject)
{
gulp.src('src/client/index.html')
.pipe(wiredep({ignorePath: "../../"}))
.pipe(gulp.dest('./build'))
.on('end', resolve)
.on('error', reject);
})
.then(function()
{
return new Promise(function(resolve, reject)
{
gulp.src(CONFIG.client.sourceFiles)
.pipe(gulp.dest('./build'))
.on('end', resolve)
.on('error', reject);
});
})
.then(function()
{
return new Promise(function(resolve, reject)
{
gulp.src(CONFIG.client.templateFiles)
.pipe(gulp.dest('./build'))
.on('end', resolve)
.on('error', reject);
});
});
});
// injects all your files into index.html
gulp.task('inject', ['copy'], function()
{
var wiredepSources = require('wiredep')();
var both = CONFIG.client.sourceFiles.concat(wiredepSources.css);
var sources = gulp.src(both, {read: false});
return gulp.src('./build/index.html')
.pipe(inject(sources, {ignorePath: '/src/client/'}))
.pipe(gulp.dest('./build'))
.pipe(browserSync.reload({stream: true}));
});
gulp.task('browserSync', function()
{
browserSync.init({
proxy: "http://localhost:" + CONFIG.staticServer.port
});
gulp.watch(["src/client/*.js",
"src/client/*.html",
"src/client/**/*.js",
"src/client/**/*.html"], ['analyze', 'inject']);
});
gulp.task('openIndex', function(done)
{
gulp.src('./build/index.html')
.pipe(open());
setTimeout(function()
{
done();
}, 2000);
});
// starts nodemon to watch files and reboot your static and api web server when they change
gulp.task('start', function (done)
{
nodemon({
script: 'src/static/app.js',
ext: 'js html',
ignore: ['Gruntfile.js', 'gulpfile.js', 'node_modules', 'bower_components'],
env: { 'NODE_ENV': 'development' },
tasks: ['clean', 'copy', 'inject']
});
done();
});
// git-r-done
gulp.task('default', [
'inject', 'browserSync'
]);
| Angular-Generator/angular-seed-project | gulpfile.js | JavaScript | mit | 6,266 |
'use strict';
const { isFunction } = require('../helpers/is');
module.exports = function pull(key, defaultValue) {
let returnValue = this.items[key] || null;
if (!returnValue && defaultValue !== undefined) {
if (isFunction(defaultValue)) {
returnValue = defaultValue();
} else {
returnValue = defaultValue;
}
}
delete this.items[key];
return returnValue;
};
| ecrmnn/collect.js | src/methods/pull.js | JavaScript | mit | 397 |
'use strict';
angular.module('fmsApp')
.config(function ($routeProvider) {
$routeProvider
.when('/admin', {
templateUrl: 'app/admin/admin.html',
controller: 'AdminCtrl'
});
}); | PongPi/fms | client/app/admin/admin.js | JavaScript | mit | 213 |
const fs = require('fs');
const path = require('path');
const after = require('after');
const mkdirp = require('mkdirp');
const config = require('../config');
const logger = require('../logger').child({component: 'storage/local'});
const CommonStorage = require('./common');
class LocalStorage extends CommonStorage {
constructor () {
super();
mkdirp.sync(`${config.storage.local.path}/npm/registry/v2/blobs`);
}
/**
* getFile
* @param {String} filename
* @param {Function} callback
* @returns {ReadStream}
*/
getFile (filename, callback) {
logger.info({filename: filename}, 'getFile');
const basepath = config.storage.local.path;
const filepath = `${basepath}/npm/registry/v2/blobs/${filename}`;
var readStream = fs.createReadStream(filepath);
readStream.on('error', (err) => {
logger.fatal({err: err, filename: filename}, 'getFile ReadStream Error');
});
callback(null, readStream);
}
/**
* saveFile
* @param {Array} attachments
* @param {Function} callback
*/
saveFile (attachments, callback) {
logger.info({files: attachments}, 'saveFile');
var done = after(Object.keys(attachments).length, callback);
Object.keys(attachments).forEach((a) => {
const basepath = config.storage.local.path;
const filename = `${basepath}/npm/registry/v2/blobs/${a}`;
const filepath = filename.substring(0, filename.lastIndexOf('/'));
// Make sure the namespace directory exists
mkdirp(filepath, (err) => {
if (err) {
logger.fatal({err: err}, 'unable to create file storage path');
return done(err);
}
fs.writeFile(filename, Buffer.from(attachments[a].data, 'base64'), (err) => {
if (err) {
logger.fatal({err: err}, 'unable to save file');
return done(err);
}
return done();
});
});
});
}
/**
* deleteFile
* @param {String} filename
* @param {Function} callback
*/
deleteFile (filename, callback) {
fs.unlink(path.join(config.storage.local.path, filename), (err) => {
if (err) {
logger.fatal({err: err}, 'unable to delete file');
return callback(err);
}
return callback();
});
}
}
module.exports = LocalStorage;
| ekristen/node-module-registry | registry/storage/local.js | JavaScript | mit | 2,315 |
import React from 'react'
import jQuery from 'jquery'
class ScoreToggler extends React.Component {
constructor () {
super()
this.state = {
isOpened: false,
}
}
show = () => {
this.setState({isOpened: true})
jQuery('.leaders-board-scores').collapse('show')
}
hide = () => {
this.setState({isOpened: false})
jQuery('.leaders-board-scores').collapse('hide')
}
render () {
return (
<div className='form-inline'>
<label className='mr-2 font-weight-bold'>スコア詳細表示</label>
<div className='form-check form-check-inline'>
<label className='form-check-label'>
<input className='form-check-input' type='radio'
name='toggleOptions'
onChange={this.show} checked={this.state.isOpened}/> 表示
</label>
</div>
<div className='form-check form-check-inline'>
<label className='form-check-label'>
<input className='form-check-input' type='radio'
name='toggleOptions'
onChange={this.hide} checked={!this.state.isOpened}/> 非表示
</label>
</div>
</div>
)
}
}
export default ScoreToggler
| YGO/compe-frontend | src/components/leadersboard/score-toggler.component.js | JavaScript | mit | 1,239 |
const themes = [
// Only add new themes at the end; never delete any existing themes (they are
// keyed by their index in the array).
{
name: 'Beige Land',
propertyIndex: 0,
displayIndex: 0,
files: [],
menuIconFile: 'themes/beige_land/menu_icons.png',
emptyTile5Src: 'themes/beige_land/empty_tile5.png',
emptyTile10Src: 'themes/beige_land/empty_tile10.png',
fullTile10Src: 'themes/beige_land/full_tile10.png',
},
{
name: 'Graph Paper (double)',
propertyIndex: 1,
displayIndex: 2,
files: [
'themes/graph_paper/style.css',
],
menuIconFile: 'themes/graph_paper/menu_icons.png',
emptyTile5Src: 'themes/graph_paper/empty_tile5.png',
emptyTile10Src: 'themes/graph_paper/empty_tile10.png',
fullTile10Src: 'themes/graph_paper/full_tile10.png',
},
{
name: 'Gridless Flat',
propertyIndex: 2,
displayIndex: 3,
files: [
'themes/gridless_flat/style.css',
],
menuIconFile: 'themes/gridless_flat/menu_icons.png',
emptyTile5Src: 'themes/white_tile5.png',
emptyTile10Src: 'themes/white_tile10.png',
fullTile10Src: 'themes/gridless_flat/full_tile10.png',
},
{
name: 'Cutout',
propertyIndex: 3,
displayIndex: 4,
files: [
'themes/cutout/style.css',
],
menuIconFile: 'themes/cutout/menu_icons.png',
emptyTile5Src: 'themes/cutout/empty_tile5.png',
emptyTile10Src: 'themes/cutout/empty_tile10.png',
fullTile10Src: 'themes/cutout/full_tile10.png',
},
{
name: 'Graph Paper (single)',
propertyIndex: 4,
displayIndex: 1,
files: [
'themes/graph_paper_single/style.css',
],
menuIconFile: 'themes/graph_paper_single/menu_icons.png',
emptyTile5Src: 'themes/graph_paper_single/empty_tile5.png',
emptyTile10Src: 'themes/graph_paper_single/empty_tile10.png',
fullTile10Src: 'themes/graph_paper_single/full_tile10.png',
},
{
name: 'Old School',
propertyIndex: 5,
displayIndex: 6,
files: [
'themes/old_school/style.css',
],
menuIconFile: 'themes/old_school/menu_icons.png',
emptyTile5Src: 'themes/old_school/empty_tile5.png',
emptyTile10Src: 'themes/old_school/empty_tile10.png',
fullTile10Src: 'themes/old_school/full_tile10.png',
},
{
name: 'Dark',
propertyIndex: 6,
displayIndex: 5,
files: [
'themes/dark/style.css',
],
menuIconFile: 'themes/dark/menu_icons.png',
emptyTile5Src: 'themes/dark/empty_tile5.png',
emptyTile10Src: 'themes/dark/empty_tile10.png',
fullTile10Src: 'themes/dark/full_tile10.png',
},
{
name: 'Cross Hatch (with grid)',
propertyIndex: 7,
displayIndex: 7,
files: [
'themes/cross_hatch/wall.css',
'themes/cross_hatch/style_gridless.css',
'themes/cross_hatch/grid.css',
],
menuIconFile: 'themes/cross_hatch/menu_icons_grid.png',
emptyTile5Src: 'themes/cross_hatch/empty_tile5_grid.png',
emptyTile10Src: 'themes/cross_hatch/empty_tile10_grid.png',
hasCoverEffect: true,
},
{
name: 'Cross Hatch (gridless)',
propertyIndex: 8,
displayIndex: 8,
files: [
'themes/cross_hatch/wall.css',
'themes/cross_hatch/style_gridless.css',
],
menuIconFile: 'themes/cross_hatch/menu_icons_gridless.png',
emptyTile5Src: 'themes/white_tile5.png',
emptyTile10Src: 'themes/white_tile10.png',
hasCoverEffect: true,
},
].sort((a, b) => a.displayIndex - b.displayIndex);
| amishne/mipui | public/app/themes.js | JavaScript | mit | 3,457 |
/*
Copyright 2014, KISSY v1.49
MIT Licensed
build time: May 22 12:31
*/
KISSY.add("toolbar/render",["component/container"],function(i,h){return h("component/container").getDefaultRender().extend({beforeCreateDom:function(f){f.elAttrs.role="toolbar"}})});
KISSY.add("toolbar",["component/container","component/extension/delegate-children","toolbar/render","node"],function(i,h){function f(a,b,c){var c=c.get("children"),d=0,e=c.length;if(void 0===a&&(a=1===b?0:e-1,!c[a].get("disabled")))return c[a];do d++,a=(a+e+b)%e;while(d<e&&c[a].get("disabled"));return d!==e?c[a]:null}function j(a){a.newVal?this.set("expandedItem",null):this.set("expandedItem",a.target)}function k(a){var b=a.target;if(this!==b&&(b.isMenuItem||b.isButton))a.newVal?(a=this.get("children"),
this.get("expandedItem")&&i.inArray(b,a)&&this.set("expandedItem",b.isMenuButton?b:null),this.set("highlightedItem",b)):a.byPassSetToolbarHighlightedItem||this.set("highlightedItem",null)}var l=h("component/container"),m=h("component/extension/delegate-children"),n=h("toolbar/render"),g=h("node").KeyCode;return l.extend([m],{_onSetHighlightedItem:function(a,b){var c,d;c=b&&b.prevVal;d=this.get("children");var e=this.el;c&&i.inArray(c,d)&&c.set("highlighted",!1,{data:{byPassSetToolbarHighlightedItem:1}});
a?(e.ownerDocument.activeElement!==e&&this.focus(),d=a.el,c=d.id,c||(d.id=c=i.guid("ks-toolbar-item")),e.setAttribute("aria-activedescendant",c)):e.setAttribute("aria-activedescendant","")},_onSetExpandedItem:function(a,b){b&&b.prevVal&&b.prevVal.set("collapsed",!0);a&&a.set("collapsed",!1)},bindUI:function(){this.on("afterCollapsedChange",j,this);this.on("afterHighlightedChange",k,this)},handleBlurInternal:function(a){var b;this.callSuper(a);this.set("expandedItem",null);(b=this.get("highlightedItem"))&&
b.set("highlighted",!1)},getNextItemByKeyDown:function(a,b){var c=this.get("children"),c=b&&i.indexOf(b,c);if(b&&b.handleKeyDownInternal(a))return!0;if(a.shiftKey||a.ctrlKey||a.metaKey||a.altKey)return!1;switch(a.keyCode){case g.ESC:return this.view.getKeyEventTarget().fire("blur"),!0;case g.HOME:b=f(void 0,1,this);break;case g.END:b=f(void 0,-1,this);break;case g.UP:b=f(c,-1,this);break;case g.LEFT:b=f(c,-1,this);break;case g.DOWN:b=f(c,1,this);break;case g.RIGHT:b=f(c,1,this);break;default:return!1}return b},
handleKeyDownInternal:function(a){var b;a:{b=this.get("children");var c,d;for(c=0;c<b.length;c++)if(d=b[c],d.get("highlighted")||d.isMenuButton&&!d.get("collapsed")){b=d;break a}b=null}a=this.getNextItemByKeyDown(a,b);if("boolean"===typeof a)return a;a&&a.set("highlighted",!0);return!0}},{xclass:"toolbar",ATTRS:{highlightedItem:{},expandedItem:{},defaultChildCfg:{value:{xclass:"button",handleMouseEvents:!1,focusable:!1}},xrender:{value:n}}})});
| tedyhy/SCI | kissy-1.4.9/build/toolbar-min.js | JavaScript | mit | 2,751 |
var bodyParser = require('body-parser');
var session = require('express-session');
var path = require('path');
module.exports = function(app, express) {
app.use(bodyParser());
app.use(session({
secret: "ill never tell",
resave: true,
saveUninitialized: true
}));
app.use(express.static(path.join(__dirname, '../client')));
require('./routes.js')(app);
}
| eave/myea2n-stack | server/config.js | JavaScript | mit | 379 |
module.exports = {
panelX: 250,
panelY: 40,
healthBarX: 310,
healthBarY: 55,
heartX: 205,
heartY: 55,
gunForLifePanelX: 205,
gunForLifePanelY: 85,
bulletsTextX: 265,
bulletsTextY: 70,
bulletsInGunTextX: 235,
bulletsInGunTextY: 70
};
| zombie-away/browser-game | src/js/game/constants/lifePanel.js | JavaScript | mit | 295 |
import React, { Component } from 'react';
import styles from './Timeline.module.scss';
class Timeline extends Component {
render() {
const { children } = this.props;
return (
<div className={styles.Timeline}>
{children}
</div>
);
}
}
export default Timeline; | IanChuckYin/IanChuckYin.github.io | src/components/Timeline/Timeline.js | JavaScript | mit | 334 |
(function() {
var Stagger;
Stagger = mojs.stagger(mojs.MotionPath);
describe('stagger ->', function() {
it('should extend Tunable', function() {
var stagger;
stagger = new Stagger({
bit: ['foo', 'bar', 'baz']
});
return expect(stagger instanceof mojs.Tunable).toBe(true);
});
describe('_getOptionByMod method ->', function() {
it('should get an option by modulo of i', function() {
var options, s;
options = {
bit: ['foo', 'bar', 'baz'],
path: 'M0,0 L100,100'
};
s = new Stagger(options);
expect(s._getOptionByMod('bit', 0, options)).toBe('foo');
expect(s._getOptionByMod('bit', 1, options)).toBe('bar');
expect(s._getOptionByMod('bit', 2, options)).toBe('baz');
expect(s._getOptionByMod('bit', 3, options)).toBe('foo');
return expect(s._getOptionByMod('bit', 7, options)).toBe('bar');
});
it('should return option if it isnt defined by array', function() {
var options, s;
options = {
bit: 'foo',
path: 'M0,0 L100,100'
};
s = new Stagger(options);
expect(s._getOptionByMod('bit', 0, options)).toBe('foo');
return expect(s._getOptionByMod('bit', 1, options)).toBe('foo');
});
it('should get option if it is array like', function() {
var div1, div2, divWrapper, options, s;
div1 = document.createElement('div');
div2 = document.createElement('div');
divWrapper = document.createElement('div');
divWrapper.appendChild(div1);
divWrapper.appendChild(div2);
options = {
bit: divWrapper.childNodes,
path: 'M0,0 L100,100'
};
s = new Stagger(options);
expect(s._getOptionByMod('bit', 0, options)).toBe(div1);
return expect(s._getOptionByMod('bit', 1, options)).toBe(div2);
});
it('should get option if it is array like #HTMLCollection', function() {
var div1, div2, divWrapper, options, s;
div1 = document.createElement('div');
div2 = document.createElement('div');
divWrapper = document.createElement('div');
divWrapper.appendChild(div1);
divWrapper.appendChild(div2);
options = {
bit: divWrapper.children,
path: 'M0,0 L100,100'
};
s = new Stagger(options);
expect(s._getOptionByMod('bit', 0, options)).toBe(div1);
return expect(s._getOptionByMod('bit', 1, options)).toBe(div2);
});
return it('should parse stagger options', function() {
var options, s;
options = {
bit: 'stagger(200)',
path: 'M0,0 L100,100'
};
s = new Stagger(options);
expect(s._getOptionByMod('bit', 0, options)).toBe(0);
expect(s._getOptionByMod('bit', 1, options)).toBe(200);
return expect(s._getOptionByMod('bit', 2, options)).toBe(400);
});
});
describe('_getOptionByIndex method ->', function() {
return it('should get option by modulo of index', function() {
var option1, options, s;
options = {
bax: ['foo', 'bar', 'baz'],
qux: 200,
norf: ['norf', 300],
path: 'M0,0 L100,100'
};
s = new Stagger(options);
option1 = s._getOptionByIndex(0, options);
expect(option1.bax).toBe('foo');
expect(option1.qux).toBe(200);
return expect(option1.norf).toBe('norf');
});
});
describe('_getChildQuantity method', function() {
it('should get quantity of child modules #array', function() {
var options, s;
options = {
el: ['body', 'body', 'body'],
path: 'M0,0 L100,100'
};
s = new Stagger(options);
return expect(s._getChildQuantity('el', options)).toBe(3);
});
it('should get quantity of child modules #dom list', function() {
var div1, div2, divWrapper, options, s;
div1 = document.createElement('div');
div2 = document.createElement('div');
divWrapper = document.createElement('div');
divWrapper.appendChild(div1);
divWrapper.appendChild(div2);
options = {
el: divWrapper.childNodes,
path: 'M0,0 L100,100'
};
s = new Stagger(options);
return expect(s._getChildQuantity('el', options)).toBe(2);
});
it('should get quantity of child modules #dom HTMLCollection', function() {
var div1, div2, divWrapper, options, s;
div1 = document.createElement('div');
div2 = document.createElement('div');
divWrapper = document.createElement('div');
divWrapper.appendChild(div1);
divWrapper.appendChild(div2);
options = {
el: divWrapper.children,
path: 'M0,0 L100,100'
};
s = new Stagger(options);
return expect(s._getChildQuantity('el', options)).toBe(2);
});
it('should get quantity of child modules #single value', function() {
var options, s;
options = {
el: document.createElement('div'),
path: 'M0,0 L100,100'
};
s = new Stagger(options);
return expect(s._getChildQuantity('el', options)).toBe(1);
});
it('should get quantity of child modules #string', function() {
var options, s;
options = {
el: 'body',
path: 'M0,0 L100,100'
};
s = new Stagger(options);
return expect(s._getChildQuantity('el', options)).toBe(1);
});
return it('should get quantity of is number was passed', function() {
var options, s;
options = {
el: ['body', 'body', 'body'],
path: 'M0,0 L100,100'
};
s = new Stagger(options);
return expect(s._getChildQuantity(2, options)).toBe(2);
});
});
describe('_createTimeline method ->', function() {
return it('should create timeline', function() {
var options, s;
options = {
el: 'body',
path: 'M0,0 L100,100'
};
s = new Stagger(options);
s._createTimeline();
return expect(s.timeline instanceof mojs.Timeline).toBe(true);
});
});
describe('_init method ->', function() {
it('should make stagger', function() {
var div, options, s;
div = document.createElement('div');
options = {
el: [div, div],
path: 'M0,0 L100,100',
delay: '200'
};
s = new Stagger(options);
s._init(options, mojs.MotionPath);
return expect(s.timeline._timelines.length).toBe(2);
});
it('should pass isRunLess = true', function() {
var div, options, s;
div = document.createElement('div');
options = {
el: [div, div],
path: 'M0,0 L100,100',
delay: '200'
};
s = new Stagger(options);
s._init(options, mojs.MotionPath);
return expect(s._modules[0].o.isRunLess).toBe(true);
});
it('should pass index to the module', function() {
var div, options, s;
div = document.createElement('div');
options = {
el: [div, div],
path: 'M0,0 L100,100',
delay: '200'
};
s = new Stagger(options);
s._init(options, mojs.Shape);
expect(s._modules[0]._o.index).toBe(0);
return expect(s._modules[1]._o.index).toBe(1);
});
return it('should return self', function() {
var div, options, s;
div = document.createElement('div');
options = {
el: [div, div],
path: 'M0,0 L100,100',
delay: '200'
};
s = new Stagger(options);
return expect(s._init(options, mojs.MotionPath)).toBe(s);
});
});
describe('timeline options', function() {
return it('should pass timeline options to main timeline', function() {
var s, timeline;
timeline = {};
s = new Stagger({
timeline: timeline
});
return expect(s.timeline._o).toBe(timeline);
});
});
describe('then method ->', function() {
it('should call _getOptionByIndex for each module', function() {
var StaggeredShape, options, s;
StaggeredShape = mojs.stagger(mojs.Shape);
s = new StaggeredShape({
quantifier: 5
});
spyOn(s, '_getOptionByIndex');
options = {
duration: 400
};
s.then(options);
expect(s._getOptionByIndex.calls.count()).toBe(5);
expect(s._getOptionByIndex).toHaveBeenCalledWith(0, options);
expect(s._getOptionByIndex).toHaveBeenCalledWith(1, options);
expect(s._getOptionByIndex).toHaveBeenCalledWith(2, options);
expect(s._getOptionByIndex).toHaveBeenCalledWith(3, options);
return expect(s._getOptionByIndex).toHaveBeenCalledWith(4, options);
});
it('should call _getOptionByIndex for each module', function() {
var StaggeredShape, options, s;
StaggeredShape = mojs.stagger(mojs.Shape);
s = new StaggeredShape({
quantifier: 5
});
spyOn(s._modules[0], 'then');
spyOn(s._modules[1], 'then');
spyOn(s._modules[2], 'then');
spyOn(s._modules[3], 'then');
spyOn(s._modules[4], 'then');
options = {
duration: 400,
fill: ['cyan', 'orange', 'yellow', 'blue'],
delay: 'stagger(200)'
};
s.then(options);
expect(s._modules[0].then).toHaveBeenCalledWith(s._getOptionByIndex(0, options));
expect(s._modules[1].then).toHaveBeenCalledWith(s._getOptionByIndex(1, options));
expect(s._modules[2].then).toHaveBeenCalledWith(s._getOptionByIndex(2, options));
expect(s._modules[3].then).toHaveBeenCalledWith(s._getOptionByIndex(3, options));
return expect(s._modules[4].then).toHaveBeenCalledWith(s._getOptionByIndex(4, options));
});
it('should not call _getOptionByIndex if no options passed', function() {
var StaggeredShape, options, s;
StaggeredShape = mojs.stagger(mojs.Shape);
s = new StaggeredShape({
quantifier: 5
});
spyOn(s, '_getOptionByIndex');
options = void 0;
s.then(options);
expect(s._getOptionByIndex.calls.count()).toBe(0);
expect(s._getOptionByIndex).not.toHaveBeenCalledWith(0, options);
expect(s._getOptionByIndex).not.toHaveBeenCalledWith(1, options);
expect(s._getOptionByIndex).not.toHaveBeenCalledWith(2, options);
expect(s._getOptionByIndex).not.toHaveBeenCalledWith(3, options);
return expect(s._getOptionByIndex).not.toHaveBeenCalledWith(4, options);
});
it('should call _recalcTotalDuration on timeline', function() {
var StaggeredShape, s;
StaggeredShape = mojs.stagger(mojs.Shape);
s = new StaggeredShape({
quantifier: 5
});
spyOn(s.timeline, '_recalcTotalDuration');
expect(s.then({
delay: 200
})).toBe(s);
return expect(s.timeline._recalcTotalDuration).toHaveBeenCalled();
});
it('should return this', function() {
var StaggeredShape, s;
StaggeredShape = mojs.stagger(mojs.Shape);
s = new StaggeredShape({
quantifier: 5
});
return expect(s.then({
delay: 200
})).toBe(s);
});
return it('should return this if no options passed', function() {
var StaggeredShape, s;
StaggeredShape = mojs.stagger(mojs.Shape);
s = new StaggeredShape({
quantifier: 5
});
return expect(s.then()).toBe(s);
});
});
describe('tune method ->', function() {
it('should call _getOptionByIndex for each module', function() {
var StaggeredShape, options, s;
StaggeredShape = mojs.stagger(mojs.Shape);
s = new StaggeredShape({
quantifier: 5
});
spyOn(s, '_getOptionByIndex');
options = {
duration: 400
};
s.tune(options);
expect(s._getOptionByIndex.calls.count()).toBe(5);
expect(s._getOptionByIndex).toHaveBeenCalledWith(0, options);
expect(s._getOptionByIndex).toHaveBeenCalledWith(1, options);
expect(s._getOptionByIndex).toHaveBeenCalledWith(2, options);
expect(s._getOptionByIndex).toHaveBeenCalledWith(3, options);
return expect(s._getOptionByIndex).toHaveBeenCalledWith(4, options);
});
it('should call _getOptionByIndex for each module', function() {
var StaggeredShape, options, s;
StaggeredShape = mojs.stagger(mojs.Shape);
s = new StaggeredShape({
quantifier: 5
});
spyOn(s._modules[0], 'tune');
spyOn(s._modules[1], 'tune');
spyOn(s._modules[2], 'tune');
spyOn(s._modules[3], 'tune');
spyOn(s._modules[4], 'tune');
options = {
duration: 400,
fill: ['cyan', 'orange', 'yellow', 'blue'],
delay: 'stagger(200)'
};
s.tune(options);
expect(s._modules[0].tune).toHaveBeenCalledWith(s._getOptionByIndex(0, options));
expect(s._modules[1].tune).toHaveBeenCalledWith(s._getOptionByIndex(1, options));
expect(s._modules[2].tune).toHaveBeenCalledWith(s._getOptionByIndex(2, options));
expect(s._modules[3].tune).toHaveBeenCalledWith(s._getOptionByIndex(3, options));
return expect(s._modules[4].tune).toHaveBeenCalledWith(s._getOptionByIndex(4, options));
});
it('should not call _getOptionByIndex if no options passed', function() {
var StaggeredShape, options, s;
StaggeredShape = mojs.stagger(mojs.Shape);
s = new StaggeredShape({
quantifier: 5
});
spyOn(s, '_getOptionByIndex');
options = void 0;
s.tune(options);
expect(s._getOptionByIndex.calls.count()).toBe(0);
expect(s._getOptionByIndex).not.toHaveBeenCalledWith(0, options);
expect(s._getOptionByIndex).not.toHaveBeenCalledWith(1, options);
expect(s._getOptionByIndex).not.toHaveBeenCalledWith(2, options);
expect(s._getOptionByIndex).not.toHaveBeenCalledWith(3, options);
return expect(s._getOptionByIndex).not.toHaveBeenCalledWith(4, options);
});
it('should call _recalcTotalDuration on timeline', function() {
var StaggeredShape, s;
StaggeredShape = mojs.stagger(mojs.Shape);
s = new StaggeredShape({
quantifier: 5
});
spyOn(s.timeline, '_recalcTotalDuration');
expect(s.tune({
delay: 200
})).toBe(s);
return expect(s.timeline._recalcTotalDuration).toHaveBeenCalled();
});
it('should return this', function() {
var StaggeredShape, s;
StaggeredShape = mojs.stagger(mojs.Shape);
s = new StaggeredShape({
quantifier: 5
});
return expect(s.tune({
delay: 200
})).toBe(s);
});
return it('should return this if no options passed', function() {
var StaggeredShape, s;
StaggeredShape = mojs.stagger(mojs.Shape);
s = new StaggeredShape({
quantifier: 5
});
return expect(s.tune()).toBe(s);
});
});
describe('generate method ->', function() {
it('should call generate for each module', function() {
var StaggeredShape, s;
StaggeredShape = mojs.stagger(mojs.Shape);
s = new StaggeredShape({
quantifier: 5
});
spyOn(s._modules[0], 'generate');
spyOn(s._modules[1], 'generate');
spyOn(s._modules[2], 'generate');
spyOn(s._modules[3], 'generate');
spyOn(s._modules[4], 'generate');
s.generate();
expect(s._modules[0].generate).toHaveBeenCalled();
expect(s._modules[1].generate).toHaveBeenCalled();
expect(s._modules[2].generate).toHaveBeenCalled();
expect(s._modules[3].generate).toHaveBeenCalled();
return expect(s._modules[4].generate).toHaveBeenCalled();
});
it('should call _recalcTotalDuration on timeline', function() {
var StaggeredShape, s;
StaggeredShape = mojs.stagger(mojs.Shape);
s = new StaggeredShape({
quantifier: 5
});
spyOn(s.timeline, '_recalcTotalDuration');
expect(s.generate()).toBe(s);
return expect(s.timeline._recalcTotalDuration).toHaveBeenCalled();
});
it('should return this', function() {
var StaggeredShape, s;
StaggeredShape = mojs.stagger(mojs.Shape);
s = new StaggeredShape({
quantifier: 5
});
return expect(s.generate()).toBe(s);
});
return it('should return this if no options passed', function() {
var StaggeredShape, s;
StaggeredShape = mojs.stagger(mojs.Shape);
s = new StaggeredShape({
quantifier: 5
});
return expect(s.generate()).toBe(s);
});
});
describe('quantifier option ->', function() {
return it('should be passed to the _getChildQuantity method', function() {
var s;
s = new Stagger({
delay: [100, 200, 300],
quantifier: 2,
el: document.createElement('div'),
path: 'M0,0 L100,100'
});
expect(s._modules[0].o.delay).toBe(100);
expect(s._modules[1].o.delay).toBe(200);
return expect(s._modules[2]).not.toBeDefined();
});
});
return describe('_makeTween and _makeTimeline methods ->', function() {
return it('should override them to empty methods', function() {
var stagger;
spyOn(mojs.Tweenable.prototype, '_makeTween');
spyOn(mojs.Tweenable.prototype, '_makeTimeline');
stagger = new Stagger({});
expect(mojs.Tweenable.prototype._makeTween).not.toHaveBeenCalled();
return expect(mojs.Tweenable.prototype._makeTimeline).not.toHaveBeenCalled();
});
});
});
}).call(this);
| tenie/SSFBlog | SpringBoot/src/main/resources/static/lib/mojs-master/spec/stagger.js | JavaScript | mit | 18,216 |
export default {
entry: "src/webility.dev.js",
format: "cjs",
dest: "dist/index.js"
}; | KhaledElAnsari/webility.js | rollup.config.dev.js | JavaScript | mit | 92 |
version https://git-lfs.github.com/spec/v1
oid sha256:39297805c3b0b05f0819fe56fe9e335b4455a3614579e027086fd4e7a2d676a4
size 249482
| yogeshsaroya/new-cdnjs | ajax/libs/mathjax/2.2.0/config/TeX-AMS_HTML-full.js | JavaScript | mit | 131 |
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* hprose/common/Future.js *
* *
* Hprose Future for Node.js. *
* *
* LastModified: Dec 5, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
(function() {
'use strict';
var TimeoutError = require('./TimeoutError');
var PENDING = 0;
var FULFILLED = 1;
var REJECTED = 2;
var hasPromise = 'Promise' in global;
var setTimeout = global.setTimeout;
var clearTimeout = global.clearTimeout;
var foreach = Array.prototype.forEach;
var slice = Array.prototype.slice;
function Future(computation) {
var self = this;
Object.defineProperties(this, {
_subscribers: { value: [] },
resolve: { value: this.resolve.bind(this) },
reject: { value: this.reject.bind(this) }
});
if (typeof computation === 'function') {
process.nextTick(function() {
try {
self.resolve(computation());
}
catch(e) {
self.reject(e);
}
});
}
}
function isFuture(obj) {
return obj instanceof Future;
}
function toFuture(obj) {
return isFuture(obj) ? obj : value(obj);
}
function isPromise(obj) {
return 'function' === typeof obj.then;
}
function delayed(duration, value) {
var computation = (typeof value === 'function') ?
value :
function() { return value; };
var future = new Future();
setTimeout(function() {
try {
future.resolve(computation());
}
catch(e) {
future.reject(e);
}
}, duration);
return future;
}
function error(e) {
var future = new Future();
future.reject(e);
return future;
}
function value(v) {
var future = new Future();
future.resolve(v);
return future;
}
function sync(computation) {
try {
var result = computation();
return value(result);
}
catch(e) {
return error(e);
}
}
function promise(executor) {
var future = new Future();
executor(future.resolve, future.reject);
return future;
}
function arraysize(array) {
var size = 0;
foreach.call(array, function() { ++size; });
return size;
}
function all(array) {
return toFuture(array).then(function(array) {
var n = array.length;
var count = arraysize(array);
var result = new Array(n);
if (count === 0) { return result; }
var future = new Future();
foreach.call(array, function(element, index) {
toFuture(element).then(function(value) {
result[index] = value;
if (--count === 0) {
future.resolve(result);
}
},
future.reject);
});
return future;
});
}
function join() {
return all(arguments);
}
function race(array) {
return toFuture(array).then(function(array) {
var future = new Future();
foreach.call(array, function(element) {
toFuture(element).fill(future);
});
return future;
});
}
function any(array) {
return toFuture(array).then(function(array) {
var n = array.length;
var count = arraysize(array);
if (count === 0) {
throw new RangeError('any(): array must not be empty');
}
var reasons = new Array(n);
var future = new Future();
foreach.call(array, function(element, index) {
toFuture(element).then(future.resolve, function(e) {
reasons[index] = e;
if (--count === 0) {
future.reject(reasons);
}
});
});
return future;
});
}
function settle(array) {
return toFuture(array).then(function(array) {
var n = array.length;
var count = arraysize(array);
var result = new Array(n);
if (count === 0) { return result; }
var future = new Future();
foreach.call(array, function(element, index) {
var f = toFuture(element);
f.complete(function() {
result[index] = f.inspect();
if (--count === 0) {
future.resolve(result);
}
});
});
return future;
});
}
function attempt(handler/*, arg1, arg2, ... */) {
var thisArg = (function() { return this; })();
var args = slice.call(arguments, 1);
return all(args).then(function(args) {
return handler.apply(thisArg, args);
});
}
function run(handler, thisArg/*, arg1, arg2, ... */) {
var args = slice.call(arguments, 2);
return all(args).then(function(args) {
return handler.apply(thisArg, args);
});
}
function isGenerator(obj) {
if (!obj) {
return false;
}
return 'function' == typeof obj.next && 'function' == typeof obj['throw'];
}
function isGeneratorFunction(obj) {
if (!obj) {
return false;
}
var constructor = obj.constructor;
if (!constructor) {
return false;
}
if ('GeneratorFunction' === constructor.name ||
'GeneratorFunction' === constructor.displayName) {
return true;
}
return isGenerator(constructor.prototype);
}
function getThunkCallback(future) {
return function(err, res) {
if (err instanceof Error) {
return future.reject(err);
}
if (arguments.length < 2) {
return future.resolve(err);
}
if (err === null || err === undefined) {
res = slice.call(arguments, 1);
}
else {
res = slice.call(arguments, 0);
}
if (res.length == 1) {
future.resolve(res[0]);
}
else {
future.resolve(res);
}
};
}
function thunkToPromise(fn) {
if (isGeneratorFunction(fn) || isGenerator(fn)) {
return co(fn);
}
var thisArg = (function() { return this; })();
var future = new Future();
fn.call(thisArg, getThunkCallback(future));
return future;
}
function thunkify(fn) {
return function() {
var args = slice.call(arguments, 0);
var thisArg = this;
var results = new Future();
args.push(function() {
thisArg = this;
results.resolve(arguments);
});
try {
fn.apply(this, args);
}
catch (err) {
results.resolve([err]);
}
return function(done) {
results.then(function(results) {
done.apply(thisArg, results);
});
};
};
}
function promisify(fn) {
return function() {
var args = slice.call(arguments, 0);
var future = new Future();
args.push(getThunkCallback(future));
try {
fn.apply(this, args);
}
catch (err) {
future.reject(err);
}
return future;
};
}
function toPromise(obj) {
if (isGeneratorFunction(obj) || isGenerator(obj)) {
return co(obj);
}
return toFuture(obj);
}
function co(gen) {
var thisArg = (function() { return this; })();
if (typeof gen === 'function') {
var args = slice.call(arguments, 1);
gen = gen.apply(thisArg, args);
}
if (!gen || typeof gen.next !== 'function') {
return toFuture(gen);
}
var future = new Future();
function onFulfilled(res) {
try {
next(gen.next(res));
}
catch (e) {
future.reject(e);
}
}
function onRejected(err) {
try {
next(gen['throw'](err));
}
catch (e) {
future.reject(e);
}
}
function next(ret) {
if (ret.done) {
future.resolve(ret.value);
}
else {
(('function' == typeof ret.value) ?
thunkToPromise(ret.value) :
toPromise(ret.value)).then(onFulfilled, onRejected);
}
}
onFulfilled();
return future;
}
function wrap(handler, thisArg) {
return function() {
thisArg = thisArg || this;
return all(arguments).then(function(args) {
var result = handler.apply(thisArg, args);
if (isGeneratorFunction(result) || isGenerator(result)) {
return co.call(thisArg, result);
}
return result;
});
};
}
co.wrap = wrap;
function forEach(array, callback, thisArg) {
thisArg = thisArg || (function() { return this; })();
return all(array).then(function(array) {
return array.forEach(callback, thisArg);
});
}
function every(array, callback, thisArg) {
thisArg = thisArg || (function() { return this; })();
return all(array).then(function(array) {
return array.every(callback, thisArg);
});
}
function some(array, callback, thisArg) {
thisArg = thisArg || (function() { return this; })();
return all(array).then(function(array) {
return array.some(callback, thisArg);
});
}
function filter(array, callback, thisArg) {
thisArg = thisArg || (function() { return this; })();
return all(array).then(function(array) {
return array.filter(callback, thisArg);
});
}
function map(array, callback, thisArg) {
thisArg = thisArg || (function() { return this; })();
return all(array).then(function(array) {
return array.map(callback, thisArg);
});
}
function reduce(array, callback, initialValue) {
if (arguments.length > 2) {
return all(array).then(function(array) {
return toFuture(initialValue).then(function(value) {
return array.reduce(callback, value);
});
});
}
return all(array).then(function(array) {
return array.reduce(callback);
});
}
function reduceRight(array, callback, initialValue) {
if (arguments.length > 2) {
return all(array).then(function(array) {
return toFuture(initialValue).then(function(value) {
return array.reduceRight(callback, value);
});
});
}
return all(array).then(function(array) {
return array.reduceRight(callback);
});
}
function indexOf(array, searchElement, fromIndex) {
return all(array).then(function(array) {
return toFuture(searchElement).then(function(searchElement) {
return array.indexOf(searchElement, fromIndex);
});
});
}
function lastIndexOf(array, searchElement, fromIndex) {
return all(array).then(function(array) {
return toFuture(searchElement).then(function(searchElement) {
if (fromIndex === undefined) {
fromIndex = array.length - 1;
}
return array.lastIndexOf(searchElement, fromIndex);
});
});
}
function includes(array, searchElement, fromIndex) {
return all(array).then(function(array) {
return toFuture(searchElement).then(function(searchElement) {
return array.includes(searchElement, fromIndex);
});
});
}
function find(array, predicate, thisArg) {
thisArg = thisArg || (function() { return this; })();
return all(array).then(function(array) {
return array.find(predicate, thisArg);
});
}
function findIndex(array, predicate, thisArg) {
thisArg = thisArg || (function() { return this; })();
return all(array).then(function(array) {
return array.findIndex(predicate, thisArg);
});
}
Object.defineProperties(Future, {
// port from Dart
delayed: { value: delayed },
error: { value: error },
sync: { value: sync },
value: { value: value },
// Promise compatible
all: { value: all },
race: { value: race },
resolve: { value: value },
reject: { value: error },
// extended methods
promise: { value: promise },
isFuture: { value: isFuture },
toFuture: { value: toFuture },
isPromise: { value: isPromise },
toPromise: { value: toPromise },
join: { value: join },
any: { value: any },
settle: { value: settle },
attempt: { value: attempt },
run: { value: run },
thunkify: { value: thunkify },
promisify: { value: promisify },
co: { value: co },
wrap: { value: wrap },
// for array
forEach: { value: forEach },
every: { value: every },
some: { value: some },
filter: { value: filter },
map: { value: map },
reduce: { value: reduce },
reduceRight: { value: reduceRight },
indexOf: { value: indexOf },
lastIndexOf: { value: lastIndexOf },
includes: { value: includes },
find: { value: find },
findIndex: { value: findIndex }
});
function _call(callback, next, x) {
process.nextTick(function() {
try {
var r = callback(x);
next.resolve(r);
}
catch(e) {
next.reject(e);
}
});
}
function _resolve(onfulfill, next, x) {
if (onfulfill) {
_call(onfulfill, next, x);
}
else {
next.resolve(x);
}
}
function _reject(onreject, next, e) {
if (onreject) {
_call(onreject, next, e);
}
else {
next.reject(e);
}
}
Object.defineProperties(Future.prototype, {
_value: { writable: true },
_reason: { writable: true },
_state: { value: PENDING, writable: true },
resolve: { value: function(value) {
if (value === this) {
this.reject(new TypeError('Self resolution'));
return;
}
if (isFuture(value)) {
value.fill(this);
return;
}
if ((value !== null) &&
(typeof value === 'object') ||
(typeof value === 'function')) {
var then;
try {
then = value.then;
}
catch (e) {
this.reject(e);
return;
}
if (typeof then === 'function') {
var notrun = true;
try {
var self = this;
then.call(value, function(y) {
if (notrun) {
notrun = false;
self.resolve(y);
}
}, function(r) {
if (notrun) {
notrun = false;
self.reject(r);
}
});
return;
}
catch (e) {
if (notrun) {
notrun = false;
this.reject(e);
}
}
return;
}
}
if (this._state === PENDING) {
this._state = FULFILLED;
this._value = value;
var subscribers = this._subscribers;
while (subscribers.length > 0) {
var subscriber = subscribers.shift();
_resolve(subscriber.onfulfill, subscriber.next, value);
}
}
} },
reject: { value: function(reason) {
if (this._state === PENDING) {
this._state = REJECTED;
this._reason = reason;
var subscribers = this._subscribers;
while (subscribers.length > 0) {
var subscriber = subscribers.shift();
_reject(subscriber.onreject, subscriber.next, reason);
}
}
} },
then: { value: function(onfulfill, onreject) {
if (typeof onfulfill !== 'function') { onfulfill = null; }
if (typeof onreject !== 'function') { onreject = null; }
var next = new Future();
if (this._state === FULFILLED) {
_resolve(onfulfill, next, this._value);
}
else if (this._state === REJECTED) {
_reject(onreject, next, this._reason);
}
else {
this._subscribers.push({
onfulfill: onfulfill,
onreject: onreject,
next: next
});
}
return next;
} },
done: { value: function(onfulfill, onreject) {
this.then(onfulfill, onreject).then(null, function(error) {
process.nextTick(function() { throw error; });
});
} },
inspect: { value: function() {
switch (this._state) {
case PENDING: return { state: 'pending' };
case FULFILLED: return { state: 'fulfilled', value: this._value };
case REJECTED: return { state: 'rejected', reason: this._reason };
}
} },
catchError: { value: function(onreject, test) {
if (typeof test === 'function') {
var self = this;
return this['catch'](function(e) {
if (test(e)) {
return self['catch'](onreject);
}
else {
throw e;
}
});
}
return this['catch'](onreject);
} },
'catch': { value: function(onreject) {
return this.then(null, onreject);
} },
fail: { value: function(onreject) {
this.done(null, onreject);
} },
whenComplete: { value: function(action) {
return this.then(
function(v) { action(); return v; },
function(e) { action(); throw e; }
);
} },
complete: { value: function(oncomplete) {
oncomplete = oncomplete || function(v) { return v; };
return this.then(oncomplete, oncomplete);
} },
always: { value: function(oncomplete) {
this.done(oncomplete, oncomplete);
} },
fill: { value: function(future) {
this.then(future.resolve, future.reject);
} },
timeout: { value: function(duration, reason) {
var future = new Future();
var timeoutId = setTimeout(function() {
future.reject(reason || new TimeoutError('timeout'));
}, duration);
this.whenComplete(function() { clearTimeout(timeoutId); })
.fill(future);
return future;
} },
delay: { value: function(duration) {
var future = new Future();
this.then(function(result) {
setTimeout(function() {
future.resolve(result);
}, duration);
},
future.reject);
return future;
} },
tap: { value: function(onfulfilledSideEffect, thisArg) {
return this.then(function(result) {
onfulfilledSideEffect.call(thisArg, result);
return result;
});
} },
spread: { value: function(onfulfilledArray, thisArg) {
return this.then(function(array) {
return onfulfilledArray.apply(thisArg, array);
});
} },
get: { value: function(key) {
return this.then(function(result) {
return result[key];
});
} },
set: { value: function(key, value) {
return this.then(function(result) {
result[key] = value;
return result;
});
} },
apply: { value: function(method, args) {
args = args || [];
return this.then(function(result) {
return all(args).then(function(args) {
return result[method].apply(result, args);
});
});
} },
call: { value: function(method) {
var args = slice.call(arguments, 1);
return this.then(function(result) {
return all(args).then(function(args) {
return result[method].apply(result, args);
});
});
} },
bind: { value: function(method) {
var bindargs = slice.call(arguments);
if (Array.isArray(method)) {
for (var i = 0, n = method.length; i < n; ++i) {
bindargs[0] = method[i];
this.bind.apply(this, bindargs);
}
return;
}
bindargs.shift();
var self = this;
Object.defineProperty(this, method, { value: function() {
var args = slice.call(arguments);
return self.then(function(result) {
return all(bindargs.concat(args)).then(function(args) {
return result[method].apply(result, args);
});
});
} });
return this;
} },
forEach: { value: function(callback, thisArg) {
return forEach(this, callback, thisArg);
} },
every: { value: function(callback, thisArg) {
return every(this, callback, thisArg);
} },
some: { value: function(callback, thisArg) {
return some(this, callback, thisArg);
} },
filter: { value: function(callback, thisArg) {
return filter(this, callback, thisArg);
} },
map: { value: function(callback, thisArg) {
return map(this, callback, thisArg);
} },
reduce: { value: function(callback, initialValue) {
if (arguments.length > 1) {
return reduce(this, callback, initialValue);
}
return reduce(this, callback);
} },
reduceRight: { value: function(callback, initialValue) {
if (arguments.length > 1) {
return reduceRight(this, callback, initialValue);
}
return reduceRight(this, callback);
} },
indexOf: { value: function(searchElement, fromIndex) {
return indexOf(this, searchElement, fromIndex);
} },
lastIndexOf: { value: function(searchElement, fromIndex) {
return lastIndexOf(this, searchElement, fromIndex);
} },
includes: { value: function(searchElement, fromIndex) {
return includes(this, searchElement, fromIndex);
} },
find: { value: function(predicate, thisArg) {
return find(this, predicate, thisArg);
} },
findIndex: { value: function(predicate, thisArg) {
return findIndex(this, predicate, thisArg);
} }
});
global.hprose.Future = Future;
global.hprose.thunkify = thunkify;
global.hprose.promisify = promisify;
global.hprose.co = co;
global.hprose.co.wrap = global.hprose.wrap = wrap;
function Completer() {
var future = new Future();
Object.defineProperties(this, {
future: { value: future },
complete: { value: future.resolve },
completeError: { value: future.reject },
isCompleted: { get: function() {
return ( future._state !== PENDING );
} }
});
}
global.hprose.Completer = Completer;
global.hprose.resolved = value;
global.hprose.rejected = error;
global.hprose.deferred = function() {
var self = new Future();
return Object.create(null, {
promise: { value: self },
resolve: { value: self.resolve },
reject: { value: self.reject }
});
};
if (hasPromise) { return; }
global.Promise = function(executor) {
Future.call(this);
executor(this.resolve, this.reject);
};
global.Promise.prototype = Object.create(Future.prototype);
global.Promise.prototype.constructor = Future;
Object.defineProperties(global.Promise, {
all: { value: all },
race: { value: race },
resolve: { value: value },
reject: { value: error }
});
})();
| hprose/hprose-nodejs | lib/common/Future.js | JavaScript | mit | 27,181 |
import React, { Component } from "react";
import Heading from "./common/Heading";
const styles = {
container: {
display: "flex",
flex: 1,
flexDirection: "column",
width: "100%",
paddingBottom: 20
},
project: { paddingBottom: 10 },
datails: {
marginLeft: 30
}
};
export default class Projects extends Component {
render() {
const { data } = this.props;
return (
<div style={styles.container}>
<Heading text={"SELECTED PROJECTS:"} />
<div>
{data.list.map(item => (
<div style={styles.project}>
<strong> {`${item.name}:`}</strong>
<div style={styles.datails}>
<div>
<strong>{"Description:"}</strong>
<span>{item.description}</span>
</div>
<div>
<strong>{"Language/Tools/Technologies:"}</strong>
<span>{item.tech}</span>
</div>
<div>
<strong>{"Contribution:"}</strong>
<span>{item.contribution}</span>
</div>
<div>
<strong>{"Website:"}</strong>
<a target="_blank" href={item.url}>
{item.url}
</a>
</div>
</div>
</div>
))}
</div>
<div>{data.footnote} </div>
</div>
);
}
}
| AbhishekCode/ReactResume | src/Components/Projects.js | JavaScript | mit | 1,460 |
var app = angular.module('billApp',[]);
app.controller('billCtrl',function($scope,$http){
$http.get("services/get-zone.php")
.then(function(response){
$scope.zone = response.data;
});
$http.get("services/get-clients.php")
.then(function(response){
$scope.clients = response.data;
});
}); | alquezajanmaverick/waterdistrict | pages/Bill/scripts/billing.js | JavaScript | mit | 300 |
define({
/**
* Converts a number of ms into a beautiful time string of
* the mm:ss form.
*/
prettifyTime: function(time) {
var totalSeconds = Math.round(time / 1000);
var minutes = parseInt(totalSeconds / 60);
var seconds = totalSeconds % 60;
var secondsStr;
if (seconds < 10) {
secondsStr = '0' + seconds;
} else {
secondsStr = '' + seconds;
}
var minutesStr;
if (minutes < 10) {
minutesStr = '0' + minutes;
} else {
minutesStr = '' + minutes;
}
return minutesStr + ':' + secondsStr;
},
/**
* Use the notification html5 api to display a message to
* user.
*/
notify: function(title, options) {
var _notify = function() {
new Notification(title, options);
};
var Notification = window.Notification || window.mozNotification || window.webkitNotification;
if (Notification) {
var permission = Notification.permission;
if (permission === "granted") {
_notify();
}
else if (permission !== 'denied') {
Notification.requestPermission(function (permission) {
if(!('permission' in Notification)) {
Notification.permission = permission;
}
if (permission === "granted") {
_notify();
}
});
}
}
},
/**
* Extract the project from the given annotatin.
*
* the project is the first word prefixed with '@'.
*/
extractProject: function(str) {
var re = /@(\w+)/;
var groups = str.match(re);
if (groups) {
return groups[1];
} else {
return null;
}
},
/**
* Extract words prefixed with '#'.
*/
extractTags: function(str) {
var tags = [];
var re = new RegExp(/#(\w+)/g);
var match = re.exec(str);
while (match !== null) {
tags.push(match[1]);
match = re.exec(str);
}
return tags;
}
});
| thibault/pomodoro | src/js/utils.js | JavaScript | mit | 2,247 |
var markdown = require( '../bower_components/marked' ),
Controller = require( './controllers/controller' ),
user = Controller( 'user' ),
article = Controller( 'article' ),
auth = require( './controllers/auth' ),
_ = require( 'underscore' );
markdown.setOptions( {
sanitize: true
} );
module.exports = function ( app ) {
var path = config.type === 'development' ? '/client/' + app.locals.site.view + '/' : '/';
// app.get( '/article/:id', article.load, function( req, res ){
// req.result.content = markdown.parse( req.result.content );
// res.render( 'article', _.extend( req.result, {
// path: path + 'article',
// user: req.user,
// type: 'article'
// } ) );
// } );
var enen = function( req, res ){
res.render( 'enen', {
path: path + 'enen',
user: req.user,
view: req.view
} );
};
app.get( '/', enen );
app.get( '/article', enen );
app.get( '/article/:id', enen );
app.get( '/front-view/:tpl', function( req, res ){
res.render( 'front-view/' + req.params.tpl );
} );
var dashboard = function( req, res ){
res.render( 'dashboard', {
path: path + 'dashboard',
title: '控制台',
user: req.user
} );
};
app.get( app.locals.site.dashboard, auth.yes, dashboard );
app.get( app.locals.site.dashboard + '/*', auth.yes, dashboard );
app.get( app.locals.site.dashboard + '-view/:tpl', auth.yes, function( req, res ){
res.render( 'dashboard-includes/' + req.params.tpl );
} );
}; | mrtone/enen | server/router.js | JavaScript | mit | 1,662 |
Meteor.publishComposite("items", function() {
return {
find: function() {
return Items.find({});
}
// ,
// children: [
// {
// find: function(item) {
// return [];
// }
// }
// ]
}
});
Meteor.publish(null,function(){
return Meteor.roles.find({});
})
| eldredbuck/helloworld | server/publications/publications.js | JavaScript | mit | 321 |
describe("liveSearch", function(){
var $form, $results, _supportHistory;
var dummyResponse = {
"query":"fiddle",
"result_count_string":"1 result",
"result_count":1,
"results_any?":true,
"results":[
{"title_with_highlighting":"my-title","link":"my-link","description":"my-description"}
]
};
beforeEach(function () {
$form = $('<form action="/somewhere" class="js-live-search-form"><input type="checkbox" name="field" value="sheep" checked></form>');
$results = $('<div class="js-live-search-results-block"><div class="result-count"></div><div class="js-live-search-results-list">my result list</div></div>');
$arialivetext = $('<div class="js-aria-live-count">10 results</div>');
$('body').append($form).append($results).append($arialivetext);
_supportHistory = GOVUK.support.history;
GOVUK.support.history = function(){ return true; };
GOVUK.liveSearch.resultCache = {};
});
afterEach(function(){
$form.remove();
$results.remove();
$arialivetext.remove();
GOVUK.support.history = _supportHistory;
});
it("should save initial state", function(){
GOVUK.liveSearch.init();
expect(GOVUK.liveSearch.state).toEqual([{name: 'field', value: 'sheep'}]);
});
it("should detect a new state", function(){
GOVUK.liveSearch.init();
expect(GOVUK.liveSearch.isNewState()).toBe(false);
$form.find('input').prop('checked', false);
expect(GOVUK.liveSearch.isNewState()).toBe(true);
});
it("should update state to current state", function(){
GOVUK.liveSearch.init();
expect(GOVUK.liveSearch.state).toEqual([{name: 'field', value: 'sheep'}]);
$form.find('input').prop('checked', false);
GOVUK.liveSearch.saveState();
expect(GOVUK.liveSearch.state).toEqual([]);
});
it("should update state to passed in state", function(){
GOVUK.liveSearch.init();
expect(GOVUK.liveSearch.state).toEqual([{name: 'field', value: 'sheep'}]);
$form.find('input').prop('checked', false);
GOVUK.liveSearch.saveState({ my: "new", state: "object"});
expect(GOVUK.liveSearch.state).toEqual({ my: "new", state: "object"});
});
it("should not request new results if they are in the cache", function(){
GOVUK.liveSearch.resultCache["more=results"] = "exists";
GOVUK.liveSearch.state = { more: "results" };
spyOn(GOVUK.liveSearch, 'displayResults');
spyOn(jQuery, 'ajax');
GOVUK.liveSearch.updateResults();
expect(GOVUK.liveSearch.displayResults).toHaveBeenCalled();
expect(jQuery.ajax).not.toHaveBeenCalled();
});
it("should return a promise like object if results are in the cache", function(){
GOVUK.liveSearch.resultCache["more=results"] = "exists";
GOVUK.liveSearch.state = { more: "results" };
spyOn(GOVUK.liveSearch, 'displayResults');
spyOn(jQuery, 'ajax');
var promise = GOVUK.liveSearch.updateResults();
expect(typeof promise.done).toBe('function');
});
it("should return a promise like object if results aren't in the cache", function(){
GOVUK.liveSearch.state = { not: "cached" };
spyOn(GOVUK.liveSearch, 'displayResults');
var ajaxCallback = jasmine.createSpyObj('ajax', ['done', 'error']);
ajaxCallback.done.andReturn(ajaxCallback);
spyOn(jQuery, 'ajax').andReturn(ajaxCallback);
GOVUK.liveSearch.updateResults();
expect(jQuery.ajax).toHaveBeenCalledWith({url: '/somewhere.json', data: {not: "cached"}});
expect(ajaxCallback.done).toHaveBeenCalled();
ajaxCallback.done.mostRecentCall.args[0]('response data')
expect(GOVUK.liveSearch.displayResults).toHaveBeenCalled();
expect(GOVUK.liveSearch.resultCache['not=cached']).toBe('response data');
});
it("should show and hide loading indicator when loading new results", function(){
GOVUK.liveSearch.state = { not: "cached" };
spyOn(GOVUK.liveSearch, 'displayResults');
spyOn(GOVUK.liveSearch, 'showLoadingIndicator');
spyOn(GOVUK.liveSearch, 'hideLoadingIndicator');
var ajaxCallback = jasmine.createSpyObj('ajax', ['done', 'error']);
ajaxCallback.done.andReturn(ajaxCallback);
spyOn(jQuery, 'ajax').andReturn(ajaxCallback);
GOVUK.liveSearch.updateResults();
expect(GOVUK.liveSearch.showLoadingIndicator).toHaveBeenCalled();
ajaxCallback.done.mostRecentCall.args[0]('response data')
expect(GOVUK.liveSearch.hideLoadingIndicator).toHaveBeenCalled();
});
it("should show error indicator when error loading new results", function(){
GOVUK.liveSearch.state = { not: "cached" };
spyOn(GOVUK.liveSearch, 'displayResults');
spyOn(GOVUK.liveSearch, 'showErrorIndicator');
var ajaxCallback = jasmine.createSpyObj('ajax', ['done', 'error']);
ajaxCallback.done.andReturn(ajaxCallback);
spyOn(jQuery, 'ajax').andReturn(ajaxCallback);
GOVUK.liveSearch.updateResults();
ajaxCallback.error.mostRecentCall.args[0]()
expect(GOVUK.liveSearch.showErrorIndicator).toHaveBeenCalled();
});
it("should return cache items for current state", function(){
GOVUK.liveSearch.state = { not: "cached" };
expect(GOVUK.liveSearch.cache()).toBe(undefined);
GOVUK.liveSearch.cache('something in the cache');
expect(GOVUK.liveSearch.cache()).toBe('something in the cache');
});
it("should return the search term from a state object", function(){
var state = [{ name: "q", value: "my-search-term" }, { name: "other", value: "something" }];
expect(GOVUK.liveSearch.searchTermValue(state)).toBe('my-search-term');
expect(GOVUK.liveSearch.searchTermValue(false)).toBe(false);
expect(GOVUK.liveSearch.searchTermValue(null)).toBe(false);
});
it("should only allow 15 organisations to be selected", function(){
var orgList = [];
for(var i=0;i<14;i++){ orgList.push( { name: 'filter_organisations[]' } ); }
spyOn(GOVUK.liveSearch.$form, 'serializeArray').andReturn(orgList);
spyOn(window, 'alert');
var event = jasmine.createSpyObj('event', ['preventDefault']);
expect(GOVUK.liveSearch.checkFilterLimit(event)).toBe(true);
orgList.push( { name: 'filter_organisations[]' } );
expect(GOVUK.liveSearch.checkFilterLimit(event)).toBe(false);
});
it("should only allow 15 filters in total to be selected", function(){
var orgList = [];
for(var i=0;i<4;i++){ orgList.push( { name: 'filter_specialist_sectors[]' } ); }
for(var i=0;i<10;i++){ orgList.push( { name: 'filter_organisations[]' } ); }
spyOn(GOVUK.liveSearch.$form, 'serializeArray').andReturn(orgList);
spyOn(window, 'alert');
var event = jasmine.createSpyObj('event', ['preventDefault']);
expect(GOVUK.liveSearch.checkFilterLimit(event)).toBe(true);
orgList.push( { name: 'filter_organisations[]' } );
expect(GOVUK.liveSearch.checkFilterLimit(event)).toBe(false);
});
describe('with relevant dom nodes set', function(){
beforeEach(function(){
GOVUK.liveSearch.$form = $form;
GOVUK.liveSearch.$resultsBlock = $results;
GOVUK.liveSearch.state = { field: "sheep" };
});
it("should update save state and update results when checkbox is changed", function(){
var promise = jasmine.createSpyObj('promise', ['done']);
spyOn(GOVUK.liveSearch, 'updateResults').andReturn(promise);
spyOn(GOVUK.liveSearch, 'pageTrack').andReturn(promise);
$form.find('input').prop('checked', false);
GOVUK.liveSearch.checkboxChange();
expect(GOVUK.liveSearch.state).toEqual([]);
expect(GOVUK.liveSearch.updateResults).toHaveBeenCalled();
promise.done.mostRecentCall.args[0]();
expect(GOVUK.liveSearch.pageTrack).toHaveBeenCalled();
});
it("should do nothing if state hasn't changed when a checkbox is changed", function(){
spyOn(GOVUK.liveSearch, 'updateResults');
GOVUK.liveSearch.checkboxChange();
expect(GOVUK.liveSearch.state).toEqual({ field: 'sheep'});
expect(GOVUK.liveSearch.updateResults).not.toHaveBeenCalled();
});
it("should display results from the cache", function(){
GOVUK.liveSearch.resultCache["the=first"] = dummyResponse;
GOVUK.liveSearch.state = { the: "first" };
GOVUK.liveSearch.displayResults();
expect($results.find('h3').text()).toBe('my-title');
expect($results.find('#js-live-search-result-count').text()).toMatch(/^\s+1 result/);
});
it("should restore checkbox values", function(){
GOVUK.liveSearch.state = [ { name: "field", value: "sheep" } ];
GOVUK.liveSearch.restoreCheckboxes();
expect($form.find('input').prop('checked')).toBe(true);
GOVUK.liveSearch.state = [ ];
GOVUK.liveSearch.restoreCheckboxes();
expect($form.find('input').prop('checked')).toBe(false);
});
it ("display results should call updateAriaLiveCount when the results have been loaded", function(){
spyOn(GOVUK.liveSearch, 'updateAriaLiveCount');
GOVUK.liveSearch.displayResults();
expect(GOVUK.liveSearch.updateAriaLiveCount).toHaveBeenCalled();
});
it ("updateAriaLiveCount should change the text of the aria-live region to match the result count", function(){
var oldCount = '1 search result',
newCount = '70 search results';
GOVUK.liveSearch.$resultsBlock.find('.result-count').text(newCount);
GOVUK.liveSearch.updateAriaLiveCount();
expect(GOVUK.liveSearch.$ariaLiveResultCount.text()).toBe(newCount);
});
});
});
| Catgov/4_frontend | test/javascripts/unit/live-search-test.js | JavaScript | mit | 9,405 |
/* We need to tell jshint which are our global variables */
/* global document: false,
window: false
*/
'use strict';
var theme = {};
var superSpeed = 0;
theme.onUpdate = function(power) {
superSpeed = power / 1000;
};
theme.usageExamples = [
{
action: 'Powering',
consumption: (0.000483 * 26400000) / 100,
object: '% of UK homes' },
{
action: 'Or driving home for Christmas',
consumption: 0.00038,
object: 'miles (in a Tesla Model S)' },
{
action: 'Or watching "How the Grinch Stole Christmas!"',
consumption: 0.000024,
object: 'times' },
{
action: 'Or baking',
consumption: 0.0000185,
object: 'mince pies' }
];
window.onload = function() {
//canvas init
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
//canvas dimensions
var W = window.innerWidth;
var H = window.innerHeight;
canvas.width = W;
canvas.height = H;
//snowflake particles
// max particles
var mp = 512;
var particles = [];
for (var i = 0; i < mp; i++) {
/*
x - coordinate
y - coordinate
r - radius
d - density
*/
particles.push({
x: Math.random() * W,
y: Math.random() * H,
r: Math.random() * 4 + 1,
d: Math.random() * mp
});
}
//Lets draw the flakes
function draw() {
ctx.clearRect(0, 0, W, H);
ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
ctx.beginPath();
for (var i = 0; i < mp; i++) {
var p = particles[i];
ctx.moveTo(p.x, p.y);
ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2, true);
}
ctx.fill();
update();
window.requestAnimationFrame(draw);
}
// Function to move the snowflakes
// angle will be an ongoing incremental flag. Sin and Cos functions will be
// applied to it to create vertical and horizontal movements of the flakes
var angle = 0;
function update() {
angle += 0.01;
for (var i = 0; i < mp; i++) {
var p = particles[i];
// Updating X and Y coordinates
// We will add 1 to the cos function to prevent negative values which will
// lead flakes to move upwards
// Every particle has its own density which can be used to make the
// downward movement different for each flake
// Lets make it more random by adding in the radius
p.y += Math.cos(angle + p.d) + 1 + p.r / 2;
p.x -= (superSpeed);
// p.x += - Math.abs(Math.sin(angle)) * 2 - superSpeed;
// Sending flakes back from the top when it exits
// Lets make it a bit more organic and let flakes enter from the left and
// right also.
if (p.x > W + 5 || p.x < -5 || p.y > H) {
if (i % 3 > 0) {
// 66.67% of the flakes
particles[i] = {x: Math.random() * W, y: -10, r: p.r, d: p.d};
} else {
var newX;
var newY;
//If the flake is exitting from the right
if (Math.sin(angle) > 0) {
//Enter from the left
newX = W + Math.random() * W;
newY = Math.random() * H;
} else {
//Enter from the right
newX = W + Math.random() * W;
newY = H / 4 + Math.random() * H / 2;
}
particles[i] = {x: newX, y: newY, r: p.r, d: p.d};
}
}
}
}
// animation loop
draw();
};
| diascreative/winderful | assets/themes/winterful/scripts/script.js | JavaScript | mit | 3,415 |
/**
* @module Application
*/
define([
'framework/BaseModel',
'collections/data/DataDecomps',
'collections/data/DataItems',
'collections/data/DataParams',
'collections/data/DataSentences',
'collections/data/DataSRSConfigs',
'collections/data/DataStrokes',
'collections/data/DataVocabs',
'collections/data/DataVocabLists'
], function(BaseModel, DataDecomps, DataItems, DataParams, DataSentences, DataSRSConfigs, DataStrokes, DataVocabs, DataVocabLists) {
/**
* @class UserData
* @extends BaseModel
*/
var UserData = BaseModel.extend({
/**
* @method initialize
* @param {User} user
* @constructor
*/
initialize: function(attributes, options) {
this.backgroundSync = undefined;
this.decomps = new DataDecomps();
this.items = new DataItems(null, {data: this});
this.params = new DataParams();
this.sentences = new DataSentences();
this.srsconfigs = new DataSRSConfigs();
this.strokes = new DataStrokes();
this.syncing = false;
this.user = options.user;
this.vocabs = new DataVocabs(null, {data: this});
this.vocablists = new DataVocabLists();
this.on('change:access_token', this.updateExpires);
this.on('change', this.cache);
},
/**
* @property defaults
* @type Object
*/
defaults: {
access_token: undefined,
addOffset: 0,
changedVocabIds: [],
downloadId: undefined,
expires: undefined,
expires_in: undefined,
lastErrorCheck: 0,
lastItemSync: 0,
lastReviewSync: 0,
lastSRSConfigSync: 0,
lastVocabSync: 0,
refresh_token: undefined,
token_type: undefined,
user_id: undefined,
userUpdated: false
},
/**
* @method cache
*/
cache: function() {
localStorage.setItem(this.user.id + '-data', JSON.stringify(this.toJSON()));
},
/**
* @method checkAutoAdd
* @param {Number|String} dueCount
*/
checkAutoAdd: function(dueCount) {
if (this.user.settings.get('autoAdd') && app.user.data.vocablists.hasActive()) {
var autoAddLimit = this.user.settings.get('autoAddLimit');
var recentCount = this.user.schedule.getRecentCount();
if (recentCount < autoAddLimit && (!dueCount || dueCount < 5)) {
this.items.fetchNew({limit: 1, lists: app.user.settings.getActiveLists()});
}
}
},
/**
* @method flagVocabUpdate
* @param {String} vocabId
*/
flagVocabUpdate: function(vocabId) {
if (this.attributes.changedVocabIds.indexOf(vocabId) === -1) {
this.attributes.changedVocabIds.push(vocabId);
}
this.cache();
},
/**
* @method loadAll
* @param {Function} [callback]
*/
loadAll: function(callback) {
var result = {};
async.parallel([
function(callback) {
app.storage.getAll('decomps', function(data) {
result.Decomps = data;
callback();
});
},
function(callback) {
app.storage.getAll('items', function(data) {
result.Items = data;
callback();
});
},
function(callback) {
app.storage.getAll('sentences', function(data) {
result.Sentences = data;
callback();
});
},
function(callback) {
app.storage.getAll('srsconfigs', function(data) {
result.SRSConfigs = data;
callback();
});
},
function(callback) {
app.storage.getAll('strokes', function(data) {
result.Strokes = data;
callback();
});
},
function(callback) {
app.storage.getAll('vocablists', function(data) {
result.VocabLists = data;
callback();
});
},
function(callback) {
app.storage.getAll('vocabs', function(data) {
result.Vocabs = data;
callback();
});
}
], function() {
if (typeof callback === 'function') {
callback(result);
}
});
},
/**
* @method put
* @param {Object} result
* @param {Function} [callback]
*/
put: function(result, callback) {
async.series([
function(callback) {
app.storage.putItems('decomps', result.Decomps, callback);
},
function(callback) {
app.storage.putItems('items', result.Items, callback);
},
function(callback) {
app.storage.putItems('sentences', result.Sentences, callback);
},
function(callback) {
app.storage.putItems('srsconfigs', result.SRSConfigs, callback);
},
function(callback) {
app.storage.putItems('strokes', result.Strokes, callback);
},
function(callback) {
app.storage.putItems('vocablists', result.VocabLists, callback);
},
function(callback) {
app.storage.putItems('vocabs', result.Vocabs, callback);
}
], function() {
if (typeof callback === 'function') {
callback();
}
});
},
/**
* @method startBackgroundSync
*/
startBackgroundSync: function() {
var self = this;
this.backgroundSync = setInterval(function() {
self.sync(1);
}, moment.duration(5, 'minutes').asMilliseconds());
},
/**
* @method stopBackgroundSync
*/
stopBackgroundSync: function() {
clearInterval(this.backgroundSync);
this.backgroundSync = undefined;
},
/**
* @method sync
* @param {Number} startFrom
* @param {Function} [callbackSuccess]
* @param {Function} [callbackError]
*/
sync: function(startFrom, callbackSuccess, callbackError) {
var self = this;
if (this.syncing) {
if (typeof callbackError === 'function') {
callbackError('Sync already in progress.');
}
} else {
this.syncing = true;
console.log('^^^SYNC STARTED:', moment().format('HH:mm:ss YYYY-MM-DD'));
async.series([
function(callback) {
app.dialogs.element('.message-text').text('CALCULATING STATS');
self.user.stats.sync(function() {
self.trigger('sync', true);
app.timer.updateOffset();
callback();
}, callback);
},
function(callback) {
if (self.get('changedVocabIds').length) {
app.dialogs.element('.message-text').text('SAVING VOCABS');
self.vocabs.putChanged(callback, callback);
} else {
callback();
}
},
function(callback) {
if (self.user.reviews.length > startFrom) {
app.dialogs.element('.message-text').text('POSTING REVIEWS');
self.user.reviews.post(startFrom, callback, callback);
} else {
callback();
}
},
function(callback) {
app.dialogs.element('.message-text').text('UPDATING ITEMS');
app.user.data.items.sync(callback, callback);
}
], function(error) {
self.syncing = false;
if (error) {
if (error.status === 403) {
self.stopBackgroundSync();
} else {
console.log('^^^SYNC ERROR', error);
}
if (typeof callbackError === 'function') {
callbackError();
}
} else {
app.analytics.trackUserEvent('background sync');
console.log('^^^SYNC FINISHED:', moment().format('HH:mm:ss YYYY-MM-DD'));
self.trigger('sync', false);
if (typeof callbackSuccess === 'function') {
callbackSuccess();
}
}
});
}
},
/**
* @method toggleKana
* @param {Function} [callbackSuccess]
* @param {Function} [callbackError]
*/
toggleKana: function(callbackSuccess, callbackError) {
var self = this;
var studyKana = this.user.settings.get('studyKana');
async.series([
function(callback) {
if (studyKana) {
app.dialogs.show('confirm').element('.modal-title').html("<i class='fa fa-exclamation-triangle'></i> Disable Kana Support <small>BETA</small>");
app.dialogs.element('.modal-message').empty();
app.dialogs.element('.modal-message').append("<p>Disabling this settings will require your account to perform a refresh.</p>");
app.dialogs.element('.modal-message').append("<p class='text-muted'>SUPPORT: josh@skritter.com</p>");
app.dialogs.element('.confirm').on('vclick', function() {
app.dialogs.element().off('hide.bs.modal');
app.dialogs.hide(callback);
});
} else {
app.dialogs.show('confirm').element('.modal-title').html("<i class='fa fa-exclamation-triangle'></i> Enable Kana Support <small>BETA</small>");
app.dialogs.element('.modal-message').empty();
app.dialogs.element('.modal-message').append("<p>Start writing words as they exist in their entirety with kanji and kana together at last. Enabling this setting will refresh account data to include kana writing elements for relevant vocab items.</p>");
app.dialogs.element('.modal-message').append("<p>This is a beta feature so we'll continue to make upgrades and improvements. You can disable kana writing at any time from the Settings menu.</p>");
app.dialogs.element('.modal-message').append("<p class='text-muted'>SUPPORT: josh@skritter.com</p>");
app.dialogs.element('.confirm').on('vclick', function() {
app.dialogs.element().off('hide.bs.modal');
app.dialogs.hide(callback);
});
}
app.dialogs.element().on('hide.bs.modal', function() {
if (typeof callbackError === 'function') {
callbackError();
}
});
},
function(callback) {
studyKana = !studyKana;
app.dialogs.show().element('.message-title').text((studyKana ? 'Enabling' : 'Disabling') + ' Kana');
app.dialogs.element('.message-text').text('');
self.user.settings.set('studyKana', studyKana).update(function() {
callback();
}, function(error) {
callback(error);
});
},
function(callback) {
app.user.data.items.downloadAll(function() {
callback();
}, function(error) {
callback(error);
});
}
], function(error) {
if (error) {
app.dialogs.element('.message-title').text('Something went wrong.');
app.dialogs.element('.message-text').text('Check your connection and click reload.');
app.dialogs.element('.message-confirm').html(app.fn.bootstrap.button('Reload', {level: 'primary'}));
app.dialogs.element('.message-confirm button').on('vclick', function() {
if (typeof callbackError === 'function') {
callbackError();
}
});
} else {
if (typeof callbackSuccess === 'function') {
callbackSuccess();
}
}
});
},
/**
* @method updateExpires
*/
updateExpires: function() {
this.set('expires', moment().unix() + this.get('expires_in'));
}
});
return UserData;
}); | mosinski/skritter-html5 | www/application/models/user/UserData.js | JavaScript | mit | 14,252 |
angular.module('paperworkNotes').factory('NotebooksService',
['$rootScope', '$http', 'NetService',
function($rootScope, $http, netService) {
var paperworkNotebooksServiceFactory = {};
// paperworkNotebooksServiceFactory.selectedNotebookId = 0;
paperworkNotebooksServiceFactory.createNotebook = function(data, callback) {
netService.apiPost('/notebooks', data, callback);
};
paperworkNotebooksServiceFactory.updateNotebook = function(notebookId, data, callback) {
netService.apiPut('/notebooks/' + notebookId, data, callback);
};
paperworkNotebooksServiceFactory.deleteNotebook = function(notebookId, callback) {
netService.apiDelete('/notebooks/' + notebookId, callback);
};
paperworkNotebooksServiceFactory.deleteTag = function(tagId, callback) {
netService.apiDelete('/tags/' + tagId, callback);
};
paperworkNotebooksServiceFactory.getNotebooks = function() {
netService.apiGet('/notebooks', function(status, data) {
if(status == 200) {
$rootScope.notebooks = data.response;
}
});
};
paperworkNotebooksServiceFactory.getNotebookById = function(notebookId) {
netService.apiGet('/notebooks/' + notebookId, function(status, data) {
if(status == 200) {
$rootScope.notebook = data.response;
}
});
};
paperworkNotebooksServiceFactory.getNotebookByIdLocal = function(notebookId) {
var i = 0, l = $rootScope.notebooks.length;
for(i = 0; i < l; i++) {
if($rootScope.notebooks[i].id == notebookId) {
return $rootScope.notebooks[i];
}
}
return null;
};
paperworkNotebooksServiceFactory.getNotebookShortcuts = function() {
netService.apiGet('/shortcuts', function(status, data) {
if(status == 200) {
$rootScope.shortcuts = data.response;
}
});
};
paperworkNotebooksServiceFactory.getShortcutByNotebookIdLocal = function(notebookId) {
var i = 0, l = $rootScope.shortcuts.length;
for(i = 0; i < l; i++) {
if($rootScope.shortcuts[i].id == notebookId) {
return $rootScope.shortcuts[i];
}
}
return null;
};
paperworkNotebooksServiceFactory.getTags = function() {
netService.apiGet('/tags', function(status, data) {
if(status == 200) {
$rootScope.tags = data.response;
}
});
};
return paperworkNotebooksServiceFactory;
}]);
| clemlaf/paperwork | frontend/app/js/paperwork/notebooks/notebooks.service.js | JavaScript | mit | 2,557 |
// Copyright Collab 2015-2016
define(
{
"appleItem": "apple",
"bananaItem": "banana"
}
); | collab-project/django-require-i18n | require_i18n/tests/static/js/test/nls/root/fruits.js | JavaScript | mit | 98 |
/**
*
* @internal Configuración Edilicia JavaScript - Reload Organigrama
* archivo: config_edilicia_efectores_servicios_script_event5_reload.twig.js
* Recarga el organigrama
*
* @author Sebastian Berra <sberra@santafe.gov.ar>
*
* @since 0.1.6
*
*/
/**
* Recarga el organigrama
*/
function reloadOrganigrama(id_efector){
var data ={};
data['id_efector'] = id_efector;
// submit AJAX
$.ajax({
url: "{{ path('ajax_config_edilicia_efectores_servicios_orgchart_json') }}",
data: data,
type: "GET",
dataType: 'json',
success: function(json){
// limpia y reinicia el div del orgchart
reloadDivChartContainer(json);
fullScreenButton();
}
});
}
/**
* Recarga el div del organigrama
*/
function reloadDivChartContainer(json){
$('#chart-container').html('');
$oc = $('#chart-container').orgchart({
'data': json,
'nodeContent': 'title',
'direction': '{{ config_orgchart.direccion }}',
'zoom': {{ config_orgchart.zoom }},
'pan': {{ config_orgchart.pan }},
{% if config_orgchart.export_file_extension != 'false' %}
'exportButton': true,
'exportFilename': 'ri_configuracion_edilicia',
'exportFileextension': '{{ config_orgchart.export_file_extension }}',
{% endif %}
'visibleLevel': {{ config_orgchart.visibleLevel }},
'createNode': function($node, data) {
var secondMenu = '<div class="second-menu">';
switch (data['className']){
case 'ri-orgchart-efector':
secondMenu += '<ul>' +
'<li>Complejidad: ' + data['nivel_complejidad'] + '</li>' +
'<li>Camas: ' + data['cant_camas'] + '</li></ul>';
break;
case 'ri-orgchart-efector-servicio':
case 'ri-orgchart-efector-servicio-baja':
secondMenu += '<ul>' +
'<li>Código Servicio: ' + data['cod_servicio'] + '</li>' +
'<li>Sector: ' + data['sector'] + '</li>' +
'<li>Sub-Sector: ' + data['subsector'] + '</li>' +
'<li>Núcleo: ' + data['nom_servicio'] + '</li>' +
'<li>Baja: ' + data['baja_desc'] + '</li></ul>';
break;
}
secondMenu +='</div>';
$node.append(secondMenu);
}
})
$(".fa-users").removeClass();
} | sebasberra/ri | ri_3_4/src/RI/RIBundle/Resources/views/ConfiguracionEdilicia/EfectoresServicios/scripts/config_edilicia_efectores_servicios_script_event5_reload.twig.js | JavaScript | mit | 2,900 |
'use strict'
const request = require('request-promise-native')
const _async = require('asyncawait/async')
const _await = require('asyncawait/await')
const he = require('he')
const endpointsSpec = require('./endpointsSpec')
function nodeGlvrd (appName) {
if (typeof appName !== 'string' || !appName.length) {
throw new Error(`appName is required and should be a string. Got ${typeof appName} ${appName}`)
}
this.params = {
app: appName,
maxTextLength: 10000,
maxHintsCount: 25
}
this.hintsCache = {}
this.req = request.defaults({
baseUrl: endpointsSpec.baseUrl,
timeout: 3000
})
}
nodeGlvrd.prototype.checkStatus = _async(function checkStatus () {
let response = _await(this._makeRequest('getStatus'))
this.params.maxTextLength = response['max_text_length']
this.params.maxHintsCount = response['max_hints_count']
return response
})
nodeGlvrd.prototype.proofread = _async(function proofread (text, callback) {
try {
let fragmentsWithoutHints = _await(this._makeRequest('postProofread', { text: text }))
this._checkIfServerError(fragmentsWithoutHints)
let fragmentsWithHints = []
fragmentsWithHints = _await(this._fillRawFragmentsWithHints(fragmentsWithoutHints.fragments))
if (!callback) return fragmentsWithHints
callback(null, fragmentsWithHints)
} catch (err) {
if (!callback) throw err
callback(err, null)
}
})
nodeGlvrd.prototype._fillRawFragmentsWithHints = _async(function _fillRawFragmentsWithHints (rawFragments) {
// Check which hints already chached
let uncachedHints = []
rawFragments.forEach(fragment => this.hintsCache.hasOwnProperty(fragment.hint_id) ? false : uncachedHints.push(fragment.hint_id))
// Early return if all our hints are cached
if (uncachedHints.length === 0) {
return _await(this._fillFragmentsWithHintFromCache(rawFragments))
}
// Remove duplicate hints
let uncachedHintIds = {}
uncachedHints.forEach(hintId => { uncachedHintIds[hintId] = null })
// Query for uncached hints by chanks -- amount of hints in a singl request is limited
let hintRequests = []
this._chunkArray(Object.keys(uncachedHintIds), this.params.maxHintsCount)
.forEach(uncachedHintIdsChunk =>
hintRequests.push(this._makeRequest('postHints', { ids: uncachedHintIdsChunk.join(',') }))
)
let hintResposes = _await(Promise.all(hintRequests))
// Fill cache with new hints
hintResposes.forEach(response => Object.assign(this.hintsCache, response.hints))
this.hintsCache = this._decodeHintsDescription(this.hintsCache)
return this._fillFragmentsWithHintFromCache(rawFragments)
})
nodeGlvrd.prototype._fillFragmentsWithHintFromCache = function _fillFragmentsWithHintFromCache (fragments) {
return fragments.splice(0).map(fragment => {
let hintFromCache = this.hintsCache[fragment.hint_id]
if (!hintFromCache) {
throw new Error(`Can't find hint ${fragment.hint_id} in cache`)
}
let { name, description } = hintFromCache
fragment.hint = {
id: fragment.hint_id,
name: name,
description: description
}
delete fragment.hint_id
return fragment
})
}
nodeGlvrd.prototype._makeRequest = _async(function _makeRequest (endpointKey, body, isJson = true) {
let endpoint = endpointsSpec.endpoints[endpointKey]
let weNeedSessionForRequest = endpoint.queryParams.includes('session')
if (weNeedSessionForRequest) {
_await(this._checkSessionBeforeRequest())
}
// Prepare request
let queryParams = this._fillQueryParams(endpoint.queryParams)
let options = {
method: endpoint.method,
uri: endpoint.name,
qs: queryParams,
json: isJson
}
if (body) {
options.form = body
}
// Make request
let responseBody = _await(this.req(options))
// Check request response
if (responseBody.status && responseBody.status === 'error') {
if (responseBody.code === endpointsSpec.errorsForCover.bad_session.code) {
// Try to update session and repeat request silently
_await(this._createSession())
responseBody = _await(this.req(options))
} else {
throw responseBody
}
}
if (endpoint.method === 'post') {
this._extendSession() // Every POST request extends session
}
return responseBody
})
nodeGlvrd.prototype._checkSessionBeforeRequest = _async(function _checkSessionBeforeRequest () {
let isSessionValid = this.params.sessionValidUntil > (Date.now() + 1000)
if (this.params.session && isSessionValid) {
return
}
_await(this._createSession())
})
nodeGlvrd.prototype._fillQueryParams = function _fillQueryParams (endpointQueryParams) {
let queryParams = {}
endpointQueryParams.forEach(queryParamName => {
if (this.params.hasOwnProperty(queryParamName)) {
queryParams[queryParamName] = this.params[queryParamName]
}
})
return queryParams
}
nodeGlvrd.prototype._createSession = _async(function _createSession () {
let response = _await(this._makeRequest('postSession'))
this._resetSessionParams(response.session, response.lifespan)
})
nodeGlvrd.prototype._extendSession = function _extendSession () {
this._resetSessionParams(this.params.session, this.params.sessionLifespan)
}
nodeGlvrd.prototype._resetSessionParams = function _resetSessionParams (session, lifespan) {
if (session !== this.params.session) {
this.hintsCache = {}
}
this.params.session = session
this.params.sessionLifespan = lifespan
this.params.sessionValidUntil = Date.now() + lifespan * 1000
}
nodeGlvrd.prototype._chunkArray = function _chunkArray (arr, len) {
let chunks = []
let i = 0
let n = arr.length
while (i < n) {
chunks.push(arr.slice(i, i += len))
}
return chunks
}
nodeGlvrd.prototype._checkIfServerError = function _checkIfServerError (functionResult) {
if (functionResult.status && functionResult.status === 'error') {
throw functionResult
}
}
nodeGlvrd.prototype._decodeHintsDescription = function _decodeHintsDescription (hints) {
let decodedHints = JSON.parse(JSON.stringify(hints))
Object.keys(decodedHints).forEach(hintId => {
let rawDescription = decodedHints[hintId].description
decodedHints[hintId].description = he.decode(rawDescription)
})
return decodedHints
}
module.exports = nodeGlvrd
| terales/node-glvrd | index.js | JavaScript | mit | 6,275 |
import DarkSky from 'dark-sky-api';
// Hardcode the key here in the client since we have no API proxy
// and there are no alternative APIs that do not require keys (and are free)
// if you know about some, please let me know
DarkSky.apiKey = '394d3340d5fb35ab845beffae8aa4be8';
DarkSky.units = 'si';
export default DarkSky;
| petersandor/react-weather-app | src/utils/weatherApiClient.js | JavaScript | mit | 326 |
/**
* Autoinsert script tags (or other filebased tags) in an html file.
*
* ---------------------------------------------------------------
*
* Automatically inject <script> tags for javascript files and <link> tags
* for css files. Also automatically links an output file containing precompiled
* templates using a <script> tag.
*
* For usage docs see:
* https://github.com/Zolmeister/grunt-sails-linker
*
*/
module.exports = function(grunt) {
grunt.config.set('sails-linker', {
devJs: {
options: {
startTag: '<!--SCRIPTS-->',
endTag: '<!--SCRIPTS END-->',
fileTmpl: '<script type="text/javascript" src="/static/%s"></script>'
},
files: {
'../templates/**/*.html': require('../pipeline').jsFilesToInject
}
},
devJsRelative: {
options: {
startTag: '<!--SCRIPTS-->',
endTag: '<!--SCRIPTS END-->',
fileTmpl: '<script type="text/javascript" src="/static/%s"></script>',
relative: true
},
files: {
'../templates/**/*.html': require('../pipeline').jsFilesToInject
}
},
prodJs: {
options: {
startTag: '<!--SCRIPTS-->',
endTag: '<!--SCRIPTS END-->',
fileTmpl: '<script type="text/javascript" src="/static/%s"></script>'
},
files: {
'../templates/**/*.html': ['./dist/libs.min.js', './dist/main.min.js']
}
},
prodJsRelative: {
options: {
startTag: '<!--SCRIPTS-->',
endTag: '<!--SCRIPTS END-->',
fileTmpl: '<script type="text/javascript" src="/static/%s"></script>',
relative: true
},
files: {
'../templates/**/*.html': ['dist/javascripts/libs.min.js', 'dist/javascripts/main.min.js']
}
},
devStyles: {
options: {
startTag: '<!--STYLES-->',
endTag: '<!--STYLES END-->',
fileTmpl: '<link rel="stylesheet" href="/static/%s">'
},
files: {
'../templates/**/*.html': require('../pipeline').cssFilesToInject
}
},
prodStyles: {
options: {
startTag: '<!--STYLES-->',
endTag: '<!--STYLES END-->',
fileTmpl: '<link rel="stylesheet" href="/static/%s">'
},
files: {
'../templates/**/*.html': ['dist/stylesheets/main.css']
}
},
devStylesRelative: {
options: {
startTag: '<!--STYLES-->',
endTag: '<!--STYLES END-->',
fileTmpl: '<link rel="stylesheet" href="/static/%s">',
relative: true
},
files: {
'../templates/**/*.html': require('../pipeline').cssFilesToInject
}
},
prodStylesRelative: {
options: {
startTag: '<!--STYLES-->',
endTag: '<!--STYLES END-->',
fileTmpl: '<link rel="stylesheet" href="/static/%s">',
relative: true
},
files: {
'../templates/**/*.html': ['dist/stylesheets/main.css']
}
},
});
grunt.loadNpmTasks('grunt-sails-linker');
}; | ifahrentholz/grunt-boilerplate | tasks/config/sails-linker.js | JavaScript | mit | 3,011 |
!function (name, context, definition) {
if (typeof module != 'undefined' && module.exports) {
module.exports = definition(require('leaflet'), require('reqwest'), require('leaflet.markercluster'));
} else {
context[name] = definition(L, reqwest);
}
}('HubMap', this, function (L, reqwest) {
HubMap = this.HubMap || {};
HubMap.map = function(elem, options) {
var baseUrl = HubMap.BASE_URL || "{{ url_for('.index', _external=True).rstrip('/') }}";
var planAppInfo = HubMap.PLAN_APP_INFO || "<h2><a href='{caseurl}'>{casereference}</a></h2><p>{locationtext}</p><p>Status: {status} {statusdesc}</p>";
L.Icon.Default.imagePath = baseUrl + "/embed/images";
var map = L.map(elem).setView([51.23, -0.32], 9);
var osmAttr = 'Tiles: © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors - ';
var hubAttr = 'Planning Applications: <a href="#">Surrey Planning Hub</a>';
var mqOpt = {
url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
options: {attribution: osmAttr + hubAttr}
};
var mq = L.tileLayer(mqOpt.url, mqOpt.options);
mq.addTo(map);
var markers = L.markerClusterGroup();
var apps = L.geoJson(null, {onEachFeature: popUp});
data_url = baseUrl + options.data_url;
reqwest({url: data_url, type: 'jsonp'}).then(function (data) {
if (data.features && data.features.length) {
apps.addData(data);
markers.addLayer(apps).addTo(map);
map.fitBounds(markers.getBounds());
} else {
HubMap.warn('No results returned for data_url: ', data_url);
}
});
function popUp(f, l){
var props = {},
key, val;
for (key in f.properties) {
if (f.properties.hasOwnProperty(key)) {
val = f.properties[key];
props[key] = (val === null) ? '' : val;
}
}
var content = L.Util.template(planAppInfo, props);
l.bindPopup(content);
}
return map;
};
HubMap.createMaps = function() {
var elems = document.getElementsByClassName('hub-map'),
maps = [];
if (elems.length === 0) {
HubMap.warn('No elements found with the "hub-map" class at this time. You may need to call HubMap.createMaps when the page has loaded or create a map manually with HubMap.map.');
}
for (var i = 0, elem, data_url; i < elems.length; i++) {
elem = elems[i];
data_url = elem.getAttribute("data-url");
if (data_url) {
maps.push(HubMap.map(elem, {data_url: data_url}));
} else {
HubMap.warn('No data URL passed, skipping creating map. Element: ', elem);
}
}
return maps;
};
HubMap.warn = function() {
if (console && console.warn) console.warn.apply(console, Array.prototype.slice.call(arguments));
};
// Attempt to create maps for elements with a "hub-map" class
HubMap.createMaps();
return HubMap;
});
| AstunTechnology/planning-hub | api/static/hubmap/main.js | JavaScript | mit | 3,250 |
function solve(commands) {
let numbers = [];
let counter = 1;
for (let command of commands) {
if (command == "add") {
numbers.unshift(counter);
}
else {
numbers.shift();
}
counter++;
}
if (numbers.length == 0) {
console.log("Empty");
return;
}
console.log(numbers.reverse().join(`\n`));
} | stoyanov7/SoftwareUniversity | JavaScriptCore/Archive/JavaScriptFundamentals/Arrays-and-Matrices-Exercise/03.addAndRemoveElements.js | JavaScript | mit | 428 |
describe('Panel', () => {
let Panel;
before(() => {
Test.assertSL();
Panel = Test.Lib.Panel.Panel;
});
it('should exist', () => {
expect(Panel).to.exist;
});
it('should have Manager property', () => {
expect(Panel.Manager).to.exist;
});
it('should have Type property', () => {
expect(Panel.Type).to.exist;
});
});
| TechNaturally/stamplines | test/tests/panel/panel-test.js | JavaScript | mit | 352 |
/**
* @copyright
* @author
* @license MIT
*/
/**
* @class Joints.Collection
* @extends Backbone.Collection
*/
Joints.defineClass('Joints.Collection', Backbone.Collection, {
}, {
inst: Joints.Object.inst
});
| ExtPoint/NeatComet | quick_start/legacy_comet_server/lib/joints/source/Collection.js | JavaScript | mit | 220 |
/**
* Copyright: (c) 2017-2018 Max Klein
* License: MIT
*/
define([
'editor/displayComponent',
'lib/SvgUtil'
], function (displayComponent, SvgUtil) {
function Component() {
this.x = 0;
this.y = 0;
this.startX = 0;
this.startY = 0;
this.$group = null;
this.transform = null;
this.mousedownCallback = null;
this.selected = false;
}
Component.prototype.save = function () {
var data = {
type: this.constructor.typeName,
x: this.x,
y: this.y
};
this._save(data);
return data;
};
Component.prototype.load = function (data) {
this.x = data.x;
this.y = data.y;
this._load(data);
};
Component.prototype.select = function () {
this.selected = true;
this._select();
};
Component.prototype.deselect = function () {
this.selected = false;
this._deselect();
};
Component.prototype.display = function ($container) {
this.$group = SvgUtil.createElement('g');
this.$group.setAttribute('transform', 'matrix(1 0 0 1 0 0)');
this.transform = this.$group.transform.baseVal[0];
this.updateDisplay();
this._display(this.$group);
$container.appendChild(this.$group);
};
Component.prototype.remove = function () {
if(!this.$group) return;
this.$group.parentNode.removeChild(this.$group);
this.$group = null;
};
Component.prototype.updateDisplay = function () {
if(!this.$group) return;
this.transform.matrix.e = this.x * 10;
this.transform.matrix.f = this.y * 10;
};
Component.prototype.serializeForSimulation = function () {
var data = this._serializeForSimulation();
data.x = this.x;
data.y = this.y;
if (this.isCustom) {
this.updatePins();
}
var pinsData = [];
for (var i = 0; i < this.pins.length; i++) {
var pin = this.pins[i];
pinsData.push({
x: pin.x,
y: pin.y,
out: pin.out,
index: pin.index
});
}
data.pins = pinsData;
return data;
};
return Component;
});
| maxkl/LogicSimulator | src/js/main/editor/Component.js | JavaScript | mit | 1,907 |
import React, { Component, PropTypes } from 'react';
import { FloatLabelInput as Input } from 'ferox';
import { Search } from 'ickle';
export default class SearchBar extends Component {
render() {
const { query, onSearch } = this.props;
return (
<Input label='Search' Icon={Search} value={query} onChange={onSearch} />
);
}
};
| defact/gabbro | lib/components/search.js | JavaScript | mit | 351 |
/**
* Created by Shawn Liu on 2015/5/20.
*/
var ScrapeQueue = require("./ScrapeQueue");
var Promise = require("bluebird");
var async = require("async");
var logger = require("node-config-logger").getLogger("components/crawler/CrawlerInstance.js");
var fs = require("fs");
var rp = require("request-promise");
var _ = require("lodash");
var webdriverIO = require('webdriverio');
var SeleniumInstance = require("../seleniumInstance");
var config = require("config")
function CrawlerInstance(serverURL, type, port, hubPort) {
this.server = serverURL;
this.port = port;
this.id = serverURL;
this.queue = new ScrapeQueue(this, {
id: this.server,
maxRetries: 0
});
this.type = type;
this.hub = hubPort;
this.timeout = config.phantom.timeout || 60000;
this.restartTimes = 3;
}
CrawlerInstance.prototype.request = function (job, retailerSelectorConfig, timeout) {
if (job.method === "details") {
return _scrape("details", job.productURL, retailerSelectorConfig.config.detail, retailerSelectorConfig.browser || job.browser, this, timeout);
} else if (job.method === "links") {
return _scrape("links", job.productURL, retailerSelectorConfig.config.search, retailerSelectorConfig.browser || job.browser, this);
}
//return _scrape(job.productURL, selectorConfig.selectors, job.browser, this)
}
CrawlerInstance.prototype.restart = function () {
//return Promise.resolve();
var crawlerInstance = this;
//SeleniumInstance.port = crawlerInstance.hub;
return SeleniumInstance.restartPhantom(crawlerInstance.port);
}
function _scrape(type, productURL, selectorConfig, browser, crawlerInstance, timeout) {
var client = webdriverIO
.remote({
desiredCapabilities: {
browserName: browser
},
port: crawlerInstance.port
});
var crawlerTimeout = null;
//setup timeout function , make function return when server no response
var jsonResult = {
"status": true,
"productURL": productURL,
"scraped": {},
"errors": [],
"browser": browser,
"updateTime": new Date()
//"selectors": _.cloneDeep(selectorConfig)
};
return new Promise(function (resolve, reject) {
crawlerTimeout = setTimeout(function () {
jsonResult.status = false;
jsonResult.errors = ["crawler server timeout after " + crawlerInstance.timeout / 1000 + " seconds"];
reject(jsonResult);
}, timeout || crawlerInstance.timeout);
return _initClient(client, jsonResult, crawlerInstance, crawlerInstance.restartTimes)
.then(function () {
return _openUrl(client, productURL, jsonResult);
})
.then(function () {
logger.info("scraping product '%s'", productURL);
var promise = Promise.resolve();
if (type === "details") {
promise = _extractStock(client, selectorConfig.stock)
.then(function (scrapedStock) {
jsonResult.status = true;
jsonResult.scraped.stock = scrapedStock;
return _extractInfo(client, selectorConfig.info, jsonResult.scraped);
})
.then(function (scrapedInfo) {
if (!scrapedInfo.status) {
jsonResult.status = false;
jsonResult.errors = scrapedInfo.errors;
} else {
jsonResult.status = true;
delete jsonResult.errors;
}
delete scrapedInfo.status;
delete scrapedInfo.errors;
jsonResult.scraped = scrapedInfo;
return jsonResult;
})
.catch(function (errors) {
logger.error("#_extractStock():", errors);
jsonResult.status = false;
jsonResult.errors = errors;
return jsonResult;
})
} else if (type === "links") {
promise = _extractLinks(client, selectorConfig)
.then(function (scrapedInfo) {
if (!scrapedInfo.status) {
jsonResult.status = false;
jsonResult.errors = scrapedInfo.errors;
} else {
jsonResult.status = true;
}
jsonResult.scraped = scrapedInfo.scraped;
return jsonResult;
})
.catch(function (errors) {
logger.error("#_extractLinks():", errors);
jsonResult.status = false;
jsonResult.errors = errors;
return jsonResult;
})
}
return promise;
})
.then(function (r) {
return _endClient(client)
.then(function () {
return r;
})
})
.then(function (result) {
//return result;
resolve(result || jsonResult);
})
.catch(function (errResult) {
logger.error("#_scrape():", errResult.errors);
reject(errResult || jsonResult);
})
.finally(function () {
if (crawlerTimeout) {
clearTimeout(crawlerTimeout);
}
});
})
}
function _extractLinks(client, selectorConfig) {
logger.warn("scraping links")
return new Promise(function (resolve, reject) {
var finished = false;
var resultJSON = {};
var products = [];
async.until(function isDone() {
return finished;
}, function next(callback) {
_extractProductForLink(client, selectorConfig.info)
.then(function (scrapedResult) {
if (scrapedResult && scrapedResult.status) {
resultJSON.status = true;
//products = products.contact(scrapedResult.scraped);
Array.prototype.push.apply(products, scrapedResult.scraped);
var pagination = selectorConfig.pagination;
if (pagination && pagination.required) {
return _pagination(client, pagination)
.then(function (r) {
if (!r || !r.status) {
resultJSON.status = true;
resultJSON.scraped = products;
finished = true;
}
})
} else {
resultJSON.status = true;
resultJSON.scraped = products;
finished = true;
}
} else {
finished = true;
resultJSON.status = false;
resultJSON.errors = scrapedResult.errors;
}
})
.catch(function (err) {
logger.error(err);
resultJSON.status = false;
resultJSON.errors = err.errors || [err.message || err];
})
.finally(function () {
callback();
});
}, function done() {
resolve(resultJSON);
})
});
}
function _generateProduct(extractJSON) {
if (extractJSON && Object.keys(extractJSON).length > 0) {
var resultJSON = {};
var array = [];
var fields = Object.keys(extractJSON);
var baseSize = 0;
var valid = true;
fields.forEach(function (field) {
if (baseSize === 0) {
baseSize = extractJSON[field].length;
}
valid = valid && (baseSize === extractJSON[field].length);
});
if (!valid) {
resultJSON.status = false;
resultJSON.errors = ["when get product links , name and url don't math"];
} else {
for (var i = 0; i < extractJSON[fields[0]].length; i++) {
var t = {};
t[fields[0]] = extractJSON[fields[0]][i];
for (var j = 1; j < fields.length; j++) {
t[fields[j]] = extractJSON[fields[j]][i];
}
array.push(t);
}
resultJSON.status = true;
resultJSON.result = array;
}
} else {
resultJSON.status = true;
resultJSON.result = [];
}
return resultJSON;
}
function _pagination(client, pageConfig) {
return new Promise(function (resolve, reject) {
var resultJSON = {};
if (pageConfig.type === "scroll") {
resultJSON.status = false;
resolve(resultJSON);
} else {//no scroll , will be click
client.click(pageConfig.button, function (err, data) {
if (err) {
logger.error(err);
resultJSON.status = false;//pagination button doesn't exist or has finished pagination
} else {
resultJSON.status = true;
}
resolve(resultJSON);
});
}
});
}
function _extractProductForLink(client, infos1, domain) {
var infos = _.cloneDeep(infos1);
return new Promise(function (resolve, reject) {
var breakDown = false;
var json = {};
var resultJSON = {};
async.until(function isDone() {
return infos.length === 0 || breakDown;
}, function next(callback) {
var infoC = infos.shift();
_scrapeBySelectors(client, infoC.scrape, infoC.selectors)
.then(function (resultContent) {
if (resultContent && resultContent.status) {
resultJSON.status = true;
if (json[infoC.field]) {
json[infoC.field] = [];
}
json[infoC.field] = resultContent.content;
} else {
breakDown = true;
resultJSON.status = false;
resultJSON.errors = err.errors;
}
})
.catch(function (err) {
resultJSON.status = false;
resultJSON.errors = err.errors || [err.message || err];
})
.finally(function () {
callback();
})
}, function done() {
if (resultJSON.status) {
var r = _generateProduct(json);
resultJSON.status = r.status;
resultJSON.scraped = r.result;
}
resolve(resultJSON);
})
});
}
/**
* init webdriverIO client , when failed to init
* will try to re-register the phantom(chrome) node by given port
* @param client
* @param jsonResult
* @param crawlerInstance
* @param retryTimes
* @returns {*}
* @private
*/
function _initClient(client, jsonResult, crawlerInstance, retryTimes) {
if (!retryTimes && retryTimes !== 0) {
retryTimes = 1;
}
function _init() {
return new Promise(function (resolve, reject) {
client.init(function (err, data) {
if (err) {
logger.error("error when init webdriver");
jsonResult.errors = [err.message || err];
jsonResult.status = false;
reject(jsonResult);
} else {
resolve();
}
})
})
}
return _init()
.catch(function (jsonResult) {
if (retryTimes > 0) {
retryTimes--;
return crawlerInstance.restart()
.then(function () {
return _init();
})
.catch(function () {
return Promise.reject(jsonResult);
})
} else {
return Promise.reject(jsonResult);
}
});
}
function _openUrl(client, productURL, jsonResult) {
return new Promise(function (resolve, reject) {
client.url(productURL)
.then(function () {
resolve();
})
.catch(function (err) {
logger.error("error when open product page ,may need to init crawler again")
jsonResult.errors.push({
"message": err.message || err
});
jsonResult.status = false;
reject(jsonResult);
});
})
}
function _endClient(client) {
return new Promise(function (resolve, reject) {
client.endAll(function () {
logger.error("===================== Close Client ==================================")
resolve();
})
})
}
/**
* scrape all other information exclude stock meanwhile check whether
* filed is required base on stock info , when it's required and can not get
* value ,will throw exception
* @param client
* @param infos Array
* @param scrapedResult like {"stock":"in-stock"}
* @returns {Promise}
* @private
*/
function _extractInfo(client, infos, scrapedResult1) {
var scrapedResult = _.cloneDeep(scrapedResult1);
scrapedResult.status = true;
return new Promise(function (resolve, reject) {
infos = infos.filter(function (item) {
return item.selectors && item.selectors.length > 0;
});
var throeError = false;
async.until(function isDone() {
return infos.length === 0 || throeError;
}, function next(callback) {
try {
var info = infos.shift();
var required = info.requiredWhenStatusInclude.some(function (item) {
return item === scrapedResult.stock;
});
_scrapeBySelectors(client, info.scrape, info.selectors)
.then(function (scrapedR) {
if (scrapedR.status) {
scrapedResult[info.field] = scrapedR.content;
} else {
if (required) {
throeError = true;
scrapedResult.status = false;
scrapedResult.errors = scrapedR.errors;
}
}
})
.catch(function (err) {
logger.error(err);
})
.finally(function () {
callback();
})
} catch (e) {
throeError = true;
scrapedResult.status = false;
scrapedResult.errors = [e.message || e];
callback();
}
}, function done() {
resolve(scrapedResult);
});
})
}
/**
* extract stock info , must be able to find one valid status from
* stockConfig.statusList , otherwise will throw exception
* @param client
* @param stockConfig
* @returns {Promise}
* @private
*/
function _extractStock(client, stockConfig) {
var result = {};
logger.info("Scraping stock info");
return new Promise(function (resolve, reject) {
try {
var finished = false;
var statusList = stockConfig.statusList.filter(function (item) {
return item.selectors && item.selectors.length > 0
});
async.until(function isDone() {
return statusList.length === 0 || finished;
}, function next(callback) {
var statusConfig = statusList.shift();
_scrapeBySelectors(client, statusConfig.scrape, statusConfig.selectors)
.then(function (statusScrapedData) {
if (statusScrapedData.status) {
result.status = true;
result.content = statusConfig.status;
finished = true;
}
})
.catch(function (err) {
logger.error("#_scrapeBySelectors() :", err);
result.status = false;
result.errors = [err.message || err];
finished = true;
})
.finally(function () {
callback()
})
}, function done() {
//resolve(result)
if (result.status) {
resolve(result.content);
} else {
reject(result.errors);
}
})
} catch (err) {
result.status = false;
result.errors = [err.message || err];
reject(result);
}
});
}
/**
* scrape for specified filed with multiply selectors ,
* will forEach the selectors to scrape ,will break when find valid value or throw error
* @param client
* @param scrapeConfig
* @param selectors
* @returns {Promise}
* @private
*/
function _scrapeBySelectors(client, scrapeConfig, selectors) {
return new Promise(function (resolve, reject) {
var finished = false;
var selectorsLength = selectors.length;
var result = {};
var errors = [];
async.until(function isDone() {
return selectors.length === 0 || finished;
}, function next(callback) {
var selector = selectors.shift();
switch (scrapeConfig.type) {
case 'value' :
{
client.getValue(selector, _handle);
break;
}
case 'html':
{
client.getHTML(selector, _handle);
break;
}
case 'attribute':
{
client.getAttribute(selector, scrapeConfig.attr, _handle);
break;
}
case 'elementExist':
{
client.isExisting(selector, _handle);
break;
}
case 'textInclude':
{
client.getText(selector, function (err, data) {
_handle(err, err ? false : _include(data, scrapeConfig.keys));
});
break;
}
default :
{
client.getText(selector, _handle);
}
}
function _handle(err, data) {
//logger.debug("scraped content '%s' with selector '%s' on type '%s'", data, selector, scrapeType.type);
if (err) {
errors.push(err.message || err);
if (errors.length === selectorsLength) {
logger.error(errors);
result.status = false;
result.errors = errors;
}
} else {
result.status = true;
result.content = data;
finished = true;
}
callback();
}
}, function done() {
resolve(result);
})
})
}
/**
* check whether resultStr contains any string from keys array
* @param resultStr String
* @param keys Array
* @returns {*}
* @private
*/
function _include(resultStr, keys) {
if (resultStr && keys) {
resultStr = resultStr.toString().toLowerCase();
return keys.some(function (item) {
return item && resultStr.indexOf(item.toLowerCase()) !== -1;
})
} else {
return false;
}
}
/**
* scrape content by multiply selectors for single filed ,
* if first one got result ,will break , otherwise execute next one
* @param client webdriverIO object
* @param selectors css or xpath array , like ["div.test1","div.test2"]
* @param type
* @returns {*}
*/
function extractBySelector(client, selectors1, scrapeType) {
return new Promise(function (resolve, reject) {
var result = {
"content": null,
"errors": []
};
var selectors = _.cloneDeep(selectors1);
if (selectors && Array.isArray(selectors)) {
async.until(function isDone() {
return result.content || selectors.length === 0;
}, function next(callback) {
var selector = selectors.shift();
switch (scrapeType.type) {
case 'value' :
{
client.getValue(selector, handle);
break;
}
case 'html':
{
client.getHTML(selector, handle);
break;
}
case 'attribute':
{
client.getAttribute(selector, scrapeType.attribute, handle);
break;
}
default :
{
client.getText(selector, handle);
}
}
function handle(err, data) {
//logger.debug("scraped content '%s' with selector '%s' on type '%s'", data, selector, scrapeType.type);
if (err) {
result.errors.push({
"message": err.message || err
});
if (result.errors.length === selectors.length) {
logger.error(errors);
}
} else {
result.content = data;
}
callback();
}
}, function done() {
if (result.content) {
//if one of the selector got content , mean got content successfully , can ignore other errors
delete result.errors;
}
resolve(result);
})
} else {
result.errors.push({
"message": "invalid selectors",
"selector": selectors
});
resolve(result);
}
});
}
function _isValidBrowser(browser) {
return true;
}
//process.on("uncaughtException", function (err) {
// logger.error("CrawlerInstance.js UncaughtException:", err);
//});
module.exports = CrawlerInstance; | shawnLiujianwei/selenium-crawler-server | components/crawler/CrawlerInstance.js | JavaScript | mit | 23,627 |
import moduleBank from './moduleBank';
export default function entities(state = {}, action) {
return {
moduleBank: moduleBank(state.moduleBank, action),
};
}
| momomods/momomods | src/reducers/entities/index.js | JavaScript | mit | 167 |
'use strict';
const debug = require('debug')('olayers:photo-mock');
const Photo = require('../../model/photo.js');
module.exports = function(done){
debug('mock photo');
new Photo({
name: 'taco tuesday',
imageURI: 'http://fdsaf.jpg',
objectKey: 'whatever',
userID: this.tempUser._id.toString(),
profileID: this.tempProfile._id.toString(),
postID: this.tempPost._id.toString(),
}).save()
.then(photo => {
this.tempPhoto = photo;
done();
})
.catch(done);
};
| irvinemd55/olayers | test/lib/photo-mock.js | JavaScript | mit | 501 |
import { mapGetters } from 'vuex';
export default {
props: ['player'],
template: `
<div class="ctrl-menu frame flex flex-wrap" >
<button-ctrl
v-for="(ctrl,i) in ctrlBets"
:key="i" :ctrl="ctrl"
@click.native="addChip(ctrl.ref)" >
</button-ctrl>
<button-ctrl
v-for="(ctrl,j) in ctrlSubmits"
:key="j" :ctrl="ctrl"
@click.native="ctrl.onClick()" >
</button-ctrl>
</div>
`,
data() {
return {
chips: [5, 10, 25, 100, 500, 1000],
currChips: [],
currChipValue: 0,
};
},
computed: {
ctrlBets() {
const maxChips = (this.player.money - this.currChipValue);
return this.chips.map((chip) => {
const canUse = chip <= maxChips;
return {
ref: chip,
name: `£${chip}`,
class: `betting-chip chip-${chip}`,
svg: '#chip',
canUse,
onClick: this.addChip,
};
});
},
ctrlSubmits() {
const bet = this.currChipValue;
const canUse = (bet >= this.minBet);
const betStr = canUse ? `Submit: £${bet}` : 'Submit';
const alert = `Min: £${this.minBet}`;
return [
{ name: betStr, class: 'btn-good', icon: 'publish', canUse, onClick: this.emitBet, alert },
{ name: 'Undo', class: 'btn-alert', icon: 'undo', canUse: bet > 0, onClick: this.removeChip },
];
},
...mapGetters([
'minBet',
]),
},
methods: {
addChip(chip) {
this.currChipValue += chip;
this.currChips.push(chip);
},
removeChip() {
const chip = this.currChips.pop();
this.currChipValue -= chip;
},
emitBet() {
const player = this.player;
const idx = player.index;
const bet = this.currChipValue;
const store = this.$store;
const betVals = {
idx,
value: bet,
};
const betEvent = {
idx,
type: 'bet',
value: 'addBet',
};
this.currChips = [];
this.currChipValue = 0;
// todo bonus combine these in store?
store.dispatch('setNewMessage', `${player.name} bets £${bet}`);
store.dispatch('playerSetBet', betVals)
.then(() => store.dispatch('doEvent', betEvent))
.then(() => store.dispatch('nextPlayer'));
},
},
};
| jon-r/jr_blackJackVue | src/ctrls/bet-ctrl.js | JavaScript | mit | 2,313 |
/*! JointJS v3.4.4 (2021-09-27) - JavaScript diagramming library
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.g = {}));
}(this, function (exports) { 'use strict';
// Declare shorthands to the most used math functions.
var round = Math.round;
var floor = Math.floor;
var PI = Math.PI;
var scale = {
// Return the `value` from the `domain` interval scaled to the `range` interval.
linear: function(domain, range, value) {
var domainSpan = domain[1] - domain[0];
var rangeSpan = range[1] - range[0];
return (((value - domain[0]) / domainSpan) * rangeSpan + range[0]) || 0;
}
};
var normalizeAngle = function(angle) {
return (angle % 360) + (angle < 0 ? 360 : 0);
};
var snapToGrid = function(value, gridSize) {
return gridSize * round(value / gridSize);
};
var toDeg = function(rad) {
return (180 * rad / PI) % 360;
};
var toRad = function(deg, over360) {
over360 = over360 || false;
deg = over360 ? deg : (deg % 360);
return deg * PI / 180;
};
// Return a random integer from the interval [min,max], inclusive.
var random = function(min, max) {
if (max === undefined) {
// use first argument as max, min is 0
max = (min === undefined) ? 1 : min;
min = 0;
} else if (max < min) {
// switch max and min
var temp = min;
min = max;
max = temp;
}
return floor((Math.random() * (max - min + 1)) + min);
};
// @return the bearing (cardinal direction) of the line. For example N, W, or SE.
var cos = Math.cos;
var sin = Math.sin;
var atan2 = Math.atan2;
var bearing = function(p, q) {
var lat1 = toRad(p.y);
var lat2 = toRad(q.y);
var lon1 = p.x;
var lon2 = q.x;
var dLon = toRad(lon2 - lon1);
var y = sin(dLon) * cos(lat2);
var x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
var brng = toDeg(atan2(y, x));
var bearings = ['NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'N'];
var index = brng - 22.5;
if (index < 0)
{ index += 360; }
index = parseInt(index / 45);
return bearings[index];
};
// @return {integer} length without sqrt
// @note for applications where the exact length is not necessary (e.g. compare only)
var squaredLength = function(start, end) {
var x0 = start.x;
var y0 = start.y;
var x1 = end.x;
var y1 = end.y;
return (x0 -= x1) * x0 + (y0 -= y1) * y0;
};
var length = function(start, end) {
return Math.sqrt(squaredLength(start, end));
};
/*
Point is the most basic object consisting of x/y coordinate.
Possible instantiations are:
* `Point(10, 20)`
* `new Point(10, 20)`
* `Point('10 20')`
* `Point(Point(10, 20))`
*/
var abs = Math.abs;
var cos$1 = Math.cos;
var sin$1 = Math.sin;
var sqrt = Math.sqrt;
var min = Math.min;
var max = Math.max;
var atan2$1 = Math.atan2;
var round$1 = Math.round;
var pow = Math.pow;
var PI$1 = Math.PI;
var Point = function(x, y) {
if (!(this instanceof Point)) {
return new Point(x, y);
}
if (typeof x === 'string') {
var xy = x.split(x.indexOf('@') === -1 ? ' ' : '@');
x = parseFloat(xy[0]);
y = parseFloat(xy[1]);
} else if (Object(x) === x) {
y = x.y;
x = x.x;
}
this.x = x === undefined ? 0 : x;
this.y = y === undefined ? 0 : y;
};
// Alternative constructor, from polar coordinates.
// @param {number} Distance.
// @param {number} Angle in radians.
// @param {point} [optional] Origin.
Point.fromPolar = function(distance, angle, origin) {
origin = new Point(origin);
var x = abs(distance * cos$1(angle));
var y = abs(distance * sin$1(angle));
var deg = normalizeAngle(toDeg(angle));
if (deg < 90) {
y = -y;
} else if (deg < 180) {
x = -x;
y = -y;
} else if (deg < 270) {
x = -x;
}
return new Point(origin.x + x, origin.y + y);
};
// Create a point with random coordinates that fall into the range `[x1, x2]` and `[y1, y2]`.
Point.random = function(x1, x2, y1, y2) {
return new Point(random(x1, x2), random(y1, y2));
};
Point.prototype = {
chooseClosest: function(points) {
var n = points.length;
if (n === 1) { return new Point(points[0]); }
var closest = null;
var minSqrDistance = Infinity;
for (var i = 0; i < n; i++) {
var p = new Point(points[i]);
var sqrDistance = this.squaredDistance(p);
if (sqrDistance < minSqrDistance) {
closest = p;
minSqrDistance = sqrDistance;
}
}
return closest;
},
// If point lies outside rectangle `r`, return the nearest point on the boundary of rect `r`,
// otherwise return point itself.
// (see Squeak Smalltalk, Point>>adhereTo:)
adhereToRect: function(r) {
if (r.containsPoint(this)) {
return this;
}
this.x = min(max(this.x, r.x), r.x + r.width);
this.y = min(max(this.y, r.y), r.y + r.height);
return this;
},
// Compute the angle between vector from me to p1 and the vector from me to p2.
// ordering of points p1 and p2 is important!
// theta function's angle convention:
// returns angles between 0 and 180 when the angle is counterclockwise
// returns angles between 180 and 360 to convert clockwise angles into counterclockwise ones
// returns NaN if any of the points p1, p2 is coincident with this point
angleBetween: function(p1, p2) {
var angleBetween = (this.equals(p1) || this.equals(p2)) ? NaN : (this.theta(p2) - this.theta(p1));
if (angleBetween < 0) {
angleBetween += 360; // correction to keep angleBetween between 0 and 360
}
return angleBetween;
},
// Return the bearing between me and the given point.
bearing: function(point) {
return bearing(this, point);
},
// Returns change in angle from my previous position (-dx, -dy) to my new position
// relative to ref point.
changeInAngle: function(dx, dy, ref) {
// Revert the translation and measure the change in angle around x-axis.
return this.clone().offset(-dx, -dy).theta(ref) - this.theta(ref);
},
clone: function() {
return new Point(this);
},
// Returns the cross product of this point relative to two other points
// this point is the common point
// point p1 lies on the first vector, point p2 lies on the second vector
// watch out for the ordering of points p1 and p2!
// positive result indicates a clockwise ("right") turn from first to second vector
// negative result indicates a counterclockwise ("left") turn from first to second vector
// zero indicates that the first and second vector are collinear
// note that the above directions are reversed from the usual answer on the Internet
// that is because we are in a left-handed coord system (because the y-axis points downward)
cross: function(p1, p2) {
return (p1 && p2) ? (((p2.x - this.x) * (p1.y - this.y)) - ((p2.y - this.y) * (p1.x - this.x))) : NaN;
},
difference: function(dx, dy) {
if ((Object(dx) === dx)) {
dy = dx.y;
dx = dx.x;
}
return new Point(this.x - (dx || 0), this.y - (dy || 0));
},
// Returns distance between me and point `p`.
distance: function(p) {
return length(this, p);
},
// Returns the dot product of this point with given other point
dot: function(p) {
return p ? (this.x * p.x + this.y * p.y) : NaN;
},
equals: function(p) {
return !!p &&
this.x === p.x &&
this.y === p.y;
},
// Linear interpolation
lerp: function(p, t) {
var x = this.x;
var y = this.y;
return new Point((1 - t) * x + t * p.x, (1 - t) * y + t * p.y);
},
magnitude: function() {
return sqrt((this.x * this.x) + (this.y * this.y)) || 0.01;
},
// Returns a manhattan (taxi-cab) distance between me and point `p`.
manhattanDistance: function(p) {
return abs(p.x - this.x) + abs(p.y - this.y);
},
// Move point on line starting from ref ending at me by
// distance distance.
move: function(ref, distance) {
var theta = toRad((new Point(ref)).theta(this));
var offset = this.offset(cos$1(theta) * distance, -sin$1(theta) * distance);
return offset;
},
// Scales x and y such that the distance between the point and the origin (0,0) is equal to the given length.
normalize: function(length) {
var scale = (length || 1) / this.magnitude();
return this.scale(scale, scale);
},
// Offset me by the specified amount.
offset: function(dx, dy) {
if ((Object(dx) === dx)) {
dy = dx.y;
dx = dx.x;
}
this.x += dx || 0;
this.y += dy || 0;
return this;
},
// Returns a point that is the reflection of me with
// the center of inversion in ref point.
reflection: function(ref) {
return (new Point(ref)).move(this, this.distance(ref));
},
// Rotate point by angle around origin.
// Angle is flipped because this is a left-handed coord system (y-axis points downward).
rotate: function(origin, angle) {
if (angle === 0) { return this; }
origin = origin || new Point(0, 0);
angle = toRad(normalizeAngle(-angle));
var cosAngle = cos$1(angle);
var sinAngle = sin$1(angle);
var x = (cosAngle * (this.x - origin.x)) - (sinAngle * (this.y - origin.y)) + origin.x;
var y = (sinAngle * (this.x - origin.x)) + (cosAngle * (this.y - origin.y)) + origin.y;
this.x = x;
this.y = y;
return this;
},
round: function(precision) {
var f = 1; // case 0
if (precision) {
switch (precision) {
case 1: f = 10; break;
case 2: f = 100; break;
case 3: f = 1000; break;
default: f = pow(10, precision); break;
}
}
this.x = round$1(this.x * f) / f;
this.y = round$1(this.y * f) / f;
return this;
},
// Scale point with origin.
scale: function(sx, sy, origin) {
origin = (origin && new Point(origin)) || new Point(0, 0);
this.x = origin.x + sx * (this.x - origin.x);
this.y = origin.y + sy * (this.y - origin.y);
return this;
},
snapToGrid: function(gx, gy) {
this.x = snapToGrid(this.x, gx);
this.y = snapToGrid(this.y, gy || gx);
return this;
},
squaredDistance: function(p) {
return squaredLength(this, p);
},
// Compute the angle between me and `p` and the x axis.
// (cartesian-to-polar coordinates conversion)
// Return theta angle in degrees.
theta: function(p) {
p = new Point(p);
// Invert the y-axis.
var y = -(p.y - this.y);
var x = p.x - this.x;
var rad = atan2$1(y, x); // defined for all 0 corner cases
// Correction for III. and IV. quadrant.
if (rad < 0) {
rad = 2 * PI$1 + rad;
}
return 180 * rad / PI$1;
},
toJSON: function() {
return { x: this.x, y: this.y };
},
// Converts rectangular to polar coordinates.
// An origin can be specified, otherwise it's 0@0.
toPolar: function(o) {
o = (o && new Point(o)) || new Point(0, 0);
var x = this.x;
var y = this.y;
this.x = sqrt((x - o.x) * (x - o.x) + (y - o.y) * (y - o.y)); // r
this.y = toRad(o.theta(new Point(x, y)));
return this;
},
toString: function() {
return this.x + '@' + this.y;
},
serialize: function() {
return this.x + ',' + this.y;
},
update: function(x, y) {
if ((Object(x) === x)) {
y = x.y;
x = x.x;
}
this.x = x || 0;
this.y = y || 0;
return this;
},
// Compute the angle between the vector from 0,0 to me and the vector from 0,0 to p.
// Returns NaN if p is at 0,0.
vectorAngle: function(p) {
var zero = new Point(0, 0);
return zero.angleBetween(this, p);
}
};
Point.prototype.translate = Point.prototype.offset;
// For backwards compatibility:
var point = Point;
var max$1 = Math.max;
var min$1 = Math.min;
var Line = function(p1, p2) {
if (!(this instanceof Line)) {
return new Line(p1, p2);
}
if (p1 instanceof Line) {
return new Line(p1.start, p1.end);
}
this.start = new Point(p1);
this.end = new Point(p2);
};
Line.prototype = {
// @returns the angle of incline of the line.
angle: function() {
var horizontalPoint = new Point(this.start.x + 1, this.start.y);
return this.start.angleBetween(this.end, horizontalPoint);
},
bbox: function() {
var left = min$1(this.start.x, this.end.x);
var top = min$1(this.start.y, this.end.y);
var right = max$1(this.start.x, this.end.x);
var bottom = max$1(this.start.y, this.end.y);
return new Rect(left, top, (right - left), (bottom - top));
},
// @return the bearing (cardinal direction) of the line. For example N, W, or SE.
// @returns {String} One of the following bearings : NE, E, SE, S, SW, W, NW, N.
bearing: function() {
return bearing(this.start, this.end);
},
clone: function() {
return new Line(this.start, this.end);
},
// @return {point} the closest point on the line to point `p`
closestPoint: function(p) {
return this.pointAt(this.closestPointNormalizedLength(p));
},
closestPointLength: function(p) {
return this.closestPointNormalizedLength(p) * this.length();
},
// @return {number} the normalized length of the closest point on the line to point `p`
closestPointNormalizedLength: function(p) {
var product = this.vector().dot((new Line(this.start, p)).vector());
var cpNormalizedLength = min$1(1, max$1(0, product / this.squaredLength()));
// cpNormalizedLength returns `NaN` if this line has zero length
// we can work with that - if `NaN`, return 0
if (cpNormalizedLength !== cpNormalizedLength) { return 0; } // condition evaluates to `true` if and only if cpNormalizedLength is `NaN`
// (`NaN` is the only value that is not equal to itself)
return cpNormalizedLength;
},
closestPointTangent: function(p) {
return this.tangentAt(this.closestPointNormalizedLength(p));
},
// Returns `true` if the point lies on the line.
containsPoint: function(p) {
var start = this.start;
var end = this.end;
if (start.cross(p, end) !== 0) { return false; }
// else: cross product of 0 indicates that this line and the vector to `p` are collinear
var length = this.length();
if ((new Line(start, p)).length() > length) { return false; }
if ((new Line(p, end)).length() > length) { return false; }
// else: `p` lies between start and end of the line
return true;
},
// Divides the line into two at requested `ratio` between 0 and 1.
divideAt: function(ratio) {
var dividerPoint = this.pointAt(ratio);
// return array with two lines
return [
new Line(this.start, dividerPoint),
new Line(dividerPoint, this.end)
];
},
// Divides the line into two at requested `length`.
divideAtLength: function(length) {
var dividerPoint = this.pointAtLength(length);
// return array with two new lines
return [
new Line(this.start, dividerPoint),
new Line(dividerPoint, this.end)
];
},
equals: function(l) {
return !!l &&
this.start.x === l.start.x &&
this.start.y === l.start.y &&
this.end.x === l.end.x &&
this.end.y === l.end.y;
},
// @return {point} Point where I'm intersecting a line.
// @return [point] Points where I'm intersecting a rectangle.
// @see Squeak Smalltalk, LineSegment>>intersectionWith:
intersect: function(shape, opt) {
if (shape && shape.intersectionWithLine) {
var intersection = shape.intersectionWithLine(this, opt);
// Backwards compatibility
if (intersection && (shape instanceof Line)) {
intersection = intersection[0];
}
return intersection;
}
return null;
},
intersectionWithLine: function(line) {
var pt1Dir = new Point(this.end.x - this.start.x, this.end.y - this.start.y);
var pt2Dir = new Point(line.end.x - line.start.x, line.end.y - line.start.y);
var det = (pt1Dir.x * pt2Dir.y) - (pt1Dir.y * pt2Dir.x);
var deltaPt = new Point(line.start.x - this.start.x, line.start.y - this.start.y);
var alpha = (deltaPt.x * pt2Dir.y) - (deltaPt.y * pt2Dir.x);
var beta = (deltaPt.x * pt1Dir.y) - (deltaPt.y * pt1Dir.x);
if (det === 0 || alpha * det < 0 || beta * det < 0) {
// No intersection found.
return null;
}
if (det > 0) {
if (alpha > det || beta > det) {
return null;
}
} else {
if (alpha < det || beta < det) {
return null;
}
}
return [new Point(
this.start.x + (alpha * pt1Dir.x / det),
this.start.y + (alpha * pt1Dir.y / det)
)];
},
isDifferentiable: function() {
return !this.start.equals(this.end);
},
// @return {double} length of the line
length: function() {
return length(this.start, this.end);
},
// @return {point} my midpoint
midpoint: function() {
return new Point(
(this.start.x + this.end.x) / 2,
(this.start.y + this.end.y) / 2
);
},
parallel: function(distance) {
var l = this.clone();
if (!this.isDifferentiable()) { return l; }
var start = l.start;
var end = l.end;
var eRef = start.clone().rotate(end, 270);
var sRef = end.clone().rotate(start, 90);
start.move(sRef, distance);
end.move(eRef, distance);
return l;
},
// @return {point} my point at 't' <0,1>
pointAt: function(t) {
var start = this.start;
var end = this.end;
if (t <= 0) { return start.clone(); }
if (t >= 1) { return end.clone(); }
return start.lerp(end, t);
},
pointAtLength: function(length) {
var start = this.start;
var end = this.end;
var fromStart = true;
if (length < 0) {
fromStart = false; // negative lengths mean start calculation from end point
length = -length; // absolute value
}
var lineLength = this.length();
if (length >= lineLength) { return (fromStart ? end.clone() : start.clone()); }
return this.pointAt((fromStart ? (length) : (lineLength - length)) / lineLength);
},
// @return {number} the offset of the point `p` from the line. + if the point `p` is on the right side of the line, - if on the left and 0 if on the line.
pointOffset: function(p) {
// Find the sign of the determinant of vectors (start,end), where p is the query point.
p = new Point(p);
var start = this.start;
var end = this.end;
var determinant = ((end.x - start.x) * (p.y - start.y) - (end.y - start.y) * (p.x - start.x));
return determinant / this.length();
},
rotate: function(origin, angle) {
this.start.rotate(origin, angle);
this.end.rotate(origin, angle);
return this;
},
round: function(precision) {
this.start.round(precision);
this.end.round(precision);
return this;
},
scale: function(sx, sy, origin) {
this.start.scale(sx, sy, origin);
this.end.scale(sx, sy, origin);
return this;
},
// @return {number} scale the line so that it has the requested length
setLength: function(length) {
var currentLength = this.length();
if (!currentLength) { return this; }
var scaleFactor = length / currentLength;
return this.scale(scaleFactor, scaleFactor, this.start);
},
// @return {integer} length without sqrt
// @note for applications where the exact length is not necessary (e.g. compare only)
squaredLength: function() {
return squaredLength(this.start, this.end);
},
tangentAt: function(t) {
if (!this.isDifferentiable()) { return null; }
var start = this.start;
var end = this.end;
var tangentStart = this.pointAt(t); // constrains `t` between 0 and 1
var tangentLine = new Line(start, end);
tangentLine.translate(tangentStart.x - start.x, tangentStart.y - start.y); // move so that tangent line starts at the point requested
return tangentLine;
},
tangentAtLength: function(length) {
if (!this.isDifferentiable()) { return null; }
var start = this.start;
var end = this.end;
var tangentStart = this.pointAtLength(length);
var tangentLine = new Line(start, end);
tangentLine.translate(tangentStart.x - start.x, tangentStart.y - start.y); // move so that tangent line starts at the point requested
return tangentLine;
},
toString: function() {
return this.start.toString() + ' ' + this.end.toString();
},
serialize: function() {
return this.start.serialize() + ' ' + this.end.serialize();
},
translate: function(tx, ty) {
this.start.translate(tx, ty);
this.end.translate(tx, ty);
return this;
},
// @return vector {point} of the line
vector: function() {
return new Point(this.end.x - this.start.x, this.end.y - this.start.y);
}
};
// For backwards compatibility:
Line.prototype.intersection = Line.prototype.intersect;
// For backwards compatibility:
var line = Line;
var sqrt$1 = Math.sqrt;
var round$2 = Math.round;
var pow$1 = Math.pow;
var Ellipse = function(c, a, b) {
if (!(this instanceof Ellipse)) {
return new Ellipse(c, a, b);
}
if (c instanceof Ellipse) {
return new Ellipse(new Point(c.x, c.y), c.a, c.b);
}
c = new Point(c);
this.x = c.x;
this.y = c.y;
this.a = a;
this.b = b;
};
Ellipse.fromRect = function(rect) {
rect = new Rect(rect);
return new Ellipse(rect.center(), rect.width / 2, rect.height / 2);
};
Ellipse.prototype = {
bbox: function() {
return new Rect(this.x - this.a, this.y - this.b, 2 * this.a, 2 * this.b);
},
/**
* @returns {g.Point}
*/
center: function() {
return new Point(this.x, this.y);
},
clone: function() {
return new Ellipse(this);
},
/**
* @param {g.Point} p
* @returns {boolean}
*/
containsPoint: function(p) {
return this.normalizedDistance(p) <= 1;
},
equals: function(ellipse) {
return !!ellipse &&
ellipse.x === this.x &&
ellipse.y === this.y &&
ellipse.a === this.a &&
ellipse.b === this.b;
},
// inflate by dx and dy
// @param dx {delta_x} representing additional size to x
// @param dy {delta_y} representing additional size to y -
// dy param is not required -> in that case y is sized by dx
inflate: function(dx, dy) {
if (dx === undefined) {
dx = 0;
}
if (dy === undefined) {
dy = dx;
}
this.a += 2 * dx;
this.b += 2 * dy;
return this;
},
intersectionWithLine: function(line) {
var intersections = [];
var a1 = line.start;
var a2 = line.end;
var rx = this.a;
var ry = this.b;
var dir = line.vector();
var diff = a1.difference(new Point(this));
var mDir = new Point(dir.x / (rx * rx), dir.y / (ry * ry));
var mDiff = new Point(diff.x / (rx * rx), diff.y / (ry * ry));
var a = dir.dot(mDir);
var b = dir.dot(mDiff);
var c = diff.dot(mDiff) - 1.0;
var d = b * b - a * c;
if (d < 0) {
return null;
} else if (d > 0) {
var root = sqrt$1(d);
var ta = (-b - root) / a;
var tb = (-b + root) / a;
if ((ta < 0 || 1 < ta) && (tb < 0 || 1 < tb)) {
// if ((ta < 0 && tb < 0) || (ta > 1 && tb > 1)) outside else inside
return null;
} else {
if (0 <= ta && ta <= 1) { intersections.push(a1.lerp(a2, ta)); }
if (0 <= tb && tb <= 1) { intersections.push(a1.lerp(a2, tb)); }
}
} else {
var t = -b / a;
if (0 <= t && t <= 1) {
intersections.push(a1.lerp(a2, t));
} else {
// outside
return null;
}
}
return intersections;
},
// Find point on me where line from my center to
// point p intersects my boundary.
// @param {number} angle If angle is specified, intersection with rotated ellipse is computed.
intersectionWithLineFromCenterToPoint: function(p, angle) {
p = new Point(p);
if (angle) { p.rotate(new Point(this.x, this.y), angle); }
var dx = p.x - this.x;
var dy = p.y - this.y;
var result;
if (dx === 0) {
result = this.bbox().pointNearestToPoint(p);
if (angle) { return result.rotate(new Point(this.x, this.y), -angle); }
return result;
}
var m = dy / dx;
var mSquared = m * m;
var aSquared = this.a * this.a;
var bSquared = this.b * this.b;
var x = sqrt$1(1 / ((1 / aSquared) + (mSquared / bSquared)));
x = dx < 0 ? -x : x;
var y = m * x;
result = new Point(this.x + x, this.y + y);
if (angle) { return result.rotate(new Point(this.x, this.y), -angle); }
return result;
},
/**
* @param {g.Point} point
* @returns {number} result < 1 - inside ellipse, result == 1 - on ellipse boundary, result > 1 - outside
*/
normalizedDistance: function(point) {
var x0 = point.x;
var y0 = point.y;
var a = this.a;
var b = this.b;
var x = this.x;
var y = this.y;
return ((x0 - x) * (x0 - x)) / (a * a) + ((y0 - y) * (y0 - y)) / (b * b);
},
round: function(precision) {
var f = 1; // case 0
if (precision) {
switch (precision) {
case 1: f = 10; break;
case 2: f = 100; break;
case 3: f = 1000; break;
default: f = pow$1(10, precision); break;
}
}
this.x = round$2(this.x * f) / f;
this.y = round$2(this.y * f) / f;
this.a = round$2(this.a * f) / f;
this.b = round$2(this.b * f) / f;
return this;
},
/** Compute angle between tangent and x axis
* @param {g.Point} p Point of tangency, it has to be on ellipse boundaries.
* @returns {number} angle between tangent and x axis
*/
tangentTheta: function(p) {
var refPointDelta = 30;
var x0 = p.x;
var y0 = p.y;
var a = this.a;
var b = this.b;
var center = this.bbox().center();
var m = center.x;
var n = center.y;
var q1 = x0 > center.x + a / 2;
var q3 = x0 < center.x - a / 2;
var y, x;
if (q1 || q3) {
y = x0 > center.x ? y0 - refPointDelta : y0 + refPointDelta;
x = (a * a / (x0 - m)) - (a * a * (y0 - n) * (y - n)) / (b * b * (x0 - m)) + m;
} else {
x = y0 > center.y ? x0 + refPointDelta : x0 - refPointDelta;
y = (b * b / (y0 - n)) - (b * b * (x0 - m) * (x - m)) / (a * a * (y0 - n)) + n;
}
return (new Point(x, y)).theta(p);
},
toString: function() {
return (new Point(this.x, this.y)).toString() + ' ' + this.a + ' ' + this.b;
}
};
// For backwards compatibility:
var ellipse = Ellipse;
var abs$1 = Math.abs;
var cos$2 = Math.cos;
var sin$2 = Math.sin;
var min$2 = Math.min;
var max$2 = Math.max;
var round$3 = Math.round;
var pow$2 = Math.pow;
var Rect = function(x, y, w, h) {
if (!(this instanceof Rect)) {
return new Rect(x, y, w, h);
}
if ((Object(x) === x)) {
y = x.y;
w = x.width;
h = x.height;
x = x.x;
}
this.x = x === undefined ? 0 : x;
this.y = y === undefined ? 0 : y;
this.width = w === undefined ? 0 : w;
this.height = h === undefined ? 0 : h;
};
Rect.fromEllipse = function(e) {
e = new Ellipse(e);
return new Rect(e.x - e.a, e.y - e.b, 2 * e.a, 2 * e.b);
};
Rect.fromPointUnion = function() {
var points = [], len = arguments.length;
while ( len-- ) points[ len ] = arguments[ len ];
if (points.length === 0) { return null; }
var p = new Point();
var minX, minY, maxX, maxY;
minX = minY = Infinity;
maxX = maxY = -Infinity;
for (var i = 0; i < points.length; i++) {
p.update(points[i]);
var x = p.x;
var y = p.y;
if (x < minX) { minX = x; }
if (x > maxX) { maxX = x; }
if (y < minY) { minY = y; }
if (y > maxY) { maxY = y; }
}
return new Rect(minX, minY, maxX - minX, maxY - minY);
};
Rect.fromRectUnion = function() {
var rects = [], len = arguments.length;
while ( len-- ) rects[ len ] = arguments[ len ];
if (rects.length === 0) { return null; }
var r = new Rect();
var minX, minY, maxX, maxY;
minX = minY = Infinity;
maxX = maxY = -Infinity;
for (var i = 0; i < rects.length; i++) {
r.update(rects[i]);
var x = r.x;
var y = r.y;
var mX = x + r.width;
var mY = y + r.height;
if (x < minX) { minX = x; }
if (mX > maxX) { maxX = mX; }
if (y < minY) { minY = y; }
if (mY > maxY) { maxY = mY; }
}
return new Rect(minX, minY, maxX - minX, maxY - minY);
};
Rect.prototype = {
// Find my bounding box when I'm rotated with the center of rotation in the center of me.
// @return r {rectangle} representing a bounding box
bbox: function(angle) {
if (!angle) { return this.clone(); }
var theta = toRad(angle);
var st = abs$1(sin$2(theta));
var ct = abs$1(cos$2(theta));
var w = this.width * ct + this.height * st;
var h = this.width * st + this.height * ct;
return new Rect(this.x + (this.width - w) / 2, this.y + (this.height - h) / 2, w, h);
},
bottomLeft: function() {
return new Point(this.x, this.y + this.height);
},
bottomLine: function() {
return new Line(this.bottomLeft(), this.bottomRight());
},
bottomMiddle: function() {
return new Point(this.x + this.width / 2, this.y + this.height);
},
center: function() {
return new Point(this.x + this.width / 2, this.y + this.height / 2);
},
clone: function() {
return new Rect(this);
},
// @return {bool} true if point p is inside me.
containsPoint: function(p) {
p = new Point(p);
return p.x >= this.x && p.x <= this.x + this.width && p.y >= this.y && p.y <= this.y + this.height;
},
// @return {bool} true if rectangle `r` is inside me.
containsRect: function(r) {
var r0 = new Rect(this).normalize();
var r1 = new Rect(r).normalize();
var w0 = r0.width;
var h0 = r0.height;
var w1 = r1.width;
var h1 = r1.height;
if (!w0 || !h0 || !w1 || !h1) {
// At least one of the dimensions is 0
return false;
}
var x0 = r0.x;
var y0 = r0.y;
var x1 = r1.x;
var y1 = r1.y;
w1 += x1;
w0 += x0;
h1 += y1;
h0 += y0;
return x0 <= x1 && w1 <= w0 && y0 <= y1 && h1 <= h0;
},
corner: function() {
return new Point(this.x + this.width, this.y + this.height);
},
// @return {boolean} true if rectangles are equal.
equals: function(r) {
var mr = (new Rect(this)).normalize();
var nr = (new Rect(r)).normalize();
return mr.x === nr.x && mr.y === nr.y && mr.width === nr.width && mr.height === nr.height;
},
// inflate by dx and dy, recompute origin [x, y]
// @param dx {delta_x} representing additional size to x
// @param dy {delta_y} representing additional size to y -
// dy param is not required -> in that case y is sized by dx
inflate: function(dx, dy) {
if (dx === undefined) {
dx = 0;
}
if (dy === undefined) {
dy = dx;
}
this.x -= dx;
this.y -= dy;
this.width += 2 * dx;
this.height += 2 * dy;
return this;
},
// @return {rect} if rectangles intersect, {null} if not.
intersect: function(r) {
var myOrigin = this.origin();
var myCorner = this.corner();
var rOrigin = r.origin();
var rCorner = r.corner();
// No intersection found
if (rCorner.x <= myOrigin.x ||
rCorner.y <= myOrigin.y ||
rOrigin.x >= myCorner.x ||
rOrigin.y >= myCorner.y) { return null; }
var x = max$2(myOrigin.x, rOrigin.x);
var y = max$2(myOrigin.y, rOrigin.y);
return new Rect(x, y, min$2(myCorner.x, rCorner.x) - x, min$2(myCorner.y, rCorner.y) - y);
},
intersectionWithLine: function(line) {
var r = this;
var rectLines = [r.topLine(), r.rightLine(), r.bottomLine(), r.leftLine()];
var points = [];
var dedupeArr = [];
var pt, i;
var n = rectLines.length;
for (i = 0; i < n; i++) {
pt = line.intersect(rectLines[i]);
if (pt !== null && dedupeArr.indexOf(pt.toString()) < 0) {
points.push(pt);
dedupeArr.push(pt.toString());
}
}
return points.length > 0 ? points : null;
},
// Find point on my boundary where line starting
// from my center ending in point p intersects me.
// @param {number} angle If angle is specified, intersection with rotated rectangle is computed.
intersectionWithLineFromCenterToPoint: function(p, angle) {
p = new Point(p);
var center = new Point(this.x + this.width / 2, this.y + this.height / 2);
var result;
if (angle) { p.rotate(center, angle); }
// (clockwise, starting from the top side)
var sides = [
this.topLine(),
this.rightLine(),
this.bottomLine(),
this.leftLine()
];
var connector = new Line(center, p);
for (var i = sides.length - 1; i >= 0; --i) {
var intersection = sides[i].intersection(connector);
if (intersection !== null) {
result = intersection;
break;
}
}
if (result && angle) { result.rotate(center, -angle); }
return result;
},
leftLine: function() {
return new Line(this.topLeft(), this.bottomLeft());
},
leftMiddle: function() {
return new Point(this.x, this.y + this.height / 2);
},
maxRectScaleToFit: function(rect, origin) {
rect = new Rect(rect);
origin || (origin = rect.center());
var sx1, sx2, sx3, sx4, sy1, sy2, sy3, sy4;
var ox = origin.x;
var oy = origin.y;
// Here we find the maximal possible scale for all corner points (for x and y axis) of the rectangle,
// so when the scale is applied the point is still inside the rectangle.
sx1 = sx2 = sx3 = sx4 = sy1 = sy2 = sy3 = sy4 = Infinity;
// Top Left
var p1 = rect.topLeft();
if (p1.x < ox) {
sx1 = (this.x - ox) / (p1.x - ox);
}
if (p1.y < oy) {
sy1 = (this.y - oy) / (p1.y - oy);
}
// Bottom Right
var p2 = rect.bottomRight();
if (p2.x > ox) {
sx2 = (this.x + this.width - ox) / (p2.x - ox);
}
if (p2.y > oy) {
sy2 = (this.y + this.height - oy) / (p2.y - oy);
}
// Top Right
var p3 = rect.topRight();
if (p3.x > ox) {
sx3 = (this.x + this.width - ox) / (p3.x - ox);
}
if (p3.y < oy) {
sy3 = (this.y - oy) / (p3.y - oy);
}
// Bottom Left
var p4 = rect.bottomLeft();
if (p4.x < ox) {
sx4 = (this.x - ox) / (p4.x - ox);
}
if (p4.y > oy) {
sy4 = (this.y + this.height - oy) / (p4.y - oy);
}
return {
sx: min$2(sx1, sx2, sx3, sx4),
sy: min$2(sy1, sy2, sy3, sy4)
};
},
maxRectUniformScaleToFit: function(rect, origin) {
var scale = this.maxRectScaleToFit(rect, origin);
return min$2(scale.sx, scale.sy);
},
// Move and expand me.
// @param r {rectangle} representing deltas
moveAndExpand: function(r) {
this.x += r.x || 0;
this.y += r.y || 0;
this.width += r.width || 0;
this.height += r.height || 0;
return this;
},
// Normalize the rectangle; i.e., make it so that it has a non-negative width and height.
// If width < 0 the function swaps the left and right corners,
// and it swaps the top and bottom corners if height < 0
// like in http://qt-project.org/doc/qt-4.8/qrectf.html#normalized
normalize: function() {
var newx = this.x;
var newy = this.y;
var newwidth = this.width;
var newheight = this.height;
if (this.width < 0) {
newx = this.x + this.width;
newwidth = -this.width;
}
if (this.height < 0) {
newy = this.y + this.height;
newheight = -this.height;
}
this.x = newx;
this.y = newy;
this.width = newwidth;
this.height = newheight;
return this;
},
// Offset me by the specified amount.
offset: function(dx, dy) {
// pretend that this is a point and call offset()
// rewrites x and y according to dx and dy
return Point.prototype.offset.call(this, dx, dy);
},
origin: function() {
return new Point(this.x, this.y);
},
// @return {point} a point on my boundary nearest to the given point.
// @see Squeak Smalltalk, Rectangle>>pointNearestTo:
pointNearestToPoint: function(point) {
point = new Point(point);
if (this.containsPoint(point)) {
var side = this.sideNearestToPoint(point);
switch (side) {
case 'right':
return new Point(this.x + this.width, point.y);
case 'left':
return new Point(this.x, point.y);
case 'bottom':
return new Point(point.x, this.y + this.height);
case 'top':
return new Point(point.x, this.y);
}
}
return point.adhereToRect(this);
},
rightLine: function() {
return new Line(this.topRight(), this.bottomRight());
},
rightMiddle: function() {
return new Point(this.x + this.width, this.y + this.height / 2);
},
round: function(precision) {
var f = 1; // case 0
if (precision) {
switch (precision) {
case 1: f = 10; break;
case 2: f = 100; break;
case 3: f = 1000; break;
default: f = pow$2(10, precision); break;
}
}
this.x = round$3(this.x * f) / f;
this.y = round$3(this.y * f) / f;
this.width = round$3(this.width * f) / f;
this.height = round$3(this.height * f) / f;
return this;
},
// Scale rectangle with origin.
scale: function(sx, sy, origin) {
origin = this.origin().scale(sx, sy, origin);
this.x = origin.x;
this.y = origin.y;
this.width *= sx;
this.height *= sy;
return this;
},
// @return {string} (left|right|top|bottom) side which is nearest to point
// @see Squeak Smalltalk, Rectangle>>sideNearestTo:
sideNearestToPoint: function(point) {
point = new Point(point);
var distToLeft = point.x - this.x;
var distToRight = (this.x + this.width) - point.x;
var distToTop = point.y - this.y;
var distToBottom = (this.y + this.height) - point.y;
var closest = distToLeft;
var side = 'left';
if (distToRight < closest) {
closest = distToRight;
side = 'right';
}
if (distToTop < closest) {
closest = distToTop;
side = 'top';
}
if (distToBottom < closest) {
// closest = distToBottom;
side = 'bottom';
}
return side;
},
snapToGrid: function(gx, gy) {
var origin = this.origin().snapToGrid(gx, gy);
var corner = this.corner().snapToGrid(gx, gy);
this.x = origin.x;
this.y = origin.y;
this.width = corner.x - origin.x;
this.height = corner.y - origin.y;
return this;
},
toJSON: function() {
return { x: this.x, y: this.y, width: this.width, height: this.height };
},
topLine: function() {
return new Line(this.topLeft(), this.topRight());
},
topMiddle: function() {
return new Point(this.x + this.width / 2, this.y);
},
topRight: function() {
return new Point(this.x + this.width, this.y);
},
toString: function() {
return this.origin().toString() + ' ' + this.corner().toString();
},
// @return {rect} representing the union of both rectangles.
union: function(rect) {
return Rect.fromRectUnion(this, rect);
},
update: function(x, y, w, h) {
if ((Object(x) === x)) {
y = x.y;
w = x.width;
h = x.height;
x = x.x;
}
this.x = x || 0;
this.y = y || 0;
this.width = w || 0;
this.height = h || 0;
return this;
}
};
Rect.prototype.bottomRight = Rect.prototype.corner;
Rect.prototype.topLeft = Rect.prototype.origin;
Rect.prototype.translate = Rect.prototype.offset;
// For backwards compatibility:
var rect = Rect;
var abs$2 = Math.abs;
var Polyline = function(points) {
if (!(this instanceof Polyline)) {
return new Polyline(points);
}
if (typeof points === 'string') {
return new Polyline.parse(points);
}
this.points = (Array.isArray(points) ? points.map(Point) : []);
};
Polyline.parse = function(svgString) {
svgString = svgString.trim();
if (svgString === '') { return new Polyline(); }
var points = [];
var coords = svgString.split(/\s*,\s*|\s+/);
var n = coords.length;
for (var i = 0; i < n; i += 2) {
points.push({ x: +coords[i], y: +coords[i + 1] });
}
return new Polyline(points);
};
Polyline.prototype = {
bbox: function() {
var x1 = Infinity;
var x2 = -Infinity;
var y1 = Infinity;
var y2 = -Infinity;
var points = this.points;
var numPoints = points.length;
if (numPoints === 0) { return null; } // if points array is empty
for (var i = 0; i < numPoints; i++) {
var point = points[i];
var x = point.x;
var y = point.y;
if (x < x1) { x1 = x; }
if (x > x2) { x2 = x; }
if (y < y1) { y1 = y; }
if (y > y2) { y2 = y; }
}
return new Rect(x1, y1, x2 - x1, y2 - y1);
},
clone: function() {
var points = this.points;
var numPoints = points.length;
if (numPoints === 0) { return new Polyline(); } // if points array is empty
var newPoints = [];
for (var i = 0; i < numPoints; i++) {
var point = points[i].clone();
newPoints.push(point);
}
return new Polyline(newPoints);
},
closestPoint: function(p) {
var cpLength = this.closestPointLength(p);
return this.pointAtLength(cpLength);
},
closestPointLength: function(p) {
var points = this.points;
var numPoints = points.length;
if (numPoints === 0) { return 0; } // if points array is empty
if (numPoints === 1) { return 0; } // if there is only one point
var cpLength;
var minSqrDistance = Infinity;
var length = 0;
var n = numPoints - 1;
for (var i = 0; i < n; i++) {
var line = new Line(points[i], points[i + 1]);
var lineLength = line.length();
var cpNormalizedLength = line.closestPointNormalizedLength(p);
var cp = line.pointAt(cpNormalizedLength);
var sqrDistance = cp.squaredDistance(p);
if (sqrDistance < minSqrDistance) {
minSqrDistance = sqrDistance;
cpLength = length + (cpNormalizedLength * lineLength);
}
length += lineLength;
}
return cpLength;
},
closestPointNormalizedLength: function(p) {
var cpLength = this.closestPointLength(p);
if (cpLength === 0) { return 0; } // shortcut
var length = this.length();
if (length === 0) { return 0; } // prevents division by zero
return cpLength / length;
},
closestPointTangent: function(p) {
var cpLength = this.closestPointLength(p);
return this.tangentAtLength(cpLength);
},
// Returns `true` if the area surrounded by the polyline contains the point `p`.
// Implements the even-odd SVG algorithm (self-intersections are "outside").
// (Uses horizontal rays to the right of `p` to look for intersections.)
// Closes open polylines (always imagines a final closing segment).
containsPoint: function(p) {
var points = this.points;
var numPoints = points.length;
if (numPoints === 0) { return false; } // shortcut (this polyline has no points)
var x = p.x;
var y = p.y;
// initialize a final closing segment by creating one from last-first points on polyline
var startIndex = numPoints - 1; // start of current polyline segment
var endIndex = 0; // end of current polyline segment
var numIntersections = 0;
for (; endIndex < numPoints; endIndex++) {
var start = points[startIndex];
var end = points[endIndex];
if (p.equals(start)) { return true; } // shortcut (`p` is a point on polyline)
var segment = new Line(start, end); // current polyline segment
if (segment.containsPoint(p)) { return true; } // shortcut (`p` lies on a polyline segment)
// do we have an intersection?
if (((y <= start.y) && (y > end.y)) || ((y > start.y) && (y <= end.y))) {
// this conditional branch IS NOT entered when `segment` is collinear/coincident with `ray`
// (when `y === start.y === end.y`)
// this conditional branch IS entered when `segment` touches `ray` at only one point
// (e.g. when `y === start.y !== end.y`)
// since this branch is entered again for the following segment, the two touches cancel out
var xDifference = (((start.x - x) > (end.x - x)) ? (start.x - x) : (end.x - x));
if (xDifference >= 0) {
// segment lies at least partially to the right of `p`
var rayEnd = new Point((x + xDifference), y); // right
var ray = new Line(p, rayEnd);
if (segment.intersect(ray)) {
// an intersection was detected to the right of `p`
numIntersections++;
}
} // else: `segment` lies completely to the left of `p` (i.e. no intersection to the right)
}
// move to check the next polyline segment
startIndex = endIndex;
}
// returns `true` for odd numbers of intersections (even-odd algorithm)
return ((numIntersections % 2) === 1);
},
// Returns a convex-hull polyline from this polyline.
// Implements the Graham scan (https://en.wikipedia.org/wiki/Graham_scan).
// Output polyline starts at the first element of the original polyline that is on the hull, then continues clockwise.
// Minimal polyline is found (only vertices of the hull are reported, no collinear points).
convexHull: function() {
var i;
var n;
var points = this.points;
var numPoints = points.length;
if (numPoints === 0) { return new Polyline(); } // if points array is empty
// step 1: find the starting point - point with the lowest y (if equality, highest x)
var startPoint;
for (i = 0; i < numPoints; i++) {
if (startPoint === undefined) {
// if this is the first point we see, set it as start point
startPoint = points[i];
} else if (points[i].y < startPoint.y) {
// start point should have lowest y from all points
startPoint = points[i];
} else if ((points[i].y === startPoint.y) && (points[i].x > startPoint.x)) {
// if two points have the lowest y, choose the one that has highest x
// there are no points to the right of startPoint - no ambiguity about theta 0
// if there are several coincident start point candidates, first one is reported
startPoint = points[i];
}
}
// step 2: sort the list of points
// sorting by angle between line from startPoint to point and the x-axis (theta)
// step 2a: create the point records = [point, originalIndex, angle]
var sortedPointRecords = [];
for (i = 0; i < numPoints; i++) {
var angle = startPoint.theta(points[i]);
if (angle === 0) {
angle = 360; // give highest angle to start point
// the start point will end up at end of sorted list
// the start point will end up at beginning of hull points list
}
var entry = [points[i], i, angle];
sortedPointRecords.push(entry);
}
// step 2b: sort the list in place
sortedPointRecords.sort(function(record1, record2) {
// returning a negative number here sorts record1 before record2
// if first angle is smaller than second, first angle should come before second
var sortOutput = record1[2] - record2[2]; // negative if first angle smaller
if (sortOutput === 0) {
// if the two angles are equal, sort by originalIndex
sortOutput = record2[1] - record1[1]; // negative if first index larger
// coincident points will be sorted in reverse-numerical order
// so the coincident points with lower original index will be considered first
}
return sortOutput;
});
// step 2c: duplicate start record from the top of the stack to the bottom of the stack
if (sortedPointRecords.length > 2) {
var startPointRecord = sortedPointRecords[sortedPointRecords.length - 1];
sortedPointRecords.unshift(startPointRecord);
}
// step 3a: go through sorted points in order and find those with right turns
// we want to get our results in clockwise order
var insidePoints = {}; // dictionary of points with left turns - cannot be on the hull
var hullPointRecords = []; // stack of records with right turns - hull point candidates
var currentPointRecord;
var currentPoint;
var lastHullPointRecord;
var lastHullPoint;
var secondLastHullPointRecord;
var secondLastHullPoint;
while (sortedPointRecords.length !== 0) {
currentPointRecord = sortedPointRecords.pop();
currentPoint = currentPointRecord[0];
// check if point has already been discarded
// keys for insidePoints are stored in the form 'point.x@point.y@@originalIndex'
if (insidePoints.hasOwnProperty(currentPointRecord[0] + '@@' + currentPointRecord[1])) {
// this point had an incorrect turn at some previous iteration of this loop
// this disqualifies it from possibly being on the hull
continue;
}
var correctTurnFound = false;
while (!correctTurnFound) {
if (hullPointRecords.length < 2) {
// not enough points for comparison, just add current point
hullPointRecords.push(currentPointRecord);
correctTurnFound = true;
} else {
lastHullPointRecord = hullPointRecords.pop();
lastHullPoint = lastHullPointRecord[0];
secondLastHullPointRecord = hullPointRecords.pop();
secondLastHullPoint = secondLastHullPointRecord[0];
var crossProduct = secondLastHullPoint.cross(lastHullPoint, currentPoint);
if (crossProduct < 0) {
// found a right turn
hullPointRecords.push(secondLastHullPointRecord);
hullPointRecords.push(lastHullPointRecord);
hullPointRecords.push(currentPointRecord);
correctTurnFound = true;
} else if (crossProduct === 0) {
// the three points are collinear
// three options:
// there may be a 180 or 0 degree angle at lastHullPoint
// or two of the three points are coincident
var THRESHOLD = 1e-10; // we have to take rounding errors into account
var angleBetween = lastHullPoint.angleBetween(secondLastHullPoint, currentPoint);
if (abs$2(angleBetween - 180) < THRESHOLD) { // rouding around 180 to 180
// if the cross product is 0 because the angle is 180 degrees
// discard last hull point (add to insidePoints)
//insidePoints.unshift(lastHullPoint);
insidePoints[lastHullPointRecord[0] + '@@' + lastHullPointRecord[1]] = lastHullPoint;
// reenter second-to-last hull point (will be last at next iter)
hullPointRecords.push(secondLastHullPointRecord);
// do not do anything with current point
// correct turn not found
} else if (lastHullPoint.equals(currentPoint) || secondLastHullPoint.equals(lastHullPoint)) {
// if the cross product is 0 because two points are the same
// discard last hull point (add to insidePoints)
//insidePoints.unshift(lastHullPoint);
insidePoints[lastHullPointRecord[0] + '@@' + lastHullPointRecord[1]] = lastHullPoint;
// reenter second-to-last hull point (will be last at next iter)
hullPointRecords.push(secondLastHullPointRecord);
// do not do anything with current point
// correct turn not found
} else if (abs$2(((angleBetween + 1) % 360) - 1) < THRESHOLD) { // rounding around 0 and 360 to 0
// if the cross product is 0 because the angle is 0 degrees
// remove last hull point from hull BUT do not discard it
// reenter second-to-last hull point (will be last at next iter)
hullPointRecords.push(secondLastHullPointRecord);
// put last hull point back into the sorted point records list
sortedPointRecords.push(lastHullPointRecord);
// we are switching the order of the 0deg and 180deg points
// correct turn not found
}
} else {
// found a left turn
// discard last hull point (add to insidePoints)
//insidePoints.unshift(lastHullPoint);
insidePoints[lastHullPointRecord[0] + '@@' + lastHullPointRecord[1]] = lastHullPoint;
// reenter second-to-last hull point (will be last at next iter of loop)
hullPointRecords.push(secondLastHullPointRecord);
// do not do anything with current point
// correct turn not found
}
}
}
}
// at this point, hullPointRecords contains the output points in clockwise order
// the points start with lowest-y,highest-x startPoint, and end at the same point
// step 3b: remove duplicated startPointRecord from the end of the array
if (hullPointRecords.length > 2) {
hullPointRecords.pop();
}
// step 4: find the lowest originalIndex record and put it at the beginning of hull
var lowestHullIndex; // the lowest originalIndex on the hull
var indexOfLowestHullIndexRecord = -1; // the index of the record with lowestHullIndex
n = hullPointRecords.length;
for (i = 0; i < n; i++) {
var currentHullIndex = hullPointRecords[i][1];
if (lowestHullIndex === undefined || currentHullIndex < lowestHullIndex) {
lowestHullIndex = currentHullIndex;
indexOfLowestHullIndexRecord = i;
}
}
var hullPointRecordsReordered = [];
if (indexOfLowestHullIndexRecord > 0) {
var newFirstChunk = hullPointRecords.slice(indexOfLowestHullIndexRecord);
var newSecondChunk = hullPointRecords.slice(0, indexOfLowestHullIndexRecord);
hullPointRecordsReordered = newFirstChunk.concat(newSecondChunk);
} else {
hullPointRecordsReordered = hullPointRecords;
}
var hullPoints = [];
n = hullPointRecordsReordered.length;
for (i = 0; i < n; i++) {
hullPoints.push(hullPointRecordsReordered[i][0]);
}
return new Polyline(hullPoints);
},
// Checks whether two polylines are exactly the same.
// If `p` is undefined or null, returns false.
equals: function(p) {
if (!p) { return false; }
var points = this.points;
var otherPoints = p.points;
var numPoints = points.length;
if (otherPoints.length !== numPoints) { return false; } // if the two polylines have different number of points, they cannot be equal
for (var i = 0; i < numPoints; i++) {
var point = points[i];
var otherPoint = p.points[i];
// as soon as an inequality is found in points, return false
if (!point.equals(otherPoint)) { return false; }
}
// if no inequality found in points, return true
return true;
},
intersectionWithLine: function(l) {
var line = new Line(l);
var intersections = [];
var points = this.points;
for (var i = 0, n = points.length - 1; i < n; i++) {
var a = points[i];
var b = points[i + 1];
var l2 = new Line(a, b);
var int = line.intersectionWithLine(l2);
if (int) { intersections.push(int[0]); }
}
return (intersections.length > 0) ? intersections : null;
},
isDifferentiable: function() {
var points = this.points;
var numPoints = points.length;
if (numPoints === 0) { return false; }
var n = numPoints - 1;
for (var i = 0; i < n; i++) {
var a = points[i];
var b = points[i + 1];
var line = new Line(a, b);
// as soon as a differentiable line is found between two points, return true
if (line.isDifferentiable()) { return true; }
}
// if no differentiable line is found between pairs of points, return false
return false;
},
length: function() {
var points = this.points;
var numPoints = points.length;
if (numPoints === 0) { return 0; } // if points array is empty
var length = 0;
var n = numPoints - 1;
for (var i = 0; i < n; i++) {
length += points[i].distance(points[i + 1]);
}
return length;
},
pointAt: function(ratio) {
var points = this.points;
var numPoints = points.length;
if (numPoints === 0) { return null; } // if points array is empty
if (numPoints === 1) { return points[0].clone(); } // if there is only one point
if (ratio <= 0) { return points[0].clone(); }
if (ratio >= 1) { return points[numPoints - 1].clone(); }
var polylineLength = this.length();
var length = polylineLength * ratio;
return this.pointAtLength(length);
},
pointAtLength: function(length) {
var points = this.points;
var numPoints = points.length;
if (numPoints === 0) { return null; } // if points array is empty
if (numPoints === 1) { return points[0].clone(); } // if there is only one point
var fromStart = true;
if (length < 0) {
fromStart = false; // negative lengths mean start calculation from end point
length = -length; // absolute value
}
var l = 0;
var n = numPoints - 1;
for (var i = 0; i < n; i++) {
var index = (fromStart ? i : (n - 1 - i));
var a = points[index];
var b = points[index + 1];
var line = new Line(a, b);
var d = a.distance(b);
if (length <= (l + d)) {
return line.pointAtLength((fromStart ? 1 : -1) * (length - l));
}
l += d;
}
// if length requested is higher than the length of the polyline, return last endpoint
var lastPoint = (fromStart ? points[numPoints - 1] : points[0]);
return lastPoint.clone();
},
round: function(precision) {
var points = this.points;
var numPoints = points.length;
for (var i = 0; i < numPoints; i++) {
points[i].round(precision);
}
return this;
},
scale: function(sx, sy, origin) {
var points = this.points;
var numPoints = points.length;
for (var i = 0; i < numPoints; i++) {
points[i].scale(sx, sy, origin);
}
return this;
},
simplify: function(opt) {
if ( opt === void 0 ) opt = {};
var points = this.points;
if (points.length < 3) { return this; } // we need at least 3 points
// TODO: we may also accept startIndex and endIndex to specify where to start and end simplification
var threshold = opt.threshold || 0; // = max distance of middle point from chord to be simplified
// start at the beginning of the polyline and go forward
var currentIndex = 0;
// we need at least one intermediate point (3 points) in every iteration
// as soon as that stops being true, we know we reached the end of the polyline
while (points[currentIndex + 2]) {
var firstIndex = currentIndex;
var middleIndex = (currentIndex + 1);
var lastIndex = (currentIndex + 2);
var firstPoint = points[firstIndex];
var middlePoint = points[middleIndex];
var lastPoint = points[lastIndex];
var chord = new Line(firstPoint, lastPoint); // = connection between first and last point
var closestPoint = chord.closestPoint(middlePoint); // = closest point on chord from middle point
var closestPointDistance = closestPoint.distance(middlePoint);
if (closestPointDistance <= threshold) {
// middle point is close enough to the chord = simplify
// 1) remove middle point:
points.splice(middleIndex, 1);
// 2) in next iteration, investigate the newly-created triplet of points
// - do not change `currentIndex`
// = (first point stays, point after removed point becomes middle point)
} else {
// middle point is far from the chord
// 1) preserve middle point
// 2) in next iteration, move `currentIndex` by one step:
currentIndex += 1;
// = (point after first point becomes first point)
}
}
// `points` array was modified in-place
return this;
},
tangentAt: function(ratio) {
var points = this.points;
var numPoints = points.length;
if (numPoints === 0) { return null; } // if points array is empty
if (numPoints === 1) { return null; } // if there is only one point
if (ratio < 0) { ratio = 0; }
if (ratio > 1) { ratio = 1; }
var polylineLength = this.length();
var length = polylineLength * ratio;
return this.tangentAtLength(length);
},
tangentAtLength: function(length) {
var points = this.points;
var numPoints = points.length;
if (numPoints === 0) { return null; } // if points array is empty
if (numPoints === 1) { return null; } // if there is only one point
var fromStart = true;
if (length < 0) {
fromStart = false; // negative lengths mean start calculation from end point
length = -length; // absolute value
}
var lastValidLine; // differentiable (with a tangent)
var l = 0; // length so far
var n = numPoints - 1;
for (var i = 0; i < n; i++) {
var index = (fromStart ? i : (n - 1 - i));
var a = points[index];
var b = points[index + 1];
var line = new Line(a, b);
var d = a.distance(b);
if (line.isDifferentiable()) { // has a tangent line (line length is not 0)
if (length <= (l + d)) {
return line.tangentAtLength((fromStart ? 1 : -1) * (length - l));
}
lastValidLine = line;
}
l += d;
}
// if length requested is higher than the length of the polyline, return last valid endpoint
if (lastValidLine) {
var ratio = (fromStart ? 1 : 0);
return lastValidLine.tangentAt(ratio);
}
// if no valid line, return null
return null;
},
toString: function() {
return this.points + '';
},
translate: function(tx, ty) {
var points = this.points;
var numPoints = points.length;
for (var i = 0; i < numPoints; i++) {
points[i].translate(tx, ty);
}
return this;
},
// Return svgString that can be used to recreate this line.
serialize: function() {
var points = this.points;
var numPoints = points.length;
if (numPoints === 0) { return ''; } // if points array is empty
var output = '';
for (var i = 0; i < numPoints; i++) {
var point = points[i];
output += point.x + ',' + point.y + ' ';
}
return output.trim();
}
};
Object.defineProperty(Polyline.prototype, 'start', {
// Getter for the first point of the polyline.
configurable: true,
enumerable: true,
get: function() {
var points = this.points;
var numPoints = points.length;
if (numPoints === 0) { return null; } // if points array is empty
return this.points[0];
},
});
Object.defineProperty(Polyline.prototype, 'end', {
// Getter for the last point of the polyline.
configurable: true,
enumerable: true,
get: function() {
var points = this.points;
var numPoints = points.length;
if (numPoints === 0) { return null; } // if points array is empty
return this.points[numPoints - 1];
},
});
var abs$3 = Math.abs;
var sqrt$2 = Math.sqrt;
var min$3 = Math.min;
var max$3 = Math.max;
var pow$3 = Math.pow;
var Curve = function(p1, p2, p3, p4) {
if (!(this instanceof Curve)) {
return new Curve(p1, p2, p3, p4);
}
if (p1 instanceof Curve) {
return new Curve(p1.start, p1.controlPoint1, p1.controlPoint2, p1.end);
}
this.start = new Point(p1);
this.controlPoint1 = new Point(p2);
this.controlPoint2 = new Point(p3);
this.end = new Point(p4);
};
// Curve passing through points.
// Ported from C# implementation by Oleg V. Polikarpotchkin and Peter Lee (http://www.codeproject.com/KB/graphics/BezierSpline.aspx).
// @param {array} points Array of points through which the smooth line will go.
// @return {array} curves.
Curve.throughPoints = (function() {
// Get open-ended Bezier Spline Control Points.
// @param knots Input Knot Bezier spline points (At least two points!).
// @param firstControlPoints Output First Control points. Array of knots.length - 1 length.
// @param secondControlPoints Output Second Control points. Array of knots.length - 1 length.
function getCurveControlPoints(knots) {
var firstControlPoints = [];
var secondControlPoints = [];
var n = knots.length - 1;
var i;
// Special case: Bezier curve should be a straight line.
if (n == 1) {
// 3P1 = 2P0 + P3
firstControlPoints[0] = new Point(
(2 * knots[0].x + knots[1].x) / 3,
(2 * knots[0].y + knots[1].y) / 3
);
// P2 = 2P1 – P0
secondControlPoints[0] = new Point(
2 * firstControlPoints[0].x - knots[0].x,
2 * firstControlPoints[0].y - knots[0].y
);
return [firstControlPoints, secondControlPoints];
}
// Calculate first Bezier control points.
// Right hand side vector.
var rhs = [];
// Set right hand side X values.
for (i = 1; i < n - 1; i++) {
rhs[i] = 4 * knots[i].x + 2 * knots[i + 1].x;
}
rhs[0] = knots[0].x + 2 * knots[1].x;
rhs[n - 1] = (8 * knots[n - 1].x + knots[n].x) / 2.0;
// Get first control points X-values.
var x = getFirstControlPoints(rhs);
// Set right hand side Y values.
for (i = 1; i < n - 1; ++i) {
rhs[i] = 4 * knots[i].y + 2 * knots[i + 1].y;
}
rhs[0] = knots[0].y + 2 * knots[1].y;
rhs[n - 1] = (8 * knots[n - 1].y + knots[n].y) / 2.0;
// Get first control points Y-values.
var y = getFirstControlPoints(rhs);
// Fill output arrays.
for (i = 0; i < n; i++) {
// First control point.
firstControlPoints.push(new Point(x[i], y[i]));
// Second control point.
if (i < n - 1) {
secondControlPoints.push(new Point(
2 * knots [i + 1].x - x[i + 1],
2 * knots[i + 1].y - y[i + 1]
));
} else {
secondControlPoints.push(new Point(
(knots[n].x + x[n - 1]) / 2,
(knots[n].y + y[n - 1]) / 2
));
}
}
return [firstControlPoints, secondControlPoints];
}
// Solves a tridiagonal system for one of coordinates (x or y) of first Bezier control points.
// @param rhs Right hand side vector.
// @return Solution vector.
function getFirstControlPoints(rhs) {
var n = rhs.length;
// `x` is a solution vector.
var x = [];
var tmp = [];
var b = 2.0;
x[0] = rhs[0] / b;
// Decomposition and forward substitution.
for (var i = 1; i < n; i++) {
tmp[i] = 1 / b;
b = (i < n - 1 ? 4.0 : 3.5) - tmp[i];
x[i] = (rhs[i] - x[i - 1]) / b;
}
for (i = 1; i < n; i++) {
// Backsubstitution.
x[n - i - 1] -= tmp[n - i] * x[n - i];
}
return x;
}
return function(points) {
if (!points || (Array.isArray(points) && points.length < 2)) {
throw new Error('At least 2 points are required');
}
var controlPoints = getCurveControlPoints(points);
var curves = [];
var n = controlPoints[0].length;
for (var i = 0; i < n; i++) {
var controlPoint1 = new Point(controlPoints[0][i].x, controlPoints[0][i].y);
var controlPoint2 = new Point(controlPoints[1][i].x, controlPoints[1][i].y);
curves.push(new Curve(points[i], controlPoint1, controlPoint2, points[i + 1]));
}
return curves;
};
})();
Curve.prototype = {
// Returns a bbox that tightly envelops the curve.
bbox: function() {
var start = this.start;
var controlPoint1 = this.controlPoint1;
var controlPoint2 = this.controlPoint2;
var end = this.end;
var x0 = start.x;
var y0 = start.y;
var x1 = controlPoint1.x;
var y1 = controlPoint1.y;
var x2 = controlPoint2.x;
var y2 = controlPoint2.y;
var x3 = end.x;
var y3 = end.y;
var points = new Array(); // local extremes
var tvalues = new Array(); // t values of local extremes
var bounds = [new Array(), new Array()];
var a, b, c, t;
var t1, t2;
var b2ac, sqrtb2ac;
for (var i = 0; i < 2; ++i) {
if (i === 0) {
b = 6 * x0 - 12 * x1 + 6 * x2;
a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
c = 3 * x1 - 3 * x0;
} else {
b = 6 * y0 - 12 * y1 + 6 * y2;
a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
c = 3 * y1 - 3 * y0;
}
if (abs$3(a) < 1e-12) { // Numerical robustness
if (abs$3(b) < 1e-12) { // Numerical robustness
continue;
}
t = -c / b;
if ((0 < t) && (t < 1)) { tvalues.push(t); }
continue;
}
b2ac = b * b - 4 * c * a;
sqrtb2ac = sqrt$2(b2ac);
if (b2ac < 0) { continue; }
t1 = (-b + sqrtb2ac) / (2 * a);
if ((0 < t1) && (t1 < 1)) { tvalues.push(t1); }
t2 = (-b - sqrtb2ac) / (2 * a);
if ((0 < t2) && (t2 < 1)) { tvalues.push(t2); }
}
var j = tvalues.length;
var jlen = j;
var mt;
var x, y;
while (j--) {
t = tvalues[j];
mt = 1 - t;
x = (mt * mt * mt * x0) + (3 * mt * mt * t * x1) + (3 * mt * t * t * x2) + (t * t * t * x3);
bounds[0][j] = x;
y = (mt * mt * mt * y0) + (3 * mt * mt * t * y1) + (3 * mt * t * t * y2) + (t * t * t * y3);
bounds[1][j] = y;
points[j] = { X: x, Y: y };
}
tvalues[jlen] = 0;
tvalues[jlen + 1] = 1;
points[jlen] = { X: x0, Y: y0 };
points[jlen + 1] = { X: x3, Y: y3 };
bounds[0][jlen] = x0;
bounds[1][jlen] = y0;
bounds[0][jlen + 1] = x3;
bounds[1][jlen + 1] = y3;
tvalues.length = jlen + 2;
bounds[0].length = jlen + 2;
bounds[1].length = jlen + 2;
points.length = jlen + 2;
var left = min$3.apply(null, bounds[0]);
var top = min$3.apply(null, bounds[1]);
var right = max$3.apply(null, bounds[0]);
var bottom = max$3.apply(null, bounds[1]);
return new Rect(left, top, (right - left), (bottom - top));
},
clone: function() {
return new Curve(this.start, this.controlPoint1, this.controlPoint2, this.end);
},
// Returns the point on the curve closest to point `p`
closestPoint: function(p, opt) {
return this.pointAtT(this.closestPointT(p, opt));
},
closestPointLength: function(p, opt) {
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
var subdivisions = (opt.subdivisions === undefined) ? this.getSubdivisions({ precision: precision }) : opt.subdivisions;
var localOpt = { precision: precision, subdivisions: subdivisions };
return this.lengthAtT(this.closestPointT(p, localOpt), localOpt);
},
closestPointNormalizedLength: function(p, opt) {
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
var subdivisions = (opt.subdivisions === undefined) ? this.getSubdivisions({ precision: precision }) : opt.subdivisions;
var localOpt = { precision: precision, subdivisions: subdivisions };
var cpLength = this.closestPointLength(p, localOpt);
if (!cpLength) { return 0; }
var length = this.length(localOpt);
if (length === 0) { return 0; }
return cpLength / length;
},
// Returns `t` of the point on the curve closest to point `p`
closestPointT: function(p, opt) {
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
var subdivisions = (opt.subdivisions === undefined) ? this.getSubdivisions({ precision: precision }) : opt.subdivisions;
// does not use localOpt
// identify the subdivision that contains the point:
var investigatedSubdivision;
var investigatedSubdivisionStartT; // assume that subdivisions are evenly spaced
var investigatedSubdivisionEndT;
var distFromStart; // distance of point from start of baseline
var distFromEnd; // distance of point from end of baseline
var chordLength; // distance between start and end of the subdivision
var minSumDist; // lowest observed sum of the two distances
var n = subdivisions.length;
var subdivisionSize = (n ? (1 / n) : 0);
for (var i = 0; i < n; i++) {
var currentSubdivision = subdivisions[i];
var startDist = currentSubdivision.start.distance(p);
var endDist = currentSubdivision.end.distance(p);
var sumDist = startDist + endDist;
// check that the point is closest to current subdivision and not any other
if (!minSumDist || (sumDist < minSumDist)) {
investigatedSubdivision = currentSubdivision;
investigatedSubdivisionStartT = i * subdivisionSize;
investigatedSubdivisionEndT = (i + 1) * subdivisionSize;
distFromStart = startDist;
distFromEnd = endDist;
chordLength = currentSubdivision.start.distance(currentSubdivision.end);
minSumDist = sumDist;
}
}
var precisionRatio = pow$3(10, -precision);
// recursively divide investigated subdivision:
// until distance between baselinePoint and closest path endpoint is within 10^(-precision)
// then return the closest endpoint of that final subdivision
while (true) {
// check if we have reached at least one required observed precision
// - calculated as: the difference in distances from point to start and end divided by the distance
// - note that this function is not monotonic = it doesn't converge stably but has "teeth"
// - the function decreases while one of the endpoints is fixed but "jumps" whenever we switch
// - this criterion works well for points lying far away from the curve
var startPrecisionRatio = (distFromStart ? (abs$3(distFromStart - distFromEnd) / distFromStart) : 0);
var endPrecisionRatio = (distFromEnd ? (abs$3(distFromStart - distFromEnd) / distFromEnd) : 0);
var hasRequiredPrecision = ((startPrecisionRatio < precisionRatio) || (endPrecisionRatio < precisionRatio));
// check if we have reached at least one required minimal distance
// - calculated as: the subdivision chord length multiplied by precisionRatio
// - calculation is relative so it will work for arbitrarily large/small curves and their subdivisions
// - this is a backup criterion that works well for points lying "almost at" the curve
var hasMinimalStartDistance = (distFromStart ? (distFromStart < (chordLength * precisionRatio)) : true);
var hasMinimalEndDistance = (distFromEnd ? (distFromEnd < (chordLength * precisionRatio)) : true);
var hasMinimalDistance = (hasMinimalStartDistance || hasMinimalEndDistance);
// do we stop now?
if (hasRequiredPrecision || hasMinimalDistance) {
return ((distFromStart <= distFromEnd) ? investigatedSubdivisionStartT : investigatedSubdivisionEndT);
}
// otherwise, set up for next iteration
var divided = investigatedSubdivision.divide(0.5);
subdivisionSize /= 2;
var startDist1 = divided[0].start.distance(p);
var endDist1 = divided[0].end.distance(p);
var sumDist1 = startDist1 + endDist1;
var startDist2 = divided[1].start.distance(p);
var endDist2 = divided[1].end.distance(p);
var sumDist2 = startDist2 + endDist2;
if (sumDist1 <= sumDist2) {
investigatedSubdivision = divided[0];
investigatedSubdivisionEndT -= subdivisionSize; // subdivisionSize was already halved
distFromStart = startDist1;
distFromEnd = endDist1;
} else {
investigatedSubdivision = divided[1];
investigatedSubdivisionStartT += subdivisionSize; // subdivisionSize was already halved
distFromStart = startDist2;
distFromEnd = endDist2;
}
}
},
closestPointTangent: function(p, opt) {
return this.tangentAtT(this.closestPointT(p, opt));
},
// Returns `true` if the area surrounded by the curve contains the point `p`.
// Implements the even-odd algorithm (self-intersections are "outside").
// Closes open curves (always imagines a closing segment).
// Precision may be adjusted by passing an `opt` object.
containsPoint: function(p, opt) {
var polyline = this.toPolyline(opt);
return polyline.containsPoint(p);
},
// Divides the curve into two at requested `ratio` between 0 and 1 with precision better than `opt.precision`; optionally using `opt.subdivisions` provided.
// For a function that uses `t`, use Curve.divideAtT().
divideAt: function(ratio, opt) {
if (ratio <= 0) { return this.divideAtT(0); }
if (ratio >= 1) { return this.divideAtT(1); }
var t = this.tAt(ratio, opt);
return this.divideAtT(t);
},
// Divides the curve into two at requested `length` with precision better than requested `opt.precision`; optionally using `opt.subdivisions` provided.
divideAtLength: function(length, opt) {
var t = this.tAtLength(length, opt);
return this.divideAtT(t);
},
// Divides the curve into two at point defined by `t` between 0 and 1.
// Using de Casteljau's algorithm (http://math.stackexchange.com/a/317867).
// Additional resource: https://pomax.github.io/bezierinfo/#decasteljau
divideAtT: function(t) {
var start = this.start;
var controlPoint1 = this.controlPoint1;
var controlPoint2 = this.controlPoint2;
var end = this.end;
// shortcuts for `t` values that are out of range
if (t <= 0) {
return [
new Curve(start, start, start, start),
new Curve(start, controlPoint1, controlPoint2, end)
];
}
if (t >= 1) {
return [
new Curve(start, controlPoint1, controlPoint2, end),
new Curve(end, end, end, end)
];
}
var dividerPoints = this.getSkeletonPoints(t);
var startControl1 = dividerPoints.startControlPoint1;
var startControl2 = dividerPoints.startControlPoint2;
var divider = dividerPoints.divider;
var dividerControl1 = dividerPoints.dividerControlPoint1;
var dividerControl2 = dividerPoints.dividerControlPoint2;
// return array with two new curves
return [
new Curve(start, startControl1, startControl2, divider),
new Curve(divider, dividerControl1, dividerControl2, end)
];
},
// Returns the distance between the curve's start and end points.
endpointDistance: function() {
return this.start.distance(this.end);
},
// Checks whether two curves are exactly the same.
equals: function(c) {
return !!c &&
this.start.x === c.start.x &&
this.start.y === c.start.y &&
this.controlPoint1.x === c.controlPoint1.x &&
this.controlPoint1.y === c.controlPoint1.y &&
this.controlPoint2.x === c.controlPoint2.x &&
this.controlPoint2.y === c.controlPoint2.y &&
this.end.x === c.end.x &&
this.end.y === c.end.y;
},
// Returns five helper points necessary for curve division.
getSkeletonPoints: function(t) {
var start = this.start;
var control1 = this.controlPoint1;
var control2 = this.controlPoint2;
var end = this.end;
// shortcuts for `t` values that are out of range
if (t <= 0) {
return {
startControlPoint1: start.clone(),
startControlPoint2: start.clone(),
divider: start.clone(),
dividerControlPoint1: control1.clone(),
dividerControlPoint2: control2.clone()
};
}
if (t >= 1) {
return {
startControlPoint1: control1.clone(),
startControlPoint2: control2.clone(),
divider: end.clone(),
dividerControlPoint1: end.clone(),
dividerControlPoint2: end.clone()
};
}
var midpoint1 = (new Line(start, control1)).pointAt(t);
var midpoint2 = (new Line(control1, control2)).pointAt(t);
var midpoint3 = (new Line(control2, end)).pointAt(t);
var subControl1 = (new Line(midpoint1, midpoint2)).pointAt(t);
var subControl2 = (new Line(midpoint2, midpoint3)).pointAt(t);
var divider = (new Line(subControl1, subControl2)).pointAt(t);
var output = {
startControlPoint1: midpoint1,
startControlPoint2: subControl1,
divider: divider,
dividerControlPoint1: subControl2,
dividerControlPoint2: midpoint3
};
return output;
},
// Returns a list of curves whose flattened length is better than `opt.precision`.
// That is, observed difference in length between recursions is less than 10^(-3) = 0.001 = 0.1%
// (Observed difference is not real precision, but close enough as long as special cases are covered)
// (That is why skipping iteration 1 is important)
// As a rule of thumb, increasing `precision` by 1 requires two more division operations
// - Precision 0 (endpointDistance) - total of 2^0 - 1 = 0 operations (1 subdivision)
// - Precision 1 (<10% error) - total of 2^2 - 1 = 3 operations (4 subdivisions)
// - Precision 2 (<1% error) - total of 2^4 - 1 = 15 operations requires 4 division operations on all elements (15 operations total) (16 subdivisions)
// - Precision 3 (<0.1% error) - total of 2^6 - 1 = 63 operations - acceptable when drawing (64 subdivisions)
// - Precision 4 (<0.01% error) - total of 2^8 - 1 = 255 operations - high resolution, can be used to interpolate `t` (256 subdivisions)
// (Variation of 1 recursion worse or better is possible depending on the curve, doubling/halving the number of operations accordingly)
getSubdivisions: function(opt) {
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
// not using opt.subdivisions
// not using localOpt
var subdivisions = [new Curve(this.start, this.controlPoint1, this.controlPoint2, this.end)];
if (precision === 0) { return subdivisions; }
var previousLength = this.endpointDistance();
var precisionRatio = pow$3(10, -precision);
// recursively divide curve at `t = 0.5`
// until the difference between observed length at subsequent iterations is lower than precision
var iteration = 0;
while (true) {
iteration += 1;
// divide all subdivisions
var newSubdivisions = [];
var numSubdivisions = subdivisions.length;
for (var i = 0; i < numSubdivisions; i++) {
var currentSubdivision = subdivisions[i];
var divided = currentSubdivision.divide(0.5); // dividing at t = 0.5 (not at middle length!)
newSubdivisions.push(divided[0], divided[1]);
}
// measure new length
var length = 0;
var numNewSubdivisions = newSubdivisions.length;
for (var j = 0; j < numNewSubdivisions; j++) {
var currentNewSubdivision = newSubdivisions[j];
length += currentNewSubdivision.endpointDistance();
}
// check if we have reached required observed precision
// sine-like curves may have the same observed length in iteration 0 and 1 - skip iteration 1
// not a problem for further iterations because cubic curves cannot have more than two local extrema
// (i.e. cubic curves cannot intersect the baseline more than once)
// therefore two subsequent iterations cannot produce sampling with equal length
var observedPrecisionRatio = ((length !== 0) ? ((length - previousLength) / length) : 0);
if (iteration > 1 && observedPrecisionRatio < precisionRatio) {
return newSubdivisions;
}
// otherwise, set up for next iteration
subdivisions = newSubdivisions;
previousLength = length;
}
},
isDifferentiable: function() {
var start = this.start;
var control1 = this.controlPoint1;
var control2 = this.controlPoint2;
var end = this.end;
return !(start.equals(control1) && control1.equals(control2) && control2.equals(end));
},
// Returns flattened length of the curve with precision better than `opt.precision`; or using `opt.subdivisions` provided.
length: function(opt) {
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; // opt.precision only used in getSubdivisions() call
var subdivisions = (opt.subdivisions === undefined) ? this.getSubdivisions({ precision: precision }) : opt.subdivisions;
// not using localOpt
var length = 0;
var n = subdivisions.length;
for (var i = 0; i < n; i++) {
var currentSubdivision = subdivisions[i];
length += currentSubdivision.endpointDistance();
}
return length;
},
// Returns distance along the curve up to `t` with precision better than requested `opt.precision`. (Not using `opt.subdivisions`.)
lengthAtT: function(t, opt) {
if (t <= 0) { return 0; }
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
// not using opt.subdivisions
// not using localOpt
var subCurve = this.divide(t)[0];
var subCurveLength = subCurve.length({ precision: precision });
return subCurveLength;
},
// Returns point at requested `ratio` between 0 and 1 with precision better than `opt.precision`; optionally using `opt.subdivisions` provided.
// Mirrors Line.pointAt() function.
// For a function that tracks `t`, use Curve.pointAtT().
pointAt: function(ratio, opt) {
if (ratio <= 0) { return this.start.clone(); }
if (ratio >= 1) { return this.end.clone(); }
var t = this.tAt(ratio, opt);
return this.pointAtT(t);
},
// Returns point at requested `length` with precision better than requested `opt.precision`; optionally using `opt.subdivisions` provided.
pointAtLength: function(length, opt) {
var t = this.tAtLength(length, opt);
return this.pointAtT(t);
},
// Returns the point at provided `t` between 0 and 1.
// `t` does not track distance along curve as it does in Line objects.
// Non-linear relationship, speeds up and slows down as curve warps!
// For linear length-based solution, use Curve.pointAt().
pointAtT: function(t) {
if (t <= 0) { return this.start.clone(); }
if (t >= 1) { return this.end.clone(); }
return this.getSkeletonPoints(t).divider;
},
// Default precision
PRECISION: 3,
round: function(precision) {
this.start.round(precision);
this.controlPoint1.round(precision);
this.controlPoint2.round(precision);
this.end.round(precision);
return this;
},
scale: function(sx, sy, origin) {
this.start.scale(sx, sy, origin);
this.controlPoint1.scale(sx, sy, origin);
this.controlPoint2.scale(sx, sy, origin);
this.end.scale(sx, sy, origin);
return this;
},
// Returns a tangent line at requested `ratio` with precision better than requested `opt.precision`; or using `opt.subdivisions` provided.
tangentAt: function(ratio, opt) {
if (!this.isDifferentiable()) { return null; }
if (ratio < 0) { ratio = 0; }
else if (ratio > 1) { ratio = 1; }
var t = this.tAt(ratio, opt);
return this.tangentAtT(t);
},
// Returns a tangent line at requested `length` with precision better than requested `opt.precision`; or using `opt.subdivisions` provided.
tangentAtLength: function(length, opt) {
if (!this.isDifferentiable()) { return null; }
var t = this.tAtLength(length, opt);
return this.tangentAtT(t);
},
// Returns a tangent line at requested `t`.
tangentAtT: function(t) {
if (!this.isDifferentiable()) { return null; }
if (t < 0) { t = 0; }
else if (t > 1) { t = 1; }
var skeletonPoints = this.getSkeletonPoints(t);
var p1 = skeletonPoints.startControlPoint2;
var p2 = skeletonPoints.dividerControlPoint1;
var tangentStart = skeletonPoints.divider;
var tangentLine = new Line(p1, p2);
tangentLine.translate(tangentStart.x - p1.x, tangentStart.y - p1.y); // move so that tangent line starts at the point requested
return tangentLine;
},
// Returns `t` at requested `ratio` with precision better than requested `opt.precision`; optionally using `opt.subdivisions` provided.
tAt: function(ratio, opt) {
if (ratio <= 0) { return 0; }
if (ratio >= 1) { return 1; }
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
var subdivisions = (opt.subdivisions === undefined) ? this.getSubdivisions({ precision: precision }) : opt.subdivisions;
var localOpt = { precision: precision, subdivisions: subdivisions };
var curveLength = this.length(localOpt);
var length = curveLength * ratio;
return this.tAtLength(length, localOpt);
},
// Returns `t` at requested `length` with precision better than requested `opt.precision`; optionally using `opt.subdivisions` provided.
// Uses `precision` to approximate length within `precision` (always underestimates)
// Then uses a binary search to find the `t` of a subdivision endpoint that is close (within `precision`) to the `length`, if the curve was as long as approximated
// As a rule of thumb, increasing `precision` by 1 causes the algorithm to go 2^(precision - 1) deeper
// - Precision 0 (chooses one of the two endpoints) - 0 levels
// - Precision 1 (chooses one of 5 points, <10% error) - 1 level
// - Precision 2 (<1% error) - 3 levels
// - Precision 3 (<0.1% error) - 7 levels
// - Precision 4 (<0.01% error) - 15 levels
tAtLength: function(length, opt) {
var fromStart = true;
if (length < 0) {
fromStart = false; // negative lengths mean start calculation from end point
length = -length; // absolute value
}
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
var subdivisions = (opt.subdivisions === undefined) ? this.getSubdivisions({ precision: precision }) : opt.subdivisions;
var localOpt = { precision: precision, subdivisions: subdivisions };
// identify the subdivision that contains the point at requested `length`:
var investigatedSubdivision;
var investigatedSubdivisionStartT; // assume that subdivisions are evenly spaced
var investigatedSubdivisionEndT;
//var baseline; // straightened version of subdivision to investigate
//var baselinePoint; // point on the baseline that is the requested distance away from start
var baselinePointDistFromStart; // distance of baselinePoint from start of baseline
var baselinePointDistFromEnd; // distance of baselinePoint from end of baseline
var l = 0; // length so far
var n = subdivisions.length;
var subdivisionSize = 1 / n;
for (var i = 0; i < n; i++) {
var index = (fromStart ? i : (n - 1 - i));
var currentSubdivision = subdivisions[i];
var d = currentSubdivision.endpointDistance(); // length of current subdivision
if (length <= (l + d)) {
investigatedSubdivision = currentSubdivision;
investigatedSubdivisionStartT = index * subdivisionSize;
investigatedSubdivisionEndT = (index + 1) * subdivisionSize;
baselinePointDistFromStart = (fromStart ? (length - l) : ((d + l) - length));
baselinePointDistFromEnd = (fromStart ? ((d + l) - length) : (length - l));
break;
}
l += d;
}
if (!investigatedSubdivision) { return (fromStart ? 1 : 0); } // length requested is out of range - return maximum t
// note that precision affects what length is recorded
// (imprecise measurements underestimate length by up to 10^(-precision) of the precise length)
// e.g. at precision 1, the length may be underestimated by up to 10% and cause this function to return 1
var curveLength = this.length(localOpt);
var precisionRatio = pow$3(10, -precision);
// recursively divide investigated subdivision:
// until distance between baselinePoint and closest path endpoint is within 10^(-precision)
// then return the closest endpoint of that final subdivision
while (true) {
// check if we have reached required observed precision
var observedPrecisionRatio;
observedPrecisionRatio = ((curveLength !== 0) ? (baselinePointDistFromStart / curveLength) : 0);
if (observedPrecisionRatio < precisionRatio) { return investigatedSubdivisionStartT; }
observedPrecisionRatio = ((curveLength !== 0) ? (baselinePointDistFromEnd / curveLength) : 0);
if (observedPrecisionRatio < precisionRatio) { return investigatedSubdivisionEndT; }
// otherwise, set up for next iteration
var newBaselinePointDistFromStart;
var newBaselinePointDistFromEnd;
var divided = investigatedSubdivision.divide(0.5);
subdivisionSize /= 2;
var baseline1Length = divided[0].endpointDistance();
var baseline2Length = divided[1].endpointDistance();
if (baselinePointDistFromStart <= baseline1Length) { // point at requested length is inside divided[0]
investigatedSubdivision = divided[0];
investigatedSubdivisionEndT -= subdivisionSize; // sudivisionSize was already halved
newBaselinePointDistFromStart = baselinePointDistFromStart;
newBaselinePointDistFromEnd = baseline1Length - newBaselinePointDistFromStart;
} else { // point at requested length is inside divided[1]
investigatedSubdivision = divided[1];
investigatedSubdivisionStartT += subdivisionSize; // subdivisionSize was already halved
newBaselinePointDistFromStart = baselinePointDistFromStart - baseline1Length;
newBaselinePointDistFromEnd = baseline2Length - newBaselinePointDistFromStart;
}
baselinePointDistFromStart = newBaselinePointDistFromStart;
baselinePointDistFromEnd = newBaselinePointDistFromEnd;
}
},
// Returns an array of points that represents the curve when flattened, up to `opt.precision`; or using `opt.subdivisions` provided.
// Flattened length is no more than 10^(-precision) away from real curve length.
toPoints: function(opt) {
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; // opt.precision only used in getSubdivisions() call
var subdivisions = (opt.subdivisions === undefined) ? this.getSubdivisions({ precision: precision }) : opt.subdivisions;
// not using localOpt
var points = [subdivisions[0].start.clone()];
var n = subdivisions.length;
for (var i = 0; i < n; i++) {
var currentSubdivision = subdivisions[i];
points.push(currentSubdivision.end.clone());
}
return points;
},
// Returns a polyline that represents the curve when flattened, up to `opt.precision`; or using `opt.subdivisions` provided.
// Flattened length is no more than 10^(-precision) away from real curve length.
toPolyline: function(opt) {
return new Polyline(this.toPoints(opt));
},
toString: function() {
return this.start + ' ' + this.controlPoint1 + ' ' + this.controlPoint2 + ' ' + this.end;
},
translate: function(tx, ty) {
this.start.translate(tx, ty);
this.controlPoint1.translate(tx, ty);
this.controlPoint2.translate(tx, ty);
this.end.translate(tx, ty);
return this;
}
};
Curve.prototype.divide = Curve.prototype.divideAtT;
// Accepts path data string, array of segments, array of Curves and/or Lines, or a Polyline.
var Path = function(arg) {
if (!(this instanceof Path)) {
return new Path(arg);
}
if (typeof arg === 'string') { // create from a path data string
return new Path.parse(arg);
}
this.segments = [];
var i;
var n;
if (!arg) ; else if (Array.isArray(arg) && arg.length !== 0) { // if arg is a non-empty array
// flatten one level deep
// so we can chain arbitrary Path.createSegment results
arg = arg.reduce(function(acc, val) {
return acc.concat(val);
}, []);
n = arg.length;
if (arg[0].isSegment) { // create from an array of segments
for (i = 0; i < n; i++) {
var segment = arg[i];
this.appendSegment(segment);
}
} else { // create from an array of Curves and/or Lines
var previousObj = null;
for (i = 0; i < n; i++) {
var obj = arg[i];
if (!((obj instanceof Line) || (obj instanceof Curve))) {
throw new Error('Cannot construct a path segment from the provided object.');
}
if (i === 0) { this.appendSegment(Path.createSegment('M', obj.start)); }
// if objects do not link up, moveto segments are inserted to cover the gaps
if (previousObj && !previousObj.end.equals(obj.start)) { this.appendSegment(Path.createSegment('M', obj.start)); }
if (obj instanceof Line) {
this.appendSegment(Path.createSegment('L', obj.end));
} else if (obj instanceof Curve) {
this.appendSegment(Path.createSegment('C', obj.controlPoint1, obj.controlPoint2, obj.end));
}
previousObj = obj;
}
}
} else if (arg.isSegment) { // create from a single segment
this.appendSegment(arg);
} else if (arg instanceof Line) { // create from a single Line
this.appendSegment(Path.createSegment('M', arg.start));
this.appendSegment(Path.createSegment('L', arg.end));
} else if (arg instanceof Curve) { // create from a single Curve
this.appendSegment(Path.createSegment('M', arg.start));
this.appendSegment(Path.createSegment('C', arg.controlPoint1, arg.controlPoint2, arg.end));
} else if (arg instanceof Polyline) { // create from a Polyline
if (!(arg.points && (arg.points.length !== 0))) { return; } // if Polyline has no points, leave Path empty
n = arg.points.length;
for (i = 0; i < n; i++) {
var point = arg.points[i];
if (i === 0) { this.appendSegment(Path.createSegment('M', point)); }
else { this.appendSegment(Path.createSegment('L', point)); }
}
} else { // unknown object
throw new Error('Cannot construct a path from the provided object.');
}
};
// More permissive than V.normalizePathData and Path.prototype.serialize.
// Allows path data strings that do not start with a Moveto command (unlike SVG specification).
// Does not require spaces between elements; commas are allowed, separators may be omitted when unambiguous (e.g. 'ZM10,10', 'L1.6.8', 'M100-200').
// Allows for command argument chaining.
// Throws an error if wrong number of arguments is provided with a command.
// Throws an error if an unrecognized path command is provided (according to Path.segmentTypes). Only a subset of SVG commands is currently supported (L, C, M, Z).
Path.parse = function(pathData) {
if (!pathData) { return new Path(); }
var path = new Path();
var commandRe = /(?:[a-zA-Z] *)(?:(?:-?\d+(?:\.\d+)?(?:e[-+]?\d+)? *,? *)|(?:-?\.\d+ *,? *))+|(?:[a-zA-Z] *)(?! |\d|-|\.)/g;
var commands = pathData.match(commandRe);
var numCommands = commands.length;
for (var i = 0; i < numCommands; i++) {
var command = commands[i];
var argRe = /(?:[a-zA-Z])|(?:(?:-?\d+(?:\.\d+)?(?:e[-+]?\d+)?))|(?:(?:-?\.\d+))/g;
var args = command.match(argRe);
var segment = Path.createSegment.apply(this, args); // args = [type, coordinate1, coordinate2...]
path.appendSegment(segment);
}
return path;
};
// Create a segment or an array of segments.
// Accepts unlimited points/coords arguments after `type`.
Path.createSegment = function(type) {
var arguments$1 = arguments;
if (!type) { throw new Error('Type must be provided.'); }
var segmentConstructor = Path.segmentTypes[type];
if (!segmentConstructor) { throw new Error(type + ' is not a recognized path segment type.'); }
var args = [];
var n = arguments.length;
for (var i = 1; i < n; i++) { // do not add first element (`type`) to args array
args.push(arguments$1[i]);
}
return applyToNew(segmentConstructor, args);
};
Path.prototype = {
// Accepts one segment or an array of segments as argument.
// Throws an error if argument is not a segment or an array of segments.
appendSegment: function(arg) {
var segments = this.segments;
var numSegments = segments.length;
// works even if path has no segments
var currentSegment;
var previousSegment = ((numSegments !== 0) ? segments[numSegments - 1] : null); // if we are appending to an empty path, previousSegment is null
var nextSegment = null;
if (!Array.isArray(arg)) { // arg is a segment
if (!arg || !arg.isSegment) { throw new Error('Segment required.'); }
currentSegment = this.prepareSegment(arg, previousSegment, nextSegment);
segments.push(currentSegment);
} else { // arg is an array of segments
// flatten one level deep
// so we can chain arbitrary Path.createSegment results
arg = arg.reduce(function(acc, val) {
return acc.concat(val);
}, []);
if (!arg[0].isSegment) { throw new Error('Segments required.'); }
var n = arg.length;
for (var i = 0; i < n; i++) {
var currentArg = arg[i];
currentSegment = this.prepareSegment(currentArg, previousSegment, nextSegment);
segments.push(currentSegment);
previousSegment = currentSegment;
}
}
},
// Returns the bbox of the path.
// If path has no segments, returns null.
// If path has only invisible segments, returns bbox of the end point of last segment.
bbox: function() {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) { return null; } // if segments is an empty array
var bbox;
for (var i = 0; i < numSegments; i++) {
var segment = segments[i];
if (segment.isVisible) {
var segmentBBox = segment.bbox();
bbox = bbox ? bbox.union(segmentBBox) : segmentBBox;
}
}
if (bbox) { return bbox; }
// if the path has only invisible elements, return end point of last segment
var lastSegment = segments[numSegments - 1];
return new Rect(lastSegment.end.x, lastSegment.end.y, 0, 0);
},
// Returns a new path that is a clone of this path.
clone: function() {
var segments = this.segments;
var numSegments = segments.length;
// works even if path has no segments
var path = new Path();
for (var i = 0; i < numSegments; i++) {
var segment = segments[i].clone();
path.appendSegment(segment);
}
return path;
},
closestPoint: function(p, opt) {
var t = this.closestPointT(p, opt);
if (!t) { return null; }
return this.pointAtT(t);
},
closestPointLength: function(p, opt) {
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
var localOpt = { precision: precision, segmentSubdivisions: segmentSubdivisions };
var t = this.closestPointT(p, localOpt);
if (!t) { return 0; }
return this.lengthAtT(t, localOpt);
},
closestPointNormalizedLength: function(p, opt) {
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
var localOpt = { precision: precision, segmentSubdivisions: segmentSubdivisions };
var cpLength = this.closestPointLength(p, localOpt);
if (cpLength === 0) { return 0; } // shortcut
var length = this.length(localOpt);
if (length === 0) { return 0; } // prevents division by zero
return cpLength / length;
},
// Private function.
closestPointT: function(p, opt) {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) { return null; } // if segments is an empty array
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
// not using localOpt
var closestPointT;
var minSquaredDistance = Infinity;
for (var i = 0; i < numSegments; i++) {
var segment = segments[i];
var subdivisions = segmentSubdivisions[i];
if (segment.isVisible) {
var segmentClosestPointT = segment.closestPointT(p, {
precision: precision,
subdivisions: subdivisions
});
var segmentClosestPoint = segment.pointAtT(segmentClosestPointT);
var squaredDistance = (new Line(segmentClosestPoint, p)).squaredLength();
if (squaredDistance < minSquaredDistance) {
closestPointT = { segmentIndex: i, value: segmentClosestPointT };
minSquaredDistance = squaredDistance;
}
}
}
if (closestPointT) { return closestPointT; }
// if no visible segment, return end of last segment
return { segmentIndex: numSegments - 1, value: 1 };
},
closestPointTangent: function(p, opt) {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) { return null; } // if segments is an empty array
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
// not using localOpt
var closestPointTangent;
var minSquaredDistance = Infinity;
for (var i = 0; i < numSegments; i++) {
var segment = segments[i];
var subdivisions = segmentSubdivisions[i];
if (segment.isDifferentiable()) {
var segmentClosestPointT = segment.closestPointT(p, {
precision: precision,
subdivisions: subdivisions
});
var segmentClosestPoint = segment.pointAtT(segmentClosestPointT);
var squaredDistance = (new Line(segmentClosestPoint, p)).squaredLength();
if (squaredDistance < minSquaredDistance) {
closestPointTangent = segment.tangentAtT(segmentClosestPointT);
minSquaredDistance = squaredDistance;
}
}
}
if (closestPointTangent) { return closestPointTangent; }
// if no valid segment, return null
return null;
},
// Returns `true` if the area surrounded by the path contains the point `p`.
// Implements the even-odd algorithm (self-intersections are "outside").
// Closes open paths (always imagines a final closing segment).
// Precision may be adjusted by passing an `opt` object.
containsPoint: function(p, opt) {
var polylines = this.toPolylines(opt);
if (!polylines) { return false; } // shortcut (this path has no polylines)
var numPolylines = polylines.length;
// how many component polylines does `p` lie within?
var numIntersections = 0;
for (var i = 0; i < numPolylines; i++) {
var polyline = polylines[i];
if (polyline.containsPoint(p)) {
// `p` lies within this polyline
numIntersections++;
}
}
// returns `true` for odd numbers of intersections (even-odd algorithm)
return ((numIntersections % 2) === 1);
},
// Divides the path into two at requested `ratio` between 0 and 1 with precision better than `opt.precision`; optionally using `opt.subdivisions` provided.
divideAt: function(ratio, opt) {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) { return null; } // if segments is an empty array
if (ratio < 0) { ratio = 0; }
if (ratio > 1) { ratio = 1; }
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
var localOpt = { precision: precision, segmentSubdivisions: segmentSubdivisions };
var pathLength = this.length(localOpt);
var length = pathLength * ratio;
return this.divideAtLength(length, localOpt);
},
// Divides the path into two at requested `length` with precision better than requested `opt.precision`; optionally using `opt.subdivisions` provided.
divideAtLength: function(length, opt) {
var numSegments = this.segments.length;
if (numSegments === 0) { return null; } // if segments is an empty array
var fromStart = true;
if (length < 0) {
fromStart = false; // negative lengths mean start calculation from end point
length = -length; // absolute value
}
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
// not using localOpt
var i;
var segment;
// identify the segment to divide:
var l = 0; // length so far
var divided;
var dividedSegmentIndex;
var lastValidSegment; // visible AND differentiable
var lastValidSegmentIndex;
var t;
for (i = 0; i < numSegments; i++) {
var index = (fromStart ? i : (numSegments - 1 - i));
segment = this.getSegment(index);
var subdivisions = segmentSubdivisions[index];
var d = segment.length({ precision: precision, subdivisions: subdivisions });
if (segment.isDifferentiable()) { // segment is not just a point
lastValidSegment = segment;
lastValidSegmentIndex = index;
if (length <= (l + d)) {
dividedSegmentIndex = index;
divided = segment.divideAtLength(((fromStart ? 1 : -1) * (length - l)), {
precision: precision,
subdivisions: subdivisions
});
break;
}
}
l += d;
}
if (!lastValidSegment) { // no valid segment found
return null;
}
// else: the path contains at least one valid segment
if (!divided) { // the desired length is greater than the length of the path
dividedSegmentIndex = lastValidSegmentIndex;
t = (fromStart ? 1 : 0);
divided = lastValidSegment.divideAtT(t);
}
// create a copy of this path and replace the identified segment with its two divided parts:
var pathCopy = this.clone();
pathCopy.replaceSegment(dividedSegmentIndex, divided);
var divisionStartIndex = dividedSegmentIndex;
var divisionMidIndex = dividedSegmentIndex + 1;
var divisionEndIndex = dividedSegmentIndex + 2;
// do not insert the part if it looks like a point
if (!divided[0].isDifferentiable()) {
pathCopy.removeSegment(divisionStartIndex);
divisionMidIndex -= 1;
divisionEndIndex -= 1;
}
// insert a Moveto segment to ensure secondPath will be valid:
var movetoEnd = pathCopy.getSegment(divisionMidIndex).start;
pathCopy.insertSegment(divisionMidIndex, Path.createSegment('M', movetoEnd));
divisionEndIndex += 1;
// do not insert the part if it looks like a point
if (!divided[1].isDifferentiable()) {
pathCopy.removeSegment(divisionEndIndex - 1);
divisionEndIndex -= 1;
}
// ensure that Closepath segments in secondPath will be assigned correct subpathStartSegment:
var secondPathSegmentIndexConversion = divisionEndIndex - divisionStartIndex - 1;
for (i = divisionEndIndex; i < pathCopy.segments.length; i++) {
var originalSegment = this.getSegment(i - secondPathSegmentIndexConversion);
segment = pathCopy.getSegment(i);
if ((segment.type === 'Z') && !originalSegment.subpathStartSegment.end.equals(segment.subpathStartSegment.end)) {
// pathCopy segment's subpathStartSegment is different from original segment's one
// convert this Closepath segment to a Lineto and replace it in pathCopy
var convertedSegment = Path.createSegment('L', originalSegment.end);
pathCopy.replaceSegment(i, convertedSegment);
}
}
// distribute pathCopy segments into two paths and return those:
var firstPath = new Path(pathCopy.segments.slice(0, divisionMidIndex));
var secondPath = new Path(pathCopy.segments.slice(divisionMidIndex));
return [firstPath, secondPath];
},
// Checks whether two paths are exactly the same.
// If `p` is undefined or null, returns false.
equals: function(p) {
if (!p) { return false; }
var segments = this.segments;
var otherSegments = p.segments;
var numSegments = segments.length;
if (otherSegments.length !== numSegments) { return false; } // if the two paths have different number of segments, they cannot be equal
for (var i = 0; i < numSegments; i++) {
var segment = segments[i];
var otherSegment = otherSegments[i];
// as soon as an inequality is found in segments, return false
if ((segment.type !== otherSegment.type) || (!segment.equals(otherSegment))) { return false; }
}
// if no inequality found in segments, return true
return true;
},
// Accepts negative indices.
// Throws an error if path has no segments.
// Throws an error if index is out of range.
getSegment: function(index) {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) { throw new Error('Path has no segments.'); }
if (index < 0) { index = numSegments + index; } // convert negative indices to positive
if (index >= numSegments || index < 0) { throw new Error('Index out of range.'); }
return segments[index];
},
// Returns an array of segment subdivisions, with precision better than requested `opt.precision`.
getSegmentSubdivisions: function(opt) {
var segments = this.segments;
var numSegments = segments.length;
// works even if path has no segments
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
// not using opt.segmentSubdivisions
// not using localOpt
var segmentSubdivisions = [];
for (var i = 0; i < numSegments; i++) {
var segment = segments[i];
var subdivisions = segment.getSubdivisions({ precision: precision });
segmentSubdivisions.push(subdivisions);
}
return segmentSubdivisions;
},
// Returns an array of subpaths of this path.
// Invalid paths are validated first.
// Returns `[]` if path has no segments.
getSubpaths: function() {
var validatedPath = this.clone().validate();
var segments = validatedPath.segments;
var numSegments = segments.length;
var subpaths = [];
for (var i = 0; i < numSegments; i++) {
var segment = segments[i];
if (segment.isSubpathStart) {
// we encountered a subpath start segment
// create a new path for segment, and push it to list of subpaths
subpaths.push(new Path(segment));
} else {
// append current segment to the last subpath
subpaths[subpaths.length - 1].appendSegment(segment);
}
}
return subpaths;
},
// Insert `arg` at given `index`.
// `index = 0` means insert at the beginning.
// `index = segments.length` means insert at the end.
// Accepts negative indices, from `-1` to `-(segments.length + 1)`.
// Accepts one segment or an array of segments as argument.
// Throws an error if index is out of range.
// Throws an error if argument is not a segment or an array of segments.
insertSegment: function(index, arg) {
var segments = this.segments;
var numSegments = segments.length;
// works even if path has no segments
// note that these are incremented compared to getSegments()
// we can insert after last element (note that this changes the meaning of index -1)
if (index < 0) { index = numSegments + index + 1; } // convert negative indices to positive
if (index > numSegments || index < 0) { throw new Error('Index out of range.'); }
var currentSegment;
var previousSegment = null;
var nextSegment = null;
if (numSegments !== 0) {
if (index >= 1) {
previousSegment = segments[index - 1];
nextSegment = previousSegment.nextSegment; // if we are inserting at end, nextSegment is null
} else { // if index === 0
// previousSegment is null
nextSegment = segments[0];
}
}
if (!Array.isArray(arg)) {
if (!arg || !arg.isSegment) { throw new Error('Segment required.'); }
currentSegment = this.prepareSegment(arg, previousSegment, nextSegment);
segments.splice(index, 0, currentSegment);
} else {
// flatten one level deep
// so we can chain arbitrary Path.createSegment results
arg = arg.reduce(function(acc, val) {
return acc.concat(val);
}, []);
if (!arg[0].isSegment) { throw new Error('Segments required.'); }
var n = arg.length;
for (var i = 0; i < n; i++) {
var currentArg = arg[i];
currentSegment = this.prepareSegment(currentArg, previousSegment, nextSegment);
segments.splice((index + i), 0, currentSegment); // incrementing index to insert subsequent segments after inserted segments
previousSegment = currentSegment;
}
}
},
intersectionWithLine: function(line, opt) {
var intersection = null;
var polylines = this.toPolylines(opt);
if (!polylines) { return null; }
for (var i = 0, n = polylines.length; i < n; i++) {
var polyline = polylines[i];
var polylineIntersection = line.intersect(polyline);
if (polylineIntersection) {
intersection || (intersection = []);
if (Array.isArray(polylineIntersection)) {
Array.prototype.push.apply(intersection, polylineIntersection);
} else {
intersection.push(polylineIntersection);
}
}
}
return intersection;
},
isDifferentiable: function() {
var segments = this.segments;
var numSegments = segments.length;
for (var i = 0; i < numSegments; i++) {
var segment = segments[i];
// as soon as a differentiable segment is found in segments, return true
if (segment.isDifferentiable()) { return true; }
}
// if no differentiable segment is found in segments, return false
return false;
},
// Checks whether current path segments are valid.
// Note that d is allowed to be empty - should disable rendering of the path.
isValid: function() {
var segments = this.segments;
var isValid = (segments.length === 0) || (segments[0].type === 'M'); // either empty or first segment is a Moveto
return isValid;
},
// Returns length of the path, with precision better than requested `opt.precision`; or using `opt.segmentSubdivisions` provided.
// If path has no segments, returns 0.
length: function(opt) {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) { return 0; } // if segments is an empty array
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision; // opt.precision only used in getSegmentSubdivisions() call
var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
// not using localOpt
var length = 0;
for (var i = 0; i < numSegments; i++) {
var segment = segments[i];
var subdivisions = segmentSubdivisions[i];
length += segment.length({ subdivisions: subdivisions });
}
return length;
},
// Private function.
lengthAtT: function(t, opt) {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) { return 0; } // if segments is an empty array
var segmentIndex = t.segmentIndex;
if (segmentIndex < 0) { return 0; } // regardless of t.value
var tValue = t.value;
if (segmentIndex >= numSegments) {
segmentIndex = numSegments - 1;
tValue = 1;
} else if (tValue < 0) { tValue = 0; }
else if (tValue > 1) { tValue = 1; }
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
// not using localOpt
var subdivisions;
var length = 0;
for (var i = 0; i < segmentIndex; i++) {
var segment = segments[i];
subdivisions = segmentSubdivisions[i];
length += segment.length({ precisison: precision, subdivisions: subdivisions });
}
segment = segments[segmentIndex];
subdivisions = segmentSubdivisions[segmentIndex];
length += segment.lengthAtT(tValue, { precisison: precision, subdivisions: subdivisions });
return length;
},
// Returns point at requested `ratio` between 0 and 1, with precision better than requested `opt.precision`; optionally using `opt.segmentSubdivisions` provided.
pointAt: function(ratio, opt) {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) { return null; } // if segments is an empty array
if (ratio <= 0) { return this.start.clone(); }
if (ratio >= 1) { return this.end.clone(); }
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
var localOpt = { precision: precision, segmentSubdivisions: segmentSubdivisions };
var pathLength = this.length(localOpt);
var length = pathLength * ratio;
return this.pointAtLength(length, localOpt);
},
// Returns point at requested `length`, with precision better than requested `opt.precision`; optionally using `opt.segmentSubdivisions` provided.
// Accepts negative length.
pointAtLength: function(length, opt) {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) { return null; } // if segments is an empty array
if (length === 0) { return this.start.clone(); }
var fromStart = true;
if (length < 0) {
fromStart = false; // negative lengths mean start calculation from end point
length = -length; // absolute value
}
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
// not using localOpt
var lastVisibleSegment;
var l = 0; // length so far
for (var i = 0; i < numSegments; i++) {
var index = (fromStart ? i : (numSegments - 1 - i));
var segment = segments[index];
var subdivisions = segmentSubdivisions[index];
var d = segment.length({ precision: precision, subdivisions: subdivisions });
if (segment.isVisible) {
if (length <= (l + d)) {
return segment.pointAtLength(((fromStart ? 1 : -1) * (length - l)), {
precision: precision,
subdivisions: subdivisions
});
}
lastVisibleSegment = segment;
}
l += d;
}
// if length requested is higher than the length of the path, return last visible segment endpoint
if (lastVisibleSegment) { return (fromStart ? lastVisibleSegment.end : lastVisibleSegment.start); }
// if no visible segment, return last segment end point (no matter if fromStart or no)
var lastSegment = segments[numSegments - 1];
return lastSegment.end.clone();
},
// Private function.
pointAtT: function(t) {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) { return null; } // if segments is an empty array
var segmentIndex = t.segmentIndex;
if (segmentIndex < 0) { return segments[0].pointAtT(0); }
if (segmentIndex >= numSegments) { return segments[numSegments - 1].pointAtT(1); }
var tValue = t.value;
if (tValue < 0) { tValue = 0; }
else if (tValue > 1) { tValue = 1; }
return segments[segmentIndex].pointAtT(tValue);
},
// Default precision
PRECISION: 3,
// Helper method for adding segments.
prepareSegment: function(segment, previousSegment, nextSegment) {
// insert after previous segment and before previous segment's next segment
segment.previousSegment = previousSegment;
segment.nextSegment = nextSegment;
if (previousSegment) { previousSegment.nextSegment = segment; }
if (nextSegment) { nextSegment.previousSegment = segment; }
var updateSubpathStart = segment;
if (segment.isSubpathStart) {
segment.subpathStartSegment = segment; // assign self as subpath start segment
updateSubpathStart = nextSegment; // start updating from next segment
}
// assign previous segment's subpath start (or self if it is a subpath start) to subsequent segments
if (updateSubpathStart) { this.updateSubpathStartSegment(updateSubpathStart); }
return segment;
},
// Remove the segment at `index`.
// Accepts negative indices, from `-1` to `-segments.length`.
// Throws an error if path has no segments.
// Throws an error if index is out of range.
removeSegment: function(index) {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) { throw new Error('Path has no segments.'); }
if (index < 0) { index = numSegments + index; } // convert negative indices to positive
if (index >= numSegments || index < 0) { throw new Error('Index out of range.'); }
var removedSegment = segments.splice(index, 1)[0];
var previousSegment = removedSegment.previousSegment;
var nextSegment = removedSegment.nextSegment;
// link the previous and next segments together (if present)
if (previousSegment) { previousSegment.nextSegment = nextSegment; } // may be null
if (nextSegment) { nextSegment.previousSegment = previousSegment; } // may be null
// if removed segment used to start a subpath, update all subsequent segments until another subpath start segment is reached
if (removedSegment.isSubpathStart && nextSegment) { this.updateSubpathStartSegment(nextSegment); }
},
// Replace the segment at `index` with `arg`.
// Accepts negative indices, from `-1` to `-segments.length`.
// Accepts one segment or an array of segments as argument.
// Throws an error if path has no segments.
// Throws an error if index is out of range.
// Throws an error if argument is not a segment or an array of segments.
replaceSegment: function(index, arg) {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) { throw new Error('Path has no segments.'); }
if (index < 0) { index = numSegments + index; } // convert negative indices to positive
if (index >= numSegments || index < 0) { throw new Error('Index out of range.'); }
var currentSegment;
var replacedSegment = segments[index];
var previousSegment = replacedSegment.previousSegment;
var nextSegment = replacedSegment.nextSegment;
var updateSubpathStart = replacedSegment.isSubpathStart; // boolean: is an update of subpath starts necessary?
if (!Array.isArray(arg)) {
if (!arg || !arg.isSegment) { throw new Error('Segment required.'); }
currentSegment = this.prepareSegment(arg, previousSegment, nextSegment);
segments.splice(index, 1, currentSegment); // directly replace
if (updateSubpathStart && currentSegment.isSubpathStart) { updateSubpathStart = false; } // already updated by `prepareSegment`
} else {
// flatten one level deep
// so we can chain arbitrary Path.createSegment results
arg = arg.reduce(function(acc, val) {
return acc.concat(val);
}, []);
if (!arg[0].isSegment) { throw new Error('Segments required.'); }
segments.splice(index, 1);
var n = arg.length;
for (var i = 0; i < n; i++) {
var currentArg = arg[i];
currentSegment = this.prepareSegment(currentArg, previousSegment, nextSegment);
segments.splice((index + i), 0, currentSegment); // incrementing index to insert subsequent segments after inserted segments
previousSegment = currentSegment;
if (updateSubpathStart && currentSegment.isSubpathStart) { updateSubpathStart = false; } // already updated by `prepareSegment`
}
}
// if replaced segment used to start a subpath and no new subpath start was added, update all subsequent segments until another subpath start segment is reached
if (updateSubpathStart && nextSegment) { this.updateSubpathStartSegment(nextSegment); }
},
round: function(precision) {
var segments = this.segments;
var numSegments = segments.length;
for (var i = 0; i < numSegments; i++) {
var segment = segments[i];
segment.round(precision);
}
return this;
},
scale: function(sx, sy, origin) {
var segments = this.segments;
var numSegments = segments.length;
for (var i = 0; i < numSegments; i++) {
var segment = segments[i];
segment.scale(sx, sy, origin);
}
return this;
},
segmentAt: function(ratio, opt) {
var index = this.segmentIndexAt(ratio, opt);
if (!index) { return null; }
return this.getSegment(index);
},
// Accepts negative length.
segmentAtLength: function(length, opt) {
var index = this.segmentIndexAtLength(length, opt);
if (!index) { return null; }
return this.getSegment(index);
},
segmentIndexAt: function(ratio, opt) {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) { return null; } // if segments is an empty array
if (ratio < 0) { ratio = 0; }
if (ratio > 1) { ratio = 1; }
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
var localOpt = { precision: precision, segmentSubdivisions: segmentSubdivisions };
var pathLength = this.length(localOpt);
var length = pathLength * ratio;
return this.segmentIndexAtLength(length, localOpt);
},
// Accepts negative length.
segmentIndexAtLength: function(length, opt) {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) { return null; } // if segments is an empty array
var fromStart = true;
if (length < 0) {
fromStart = false; // negative lengths mean start calculation from end point
length = -length; // absolute value
}
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
// not using localOpt
var lastVisibleSegmentIndex = null;
var l = 0; // length so far
for (var i = 0; i < numSegments; i++) {
var index = (fromStart ? i : (numSegments - 1 - i));
var segment = segments[index];
var subdivisions = segmentSubdivisions[index];
var d = segment.length({ precision: precision, subdivisions: subdivisions });
if (segment.isVisible) {
if (length <= (l + d)) { return index; }
lastVisibleSegmentIndex = index;
}
l += d;
}
// if length requested is higher than the length of the path, return last visible segment index
// if no visible segment, return null
return lastVisibleSegmentIndex;
},
// Returns a string that can be used to reconstruct the path.
// Additional error checking compared to toString (must start with M segment).
serialize: function() {
if (!this.isValid()) { throw new Error('Invalid path segments.'); }
return this.toString();
},
// Returns tangent line at requested `ratio` between 0 and 1, with precision better than requested `opt.precision`; optionally using `opt.segmentSubdivisions` provided.
tangentAt: function(ratio, opt) {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) { return null; } // if segments is an empty array
if (ratio < 0) { ratio = 0; }
if (ratio > 1) { ratio = 1; }
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
var localOpt = { precision: precision, segmentSubdivisions: segmentSubdivisions };
var pathLength = this.length(localOpt);
var length = pathLength * ratio;
return this.tangentAtLength(length, localOpt);
},
// Returns tangent line at requested `length`, with precision better than requested `opt.precision`; optionally using `opt.segmentSubdivisions` provided.
// Accepts negative length.
tangentAtLength: function(length, opt) {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) { return null; } // if segments is an empty array
var fromStart = true;
if (length < 0) {
fromStart = false; // negative lengths mean start calculation from end point
length = -length; // absolute value
}
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
// not using localOpt
var lastValidSegment; // visible AND differentiable (with a tangent)
var l = 0; // length so far
for (var i = 0; i < numSegments; i++) {
var index = (fromStart ? i : (numSegments - 1 - i));
var segment = segments[index];
var subdivisions = segmentSubdivisions[index];
var d = segment.length({ precision: precision, subdivisions: subdivisions });
if (segment.isDifferentiable()) {
if (length <= (l + d)) {
return segment.tangentAtLength(((fromStart ? 1 : -1) * (length - l)), {
precision: precision,
subdivisions: subdivisions
});
}
lastValidSegment = segment;
}
l += d;
}
// if length requested is higher than the length of the path, return tangent of endpoint of last valid segment
if (lastValidSegment) {
var t = (fromStart ? 1 : 0);
return lastValidSegment.tangentAtT(t);
}
// if no valid segment, return null
return null;
},
// Private function.
tangentAtT: function(t) {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) { return null; } // if segments is an empty array
var segmentIndex = t.segmentIndex;
if (segmentIndex < 0) { return segments[0].tangentAtT(0); }
if (segmentIndex >= numSegments) { return segments[numSegments - 1].tangentAtT(1); }
var tValue = t.value;
if (tValue < 0) { tValue = 0; }
else if (tValue > 1) { tValue = 1; }
return segments[segmentIndex].tangentAtT(tValue);
},
toPoints: function(opt) {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) { return null; } // if segments is an empty array
opt = opt || {};
var precision = (opt.precision === undefined) ? this.PRECISION : opt.precision;
var segmentSubdivisions = (opt.segmentSubdivisions === undefined) ? this.getSegmentSubdivisions({ precision: precision }) : opt.segmentSubdivisions;
var points = [];
var partialPoints = [];
for (var i = 0; i < numSegments; i++) {
var segment = segments[i];
if (segment.isVisible) {
var currentSegmentSubdivisions = segmentSubdivisions[i];
if (currentSegmentSubdivisions.length > 0) {
var subdivisionPoints = currentSegmentSubdivisions.map(function(curve) {
return curve.start;
});
Array.prototype.push.apply(partialPoints, subdivisionPoints);
} else {
partialPoints.push(segment.start);
}
} else if (partialPoints.length > 0) {
partialPoints.push(segments[i - 1].end);
points.push(partialPoints);
partialPoints = [];
}
}
if (partialPoints.length > 0) {
partialPoints.push(this.end);
points.push(partialPoints);
}
return points;
},
toPolylines: function(opt) {
var polylines = [];
var points = this.toPoints(opt);
if (!points) { return null; }
for (var i = 0, n = points.length; i < n; i++) {
polylines.push(new Polyline(points[i]));
}
return polylines;
},
toString: function() {
var segments = this.segments;
var numSegments = segments.length;
var pathData = '';
for (var i = 0; i < numSegments; i++) {
var segment = segments[i];
pathData += segment.serialize() + ' ';
}
return pathData.trim();
},
translate: function(tx, ty) {
var segments = this.segments;
var numSegments = segments.length;
for (var i = 0; i < numSegments; i++) {
var segment = segments[i];
segment.translate(tx, ty);
}
return this;
},
// Helper method for updating subpath start of segments, starting with the one provided.
updateSubpathStartSegment: function(segment) {
var previousSegment = segment.previousSegment; // may be null
while (segment && !segment.isSubpathStart) {
// assign previous segment's subpath start segment to this segment
if (previousSegment) { segment.subpathStartSegment = previousSegment.subpathStartSegment; } // may be null
else { segment.subpathStartSegment = null; } // if segment had no previous segment, assign null - creates an invalid path!
previousSegment = segment;
segment = segment.nextSegment; // move on to the segment after etc.
}
},
// If the path is not valid, insert M 0 0 at the beginning.
// Path with no segments is considered valid, so nothing is inserted.
validate: function() {
if (!this.isValid()) { this.insertSegment(0, Path.createSegment('M', 0, 0)); }
return this;
}
};
Object.defineProperty(Path.prototype, 'start', {
// Getter for the first visible endpoint of the path.
configurable: true,
enumerable: true,
get: function() {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) { return null; }
for (var i = 0; i < numSegments; i++) {
var segment = segments[i];
if (segment.isVisible) { return segment.start; }
}
// if no visible segment, return last segment end point
return segments[numSegments - 1].end;
}
});
Object.defineProperty(Path.prototype, 'end', {
// Getter for the last visible endpoint of the path.
configurable: true,
enumerable: true,
get: function() {
var segments = this.segments;
var numSegments = segments.length;
if (numSegments === 0) { return null; }
for (var i = numSegments - 1; i >= 0; i--) {
var segment = segments[i];
if (segment.isVisible) { return segment.end; }
}
// if no visible segment, return last segment end point
return segments[numSegments - 1].end;
}
});
// Local helper function.
// Use an array of arguments to call a constructor (function called with `new`).
// Adapted from https://stackoverflow.com/a/8843181/2263595
// It is not necessary to use this function if the arguments can be passed separately (i.e. if the number of arguments is limited).
// - If that is the case, use `new constructor(arg1, arg2)`, for example.
// It is not necessary to use this function if the function that needs an array of arguments is not supposed to be used as a constructor.
// - If that is the case, use `f.apply(thisArg, [arg1, arg2...])`, for example.
function applyToNew(constructor, argsArray) {
// The `new` keyword can only be applied to functions that take a limited number of arguments.
// - We can fake that with .bind().
// - It calls a function (`constructor`, here) with the arguments that were provided to it - effectively transforming an unlimited number of arguments into limited.
// - So `new (constructor.bind(thisArg, arg1, arg2...))`
// - `thisArg` can be anything (e.g. null) because `new` keyword resets context to the constructor object.
// We need to pass in a variable number of arguments to the bind() call.
// - We can use .apply().
// - So `new (constructor.bind.apply(constructor, [thisArg, arg1, arg2...]))`
// - `thisArg` can still be anything because `new` overwrites it.
// Finally, to make sure that constructor.bind overwriting is not a problem, we switch to `Function.prototype.bind`.
// - So, the final version is `new (Function.prototype.bind.apply(constructor, [thisArg, arg1, arg2...]))`
// The function expects `argsArray[0]` to be `thisArg`.
// - This means that whatever is sent as the first element will be ignored.
// - The constructor will only see arguments starting from argsArray[1].
// - So, a new dummy element is inserted at the start of the array.
argsArray.unshift(null);
return new (Function.prototype.bind.apply(constructor, argsArray));
}
// Local helper function.
// Add properties from arguments on top of properties from `obj`.
// This allows for rudimentary inheritance.
// - The `obj` argument acts as parent.
// - This function creates a new object that inherits all `obj` properties and adds/replaces those that are present in arguments.
// - A high-level example: calling `extend(Vehicle, Car)` would be akin to declaring `class Car extends Vehicle`.
function extend(obj) {
var arguments$1 = arguments;
// In JavaScript, the combination of a constructor function (e.g. `g.Line = function(...) {...}`) and prototype (e.g. `g.Line.prototype = {...}) is akin to a C++ class.
// - When inheritance is not necessary, we can leave it at that. (This would be akin to calling extend with only `obj`.)
// - But, what if we wanted the `g.Line` quasiclass to inherit from another quasiclass (let's call it `g.GeometryObject`) in JavaScript?
// - First, realize that both of those quasiclasses would still have their own separate constructor function.
// - So what we are actually saying is that we want the `g.Line` prototype to inherit from `g.GeometryObject` prototype.
// - This method provides a way to do exactly that.
// - It copies parent prototype's properties, then adds extra ones from child prototype/overrides parent prototype properties with child prototype properties.
// - Therefore, to continue with the example above:
// - `g.Line.prototype = extend(g.GeometryObject.prototype, linePrototype)`
// - Where `linePrototype` is a properties object that looks just like `g.Line.prototype` does right now.
// - Then, `g.Line` would allow the programmer to access to all methods currently in `g.Line.Prototype`, plus any non-overridden methods from `g.GeometryObject.prototype`.
// - In that aspect, `g.GeometryObject` would then act like the parent of `g.Line`.
// - Multiple inheritance is also possible, if multiple arguments are provided.
// - What if we wanted to add another level of abstraction between `g.GeometryObject` and `g.Line` (let's call it `g.LinearObject`)?
// - `g.Line.prototype = extend(g.GeometryObject.prototype, g.LinearObject.prototype, linePrototype)`
// - The ancestors are applied in order of appearance.
// - That means that `g.Line` would have inherited from `g.LinearObject` that would have inherited from `g.GeometryObject`.
// - Any number of ancestors may be provided.
// - Note that neither `obj` nor any of the arguments need to actually be prototypes of any JavaScript quasiclass, that was just a simplified explanation.
// - We can create a new object composed from the properties of any number of other objects (since they do not have a constructor, we can think of those as interfaces).
// - `extend({ a: 1, b: 2 }, { b: 10, c: 20 }, { c: 100, d: 200 })` gives `{ a: 1, b: 10, c: 100, d: 200 }`.
// - Basically, with this function, we can emulate the `extends` keyword as well as the `implements` keyword.
// - Therefore, both of the following are valid:
// - `Lineto.prototype = extend(Line.prototype, segmentPrototype, linetoPrototype)`
// - `Moveto.prototype = extend(segmentPrototype, movetoPrototype)`
var i;
var n;
var args = [];
n = arguments.length;
for (i = 1; i < n; i++) { // skip over obj
args.push(arguments$1[i]);
}
if (!obj) { throw new Error('Missing a parent object.'); }
var child = Object.create(obj);
n = args.length;
for (i = 0; i < n; i++) {
var src = args[i];
var inheritedProperty;
var key;
for (key in src) {
if (src.hasOwnProperty(key)) {
delete child[key]; // delete property inherited from parent
inheritedProperty = Object.getOwnPropertyDescriptor(src, key); // get new definition of property from src
Object.defineProperty(child, key, inheritedProperty); // re-add property with new definition (includes getter/setter methods)
}
}
}
return child;
}
// Path segment interface:
var segmentPrototype = {
// virtual
bbox: function() {
throw new Error('Declaration missing for virtual function.');
},
// virtual
clone: function() {
throw new Error('Declaration missing for virtual function.');
},
// virtual
closestPoint: function() {
throw new Error('Declaration missing for virtual function.');
},
// virtual
closestPointLength: function() {
throw new Error('Declaration missing for virtual function.');
},
// virtual
closestPointNormalizedLength: function() {
throw new Error('Declaration missing for virtual function.');
},
// Redirect calls to closestPointNormalizedLength() function if closestPointT() is not defined for segment.
closestPointT: function(p) {
if (this.closestPointNormalizedLength) { return this.closestPointNormalizedLength(p); }
throw new Error('Neither closestPointT() nor closestPointNormalizedLength() function is implemented.');
},
// virtual
closestPointTangent: function() {
throw new Error('Declaration missing for virtual function.');
},
// virtual
divideAt: function() {
throw new Error('Declaration missing for virtual function.');
},
// virtual
divideAtLength: function() {
throw new Error('Declaration missing for virtual function.');
},
// Redirect calls to divideAt() function if divideAtT() is not defined for segment.
divideAtT: function(t) {
if (this.divideAt) { return this.divideAt(t); }
throw new Error('Neither divideAtT() nor divideAt() function is implemented.');
},
// virtual
equals: function() {
throw new Error('Declaration missing for virtual function.');
},
// virtual
getSubdivisions: function() {
throw new Error('Declaration missing for virtual function.');
},
// virtual
isDifferentiable: function() {
throw new Error('Declaration missing for virtual function.');
},
isSegment: true,
isSubpathStart: false, // true for Moveto segments
isVisible: true, // false for Moveto segments
// virtual
length: function() {
throw new Error('Declaration missing for virtual function.');
},
// Return a fraction of result of length() function if lengthAtT() is not defined for segment.
lengthAtT: function(t) {
if (t <= 0) { return 0; }
var length = this.length();
if (t >= 1) { return length; }
return length * t;
},
nextSegment: null, // needed for subpath start segment updating
// virtual
pointAt: function() {
throw new Error('Declaration missing for virtual function.');
},
// virtual
pointAtLength: function() {
throw new Error('Declaration missing for virtual function.');
},
// Redirect calls to pointAt() function if pointAtT() is not defined for segment.
pointAtT: function(t) {
if (this.pointAt) { return this.pointAt(t); }
throw new Error('Neither pointAtT() nor pointAt() function is implemented.');
},
previousSegment: null, // needed to get segment start property
// virtual
round: function() {
throw new Error('Declaration missing for virtual function.');
},
subpathStartSegment: null, // needed to get Closepath segment end property
// virtual
scale: function() {
throw new Error('Declaration missing for virtual function.');
},
// virtual
serialize: function() {
throw new Error('Declaration missing for virtual function.');
},
// virtual
tangentAt: function() {
throw new Error('Declaration missing for virtual function.');
},
// virtual
tangentAtLength: function() {
throw new Error('Declaration missing for virtual function.');
},
// Redirect calls to tangentAt() function if tangentAtT() is not defined for segment.
tangentAtT: function(t) {
if (this.tangentAt) { return this.tangentAt(t); }
throw new Error('Neither tangentAtT() nor tangentAt() function is implemented.');
},
// virtual
toString: function() {
throw new Error('Declaration missing for virtual function.');
},
// virtual
translate: function() {
throw new Error('Declaration missing for virtual function.');
}
};
// usually directly assigned
// getter for Closepath
Object.defineProperty(segmentPrototype, 'end', {
configurable: true,
enumerable: true,
writable: true
});
// always a getter
// always throws error for Moveto
Object.defineProperty(segmentPrototype, 'start', {
// get a reference to the end point of previous segment
configurable: true,
enumerable: true,
get: function() {
if (!this.previousSegment) { throw new Error('Missing previous segment. (This segment cannot be the first segment of a path; OR segment has not yet been added to a path.)'); }
return this.previousSegment.end;
}
});
// virtual
Object.defineProperty(segmentPrototype, 'type', {
configurable: true,
enumerable: true,
get: function() {
throw new Error('Bad segment declaration. No type specified.');
}
});
// Path segment implementations:
var Lineto = function() {
var arguments$1 = arguments;
var args = [];
var n = arguments.length;
for (var i = 0; i < n; i++) {
args.push(arguments$1[i]);
}
if (!(this instanceof Lineto)) { // switching context of `this` to Lineto when called without `new`
return applyToNew(Lineto, args);
}
if (n === 0) {
throw new Error('Lineto constructor expects a line, 1 point, or 2 coordinates (none provided).');
}
var outputArray;
if (args[0] instanceof Line) { // lines provided
if (n === 1) {
this.end = args[0].end.clone();
return this;
} else {
throw new Error('Lineto constructor expects a line, 1 point, or 2 coordinates (' + n + ' lines provided).');
}
} else if (typeof args[0] === 'string' || typeof args[0] === 'number') { // coordinates provided
if (n === 2) {
this.end = new Point(+args[0], +args[1]);
return this;
} else if (n < 2) {
throw new Error('Lineto constructor expects a line, 1 point, or 2 coordinates (' + n + ' coordinates provided).');
} else { // this is a poly-line segment
var segmentCoords;
outputArray = [];
for (i = 0; i < n; i += 2) { // coords come in groups of two
segmentCoords = args.slice(i, i + 2); // will send one coord if args.length not divisible by 2
outputArray.push(applyToNew(Lineto, segmentCoords));
}
return outputArray;
}
} else { // points provided (needs to be last to also cover plain objects with x and y)
if (n === 1) {
this.end = new Point(args[0]);
return this;
} else { // this is a poly-line segment
var segmentPoint;
outputArray = [];
for (i = 0; i < n; i += 1) {
segmentPoint = args[i];
outputArray.push(new Lineto(segmentPoint));
}
return outputArray;
}
}
};
var linetoPrototype = {
clone: function() {
return new Lineto(this.end);
},
divideAt: function(ratio) {
var line = new Line(this.start, this.end);
var divided = line.divideAt(ratio);
return [
new Lineto(divided[0]),
new Lineto(divided[1])
];
},
divideAtLength: function(length) {
var line = new Line(this.start, this.end);
var divided = line.divideAtLength(length);
return [
new Lineto(divided[0]),
new Lineto(divided[1])
];
},
getSubdivisions: function() {
return [];
},
isDifferentiable: function() {
if (!this.previousSegment) { return false; }
return !this.start.equals(this.end);
},
round: function(precision) {
this.end.round(precision);
return this;
},
scale: function(sx, sy, origin) {
this.end.scale(sx, sy, origin);
return this;
},
serialize: function() {
var end = this.end;
return this.type + ' ' + end.x + ' ' + end.y;
},
toString: function() {
return this.type + ' ' + this.start + ' ' + this.end;
},
translate: function(tx, ty) {
this.end.translate(tx, ty);
return this;
}
};
Object.defineProperty(linetoPrototype, 'type', {
configurable: true,
enumerable: true,
value: 'L'
});
Lineto.prototype = extend(segmentPrototype, Line.prototype, linetoPrototype);
var Curveto = function() {
var arguments$1 = arguments;
var args = [];
var n = arguments.length;
for (var i = 0; i < n; i++) {
args.push(arguments$1[i]);
}
if (!(this instanceof Curveto)) { // switching context of `this` to Curveto when called without `new`
return applyToNew(Curveto, args);
}
if (n === 0) {
throw new Error('Curveto constructor expects a curve, 3 points, or 6 coordinates (none provided).');
}
var outputArray;
if (args[0] instanceof Curve) { // curves provided
if (n === 1) {
this.controlPoint1 = args[0].controlPoint1.clone();
this.controlPoint2 = args[0].controlPoint2.clone();
this.end = args[0].end.clone();
return this;
} else {
throw new Error('Curveto constructor expects a curve, 3 points, or 6 coordinates (' + n + ' curves provided).');
}
} else if (typeof args[0] === 'string' || typeof args[0] === 'number') { // coordinates provided
if (n === 6) {
this.controlPoint1 = new Point(+args[0], +args[1]);
this.controlPoint2 = new Point(+args[2], +args[3]);
this.end = new Point(+args[4], +args[5]);
return this;
} else if (n < 6) {
throw new Error('Curveto constructor expects a curve, 3 points, or 6 coordinates (' + n + ' coordinates provided).');
} else { // this is a poly-bezier segment
var segmentCoords;
outputArray = [];
for (i = 0; i < n; i += 6) { // coords come in groups of six
segmentCoords = args.slice(i, i + 6); // will send fewer than six coords if args.length not divisible by 6
outputArray.push(applyToNew(Curveto, segmentCoords));
}
return outputArray;
}
} else { // points provided (needs to be last to also cover plain objects with x and y)
if (n === 3) {
this.controlPoint1 = new Point(args[0]);
this.controlPoint2 = new Point(args[1]);
this.end = new Point(args[2]);
return this;
} else if (n < 3) {
throw new Error('Curveto constructor expects a curve, 3 points, or 6 coordinates (' + n + ' points provided).');
} else { // this is a poly-bezier segment
var segmentPoints;
outputArray = [];
for (i = 0; i < n; i += 3) { // points come in groups of three
segmentPoints = args.slice(i, i + 3); // will send fewer than three points if args.length is not divisible by 3
outputArray.push(applyToNew(Curveto, segmentPoints));
}
return outputArray;
}
}
};
var curvetoPrototype = {
clone: function() {
return new Curveto(this.controlPoint1, this.controlPoint2, this.end);
},
divideAt: function(ratio, opt) {
var curve = new Curve(this.start, this.controlPoint1, this.controlPoint2, this.end);
var divided = curve.divideAt(ratio, opt);
return [
new Curveto(divided[0]),
new Curveto(divided[1])
];
},
divideAtLength: function(length, opt) {
var curve = new Curve(this.start, this.controlPoint1, this.controlPoint2, this.end);
var divided = curve.divideAtLength(length, opt);
return [
new Curveto(divided[0]),
new Curveto(divided[1])
];
},
divideAtT: function(t) {
var curve = new Curve(this.start, this.controlPoint1, this.controlPoint2, this.end);
var divided = curve.divideAtT(t);
return [
new Curveto(divided[0]),
new Curveto(divided[1])
];
},
isDifferentiable: function() {
if (!this.previousSegment) { return false; }
var start = this.start;
var control1 = this.controlPoint1;
var control2 = this.controlPoint2;
var end = this.end;
return !(start.equals(control1) && control1.equals(control2) && control2.equals(end));
},
round: function(precision) {
this.controlPoint1.round(precision);
this.controlPoint2.round(precision);
this.end.round(precision);
return this;
},
scale: function(sx, sy, origin) {
this.controlPoint1.scale(sx, sy, origin);
this.controlPoint2.scale(sx, sy, origin);
this.end.scale(sx, sy, origin);
return this;
},
serialize: function() {
var c1 = this.controlPoint1;
var c2 = this.controlPoint2;
var end = this.end;
return this.type + ' ' + c1.x + ' ' + c1.y + ' ' + c2.x + ' ' + c2.y + ' ' + end.x + ' ' + end.y;
},
toString: function() {
return this.type + ' ' + this.start + ' ' + this.controlPoint1 + ' ' + this.controlPoint2 + ' ' + this.end;
},
translate: function(tx, ty) {
this.controlPoint1.translate(tx, ty);
this.controlPoint2.translate(tx, ty);
this.end.translate(tx, ty);
return this;
}
};
Object.defineProperty(curvetoPrototype, 'type', {
configurable: true,
enumerable: true,
value: 'C'
});
Curveto.prototype = extend(segmentPrototype, Curve.prototype, curvetoPrototype);
var Moveto = function() {
var arguments$1 = arguments;
var args = [];
var n = arguments.length;
for (var i = 0; i < n; i++) {
args.push(arguments$1[i]);
}
if (!(this instanceof Moveto)) { // switching context of `this` to Moveto when called without `new`
return applyToNew(Moveto, args);
}
if (n === 0) {
throw new Error('Moveto constructor expects a line, a curve, 1 point, or 2 coordinates (none provided).');
}
var outputArray;
if (args[0] instanceof Line) { // lines provided
if (n === 1) {
this.end = args[0].end.clone();
return this;
} else {
throw new Error('Moveto constructor expects a line, a curve, 1 point, or 2 coordinates (' + n + ' lines provided).');
}
} else if (args[0] instanceof Curve) { // curves provided
if (n === 1) {
this.end = args[0].end.clone();
return this;
} else {
throw new Error('Moveto constructor expects a line, a curve, 1 point, or 2 coordinates (' + n + ' curves provided).');
}
} else if (typeof args[0] === 'string' || typeof args[0] === 'number') { // coordinates provided
if (n === 2) {
this.end = new Point(+args[0], +args[1]);
return this;
} else if (n < 2) {
throw new Error('Moveto constructor expects a line, a curve, 1 point, or 2 coordinates (' + n + ' coordinates provided).');
} else { // this is a moveto-with-subsequent-poly-line segment
var segmentCoords;
outputArray = [];
for (i = 0; i < n; i += 2) { // coords come in groups of two
segmentCoords = args.slice(i, i + 2); // will send one coord if args.length not divisible by 2
if (i === 0) { outputArray.push(applyToNew(Moveto, segmentCoords)); }
else { outputArray.push(applyToNew(Lineto, segmentCoords)); }
}
return outputArray;
}
} else { // points provided (needs to be last to also cover plain objects with x and y)
if (n === 1) {
this.end = new Point(args[0]);
return this;
} else { // this is a moveto-with-subsequent-poly-line segment
var segmentPoint;
outputArray = [];
for (i = 0; i < n; i += 1) { // points come one by one
segmentPoint = args[i];
if (i === 0) { outputArray.push(new Moveto(segmentPoint)); }
else { outputArray.push(new Lineto(segmentPoint)); }
}
return outputArray;
}
}
};
var movetoPrototype = {
bbox: function() {
return null;
},
clone: function() {
return new Moveto(this.end);
},
closestPoint: function() {
return this.end.clone();
},
closestPointNormalizedLength: function() {
return 0;
},
closestPointLength: function() {
return 0;
},
closestPointT: function() {
return 1;
},
closestPointTangent: function() {
return null;
},
divideAt: function() {
return [
this.clone(),
this.clone()
];
},
divideAtLength: function() {
return [
this.clone(),
this.clone()
];
},
equals: function(m) {
return this.end.equals(m.end);
},
getSubdivisions: function() {
return [];
},
isDifferentiable: function() {
return false;
},
isSubpathStart: true,
isVisible: false,
length: function() {
return 0;
},
lengthAtT: function() {
return 0;
},
pointAt: function() {
return this.end.clone();
},
pointAtLength: function() {
return this.end.clone();
},
pointAtT: function() {
return this.end.clone();
},
round: function(precision) {
this.end.round(precision);
return this;
},
scale: function(sx, sy, origin) {
this.end.scale(sx, sy, origin);
return this;
},
serialize: function() {
var end = this.end;
return this.type + ' ' + end.x + ' ' + end.y;
},
tangentAt: function() {
return null;
},
tangentAtLength: function() {
return null;
},
tangentAtT: function() {
return null;
},
toString: function() {
return this.type + ' ' + this.end;
},
translate: function(tx, ty) {
this.end.translate(tx, ty);
return this;
}
};
Object.defineProperty(movetoPrototype, 'start', {
configurable: true,
enumerable: true,
get: function() {
throw new Error('Illegal access. Moveto segments should not need a start property.');
}
});
Object.defineProperty(movetoPrototype, 'type', {
configurable: true,
enumerable: true,
value: 'M'
});
Moveto.prototype = extend(segmentPrototype, movetoPrototype); // does not inherit from any other geometry object
var Closepath = function() {
var arguments$1 = arguments;
var args = [];
var n = arguments.length;
for (var i = 0; i < n; i++) {
args.push(arguments$1[i]);
}
if (!(this instanceof Closepath)) { // switching context of `this` to Closepath when called without `new`
return applyToNew(Closepath, args);
}
if (n > 0) {
throw new Error('Closepath constructor expects no arguments.');
}
return this;
};
var closepathPrototype = {
clone: function() {
return new Closepath();
},
divideAt: function(ratio) {
var line = new Line(this.start, this.end);
var divided = line.divideAt(ratio);
return [
// if we didn't actually cut into the segment, first divided part can stay as Z
(divided[1].isDifferentiable() ? new Lineto(divided[0]) : this.clone()),
new Lineto(divided[1])
];
},
divideAtLength: function(length) {
var line = new Line(this.start, this.end);
var divided = line.divideAtLength(length);
return [
// if we didn't actually cut into the segment, first divided part can stay as Z
(divided[1].isDifferentiable() ? new Lineto(divided[0]) : this.clone()),
new Lineto(divided[1])
];
},
getSubdivisions: function() {
return [];
},
isDifferentiable: function() {
if (!this.previousSegment || !this.subpathStartSegment) { return false; }
return !this.start.equals(this.end);
},
round: function() {
return this;
},
scale: function() {
return this;
},
serialize: function() {
return this.type;
},
toString: function() {
return this.type + ' ' + this.start + ' ' + this.end;
},
translate: function() {
return this;
}
};
Object.defineProperty(closepathPrototype, 'end', {
// get a reference to the end point of subpath start segment
configurable: true,
enumerable: true,
get: function() {
if (!this.subpathStartSegment) { throw new Error('Missing subpath start segment. (This segment needs a subpath start segment (e.g. Moveto); OR segment has not yet been added to a path.)'); }
return this.subpathStartSegment.end;
}
});
Object.defineProperty(closepathPrototype, 'type', {
configurable: true,
enumerable: true,
value: 'Z'
});
Closepath.prototype = extend(segmentPrototype, Line.prototype, closepathPrototype);
var segmentTypes = Path.segmentTypes = {
L: Lineto,
C: Curveto,
M: Moveto,
Z: Closepath,
z: Closepath
};
Path.regexSupportedData = new RegExp('^[\\s\\d' + Object.keys(segmentTypes).join('') + ',.]*$');
Path.isDataSupported = function(data) {
if (typeof data !== 'string') { return false; }
return this.regexSupportedData.test(data);
};
var bezier = {
// Cubic Bezier curve path through points.
// @deprecated
// @param {array} points Array of points through which the smooth line will go.
// @return {array} SVG Path commands as an array
curveThroughPoints: function(points) {
console.warn('deprecated');
return new Path(Curve.throughPoints(points)).serialize();
},
// Get open-ended Bezier Spline Control Points.
// @deprecated
// @param knots Input Knot Bezier spline points (At least two points!).
// @param firstControlPoints Output First Control points. Array of knots.length - 1 length.
// @param secondControlPoints Output Second Control points. Array of knots.length - 1 length.
getCurveControlPoints: function(knots) {
console.warn('deprecated');
var firstControlPoints = [];
var secondControlPoints = [];
var n = knots.length - 1;
var i;
// Special case: Bezier curve should be a straight line.
if (n == 1) {
// 3P1 = 2P0 + P3
firstControlPoints[0] = new Point(
(2 * knots[0].x + knots[1].x) / 3,
(2 * knots[0].y + knots[1].y) / 3
);
// P2 = 2P1 – P0
secondControlPoints[0] = new Point(
2 * firstControlPoints[0].x - knots[0].x,
2 * firstControlPoints[0].y - knots[0].y
);
return [firstControlPoints, secondControlPoints];
}
// Calculate first Bezier control points.
// Right hand side vector.
var rhs = [];
// Set right hand side X values.
for (i = 1; i < n - 1; i++) {
rhs[i] = 4 * knots[i].x + 2 * knots[i + 1].x;
}
rhs[0] = knots[0].x + 2 * knots[1].x;
rhs[n - 1] = (8 * knots[n - 1].x + knots[n].x) / 2.0;
// Get first control points X-values.
var x = this.getFirstControlPoints(rhs);
// Set right hand side Y values.
for (i = 1; i < n - 1; ++i) {
rhs[i] = 4 * knots[i].y + 2 * knots[i + 1].y;
}
rhs[0] = knots[0].y + 2 * knots[1].y;
rhs[n - 1] = (8 * knots[n - 1].y + knots[n].y) / 2.0;
// Get first control points Y-values.
var y = this.getFirstControlPoints(rhs);
// Fill output arrays.
for (i = 0; i < n; i++) {
// First control point.
firstControlPoints.push(new Point(x[i], y[i]));
// Second control point.
if (i < n - 1) {
secondControlPoints.push(new Point(
2 * knots [i + 1].x - x[i + 1],
2 * knots[i + 1].y - y[i + 1]
));
} else {
secondControlPoints.push(new Point(
(knots[n].x + x[n - 1]) / 2,
(knots[n].y + y[n - 1]) / 2)
);
}
}
return [firstControlPoints, secondControlPoints];
},
// Divide a Bezier curve into two at point defined by value 't' <0,1>.
// Using deCasteljau algorithm. http://math.stackexchange.com/a/317867
// @deprecated
// @param control points (start, control start, control end, end)
// @return a function that accepts t and returns 2 curves.
getCurveDivider: function(p0, p1, p2, p3) {
console.warn('deprecated');
var curve = new Curve(p0, p1, p2, p3);
return function divideCurve(t) {
var divided = curve.divide(t);
return [{
p0: divided[0].start,
p1: divided[0].controlPoint1,
p2: divided[0].controlPoint2,
p3: divided[0].end
}, {
p0: divided[1].start,
p1: divided[1].controlPoint1,
p2: divided[1].controlPoint2,
p3: divided[1].end
}];
};
},
// Solves a tridiagonal system for one of coordinates (x or y) of first Bezier control points.
// @deprecated
// @param rhs Right hand side vector.
// @return Solution vector.
getFirstControlPoints: function(rhs) {
console.warn('deprecated');
var n = rhs.length;
// `x` is a solution vector.
var x = [];
var tmp = [];
var b = 2.0;
x[0] = rhs[0] / b;
// Decomposition and forward substitution.
for (var i = 1; i < n; i++) {
tmp[i] = 1 / b;
b = (i < n - 1 ? 4.0 : 3.5) - tmp[i];
x[i] = (rhs[i] - x[i - 1]) / b;
}
for (i = 1; i < n; i++) {
// Backsubstitution.
x[n - i - 1] -= tmp[n - i] * x[n - i];
}
return x;
},
// Solves an inversion problem -- Given the (x, y) coordinates of a point which lies on
// a parametric curve x = x(t)/w(t), y = y(t)/w(t), find the parameter value t
// which corresponds to that point.
// @deprecated
// @param control points (start, control start, control end, end)
// @return a function that accepts a point and returns t.
getInversionSolver: function(p0, p1, p2, p3) {
console.warn('deprecated');
var curve = new Curve(p0, p1, p2, p3);
return function solveInversion(p) {
return curve.closestPointT(p);
};
}
};
exports.Curve = Curve;
exports.Ellipse = Ellipse;
exports.Line = Line;
exports.Path = Path;
exports.Point = Point;
exports.Polyline = Polyline;
exports.Rect = Rect;
exports.bezier = bezier;
exports.ellipse = ellipse;
exports.line = line;
exports.normalizeAngle = normalizeAngle;
exports.point = point;
exports.random = random;
exports.rect = rect;
exports.scale = scale;
exports.snapToGrid = snapToGrid;
exports.toDeg = toDeg;
exports.toRad = toRad;
Object.defineProperty(exports, '__esModule', { value: true });
}));
| cdnjs/cdnjs | ajax/libs/jointjs/3.4.4/geometry.js | JavaScript | mit | 204,970 |
module.exports = {
orientation: "row",
defaultChildOpts: { weight: null },
overflowAllowed: true,
}
| KAESapps/uiks | reaks-layout/flex/configs/hPile.js | JavaScript | mit | 106 |
var slugify = require('slug')
module.exports = function(tag) {
if (!tag) return
return '<a href="/tag/' + slugify(tag) + '/" class="icon fa-tag" />' + tag + '</a>'
}
| therabbitteam/blog | layouts/helpers/tag.js | JavaScript | mit | 172 |
const mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
bID: {type: Number, default: 0},
bOriginalID: {type: Number, default: 0},
});
var CoreBlock = mongoose.model("btCoreScrapbookDisplay",schema);
module.exports = CoreBlock; | Developer314/node5 | core/blocks/core_scrapbook_display/model.js | JavaScript | mit | 272 |
var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
host: 'es.lex.orionmd.com',
log: 'trace',
});
client.ping({
requestTimeout: 5000,
// undocumented params are appended to the query string
hello: 'elasticsearch',
}, (error) => {
if (error) {
console.error('elasticsearch cluster is down!');
} else {
console.log('All is well');
}
});
| jmhmd/lex-search | elasticsearch.js | JavaScript | mit | 395 |
import {
START_RECORDING_WORKOUT,
STOP_RECORDING_WORKOUT,
DISMISS_WORKOUT_VIDEO_RECORDER,
SAVE_WORKOUT_VIDEO,
SAVE_VIDEO_ERROR,
TOGGLE_WORKOUT_CAMERA_TYPE,
} from 'app/configs+constants/ActionTypes';
import * as DurationsSelectors from 'app/redux/selectors/DurationsSelectors';
import * as Analytics from 'app/services/Analytics';
import * as SetsSelectors from 'app/redux/selectors/SetsSelectors';
export const startRecording = (setID) => (dispatch, getState) => {
const state = getState();
logStartRecordingVideoAnalytics(state, setID);
dispatch({
type: START_RECORDING_WORKOUT,
setID: setID
});
};
export const stopRecording = () => ({
type: STOP_RECORDING_WORKOUT
});
export const dismissRecording = (setID) => (dispatch, getState) => {
const state = getState();
logCancelRecordVideoAnalytics(state, setID);
Analytics.setCurrentScreen('workout');
dispatch({
type: DISMISS_WORKOUT_VIDEO_RECORDER
});
};
export const saveVideo = (setID, videoFileURL, videoType) => (dispatch, getState) => {
const state = getState();
logSaveVideoAnalytics(state, setID);
dispatch({
type: SAVE_WORKOUT_VIDEO,
setID: setID,
videoFileURL: videoFileURL,
videoType: videoType
});
};
export const saveVideoError = (setID, error) => (dispatch, getState) => {
const state = getState();
logSaveVideoErrorAnalytics(state, setID, error);
dispatch({
type: SAVE_VIDEO_ERROR,
});
};
export const toggleCameraType = () => (dispatch, getState) => {
const state = getState();
logToggleCameraAnalytics(state);
dispatch({
type: TOGGLE_WORKOUT_CAMERA_TYPE,
});
};
const logStartRecordingVideoAnalytics = (state, setID) => {
const is_working_set = SetsSelectors.getIsWorkingSet(state, setID);
Analytics.logEventWithAppState('start_recording_video', {
is_working_set: is_working_set,
set_id: setID,
}, state);
};
const logSaveVideoAnalytics = (state, setID) => {
const duration = DurationsSelectors.getWorkoutVideoRecorderDuration(state);
const is_working_set = SetsSelectors.getIsWorkingSet(state, setID);
Analytics.logEventWithAppState('save_video', {
duration: duration,
is_working_set: is_working_set,
set_id: setID,
}, state);
};
const logCancelRecordVideoAnalytics = (state, setID) => {
const duration = DurationsSelectors.getWorkoutVideoRecorderDuration(state);
const is_working_set = SetsSelectors.getIsWorkingSet(state, setID);
Analytics.logEventWithAppState('cancel_record_video', {
duration: duration,
is_working_set: is_working_set,
set_id: setID,
}, state);
};
const logSaveVideoErrorAnalytics = (state, setID, error) => {
const duration = DurationsSelectors.getWorkoutVideoRecorderDuration(state);
const is_working_set = SetsSelectors.getIsWorkingSet(state, setID);
Analytics.logErrorWithAppState(error, 'save_video_error', {
duration: duration,
is_working_set: is_working_set,
set_id: setID,
}, state);
};
const logToggleCameraAnalytics = (state) => {
Analytics.logEventWithAppState('toggle_camera', {
}, state);
};
| squatsandsciencelabs/OpenBarbellApp | app/features/workout/camera/WorkoutVideoRecorderActions.js | JavaScript | mit | 3,262 |
ValueView = GenericView.extend({
events: {
"change": "highlightInteger"
},
tagName: 'input',
initialize: function(options) {
GenericView.prototype.initialize.apply(this, arguments);
this.param = options.parameter;
this.valueElement = $(this.el);
_.bindAll(this, 'getValue', 'showErrors', 'highlightInteger');
this.setValue();
this.model.bind('change:'+this.param, this.getValue);
this.getValue();
this.valueElement.trigger('change');
},
setValue: function() {
params = {};
this.value = this.fixComma(this.valueElement.val());
if (!isNaN(this.value) && this.value >= 0) {
params[this.param] = this.value;
this.clearErrors();
this.model.set(params, {'error': this.showErrors });
}
},
fixComma: function(value) {
// fixes comma/dot decimal separator
parsed = parseFloat(value.replace(',','.'));
if (_.isNumber(parsed)) return parsed;
return NaN;
},
prettyPrint: function(value) {
if (_.isNumber(value)) return value.toFixed(2);
return NaN;
},
highlightInteger: function() {
this.setValue();
value = this.fixComma(this.valueElement.val());
if ((value.toFixed(2) % 1) === 0) {
this.valueElement.parent().addClass('success');
} else {
this.valueElement.parent().removeClass('success');
}
},
getValue: function() {
value = this.model.get(this.param);
if (value != this.value) {
this.value = value;
this.valueElement.val(this.prettyPrint(this.value));
}
},
showErrors: function(model, errors) {
return this.parentView.showErrors(model, errors);
},
clearErrors: function() {
return this.parentView.clearErrors();
}
}); | PDFGridder/PDFGridder | site_media/static/js/views/ValueView.js | JavaScript | mit | 1,905 |
/**
* Created by Leo on 8/10/15.
*/
var app = angular.module('toDoApp', []);
app.controller('toDoListCtrl', ['$scope', function($scope) {
var toDoList = this;
toDoList.inputText = '';
toDoList.lists = [
{text: "running", done: false},
{text: "workout", done: true}
];
toDoList.enter = function() {
if(toDoList.inputText) {
toDoList.lists.push({text: toDoList.inputText, done: false});
toDoList.inputText = '';
}
};
toDoList.reset = function() {
toDoList.inputText = '';
};
toDoList.clear = function() {
toDoList.inputText = '';
toDoList.lists = [];
};
}]);
| dglzs/AngularDemo1 | main.js | JavaScript | mit | 623 |
/*
* Test service
*/
var config = require('../configs/server.js');
var configs = config.configs,
server_prefix = configs.server_prefix || 'CORE';
console.log(server_prefix + " - Test service required.");
/*
* Test Read and Write Service.
*/
/********************************************************************************************
* TEST READ
*********************************************************************************************/
exports.read = function(req, res) {
res.header("Access-Control-Allow-Origin", "*"); // to allow cross-domain, replace * with a list of domains is desired.
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS'); // ExtJS will sent out OPTIONS
res.header('Content-Type', 'application/json');
res.send({ read: 'ok'});
}
/********************************************************************************************
* TEST WRITE
*********************************************************************************************/
exports.write = function(req, res) {
res.header("Access-Control-Allow-Origin", "*"); // to allow cross-domain, replace * with a list of domains is desired.
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS'); // ExtJS will sent out OPTIONS
res.header('Content-Type', 'application/json');
res.send({ write: 'ok'});
}
| vanHeemstraSystems/core | OLD-services/test.sample.js | JavaScript | mit | 1,639 |
const model = require('../lib/db')
const util = require('../lib/util')
const appraisal_keys = require('../keys/appraisal')
module.exports = {
keys:{
response: async ctx => {
let keys = JSON.parse(JSON.stringify(appraisal_keys))
ctx.body = keys
}
},
'keys/type':{
type: 'post',
response: async ctx => {
let result = JSON.parse(JSON.stringify(appraisal_keys))
let req = ctx.request.body
let type = Number(req.type)
let typeText = result[0].child[type]
if (req.type == undefined) {
util.err('FIELD_DELETION','意见的类型未设置')
}
for (var index = 0; index < result.length; index++) {
let item = result[index]
if (item.key == 'type') {
item[item.key] = type
}
if (item.key == 'content') {
item.text = typeText
}
if (type==0 || type==1 ) {
if (item.key=='score') {
item.hide = false
item.text = (type==0?'自评':'评定') + '分值'
item.require = true
if (req.plan_id) {
let plan = await model.plan.findById(req.plan_id)
if (plan.subtask.length>0) {
let score_count = 0
for (var i = 0; i < plan.subtask.length; i++) {
var subtask_id = plan.subtask[i]
var subtask= await model.plan.findById(subtask_id)
var appraisals = await model.appraisal.find({plan_id:subtask_id,type:type}).sort('-createTime')
if (appraisals.length>0) {
score_count+= (appraisals[0].score*subtask.ratio/100)
}
}
item[item.key] = score_count
}
}
}
if (item.key == 'content') {
item.require = true
}
}
if (type==7) {
if ( item.key == 'createTime' || item.key == 'remindTime' || item.key == 'user') {
item.hide = false
}
if (item.key == 'user') {
item.text = '审核人'
}
if (item.key == 'createTime') {
item.text = '审核时间'
}
}
if (type==8 ) {
if (item.key == 'createTime' || item.key == 'remindTime' || item.key == 'user') {
item.hide = false
}
if (item.key == 'user') {
item.text = '审批人'
}
if (item.key == 'createTime') {
item.text = '审批时间'
}
}
}
ctx.body = result
}
},
'keys/briefing':{
type: 'post',
response:async ctx=>{
let req = ctx.request.body
let briefing = await model.briefing.findById(req.briefing_id)
let plan = await model.plan.findById(briefing.plan_id)
let result,type,require
if (util.idIn(plan.resman[0].superiors,ctx.user._id)) {
type = 4
require = false
}
if (plan.resman[0].superiors == undefined || plan.resman[0].superiors.length==0) {
if (ctx.user._id == plan.resman[0]._id) {
type = 4
require = false
}
}
if (util.idIn(plan.ccMan,ctx.user._id)) {
type = 2
require = false
}
if (util.idIn(plan.follow,ctx.user._id)) {
type = 3
require = false
}
if (util.idIn(briefing.superiors,ctx.user._id)) {
type = 4
require = true
}
if (util.idIn(briefing.participant,ctx.user._id)) {
type = 5
require = true
}
if (util.idIn(briefing.assist,ctx.user._id)) {
type = 6
require = true
}
if (type) {
let child = appraisal_keys[0].child
result = [{
text:'意见类型',
key:'type',
type:type,
child:child,
control_type:'text',
style:{width:'100%',color:'#aaa'}
},
{
text:child[type],
key:'content',
content:'',
require:require,
control_type:'textarea',
style:{width:'100%'}
}]
ctx.body = result
}
}
},
add:{
type: 'post',
response:async ctx=>{
let req = ctx.request.body
if (req.content == undefined || req.content == '') {
util.err('FIELD_DELETION','意见内容不能为空')
}
if (req.type==0||req.type==1) {
if (req.score<=0) {
util.err('FIELD_DELETION','分值必须大于0')
}
if (req.score>100) {
util.err('FIELD_DELETION','分值最大值为100')
}
}
req.createTime = util.createTime()
let appraisal = new model.appraisal(req)
await appraisal.save()
let result = JSON.parse(JSON.stringify(await model.appraisal.findById(appraisal._id)))
let child = appraisal_keys[0].child
if (req.type == 0) {
result.typeText = '责任自评查看'
}else if(req.type == 1){
result.typeText = '上级评定查看'
}else{
result.typeText = child[req.type]
if (req.type === 7) {
let plan = await model.plan.findById(req.plan_id)
plan.update({
$set: {
state: 3
}
})
}
}
ctx.body = result
}
},
'read/by_id':{
type: 'post',
response:async ctx=>{
let req = ctx.request.body
let child = appraisal_keys[0].child
let appraisal = JSON.parse(JSON.stringify(await model.appraisal.findById(req._id)))
let result = JSON.parse(JSON.stringify(appraisal_keys))
result.forEach((item)=>{
item.control_type = 'text'
if (item.key == 'user' || item.key == 'createTime') {
item.hide = false
}
for (var key in appraisal) {
if (key == item.key) {
item[item.key] = appraisal[key]
if (key=='score') {
item.hide = false
item.style = {width:'calc(100%/3)'}
}
}
}
})
ctx.body = result
}
},
'read/by_briefing':{
type: 'post',
response:async ctx=>{
let req = ctx.request.body
let appraisals = await model.appraisal.find({briefing_id:req.briefing_id}).sort('-createTime')
let result = []
appraisals.forEach((item)=>{
let temp = JSON.parse(JSON.stringify(item))
if (item.type>=2 && item.type<=6) {
result.push(temp)
}
})
ctx.body = result
}
},
'read/by_plan':{
type: 'post',
response:async ctx=>{
let req = ctx.request.body
let appraisals = await model.appraisal.find({plan_id:req.plan_id}).sort('-createTime')
let result = []
appraisals.forEach((item)=>{
if(item.type<2) {
result.push(item)
}
})
ctx.body = result
}
},
'read/by_type':{
type: 'post',
response:async ctx=>{
let req = ctx.request.body
if (req.plan_id == undefined) {
util.err('FIELD_DELETION','获取意见详情参数缺失:关联的计划')
}
if (req.type == undefined) {
util.err('FIELD_DELETION','获取意见详情参数缺失:意见类型')
}
let type = Number(req.type)
let appraisals = await model.appraisal.find({plan_id:req.plan_id,type:type}).sort('-createTime')
ctx.body = appraisals
}
},
'read/not_check':{
type: 'post',
response:async ctx=>{
let req = ctx.request.body
let appraisals = await model.appraisal.find({plan_id:req.plan_id}).sort('-createTime')
let result = []
appraisals.forEach((item)=>{
if (item.type==7) {
result.push(item)
}
})
ctx.body = result
}
},
'read/not_update':{
type: 'post',
response:async ctx=>{
let req = ctx.request.body
let appraisals = await model.appraisal.find({plan_id:req.plan_id}).sort('-createTime')
let result = []
appraisals.forEach((item)=>{
if (item.type==9) {
result.push(item)
}
})
ctx.body = result
}
}
}
| xiechaopeng/jz-plan-system | server/controller/appraisal.js | JavaScript | mit | 8,127 |
import config from '../config'
import createKarmaConfig from 'react-esc/build/karma.conf'
const karmaConfig = createKarmaConfig(config)
module.exports = (cfg) => cfg.set(karmaConfig)
| TriPSs/react-esc-example | bin/test.js | JavaScript | mit | 185 |
import * as React from 'react';
import { expect } from 'chai';
import { spy, stub, useFakeTimers } from 'sinon';
import { createClientRender, createMount, describeConformance } from 'test/utils';
import { createMuiTheme } from '@material-ui/core/styles';
import { Transition } from 'react-transition-group';
import Slide from '@material-ui/core/Slide';
import { setTranslateValue } from './Slide';
import { useForkRef } from '../utils';
describe('<Slide />', () => {
const render = createClientRender();
const mount = createMount();
const defaultProps = {
in: true,
children: <div id="testChild" />,
direction: 'down',
};
describeConformance(
<Slide in>
<div />
</Slide>,
() => ({
classes: {},
inheritComponent: Transition,
mount,
refInstanceof: window.HTMLDivElement,
skip: [
'componentProp',
// react-transition-group issue
'reactTestRenderer',
],
}),
);
it('should not override children styles', () => {
const { container } = render(
<Slide
{...defaultProps}
style={{ color: 'red', backgroundColor: 'yellow' }}
theme={createMuiTheme()}
>
<div id="with-slide" style={{ color: 'blue' }} />
</Slide>,
);
const slide = container.querySelector('#with-slide');
expect(slide.style).to.have.property('backgroundColor', 'yellow');
expect(slide.style).to.have.property('color', 'blue');
expect(slide.style).to.have.property('visibility', '');
});
describe('transition lifecycle', () => {
let clock;
beforeEach(() => {
clock = useFakeTimers();
});
afterEach(() => {
clock.restore();
});
it('tests', () => {
const handleEnter = spy();
const handleEntering = spy();
const handleEntered = spy();
const handleExit = spy();
const handleExiting = spy();
const handleExited = spy();
let child;
const { setProps } = render(
<Slide
onEnter={handleEnter}
onEntering={handleEntering}
onEntered={handleEntered}
onExit={handleExit}
onExiting={handleExiting}
onExited={handleExited}
>
<div
ref={(ref) => {
child = ref;
}}
/>
</Slide>,
);
setProps({ in: true });
expect(handleEntering.callCount).to.equal(1);
expect(handleEntering.args[0][0]).to.equal(child);
expect(handleEntering.args[0][0].style.transform).to.match(/none/);
expect(handleEntering.callCount).to.equal(1);
expect(handleEntering.args[0][0]).to.equal(child);
clock.tick(1000);
expect(handleEntered.callCount).to.equal(1);
setProps({ in: false });
expect(handleExiting.callCount).to.equal(1);
expect(handleExiting.args[0][0]).to.equal(child);
expect(handleExiting.callCount).to.equal(1);
expect(handleExiting.args[0][0]).to.equal(child);
clock.tick(1000);
expect(handleExited.callCount).to.equal(1);
expect(handleExited.args[0][0]).to.equal(child);
});
});
describe('prop: timeout', () => {
it('should create proper enter animation onEntering', () => {
const handleEntering = spy();
render(
<Slide
{...defaultProps}
timeout={{
enter: 556,
}}
onEntering={handleEntering}
/>,
);
expect(handleEntering.args[0][0].style.transition).to.match(
/transform 556ms cubic-bezier\(0(.0)?, 0, 0.2, 1\)( 0ms)?/,
);
});
it('should create proper exit animation', () => {
const handleExit = spy();
const { setProps } = render(
<Slide
{...defaultProps}
timeout={{
exit: 446,
}}
onExit={handleExit}
/>,
);
setProps({ in: false });
expect(handleExit.args[0][0].style.transition).to.match(
/transform 446ms cubic-bezier\(0.4, 0, 0.6, 1\)( 0ms)?/,
);
});
});
describe('prop: easing', () => {
it('should create proper enter animation', () => {
const handleEntering = spy();
render(
<Slide
{...defaultProps}
easing={{
enter: 'cubic-bezier(1, 1, 0, 0)',
}}
onEntering={handleEntering}
/>,
);
expect(handleEntering.args[0][0].style.transition).to.match(
/transform 225ms cubic-bezier\(1, 1, 0, 0\)( 0ms)?/,
);
});
it('should create proper exit animation', () => {
const handleExit = spy();
const { setProps } = render(
<Slide
{...defaultProps}
easing={{
exit: 'cubic-bezier(0, 0, 1, 1)',
}}
onExit={handleExit}
/>,
);
setProps({ in: false });
expect(handleExit.args[0][0].style.transition).to.match(
/transform 195ms cubic-bezier\(0, 0, 1, 1\)( 0ms)?/,
);
});
});
describe('prop: direction', () => {
it('should update the position', () => {
const { container, setProps } = render(
<Slide {...defaultProps} in={false} direction="left" />,
);
const child = container.querySelector('#testChild');
const transition1 = child.style.transform;
setProps({
direction: 'right',
});
const transition2 = child.style.transform;
expect(transition1).not.to.equal(transition2);
});
});
describe('transform styling', () => {
const FakeDiv = React.forwardRef((props, ref) => {
const stubBoundingClientRect = (element) => {
if (element !== null) {
element.fakeTransform = 'none';
try {
stub(element, 'getBoundingClientRect').callsFake(() => ({
width: 500,
height: 300,
left: 300,
right: 800,
top: 200,
bottom: 500,
...props.rect,
}));
} catch (error) {
// already stubbed
}
}
};
const handleRef = useForkRef(ref, stubBoundingClientRect);
return <div {...props} ref={handleRef} />;
});
describe('handleEnter()', () => {
it('should set element transform and transition in the `left` direction', () => {
let nodeEnterTransformStyle;
const { setProps } = render(
<Slide
direction="left"
onEnter={(node) => {
nodeEnterTransformStyle = node.style.transform;
}}
>
<FakeDiv />
</Slide>,
);
setProps({ in: true });
expect(nodeEnterTransformStyle).to.equal(
`translateX(${global.innerWidth}px) translateX(-300px)`,
);
});
it('should set element transform and transition in the `right` direction', () => {
let nodeEnterTransformStyle;
const { setProps } = render(
<Slide
direction="right"
onEnter={(node) => {
nodeEnterTransformStyle = node.style.transform;
}}
>
<FakeDiv />
</Slide>,
);
setProps({ in: true });
expect(nodeEnterTransformStyle).to.equal('translateX(-800px)');
});
it('should set element transform and transition in the `up` direction', () => {
let nodeEnterTransformStyle;
const { setProps } = render(
<Slide
direction="up"
onEnter={(node) => {
nodeEnterTransformStyle = node.style.transform;
}}
>
<FakeDiv />
</Slide>,
);
setProps({ in: true });
expect(nodeEnterTransformStyle).to.equal(
`translateY(${global.innerHeight}px) translateY(-200px)`,
);
});
it('should set element transform and transition in the `down` direction', () => {
let nodeEnterTransformStyle;
const { setProps } = render(
<Slide
direction="down"
onEnter={(node) => {
nodeEnterTransformStyle = node.style.transform;
}}
>
<FakeDiv />
</Slide>,
);
setProps({ in: true });
expect(nodeEnterTransformStyle).to.equal('translateY(-500px)');
});
it('should reset the previous transition if needed', () => {
const childRef = React.createRef();
let nodeEnterTransformStyle;
const { setProps } = render(
<Slide
direction="right"
onEnter={(node) => {
nodeEnterTransformStyle = node.style.transform;
}}
>
<FakeDiv ref={childRef} />
</Slide>,
);
childRef.current.style.transform = 'translateX(-800px)';
setProps({ in: true });
expect(nodeEnterTransformStyle).to.equal('translateX(-800px)');
});
it('should set element transform in the `up` direction when element is offscreen', () => {
const childRef = React.createRef();
let nodeEnterTransformStyle;
const { setProps } = render(
<Slide
direction="up"
onEnter={(node) => {
nodeEnterTransformStyle = node.style.transform;
}}
>
<FakeDiv rect={{ top: -100 }} ref={childRef} />
</Slide>,
);
setProps({ in: true });
expect(nodeEnterTransformStyle).to.equal(
`translateY(${global.innerHeight}px) translateY(100px)`,
);
});
it('should set element transform in the `left` direction when element is offscreen', () => {
const childRef = React.createRef();
let nodeEnterTransformStyle;
const { setProps } = render(
<Slide
direction="left"
onEnter={(node) => {
nodeEnterTransformStyle = node.style.transform;
}}
>
<FakeDiv rect={{ left: -100 }} ref={childRef} />
</Slide>,
);
setProps({ in: true });
expect(nodeEnterTransformStyle).to.equal(
`translateX(${global.innerWidth}px) translateX(100px)`,
);
});
});
describe('handleExiting()', () => {
it('should set element transform and transition in the `left` direction', () => {
let nodeExitingTransformStyle;
const { setProps } = render(
<Slide
direction="left"
in
onExit={(node) => {
nodeExitingTransformStyle = node.style.transform;
}}
>
<FakeDiv />
</Slide>,
);
setProps({ in: false });
expect(nodeExitingTransformStyle).to.equal(
`translateX(${global.innerWidth}px) translateX(-300px)`,
);
});
it('should set element transform and transition in the `right` direction', () => {
let nodeExitingTransformStyle;
const { setProps } = render(
<Slide
direction="right"
in
onExit={(node) => {
nodeExitingTransformStyle = node.style.transform;
}}
>
<FakeDiv />
</Slide>,
);
setProps({ in: false });
expect(nodeExitingTransformStyle).to.equal('translateX(-800px)');
});
it('should set element transform and transition in the `up` direction', () => {
let nodeExitingTransformStyle;
const { setProps } = render(
<Slide
direction="up"
in
onExit={(node) => {
nodeExitingTransformStyle = node.style.transform;
}}
>
<FakeDiv />
</Slide>,
);
setProps({ in: false });
expect(nodeExitingTransformStyle).to.equal(
`translateY(${global.innerHeight}px) translateY(-200px)`,
);
});
it('should set element transform and transition in the `down` direction', () => {
let nodeExitingTransformStyle;
const { setProps } = render(
<Slide
direction="down"
in
onExit={(node) => {
nodeExitingTransformStyle = node.style.transform;
}}
>
<FakeDiv />
</Slide>,
);
setProps({ in: false });
expect(nodeExitingTransformStyle).to.equal('translateY(-500px)');
});
});
});
describe('mount', () => {
it('should work when initially hidden', () => {
const childRef = React.createRef();
render(
<Slide in={false}>
<div ref={childRef}>Foo</div>
</Slide>,
);
const transition = childRef.current;
expect(transition.style.visibility).to.equal('hidden');
expect(transition.style.transform).not.to.equal(undefined);
});
});
describe('resize', () => {
let clock;
beforeEach(() => {
clock = useFakeTimers();
});
afterEach(() => {
clock.restore();
});
it('should recompute the correct position', () => {
const { container } = render(
<Slide direction="up" in={false}>
<div id="testChild">Foo</div>
</Slide>,
);
window.dispatchEvent(new window.Event('resize', {}));
clock.tick(166);
const child = container.querySelector('#testChild');
expect(child.style.transform).not.to.equal(undefined);
});
it('should take existing transform into account', () => {
const element = {
fakeTransform: 'transform matrix(1, 0, 0, 1, 0, 420)',
getBoundingClientRect: () => ({
width: 500,
height: 300,
left: 300,
right: 800,
top: 1200,
bottom: 1500,
}),
style: {},
};
setTranslateValue('up', element);
expect(element.style.transform).to.equal(
`translateY(${global.innerHeight}px) translateY(-780px)`,
);
});
it('should do nothing when visible', () => {
render(<Slide {...defaultProps} />);
window.dispatchEvent(new window.Event('resize', {}));
clock.tick(166);
});
});
describe('server-side', () => {
it('should be initially hidden', () => {
const { container } = render(
<Slide {...defaultProps} in={false}>
<div id="with-slide" />
</Slide>,
);
const slide = container.querySelector('#with-slide');
expect(slide.style).to.have.property('visibility', 'hidden');
});
});
});
| callemall/material-ui | packages/material-ui/src/Slide/Slide.test.js | JavaScript | mit | 14,623 |
version https://git-lfs.github.com/spec/v1
oid sha256:5b8dc53d42e16f198773498e313e5e2e4cb1bfb48265ad3b53dea7e2224e1c17
size 3414
| yogeshsaroya/new-cdnjs | ajax/libs/openlayers/2.11/lib/OpenLayers/Lang/hsb.min.js | JavaScript | mit | 129 |
/*!
* random-range <https://github.com/jonschlinkert/random-range>
*
* Copyright (c) 2014 Jon Schlinkert, contributors.
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(max, repeat) {
repeat = repeat || 1;
var arr = [];
for (var i = 0; i < repeat; i++) {
arr.push(randRange(max));
}
if (arr.length === 1) {
return arr[0];
}
return arr;
};
function randRange(max) {
var from = randInt(0, max);
var to = randInt(from, max);
return [from, to];
}
function randInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
| jonschlinkert/random-range | index.js | JavaScript | mit | 602 |
/**
* <app-messages> ディレクティブ。SharedService内のmessages情報を元に表示
*/
const AppMessagesDirective = function(SharedService) {
//return Directive Definition Object.
return {
restrict : 'E',
template: require('./template.html'),
scope : true,
link : function(scope, elements, attr) {
//共通サービスであるところの SharedServiceを、ディレクティブのスコープとして生やす
scope.SharedService = SharedService;
}
};
}
AppMessagesDirective.$inject = ['SharedService'];
export default AppMessagesDirective;
| mtakeshi-ibm/app-starter-kit-image-recognition | app/src/app/components/directives/appMessages/index.js | JavaScript | mit | 614 |
// Rayson package (c) Tomasz Zduńczyk <tomasz@zdunczyk.org>
// Please view the LICENSE file distributed with this code.
require('../bootstrap.js');
describe("Operation on stream", function() {
var rayson_stream = null;
beforeEach(function() {
rayson_stream = new rayson.stream([ 34, 55, 23, 89, 23 ]);
});
it("getting bytes shouldn't change its size", function() {
var size_before = rayson_stream.size();
rayson_stream.getByte();
rayson_stream.getByte(3);
expect(rayson_stream.size()).toEqual(size_before);
});
it("reading bytes removes them from stream", function() {
expect(rayson_stream.readByte()).toEqual(34);
expect(rayson_stream.readByte(rayson_stream.size())).toEqual([ 55, 23, 89, 23 ]);
});
it("should return true for empty stream", function() {
stream = new rayson.stream([]);
expect(stream.empty()).toEqual(true);
});
}); | zdunczyk/rayson | tests/unit/stream-spec.js | JavaScript | mit | 971 |
'use strict';
/*
Aggie behavior, mob will attack whatever creature enters the room,
can specifiy min/max target level in behavior definition.
If mob.attackOnVisit is false then the mob will only look for a target during
the onAlive tick. If mob.preventOnAlive is toggled to true then the mob will
only attack if something enters the room from an adjacent room (entering the room
via portal or the like would then not trigger the aggressive behavior).
Setting mob.mobAggressive to true will empower the mob to attack other mobs.
Setting revenge to true limits the mob to only being aggie against the thing that attacked it last.
*/
module.exports = {
attackOnVisit: true,
attackOnAlive: true,
playerAggressive: true,
mobAggressive: false,
onlyAttackLarger: false,
onlyAttackSmaller: false,
onlyAttackSleeping: false,
revenge: false,
onVisit: function(World, behavior, mob, roomObj, target, incomingRoomObj, command) {
var target;
if (!mob.fighting) {
if (roomObj.playersInRoom.length && behavior.playerAggressive) {
target = roomObj.playersInRoom[World.dice.roll(1, roomObj.playersInRoom.length) - 1];
} else if (roomObj.monsters.length && behavior.mobAggressive) {
target = roomObj.monsters[World.dice.roll(1, roomObj.monsters.length) - 1];
}
if (behavior.onlyAttackLarger && mob.size.value >= target.size.value) {
target = false;
} else if (behavior.onlyAttackSmaller && mob.size.value <= target.size.value) {
target = false;
}
if (target && behavior.attackOnVisit && mob.position === 'standing' && target.roomid === mob.roomid) {
if (!mob.revenge) {
World.addCommand({
cmd: 'kill',
arg: target.name,
roomObj: roomObj,
target: target
}, mob);
} else if (target.refId === behavior.lastAttackedBy) {
World.addCommand({
cmd: 'kill',
arg: target.name,
roomObj: roomObj,
target: target
}, mob);
}
}
}
},
onAlive: function(World, behavior, mob, roomObj) {
var target;
if (!mob.fighting) {
if (roomObj.playersInRoom.length && behavior.playerAggressive) {
target = roomObj.playersInRoom[World.dice.roll(1, roomObj.playersInRoom.length) - 1];
} else if (roomObj.monsters.length && behavior.mobAggressive) {
target = roomObj.monsters[World.dice.roll(1, roomObj.monsters.length) - 1];
}
if (behavior.onlyAttackLarger && mob.size.value >= target.size.value) {
target = false;
} else if (behavior.onlyAttackSmaller && mob.size.value <= target.size.value) {
target = false;
}
if (behavior.onlyAttackSleeping === true && target.position !== 'sleeping') {
target = false;
}
if (target && behavior.attackOnAlive && mob.position === 'standing' && target.roomid === mob.roomid) {
if (!mob.revenge) {
World.addCommand({
cmd: 'kill',
arg: target.name,
roomObj: roomObj,
target: target
}, mob);
} else if (target.refId === behavior.lastAttackedBy) {
World.addCommand({
cmd: 'kill',
arg: target.name,
roomObj: roomObj,
target: target
}, mob);
}
}
}
}
};
| MoreOutput/RockMUD | ai/aggie.js | JavaScript | mit | 3,126 |
const ICON_HTML = '<div class="icon"><div class="icon__next"></div></div>';
const ROOT_DIR_HTML = `
<div class="icon icon--button icon--large">
<div class="icon__root-dir"></div>
</div>`;
const TOGGLE_BTN_HTML = `
<div class="breadcrumb__toggle-btn">
${ICON_HTML}
<div class="breadcrumb__text">...</div>
</div>`;
/**
* @param {Object[]} breadcrumbs
* @param {string} breadcrumbs[].path
* @param {boolean} breadcrumbs[].visible
* @param {number} maxWidth
*/
function isBreadcrumbOverflow(breadcrumbs, maxWidth) {
const hiddenContainer = $('.breadcrumb__hidden');
const showToggleButton = breadcrumbs.includes(e => e.visible === false);
const els = [ROOT_DIR_HTML];
if (showToggleButton) {
els.push(TOGGLE_BTN_HTML);
}
breadcrumbs.filter(e => e.visible).forEach((breadcrumb) => {
els.push(
ICON_HTML,
`<div class="breadcrumb__text">${breadcrumb.path}</div>`,
);
});
const html = `<div class="breadcrumb">${els.join('')}</div>`;
hiddenContainer.html(html);
const width = hiddenContainer.outerWidth();
return width >= maxWidth;
}
/**
* @param {Object[]} breadcrumbs
* @param {string} breadcrumbs[].path
* @param {boolean} breadcrumbs[].visible
*/
function adjustBreadcrumbWidth(breadcrumbs) {
if (breadcrumbs === null || breadcrumbs.length <= 1) {
return breadcrumbs;
}
const maxWidth = $('.breadcrumb').outerWidth();
const { length } = breadcrumbs;
let index = breadcrumbs.findIndex(e => e.visible);
while (index < length - 1 && isBreadcrumbOverflow(breadcrumbs, maxWidth)) {
breadcrumbs[index].visible = false;
index += 1;
}
return breadcrumbs;
}
export default adjustBreadcrumbWidth;
| Kloudless/file-explorer | src/picker/js/breadcrumb.js | JavaScript | mit | 1,689 |
define(['angular'], function(angular){
angular.module("dropboxPicker", [])
.provider("DropBoxSettings", function() {
this.linkType = 'preview',
this.multiselect = true,
this.extensions = ['images', 'video'],
this.$get = function() {
return {
linkType: this.linkType,
multiselect: this.multiselect,
extensions: this.extensions
}
},
this.configure = function(e) {
for (key in e) this[key] = e[key]
}
})
.directive("dropBoxPicker", ["DropBoxSettings",
function(DropBoxSettings) {
return {
restrict: "A",
scope: {
dbpickerFiles: "="
},
link: function(scope, element, attrs) {
function instanciate() {
Dropbox.choose(dropboxOptions);
}
var dropboxOptions = {
success: dropboxsuccess,
cancel: function() {},
linkType : DropBoxSettings.linkType,
multiselect: DropBoxSettings.multiselect,
extensions : DropBoxSettings.extensions
};
function dropboxsuccess(files){
scope.$apply(function() {
for (var i = 0; i < files.length; i++){
scope.dbpickerFiles.push(files[i]);
}
});
};
element.bind("click", function() {
instanciate()
})
}
}
}])
});
| firebull81/viktoria | app/scripts/ui/dropbox-picker.js | JavaScript | mit | 1,506 |
'use strict';
angular.module('angularInputValidator.directives.customValidators', [])
.directive('nmCustomValidators', function(nmCustomValidators){
return {
require: '?ngModel',
restrict: 'A',
scope: {
nmCustomValidators: '=',
},
link: function(scope, elm, attrs, ctrl){
if(!ctrl) return;
var validations = [],
allowedFails = 0,
runValidators = function(modelValue){
var fails = _.reduce(validations, function(memo, validation){
validation.value = ctrl.$isEmpty(modelValue) || validation.validator.fn(modelValue);
return memo + !validation.value;
}, 0);
_.each(validations, function(validation){
ctrl.$setValidity(validation.validator.name, (fails <= allowedFails) || validation.value);
});
},
validatorsChange = function(newValidators, oldValidators){
setValidators(newValidators);
removeValidations(_.difference(oldValidators, newValidators));
runValidators(ctrl.$modelValue);
},
removeValidations = function(oldValidators){
_.each(oldValidators, function(validatorName){
ctrl.$setValidity(validatorName, true);
});
},
setValidators = function(newValidators){
validations = _.map(newValidators, function(validatorName){
return {validator: nmCustomValidators.getRule(validatorName)};
});
};
scope.$watch('nmCustomValidators', validatorsChange);
scope.$watch(function(){return ctrl.$modelValue;}, runValidators);
attrs.$observe('nmAllowFails', function(newAllowedFails){
allowedFails = (newAllowedFails) ? parseInt(newAllowedFails) : 0;
});
}
};
}); | Nimble-Momonga/angular-input-validator | src/angular-input-validator/directives/customValidators.directive.js | JavaScript | mit | 1,655 |
CMS.ui.attach.tinyMCEinit = function(){
tinyMCE.init({
language: 'ru',
// General options
mode : "textareas",
theme : "advanced",
plugins : "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
// Theme options
theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing : true,
content_css : CMS.settings.stylesheet,
file_browser_callback : 'elFinderBrowser',
document_base_url: '/',
convert_urls : false
});
}
function elFinderBrowser (field_name, url, type, win) {
var elfinder_url = '/admin/files?minimal=true&tinymce=true'; // use an absolute path!
tinyMCE.activeEditor.windowManager.open({
file: elfinder_url,
title: 'elFinder 2.0',
width: 900,
height: 450,
resizable: 'yes',
inline: 'yes', // This parameter only has an effect if you use the inlinepopups plugin!
popup_css: false, // Disable TinyMCE's default popup CSS
close_previous: 'no'
}, {
window: win,
input: field_name
});
return false;
} | Doka-NT/SkobkaCMS | modules/tinymce/init.js | JavaScript | mit | 2,223 |
import React from 'react';
import { Form, Row, Col, Input, Button,DatePicker } from 'antd';
const FormItem = Form.Item;
class AdvancedSearchForm extends React.Component {
constructor(props){
super(props)
}
render() {
return (
<Form horizontal className="ant-advanced-search-form">
<Row gutter={16}>
<Col sm={8}>
<FormItem
label="搜索名称"
labelCol={{ span: 10 }}
wrapperCol={{ span: 14 }}
>
<Input placeholder="请输入搜索名称" size="default" />
</FormItem>
<FormItem
label="较长搜索名称"
labelCol={{ span: 10 }}
wrapperCol={{ span: 14 }}
>
<DatePicker size="default" />
</FormItem>
<FormItem
label="搜索名称"
labelCol={{ span: 10 }}
wrapperCol={{ span: 14 }}
>
<Input placeholder="请输入搜索名称" size="default" />
</FormItem>
</Col>
<Col sm={8}>
<FormItem
label="搜索名称"
labelCol={{ span: 10 }}
wrapperCol={{ span: 14 }}
>
<Input placeholder="请输入搜索名称" size="default" />
</FormItem>
<FormItem
label="较长搜索名称"
labelCol={{ span: 10 }}
wrapperCol={{ span: 14 }}
>
<DatePicker size="default" />
</FormItem>
<FormItem
label="搜索名称"
labelCol={{ span: 10 }}
wrapperCol={{ span: 14 }}
>
<Input placeholder="请输入搜索名称" size="default" />
</FormItem>
</Col>
<Col sm={8}>
<FormItem
label="搜索名称"
labelCol={{ span: 10 }}
wrapperCol={{ span: 14 }}
>
<Input placeholder="请输入搜索名称" size="default" />
</FormItem>
<FormItem
label="较长搜索名称"
labelCol={{ span: 10 }}
wrapperCol={{ span: 14 }}
>
<DatePicker size="default" />
</FormItem>
<FormItem
label="搜索名称"
labelCol={{ span: 10 }}
wrapperCol={{ span: 14 }}
>
<Input placeholder="请输入搜索名称" size="default" />
</FormItem>
</Col>
</Row>
<Row>
<Col span={12} offset={12} style={{ textAlign: 'right' }}>
<Button type="primary" htmlType="submit">搜索</Button>
<Button>清除条件</Button>
</Col>
</Row>
</Form>
);
}
}
export default AdvancedSearchForm | ZCY-frontend/generator-zcyrrrw | generators/app/templates/src/components/Search/Search.js | JavaScript | mit | 2,907 |
const ValidateRefersDoValidateExample = React.createClass({
handleClick() {
let result = this.validateRefersRef.doValidate();
alert('校验状态为:' + (result ? '成功' : '失败'));
},
render() {
return (
<div>
<button onClick={this.handleClick}>主动校验</button>
<ValidateRefers
ref={(c) => this.validateRefersRef = c}
validators={[
{ type: 'required' },
]}
referConditions={{
refCode: 'user',
refType: 'tree',
rootName: '部门主管',
}}
referDataUrl="http://172.20.4.220/ficloud/refbase_ctr/queryRefJSON"
selected={[]}
/>
</div>
);
}
});
ReactDOM.render(<ValidateRefersDoValidateExample />, mountNode);
| yyssc/ssc-grid | docs/examples/ValidateRefersDoValidate.js | JavaScript | mit | 794 |
var basename = require("path").basename
var fs = require("fs")
var filed = require("filed")
// this should be a module on npm
module.exports = serveFileDownload
function serveFileDownload(req, res, uri, cb) {
fs.stat(uri, function (err, stat) {
// 404
if (err && err.code === "ENOENT") {
res.statusCode = 404
return res.end("Cant find that file, sorry!")
} else if (err) {
return cb(err)
}
res.setHeader("Content-Disposition", "attachment; filename=\"" +
basename(uri) + "\"")
filed(uri).pipe(res)
})
}
| maxogden/http-framework | examples/downloads/serve-file-download.js | JavaScript | mit | 610 |
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*
* This is log state object
*
* Its configured by incoming object and return turned on statuses
*/
Object.defineProperty(exports, "__esModule", {
value: true
});
var _type_detector = require('./type_detector');
var _type_detector2 = _interopRequireDefault(_type_detector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var LogState = function () {
function LogState(options) {
_classCallCheck(this, LogState);
// NB - options may have some another settings from main object - just ignore it
this.options = options;
this.state = {
DEBUGGING: false,
LOGGING: false,
TIMING: false,
WARNING: false
};
this.processOptions();
this.initState();
}
/*
* Complex options processor
*/
_createClass(LogState, [{
key: 'processOptions',
value: function processOptions() {
if (this.options && this.options.debug === true) {
this.state.DEBUGGING = true;
this.options.timing = true;
this.options.logging = true;
this.options.warning = true;
} else {
this.state.debug = false;
}
}
/*
* Set object state by options
*/
}, {
key: 'initState',
value: function initState() {
// for benchmarking
if (this.options) {
if (this.options.timing === true && (0, _type_detector2.default)(console.time) === 'FUNCTION') {
this.state.TIMING = true;
}
if (this.options.logging === true && (0, _type_detector2.default)(console.log) === 'FUNCTION') {
this.state.LOGGING = true;
}
if (this.options.warning === true && (0, _type_detector2.default)(console.warn) === 'FUNCTION') {
this.state.WARNING = true;
}
}
}
/*
* Return statement is logger must do some thing
*/
}, {
key: 'mustDo',
value: function mustDo(stateName) {
var upperStateName = stateName.toUpperCase();
var res = this.state[upperStateName];
if ((0, _type_detector2.default)(res) !== 'BOOLEAN') {
throw Error('dont know |' + stateName + '| state');
}
return res;
}
}]);
return LogState;
}();
exports.default = LogState; | Meettya/TinyData | lib/helpers/log_state.js | JavaScript | mit | 5,245 |
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M2 16v2h20v-2H2zm0-5v2h20v-2H2zm0-5v2h20V6H2z" />
, 'DehazeOutlined');
| kybarg/material-ui | packages/material-ui-icons/src/DehazeOutlined.js | JavaScript | mit | 191 |
const test = require('tape')
const vectors = [{
input: '',
keccak224: 'f71837502ba8e10837bdd8d365adb85591895602fc552b48b7390abd',
keccak256: 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470',
keccak384: '2c23146a63a29acf99e73b88f8c24eaa7dc60aa771780ccc006afbfa8fe2479b2dd2b21362337441ac12b515911957ff',
keccak512: '0eab42de4c3ceb9235fc91acffe746b29c29a8c366b7c60e4e67c466f36a4304c00fa9caf9d87976ba469bcbe06713b435f091ef2769fb160cdab33d3670680e'
}]
module.exports = (name, createHash) => {
for (let i = 0; i < vectors.length; ++i) {
const vector = vectors[i]
const data = Buffer.from(vector.input, 'hex')
for (const hash of ['keccak224', 'keccak256', 'keccak384', 'keccak512']) {
test(`${name} ${hash} vector#${i}`, (t) => {
t.equal(createHash(hash).update(data).digest('hex'), vector[hash])
t.end()
})
}
}
}
| cryptocoinjs/keccak | test/vectors-keccak.js | JavaScript | mit | 886 |
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
} = React;
var DeviceMotion = require('./DeviceMotion.ios.js');
var DeviceMotionExample = React.createClass({
getInitialState: function () {
return {
motionData: null
};
},
componentDidMount: function () {
DeviceMotion.startDeviceMotionUpdates(1000/60, (data) => {
this.setState({
motionData: data,
});
});
},
render: function() {
var motionData = this.state.motionData;
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Device Motion for React Native
</Text>
<Text style={styles.instructions}>
This app shows three bars below corresponding to roll, pitch and yaw of the device.
</Text>
{this.state.motionData ?
<View>
<View style={{backgroundColor: 'red', height: 10, width: (motionData.attitude.roll+1)*100}} />
<View style={{backgroundColor: 'green', height: 10, width: (motionData.attitude.pitch+1)*100}} />
<View style={{backgroundColor: 'blue', height: 10, width: (motionData.attitude.yaw+1)*100}} />
</View>
: null}
<Text style={styles.instructions}>
Make sure you try this out on an iOS device. No motion data in Simulator.
</Text>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
// alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('RNTDeviceMotion', () => DeviceMotionExample);
| paramaggarwal/react-native-device-motion | index.ios.js | JavaScript | mit | 1,905 |
'use strict'
const gulp = require('gulp')
const notify = require('gulp-notify')
/**
* Notify that all tasks have been completed
*/
gulp.task('notify', function (cb) {
if (process.env.NODE_ENV !== 'development') {
cb()
} else {
return gulp.src('./gulpfile.js', {read: false})
.pipe(notify('Finished all tasks.'))
}
})
| MrSlide/project-unum | gulp/notify.js | JavaScript | mit | 339 |
/**
* GDE Sample: Chrome extension Google APIs.
*
* This Chrome extension is example code of how to use Chrome's identity API
* to get access to Google's web APIs.
*/
/**
* Create a basic Desktop notification.
*
* @param {object} options
* @value {string} iconUrl - Image URL to display in notification.
* @value {string} title - Notification header.
* @value {string} message - Notification message.
*/
function createBasicNotification(options) {
var notificationOptions = {
'type': 'basic',
'iconUrl': options.iconUrl, // Relative to Chrome dir or remote URL must be whitelisted in manifest.
'title': options.title,
'message': options.message,
'isClickable': true,
};
chrome.notifications.create(options.id, notificationOptions, function(notificationId) {});
}
/**
* Show a notification that prompts the user to authenticate their Google account.
*/
function showAuthNotification() {
var options = {
'id': 'start-auth',
'iconUrl': 'img/developers-logo.png',
'title': 'GDE Sample: Chrome extension Google APIs',
'message': 'Click here to authorize access to Gmail',
};
createBasicNotification(options);
}
/**
* Show a notification that authentication was completed successfully.
*
* @param {object} profile
* @value {string} imageUrl - Google+ profile image URL.
* @value {string} displayName - Google+ profile full name.
*/
function showProfileNotification(profile) {
var options = {
'id': 'show-profile',
'iconUrl': profile.imageUrl,
'title': 'Welcome ' + profile.displayName,
'message': 'Gmail checker is now active',
};
createBasicNotification(options);
}
/**
* Triggered anytime user clicks on a desktop notification.
*/
function notificationClicked(notificationId){
// User clicked on notification to start auth flow.
if (notificationId === 'start-auth') {
getAuthTokenInteractive();
}
clearNotification(notificationId);
}
/**
* Clear a desktop notification.
*
* @param {string} notificationId - Id of notification to clear.
*/
function clearNotification(notificationId) {
chrome.notifications.clear(notificationId, function(wasCleared) {});
}
/**
* Get users access_token.
*
* @param {object} options
* @value {boolean} interactive - If user is not authorized ext, should auth UI be displayed.
* @value {function} callback - Async function to receive getAuthToken result.
*/
function getAuthToken(options) {
chrome.identity.getAuthToken({ 'interactive': options.interactive }, options.callback);
}
/**
* Get users access_token in background with now UI prompts.
*/
function getAuthTokenSilent() {
getAuthToken({
'interactive': false,
'callback': getAuthTokenSilentCallback,
});
}
/**
* Get users access_token or show authorize UI if access has not been granted.
*/
function getAuthTokenInteractive() {
getAuthToken({
'interactive': true,
'callback': getAuthTokenInteractiveCallback,
});
}
/**
* If user is authorized, start getting Gmail count.
*
* @param {string} token - Users access_token.
*/
function getAuthTokenSilentCallback(token) {
// Catch chrome error if user is not authorized.
if (chrome.runtime.lastError) {
showAuthNotification();
} else {
updateLabelCount(token);
}
}
/**
* User finished authorizing, start getting Gmail count.
*
* @param {string} token - Current users access_token.
*/
function getAuthTokenInteractiveCallback(token) {
// Catch chrome error if user is not authorized.
if (chrome.runtime.lastError) {
showAuthNotification();
} else {
updateLabelCount(token);
getProfile(token);
}
}
/**
* Get the current users Google+ profile to welcome them.
*
* https://developers.google.com/+/api/latest/people/get
*
* @param {string} token - Current users access_token.
*/
function getProfile(token) {
get({
'url': 'https://www.googleapis.com/plus/v1/people/me',
'callback': getProfileCallback,
'token': token,
});
}
/**
* Got users Google+ profile, show welcome desktop notification.
*
* https://developers.google.com/+/api/latest/people/get
*
* @param {object} person - Google+ person resource.
*/
function getProfileCallback(person) {
var options = {
'displayName': person.displayName,
'imageUrl': person.image.url + '0',
};
showProfileNotification(options);
}
/**
* Get details about the users Gmail inbox.
*
* https://developers.google.com/gmail/api/v1/reference/users/labels/get
*
* @param {string} token - Current users access_token.
*/
function updateLabelCount(token) {
get({
'url': 'https://www.googleapis.com/gmail/v1/users/me/labels/INBOX',
'callback': updateLabelCountCallback,
'token': token,
});
}
/**
* Got users Gmail inbox details.
*
* https://developers.google.com/gmail/api/v1/reference/users/labels/get
*
* @param {object} label - Gmail users.labels resource.
*/
function updateLabelCountCallback(label) {
setBadgeCount(label.threadsUnread);
}
/**
* Make an authenticated HTTP GET request.
*
* @param {object} options
* @value {string} url - URL to make the request to. Must be whitelisted in manifest.json
* @value {string} token - Google access_token to authenticate request with.
* @value {function} callback - Function to receive response.
*/
function get(options) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// JSON response assumed. Other APIs may have different responses.
options.callback(JSON.parse(xhr.responseText));
} else {
console.log('get', xhr.readyState, xhr.status, xhr.responseText);
}
};
xhr.open("GET", options.url, true);
// Set standard Google APIs authentication header.
xhr.setRequestHeader('Authorization', 'Bearer ' + options.token);
xhr.send();
}
/**
* Set browserAction status.
*
* @param {object} options
* @value {string} text - Up to four letters to be visible on browserAction.
* @value {string} color - Text background color. E.g. #FF0000
* @value {string} title - The hover tooltip.
*/
function setBadge(options) {
chrome.browserAction.setBadgeText({ 'text': options.text });
chrome.browserAction.setBadgeBackgroundColor({ 'color': options.color });
chrome.browserAction.setTitle({ 'title': options.title });
}
/**
* Set the browserAction status for unauthenticated user.
*/
function setBadgeNoAuth() {
setBadge({
'text': '?',
'color': '#9E9E9E',
'title': 'Click to authorize Gmail',
});
}
/**
* Set the browserAction status for Gmail label count.
*
* @param {int} count - The count of unread emails in label.
*/
function setBadgeCount(count) {
var color = '#9E9E9E';
var title = 'No unread mail';
if (count > 0) {
color = '#F44336';
title = count + ' unread mail';
}
setBadge({
'text': count + '', // Cast count int to string.
'color': color,
'title': title,
});
}
/**
* User clicked on browserAction button. Check if user is authenticated.
*
* @param {object} tab - Chrome tab resource.
*/
function browserActionClicked(tab) {
getAuthToken({
'interactive': false,
'callback': getBrowserActionAuthTokenCallback,
});
}
/**
* If user is authenticated open Gmail in new tab or start auth flow.
*
* @param {string} token - Current users access_token.
*/
function getBrowserActionAuthTokenCallback(token) {
if (chrome.runtime.lastError) {
getAuthTokenInteractive();
} else {
chrome.tabs.create({ 'url': 'https://mail.google.com' });
}
}
/**
* Chrome alarm has triggered.
*
* @param {object} alarm - Chrome alarm resource.
*/
function onAlarm(alarm) {
// Check Gmail for current unread count.
if (alarm.name === 'update-count') {
getAuthTokenSilent();
}
}
/**
* Wire up Chrome event listeners.
*/
chrome.notifications.onClicked.addListener(notificationClicked);
chrome.browserAction.onClicked.addListener(browserActionClicked);
chrome.alarms.onAlarm.addListener(onAlarm);
/**
* Perform initial auth checks and set alarm for periodic updates.
*/
setBadgeNoAuth();
getAuthTokenSilent();
chrome.alarms.create('update-count', { 'delayInMinutes': 15, 'periodInMinutes': 15 });
| GoogleDeveloperExperts/chrome-extension-google-apis | js/background.js | JavaScript | mit | 8,539 |
import React, { Component, PropTypes } from 'react';
import SignUpForm from './SignUpForm';
class SignUpPage extends Component {
constructor(props, context) {
super(props, context);
this.state = {
errors: {},
user: {
email: '',
password: '',
confirm_password: ''
}
};
this.processForm = this.processForm.bind(this);
this.changeUser = this.changeUser.bind(this);
}
processForm(event) {
event.preventDefault();
const email = this.state.user.email;
const password = this.state.user.password;
const confirm_password = this.state.user.confirm_password;
if (password !== confirm_password) {
return;
}
fetch('http://localhost:3000/auth/signup', {
method: 'POST',
cache: false,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: this.state.user.email,
password: this.state.user.password
})
}).then(response => {
if (response.status === 200) {
this.setState({
errors: {}
});
// change the current URL to /login
// console.log(this);
this.context.router.replace('/login');
} else {
response.json().then(function(json) {
console.log(json);
const errors = json.errors ? json.errors : {};
errors.summary = json.message;
console.log(this.state.errors);
this.setState({errors});
}.bind(this));
}
});
}
changeUser(event) {
const field = event.target.name;
const user = this.state.user;
user[field] = event.target.value;
this.setState({
user
});
if (this.state.user.password !== this.state.user.confirm_password) {
const errors = this.state.errors;
errors.password = 'Password and Confirm Password must match.';
this.setState({errors});
} else {
const errors = this.state.errors;
errors.password = ''; // reset password error message
this.setState({errors});
}
}
render() {
return (
<div>
<SignUpForm
onSubmit={this.processForm}
onChange={this.changeUser}
errors={this.state.errors}
/>
</div>
);
}
}
SignUpPage.contextTypes = {
router: PropTypes.object.isRequired
};
export default SignUpPage; | ThomasWu/PersonalNewsWeb | frontend/web-client/src/SignUp/SignUpPage.js | JavaScript | mit | 2,855 |
import TumblrPost from './tumblr-post';
export default TumblrPost.extend({
classNames: ['tumblr-post-photo']
});
| elwayman02/ember-tumblr | addon/components/tumblr-post-photo.js | JavaScript | mit | 116 |
require(['config'], function(){
require(['bootstrap', 'backendRouter']);
});
| jrbellido/bistro | client/static/js/backend.js | JavaScript | mit | 79 |
import FirebaseSerializer from 'emberfire/serializers/firebase';
export default FirebaseSerializer.extend({
attrs: {
ratings: { embedded: 'always' },
wannaSees: { embedded: 'always' }
}
}); | JaxonWright/CineR8 | app/serializers/user.js | JavaScript | mit | 202 |
var common = require("./common");
var moment = require("moment");
exports.upload_feedback = function(req, res) {
if (!(req.param("name") && req.param("email") && req.param("message"))) {
res.send({
status: 0,
message: "You must fill out all of the fields."
});
return;
}
common.db.collection("feedback").insert({
name: req.param("name"),
email: req.param("email"),
message: req.param("message"),
timestamp: moment().format()
}, { w: 1 }, function(err, data) {
if (err) {
res.send({
status: 0,
message: "Internal error"
});
return;
}
res.send({
status: 1,
message: "Thanks for your feedback!"
});
return;
});
}; | CTCTF/Backend | api/feedback.js | JavaScript | mit | 669 |
'use strict';
angular.module('seaWebApp')
.factory('User', function ($http, $location) {
var user = {
isLoggedIn: false,
username: ''
};
return {
username: function () {
return user.username;
},
isLoggedIn: function() {
return user.isLoggedIn;
},
login: function (username, token) {
user.isLoggedIn = true;
user.username = username;
$http.defaults.headers.common['Authorization'] = 'Token ' + token;
$location.path( '/home' );
},
logout: function () {
user.isLoggedIn = false;
user.username = '';
$http.defaults.headers.common['Authorization'] = '';
$location.path( '/login' );
}
}
});
| grollins/sea-web-angular | app/scripts/services/user.js | JavaScript | mit | 855 |
// Zepto.js
// (c) 2010-2014 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
;(function($){
var $$ = $.zepto.qsa, _zid = 1, undefined,
slice = Array.prototype.slice,
isFunction = $.isFunction,
isString = function(obj){ return typeof obj == 'string' },
handlers = {},
specialEvents={},
focusinSupported = 'onfocusin' in window,
focus = { focus: 'focusin', blur: 'focusout' },
hover = { mouseenter: 'mouseover', mouseleave: 'mouseout' }
specialEvents.click = specialEvents.mousedown = specialEvents.mouseup = specialEvents.mousemove = 'MouseEvents'
function zid(element) {
return element._zid || (element._zid = _zid++)
}
function findHandlers(element, event, fn, selector) {
event = parse(event)
if (event.ns) var matcher = matcherFor(event.ns)
return (handlers[zid(element)] || []).filter(function(handler) {
return handler
&& (!event.e || handler.e == event.e)
&& (!event.ns || matcher.test(handler.ns))
&& (!fn || zid(handler.fn) === zid(fn))
&& (!selector || handler.sel == selector)
})
}
function parse(event) {
var parts = ('' + event).split('.')
return {e: parts[0], ns: parts.slice(1).sort().join(' ')}
}
function matcherFor(ns) {
return new RegExp('(?:^| )' + ns.replace(' ', ' .* ?') + '(?: |$)')
}
function eventCapture(handler, captureSetting) {
return handler.del &&
(!focusinSupported && (handler.e in focus)) ||
!!captureSetting
}
function realEvent(type) {
return hover[type] || (focusinSupported && focus[type]) || type
}
function add(element, events, fn, data, selector, delegator, capture){
var id = zid(element), set = (handlers[id] || (handlers[id] = []))
events.split(/\s/).forEach(function(event){
if (event == 'ready') return $(document).ready(fn)
var handler = parse(event)
handler.fn = fn
handler.sel = selector
// emulate mouseenter, mouseleave
if (handler.e in hover) fn = function(e){
var related = e.relatedTarget
if (!related || (related !== this && !$.contains(this, related)))
return handler.fn.apply(this, arguments)
}
handler.del = delegator
var callback = delegator || fn
handler.proxy = function(e){
e = compatible(e)
if (e.isImmediatePropagationStopped()) return
e.data = data
var result = callback.apply(element, e._args == undefined ? [e] : [e].concat(e._args))
if (result === false) e.preventDefault(), e.stopPropagation()
return result
}
handler.i = set.length
set.push(handler)
if ('addEventListener' in element)
element.addEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture))
})
}
function remove(element, events, fn, selector, capture){
var id = zid(element)
;(events || '').split(/\s/).forEach(function(event){
findHandlers(element, event, fn, selector).forEach(function(handler){
delete handlers[id][handler.i]
if ('removeEventListener' in element)
element.removeEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture))
})
})
}
$.event = { add: add, remove: remove }
$.proxy = function(fn, context) {
if (isFunction(fn)) {
var proxyFn = function(){ return fn.apply(context, arguments) }
proxyFn._zid = zid(fn)
return proxyFn
} else if (isString(context)) {
return $.proxy(fn[context], fn)
} else {
throw new TypeError("expected function")
}
}
$.fn.bind = function(event, data, callback){
return this.on(event, data, callback)
}
$.fn.unbind = function(event, callback){
return this.off(event, callback)
}
$.fn.one = function(event, selector, data, callback){
return this.on(event, selector, data, callback, 1)
}
var returnTrue = function(){return true},
returnFalse = function(){return false},
ignoreProperties = /^([A-Z]|returnValue$|layer[XY]$)/,
eventMethods = {
preventDefault: 'isDefaultPrevented',
stopImmediatePropagation: 'isImmediatePropagationStopped',
stopPropagation: 'isPropagationStopped'
}
function compatible(event, source) {
if (source || !event.isDefaultPrevented) {
source || (source = event)
$.each(eventMethods, function(name, predicate) {
var sourceMethod = source[name]
event[name] = function(){
this[predicate] = returnTrue
return sourceMethod && sourceMethod.apply(source, arguments)
}
event[predicate] = returnFalse
})
if (source.defaultPrevented !== undefined ? source.defaultPrevented :
'returnValue' in source ? source.returnValue === false :
source.getPreventDefault && source.getPreventDefault())
event.isDefaultPrevented = returnTrue
}
return event
}
function createProxy(event) {
var key, proxy = { originalEvent: event }
for (key in event)
if (!ignoreProperties.test(key) && event[key] !== undefined) proxy[key] = event[key]
return compatible(proxy, event)
}
$.fn.delegate = function(selector, event, callback){
return this.on(event, selector, callback)
}
$.fn.undelegate = function(selector, event, callback){
return this.off(event, selector, callback)
}
$.fn.live = function(event, callback){
$(document.body).delegate(this.selector, event, callback)
return this
}
$.fn.die = function(event, callback){
$(document.body).undelegate(this.selector, event, callback)
return this
}
$.fn.on = function(event, selector, data, callback, one){
var autoRemove, delegator, $this = this
if (event && !isString(event)) {
$.each(event, function(type, fn){
$this.on(type, selector, data, fn, one)
})
return $this
}
if (!isString(selector) && !isFunction(callback) && callback !== false)
callback = data, data = selector, selector = undefined
if (isFunction(data) || data === false)
callback = data, data = undefined
if (callback === false) callback = returnFalse
return $this.each(function(_, element){
if (one) autoRemove = function(e){
remove(element, e.type, callback)
return callback.apply(this, arguments)
}
if (selector) delegator = function(e){
var evt, match = $(e.target).closest(selector, element).get(0)
if (match && match !== element) {
evt = $.extend(createProxy(e), {currentTarget: match, liveFired: element})
return (autoRemove || callback).apply(match, [evt].concat(slice.call(arguments, 1)))
}
}
add(element, event, callback, data, selector, delegator || autoRemove)
})
}
$.fn.off = function(event, selector, callback){
var $this = this
if (event && !isString(event)) {
$.each(event, function(type, fn){
$this.off(type, selector, fn)
})
return $this
}
if (!isString(selector) && !isFunction(callback) && callback !== false)
callback = selector, selector = undefined
if (callback === false) callback = returnFalse
return $this.each(function(){
remove(this, event, callback, selector)
})
}
$.fn.trigger = function(event, args){
event = (isString(event) || $.isPlainObject(event)) ? $.Event(event) : compatible(event)
event._args = args
return this.each(function(){
// items in the collection might not be DOM elements
if('dispatchEvent' in this) this.dispatchEvent(event)
else $(this).triggerHandler(event, args)
})
}
// triggers event handlers on current element just as if an event occurred,
// doesn't trigger an actual event, doesn't bubble
$.fn.triggerHandler = function(event, args){
var e, result
this.each(function(i, element){
e = createProxy(isString(event) ? $.Event(event) : event)
e._args = args
e.target = element
$.each(findHandlers(element, event.type || event), function(i, handler){
result = handler.proxy(e)
if (e.isImmediatePropagationStopped()) return false
})
})
return result
}
// shortcut methods for `.bind(event, fn)` for each event type
;('focusin focusout load resize scroll unload click dblclick '+
'mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave '+
'change select keydown keypress keyup error').split(' ').forEach(function(event) {
$.fn[event] = function(callback) {
return callback ?
this.bind(event, callback) :
this.trigger(event)
}
})
;['focus', 'blur'].forEach(function(name) {
$.fn[name] = function(callback) {
if (callback) this.bind(name, callback)
else this.each(function(){
try { this[name]() }
catch(e) {}
})
return this
}
})
$.Event = function(type, props) {
if (!isString(type)) props = type, type = props.type
var event = document.createEvent(specialEvents[type] || 'Events'), bubbles = true
if (props) for (var name in props) (name == 'bubbles') ? (bubbles = !!props[name]) : (event[name] = props[name])
event.initEvent(type, bubbles, true)
return compatible(event)
}
})(Zepto);
| maboiteaspam/phantomizer-websupport | shared/js/vendors/go-zepto/zepto-event.js | JavaScript | mit | 10,482 |
var fs = require('fs');
fs.open('/home/david/applilanche/resume/file.txt', 'r', function(status, fd) {
if (status) {
console.log(status.message);
return;
}
var buffer = new Buffer(100);
fs.read(fd, buffer, 0, 100, 0, function(err, num) {
console.log(buffer.toString('utf8', 0, num));
});
}); | davidmashe/applilanche | test/testReadFile.js | JavaScript | mit | 336 |
if(typeof exports === 'object') {
var assert = require("assert");
var alasql = require('../alasql.js');
};
describe('Test 22', function() {
it('EXCEPT and INTERSECT', function(done){
var db = new alasql.Database("db");
db.exec('CREATE TABLE test (a int, b int)');
db.exec('INSERT INTO test VALUES (1,1)');
db.exec('INSERT INTO test VALUES (2,2)');
db.exec('INSERT INTO test VALUES (3,3)');
db.exec('INSERT INTO test VALUES (4,4)');
db.exec('INSERT INTO test VALUES (5,5)');
db.exec('INSERT INTO test VALUES (6,6)');
var res = db.queryArray('SELECT a FROM test WHERE a<5 INTERSECT SELECT a FROM test WHERE a>2');
assert.deepEqual([ 3,4 ], res);
var res = db.queryArray('SELECT a FROM test WHERE a<5 EXCEPT SELECT a FROM test WHERE a>2');
assert.deepEqual([ 1,2 ], res);
done();
});
});
| agershun/alamdx | node_modules/alasql/test/test22.js | JavaScript | mit | 822 |
import { get_definition_with_tags } from './../../base';
export const confirmation = (
title, text, asssign_to=[], tags=[],
when, additional_args, description
) => get_definition_with_tags(
{
assignto: asssign_to,
text,
title
},
{
kind: 'actions',
label: 'Flow - Interact - Confirmation',
method: 'confirmation',
module: 'interact',
name: 'flow',
type: 'interaction'
},
tags, when, additional_args, description
); | walkerrandolphsmith/VersionOne.JavaScript.PipelineBuilder | src/plugins/flow/interact/confirmation.js | JavaScript | mit | 514 |
(function() {
'use strict';
angular
.module('jhipsterApp')
.factory('DataUtils', DataUtils);
DataUtils.$inject = ['$window'];
function DataUtils ($window) {
var service = {
abbreviate: abbreviate,
byteSize: byteSize,
openFile: openFile,
toBase64: toBase64
};
return service;
function abbreviate (text) {
if (!angular.isString(text)) {
return '';
}
if (text.length < 30) {
return text;
}
return text ? (text.substring(0, 15) + '...' + text.slice(-10)) : '';
}
function byteSize (base64String) {
if (!angular.isString(base64String)) {
return '';
}
function endsWith(suffix, str) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function paddingSize(base64String) {
if (endsWith('==', base64String)) {
return 2;
}
if (endsWith('=', base64String)) {
return 1;
}
return 0;
}
function size(base64String) {
return base64String.length / 4 * 3 - paddingSize(base64String);
}
function formatAsBytes(size) {
return size.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ' ') + ' bytes';
}
return formatAsBytes(size(base64String));
}
function openFile (type, data) {
$window.open('data:' + type + ';base64,' + data, '_blank', 'height=300,width=400');
}
function toBase64 (file, cb) {
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function (e) {
var base64Data = e.target.result.substr(e.target.result.indexOf('base64,') + 'base64,'.length);
cb(base64Data);
};
}
}
})();
| danimaniarqsoft/kukulcan | src/main/webapp/app/components/util/data-util.service.js | JavaScript | mit | 2,097 |
/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, window, log , Mustache */
define(function (require, exports, module) {
"use strict";
var CommandManager = brackets.getModule("command/CommandManager"),
KeyBindingManager = brackets.getModule("command/KeyBindingManager"),
Menus = brackets.getModule("command/Menus"),
PanelManager = brackets.getModule("view/PanelManager"),
ExtensionUtils = brackets.getModule("utils/ExtensionUtils"),
AppInit = brackets.getModule("utils/AppInit"),
NodeDomain = brackets.getModule("utils/NodeDomain"),
PreferencesManager = brackets.getModule("preferences/PreferencesManager"),
ProjectManager = brackets.getModule("project/ProjectManager"),
WorkspaceManager = brackets.getModule('view/WorkspaceManager');
var panelHtml = require("text!panel/panel.html");
var panel;
var $icon = $("<a id='grunt-toolbar-icon' href='#'> </a>")
.attr("title", "Grunt")
.appendTo($("#main-toolbar .buttons"));
var $console;
var taskTemplate = require("text!panel/task-list-template.html");
var gruntDomain = new NodeDomain("grunt", ExtensionUtils.getModulePath(module, "node/GruntDomain"));
var pathSettingName = "brackets-grunt.-path";
var path = "";
var RUN_DEFAULT_ID = "brackets-grunt.rundefault";
function getKeyBinding(id) {
var bindings = KeyBindingManager.getKeyBindings(id);
if (bindings.length > 0) {
return bindings[0].key;
}
return "";
}
function togglePanel() {
if (panel.isVisible()) {
panel.hide();
} else {
panel.show();
}
}
function clearConsole() {
panel.$panel.find("#grunt-console").empty();
}
function log(msg) {
if (!msg) {
return;
}
$console.append(msg.replace(/\n/g, "<br>"));
$console.scrollTop($console.prop("scrollHeight"));
//console.log(msg);
}
function getTasks() {
var key = getKeyBinding(RUN_DEFAULT_ID);
panel.$panel.find(".grunt-loader").removeClass("grunt-hide");
$icon.addClass("on");
log("Loading tasks from file<br>");
gruntDomain.exec("getTasks", ProjectManager.getProjectRoot().fullPath + path)
.done(function (tasks) {
panel.$panel.find("#tasks").html(Mustache.render(taskTemplate, {tasks: tasks, defaultkey: key}));
panel.$panel.find(".grunt-loader").addClass("grunt-hide");
$icon.removeClass("on");
if (tasks) {
log("Load complete!<br>");
}
}).fail(function (err) {
console.error("[Grunt] Error getting tasks", err);
panel.$panel.find(".grunt-loader").addClass("grunt-hide");
$icon.removeClass("on");
log("Load error!");
});
}
function runTask(taskName) {
panel.$panel.find(".grunt-runner").removeClass("grunt-hide").html("Running '" + (taskName || 'default') + "' ( <div id='kill-btn' class='btn small'>kill</div> )");
$icon.addClass("on");
gruntDomain.exec("runTask", taskName, ProjectManager.getProjectRoot().fullPath + path, ExtensionUtils.getModulePath(module))
.done(function (msg) {
panel.$panel.find(".grunt-runner").addClass("grunt-hide");
$icon.removeClass("on");
log("###<br><br>");
}).fail(function (err) {
panel.$panel.find(".grunt-runner").addClass("grunt-hide");
$icon.removeClass("on");
log("###<br><br>");
});
}
function killTask(clear) {
gruntDomain.exec("killTask")
.done(function (msg) {
$icon.removeClass("on");
panel.$panel.find(".grunt-runner").addClass("grunt-hide");
if (msg) {
log("###<br>");
}
if (clear) {
clearConsole();
}
}).fail(function (err) {
log("Error killing task: " + err);
});
}
function loadPathSettings(projectName) {
pathSettingName = "brackets-grunt." + projectName + "-path";
path = (PreferencesManager.get(pathSettingName) || "");
panel.$panel.find("#path").val(path);
}
AppInit.appReady(function () {
ExtensionUtils.loadStyleSheet(module, "style/style.css");
panel = WorkspaceManager.createBottomPanel("grunt.panel", $(panelHtml), 100);
$console = panel.$panel.find("#grunt-console");
loadPathSettings(ProjectManager.getProjectRoot().name);
// Panel Event Handlers
panel.$panel.on("click", ".task", function (e) {
runTask(e.currentTarget.getAttribute("task-name"));
});
panel.$panel.on("click", "#refresh", function () {
path = panel.$panel.find("#path").val();
if (pathSettingName && path) {
PreferencesManager.set(pathSettingName, path);
}
getTasks();
});
panel.$panel.on("click", "#clear-console", function () { clearConsole(); });
panel.$panel.on("click", "#close", function () { togglePanel(); });
panel.$panel.on("click", "#kill-btn", function (e) {
killTask();
});
$icon.on("click", togglePanel);
//run-default-task key shortcut
CommandManager.register("Run Default", RUN_DEFAULT_ID, runTask);
//Don't bind if it the shortcut is already taken
//TODO: Ask the user for another shortcut
if (!KeyBindingManager.getKeymap()["Ctrl-Alt-D"]) {
KeyBindingManager.addBinding(RUN_DEFAULT_ID, {"key": "Ctrl-Alt-D"});
}
//Handle messages from Node domain
$(gruntDomain).on("change", function (event, data) {
log(data);
});
//Kill running task when Brackets is closed
$(ProjectManager).on('beforeAppClose', function () {
killTask();
});
//Kill running task when project is changed
$(ProjectManager).on('beforeProjectClose', function () {
killTask(true);
});
$(ProjectManager).on("projectOpen", function (e, projectRoot) {
loadPathSettings(projectRoot.name);
getTasks();
});
//Load tasks
getTasks();
});
});
| dhategan/brackets-grunt | main.js | JavaScript | mit | 5,906 |
var expect = require('chai').expect;
var validator = require('../lib/index')
describe('ValidString#alphabetic', function() {
var instance = new validator().alphabetic({
extraChars: '*'
})
it('should return true when the string contains letters', function() {
var result = instance.test('test')
expect(result.isValid).to.equal(true);
});
it('should return true when the string contains extra characters', function() {
var result = instance.test('**test**')
expect(result.isValid).to.equal(true);
});
it('should return false when the string contains numbers', function() {
var result = instance.test('test123')
expect(result.isValid).to.equal(false);
});
it('should return false when the string contains spaces', function() {
var result = instance.test('test 123')
expect(result.isValid).to.equal(false);
});
});
describe('ValidString#alphaNumeric', function() {
var instance = new validator().alphaNumeric({
extraChars: '*'
})
it('should return true when the string contains letters or numbers', function() {
var result = instance.test('test123')
expect(result.isValid).to.equal(true);
});
it('should return true when the string contains extra characters', function() {
var result = instance.test('**test**')
expect(result.isValid).to.equal(true);
});
it('should return false when the string contains spaces', function() {
var result = instance.test('test 123')
expect(result.isValid).to.equal(false);
});
it('should return false when the string contains dashes', function() {
var result = instance.test('test-123')
expect(result.isValid).to.equal(false);
});
});
describe('ValidString#has', function() {
var instance = new validator().has({
chars: '@'
})
it('should return true when the string contains a @', function() {
var result = instance.test('test@example.com')
expect(result.isValid).to.equal(true);
});
it('should return false when the string does not contain a @', function() {
var result = instance.test('test')
expect(result.isValid).to.equal(false);
});
});
describe('ValidString#hasNot', function() {
var instance = new validator().hasNot({
chars: '@'
})
it('should return false when the string contains a @', function() {
var result = instance.test('test@example.com')
expect(result.isValid).to.equal(false);
});
it('should return true when the string does not contain a @', function() {
var result = instance.test('test')
expect(result.isValid).to.equal(true);
});
});
| ranaharoni/validstring | test/validationMethods.js | JavaScript | mit | 2,628 |
module.exports = {
el: '#userprofile-fields',
data: function () {
return _.merge({
users: false,
pages: 0,
count: '',
fields: [],
types: [],
selected: []
}, window.$data);
},
created: function () {
this.Fields = this.$resource('api/userprofile/field{/id}');
this.load();
},
methods: {
load: function () {
return this.Fields.query().then(function (res) {
this.$set('fields', res.data);
});
},
toggleRequired: function (field) {
field.data.required = field.data.required ? 0 : 1;
this.Fields.save({id: field.id}, {field: field}).then(function () {
this.load();
this.$notify('Field saved.');
}, function (res) {
this.load();
this.$notify(res.data, 'danger');
});
},
getSelected: function () {
return this.fields.filter(function (field) {
return this.isSelected(field);
}, this);
},
isSelected: function (field, children) {
if (_.isArray(field)) {
return _.every(field, function (field) {
return this.isSelected(field, children);
}, this);
}
return this.selected.indexOf(field.id.toString()) !== -1 && (!children || !this.tree[field.id] || this.isSelected(this.tree[field.id], true));
},
toggleSelect: function (field) {
var index = this.selected.indexOf(field.id.toString());
if (index == -1) {
this.selected.push(field.id.toString());
} else {
this.selected.splice(index, 1);
}
},
getType: function (field) {
return _.find(this.types, 'id', field.type);
},
removeFields: function () {
this.Fields.delete({id: 'bulk'}, {ids: this.selected}).then(function () {
this.load();
this.$notify('Fields(s) deleted.');
});
}
},
components: {
field: {
props: ['field'],
template: '#field',
computed: {
type: function () {
return this.$root.getType(this.field);
}
},
methods: {
isSelected: function (field) {
return this.$root.isSelected(field);
}
}
}
},
watch: {
fields: function () {
var vm = this;
// TODO this is still buggy
UIkit.nestable(this.$els.nestable, {
maxDepth: 1,
group: 'userprofile.fields'
}).off('change.uk.nestable').on('change.uk.nestable', function (e, nestable, el, type) {
if (type && type !== 'removed') {
vm.Fields.save({id: 'updateOrder'}, {fields: nestable.list()}).then(function () {
// @TODO reload everything on reorder really needed?
vm.load().success(function () {
// hack for weird flickr bug
if (el.parent()[0] === nestable.element[0]) {
setTimeout(function () {
el.remove();
}, 50);
}
});
}, function () {
this.$notify('Reorder failed.', 'danger');
});
}
});
}
}
};
Vue.ready(module.exports);
| yaelduckwen/e-pagekit | packages/bixie/userprofile/app/views/admin/fields.js | JavaScript | mit | 3,809 |
var Directive = angular.module('module.directives',['module.controllers']);
Directive
.directive('typemenu',function(){
return {
restrict:'E',
transclude:true,
template:'<div><button class="btn btn-default dropdown-toggle" type="button" ng-click="toggleMenu()">{{book.type}} '
+ '<span class="caret"></span></button>'
+ '<ul class="dropdown-menu" ng-show="isShow" style="display: block">'
+ '<li ng-repeat="c in category"><a ng-click="changeMenu($index)">{{c}}</a></li>'
+ '</ul></div>',
scope:true,
link:function(scope,element,attrs){
scope.isShow = false;
scope.category = ['node','angular','react','native']
scope.toggleMenu = function(){
scope.isShow = !scope.isShow;
}
scope.changeMenu = function(index){
scope.book.type = scope.category[index];
this.toggleMenu();
}
}
}
}); | leonz3/Ng.BookStore | app/js/directives.js | JavaScript | mit | 1,112 |
var assert = require('assert');
var R = require('..');
describe('prependTo', function() {
it('adds the element to the beginning of the list', function() {
assert.deepEqual(R.prependTo([4, 5, 6], 3), [3, 4, 5, 6]);
assert.deepEqual(R.prependTo([4, 5, 6], [1, 2, 3]), [[1, 2, 3], 4, 5, 6]);
});
it('works on empty list', function() {
assert.deepEqual(R.prependTo([], 1), [1]);
});
it('is curried', function() {
assert.strictEqual(typeof R.prependTo([]), 'function');
assert.deepEqual(R.prependTo([3, 2, 1])(4), [4, 3, 2, 1]);
});
it('throws on zero arguments', function() {
assert.throws(R.prependTo, TypeError);
});
});
| stoeffel/ramda | test/prependTo.js | JavaScript | mit | 705 |
module.exports = function(grunt){
grunt.initConfig({
gitclone: {
fontawesome: {
options: {
repository: 'https://github.com/FortAwesome/Font-Awesome.git',
directory: 'tmp/fontawesome'
}
},
fancybox: {
options: {
repository: 'https://github.com/fancyapps/fancyBox.git',
directory: 'tmp/fancybox'
}
}
},
copy: {
fontawesome: {
expand: true,
cwd: 'tmp/fontawesome/fonts/',
src: ['**'],
dest: 'source/css/fonts/'
},
fancybox: {
expand: true,
cwd: 'tmp/fancybox/source/',
src: ['**'],
dest: 'source/fancybox/'
}
},
_clean: {
tmp: ['tmp'],
fontawesome: ['source/css/fonts'],
fancybox: ['source/fancybox']
}
});
require('load-grunt-tasks')(grunt);
grunt.renameTask('clean', '_clean');
grunt.registerTask('fontawesome', ['gitclone:fontawesome', 'copy:fontawesome', '_clean:tmp']);
grunt.registerTask('fancybox', ['gitclone:fancybox', 'copy:fancybox', '_clean:tmp']);
grunt.registerTask('default', ['gitclone', 'copy', '_clean:tmp']);
grunt.registerTask('clean', ['_clean']);
}; | Erudika/erudika.github.io | themes/landscape/Gruntfile.js | JavaScript | mit | 1,213 |
var _ = require('lodash');
var db = {};
var get = function(id, field) {
if (!db[stringify(id)]) return null;
return _.cloneDeep(db[stringify(id)][field]);
};
var set = function(id, field, value) {
if (!db[stringify(id)]) db[stringify(id)] = { id: id };
db[stringify(id)][field] = value;
};
var stringify = function(id) {
if (id.instanceName) return id.namespace + ':' + id.hostAddress + ':' + id.instanceName;
else if (id.hostAddress) return id.namespace + ':' + id.hostAddress;
else if (id.namespace) return id.namespace;
else return '';
};
exports.setStatus = function(id, status, callback) {
set(id, 'status', status);
callback();
};
exports.getStatus = function(id, callback) {
callback(null, get(id, 'status'));
};
exports.setMetadata = function(id, metadata, callback) {
set(id, 'metadata', metadata);
callback();
};
exports.getMetadata = function(id, callback) {
callback(null, get(id, 'metadata'));
};
exports.setLinks = function(id, links, callback) {
set(id, 'links', links);
callback();
};
exports.getLinks = function(id, callback) {
callback(null, get(id, 'links'));
};
exports.setConfig = function(id, config, callback) {
set(id, 'config', config);
callback();
};
exports.getConfig = function(id, callback) {
callback(null, get(id, 'config'));
};
exports.getInstances = function(id, callback) {
callback(null, _.map(db, function(entry) { return entry; }));
}; | jojow/artifactmgr | store/instanceStore.js | JavaScript | mit | 1,475 |
module.exports = function (grunt) {
var _ = require('lodash');
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watchify: {
options: {
debug: true
},
isomorphism: {
src: './shared-modules/shirts.js',
dest: 'public/javascripts/shirts-module.js'
}
}
});
grunt.loadNpmTasks('grunt-watchify');
grunt.registerTask('default', ['watchify']);
};
| adamshaylor/complex-spa-architectures | isomorphism/Gruntfile.js | JavaScript | mit | 433 |
const towerIdRegex = /(?:@warriorjs\/|warriorjs-)tower-(.+)/;
/**
* Returns the identifier of the tower based on the package name.
*
* @param {string} towerPackageName The package name of the tower.
*/
function getTowerId(towerPackageName) {
return towerPackageName.match(towerIdRegex)[1];
}
export default getTowerId;
| olistic/warriorjs | packages/warriorjs-cli/src/utils/getTowerId.js | JavaScript | mit | 327 |
var TerminalDecoder = require('../client/TerminalDecoder');
var expect = require('chai').expect;
describe('TerminalDecoder', function() {
function processChunks(chunks) {
var d = new TerminalDecoder();
var output = [];
chunks.forEach(function(c) {
d.write(c, function() {
output.push(Array.prototype.slice.call(arguments));
});
});
d.end().forEach(function(command) {
output.push(command);
});
return output;
}
function process(input) {
return processChunks([ input ]);
};
it('processes simple strings', function() {
var result = processChunks([ "abc" ]);
expect(result).to.deep.equal([ [ 'output', 'abc' ] ]);
});
it('processes simple escape sequences', function() {
var result = processChunks([ TerminalDecoder.ESC + "c" ]);
expect(result).to.deep.equal([ [ 'reset' ] ]);
});
it('processes escape sequences between chunks', function() {
var result = processChunks([ TerminalDecoder.ESC, "c" ]);
expect(result).to.deep.equal([ [ 'reset' ] ]);
});
it('returns unfinished escape sequences at end', function() {
var result = processChunks([ TerminalDecoder.ESC ]);
expect(result).to.deep.equal([ [ 'output', '\x1b' ] ]);
});
it('processes character attributes', function() {
var result = process(TerminalDecoder.CSI + "0m");
expect(result).to.deep.equal([ [ 'style', { } ] ]);
result = process(TerminalDecoder.CSI + "1;32m");
expect(result).to.deep.equal([ [ 'style', { bold: true, foreground: 'green' } ] ]);
});
});
| CGamesPlay/hterminal | test/TerminalDecoder_spec.js | JavaScript | mit | 1,556 |
'use strict';
module.exports = {
name: require('./package').name,
isDevelopingAddon: function() {
return true;
},
options: {
babel: {
plugins: [
'@babel/plugin-proposal-object-rest-spread'
]
}
}
};
| GCheung55/ember-vega | index.js | JavaScript | mit | 285 |
/**
* @name sandbox
*/
(function (sb) {
if ($P.WRAP_MODULE) {
/**
* @param code
* @return {Boolean} true if it is a plain LMD module
*/
var async_is_plain_code = function (code) {
// remove comments (bad rx - I know it, but it works for that case), spaces and ;
code = code.replace(/\/\*.*?\*\/|\/\/.*(?=[\n\r])|\s|\;/g, '');
// simple FD/FE parser
if (/\(function\(|function[a-z0-9_]+\(/.test(code)) {
var index = 0,
length = code.length,
is_can_return = false,
string = false,
parentheses = 0,
braces = 0;
while (index < length) {
switch (code.charAt(index)) {
// count braces if not in string
case '{':
if (!string) {
is_can_return = true;
braces++
}
break;
case '}':
if (!string) braces--;
break;
case '(':
if (!string) parentheses++;
break;
case ')':
if (!string) parentheses--;
break;
case '\\':
if (string) index++; // skip next char in in string
break;
case "'":
if (string === "'") {
string = false; // close string
} else if (string === false) {
string = "'"; // open string
}
break;
case '"':
if (string === '"') {
string = false; // close string
} else if (string === false) {
string = '"'; // open string
}
break;
}
index++;
if (is_can_return && !parentheses && !braces) {
return index !== length;
}
}
}
return true;
};
}
var async_plain = function (module, contentTypeOrExtension) {
// its NOT a JSON ant its a plain code
if (!(/json/).test(contentTypeOrExtension)/*if ($P.WRAP_MODULE) {*/ && async_is_plain_code(module)/*}*/) {
// its not a JSON and its a Plain LMD module - wrap it
module = '(function(require,exports,module){\n' + module + '\n})';
}
return module;
};
/**
* @event *:wrap-module Module wrap request
*
* @param {String} moduleName
* @param {String} module this module will be wrapped
* @param {String} contentTypeOrExtension file content type or extension to avoid wrapping json file
*
* @retuns yes
*/
sb.on('*:wrap-module', function (moduleName, module, contentTypeOrExtension) {
module = async_plain(module, contentTypeOrExtension);
return [moduleName, module, contentTypeOrExtension];
});
/**
* @event *:is-plain-module code type check request: plain or lmd-module
*
* @param {String} moduleName
* @param {String} module
* @param {String} isPlainCode default value
*
* @retuns yes
*/
sb.on('*:is-plain-module', function (moduleName, module, isPlainCode) {
if (typeof async_is_plain_code === "function") {
return [moduleName, module, async_is_plain_code(module)];
}
});
}(sandbox));
| azproduction/lmd | src/plugin/common/wrap_module.js | JavaScript | mit | 3,652 |
/*
* jQuery One Page Nav Plugin
* http://github.com/davist11/jQuery-One-Page-Nav
*
* Copyright (c) 2010 Trevor Davis (http://trevordavis.net)
* Dual licensed under the MIT and GPL licenses.
* Uses the same license as jQuery, see:
* http://jquery.org/license
*
* @version 3.0.0
*
* Example usage:
* $('#nav').onePageNav({
* currentClass: 'current',
* changeHash: false,
* scrollSpeed: 750
* });
*/
/* ´úÂëÕûÀí£ºÀÁÈËÖ®¼Ò www.lanrenzhijia.com */
;(function($, window, document, undefined){
// our plugin constructor
var OnePageNav = function(elem, options){
this.elem = elem;
this.$elem = $(elem);
this.options = options;
this.metadata = this.$elem.data('plugin-options');
this.$win = $(window);
this.sections = {};
this.didScroll = false;
this.$doc = $(document);
this.docHeight = this.$doc.height();
};
// the plugin prototype
OnePageNav.prototype = {
defaults: {
navItems: 'a',
currentClass: 'current',
changeHash: false,
easing: 'swing',
filter: '',
scrollSpeed: 750,
scrollThreshold: 0.5,
begin: false,
end: false,
scrollChange: false
},
init: function() {
// Introduce defaults that can be extended either
// globally or using an object literal.
this.config = $.extend({}, this.defaults, this.options, this.metadata);
this.$nav = this.$elem.find(this.config.navItems);
//Filter any links out of the nav
if(this.config.filter !== '') {
this.$nav = this.$nav.filter(this.config.filter);
}
//Handle clicks on the nav
this.$nav.on('click.onePageNav', $.proxy(this.handleClick, this));
//Get the section positions
this.getPositions();
//Handle scroll changes
this.bindInterval();
//Update the positions on resize too
this.$win.on('resize.onePageNav', $.proxy(this.getPositions, this));
return this;
},
adjustNav: function(self, $parent) {
self.$elem.find('.' + self.config.currentClass).removeClass(self.config.currentClass);
$parent.addClass(self.config.currentClass);
},
bindInterval: function() {
var self = this;
var docHeight;
self.$win.on('scroll.onePageNav', function() {
self.didScroll = true;
});
self.t = setInterval(function() {
docHeight = self.$doc.height();
//If it was scrolled
if(self.didScroll) {
self.didScroll = false;
self.scrollChange();
}
//If the document height changes
if(docHeight !== self.docHeight) {
self.docHeight = docHeight;
self.getPositions();
}
}, 250);
},
getHash: function($link) {
return $link.attr('href').split('#')[1];
},
getPositions: function() {
var self = this;
var linkHref;
var topPos;
var $target;
self.$nav.each(function() {
linkHref = self.getHash($(this));
$target = $('#' + linkHref);
if($target.length) {
topPos = $target.offset().top;
self.sections[linkHref] = Math.round(topPos);
}
});
},
getSection: function(windowPos) {
var returnValue = null;
var windowHeight = Math.round(this.$win.height() * this.config.scrollThreshold);
for(var section in this.sections) {
if((this.sections[section] - windowHeight) < windowPos) {
returnValue = section;
}
}
return returnValue;
},
handleClick: function(e) {
var self = this;
var $link = $(e.currentTarget);
var $parent = $link.parent();
var newLoc = '#' + self.getHash($link);
if(!$parent.hasClass(self.config.currentClass)) {
//Start callback
if(self.config.begin) {
self.config.begin();
}
//Change the highlighted nav item
self.adjustNav(self, $parent);
//Removing the auto-adjust on scroll
self.unbindInterval();
//Scroll to the correct position
self.scrollTo(newLoc, function() {
//Do we need to change the hash?
if(self.config.changeHash) {
window.location.hash = newLoc;
}
//Add the auto-adjust on scroll back in
self.bindInterval();
//End callback
if(self.config.end) {
self.config.end();
}
});
}
e.preventDefault();
},
scrollChange: function() {
var windowTop = this.$win.scrollTop();
var position = this.getSection(windowTop);
var $parent;
//If the position is set
if(position !== null) {
$parent = this.$elem.find('a[href$="#' + position + '"]').parent();
//If it's not already the current section
if(!$parent.hasClass(this.config.currentClass)) {
//Change the highlighted nav item
this.adjustNav(this, $parent);
//If there is a scrollChange callback
if(this.config.scrollChange) {
this.config.scrollChange($parent);
}
}
}
},
scrollTo: function(target, callback) {
var offset = $(target).offset().top;
$('html, body').animate({
scrollTop: offset
}, this.config.scrollSpeed, this.config.easing, callback);
},
unbindInterval: function() {
clearInterval(this.t);
this.$win.unbind('scroll.onePageNav');
}
};
OnePageNav.defaults = OnePageNav.prototype.defaults;
$.fn.onePageNav = function(options) {
return this.each(function() {
new OnePageNav(this, options).init();
});
};
})( jQuery, window , document );
/* ´úÂëÕûÀí£ºÀÁÈËÖ®¼Ò www.lanrenzhijia.com */ | imdeakin/yueyun-v3 | src/assets/js/jquery.nav.js | JavaScript | mit | 5,229 |
"use strict";
const Constants = require("../Constants");
const StatusTypes = Constants.StatusTypes;
const Events = Constants.Events;
const Utils = require("../core/Utils");
const BaseCollection = require("./BaseCollection");
const GuildMember = require("../models/GuildMember");
function createGuildMember(member) {
if (member.user) member.id = member.user.id;
return new GuildMember({
id: member.id,
guild_id: member.guild_id,
nick: member.nick || null,
roles: member.roles || [],
mute: member.mute || false,
deaf: member.deaf || false,
self_mute: member.self_mute || false,
self_deaf: member.self_deaf || false,
joined_at: member.joined_at
});
}
function handleConnectionOpen(data) {
this.clear();
data.guilds.forEach(guild => handleCreateGuild.call(this, guild));
return true;
}
function handleGuildMemberCreateOrUpdate(member, e) {
const memberCollection = this.get(member.guild_id);
if (!memberCollection) return true;
const prev = memberCollection.get(member.user.id);
const next = createGuildMember(member);
memberCollection.mergeOrSet(member.user.id, next);
if (e.type === Events.GUILD_MEMBER_UPDATE) {
e.data._prev = prev;
e.data._next = next;
}
return true;
}
function handleGuildMemberRemove(member, e) {
const memberCollection = this.get(member.guild_id);
if (!memberCollection) return true;
const oldMember = memberCollection.get(member.user.id);
if (oldMember) e.data._cached = oldMember;
memberCollection.delete(member.user.id);
return true;
}
function handleCreateGuild(guild) {
if (!guild || guild.unavailable) return true;
if (!this._discordie._guilds.get(guild.id)) return true; // GUILD_SYNC case
const memberCollection = new BaseCollection();
this.set(guild.id, memberCollection);
guild.members.forEach(member => {
member.guild_id = guild.id;
memberCollection.set(member.user.id, createGuildMember(member));
});
return true;
}
function handleDeleteGuild(guild) {
this.delete(guild.id);
return true;
}
function handleVoiceStateUpdate(data) {
const memberCollection = this.get(data.guild_id);
if (!memberCollection) return true;
const member = memberCollection.get(data.user_id);
if (!member) return true;
memberCollection.set(data.user_id,
member.merge({
mute: data.mute,
deaf: data.deaf,
self_mute: data.self_mute,
self_deaf: data.self_deaf
})
);
return true;
}
function handlePresenceUpdate(presence) {
if (!presence.user || !presence.user.id) return true;
// add members only for online users and if presence is not partial
if (presence.status == StatusTypes.OFFLINE || !presence.user.username)
return true;
const memberCollection = this.get(presence.guild_id);
if (!memberCollection) return true;
const cachedMember = memberCollection.get(presence.user.id);
if (!cachedMember) {
// note: presences only contain roles
memberCollection.set(presence.user.id, createGuildMember(presence));
}
return true;
}
function handleGuildMembersChunk(chunk) {
var guildId = chunk.guild_id;
if (!guildId || !chunk.members) return true;
var state = this._guildMemberChunks[guildId];
if (!state) return true;
var guild = this._discordie._guilds.get(guildId);
if (!guild) return true;
const memberCollection = this.get(guildId);
if (!memberCollection) return true;
chunk.members.forEach(member => {
member.guild_id = guildId;
memberCollection.mergeOrSet(member.user.id, createGuildMember(member))
});
if (memberCollection.size >= guild.member_count) state.resolve();
return true;
}
class GuildMemberCollection extends BaseCollection {
constructor(discordie, gateway) {
super();
if (typeof gateway !== "function")
throw new Error("Gateway parameter must be a function");
discordie.Dispatcher.on(Events.GATEWAY_DISPATCH, e => {
if (e.socket != gateway()) return;
Utils.bindGatewayEventHandlers(this, e, {
READY: handleConnectionOpen,
GUILD_SYNC: handleCreateGuild,
GUILD_CREATE: handleCreateGuild,
GUILD_DELETE: handleDeleteGuild,
GUILD_MEMBER_ADD: handleGuildMemberCreateOrUpdate,
GUILD_MEMBER_UPDATE: handleGuildMemberCreateOrUpdate,
GUILD_MEMBER_REMOVE: handleGuildMemberRemove,
VOICE_STATE_UPDATE: handleVoiceStateUpdate,
PRESENCE_UPDATE: handlePresenceUpdate,
GUILD_MEMBERS_CHUNK: handleGuildMembersChunk
});
});
discordie.Dispatcher.on(Events.GATEWAY_DISCONNECT, e => {
if (e.socket != gateway()) return;
for (var guildId in this._guildMemberChunks) {
var state = this._guildMemberChunks[guildId];
if (!state) continue;
state.reject(new Error("Gateway disconnect"));
}
this._guildMemberChunks = {};
});
this._guildMemberChunks = {};
this._discordie = discordie;
Utils.privatify(this);
}
fetchMembers(guilds){
const gateway = this._discordie.gatewaySocket;
if (!gateway || !gateway.connected)
return Promise.reject(new Error("No gateway socket (not connected)"));
const largeGuilds =
Array.from(this._discordie._guilds.values())
.filter(guild => {
if (!guild.large) return false;
var cachedMembers = this._discordie._members.get(guild.id);
if (!cachedMembers) return false;
return guild.member_count > cachedMembers.size;
})
.map(guild => guild.id);
// filter out only requested guilds (if specified) from large ones
// return a resolved promise if no large guilds in the list
let targetGuilds =
!guilds ?
largeGuilds :
largeGuilds.filter(guild => guilds.indexOf(guild) >= 0);
if (!targetGuilds.length) return Promise.resolve();
targetGuilds.forEach(guildId => {
if (this._guildMemberChunks[guildId]) return;
var state = {promise: null, resolve: null, reject: null, timer: null};
state.promise = new Promise((rs, rj) => {
const destroyState = () => {
if (!state.timer) return;
clearTimeout(state.timer);
state.timer = null;
delete this._guildMemberChunks[guildId];
};
state.resolve = result => { destroyState(); return rs(result); };
state.reject = reason => { destroyState(); return rj(reason); };
});
state.timer = setTimeout(() => {
if (!this._guildMemberChunks[guildId]) return;
state.reject(new Error(
"Guild member request timed out (" + guildId + ")"
));
delete this._guildMemberChunks[guildId];
}, 60000);
this._guildMemberChunks[guildId] = state;
});
gateway.requestGuildMembers(targetGuilds);
var targetPromises =
targetGuilds.map(guildId => this._guildMemberChunks[guildId].promise);
return Promise.all(targetPromises);
}
getMember(guildId, userId) {
const memberCollection = this.get(guildId);
if (!memberCollection) return null;
return memberCollection.get(userId);
}
}
module.exports = GuildMemberCollection;
| Gamecloud-Solutions/streambot | node_modules/discordie/lib/collections/GuildMemberCollection.js | JavaScript | mit | 7,115 |