code stringlengths 2 1.05M |
|---|
var createDefaults = require('lodash/internal/createDefaults'),
merge = require('lodash/object/merge'),
mergeDefaults = require('lodash/internal/mergeDefaults');
/**
* This method is like `_.defaults` except that it recursively assigns
* default properties.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* _.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } });
* // => { 'user': { 'name': 'barney', 'age': 36 } }
*
*/
var defaultsDeep = createDefaults(merge, mergeDefaults);
module.exports = defaultsDeep;
|
import { Record } from 'immutable'
import I18n from 'react-native-i18n'
import {
SET_FROM,
SET_TO,
SET_TYPE,
TYPE_OWN_BIKE
} from '../actions/routeSearch'
import {
GET_GEOLOCATION_SUCCESS,
WATCH_GEOLOCATION_SUCCESS
} from '../actions/geolocation'
import LocationRecord from '../records/location'
const defaultState = new Record({
from: new LocationRecord({
name: I18n.t('myLocation'),
myLocation: true
}),
to: new LocationRecord(),
type: TYPE_OWN_BIKE
})()
export default function locations(state = defaultState, action) {
switch (action.type) {
case SET_FROM:
return state.set('from', new LocationRecord(action.state))
case SET_TO:
return state.set('to', new LocationRecord(action.state))
case SET_TYPE:
return state.set('type', action.state)
case GET_GEOLOCATION_SUCCESS:
case WATCH_GEOLOCATION_SUCCESS:
if (state.from.myLocation || state.to.myLocation) {
const target = state.from.myLocation ? 'from' : 'to'
return state
.updateIn([target, 'latitude'], () => action.state.coords.latitude)
.updateIn([target, 'longitude'], () => action.state.coords.longitude)
}
else {
return state
}
default:
return state
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:097c910513c52b705ae5a0ab291f1bff216a25dc4b3178615bfd31ed9a55e98a
size 81968
|
'use strict';
var _supertest = require('supertest');
var _supertest2 = _interopRequireDefault(_supertest);
var _chai = require('chai');
var _chai2 = _interopRequireDefault(_chai);
var _chaiHttp = require('chai-http');
var _chaiHttp2 = _interopRequireDefault(_chaiHttp);
var _models = require('../models');
var _app = require('../app');
var _app2 = _interopRequireDefault(_app);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// During the test the env variable is set to test
process.env.NODE_ENV = 'test'; // Require the dev-dependencies
var server = _supertest2.default.agent(_app2.default);
var should = _chai2.default.should();
_chai2.default.use(_chaiHttp2.default);
describe('Messages', function () {
var token = '';
before(function (done) {
// Before each test we empty the database
server.post('/api/v1/users/signin').send({
username: 'kene',
password: 'kene' }).end(function (err, res) {
token = res.body.token;
});
_models.Messages.sync({ force: true }).then(function () {
_models.MessageReads.sync({ force: true });
done();
}).catch(function (error) {
done(error);
});
});
describe('Controller Tests: ', function () {
// Test for messages
describe('Message Controller: ', function () {
var groupId = 1;
it('should display no message when a group does not have message', function (done) {
server.get('/api/v1/groups/' + groupId + '/messages').set({ 'x-access-token': token }).end(function (err, res) {
res.should.have.status(404);
res.body.should.be.a('object');
res.body.should.have.property('message').eql('This is the start of messaging in this group!');
done();
});
});
it('should send message', function (done) {
server.post('/api/v1/groups/' + groupId + '/message').send({
token: token,
message: 'This is a sample message',
priorityLevel: 'Normal',
groupId: groupId,
sentBy: 1,
readBy: '1'
}).end(function (err, res) {
res.should.have.status(201);
res.body.should.be.a('object');
res.body.should.have.property('status').eql('Message sent successfully');
done();
});
});
it('should not send a message if any paramter is missing', function (done) {
server.post('/api/v1/groups/' + groupId + '/message').send({
token: token,
// message: 'This is a sample message',
priorityLevel: 'Normal',
groupId: groupId,
sentBy: 1,
readBy: '1'
}).end(function (err, res) {
res.should.have.status(400);
res.body.should.be.a('object');
res.body.should.have.property('message').eql('Invalid request. Some column(s) are missing');
done();
});
});
it('should not send a message if any paramter is empty', function (done) {
server.post('/api/v1/groups/' + groupId + '/message').send({
token: token,
message: '',
priorityLevel: 'Normal',
groupId: groupId,
sentBy: 1,
readBy: '1'
}).end(function (err, res) {
res.should.have.status(400);
res.body.should.be.a('object');
res.body.should.have.property('message').eql('Invalid request. Some column(s) are missing');
done();
});
});
it('should display message when a group have message', function (done) {
server.get('/api/v1/groups/' + groupId + '/messages').set({ 'x-access-token': token }).end(function (err, res) {
res.should.have.status(200);
res.body.should.be.a('array');
res.body[0].should.have.property('message').eql('This is a sample message');
res.body[0].should.have.property('priorityLevel').eql('Normal');
done();
});
});
it('should add notification when a message\n is sent', function (done) {
var messageId = 1;
server.post('/api/v1/groups/' + messageId + '/notification').send({
token: token,
userId: 1,
readStatus: 0,
senderId: 1,
groupId: groupId
}).end(function (err, res) {
res.should.have.status(201);
res.body.should.be.a('object');
res.body.should.have.property('message').eql('Notification Added');
res.body.should.have.property('success').eql(true);
done();
});
});
it('should not add notification when a all required \n parameter is not available', function (done) {
var messageId = 1;
server.post('/api/v1/groups/' + messageId + '/notification').send({
token: token,
// userId: 1,
readStatus: 0,
senderId: 1,
groupId: groupId
}).end(function (err, res) {
res.should.have.status(400);
res.body.should.be.a('object');
res.body.should.have.property('message').eql('Invalid request.Some column(s) column are missing');
done();
});
});
it('should not add a duplicate notification', function (done) {
var messageId = 1;
server.post('/api/v1/groups/' + messageId + '/notification').send({
token: token,
userId: 1,
readStatus: 0,
senderId: 1,
groupId: groupId
}).end(function (err, res) {
res.should.have.status(409);
res.body.should.be.a('object');
res.body.should.have.property('message').eql('Notification already exist');
res.body.should.have.property('success').eql(false);
done();
});
});
it('should not add a notification when message\n with messageId is not found', function (done) {
var messageId = 10;
server.post('/api/v1/groups/' + messageId + '/notification').send({
token: token,
userId: 1,
readStatus: 0,
senderId: 1,
groupId: groupId
}).end(function (err, res) {
res.should.have.status(500);
res.body.should.be.a('object');
done();
});
});
it('should retrieve notifications', function (done) {
server.post('/api/v1/user/notifications').send({
token: token,
userId: 1
}).end(function (err, res) {
res.should.have.status(200);
res.body.should.be.a('object');
done();
});
});
it('should return empty array when\n retrieving a notification of user who has no notification', function (done) {
server.post('/api/v1/user/notifications').send({
token: token,
userId: 3
}).end(function (err, res) {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('messageRes').eql([]);
done();
});
});
it('should return empty array if message readers are empty', function (done) {
var messageId = 1;
server.post('/api/v1/users/' + messageId + '/read').send({
token: token
}).end(function (err, res) {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('messageReadUsers').eql([]);
done();
});
});
it('should update notification', function (done) {
var messageId = 1;
server.post('/api/v1/user/' + messageId + '/notification').send({
token: token,
userId: 1,
readStatus: 1
}).end(function (err, res) {
res.should.have.status(201);
res.body.should.be.a('object');
res.body.should.have.property('message').eql('Notification Updated');
res.body.should.have.property('success').eql(true);
done();
});
});
it('should throw not found error when attempting\n to update a notification that does not exist', function (done) {
var messageId = 1;
server.post('/api/v1/user/' + messageId + '/notification').send({
token: token,
userId: 2,
readStatus: 1
}).end(function (err, res) {
res.should.have.status(404);
res.body.should.be.a('object');
res.body.should.have.property('message').eql('Notification does not exist');
done();
});
});
it('should not update the notification of a user\n if userId is not found', function (done) {
var messageId = 1;
server.post('/api/v1/user/' + messageId + '/notification').send({
token: token,
// userId: 2,
readStatus: 1
}).end(function (err, res) {
res.should.have.status(400);
res.body.should.be.a('object');
res.body.should.have.property('message').eql('Invalid request.Some column are missing');
done();
});
});
it('should return status code 200 and res\n of object when getting all users that read\n a message', function (done) {
var messageId = 1;
server.post('/api/v1/users/' + messageId + '/read').send({
token: token
}).end(function (err, res) {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('messageReadUsers');
done();
});
});
});
});
}); |
var pathExists = require('path-exists');
var beautify = require('js-beautify').js_beautify;
module.exports= {
pathExist: function (query) {
if(pathExists.sync(query))
return true;
else
return false;
},
beautify: function (data) {
return beautify(data, { indent_size: 4 });
},
capitalize: function (str)
{
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1)});
}
} |
'use strict';
angular
.module('docs', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngSanitize',
'ngTouch',
'ui.bootstrap',
'ui.router',
'docs.header',
'docs.settings',
'docs.viewer'
]);
|
/*
* The scene encapsulates all the object-cpu side of the engine.
* It contains all the configuration parameters + objects and lights.
*/
// TODO: move each subsection to its separated object
// TODO: save to storage the last thing you did! all the parameters!
var Scene = GUIObject.extend({
// ---------- GLOBALS ----------
// TODO: SCENE PRESETS!!! (like cornel, empty, etc)
// TODO: LOAD AND SAVE SCENE!
width : APP_WIDTH,
height : APP_HEIGHT,
rayRes : 64.0,
shadowRes : 24.0,
aoRes : 6.0,
aoStrength : 8.0,
reflEnabled : false,
reflRes : 2.0,
// ---------- CAMERA ----------
cameraPosition : null,
cameraView : null,
cameraSpeed : 4.0,
cameraFov : 2.0,
// ---------- ENVIRONMENT ----------
//isEnvEnabled : true, // set to false to fuck it all :D
bgrColor : null,
// TODO> ADD TERRAIN!!!!!!!!!!!!!!!!
sun : null,
horizon : null,
clouds : null,
fog : null,
// TODO> MOON???????
// ---------- POSTPROCESSING ----------
// gamma correction
gammaEnabled : true,
gammaAmount : 0.35,
// todo> tonemapping????
// todo> FILMIC GRAIN! (the order forthefuck)
// todo> LENS FUCKIN' FLARE! - dirty texture, intensity, enabled - use the sun color!. extra: apocalypse fx
// contrast
contrastEnabled : true,
contrastValue : 0.5,
// desaturation
desaturationEnabled : false,
//desatColor : null,
desaturationStrength : 0.25,
// tinting
tintingEnabled : true,
tintingColor : null,
// vignetting
vignettingEnabled : true,
vignettingMin : 0.5,
vignettingMax : 0.5,
objects : null,
lights : null,
//tracer : null,
//gui : null,
//recompile : false,
// todo: params
constructor : function(gui)
{
this.bgrColor = [ 128, 128, 196 ];
//this.sunLightPos = { x: -19.5, y: 3.5, z: -25.0 };
this.cameraPosition = { x: 0.9, y: 0.3, z: 1.5 };
this.cameraView = {x: 0.0, y: 0.2, z: 0.1 };
this.lights = [];
this.callParent(gui);
},
createGUI : function()
{
var addLightController = this.gui.add(this, 'addPointLight').name('Add point light');
addLightController.onFinishChange( this.onPropertyChanged.bind(this) );
var showShaderController = this.gui.add(this, 'printShader').name('Debug print shader');
var tab = this.gui.addFolder("GLOBALS");
tab.add(this, 'width', 240, 1920).name("Width").onFinishChange( this.onPropertyChanged.bind(this) );
tab.add(this, 'height', 120, 1920).name("Height").onFinishChange( this.onPropertyChanged.bind(this) );
tab.add(this, 'rayRes', 1.0, 256.0).name("Ray resolution").onFinishChange( this.onPropertyChanged.bind(this) );
tab.add(this, 'shadowRes', 1.0, 128.0).name("Softshadow res").onFinishChange( this.onPropertyChanged.bind(this) );
tab.add(this, 'aoRes', 1.0, 128.0).name("AO res").onFinishChange( this.onPropertyChanged.bind(this) );
tab.add(this, 'aoStrength', 0.0, 50.0).name("AO strength").onFinishChange( this.onPropertyChanged.bind(this) );
tab.add(this, 'reflEnabled').name("Refl. enabled").onFinishChange( this.onPropertyChanged.bind(this) );
tab.add(this, 'reflRes', 1.0, 64.0).name("Refl. resolution").onFinishChange( this.onPropertyChanged.bind(this) );
//f1.open();
// todo: bring a good fps cam pretty please
var f2 = this.gui.addFolder("CAMERA");
f2.add(this, 'cameraSpeed', 1.0, 10.0).name("Speed");
f2.add(this, 'cameraFov', 0.1, 8.0).name("Fov");
var f21 = f2.addFolder("Position");
f21.add(this.cameraPosition, 'x', -25.0, 25.0).listen();
f21.add(this.cameraPosition, 'y', -25.0, 25.0).listen();
f21.add(this.cameraPosition, 'z', -25.0, 25.0).listen();
var f22 = f2.addFolder("View");
f22.add(this.cameraView, 'x', -15.0, 15.0);
f22.add(this.cameraView, 'y', -15.0, 15.0);
f22.add(this.cameraView, 'z', -15.0, 15.0);
var folderEnv = this.gui.addFolder("ENVIRONMENT");
//folderEnv.add(this, 'isEnvEnabled', true).name("Enabled").onFinishChange( this.onPropertyChanged.bind(this) );
folderEnv.addColor(this, 'bgrColor').name("Background").onChange( this.onPropertyChanged.bind(this) ); // onFinishChange
this.sun = new Sun(folderEnv);
this.horizon = new Horizon(folderEnv);
this.clouds = new Clouds(folderEnv);
this.fog = new Fog(folderEnv);
//var f32 = f3.addFolder("CLOUDS");
//this.addPointLight();
//this.recompile = true;
},
// one day I will have to read this shit to remember why in all heavens I'm not just executing a callback
shouldRecompile : function()
{
var ret = false;
var shouldRecompileLights = false;
for(var i = 0; i < this.lights.length; i++)
{
shouldRecompileLights = this.lights[i].shouldRecompile();
if(shouldRecompileLights)
{
ret = true;
}
}
if(shouldRecompileLights === false)
{
ret = this.recompile || this.sun.shouldRecompile() || this.horizon.shouldRecompile() || this.clouds.shouldRecompile() || this.fog.shouldRecompile();
this.recompile = false;
}
return ret;
},
// todo: print to file
printShader : function()
{
console.log("---------------------------------------------------\n", g_shaderSrc);
},
addPointLight : function()
{
var pointLight = new PointLight(this.gui, this);
this.lights.push(pointLight);
},
removePointLight : function(light)
{
var index = this.lights.indexOf(light);
this.lights.splice(index, 1);
this.onPropertyChanged(); // force reload
},
// find object by name (useful to do things later)
getPointLight : function(name)
{
// todo
},
update : function(delta)
{
this.callParent(delta);
if(Input.isKeyPressed(Input.KEY_A))
{
this.cameraPosition.x -= delta * this.cameraSpeed;
}
else if(Input.isKeyPressed(Input.KEY_D))
{
this.cameraPosition.x += delta * this.cameraSpeed;
}
if(Input.isKeyPressed(Input.KEY_Q))
{
this.cameraPosition.y -= delta * this.cameraSpeed;
}
else if(Input.isKeyPressed(Input.KEY_E))
{
this.cameraPosition.y += delta * this.cameraSpeed;
}
if(Input.isKeyPressed(Input.KEY_W))
{
this.cameraPosition.z -= delta * this.cameraSpeed;
}
else if(Input.isKeyPressed(Input.KEY_S))
{
this.cameraPosition.z += delta * this.cameraSpeed;
}
},
//------------------------------------------------
// src
getBgrSrc : function()
{
var r = getValue(this.bgrColor[0] / 255.0);
var g = getValue(this.bgrColor[1] / 255.0);
var b = getValue(this.bgrColor[2] / 255.0);
var src = 'col = vec3('+ r +','+ g +','+ b +')*(1.0-0.8*rd.y);';
return src;
},
getReflEnabledSrc : function()
{
var src = '';
if(this.reflEnabled)
{
src = ' #define USE_REFLECTIONS';
}
return src;
},
getLightsUniforms : function()
{
var src = '';
for(var i = 0; i < this.lights.length; i++)
{
if(this.lights[i].alive)
{
src += this.lights[i].getUniformsSrc();
}
}
return src;
},
getLightsSrc : function()
{
var src = '';
for(var i = 0; i < this.lights.length; i++)
{
if(this.lights[i].alive)
{
src += this.lights[i].getSrc();
}
}
//console.log(this.lights);
//console.log("\n\n LIGHTS CODE: \n\n" + src);
return src;
},
getLightsFinalSrc : function()
{
var src = '';
var temp = '';
var lights = 0;
for(var i = 0; i < this.lights.length; i++)
{
if(this.lights[i].alive && this.lights[i].isEnabled)
{
lights++;
if(lights > 1)
{
temp += ' + ';
}
temp += 'light'+this.lights[i].id;
}
}
if(lights > 0)
{
//lin = (light1 + light2 + light3) * occ;
src = 'lin = (' + temp + ') * occ; \n';
}
return src;
}
// environment
/*
getCloudsSrc : function()
{
// clouds
cloudsEnabled : true,
cloudsStatic : true, // position missing? animation?
cloudsColor : null,
cloudsHeight : 1000.0,
cloudsSizeMin : 0.23,
cloudsSizeMax : 0.8,
cloudsAmount : 0.5,
cloudsNoiseSize : 0.0005,
},
getSunSrc : function()
{
// sun
sunEnabled : true,
sunStatic : true,
sunColor : null,
sunInvSize : 5.0,
sunStrength : 0.5,
sunPos : null, // array NOTE: THIS SHIT SHOULD BE USED FOR THE MAIN SUNLIGHT POSITION AS WELL, OR SOMETHING!!!
},
// todo> tonemapping????
// todo> FILMIC GRAIN! (the order forthefuck)
// todo> LENS FUCKING FLARE!
// postprocessing stuff
getGammaSrc : function()
{
gammaEnabled : true,
gammaAmount : 0.35,
},
getContrastSrc : function()
{
contrastEnabled : true,
contrastValue : 0.5,
},
getDesaturationSrc : function()
{
desaturationEnabled : false,
//desatColor : null,
desaturationStrength : 0.25,
},
getTintingSrc : function()
{
tintingEnabled : true,
tintingColor : null,
},
getVignettingSrc : function()
{
vignettingEnabled : true,
vignettingMin : 0.5,
vignettingMax : 0.5,
}
*/
// New object
// New point light
// New area light (?)
// EXPORT SCENE
// IMPORT SCENE
});
|
/**
* @jsx React.DOM
*/
'use strict';
// config
var config = require('./config');
// dependencies
var React = require('react');
var ReactAsync = require('react-async');
// custom components
var Head = require('./modules/components/head');
var LoginForm = require('./modules/components/login-form');
// Main page component (this is asyncronous)
var Landing = React.createClass({
mixins: [ReactAsync.Mixin],
getInitialStateAsync: function (callback) {
callback(null, this.props); // set the input props as state (equal to 'return this.props' in getInitialState, but async)
},
render: function() {
return (
<html>
<Head title={this.state.title} description={this.state.description}></Head>
<body id="landing">
<div className="container">
<div className="jumbotron text-center">
<h1><span className="fa fa-cloud"></span> {this.state.title}</h1>
<LoginForm />
</div>
</div>
</body>
</html>
);
}
});
module.exports = Landing;
// If the file is processed by the browser, it should mount itself to the document and 'overtake' the markup from the server without rerendering
if (typeof window !== 'undefined') {
// enable the react developer tools when developing (loads another 450k into the DOM..)
if (config.environment == 'development') {
window.React = require('react');
}
window.onload = function () {
React.renderComponent(Landing(), document);
}
}
|
import cookieParser from 'cookie-parser';
export default cookieParser();
|
// 存储全局的actions事件
import http from 'api/http'
export const getUserInfo = ({ commit }) => {
console.log(http)
http.get('user/userInfos').end((err, res) => {
console.log(err)
console.log(res)
})
}
|
#!/usr/bin/env node
//this hook installs all your plugins
// add your plugins to this list--either the identifier, the filesystem location or the URL
var pluginlist = [
"org.apache.cordova.device",
"org.apache.cordova.device-motion",
"org.apache.cordova.device-orientation",
"org.apache.cordova.geolocation",
"https://github.com/chrisekelley/AppPreferences/"
];
// no need to configure below
var fs = require('fs');
var path = require('path');
var sys = require('sys')
var exec = require('child_process').exec;
function puts(error, stdout, stderr) {
sys.puts(stdout)
}
pluginlist.forEach(function(plug) {
exec("cordova plugin add " + plug, puts);
});
|
"use strict";
var expect = require("expect.js"),
path = require("path"),
extractConfig = require("../../../lib/core/config/extractConfig.js");
describe("extractConfig", function () {
var config,
resultingConfig;
beforeEach(function () {
config = {
"env" : "development",
"server" : {
"port" : 9191,
"useBundling" : true
},
"client" : {
basePath : "/"
}
};
});
it("should should extract the given part and merge with globals", function () {
resultingConfig = extractConfig(config, "server");
expect(resultingConfig.port).to.be(config.server.port);
expect(resultingConfig.useBundling).to.be(config.server.useBundling);
expect(resultingConfig.env).to.be(config.env);
expect(resultingConfig).to.only.have.keys(["port", "useBundling", "env"]);
});
it("should should overwrite shared config with local config if set", function () {
config.server.env = "testing";
resultingConfig = extractConfig(config, "server");
expect(resultingConfig.port).to.be(config.server.port);
expect(resultingConfig.useBundling).to.be(config.server.useBundling);
expect(resultingConfig.env).to.be(config.server.env);
expect(resultingConfig).to.only.have.keys(["port", "useBundling", "env"]);
});
it("should overwrite and merge the values from shared to local", function () {
config = {
"use" : {
"websockets" : true
},
"client" : {
use : {
"client" : true
}
},
"server" : {
}
};
var clientConf = extractConfig(config, "client");
var serverConf = extractConfig(config, "server");
expect(clientConf.use.websockets).to.be(true);
expect(clientConf.use.client).to.be(true);
expect(serverConf.use.websockets).to.be(true);
expect(serverConf.use.client).to.be(undefined);
});
}); |
var Icon = require('../icon');
var element = require('magic-virtual-element');
var clone = require('../clone');
exports.render = function render(component) {
var props = clone(component.props);
delete props.children;
return element(
Icon,
props,
element('path', { d: 'M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4z' })
);
}; |
/**
* Created by kfirerez on 16/11/2016.
*/
import Q from 'q';
import axios from 'axios';
export default class ModelsServices {
static get baseURL() {
return 'http://localhost.rollout.io:4000';
}
static loadModels() {
return axios.get('http://localhost.rollout.io:4000/api/models');
}
} |
import React from 'react';
import { Link } from 'react-router';
class Navigation extends React.Component {
render() {
const { forward, backward, route } = this.props;
return (
<Link
to={route}
className={ forward ? 'navigation forward-nav' : 'navigation backward-nav' }
>
<img src={ forward ? './imgs/right-arrow.svg' : './imgs/left-arrow.svg' } />
</Link>
);
}
};
export default Navigation;
|
"use strict";
var adapter = global.adapter;
var resolved = adapter.resolved;
var rejected = adapter.rejected;
var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it
describe("2.2.1: Both `onFulfilled` and `onRejected` are optional arguments.", function () {
describe("2.2.1.1: If `onFulfilled` is not a function, it must be ignored.", function () {
describe("applied to a directly-rejected promise", function () {
function testNonFunction(nonFunction, stringRepresentation) {
specify("`onFulfilled` is " + stringRepresentation, function (done) {
rejected(dummy).then(nonFunction, function () {
done();
});
});
}
testNonFunction(undefined, "`undefined`");
testNonFunction(null, "`null`");
testNonFunction(false, "`false`");
testNonFunction(5, "`5`");
testNonFunction({}, "an object");
});
describe("applied to a promise rejected and then chained off of", function () {
function testNonFunction(nonFunction, stringRepresentation) {
specify("`onFulfilled` is " + stringRepresentation, function (done) {
rejected(dummy).then(function () { }, undefined).then(nonFunction, function () {
done();
});
});
}
testNonFunction(undefined, "`undefined`");
testNonFunction(null, "`null`");
testNonFunction(false, "`false`");
testNonFunction(5, "`5`");
testNonFunction({}, "an object");
});
});
describe("2.2.1.2: If `onRejected` is not a function, it must be ignored.", function () {
describe("applied to a directly-fulfilled promise", function () {
function testNonFunction(nonFunction, stringRepresentation) {
specify("`onRejected` is " + stringRepresentation, function (done) {
resolved(dummy).then(function () {
done();
}, nonFunction);
});
}
testNonFunction(undefined, "`undefined`");
testNonFunction(null, "`null`");
testNonFunction(false, "`false`");
testNonFunction(5, "`5`");
testNonFunction({}, "an object");
});
describe("applied to a promise fulfilled and then chained off of", function () {
function testNonFunction(nonFunction, stringRepresentation) {
specify("`onFulfilled` is " + stringRepresentation, function (done) {
resolved(dummy).then(undefined, function () { }).then(function () {
done();
}, nonFunction);
});
}
testNonFunction(undefined, "`undefined`");
testNonFunction(null, "`null`");
testNonFunction(false, "`false`");
testNonFunction(5, "`5`");
testNonFunction({}, "an object");
});
});
});
|
var async = require('async');
var fs = require('fs');
var loadDirectories = ['ccda'];
exports.load = function(callback){
async.reduce(loadDirectories, {}, function(loadedDirectories, directoryName, reduction){
var directory = "./"+directoryName+"/";
fs.readdir(directory, function(err, fileNames){
console.log("Loaded:",directory,"contains",fileNames);
async.reduce(fileNames, {}, function(loadedFiles, fileName, reduction){
fs.readFile(directory+fileName, 'utf-8', function(err, data){
loadedFiles[fileName] = data;
reduction(loadedFiles);
});
}, function(error, filesInDirectory){
loadedDirectories[directoryName] = filesInDirectory;
reduction(error, loadedDirectories);
});
});
}),
callback
}
exports.fixtures = function(){
loaded = {};
loadDirectories.forEach(function(directoryName){
loaded[directoryName] = {};
var directory = __dirname + "/" + directoryName+"/";
var fileNames = fs.readdirSync(directory);
fileNames.forEach(function(fileName){
loaded[directoryName][fileName] = fs.readFileSync(directory+fileName, 'utf-8');
});
});
return loaded;
}
exports.medications = function(){
return require('./medications');
}
|
'use strict';
var concat = require('..');
var File = require('gulp-util').File;
var fs = require('fs');
var path = require('path');
require('should');
var hiPOT = fs.readFileSync(__dirname + '/fixtures/hi.pot', {encoding: 'utf8'});
var byePOT = fs.readFileSync(__dirname + '/fixtures/bye.pot', {encoding: 'utf8'});
var byehiPOT = fs.readFileSync(__dirname + '/fixtures/bye_hi.pot', {encoding: 'utf8'});
describe('gulp-po-concat', function () {
it('should work on one file', function (done) {
var stream = concat();
stream.on('error', done);
stream.on('data', function (file) {
file.contents.toString().should.equal(hiPOT);
done();
});
stream.write(new File({
cwd: __dirname,
base: __dirname,
path: path.join(__dirname, 'messages.pot'),
contents: new Buffer(hiPOT)
}));
stream.end();
});
it('should work on two files', function (done) {
var stream = concat();
stream.on('error', done);
stream.on('data', function (file) {
file.contents.toString().should.equal(byehiPOT);
done();
});
stream.write(new File({
cwd: __dirname,
base: __dirname,
path: path.join(__dirname, 'messages.pot'),
contents: new Buffer(hiPOT)
}));
stream.write(new File({
cwd: __dirname,
base: __dirname,
path: path.join(__dirname, 'messages.pot'),
contents: new Buffer(byePOT)
}));
stream.end();
});
it("shouldn't combine messages from different domains", function (done) {
var stream = concat();
stream.on('error', done);
stream.once('data', function (file) {
file.contents.toString().should.equal(hiPOT);
stream.on('data', function (file) {
file.contents.toString().should.equal(byePOT);
done();
});
});
stream.write(new File({
cwd: __dirname,
base: __dirname,
path: path.join(__dirname, 'messages1.pot'),
contents: new Buffer(hiPOT)
}));
stream.write(new File({
cwd: __dirname,
base: __dirname,
path: path.join(__dirname, 'messages2.pot'),
contents: new Buffer(byePOT)
}));
stream.end();
});
it('should be able to force a single domain via a string', function (done) {
var stream = concat({
domain: 'messages'
});
stream.on('error', done);
stream.on('data', function (file) {
path.basename(file.path).should.equal('messages.pot');
file.contents.toString().should.equal(byehiPOT);
done();
});
stream.write(new File({
cwd: __dirname,
base: __dirname,
path: path.join(__dirname, 'hi.pot'),
contents: new Buffer(hiPOT)
}));
stream.write(new File({
cwd: __dirname,
base: __dirname,
path: path.join(__dirname, 'bye.pot'),
contents: new Buffer(byePOT)
}));
stream.end();
});
it('should be able to force a domain via a function', function (done) {
var stream = concat({
domain: function (file) {
return path.basename(file.path) + '-override';
}
});
stream.on('error', done);
stream.once('data', function (file) {
path.basename(file.path).should.equal('messages1.pot-override.pot');
file.contents.toString().should.equal(hiPOT);
stream.on('data', function (file) {
path.basename(file.path).should.equal('messages2.pot-override.pot');
file.contents.toString().should.equal(byePOT);
done();
});
});
stream.write(new File({
cwd: __dirname,
base: __dirname,
path: path.join(__dirname, 'messages1.pot'),
contents: new Buffer(hiPOT)
}));
stream.write(new File({
cwd: __dirname,
base: __dirname,
path: path.join(__dirname, 'messages2.pot'),
contents: new Buffer(byePOT)
}));
stream.end();
});
});
|
const callWithPromise = (method, ...args) => {
return new Promise((resolve, reject) => {
Meteor.call(method, ...args, (err, res) => {
if (err) reject(err.reason || 'Something went wrong.');
resolve(res);
});
});
};
Meteor.callWithPromise = callWithPromise;
const waitForHandleToBeReady = handle => {
return new Promise((resolve, reject) => {
Tracker.autorun(c => {
if (handle.ready()) {
c.stop();
resolve();
}
});
});
};
export { callWithPromise, waitForHandleToBeReady };
|
import {Items, Children} from './collections';
const ITEMS = 5;
const CHILDREN_PER_ITEM = 5;
export default () => {
Items.remove({});
Children.remove({});
for (let i = 0; i < ITEMS; i++) {
const itemId = Items.insert({
name: 'Name - ' + i
});
for (let j = 0; j < CHILDREN_PER_ITEM; j++) {
Children.insert({
name: 'Child - ' + i + '- ' + j,
itemId
})
}
}
}
|
'use strict';
var slides = document.getElementsByClassName('slide');
var currentSlide = 0;
var isAnimating = false;
_Intitialize();
/**
* =======================
* FUNCTION DEFINITIONS
* =======================
*/
/**
* Function: Initalize
*
* App Initializer
*/
function _Intitialize() {
for (var i = 0, limit = slides.length; i < limit; i++) {
slides[i].style.zIndex = slides.length - i;
}
}
/**
* Function: ShowSample
*/
function ShowSample() {
slides[currentSlide].children[1].style.display = 'block';
}
/**
* Function: HideSample
*/
function HideSample() {
slides[currentSlide].children[1].style.display = 'none';
}
/**
* Function: NextSlide
*/
function _NextSlide() {
if (currentSlide === (slides.length - 1)) {
return;
}
TweenLite.to(slides[currentSlide], 0.4, {
left: '-100px',
ease: 'easeInExpo',
display: 'none',
opacity: 0,
onComplete: function() {
currentSlide++;
isAnimating = false;
}
});
}
/**
* Function: PrevSlide
*/
function _PrevSlide() {
if ( ! currentSlide) {
return;
}
TweenLite.to(slides[--currentSlide], 0.5, {
left: '0px',
ease: 'easeOutExpo',
display: 'block',
opacity: 1,
onComplete: function() {
isAnimating = false;
}
});
}
/**
* Function: ToggleSize
*/
var size = 1;
function ToggleSize() {
switch(size) {
case 1:
TweenLite.to(slides[currentSlide].children[1].children[1], 0.5, {
width: '992px',
height: '600px'
});
size = 2;
break;
case 2:
TweenLite.to(slides[currentSlide].children[1].children[1], 0.5, {
width: '776px',
height: '550px'
});
size = 3;
break;
case 3:
TweenLite.to(slides[currentSlide].children[1].children[1], 0.5, {
width: '1244px',
height: '620px'
});
size = 1;
break;
}
}
/**
* Function: Keydown
*
* Manipulate keypress actions.
*
* Parameters:
* (Object) evt - Keydown object
*
* Returns:
* null
*/
function Keydown(evt) {
if (isAnimating) {
return;
}
// keyCode source: http://www.asquare.net/javascript/tests/KeyCode.html
switch (evt.keyCode) {
case 38: // Up
case 37: // Right
_PrevSlide();
break;
case 39: // Left
_NextSlide();
break;
case 40: // Down
break;
}
}
window.onkeydown = Keydown;
|
import React, { Component } from 'react';
import { articleMounting } from '../../actions/index.js';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import Parser from 'html-react-parser';
import { Parallax, Background } from 'react-parallax';
import { Image } from 'react-bootstrap';
class FrequentlyAskedQuestions extends Component {
componentWillMount() {
this.props.articleMounting("frequently-asked-questions");
}
render() {
return (
<article className="frequently-asked-questions">
<Parallax strength={200}>
<Background>
<Image
className="parallax-image"
src={this.props.siteConfig.imageCDN + this.props.siteConfig.faq.image}
alt={this.props.siteConfig.faq.title}
/>
</Background>
<h1 className="faq-title" >{this.props.siteConfig.faq.title}</h1>
<div className="faq-copy" >{Parser(this.props.siteConfig.faq.copy.join(''))}</div>
</Parallax>
</article>
);
}
};
const mapStateToProps = (state) => ({ siteConfig: state.siteConfig });
const mapDispatchToProps = (dispatch) => bindActionCreators({ articleMounting }, dispatch);
export default connect(mapStateToProps, mapDispatchToProps) (FrequentlyAskedQuestions);
|
import * as utils from 'ld/board/utils'
export default class Tile {
constructor(data, coord) {
this.type = data.type
this.restrict = data.restrict
this.movementCost = data.movementCost
this.image = data.image
this.coord = coord
this.pawns = []
this.enemies = []
this.item = null
this.spawnPoint = false
this.event = false
}
addPawn(id) { this.pawns.push(id) }
removePawn(id) {
let index = this.pawns.indexOf(id)
if (index >= 0) {
return this.pawns.splice(this.pawns.indexOf(id), 1)
}
}
addEnemy(id) { this.enemies.push(id) }
removeEnemy(id) {
let index = this.enemies.indexOf(id)
if (index >= 0) {
return this.enemies.splice(this.enemies.indexOf(id), 1)
}
}
addItem(id) { this.item = id }
removeItem(id) {
let item = this.item
this.item = null
return item
}
addSpawnPoint(id) { this.spawnPoint = true }
removeSpawnPoint(id) {
let v = this.spawnPoint
this.spawnPoint = false
return v
}
}
|
// Chronograph Class
// @params settings: object
// @params parentWatch: Watch instance
//
// The chronograph complication requires a buttons and hands object
// the buttons object contains the start and reset buttons which control the hands
// The hands are designed and used to indicate tenth seconds, seconds, and minutes
// for timing events. Flyback and Split-Second (rattrapante) functionality is supported for timing laps.
//
// MONO-PUSHER
// Pusher 1: Click to start
// Pusher 1: Click to pause
// Pusher 1: Click to reset
//
// DUAL-PUSHER
// Standard
// Pusher 1: Starts the time
// Pusher 1: Pauses all hands
// Pusher 2: Resets all hands
//
// Flyback
// Pusher 1: Starts the time
// Pusher 2: Resets all hands then continues
//
// Rattrapante
// Pusher 1: Starts the time
// Pusher 2: Stops the lap hand
// Pusher 2: Resets lap hand to current second hand
// Pusher 1: Stops all hands
// Pusher 2: Resets all hands
//
// TRI-PUSHER
// Pusher 1: Starts the time
// Pusher 2: Pauses the lap hand
// Pusher 2: Resets the lap hand back to constant second hand
// Pusher 3: Stops all hands
// Pusher 1: Resets all hands to original position
class Chronograph {
constructor(settings, parentWatch) {
this.errorChecking(settings);
this.buttons = {
primary: document.getElementById(settings.buttons.primary),
secondary: document.getElementById(settings.buttons.secondary) || null,
tertiary: document.getElementById(settings.buttons.tertiary) || null
};
this.hands = {
tenth: document.getElementById(settings.hands.tenth) || null,
second: document.getElementById(settings.hands.second),
minute: document.getElementById(settings.hands.minute),
hour: document.getElementById(settings.hands.hour) || null,
lap: document.getElementById(settings.hands.lap) || null,
};
this.flyback = settings.flyback || false;
this.rattrapante = settings.rattrapante || false;
this.monopusher = false;
this.dualpusher = false;
this.tripusher = false;
this.interval;
this.counter = 1;
this.isRunning = false;
this.isPaused = false;
this.lapActive = false;
this.parent = parentWatch;
if (!this.parent.testing) this.init();
}
errorChecking(settings) {
if (!settings.buttons || !settings.hands) throw new ReferenceError("The Chronograph requires a settings object containing both the buttons and hands.");
if (!settings.hands.second || !settings.hands.minute) throw new ReferenceError("The Chronograph requires at least a second and minute hands.");
if (!settings.buttons.secondary && !settings.buttons.tertiary && settings.rattrapante) throw new ReferenceError("A monopusher chronograph cannot support rattrapante functionality.");
if (!settings.buttons.secondary && !settings.buttons.tertiary && settings.flyback) throw new ReferenceError("A monopusher chronograph cannot support flyuback functionality.");
if (settings.rattrapante && !settings.hands.lap) throw new ReferenceError("A rattrapante Chronograph requires a 'lap' hand.");
}
checkForChronographType() {
if (this.buttons.primary && !this.buttons.secondary && !this.buttons.tertiary) {
this.monopusher = true;
} else if (this.buttons.primary && this.buttons.secondary && !this.buttons.tertiary) {
this.dualpusher = true;
} else if (this.buttons.primary && this.buttons.secondary && this.buttons.tertiary) {
this.tripusher = true;
this.rattrapante = true;
} else {
throw "The Chronograph class expects the buttons to be added sequentially beginning with primary, secondary, and, lastly, tertiary.";
}
}
bindEvents() {
this.buttons.primary.addEventListener('click', () => {
this.toggleActiveState(this.buttons.primary);
if (this.monopusher) {
if (!this.isRunning && !this.isPaused) {
this.isRunning = true;
this.startInterval();
} else if (this.isRunning && !this.isPaused) {
this.isRunning = false;
this.isPaused = true;
this.clearInterval();
} else if (!this.isRunning && this.isPaused) {
this.isPaused = false;
this.resetHands();
}
} else if (this.dualpusher) {
this.isRunning = !this.isRunning;
if (this.isRunning) {
this.startInterval();
} else {
this.clearInterval();
}
} else if (this.tripusher) {
if (!this.isRunning && !this.isPaused) {
this.isRunning = true;
this.startInterval();
} else if (!this.isRunning && this.isPaused) {
this.isRunning = false;
this.isPaused = false;
this.counter = 1;
this.clearInterval();
this.resetHands();
}
}
});
this.buttons.primary.addEventListener('transitionend', () => {
if (this.buttons.primary.classList.contains('active')) this.toggleActiveState(this.buttons.primary);
});
if (this.buttons.secondary) {
this.buttons.secondary.addEventListener('click', () => {
this.toggleActiveState(this.buttons.secondary);
if (this.dualpusher) {
this.resetHands();
this.counter = 1;
if ((!this.rattrapante && !this.flyback) || !this.isRunning) {
this.clearInterval();
this.isRunning = false;
}
} else if (this.tripusher) {
if (this.isRunning) {
this.resetHands();
}
}
});
this.buttons.secondary.addEventListener('transitionend', () => {
if (this.buttons.secondary.classList.contains('active')) this.toggleActiveState(this.buttons.secondary);
});
}
if (this.buttons.tertiary) {
this.buttons.tertiary.addEventListener('click', () => {
this.toggleActiveState(this.buttons.tertiary);
this.isRunning = !this.isRunning;
if (this.isRunning) {
this.startInterval();
this.isPaused = false;
} else {
this.clearInterval();
this.isRunning = false;
this.isPaused = true;
}
});
this.buttons.tertiary.addEventListener('transitionend', () => {
if (this.buttons.tertiary.classList.contains('active')) this.toggleActiveState(this.buttons.tertiary);
});
}
}
clearInterval() {
clearInterval(this.interval);
this.interval = null;
}
startInterval() {
this.interval = setInterval(() => {
this.rotateHands();
this.counter++;
}, 100);
}
resetHands() {
if (this.rattrapante && this.isRunning) {
if (!this.flyback) {
this.lapActive = !this.lapActive;
if (!this.lapActive) {
this.hands.lap.style.transform = `rotate(${this.parent.getCurrentRotateValue(this.hands.second)}deg)`;
}
} else {
this.lapActive = true;
this.hands.lap.style.transform = `rotate(${this.parent.getCurrentRotateValue(this.hands.second)}deg)`;
this.hands.second.style.transform = 'rotate(0deg)';
if (this.hands.tenth) this.hands.tenth.style.transform = 'rotate(0deg)';
}
} else {
Object.keys(this.hands).map(hand => {
if (this.hands[hand]) this.hands[hand].style.transform = 'rotate(0deg)';
});
this.lapActive = false;
}
}
rotateHands() {
let tenthValue = this.hands.tenth ? this.parent.getCurrentRotateValue(this.hands.tenth) : 0;
let secondValue = this.parent.getCurrentRotateValue(this.hands.second);
let minuteValue = this.parent.getCurrentRotateValue(this.hands.minute);
let hourValue = this.hands.hour ? this.parent.getCurrentRotateValue(this.hands.hour) : 0;
if (this.hands.tenth) this.hands.tenth.style.transform = `rotate(${tenthValue + 0.6}deg)`;
if (this.counter % 10 === 0) {
this.hands.second.style.transform = `rotate(${secondValue + 6}deg)`;
if (!this.lapActive && this.hands.lap) this.hands.lap.style.transform = `rotate(${secondValue + 6}deg)`;
}
if (this.counter % 600 === 0) {
this.hands.minute.style.transform = `rotate(${minuteValue + 6}deg)`;
if (this.hands.hour) this.hands.hour.style.transform = `rotate(${hourValue + 0.5}deg)`;
this.counter = 0;
}
}
toggleActiveState(btn) {
btn.classList.toggle('active');
}
init() {
this.checkForChronographType();
this.bindEvents();
Object.keys(this.buttons).map(btn => {
if (this.buttons[btn]) {
this.buttons[btn].style.cursor = 'pointer';
}
});
}
}
module.exports = Chronograph; |
'use strict';
var logMethods = require('./log');
var type = require('./type');
var when = require('./when');
var Mouse = require('./mouse');
module.exports = GlobalMouse;
/**
* Global mouse object handling global mouse commands
*
* @constructor
* @class GlobalMouse
* @module WebDriver
* @submodule Interaction
* @param {Driver} driver
*/
function GlobalMouse (driver) {
this._driver = driver;
}
/////////////////////
// Private Methods //
/////////////////////
/**
* Logs a method call by an event
*
* @param {object} event
* @method _logMethodCall
* @private
*/
GlobalMouse.prototype._logMethodCall = function (event) {
event.target = 'GlobalMouse';
this._driver._logMethodCall(event);
};
/**
* Performs a context dependent JSON request for the current session.
* The result is parsed for errors.
*
* @method _requestJSON
* @private
* @param {String} method
* @param {String} path
* @param {*} [body]
* @return {*}
*/
GlobalMouse.prototype._requestJSON = function (method, path, body) {
return this._driver._requestJSON(method, path, body);
};
////////////////////
// Public Methods //
////////////////////
/**
* Gets the driver object.
* Direct-access. No need to wait.
*
* @return {Driver}
*/
GlobalMouse.prototype.getDriver = function () {
return this._driver;
};
/**
* Move the mouse by an offset of the specified element. If no element is specified,
* the move is relative to the current mouse cursor. If an element is provided but
* no offset, the mouse will be moved to the center of the element. If the element
* is not visible, it will be scrolled into view.
*
* @protected
* @method _moveTo
* @param {String|undefined} elementId
* @param {Number|undefined} xOffset
* @param {Number|undefined} yOffset
*/
GlobalMouse.prototype._moveTo = function (elementId, xOffset, yOffset) {
var params = {};
if (elementId !== undefined) {
params.element = elementId;
}
if ((xOffset !== undefined) || (yOffset !== undefined)) {
params.xoffset = xOffset;
params.yoffset = yOffset;
}
return this._requestJSON('POST', '/moveto', params);
};
/**
* Move the mouse by an offset relative to the current mouse cursor position
*
* @method moveTo
* @param {Number} xOffset
* @param {Number} yOffset
*/
GlobalMouse.prototype.moveTo = function (xOffset, yOffset) {
type('xOffset', xOffset, 'Number');
type('yOffset', yOffset, 'Number');
return this._moveTo(undefined, xOffset, yOffset);
};
/**
* Click any mouse button at the current location of the mouse cursor
*
* @method click
* @param {Number} [button=Mouse.BUTTON_LEFT]
*/
GlobalMouse.prototype.click = function (button) {
button = button || Mouse.BUTTON_LEFT;
type('button', button, 'Number');
return this._requestJSON('POST', '/click', { button: button });
};
/**
* Click any mouse button at an offset relative to the current location of the mouse cursor
*
* @method clickAt
* @param {Number} xOffset
* @param {Number} yOffset
* @param {Number} [button=Mouse.BUTTON_LEFT]
*/
GlobalMouse.prototype.clickAt = function (xOffset, yOffset, button) {
return when(this.moveTo(xOffset, yOffset), function () {
return this.click(button);
}.bind(this));
};
/**
* Double-clicks at the current location of the mouse cursor
*
* @method doubleClick
*/
GlobalMouse.prototype.doubleClick = function () {
return this._requestJSON('POST', '/doubleclick');
};
/**
* Double-clicks at the current location of the mouse cursor
*
* @method doubleClickAt
* @param {Number} x
* @param {Number} y
*/
GlobalMouse.prototype.doubleClickAt = function (x, y) {
return when(this.moveTo(x, y), function () {
return this._requestJSON('POST', '/doubleclick');
}.bind(this));
};
/**
* Click and hold the any mouse button at the current location of the mouse cursor
*
* @method buttonDown
* @param {Number} [button=Mouse.BUTTON_LEFT]
*/
GlobalMouse.prototype.buttonDown = function (button) {
button = button || Mouse.BUTTON_LEFT;
type('button', button, 'Number');
return this._requestJSON('POST', '/buttondown', { button: button });
};
/**
* Click and hold the any mouse button relative to the current location of the mouse cursor
*
* @method buttonDownAt
* @param {Number} xOffset
* @param {Number} yOffset
* @param {Number} [button=Mouse.BUTTON_LEFT]
*/
GlobalMouse.prototype.buttonDownAt = function (xOffset, yOffset, button) {
return when(this.moveTo(xOffset, yOffset), function () {
return this.buttonDown(button);
}.bind(this));
};
/**
* Releases the mouse button previously held at the current location of the mouse cursor
*
* @method buttonUp
* @param {Number} [button=Mouse.BUTTON_LEFT]
*/
GlobalMouse.prototype.buttonUp = function (button) {
button = button || Mouse.BUTTON_LEFT;
type('button', button, 'Number');
return this._requestJSON('POST', '/buttonup', { button: button });
};
/**
* Releases the mouse button previously held at the current location of the mouse cursor
*
* @method buttonUpAt
* @param {Number} xOffset
* @param {Number} yOffset
* @param {Number} [button=Mouse.BUTTON_LEFT]
*/
GlobalMouse.prototype.buttonUpAt = function (xOffset, yOffset, button) {
return when(this.moveTo(xOffset, yOffset), function () {
return this.buttonUp(button);
}.bind(this));
};
logMethods(GlobalMouse.prototype);
|
Object.assign = require('object-assign');
if (typeof Promise === 'undefined') {
require('promise/lib/rejection-tracking').enable();
window.Promise = require('promise/lib/es6-extensions.js')
}
if (typeof window.fetch === 'undefined') {
require('whatwg-fetch')
} |
import {
visitAndApproveStorage, testSnapshot
} from '../../support/ui-test-helper.js'
describe('use all parts of svg-edit', function () {
before(() => {
visitAndApproveStorage()
})
it('check tool_source_set', function () {
cy.get('#tool_source').click({ force: true })
cy.get('#svg_source_textarea')
.type('{selectall}', { force: true })
.type(`<svg width="640" height="480" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg">
<g class="layer">
<title>Layer 1</title>
</g>
</svg>`, { force: true, parseSpecialCharSequences: false })
cy.get('#tool_source_save').click({ force: true })
testSnapshot()
})
it('check tool_polygon', function () {
cy.get('#tool_polygon')
.click({ force: true })
cy.get('#svgcontent')
.trigger('mousedown', 325, 250, { force: true })
.trigger('mousemove', 325, 345, { force: true })
.trigger('mouseup', { force: true })
testSnapshot()
})
it('check tool_polygon_clone', function () {
cy.get('#svg_1').click({ force: true })
cy.get('#tool_clone').click({ force: true })
testSnapshot()
})
it('check tool_polygon_change_class', function () {
cy.get('#svg_2').click({ force: true })
cy.get('#elem_class').shadow().find('elix-input').eq(0).shadow().find('#inner').eq(0)
.type('svg_2_class{enter}', { force: true })
cy.get('#svg_2')
.should('satisfy', ($el) => {
const classList = Array.from($el[0].classList)
return classList.includes('svg_2_class')
})
})
it('check tool_polygon_change_id', function () {
cy.get('#svg_2').click({ force: true }).click({ force: true })
cy.get('#elem_id').shadow().find('elix-input').eq(0).shadow().find('#inner').eq(0)
.type('_id{enter}', { force: true })
cy.get('#svg_2_id')
.should('satisfy', ($el) => {
const classList = Array.from($el[0].classList)
return classList.includes('svg_2_class')
})
})
it('check tool_polygon_change_rotation', function () {
cy.get('#svg_2_id').click({ force: true })
for (let n = 0; n < 5; n++) {
cy.get('#angle').shadow().find('elix-number-spin-box').eq(0).shadow().find('#upButton').eq(0)
.click({ force: true })
}
testSnapshot()
})
it('check tool_polygon_change_blur', function () {
cy.get('#svg_2_id').click({ force: true })
for (let n = 0; n < 10; n++) {
cy.get('#blur').shadow().find('elix-number-spin-box').eq(0).shadow().find('#upButton').eq(0)
.click({ force: true })
}
testSnapshot()
})
it('check tool_polygon_change_opacity', function () {
cy.get('#svg_2_id').click({ force: true })
for (let n = 0; n < 10; n++) {
cy.get('#opacity').shadow().find('elix-number-spin-box').eq(0).shadow().find('#downButton').eq(0)
.click({ force: true })
}
testSnapshot()
})
it('check tool_polygon_bring_to_back', function () {
cy.get('#svg_2_id').click({ force: true })
cy.get('#tool_move_bottom').click({ force: true })
testSnapshot()
})
it('check tool_polygon_bring_to_front', function () {
cy.get('#svg_2_id').click({ force: true })
cy.get('#tool_move_top').click({ force: true })
testSnapshot()
})
it('check tool_polygon_delete', function () {
cy.get('#svg_2_id').click({ force: true })
cy.get('#tool_delete').click({ force: true })
testSnapshot()
})
it('check tool_polygon_align_to_page', function () {
cy.get('#svg_1').click({ force: true })
cy.get('#tool_position').shadow().find('elix-dropdown-list').eq(0).invoke('attr', 'opened', 'opened')
cy.get('#tool_position').find('se-list-item').eq(0).shadow().find('elix-option').eq(0)
.click({ force: true })
testSnapshot()
})
/* it('check tool_polygon_change_x_y_coordinate', function () {
cy.get('#svg_1').click({ force: true });
for(let n = 0; n < 25; n ++){
cy.get('#selected_x').shadow().find('elix-number-spin-box').eq(0).shadow().find('#upButton').eq(0)
.click({ force: true });
}
for(let n = 0; n < 25; n ++){
cy.get('#selected_y').shadow().find('elix-number-spin-box').eq(0).shadow().find('#upButton').eq(0)
.click({ force: true });
}
testSnapshot();
}); */
it('check tool_polygon_change_stroke_width', function () {
cy.get('#svg_1').click({ force: true })
for (let n = 0; n < 10; n++) {
cy.get('#stroke_width').shadow().find('elix-number-spin-box').eq(0).shadow().find('#upButton').eq(0)
.click({ force: true })
}
testSnapshot()
})
it('check tool_polygon_change_stoke_fill_color', function () {
cy.get('#svg_1').click({ force: true })
cy.get('#stroke_color').shadow().find('#picker').eq(0).click({ force: true })
cy.get('#stroke_color').shadow().find('#color_picker').eq(0)
.find('#jGraduate_colPick').eq(0).find('#jPicker-table').eq(0)
.find('.QuickColor').eq(51).click({ force: true })
cy.get('#stroke_color').shadow().find('#color_picker').eq(0)
.find('#jGraduate_colPick').eq(0).find('#jPicker-table').eq(0)
.find('#Ok').eq(0).click({ force: true })
cy.get('#fill_color').shadow().find('#picker').eq(0).click({ force: true })
cy.get('#fill_color').shadow().find('#color_picker').eq(0)
.find('#jGraduate_colPick').eq(0).find('#jPicker-table').eq(0)
.find('.QuickColor').eq(3).click({ force: true })
cy.get('#fill_color').shadow().find('#color_picker').eq(0)
.find('#jGraduate_colPick').eq(0).find('#jPicker-table').eq(0)
.find('#Ok').eq(0).click({ force: true })
testSnapshot()
})
it('check tool_polygon_change_sides', function () {
cy.get('#svg_1').click({ force: true })
cy.get('#polySides').shadow().find('elix-number-spin-box').eq(0).shadow().find('#upButton').eq(0)
.click({ force: true })
testSnapshot()
})
})
|
"use strict";
var EventEmitter = require('events').EventEmitter
, inherits = require('util').inherits
, getSingleProperty = require('./utils').getSingleProperty
, shallowClone = require('./utils').shallowClone
, parseIndexOptions = require('./utils').parseIndexOptions
, debugOptions = require('./utils').debugOptions
, CommandCursor = require('./command_cursor')
, handleCallback = require('./utils').handleCallback
, toError = require('./utils').toError
, ReadPreference = require('./read_preference')
, f = require('util').format
, Admin = require('./admin')
, Code = require('mongodb-core').BSON.Code
, CoreReadPreference = require('mongodb-core').ReadPreference
, MongoError = require('mongodb-core').MongoError
, ObjectID = require('mongodb-core').ObjectID
, Define = require('./metadata')
, Logger = require('mongodb-core').Logger
, Collection = require('./collection')
, crypto = require('crypto');
var debugFields = ['authSource', 'w', 'wtimeout', 'j', 'native_parser', 'forceServerObjectId'
, 'serializeFunctions', 'raw', 'promoteLongs', 'bufferMaxEntries', 'numberOfRetries', 'retryMiliSeconds'
, 'readPreference', 'pkFactory'];
/**
* @fileOverview The **Db** class is a class that represents a MongoDB Database.
*
* @example
* var MongoClient = require('mongodb').MongoClient,
* test = require('assert');
* // Connection url
* var url = 'mongodb://localhost:27017/test';
* // Connect using MongoClient
* MongoClient.connect(url, function(err, db) {
* // Get an additional db
* var testDb = db.db('test');
* db.close();
* });
*/
/**
* Creates a new Db instance
* @class
* @param {string} databaseName The name of the database this instance represents.
* @param {(Server|ReplSet|Mongos)} topology The server topology for the database.
* @param {object} [options=null] Optional settings.
* @param {string} [options.authSource=null] If the database authentication is dependent on another databaseName.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.native_parser=true] Select C++ bson parser instead of JavaScript parser.
* @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.
* @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
* @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
* @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
* @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.
* @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys.
* @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
* @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported)
* @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported)
* @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology.
* @property {number} bufferMaxEntries Current bufferMaxEntries value for the database
* @property {string} databaseName The name of the database this instance represents.
* @property {object} options The options associated with the db instance.
* @property {boolean} native_parser The current value of the parameter native_parser.
* @property {boolean} slaveOk The current slaveOk value for the db instance.
* @property {object} writeConcern The current write concern values.
* @fires Db#close
* @fires Db#authenticated
* @fires Db#reconnect
* @fires Db#error
* @fires Db#timeout
* @fires Db#parseError
* @fires Db#fullsetup
* @return {Db} a Db instance.
*/
var Db = function(databaseName, topology, options) {
options = options || {};
if(!(this instanceof Db)) return new Db(databaseName, topology, options);
EventEmitter.call(this);
var self = this;
// Get the promiseLibrary
var promiseLibrary = options.promiseLibrary;
// No promise library selected fall back
if(!promiseLibrary) {
promiseLibrary = typeof global.Promise == 'function' ?
global.Promise : require('es6-promise').Promise;
}
// Ensure we put the promiseLib in the options
options.promiseLibrary = promiseLibrary;
// var self = this; // Internal state of the db object
this.s = {
// Database name
databaseName: databaseName
// DbCache
, dbCache: {}
// Children db's
, children: []
// Topology
, topology: topology
// Options
, options: options
// Logger instance
, logger: Logger('Db', options)
// Get the bson parser
, bson: topology ? topology.bson : null
// Authsource if any
, authSource: options.authSource
// Unpack read preference
, readPreference: options.readPreference
// Set buffermaxEntries
, bufferMaxEntries: typeof options.bufferMaxEntries == 'number' ? options.bufferMaxEntries : -1
// Parent db (if chained)
, parentDb: options.parentDb || null
// Set up the primary key factory or fallback to ObjectID
, pkFactory: options.pkFactory || ObjectID
// Get native parser
, nativeParser: options.nativeParser || options.native_parser
// Promise library
, promiseLibrary: promiseLibrary
// No listener
, noListener: typeof options.noListener == 'boolean' ? options.noListener : false
// ReadConcern
, readConcern: options.readConcern
}
// Ensure we have a valid db name
validateDatabaseName(self.s.databaseName);
// If we have specified the type of parser
if(typeof self.s.nativeParser == 'boolean') {
if(self.s.nativeParser) {
topology.setBSONParserType("c++");
} else {
topology.setBSONParserType("js");
}
}
// Add a read Only property
getSingleProperty(this, 'serverConfig', self.s.topology);
getSingleProperty(this, 'bufferMaxEntries', self.s.bufferMaxEntries);
getSingleProperty(this, 'databaseName', self.s.databaseName);
// Last ismaster
Object.defineProperty(this, 'options', {
enumerable:true,
get: function() { return self.s.options; }
});
// Last ismaster
Object.defineProperty(this, 'native_parser', {
enumerable:true,
get: function() { return self.s.topology.parserType() == 'c++'; }
});
// Last ismaster
Object.defineProperty(this, 'slaveOk', {
enumerable:true,
get: function() {
if(self.s.options.readPreference != null
&& (self.s.options.readPreference != 'primary' || self.s.options.readPreference.mode != 'primary')) {
return true;
}
return false;
}
});
Object.defineProperty(this, 'writeConcern', {
enumerable:true,
get: function() {
var ops = {};
if(self.s.options.w != null) ops.w = self.s.options.w;
if(self.s.options.j != null) ops.j = self.s.options.j;
if(self.s.options.fsync != null) ops.fsync = self.s.options.fsync;
if(self.s.options.wtimeout != null) ops.wtimeout = self.s.options.wtimeout;
return ops;
}
});
// This is a child db, do not register any listeners
if(options.parentDb) return;
if(this.s.noListener) return;
// Add listeners
topology.on('error', createListener(self, 'error', self));
topology.on('timeout', createListener(self, 'timeout', self));
topology.on('close', createListener(self, 'close', self));
topology.on('parseError', createListener(self, 'parseError', self));
topology.once('open', createListener(self, 'open', self));
topology.once('fullsetup', createListener(self, 'fullsetup', self));
topology.once('all', createListener(self, 'all', self));
topology.on('reconnect', createListener(self, 'reconnect', self));
}
inherits(Db, EventEmitter);
var define = Db.define = new Define('Db', Db, false);
/**
* The callback format for the Db.open method
* @callback Db~openCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {Db} db The Db instance if the open method was successful.
*/
// Internal method
var open = function(self, callback) {
self.s.topology.connect(self, self.s.options, function(err, topology) {
if(callback == null) return;
var internalCallback = callback;
callback == null;
if(err) {
self.close();
return internalCallback(err);
}
internalCallback(null, self);
});
}
/**
* Open the database
* @method
* @param {Db~openCallback} [callback] Callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.open = function(callback) {
var self = this;
// We provided a callback leg
if(typeof callback == 'function') return open(self, callback);
// Return promise
return new self.s.promiseLibrary(function(resolve, reject) {
open(self, function(err, db) {
if(err) return reject(err);
resolve(db);
})
});
}
define.classMethod('open', {callback: true, promise:true});
/**
* The callback format for results
* @callback Db~resultCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {object} result The result object if the command was executed successfully.
*/
var executeCommand = function(self, command, options, callback) {
// Did the user destroy the topology
if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));
// Get the db name we are executing against
var dbName = options.dbName || options.authdb || self.s.databaseName;
// If we have a readPreference set
if(options.readPreference == null && self.s.readPreference) {
options.readPreference = self.s.readPreference;
}
// Convert the readPreference
if(options.readPreference && typeof options.readPreference == 'string') {
options.readPreference = new CoreReadPreference(options.readPreference);
} else if(options.readPreference instanceof ReadPreference) {
options.readPreference = new CoreReadPreference(options.readPreference.mode
, options.readPreference.tags);
}
// Debug information
if(self.s.logger.isDebug()) self.s.logger.debug(f('executing command %s against %s with options [%s]'
, JSON.stringify(command), f('%s.$cmd', dbName), JSON.stringify(debugOptions(debugFields, options))));
// Execute command
self.s.topology.command(f('%s.$cmd', dbName), command, options, function(err, result) {
if(err) return handleCallback(callback, err);
handleCallback(callback, null, result.result);
});
}
/**
* Execute a command
* @method
* @param {object} command The command hash
* @param {object} [options=null] Optional settings.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {Db~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.command = function(command, options, callback) {
var self = this;
// Change the callback
if(typeof options == 'function') callback = options, options = {};
// Clone the options
options = shallowClone(options);
// Do we have a callback
if(typeof callback == 'function') return executeCommand(self, command, options, callback);
// Return a promise
return new this.s.promiseLibrary(function(resolve, reject) {
executeCommand(self, command, options, function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
}
define.classMethod('command', {callback: true, promise:true});
/**
* The callback format for results
* @callback Db~noResultCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {null} result Is not set to a value
*/
/**
* Close the db and it's underlying connections
* @method
* @param {boolean} force Force close, emitting no events
* @param {Db~noResultCallback} [callback] The result callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.close = function(force, callback) {
if(typeof force == 'function') callback = force, force = false;
this.s.topology.close(force);
var self = this;
// Fire close event if any listeners
if(this.listeners('close').length > 0) {
this.emit('close');
// If it's the top level db emit close on all children
if(this.parentDb == null) {
// Fire close on all children
for(var i = 0; i < this.s.children.length; i++) {
this.s.children[i].emit('close');
}
}
// Remove listeners after emit
self.removeAllListeners('close');
}
// Close parent db if set
if(this.s.parentDb) this.s.parentDb.close();
// Callback after next event loop tick
if(typeof callback == 'function') return process.nextTick(function() {
handleCallback(callback, null);
})
// Return dummy promise
return new this.s.promiseLibrary(function(resolve, reject) {
resolve();
});
}
define.classMethod('close', {callback: true, promise:true});
/**
* Return the Admin db instance
* @method
* @return {Admin} return the new Admin db instance
*/
Db.prototype.admin = function() {
return new Admin(this, this.s.topology, this.s.promiseLibrary);
};
define.classMethod('admin', {callback: false, promise:false, returns: [Admin]});
/**
* The callback format for the collection method, must be used if strict is specified
* @callback Db~collectionResultCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {Collection} collection The collection instance.
*/
/**
* Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you can
* can use it without a callback in the following way. var collection = db.collection('mycollection');
*
* @method
* @param {string} name the collection name we wish to access.
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
* @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
* @param {boolean} [options.strict=false] Returns an error if the collection does not exist
* @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported)
* @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported)
* @param {Db~collectionResultCallback} callback The collection result callback
* @return {Collection} return the new Collection instance if not in strict mode
*/
Db.prototype.collection = function(name, options, callback) {
var self = this;
if(typeof options == 'function') callback = options, options = {};
options = options || {};
options = shallowClone(options);
// Set the promise library
options.promiseLibrary = this.s.promiseLibrary;
// If we have not set a collection level readConcern set the db level one
options.readConcern = options.readConcern || this.s.readConcern;
// Do we have ignoreUndefined set
if(this.s.options.ignoreUndefined) {
options.ignoreUndefined = this.s.options.ignoreUndefined;
}
// Execute
if(options == null || !options.strict) {
try {
var collection = new Collection(this, this.s.topology, this.s.databaseName, name, this.s.pkFactory, options);
if(callback) callback(null, collection);
return collection;
} catch(err) {
if(callback) return callback(err);
throw err;
}
}
// Strict mode
if(typeof callback != 'function') {
throw toError(f("A callback is required in strict mode. While getting collection %s.", name));
}
// Strict mode
this.listCollections({name:name}).toArray(function(err, collections) {
if(err != null) return handleCallback(callback, err, null);
if(collections.length == 0) return handleCallback(callback, toError(f("Collection %s does not exist. Currently in strict mode.", name)), null);
try {
return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options));
} catch(err) {
return handleCallback(callback, err, null);
}
});
}
define.classMethod('collection', {callback: true, promise:false, returns: [Collection]});
var createCollection = function(self, name, options, callback) {
// Get the write concern options
var finalOptions = writeConcern(shallowClone(options), self, options);
// Did the user destroy the topology
if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));
// Check if we have the name
self.listCollections({name: name}).toArray(function(err, collections) {
if(err != null) return handleCallback(callback, err, null);
if(collections.length > 0 && finalOptions.strict) {
return handleCallback(callback, MongoError.create({message: f("Collection %s already exists. Currently in strict mode.", name), driver:true}), null);
} else if (collections.length > 0) {
try { return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); }
catch(err) { return handleCallback(callback, err); }
}
// Create collection command
var cmd = {'create':name};
// Add all optional parameters
for(var n in options) {
if(options[n] != null && typeof options[n] != 'function')
cmd[n] = options[n];
}
// Execute command
self.command(cmd, finalOptions, function(err, result) {
if(err) return handleCallback(callback, err);
handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options));
});
});
}
/**
* Creates a collection on a server pre-allocating space, need to create f.ex capped collections.
*
* @method
* @param {string} name the collection name we wish to access.
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
* @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
* @param {boolean} [options.strict=false] Returns an error if the collection does not exist
* @param {boolean} [options.capped=false] Create a capped collection.
* @param {number} [options.size=null] The size of the capped collection in bytes.
* @param {number} [options.max=null] The maximum number of documents in the capped collection.
* @param {boolean} [options.autoIndexId=true] Create an index on the _id field of the document, True by default on MongoDB 2.2 or higher off for version < 2.2.
* @param {Db~collectionResultCallback} [callback] The results callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.createCollection = function(name, options, callback) {
var self = this;
var args = Array.prototype.slice.call(arguments, 0);
callback = args.pop();
if(typeof callback != 'function') args.push(callback);
name = args.length ? args.shift() : null;
options = args.length ? args.shift() || {} : {};
// Do we have a promisesLibrary
options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary;
// Check if the callback is in fact a string
if(typeof callback == 'string') name = callback;
// Execute the fallback callback
if(typeof callback == 'function') return createCollection(self, name, options, callback);
return new this.s.promiseLibrary(function(resolve, reject) {
createCollection(self, name, options, function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
}
define.classMethod('createCollection', {callback: true, promise:true});
/**
* Get all the db statistics.
*
* @method
* @param {object} [options=null] Optional settings.
* @param {number} [options.scale=null] Divide the returned sizes by scale value.
* @param {Db~resultCallback} [callback] The collection result callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.stats = function(options, callback) {
if(typeof options == 'function') callback = options, options = {};
options = options || {};
// Build command object
var commandObject = { dbStats:true };
// Check if we have the scale value
if(options['scale'] != null) commandObject['scale'] = options['scale'];
// Execute the command
return this.command(commandObject, options, callback);
}
define.classMethod('stats', {callback: true, promise:true});
// Transformation methods for cursor results
var listCollectionsTranforms = function(databaseName) {
var matching = f('%s.', databaseName);
return {
doc: function(doc) {
var index = doc.name.indexOf(matching);
// Remove database name if available
if(doc.name && index == 0) {
doc.name = doc.name.substr(index + matching.length);
}
return doc;
}
}
}
/**
* Get the list of all collection information for the specified db.
*
* @method
* @param {object} filter Query to filter collections by
* @param {object} [options=null] Optional settings.
* @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @return {CommandCursor}
*/
Db.prototype.listCollections = function(filter, options) {
filter = filter || {};
options = options || {};
// Shallow clone the object
options = shallowClone(options);
// Set the promise library
options.promiseLibrary = this.s.promiseLibrary;
// We have a list collections command
if(this.serverConfig.capabilities().hasListCollectionsCommand) {
// Cursor options
var cursor = options.batchSize ? {batchSize: options.batchSize} : {}
// Build the command
var command = { listCollections : true, filter: filter, cursor: cursor };
// Set the AggregationCursor constructor
options.cursorFactory = CommandCursor;
// Filter out the correct field values
options.transforms = listCollectionsTranforms(this.s.databaseName);
// Create the cursor
var cursor = this.s.topology.cursor(f('%s.$cmd', this.s.databaseName), command, options);
// Do we have a readPreference, apply it
if(options.readPeference) cursor.setReadPreference(options.readPeference);
// Return the cursor
return cursor;
}
// We cannot use the listCollectionsCommand
if(!this.serverConfig.capabilities().hasListCollectionsCommand) {
// If we have legacy mode and have not provided a full db name filter it
if(typeof filter.name == 'string' && !(new RegExp('^' + this.databaseName + '\\.').test(filter.name))) {
filter = shallowClone(filter);
filter.name = f('%s.%s', this.s.databaseName, filter.name);
}
}
// No filter, filter by current database
if(filter == null) {
filter.name = f('/%s/', this.s.databaseName);
}
// Rewrite the filter to use $and to filter out indexes
if(filter.name) {
filter = {$and: [{name: filter.name}, {name:/^((?!\$).)*$/}]};
} else {
filter = {name:/^((?!\$).)*$/};
}
// Return options
var _options = {transforms: listCollectionsTranforms(this.s.databaseName)}
// Get the cursor
var cursor = this.collection(Db.SYSTEM_NAMESPACE_COLLECTION).find(filter, _options);
// Do we have a readPreference, apply it
if(options.readPeference) cursor.setReadPreference(options.readPeference);
// Set the passed in batch size if one was provided
if(options.batchSize) cursor = cursor.batchSize(options.batchSize);
// We have a fallback mode using legacy systems collections
return cursor;
};
define.classMethod('listCollections', {callback: false, promise:false, returns: [CommandCursor]});
var evaluate = function(self, code, parameters, options, callback) {
var finalCode = code;
var finalParameters = [];
// Did the user destroy the topology
if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));
// If not a code object translate to one
if(!(finalCode instanceof Code)) finalCode = new Code(finalCode);
// Ensure the parameters are correct
if(parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') {
finalParameters = [parameters];
} else if(parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') {
finalParameters = parameters;
}
// Create execution selector
var cmd = {'$eval':finalCode, 'args':finalParameters};
// Check if the nolock parameter is passed in
if(options['nolock']) {
cmd['nolock'] = options['nolock'];
}
// Set primary read preference
options.readPreference = new CoreReadPreference(ReadPreference.PRIMARY);
// Execute the command
self.command(cmd, options, function(err, result) {
if(err) return handleCallback(callback, err, null);
if(result && result.ok == 1) return handleCallback(callback, null, result.retval);
if(result) return handleCallback(callback, MongoError.create({message: f("eval failed: %s", result.errmsg), driver:true}), null);
handleCallback(callback, err, result);
});
}
/**
* Evaluate JavaScript on the server
*
* @method
* @param {Code} code JavaScript to execute on server.
* @param {(object|array)} parameters The parameters for the call.
* @param {object} [options=null] Optional settings.
* @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaulation of the javascript.
* @param {Db~resultCallback} [callback] The results callback
* @deprecated Eval is deprecated on MongoDB 3.2 and forward
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.eval = function(code, parameters, options, callback) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
callback = args.pop();
if(typeof callback != 'function') args.push(callback);
parameters = args.length ? args.shift() : parameters;
options = args.length ? args.shift() || {} : {};
// Check if the callback is in fact a string
if(typeof callback == 'function') return evaluate(self, code, parameters, options, callback);
// Execute the command
return new this.s.promiseLibrary(function(resolve, reject) {
evaluate(self, code, parameters, options, function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
};
define.classMethod('eval', {callback: true, promise:true});
/**
* Rename a collection.
*
* @method
* @param {string} fromCollection Name of current collection to rename.
* @param {string} toCollection New name of of the collection.
* @param {object} [options=null] Optional settings.
* @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists.
* @param {Db~collectionResultCallback} [callback] The results callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) {
var self = this;
if(typeof options == 'function') callback = options, options = {};
options = options || {};
// Add return new collection
options.new_collection = true;
// Check if the callback is in fact a string
if(typeof callback == 'function') {
return this.collection(fromCollection).rename(toCollection, options, callback);
}
// Return a promise
return new this.s.promiseLibrary(function(resolve, reject) {
self.collection(fromCollection).rename(toCollection, options, function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
};
define.classMethod('renameCollection', {callback: true, promise:true});
/**
* Drop a collection from the database, removing it permanently. New accesses will create a new collection.
*
* @method
* @param {string} name Name of collection to drop
* @param {Db~resultCallback} [callback] The results callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.dropCollection = function(name, callback) {
var self = this;
// Command to execute
var cmd = {'drop':name}
// Check if the callback is in fact a string
if(typeof callback == 'function') return this.command(cmd, this.s.options, function(err, result) {
// Did the user destroy the topology
if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));
if(err) return handleCallback(callback, err);
if(result.ok) return handleCallback(callback, null, true);
handleCallback(callback, null, false);
});
// Execute the command
return new this.s.promiseLibrary(function(resolve, reject) {
// Execute command
self.command(cmd, self.s.options, function(err, result) {
// Did the user destroy the topology
if(self.serverConfig && self.serverConfig.isDestroyed()) return reject(new MongoError('topology was destroyed'));
if(err) return reject(err);
if(result.ok) return resolve(true);
resolve(false);
});
});
};
define.classMethod('dropCollection', {callback: true, promise:true});
/**
* Drop a database.
*
* @method
* @param {Db~resultCallback} [callback] The results callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.dropDatabase = function(callback) {
var self = this;
// Drop database command
var cmd = {'dropDatabase':1};
// Check if the callback is in fact a string
if(typeof callback == 'function') return this.command(cmd, this.s.options, function(err, result) {
// Did the user destroy the topology
if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));
if(callback == null) return;
if(err) return handleCallback(callback, err, null);
handleCallback(callback, null, result.ok ? true : false);
});
// Execute the command
return new this.s.promiseLibrary(function(resolve, reject) {
// Execute command
self.command(cmd, self.s.options, function(err, result) {
// Did the user destroy the topology
if(self.serverConfig && self.serverConfig.isDestroyed()) return reject(new MongoError('topology was destroyed'));
if(err) return reject(err);
if(result.ok) return resolve(true);
resolve(false);
});
});
}
define.classMethod('dropDatabase', {callback: true, promise:true});
/**
* The callback format for the collections method.
* @callback Db~collectionsResultCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {Collection[]} collections An array of all the collections objects for the db instance.
*/
var collections = function(self, callback) {
// Let's get the collection names
self.listCollections().toArray(function(err, documents) {
if(err != null) return handleCallback(callback, err, null);
// Filter collections removing any illegal ones
documents = documents.filter(function(doc) {
return doc.name.indexOf('$') == -1;
});
// Return the collection objects
handleCallback(callback, null, documents.map(function(d) {
return new Collection(self, self.s.topology, self.s.databaseName, d.name.replace(self.s.databaseName + ".", ''), self.s.pkFactory, self.s.options);
}));
});
}
/**
* Fetch all collections for the current db.
*
* @method
* @param {Db~collectionsResultCallback} [callback] The results callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.collections = function(callback) {
var self = this;
// Return the callback
if(typeof callback == 'function') return collections(self, callback);
// Return the promise
return new self.s.promiseLibrary(function(resolve, reject) {
collections(self, function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
};
define.classMethod('collections', {callback: true, promise:true});
/**
* Runs a command on the database as admin.
* @method
* @param {object} command The command hash
* @param {object} [options=null] Optional settings.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query.
* @param {Db~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.executeDbAdminCommand = function(selector, options, callback) {
var self = this;
if(typeof options == 'function') callback = options, options = {};
options = options || {};
if(options.readPreference) {
options.readPreference = options.readPreference;
}
// Return the callback
if(typeof callback == 'function') return self.s.topology.command('admin.$cmd', selector, options, function(err, result) {
// Did the user destroy the topology
if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));
if(err) return handleCallback(callback, err);
handleCallback(callback, null, result.result);
});
// Return promise
return new self.s.promiseLibrary(function(resolve, reject) {
self.s.topology.command('admin.$cmd', selector, options, function(err, result) {
// Did the user destroy the topology
if(self.serverConfig && self.serverConfig.isDestroyed()) return reject(new MongoError('topology was destroyed'));
if(err) return reject(err);
resolve(result.result);
});
});
};
define.classMethod('executeDbAdminCommand', {callback: true, promise:true});
/**
* Creates an index on the db and collection collection.
* @method
* @param {string} name Name of the collection to create the index on.
* @param {(string|object)} fieldOrSpec Defines the index.
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.unique=false] Creates an unique index.
* @param {boolean} [options.sparse=false] Creates a sparse index.
* @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.
* @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value
* @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates.
* @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates.
* @param {number} [options.v=null] Specify the format version of the indexes.
* @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
* @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
* @param {Db~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) {
var self = this;
var args = Array.prototype.slice.call(arguments, 2);
callback = args.pop();
if(typeof callback != 'function') args.push(callback);
options = args.length ? args.shift() || {} : {};
options = typeof callback === 'function' ? options : callback;
options = options == null ? {} : options;
// Shallow clone the options
options = shallowClone(options);
// Run only against primary
options.readPreference = ReadPreference.PRIMARY;
// If we have a callback fallback
if(typeof callback == 'function') return createIndex(self, name, fieldOrSpec, options, callback);
// Return a promise
return new this.s.promiseLibrary(function(resolve, reject) {
createIndex(self, name, fieldOrSpec, options, function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
};
var createIndex = function(self, name, fieldOrSpec, options, callback) {
// Get the write concern options
var finalOptions = writeConcern({}, self, options);
// Ensure we have a callback
if(finalOptions.writeConcern && typeof callback != 'function') {
throw MongoError.create({message: "Cannot use a writeConcern without a provided callback", driver:true});
}
// Did the user destroy the topology
if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));
// Attempt to run using createIndexes command
createIndexUsingCreateIndexes(self, name, fieldOrSpec, options, function(err, result) {
if(err == null) return handleCallback(callback, err, result);
// Create command
var doc = createCreateIndexCommand(self, name, fieldOrSpec, options);
// Set no key checking
finalOptions.checkKeys = false;
// Insert document
self.s.topology.insert(f("%s.%s", self.s.databaseName, Db.SYSTEM_INDEX_COLLECTION), doc, finalOptions, function(err, result) {
if(callback == null) return;
if(err) return handleCallback(callback, err);
if(result == null) return handleCallback(callback, null, null);
if(result.result.writeErrors) return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null);
handleCallback(callback, null, doc.name);
});
});
}
define.classMethod('createIndex', {callback: true, promise:true});
/**
* Ensures that an index exists, if it does not it creates it
* @method
* @deprecated since version 2.0
* @param {string} name The index name
* @param {(string|object)} fieldOrSpec Defines the index.
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {boolean} [options.unique=false] Creates an unique index.
* @param {boolean} [options.sparse=false] Creates a sparse index.
* @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.
* @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value
* @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates.
* @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates.
* @param {number} [options.v=null] Specify the format version of the indexes.
* @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
* @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
* @param {Db~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.ensureIndex = function(name, fieldOrSpec, options, callback) {
var self = this;
if(typeof options == 'function') callback = options, options = {};
options = options || {};
// If we have a callback fallback
if(typeof callback == 'function') return ensureIndex(self, name, fieldOrSpec, options, callback);
// Return a promise
return new this.s.promiseLibrary(function(resolve, reject) {
ensureIndex(self, name, fieldOrSpec, options, function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
};
var ensureIndex = function(self, name, fieldOrSpec, options, callback) {
// Get the write concern options
var finalOptions = writeConcern({}, self, options);
// Create command
var selector = createCreateIndexCommand(self, name, fieldOrSpec, options);
var index_name = selector.name;
// Did the user destroy the topology
if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));
// Default command options
var commandOptions = {};
// Check if the index allready exists
self.indexInformation(name, finalOptions, function(err, indexInformation) {
if(err != null && err.code != 26) return handleCallback(callback, err, null);
// If the index does not exist, create it
if(indexInformation == null || !indexInformation[index_name]) {
self.createIndex(name, fieldOrSpec, options, callback);
} else {
if(typeof callback === 'function') return handleCallback(callback, null, index_name);
}
});
}
define.classMethod('ensureIndex', {callback: true, promise:true});
Db.prototype.addChild = function(db) {
if(this.s.parentDb) return this.s.parentDb.addChild(db);
this.s.children.push(db);
}
/**
* Create a new Db instance sharing the current socket connections. Be aware that the new db instances are
* related in a parent-child relationship to the original instance so that events are correctly emitted on child
* db instances. Child db instances are cached so performing db('db1') twice will return the same instance.
* You can control these behaviors with the options noListener and returnNonCachedInstance.
*
* @method
* @param {string} name The name of the database we want to use.
* @param {object} [options=null] Optional settings.
* @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection.
* @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created
* @return {Db}
*/
Db.prototype.db = function(dbName, options) {
options = options || {};
// Copy the options and add out internal override of the not shared flag
for(var key in this.options) {
options[key] = this.options[key];
}
// Do we have the db in the cache already
if(this.s.dbCache[dbName] && options.returnNonCachedInstance !== true) {
return this.s.dbCache[dbName];
}
// Add current db as parentDb
if(options.noListener == null || options.noListener == false) {
options.parentDb = this;
}
// Add promiseLibrary
options.promiseLibrary = this.s.promiseLibrary;
// Return the db object
var db = new Db(dbName, this.s.topology, options)
// Add as child
if(options.noListener == null || options.noListener == false) {
this.addChild(db);
}
// Add the db to the cache
this.s.dbCache[dbName] = db;
// Return the database
return db;
};
define.classMethod('db', {callback: false, promise:false, returns: [Db]});
var _executeAuthCreateUserCommand = function(self, username, password, options, callback) {
// Special case where there is no password ($external users)
if(typeof username == 'string'
&& password != null && typeof password == 'object') {
options = password;
password = null;
}
// Unpack all options
if(typeof options == 'function') {
callback = options;
options = {};
}
// Error out if we digestPassword set
if(options.digestPassword != null) {
throw toError("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option.");
}
// Get additional values
var customData = options.customData != null ? options.customData : {};
var roles = Array.isArray(options.roles) ? options.roles : [];
var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null;
// If not roles defined print deprecated message
if(roles.length == 0) {
console.log("Creating a user without roles is deprecated in MongoDB >= 2.6");
}
// Get the error options
var commandOptions = {writeCommand:true};
if(options['dbName']) commandOptions.dbName = options['dbName'];
// Add maxTimeMS to options if set
if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS;
// Check the db name and add roles if needed
if((self.databaseName.toLowerCase() == 'admin' || options.dbName == 'admin') && !Array.isArray(options.roles)) {
roles = ['root']
} else if(!Array.isArray(options.roles)) {
roles = ['dbOwner']
}
// Build the command to execute
var command = {
createUser: username
, customData: customData
, roles: roles
, digestPassword:false
}
// Apply write concern to command
command = writeConcern(command, self, options);
// Use node md5 generator
var md5 = crypto.createHash('md5');
// Generate keys used for authentication
md5.update(username + ":mongo:" + password);
var userPassword = md5.digest('hex');
// No password
if(typeof password == 'string') {
command.pwd = userPassword;
}
// Force write using primary
commandOptions.readPreference = CoreReadPreference.primary;
// Execute the command
self.command(command, commandOptions, function(err, result) {
if(err && err.ok == 0 && err.code == undefined) return handleCallback(callback, {code: -5000}, null);
if(err) return handleCallback(callback, err, null);
handleCallback(callback, !result.ok ? toError(result) : null
, result.ok ? [{user: username, pwd: ''}] : null);
})
}
var addUser = function(self, username, password, options, callback) {
// Did the user destroy the topology
if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));
// Attempt to execute auth command
_executeAuthCreateUserCommand(self, username, password, options, function(err, r) {
// We need to perform the backward compatible insert operation
if(err && err.code == -5000) {
var finalOptions = writeConcern(shallowClone(options), self, options);
// Use node md5 generator
var md5 = crypto.createHash('md5');
// Generate keys used for authentication
md5.update(username + ":mongo:" + password);
var userPassword = md5.digest('hex');
// If we have another db set
var db = options.dbName ? self.db(options.dbName) : self;
// Fetch a user collection
var collection = db.collection(Db.SYSTEM_USER_COLLECTION);
// Check if we are inserting the first user
collection.count({}, function(err, count) {
// We got an error (f.ex not authorized)
if(err != null) return handleCallback(callback, err, null);
// Check if the user exists and update i
collection.find({user: username}, {dbName: options['dbName']}).toArray(function(err, documents) {
// We got an error (f.ex not authorized)
if(err != null) return handleCallback(callback, err, null);
// Add command keys
finalOptions.upsert = true;
// We have a user, let's update the password or upsert if not
collection.update({user: username},{$set: {user: username, pwd: userPassword}}, finalOptions, function(err, results, full) {
if(count == 0 && err) return handleCallback(callback, null, [{user:username, pwd:userPassword}]);
if(err) return handleCallback(callback, err, null)
handleCallback(callback, null, [{user:username, pwd:userPassword}]);
});
});
});
return;
}
if(err) return handleCallback(callback, err);
handleCallback(callback, err, r);
});
}
/**
* Add a user to the database.
* @method
* @param {string} username The username.
* @param {string} password The password.
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher)
* @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher)
* @param {Db~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.addUser = function(username, password, options, callback) {
// Unpack the parameters
var self = this;
var args = Array.prototype.slice.call(arguments, 2);
callback = args.pop();
if(typeof callback != 'function') args.push(callback);
options = args.length ? args.shift() || {} : {};
// If we have a callback fallback
if(typeof callback == 'function') return addUser(self, username, password, options, callback);
// Return a promise
return new this.s.promiseLibrary(function(resolve, reject) {
addUser(self, username, password, options, function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
};
define.classMethod('addUser', {callback: true, promise:true});
var _executeAuthRemoveUserCommand = function(self, username, options, callback) {
if(typeof options == 'function') callback = options, options = {};
// Did the user destroy the topology
if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));
// Get the error options
var commandOptions = {writeCommand:true};
if(options['dbName']) commandOptions.dbName = options['dbName'];
// Get additional values
var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null;
// Add maxTimeMS to options if set
if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS;
// Build the command to execute
var command = {
dropUser: username
}
// Apply write concern to command
command = writeConcern(command, self, options);
// Force write using primary
commandOptions.readPreference = CoreReadPreference.primary;
// Execute the command
self.command(command, commandOptions, function(err, result) {
if(err && !err.ok && err.code == undefined) return handleCallback(callback, {code: -5000});
if(err) return handleCallback(callback, err, null);
handleCallback(callback, null, result.ok ? true : false);
})
}
var removeUser = function(self, username, options, callback) {
// Attempt to execute command
_executeAuthRemoveUserCommand(self, username, options, function(err, result) {
if(err && err.code == -5000) {
var finalOptions = writeConcern(shallowClone(options), self, options);
// If we have another db set
var db = options.dbName ? self.db(options.dbName) : self;
// Fetch a user collection
var collection = db.collection(Db.SYSTEM_USER_COLLECTION);
// Locate the user
collection.findOne({user: username}, {}, function(err, user) {
if(user == null) return handleCallback(callback, err, false);
collection.remove({user: username}, finalOptions, function(err, result) {
handleCallback(callback, err, true);
});
});
return;
}
if(err) return handleCallback(callback, err);
handleCallback(callback, err, result);
});
}
define.classMethod('removeUser', {callback: true, promise:true});
/**
* Remove a user from a database
* @method
* @param {string} username The username.
* @param {object} [options=null] Optional settings.
* @param {(number|string)} [options.w=null] The write concern.
* @param {number} [options.wtimeout=null] The write concern timeout.
* @param {boolean} [options.j=false] Specify a journal write concern.
* @param {Db~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.removeUser = function(username, options, callback) {
// Unpack the parameters
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
callback = args.pop();
if(typeof callback != 'function') args.push(callback);
options = args.length ? args.shift() || {} : {};
// If we have a callback fallback
if(typeof callback == 'function') return removeUser(self, username, options, callback);
// Return a promise
return new this.s.promiseLibrary(function(resolve, reject) {
removeUser(self, username, options, function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
};
var authenticate = function(self, username, password, options, callback) {
// Did the user destroy the topology
if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));
// the default db to authenticate against is 'self'
// if authententicate is called from a retry context, it may be another one, like admin
var authdb = options.authdb ? options.authdb : options.dbName;
authdb = options.authSource ? options.authSource : authdb;
authdb = authdb ? authdb : self.databaseName;
// Callback
var _callback = function(err, result) {
if(self.listeners('authenticated').length > 0) {
self.emit('authenticated', err, result);
}
// Return to caller
handleCallback(callback, err, result);
}
// authMechanism
var authMechanism = options.authMechanism || '';
authMechanism = authMechanism.toUpperCase();
// If classic auth delegate to auth command
if(authMechanism == 'MONGODB-CR') {
self.s.topology.auth('mongocr', authdb, username, password, function(err, result) {
if(err) return handleCallback(callback, err, false);
_callback(null, true);
});
} else if(authMechanism == 'PLAIN') {
self.s.topology.auth('plain', authdb, username, password, function(err, result) {
if(err) return handleCallback(callback, err, false);
_callback(null, true);
});
} else if(authMechanism == 'MONGODB-X509') {
self.s.topology.auth('x509', authdb, username, password, function(err, result) {
if(err) return handleCallback(callback, err, false);
_callback(null, true);
});
} else if(authMechanism == 'SCRAM-SHA-1') {
self.s.topology.auth('scram-sha-1', authdb, username, password, function(err, result) {
if(err) return handleCallback(callback, err, false);
_callback(null, true);
});
} else if(authMechanism == 'GSSAPI') {
if(process.platform == 'win32') {
self.s.topology.auth('sspi', authdb, username, password, options, function(err, result) {
if(err) return handleCallback(callback, err, false);
_callback(null, true);
});
} else {
self.s.topology.auth('gssapi', authdb, username, password, options, function(err, result) {
if(err) return handleCallback(callback, err, false);
_callback(null, true);
});
}
} else if(authMechanism == 'DEFAULT') {
self.s.topology.auth('default', authdb, username, password, function(err, result) {
if(err) return handleCallback(callback, err, false);
_callback(null, true);
});
} else {
handleCallback(callback, MongoError.create({message: f("authentication mechanism %s not supported", options.authMechanism), driver:true}));
}
}
/**
* Authenticate a user against the server.
* @method
* @param {string} username The username.
* @param {string} [password] The password.
* @param {object} [options=null] Optional settings.
* @param {string} [options.authMechanism=MONGODB-CR] The authentication mechanism to use, GSSAPI, MONGODB-CR, MONGODB-X509, PLAIN
* @param {Db~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.authenticate = function(username, password, options, callback) {
if(typeof options == 'function') callback = options, options = {};
var self = this;
// Shallow copy the options
options = shallowClone(options);
// Set default mechanism
if(!options.authMechanism) {
options.authMechanism = 'DEFAULT';
} else if(options.authMechanism != 'GSSAPI'
&& options.authMechanism != 'MONGODB-CR'
&& options.authMechanism != 'MONGODB-X509'
&& options.authMechanism != 'SCRAM-SHA-1'
&& options.authMechanism != 'PLAIN') {
return handleCallback(callback, MongoError.create({message: "only GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism", driver:true}));
}
// If we have a callback fallback
if(typeof callback == 'function') return authenticate(self, username, password, options, function(err, r) {
// Support failed auth method
if(err && err.message && err.message.indexOf('saslStart') != -1) err.code = 59;
// Reject error
if(err) return callback(err, r);
callback(null, r);
});
// Return a promise
return new this.s.promiseLibrary(function(resolve, reject) {
authenticate(self, username, password, options, function(err, r) {
// Support failed auth method
if(err && err.message && err.message.indexOf('saslStart') != -1) err.code = 59;
// Reject error
if(err) return reject(err);
resolve(r);
});
});
};
define.classMethod('authenticate', {callback: true, promise:true});
/**
* Logout user from server, fire off on all connections and remove all auth info
* @method
* @param {object} [options=null] Optional settings.
* @param {string} [options.dbName=null] Logout against different database than current.
* @param {Db~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.logout = function(options, callback) {
var self = this;
var args = Array.prototype.slice.call(arguments, 0);
callback = args.pop();
if(typeof callback != 'function') args.push(callback);
options = args.length ? args.shift() || {} : {};
// logout command
var cmd = {'logout':1};
// Add onAll to login to ensure all connection are logged out
options.onAll = true;
// We authenticated against a different db use that
if(this.s.authSource) options.dbName = this.s.authSource;
// Execute the command
if(typeof callback == 'function') return this.command(cmd, options, function(err, result) {
// Did the user destroy the topology
if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));
if(err) return handleCallback(callback, err, false);
handleCallback(callback, null, true)
});
// Return promise
return new this.s.promiseLibrary(function(resolve, reject) {
self.command(cmd, options, function(err, result) {
// Did the user destroy the topology
if(self.serverConfig && self.serverConfig.isDestroyed()) return reject(new MongoError('topology was destroyed'));
if(err) return reject(err);
resolve(true);
});
});
}
define.classMethod('logout', {callback: true, promise:true});
// Figure out the read preference
var getReadPreference = function(options, db) {
if(options.readPreference) return options;
if(db.readPreference) options.readPreference = db.readPreference;
return options;
}
/**
* Retrieves this collections index info.
* @method
* @param {string} name The name of the collection.
* @param {object} [options=null] Optional settings.
* @param {boolean} [options.full=false] Returns the full raw index information.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {Db~resultCallback} [callback] The command result callback
* @return {Promise} returns Promise if no callback passed
*/
Db.prototype.indexInformation = function(name, options, callback) {
var self = this;
if(typeof options == 'function') callback = options, options = {};
options = options || {};
// If we have a callback fallback
if(typeof callback == 'function') return indexInformation(self, name, options, callback);
// Return a promise
return new this.s.promiseLibrary(function(resolve, reject) {
indexInformation(self, name, options, function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
};
var indexInformation = function(self, name, options, callback) {
// If we specified full information
var full = options['full'] == null ? false : options['full'];
// Did the user destroy the topology
if(self.serverConfig && self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));
// Process all the results from the index command and collection
var processResults = function(indexes) {
// Contains all the information
var info = {};
// Process all the indexes
for(var i = 0; i < indexes.length; i++) {
var index = indexes[i];
// Let's unpack the object
info[index.name] = [];
for(var name in index.key) {
info[index.name].push([name, index.key[name]]);
}
}
return info;
}
// Get the list of indexes of the specified collection
self.collection(name).listIndexes().toArray(function(err, indexes) {
if(err) return callback(toError(err));
if(!Array.isArray(indexes)) return handleCallback(callback, null, []);
if(full) return handleCallback(callback, null, indexes);
handleCallback(callback, null, processResults(indexes));
});
}
define.classMethod('indexInformation', {callback: true, promise:true});
var createCreateIndexCommand = function(db, name, fieldOrSpec, options) {
var indexParameters = parseIndexOptions(fieldOrSpec);
var fieldHash = indexParameters.fieldHash;
var keys = indexParameters.keys;
// Generate the index name
var indexName = typeof options.name == 'string' ? options.name : indexParameters.name;
var selector = {
'ns': db.databaseName + "." + name, 'key': fieldHash, 'name': indexName
}
// Ensure we have a correct finalUnique
var finalUnique = options == null || 'object' === typeof options ? false : options;
// Set up options
options = options == null || typeof options == 'boolean' ? {} : options;
// Add all the options
var keysToOmit = Object.keys(selector);
for(var optionName in options) {
if(keysToOmit.indexOf(optionName) == -1) {
selector[optionName] = options[optionName];
}
}
if(selector['unique'] == null) selector['unique'] = finalUnique;
// Remove any write concern operations
var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference'];
for(var i = 0; i < removeKeys.length; i++) {
delete selector[removeKeys[i]];
}
// Return the command creation selector
return selector;
}
var createIndexUsingCreateIndexes = function(self, name, fieldOrSpec, options, callback) {
// Build the index
var indexParameters = parseIndexOptions(fieldOrSpec);
// Generate the index name
var indexName = typeof options.name == 'string' ? options.name : indexParameters.name;
// Set up the index
var indexes = [{ name: indexName, key: indexParameters.fieldHash }];
// merge all the options
var keysToOmit = Object.keys(indexes[0]);
for(var optionName in options) {
if(keysToOmit.indexOf(optionName) == -1) {
indexes[0][optionName] = options[optionName];
}
// Remove any write concern operations
var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference'];
for(var i = 0; i < removeKeys.length; i++) {
delete indexes[0][removeKeys[i]];
}
}
// Create command
var cmd = {createIndexes: name, indexes: indexes};
// Apply write concern to command
cmd = writeConcern(cmd, self, options);
// Build the command
self.command(cmd, options, function(err, result) {
if(err) return handleCallback(callback, err, null);
if(result.ok == 0) return handleCallback(callback, toError(result), null);
// Return the indexName for backward compatibility
handleCallback(callback, null, indexName);
});
}
// Validate the database name
var validateDatabaseName = function(databaseName) {
if(typeof databaseName !== 'string') throw MongoError.create({message: "database name must be a string", driver:true});
if(databaseName.length === 0) throw MongoError.create({message: "database name cannot be the empty string", driver:true});
if(databaseName == '$external') return;
var invalidChars = [" ", ".", "$", "/", "\\"];
for(var i = 0; i < invalidChars.length; i++) {
if(databaseName.indexOf(invalidChars[i]) != -1) throw MongoError.create({message: "database names cannot contain the character '" + invalidChars[i] + "'", driver:true});
}
}
// Get write concern
var writeConcern = function(target, db, options) {
if(options.w != null || options.j != null || options.fsync != null) {
var opts = {};
if(options.w) opts.w = options.w;
if(options.wtimeout) opts.wtimeout = options.wtimeout;
if(options.j) opts.j = options.j;
if(options.fsync) opts.fsync = options.fsync;
target.writeConcern = opts;
} else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) {
target.writeConcern = db.writeConcern;
}
return target
}
// Add listeners to topology
var createListener = function(self, e, object) {
var listener = function(err) {
if(e != 'error') {
object.emit(e, err, self);
// Emit on all associated db's if available
for(var i = 0; i < self.s.children.length; i++) {
self.s.children[i].emit(e, err, self.s.children[i]);
}
}
}
return listener;
}
/**
* Db close event
*
* Emitted after a socket closed against a single server or mongos proxy.
*
* @event Db#close
* @type {MongoError}
*/
/**
* Db authenticated event
*
* Emitted after all server members in the topology (single server, replicaset or mongos) have successfully authenticated.
*
* @event Db#authenticated
* @type {object}
*/
/**
* Db reconnect event
*
* * Server: Emitted when the driver has reconnected and re-authenticated.
* * ReplicaSet: N/A
* * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos.
*
* @event Db#reconnect
* @type {object}
*/
/**
* Db error event
*
* Emitted after an error occurred against a single server or mongos proxy.
*
* @event Db#error
* @type {MongoError}
*/
/**
* Db timeout event
*
* Emitted after a socket timeout occurred against a single server or mongos proxy.
*
* @event Db#timeout
* @type {MongoError}
*/
/**
* Db parseError event
*
* The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server.
*
* @event Db#parseError
* @type {MongoError}
*/
/**
* Db fullsetup event, emitted when all servers in the topology have been connected to at start up time.
*
* * Server: Emitted when the driver has connected to the single server and has authenticated.
* * ReplSet: Emitted after the driver has attempted to connect to all replicaset members.
* * Mongos: Emitted after the driver has attempted to connect to all mongos proxies.
*
* @event Db#fullsetup
* @type {Db}
*/
// Constants
Db.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces";
Db.SYSTEM_INDEX_COLLECTION = "system.indexes";
Db.SYSTEM_PROFILE_COLLECTION = "system.profile";
Db.SYSTEM_USER_COLLECTION = "system.users";
Db.SYSTEM_COMMAND_COLLECTION = "$cmd";
Db.SYSTEM_JS_COLLECTION = "system.js";
module.exports = Db;
|
var _ = require('underscore');
var Helpers = {};
Helpers.productLink = function (links) {
var productLink = _.find(links, function (l) {
return l.link.type === 'offer' || l.link.type === 'product';
});
return productLink.link.url || null;
};
Helpers.searchParams = function(keywords) {
var iteratee = function(memo, keyword) {
if(_.indexOf(keywords, keyword) === 0){
return keyword;
} else {
return memo + '+'+ keyword;
}
};
return 'keyword= '+ _.reduce(keywords, iteratee, '').toString();
};
module.exports = Helpers; |
//$(document).ready(function(){
//});
$('#selectshop_id').on('change', function() {
alert( "HI" ); // or $(this).val()
});
|
/**
* Created by SavioJoseph on 8/23/2016.
*/
angular.module("sprocketApp.data")
.factory("placeOrderDal", ['$http', '$q', function ($http, $q) {
return {
getOrderDetails: function () {
var deferred = $q.defer();
//var url = "sprocketModule/mocks/sampleMockData.json";
var url=appUrl.baseUrl+'/sprocketdetail';
$http.get(url).success(function (data) {
deferred.resolve(data);
})
.error(function (data) {
deferred.reject(data);
});
return deferred.promise;
},
postOrderDetails: function () {
var deferred = $q.defer();
var url = appUrl.baseUrl+'/sprocketHistory';//add the post url;
$http.post(url).success(function (data) {
deferred.resolve(data);
})
.error(function (data) {
deferred.reject(data);
});
return deferred.promise;
},
getHistoryDetails: function () {
var deferred = $q.defer();
var url = "sprocketModule/mocks/historyMock.json";
$http.get(url).success(function (data) {
deferred.resolve(data);
})
.error(function (data) {
deferred.reject(data);
});
return deferred.promise;
}
}
}]); |
define([
"omega/widgets/Dialog",
"text!./templates/ConfirmationDialog.html",
"omega/widgets/Confirmation"
], function(Dialog, template) {
return Dialog.extend({
options: {
title: "Confirm...",
message: "Are you sure you want to do that?",
width: 300,
height: "auto",
sizable: false,
closable: false
},
initialize: function() {
this.inherited(Dialog, arguments);
this._mixinTemplateStrings.push(template);
},
startup: function() {
this.inherited(Dialog, arguments);
this._confirmationNode.setMessage(this.message);
this._confirmationNode.on("confirm", this.hide, this);
this._confirmationNode.on("cancel", this.hide, this);
this.wireEventsTo(this._confirmationNode);
}
});
}); |
var searchData=
[
['repetier_2epde',['Repetier.pde',['../_repetier_8pde.html',1,'']]],
['reptier_2eh',['Reptier.h',['../_reptier_8h.html',1,'']]]
];
|
'use strict';
import {List, Map, fromJS} from 'immutable';
import {expect} from 'chai';
import Theme from '../src/defaultTheme';
import reducer from '../src/themeReducer';
import {createStore, combineReducers} from 'redux';
import React from 'react';
import {renderIntoDocument, findRenderedDOMComponentWithTag} from 'react-addons-test-utils';
import ReduxTheme from '../src/ReduxTheme';
import testTheme from './themes_test/test-theme';
import testStyle from './styles_test/Test.styles.js';
import TestComponent from './components_test/Test';
describe('component_spec -> <ReduxTheme>', () => {
const reducers = combineReducers({
theme: reducer
});
const testTheme = new Theme ('test');
testTheme.typo.font = 'Luckiest Guy, sans-serif';
const testStyle = (theme) => ({
base: {
fontFamily: theme.typo.font
}
});
const styles = [{
componentName: 'Test',
style: testStyle
}];
const store = createStore (reducers);
renderIntoDocument (
<ReduxTheme
store={store}
themes={[testTheme]}
styles={styles}
defaultTheme={'test'}/>
);
const component = renderIntoDocument (
<TestComponent store={store} />
);
const node = findRenderedDOMComponentWithTag (component, 'div');
it('set correct google font in header', () => {
expect(document.getElementById ('reduxtheme').href).to
.equal ('http://fonts.googleapis.com/css?family=Luckiest Guy');
});
it('Test component has correct style', () => {
expect(node.style[0]).to
.equal ('font-family');
});
});
|
'use strict';
module.exports = function(sequelize, DataTypes) {
return sequelize.define('TaskLog', {
'content': {type: DataTypes.TEXT, required: true }
});
};
|
/**
* Spiral gulp task file.
* @version 0.0.2
*/
var gulp = require('gulp'),
plugins = require('gulp-load-plugins')(),
browserSync = require('browser-sync'),
runSequence = require('run-sequence'),
del = require('del');
combiner = require('stream-combiner2');
var reload = browserSync.reload;
var SOURCE_FILES = [
'src/compat.js',
'src/spiral.core.js',
'src/spiral.util.js',
'src/spiral.buff.js',
'src/spiral.midi.js'
];
// Compile: compile source files.
gulp.task('compile', function () {
var combined = combiner.obj([
gulp.src(SOURCE_FILES),
plugins.uglify({ mangle: false }),
plugins.concat('spiral.min.js'),
gulp.dest('.')
]);
combined.on('error', console.error.bind(console));
return combined;
});
// Serve: Start a dev server at 127.0.0.1:3000.
gulp.task('serve', function () {
browserSync({
notify: false,
server: {
baseDir: './'
},
browser: 'google chrome'
});
gulp.watch(['src/*.js'], reload);
gulp.watch(['tests/*.html'], reload);
gulp.watch(['examples/*.html'], reload);
});
// Build: Clean and build everything in build/ path.
gulp.task('build', function (cb) {
runSequence('compile', cb);
});
// Default: Build and serve.
gulp.task('default', function (cb) {
runSequence('build', 'serve', cb);
});
|
module.exports = {
test: () => 'model.loader.foo.fozCamel.foo.test',
};
|
// Generated by jsScript 1.10.0
(function() {
Template.favoriteButton.helpers({
isFavorite: function(_id) {
return Favorites.findOne({
doc: _id,
owner: Meteor.userId()
});
}
});
Template.favoriteButtonNotFavorited.events({
'click .js-favorite-button': function(e, t) {
return Favorites.insert({
doc: $(e.currentTarget).attr('doc'),
owner: Meteor.userId()
});
}
});
Template.favoriteButtonFavorited.events({
'click .js-favorite-button': function(e, t) {
var favorite;
favorite = Favorites.findOne({
owner: Meteor.userId(),
doc: $(e.currentTarget).attr('doc')
});
return Favorites.remove({
_id: favorite._id
});
}
});
}).call(this);
|
import * as actions from '../app/types'
const initialCommentsState = []
export function comments ( state = initialCommentsState, action) {
switch (action.type) {
case actions.GET_POST_COMMENTS:
return [...state, ...action.comments]
case actions.UPDATE_COMMENT:
case actions.UPDATE_COMMENT_VOTESCORE:
case actions.REMOVE_COMMENT:
return state.map(comment => {
if(comment.id === action.comment.id) {
return action.comment
}
return comment
})
case actions.GOT_NEW_COMMENT:
return [...state, action.comment]
default:
return state
}
} |
var MagicWand = (function () {
var lib = {};
/** Create a binary mask on the image by color threshold
* Algorithm: Scanline flood fill (http://en.wikipedia.org/wiki/Flood_fill)
* @param {Object} image: {Uint8Array} data, {int} width, {int} height, {int} bytes
* @param {int} x of start pixel
* @param {int} y of start pixel
* @param {int} color threshold
* @param {Uint8Array} mask of visited points (optional)
* @param {boolean} [includeBorders=false] indicate whether to include borders pixels
* @return {Object} mask: {Uint8Array} data, {int} width, {int} height, {Object} bounds
*/
lib.floodFill = function(image, px, py, colorThreshold, mask, includeBorders) {
return includeBorders
? floodFillWithBorders(image, px, py, colorThreshold, mask)
: floodFillWithoutBorders(image, px, py, colorThreshold, mask);
};
function floodFillWithoutBorders(image, px, py, colorThreshold, mask) {
var c, x, newY, el, xr, xl, dy, dyl, dyr, checkY,
data = image.data,
w = image.width,
h = image.height,
bytes = image.bytes, // number of bytes in the color
maxX = -1, minX = w + 1, maxY = -1, minY = h + 1,
i = py * w + px, // start point index in the mask data
result = new Uint8Array(w * h), // result mask
visited = new Uint8Array(mask ? mask : w * h); // mask of visited points
if (visited[i] === 1) return null;
i = i * bytes; // start point index in the image data
var sampleColor = [data[i], data[i + 1], data[i + 2], data[i + 3]]; // start point color (sample)
var stack = [{ y: py, left: px - 1, right: px + 1, dir: 1 }]; // first scanning line
do {
el = stack.shift(); // get line for scanning
checkY = false;
for (x = el.left + 1; x < el.right; x++) {
dy = el.y * w;
i = (dy + x) * bytes; // point index in the image data
if (visited[dy + x] === 1) continue; // check whether the point has been visited
// compare the color of the sample
c = data[i] - sampleColor[0]; // check by red
if (c > colorThreshold || c < -colorThreshold) continue;
c = data[i + 1] - sampleColor[1]; // check by green
if (c > colorThreshold || c < -colorThreshold) continue;
c = data[i + 2] - sampleColor[2]; // check by blue
if (c > colorThreshold || c < -colorThreshold) continue;
checkY = true; // if the color of the new point(x,y) is similar to the sample color need to check minmax for Y
result[dy + x] = 1; // mark a new point in mask
visited[dy + x] = 1; // mark a new point as visited
xl = x - 1;
// walk to left side starting with the left neighbor
while (xl > -1) {
dyl = dy + xl;
i = dyl * bytes; // point index in the image data
if (visited[dyl] === 1) break; // check whether the point has been visited
// compare the color of the sample
c = data[i] - sampleColor[0]; // check by red
if (c > colorThreshold || c < -colorThreshold) break;
c = data[i + 1] - sampleColor[1]; // check by green
if (c > colorThreshold || c < -colorThreshold) break;
c = data[i + 2] - sampleColor[2]; // check by blue
if (c > colorThreshold || c < -colorThreshold) break;
result[dyl] = 1;
visited[dyl] = 1;
xl--;
}
xr = x + 1;
// walk to right side starting with the right neighbor
while (xr < w) {
dyr = dy + xr;
i = dyr * bytes; // index point in the image data
if (visited[dyr] === 1) break; // check whether the point has been visited
// compare the color of the sample
c = data[i] - sampleColor[0]; // check by red
if (c > colorThreshold || c < -colorThreshold) break;
c = data[i + 1] - sampleColor[1]; // check by green
if (c > colorThreshold || c < -colorThreshold) break;
c = data[i + 2] - sampleColor[2]; // check by blue
if (c > colorThreshold || c < -colorThreshold) break;
result[dyr] = 1;
visited[dyr] = 1;
xr++;
}
// check minmax for X
if (xl < minX) minX = xl + 1;
if (xr > maxX) maxX = xr - 1;
newY = el.y - el.dir;
if (newY >= 0 && newY < h) { // add two scanning lines in the opposite direction (y - dir) if necessary
if (xl < el.left) stack.push({ y: newY, left: xl, right: el.left, dir: -el.dir }); // from "new left" to "current left"
if (el.right < xr) stack.push({ y: newY, left: el.right, right: xr, dir: -el.dir }); // from "current right" to "new right"
}
newY = el.y + el.dir;
if (newY >= 0 && newY < h) { // add the scanning line in the direction (y + dir) if necessary
if (xl < xr) stack.push({ y: newY, left: xl, right: xr, dir: el.dir }); // from "new left" to "new right"
}
}
// check minmax for Y if necessary
if (checkY) {
if (el.y < minY) minY = el.y;
if (el.y > maxY) maxY = el.y;
}
} while (stack.length > 0);
return {
data: result,
width: image.width,
height: image.height,
bounds: {
minX: minX,
minY: minY,
maxX: maxX,
maxY: maxY
}
};
};
function floodFillWithBorders(image, px, py, colorThreshold, mask) {
var c, x, newY, el, xr, xl, dy, dyl, dyr, checkY,
data = image.data,
w = image.width,
h = image.height,
bytes = image.bytes, // number of bytes in the color
maxX = -1, minX = w + 1, maxY = -1, minY = h + 1,
i = py * w + px, // start point index in the mask data
result = new Uint8Array(w * h), // result mask
visited = new Uint8Array(mask ? mask : w * h); // mask of visited points
if (visited[i] === 1) return null;
i = i * bytes; // start point index in the image data
var sampleColor = [data[i], data[i + 1], data[i + 2], data[i + 3]]; // start point color (sample)
var stack = [{ y: py, left: px - 1, right: px + 1, dir: 1 }]; // first scanning line
do {
el = stack.shift(); // get line for scanning
checkY = false;
for (x = el.left + 1; x < el.right; x++) {
dy = el.y * w;
i = (dy + x) * bytes; // point index in the image data
if (visited[dy + x] === 1) continue; // check whether the point has been visited
checkY = true; // if the color of the new point(x,y) is similar to the sample color need to check minmax for Y
result[dy + x] = 1; // mark a new point in mask
visited[dy + x] = 1; // mark a new point as visited
// compare the color of the sample
c = data[i] - sampleColor[0]; // check by red
if (c > colorThreshold || c < -colorThreshold) continue;
c = data[i + 1] - sampleColor[1]; // check by green
if (c > colorThreshold || c < -colorThreshold) continue;
c = data[i + 2] - sampleColor[2]; // check by blue
if (c > colorThreshold || c < -colorThreshold) continue;
xl = x - 1;
// walk to left side starting with the left neighbor
while (xl > -1) {
dyl = dy + xl;
i = dyl * bytes; // point index in the image data
if (visited[dyl] === 1) break; // check whether the point has been visited
result[dyl] = 1;
visited[dyl] = 1;
xl--;
// compare the color of the sample
c = data[i] - sampleColor[0]; // check by red
if (c > colorThreshold || c < -colorThreshold) break;
c = data[i + 1] - sampleColor[1]; // check by green
if (c > colorThreshold || c < -colorThreshold) break;
c = data[i + 2] - sampleColor[2]; // check by blue
if (c > colorThreshold || c < -colorThreshold) break;
}
xr = x + 1;
// walk to right side starting with the right neighbor
while (xr < w) {
dyr = dy + xr;
i = dyr * bytes; // index point in the image data
if (visited[dyr] === 1) break; // check whether the point has been visited
result[dyr] = 1;
visited[dyr] = 1;
xr++;
// compare the color of the sample
c = data[i] - sampleColor[0]; // check by red
if (c > colorThreshold || c < -colorThreshold) break;
c = data[i + 1] - sampleColor[1]; // check by green
if (c > colorThreshold || c < -colorThreshold) break;
c = data[i + 2] - sampleColor[2]; // check by blue
if (c > colorThreshold || c < -colorThreshold) break;
}
// check minmax for X
if (xl < minX) minX = xl + 1;
if (xr > maxX) maxX = xr - 1;
newY = el.y - el.dir;
if (newY >= 0 && newY < h) { // add two scanning lines in the opposite direction (y - dir) if necessary
if (xl < el.left) stack.push({ y: newY, left: xl, right: el.left, dir: -el.dir }); // from "new left" to "current left"
if (el.right < xr) stack.push({ y: newY, left: el.right, right: xr, dir: -el.dir }); // from "current right" to "new right"
}
newY = el.y + el.dir;
if (newY >= 0 && newY < h) { // add the scanning line in the direction (y + dir) if necessary
if (xl < xr) stack.push({ y: newY, left: xl, right: xr, dir: el.dir }); // from "new left" to "new right"
}
}
// check minmax for Y if necessary
if (checkY) {
if (el.y < minY) minY = el.y;
if (el.y > maxY) maxY = el.y;
}
} while (stack.length > 0);
return {
data: result,
width: image.width,
height: image.height,
bounds: {
minX: minX,
minY: minY,
maxX: maxX,
maxY: maxY
}
};
};
/** Apply the gauss-blur filter to binary mask
* Algorithms: http://blog.ivank.net/fastest-gaussian-blur.html
* http://www.librow.com/articles/article-9
* http://elynxsdk.free.fr/ext-docs/Blur/Fast_box_blur.pdf
* @param {Object} mask: {Uint8Array} data, {int} width, {int} height, {Object} bounds
* @param {int} blur radius
* @return {Object} mask: {Uint8Array} data, {int} width, {int} height, {Object} bounds
*/
lib.gaussBlur = function(mask, radius) {
var i, k, k1, x, y, val, start, end,
n = radius * 2 + 1, // size of the pattern for radius-neighbors (from -r to +r with the center point)
s2 = radius * radius,
wg = new Float32Array(n), // weights
total = 0, // sum of weights(used for normalization)
w = mask.width,
h = mask.height,
data = mask.data,
minX = mask.bounds.minX,
maxX = mask.bounds.maxX,
minY = mask.bounds.minY,
maxY = mask.bounds.maxY;
// calc gauss weights
for (i = 0; i < radius; i++) {
var dsq = (radius - i) * (radius - i);
var ww = Math.exp(-dsq / (2.0 * s2)) / (2 * Math.PI * s2);
wg[radius + i] = wg[radius - i] = ww;
total += 2 * ww;
}
// normalization weights
for (i = 0; i < n; i++) {
wg[i] /= total;
}
var result = new Uint8Array(w * h), // result mask
endX = radius + w,
endY = radius + h;
//walk through all source points for blur
for (y = minY; y < maxY + 1; y++)
for (x = minX; x < maxX + 1; x++) {
val = 0;
k = y * w + x; // index of the point
start = radius - x > 0 ? radius - x : 0;
end = endX - x < n ? endX - x : n; // Math.min((((w - 1) - x) + radius) + 1, n);
k1 = k - radius;
// walk through x-neighbors
for (i = start; i < end; i++) {
val += data[k1 + i] * wg[i];
}
start = radius - y > 0 ? radius - y : 0;
end = endY - y < n ? endY - y : n; // Math.min((((h - 1) - y) + radius) + 1, n);
k1 = k - radius * w;
// walk through y-neighbors
for (i = start; i < end; i++) {
val += data[k1 + i * w] * wg[i];
}
result[k] = val > 0.5 ? 1 : 0;
}
return {
data: result,
width: w,
height: h,
bounds: {
minX: minX,
minY: minY,
maxX: maxX,
maxY: maxY
}
};
};
/** Create a border index array of boundary points of the mask with radius-neighbors
* @param {Object} mask: {Uint8Array} data, {int} width, {int} height, {Object} bounds
* @param {int} blur radius
* @param {Uint8Array} visited: mask of visited points (optional)
* @return {Array} border index array of boundary points with radius-neighbors (only points need for blur)
*/
function createBorderForBlur(mask, radius, visited) {
var x, i, j, y, k, k1, k2,
w = mask.width,
h = mask.height,
data = mask.data,
visitedData = new Uint8Array(data),
minX = mask.bounds.minX,
maxX = mask.bounds.maxX,
minY = mask.bounds.minY,
maxY = mask.bounds.maxY,
len = w * h,
temp = new Uint8Array(len), // auxiliary array to check uniqueness
border = [], // only border points
x0 = Math.max(minX, 1),
x1 = Math.min(maxX, w - 2),
y0 = Math.max(minY, 1),
y1 = Math.min(maxY, h - 2);
if (visited && visited.length > 0) {
// copy visited points (only "black")
for (k = 0; k < len; k++) {
if (visited[k] === 1) visitedData[k] = 1;
}
}
// walk through inner values except points on the boundary of the image
for (y = y0; y < y1 + 1; y++)
for (x = x0; x < x1 + 1; x++) {
k = y * w + x;
if (data[k] === 0) continue; // "white" point isn't the border
k1 = k + w; // y + 1
k2 = k - w; // y - 1
// check if any neighbor with a "white" color
if (visitedData[k + 1] === 0 || visitedData[k - 1] === 0 ||
visitedData[k1] === 0 || visitedData[k1 + 1] === 0 || visitedData[k1 - 1] === 0 ||
visitedData[k2] === 0 || visitedData[k2 + 1] === 0 || visitedData[k2 - 1] === 0) {
//if (visitedData[k + 1] + visitedData[k - 1] +
// visitedData[k1] + visitedData[k1 + 1] + visitedData[k1 - 1] +
// visitedData[k2] + visitedData[k2 + 1] + visitedData[k2 - 1] == 8) continue;
border.push(k);
}
}
// walk through points on the boundary of the image if necessary
// if the "black" point is adjacent to the boundary of the image, it is a border point
if (minX == 0)
for (y = minY; y < maxY + 1; y++)
if (data[y * w] === 1)
border.push(y * w);
if (maxX == w - 1)
for (y = minY; y < maxY + 1; y++)
if (data[y * w + maxX] === 1)
border.push(y * w + maxX);
if (minY == 0)
for (x = minX; x < maxX + 1; x++)
if (data[x] === 1)
border.push(x);
if (maxY == h - 1)
for (x = minX; x < maxX + 1; x++)
if (data[maxY * w + x] === 1)
border.push(maxY * w + x);
var result = [], // border points with radius-neighbors
start, end,
endX = radius + w,
endY = radius + h,
n = radius * 2 + 1; // size of the pattern for radius-neighbors (from -r to +r with the center point)
len = border.length;
// walk through radius-neighbors of border points and add them to the result array
for (j = 0; j < len; j++) {
k = border[j]; // index of the border point
temp[k] = 1; // mark border point
result.push(k); // save the border point
x = k % w; // calc x by index
y = (k - x) / w; // calc y by index
start = radius - x > 0 ? radius - x : 0;
end = endX - x < n ? endX - x : n; // Math.min((((w - 1) - x) + radius) + 1, n);
k1 = k - radius;
// walk through x-neighbors
for (i = start; i < end; i++) {
k2 = k1 + i;
if (temp[k2] === 0) { // check the uniqueness
temp[k2] = 1;
result.push(k2);
}
}
start = radius - y > 0 ? radius - y : 0;
end = endY - y < n ? endY - y : n; // Math.min((((h - 1) - y) + radius) + 1, n);
k1 = k - radius * w;
// walk through y-neighbors
for (i = start; i < end; i++) {
k2 = k1 + i * w;
if (temp[k2] === 0) { // check the uniqueness
temp[k2] = 1;
result.push(k2);
}
}
}
return result;
};
/** Apply the gauss-blur filter ONLY to border points with radius-neighbors
* Algorithms: http://blog.ivank.net/fastest-gaussian-blur.html
* http://www.librow.com/articles/article-9
* http://elynxsdk.free.fr/ext-docs/Blur/Fast_box_blur.pdf
* @param {Object} mask: {Uint8Array} data, {int} width, {int} height, {Object} bounds
* @param {int} blur radius
* @param {Uint8Array} visited: mask of visited points (optional)
* @return {Object} mask: {Uint8Array} data, {int} width, {int} height, {Object} bounds
*/
lib.gaussBlurOnlyBorder = function(mask, radius, visited) {
var border = createBorderForBlur(mask, radius, visited), // get border points with radius-neighbors
ww, dsq, i, j, k, k1, x, y, val, start, end,
n = radius * 2 + 1, // size of the pattern for radius-neighbors (from -r to +r with center point)
s2 = 2 * radius * radius,
wg = new Float32Array(n), // weights
total = 0, // sum of weights(used for normalization)
w = mask.width,
h = mask.height,
data = mask.data,
minX = mask.bounds.minX,
maxX = mask.bounds.maxX,
minY = mask.bounds.minY,
maxY = mask.bounds.maxY,
len = border.length;
// calc gauss weights
for (i = 0; i < radius; i++) {
dsq = (radius - i) * (radius - i);
ww = Math.exp(-dsq / s2) / Math.PI;
wg[radius + i] = wg[radius - i] = ww;
total += 2 * ww;
}
// normalization weights
for (i = 0; i < n; i++) {
wg[i] /= total;
}
var result = new Uint8Array(data), // copy the source mask
endX = radius + w,
endY = radius + h;
//walk through all border points for blur
for (i = 0; i < len; i++) {
k = border[i]; // index of the border point
val = 0;
x = k % w; // calc x by index
y = (k - x) / w; // calc y by index
start = radius - x > 0 ? radius - x : 0;
end = endX - x < n ? endX - x : n; // Math.min((((w - 1) - x) + radius) + 1, n);
k1 = k - radius;
// walk through x-neighbors
for (j = start; j < end; j++) {
val += data[k1 + j] * wg[j];
}
if (val > 0.5) {
result[k] = 1;
// check minmax
if (x < minX) minX = x;
if (x > maxX) maxX = x;
if (y < minY) minY = y;
if (y > maxY) maxY = y;
continue;
}
start = radius - y > 0 ? radius - y : 0;
end = endY - y < n ? endY - y : n; // Math.min((((h - 1) - y) + radius) + 1, n);
k1 = k - radius * w;
// walk through y-neighbors
for (j = start; j < end; j++) {
val += data[k1 + j * w] * wg[j];
}
if (val > 0.5) {
result[k] = 1;
// check minmax
if (x < minX) minX = x;
if (x > maxX) maxX = x;
if (y < minY) minY = y;
if (y > maxY) maxY = y;
} else {
result[k] = 0;
}
}
return {
data: result,
width: w,
height: h,
bounds: {
minX: minX,
minY: minY,
maxX: maxX,
maxY: maxY
}
};
};
/** Create a border mask (only boundary points)
* @param {Object} mask: {Uint8Array} data, {int} width, {int} height, {Object} bounds
* @return {Object} border mask: {Uint8Array} data, {int} width, {int} height, {Object} offset
*/
lib.createBorderMask = function(mask) {
var x, y, k, k1, k2,
w = mask.width,
h = mask.height,
data = mask.data,
minX = mask.bounds.minX,
maxX = mask.bounds.maxX,
minY = mask.bounds.minY,
maxY = mask.bounds.maxY,
rw = maxX - minX + 1, // bounds size
rh = maxY - minY + 1,
result = new Uint8Array(rw * rh), // reduced mask (bounds size)
x0 = Math.max(minX, 1),
x1 = Math.min(maxX, w - 2),
y0 = Math.max(minY, 1),
y1 = Math.min(maxY, h - 2);
// walk through inner values except points on the boundary of the image
for (y = y0; y < y1 + 1; y++)
for (x = x0; x < x1 + 1; x++) {
k = y * w + x;
if (data[k] === 0) continue; // "white" point isn't the border
k1 = k + w; // y + 1
k2 = k - w; // y - 1
// check if any neighbor with a "white" color
if (data[k + 1] === 0 || data[k - 1] === 0 ||
data[k1] === 0 || data[k1 + 1] === 0 || data[k1 - 1] === 0 ||
data[k2] === 0 || data[k2 + 1] === 0 || data[k2 - 1] === 0) {
//if (data[k + 1] + data[k - 1] +
// data[k1] + data[k1 + 1] + data[k1 - 1] +
// data[k2] + data[k2 + 1] + data[k2 - 1] == 8) continue;
result[(y - minY) * rw + (x - minX)] = 1;
}
}
// walk through points on the boundary of the image if necessary
// if the "black" point is adjacent to the boundary of the image, it is a border point
if (minX == 0)
for (y = minY; y < maxY + 1; y++)
if (data[y * w] === 1)
result[(y - minY) * rw] = 1;
if (maxX == w - 1)
for (y = minY; y < maxY + 1; y++)
if (data[y * w + maxX] === 1)
result[(y - minY) * rw + (maxX - minX)] = 1;
if (minY == 0)
for (x = minX; x < maxX + 1; x++)
if (data[x] === 1)
result[x - minX] = 1;
if (maxY == h - 1)
for (x = minX; x < maxX + 1; x++)
if (data[maxY * w + x] === 1)
result[(maxY - minY) * rw + (x - minX)] = 1;
return {
data: result,
width: rw,
height: rh,
offset: { x: minX, y: minY }
};
};
/** Create a border index array of boundary points of the mask
* @param {Object} mask: {Uint8Array} data, {int} width, {int} height
* @return {Array} border index array boundary points of the mask
*/
lib.getBorderIndices = function(mask) {
var x, y, k, k1, k2,
w = mask.width,
h = mask.height,
data = mask.data,
border = [], // only border points
x1 = w - 1,
y1 = h - 1;
// walk through inner values except points on the boundary of the image
for (y = 1; y < y1; y++)
for (x = 1; x < x1; x++) {
k = y * w + x;
if (data[k] === 0) continue; // "white" point isn't the border
k1 = k + w; // y + 1
k2 = k - w; // y - 1
// check if any neighbor with a "white" color
if (data[k + 1] === 0 || data[k - 1] === 0 ||
data[k1] === 0 || data[k1 + 1] === 0 || data[k1 - 1] === 0 ||
data[k2] === 0 || data[k2 + 1] === 0 || data[k2 - 1] === 0) {
//if (data[k + 1] + data[k - 1] +
// data[k1] + data[k1 + 1] + data[k1 - 1] +
// data[k2] + data[k2 + 1] + data[k2 - 1] == 8) continue;
border.push(k);
}
}
// walk through points on the boundary of the image if necessary
// if the "black" point is adjacent to the boundary of the image, it is a border point
for (y = 0; y < h; y++)
if (data[y * w] === 1)
border.push(y * w);
for (x = 0; x < w; x++)
if (data[x] === 1)
border.push(x);
k = w - 1;
for (y = 0; y < h; y++)
if (data[y * w + k] === 1)
border.push(y * w + k);
k = (h - 1) * w;
for (x = 0; x < w; x++)
if (data[k + x] === 1)
border.push(k + x);
return border;
};
/** Create a compressed mask with a "white" border (1px border with zero values) for the contour tracing
* @param {Object} mask: {Uint8Array} data, {int} width, {int} height, {Object} bounds
* @return {Object} border mask: {Uint8Array} data, {int} width, {int} height, {Object} offset
*/
function prepareMask(mask) {
var x, y,
w = mask.width,
data = mask.data,
minX = mask.bounds.minX,
maxX = mask.bounds.maxX,
minY = mask.bounds.minY,
maxY = mask.bounds.maxY,
rw = maxX - minX + 3, // bounds size +1 px on each side (a "white" border)
rh = maxY - minY + 3,
result = new Uint8Array(rw * rh); // reduced mask (bounds size)
// walk through inner values and copy only "black" points to the result mask
for (y = minY; y < maxY + 1; y++)
for (x = minX; x < maxX + 1; x++) {
if (data[y * w + x] === 1)
result[(y - minY + 1) * rw + (x - minX + 1)] = 1;
}
return {
data: result,
width: rw,
height: rh,
offset: { x: minX - 1, y: minY - 1 }
};
};
/** Create a contour array for the binary mask
* Algorithm: http://www.sciencedirect.com/science/article/pii/S1077314203001401
* @param {Object} mask: {Uint8Array} data, {int} width, {int} height, {Object} bounds
* @return {Array} contours: {Array} points, {bool} inner, {int} label
*/
lib.traceContours = function(mask) {
var m = prepareMask(mask),
contours = [],
label = 0,
w = m.width,
w2 = w * 2,
h = m.height,
src = m.data,
dx = m.offset.x,
dy = m.offset.y,
dest = new Uint8Array(src), // label matrix
i, j, x, y, k, k1, c, inner, dir, first, second, current, previous, next, d;
// all [dx,dy] pairs (array index is the direction)
// 5 6 7
// 4 X 0
// 3 2 1
var directions = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]];
for (y = 1; y < h - 1; y++)
for (x = 1; x < w - 1; x++) {
k = y * w + x;
if (src[k] === 1) {
for (i = -w; i < w2; i += w2) { // k - w: outer tracing (y - 1), k + w: inner tracing (y + 1)
if (src[k + i] === 0 && dest[k + i] === 0) { // need contour tracing
inner = i === w; // is inner contour tracing ?
label++; // label for the next contour
c = [];
dir = inner ? 2 : 6; // start direction
current = previous = first = { x: x, y: y };
second = null;
while (true) {
dest[current.y * w + current.x] = label; // mark label for the current point
// bypass all the neighbors around the current point in a clockwise
for (j = 0; j < 8; j++) {
dir = (dir + 1) % 8;
// get the next point by new direction
d = directions[dir]; // index as direction
next = { x: current.x + d[0], y: current.y + d[1] };
k1 = next.y * w + next.x;
if (src[k1] === 1) // black boundary pixel
{
dest[k1] = label; // mark a label
break;
}
dest[k1] = -1; // mark a white boundary pixel
next = null;
}
if (next === null) break; // no neighbours (one-point contour)
current = next;
if (second) {
if (previous.x === first.x && previous.y === first.y && current.x === second.x && current.y === second.y) {
break; // creating the contour completed when returned to original position
}
} else {
second = next;
}
c.push({ x: previous.x + dx, y: previous.y + dy });
previous = current;
dir = (dir + 4) % 8; // next dir (symmetrically to the current direction)
}
if (next != null) {
c.push({ x: first.x + dx, y: first.y + dy }); // close the contour
contours.push({ inner: inner, label: label, points: c }); // add contour to the list
}
}
}
}
}
return contours;
};
/** Simplify contours
* Algorithms: http://psimpl.sourceforge.net/douglas-peucker.html
* http://neerc.ifmo.ru/wiki/index.php?title=%D0%A3%D0%BF%D1%80%D0%BE%D1%89%D0%B5%D0%BD%D0%B8%D0%B5_%D0%BF%D0%BE%D0%BB%D0%B8%D0%B3%D0%BE%D0%BD%D0%B0%D0%BB%D1%8C%D0%BD%D0%BE%D0%B9_%D1%86%D0%B5%D0%BF%D0%B8
* @param {Array} contours: {Array} points, {bool} inner, {int} label
* @param {float} simplify tolerant
* @param {int} simplify count: min number of points when the contour is simplified
* @return {Array} contours: {Array} points, {bool} inner, {int} label, {int} initialCount
*/
lib.simplifyContours = function(contours, simplifyTolerant, simplifyCount) {
var lenContours = contours.length,
result = [],
i, j, k, c, points, len, resPoints, lst, stack, ids,
maxd, maxi, dist, r1, r2, r12, dx, dy, pi, pf, pl;
// walk through all contours
for (j = 0; j < lenContours; j++) {
c = contours[j];
points = c.points;
len = c.points.length;
if (len < simplifyCount) { // contour isn't simplified
resPoints = [];
for (k = 0; k < len; k++) {
resPoints.push({ x: points[k].x, y: points[k].y });
}
result.push({ inner: c.inner, label: c.label, points: resPoints, initialCount: len });
continue;
}
lst = [0, len - 1]; // always add first and last points
stack = [{ first: 0, last: len - 1 }]; // first processed edge
do {
ids = stack.shift();
if (ids.last <= ids.first + 1) // no intermediate points
{
continue;
}
maxd = -1.0; // max distance from point to current edge
maxi = ids.first; // index of maximally distant point
for (i = ids.first + 1; i < ids.last; i++) // bypass intermediate points in edge
{
// calc the distance from current point to edge
pi = points[i];
pf = points[ids.first];
pl = points[ids.last];
dx = pi.x - pf.x;
dy = pi.y - pf.y;
r1 = Math.sqrt(dx * dx + dy * dy);
dx = pi.x - pl.x;
dy = pi.y - pl.y;
r2 = Math.sqrt(dx * dx + dy * dy);
dx = pf.x - pl.x;
dy = pf.y - pl.y;
r12 = Math.sqrt(dx * dx + dy * dy);
if (r1 >= Math.sqrt(r2 * r2 + r12 * r12)) dist = r2;
else if (r2 >= Math.sqrt(r1 * r1 + r12 * r12)) dist = r1;
else dist = Math.abs((dy * pi.x - dx * pi.y + pf.x * pl.y - pl.x * pf.y) / r12);
if (dist > maxd) {
maxi = i; // save the index of maximally distant point
maxd = dist;
}
}
if (maxd > simplifyTolerant) // if the max "deviation" is larger than allowed then...
{
lst.push(maxi); // add index to the simplified list
stack.push({ first: ids.first, last: maxi }); // add the left part for processing
stack.push({ first: maxi, last: ids.last }); // add the right part for processing
}
} while (stack.length > 0);
resPoints = [];
len = lst.length;
lst.sort(function(a, b) { return a - b; }); // restore index order
for (k = 0; k < len; k++) {
resPoints.push({ x: points[lst[k]].x, y: points[lst[k]].y }); // add result points to the correct order
}
result.push({ inner: c.inner, label: c.label, points: resPoints, initialCount: c.points.length });
}
return result;
};
return lib;
})();
if (typeof module !== "undefined" && module !== null) module.exports = MagicWand;
if (typeof window !== "undefined" && window !== null) window.MagicWand = MagicWand;
|
export const TOGGLE_STREAM = 'TOGGLE_STREAM';
export const TOGGLE_PREVIEW = 'TOGGLE_PREVIEW';
export const TOGGLE_BROADCAST = 'TOGGLE_BROADCAST';
export const toggleStream = () => ({
type: TOGGLE_STREAM,
});
export const togglePreview = () => ({
type: TOGGLE_PREVIEW,
});
export const toggleBroadcast = () => ({
type: TOGGLE_BROADCAST,
});
|
import * as OV from '../../source/engine/main.js';
import * as fs from 'fs';
import * as path from 'path';
export function GetTextFileContent (fileName)
{
var testFilePath = path.join (path.resolve (), 'test', 'testfiles', fileName);
if (!fs.existsSync (testFilePath)) {
return null;
}
return fs.readFileSync (testFilePath).toString ();
}
export function GetArrayBufferFileContent (fileName)
{
var testFilePath = path.join (path.resolve (), 'test', 'testfiles', fileName);
var buffer = fs.readFileSync (testFilePath);
var arrayBuffer = new ArrayBuffer (buffer.length);
var uint8Array = new Uint8Array (arrayBuffer);
var i;
for (i = 0; i < buffer.length; ++i) {
uint8Array[i] = buffer[i];
}
return arrayBuffer
}
export function ModelNodesToTree (model)
{
function AddNodeToModelTree (model, node, modelTree)
{
modelTree.name = node.HasParent () ? node.GetName () : '<Root>';
modelTree.childNodes = [];
for (const childNode of node.GetChildNodes ()) {
let childTree = {};
AddNodeToModelTree (model, childNode, childTree);
modelTree.childNodes.push (childTree);
}
modelTree.meshNames = [];
for (const meshIndex of node.GetMeshIndices ()) {
modelTree.meshNames.push (model.GetMesh (meshIndex).GetName ());
}
}
let modelTree = {};
let root = model.GetRootNode ();
AddNodeToModelTree (model, root, modelTree);
return modelTree;
}
export function ModelToObject (model)
{
var obj = {
name : model.GetName (),
materials : [],
meshes : []
};
var i, j;
var material;
for (i = 0; i < model.MaterialCount (); i++) {
material = model.GetMaterial (i);
obj.materials.push ({
name : material.name
});
}
var mesh, triangle, meshObj, triangleObj;
for (i = 0; i < model.MeshCount (); i++) {
mesh = model.GetMesh (i);
meshObj = {
name : mesh.GetName (),
triangles : []
};
for (j = 0; j < mesh.TriangleCount (); j++) {
triangle = mesh.GetTriangle (j);
triangleObj = {
mat : triangle.mat,
vertices : [],
normals : [],
uvs : []
};
triangleObj.vertices.push (
mesh.GetVertex (triangle.v0).x,
mesh.GetVertex (triangle.v0).y,
mesh.GetVertex (triangle.v0).z,
mesh.GetVertex (triangle.v1).x,
mesh.GetVertex (triangle.v1).y,
mesh.GetVertex (triangle.v1).z,
mesh.GetVertex (triangle.v2).x,
mesh.GetVertex (triangle.v2).y,
mesh.GetVertex (triangle.v2).z
);
triangleObj.normals.push (
mesh.GetNormal (triangle.n0).x,
mesh.GetNormal (triangle.n0).y,
mesh.GetNormal (triangle.n0).z,
mesh.GetNormal (triangle.n1).x,
mesh.GetNormal (triangle.n1).y,
mesh.GetNormal (triangle.n1).z,
mesh.GetNormal (triangle.n2).x,
mesh.GetNormal (triangle.n2).y,
mesh.GetNormal (triangle.n2).z
);
if (triangle.HasTextureUVs ()) {
triangleObj.uvs.push (
mesh.GetTextureUV (triangle.u0).x,
mesh.GetTextureUV (triangle.u0).y,
mesh.GetTextureUV (triangle.u1).x,
mesh.GetTextureUV (triangle.u1).y,
mesh.GetTextureUV (triangle.u2).x,
mesh.GetTextureUV (triangle.u2).y
);
}
meshObj.triangles.push (triangleObj);
}
obj.meshes.push (meshObj);
}
return obj;
}
export function ModelToObjectSimple (model)
{
var obj = {
name : model.GetName (),
materials : [],
meshes : []
};
var i;
var material;
for (i = 0; i < model.MaterialCount (); i++) {
material = model.GetMaterial (i);
obj.materials.push ({
name : material.name
});
}
model.EnumerateTransformedMeshes ((mesh) => {
let boundingBox = OV.GetBoundingBox (mesh);
let meshObj = {
name : mesh.GetName (),
vertexCount : mesh.VertexCount (),
vertexColorCount : mesh.VertexColorCount (),
normalCount : mesh.NormalCount (),
uvCount : mesh.TextureUVCount (),
triangleCount : mesh.TriangleCount (),
boundingBox : {
min : [boundingBox.min.x, boundingBox.min.y, boundingBox.min.z],
max : [boundingBox.max.x, boundingBox.max.y, boundingBox.max.z]
}
};
obj.meshes.push (meshObj);
});
return obj;
}
export function GetTwoCubesConnectingInOneVertexModel ()
{
let model = new OV.Model ();
let cube1 = OV.GenerateCuboid (null, 1.0, 1.0, 1.0);
model.AddMeshToRootNode (cube1);
let cube2 = OV.GenerateCuboid (null, 1.0, 1.0, 1.0);
let matrix = new OV.Matrix ().CreateTranslation (1.0, 1.0, 1.0);
OV.TransformMesh (cube2, new OV.Transformation (matrix));
model.AddMeshToRootNode (cube2);
OV.FinalizeModel (model);
return model;
}
export function GetTwoCubesConnectingInOneEdgeModel ()
{
let model = new OV.Model ();
let cube1 = OV.GenerateCuboid (null, 1.0, 1.0, 1.0);
model.AddMeshToRootNode (cube1);
let cube2 = OV.GenerateCuboid (null, 1.0, 1.0, 1.0);
let matrix = new OV.Matrix ().CreateTranslation (1.0, 0.0, 1.0);
OV.TransformMesh (cube2, new OV.Transformation (matrix))
model.AddMeshToRootNode (cube2);
OV.FinalizeModel (model);
return model;
}
export function GetTwoCubesConnectingInOneFaceModel ()
{
let model = new OV.Model ();
let cube1 = OV.GenerateCuboid (null, 1.0, 1.0, 1.0);
model.AddMeshToRootNode (cube1);
let cube2 = OV.GenerateCuboid (null, 1.0, 1.0, 1.0);
let matrix = new OV.Matrix ().CreateTranslation (1.0, 0.0, 0.0);
OV.TransformMesh (cube2, new OV.Transformation (matrix));
model.AddMeshToRootNode (cube2);
OV.FinalizeModel (model);
return model;
}
export function GetCubeWithOneMissingFaceMesh ()
{
var cube = new OV.Mesh ();
cube.AddVertex (new OV.Coord3D (0.0, 0.0, 0.0));
cube.AddVertex (new OV.Coord3D (1.0, 0.0, 0.0));
cube.AddVertex (new OV.Coord3D (1.0, 1.0, 0.0));
cube.AddVertex (new OV.Coord3D (0.0, 1.0, 0.0));
cube.AddVertex (new OV.Coord3D (0.0, 0.0, 1.0));
cube.AddVertex (new OV.Coord3D (1.0, 0.0, 1.0));
cube.AddVertex (new OV.Coord3D (1.0, 1.0, 1.0));
cube.AddVertex (new OV.Coord3D (0.0, 1.0, 1.0));
cube.AddTriangle (new OV.Triangle (0, 1, 5));
cube.AddTriangle (new OV.Triangle (0, 5, 4));
cube.AddTriangle (new OV.Triangle (1, 2, 6));
cube.AddTriangle (new OV.Triangle (1, 6, 5));
cube.AddTriangle (new OV.Triangle (2, 3, 7));
cube.AddTriangle (new OV.Triangle (2, 7, 6));
cube.AddTriangle (new OV.Triangle (3, 0, 4));
cube.AddTriangle (new OV.Triangle (3, 4, 7));
cube.AddTriangle (new OV.Triangle (0, 3, 2));
cube.AddTriangle (new OV.Triangle (0, 2, 1));
return cube;
}
export function GetTetrahedronMesh ()
{
var tetrahedron = new OV.Mesh ();
let a = 1.0;
tetrahedron.AddVertex (new OV.Coord3D (+a, +a, +a));
tetrahedron.AddVertex (new OV.Coord3D (-a, -a, +a));
tetrahedron.AddVertex (new OV.Coord3D (-a, +a, -a));
tetrahedron.AddVertex (new OV.Coord3D (+a, -a, -a));
tetrahedron.AddTriangle (new OV.Triangle (0, 1, 3));
tetrahedron.AddTriangle (new OV.Triangle (0, 2, 1));
tetrahedron.AddTriangle (new OV.Triangle (0, 3, 2));
tetrahedron.AddTriangle (new OV.Triangle (1, 2, 3));
return tetrahedron;
}
export function GetModelWithOneMesh (mesh)
{
var model = new OV.Model ();
model.AddMeshToRootNode (mesh);
OV.FinalizeModel (model);
return model;
}
export function GetHierarchicalModelNoFinalization ()
{
/*
+ <Root>
+ Node 1
+ Node 3
Mesh 5
Mesh 6
Mesh 7
+ Node 4
Mesh 7
Mesh 3
Mesh 4
+ Node 2
Mesh 1
Mesh 2
*/
let model = new OV.Model ();
let root = model.GetRootNode ();
let node1 = new OV.Node ();
node1.SetName ('Node 1');
let node2 = new OV.Node ();
node2.SetName ('Node 2');
let node3 = new OV.Node ();
node3.SetName ('Node 3');
let node4 = new OV.Node ();
node4.SetName ('Node 4');
root.AddChildNode (node1);
root.AddChildNode (node2);
node1.AddChildNode (node3);
node1.AddChildNode (node4);
let mesh1 = new OV.Mesh ();
mesh1.SetName ('Mesh 1');
let mesh2 = new OV.Mesh ();
mesh2.SetName ('Mesh 2');
let mesh3 = new OV.Mesh ();
mesh3.SetName ('Mesh 3');
let mesh4 = new OV.Mesh ();
mesh4.SetName ('Mesh 4');
let mesh5 = new OV.Mesh ();
mesh5.SetName ('Mesh 5');
let mesh6 = new OV.Mesh ();
mesh6.SetName ('Mesh 6');
let mesh7 = new OV.Mesh ();
mesh7.SetName ('Mesh 7');
let mesh1Ind = model.AddMesh (mesh1);
let mesh2Ind = model.AddMesh (mesh2);
let mesh3Ind = model.AddMesh (mesh3);
let mesh4Ind = model.AddMesh (mesh4);
let mesh5Ind = model.AddMesh (mesh5);
let mesh6Ind = model.AddMesh (mesh6);
let mesh7Ind = model.AddMesh (mesh7);
root.AddMeshIndex (mesh1Ind);
root.AddMeshIndex (mesh2Ind);
node1.AddMeshIndex (mesh3Ind);
node1.AddMeshIndex (mesh4Ind);
node3.AddMeshIndex (mesh5Ind);
node3.AddMeshIndex (mesh6Ind);
node3.AddMeshIndex (mesh7Ind);
node4.AddMeshIndex (mesh7Ind);
return model;
}
export function GetTranslatedRotatedCubesModel ()
{
/*
+ <Root>
+ Translated
Cube
+ Rotated
+ Translated and Rotated
Cube
Cube
*/
let model = new OV.Model ();
let mesh = OV.GenerateCuboid (null, 1.0, 1.0, 1.0);
mesh.SetName ('Cube');
let meshIndex = model.AddMesh (mesh);
let root = model.GetRootNode ();
root.AddMeshIndex (0);
let translatedNode = new OV.Node ();
translatedNode.SetName ('Translated');
translatedNode.SetTransformation (new OV.Transformation (new OV.Matrix ().CreateTranslation (2.0, 0.0, 0.0)));
translatedNode.AddMeshIndex (0);
let rotatedNode = new OV.Node ();
rotatedNode.SetName ('Rotated');
let rotation = OV.QuaternionFromAxisAngle (new OV.Coord3D (0.0, 0.0, 1.0), Math.PI / 2.0);
rotatedNode.SetTransformation (new OV.Transformation (new OV.Matrix ().CreateRotation (rotation.x, rotation.y, rotation.z, rotation.w)));
let translatedRotatedNode = new OV.Node ();
translatedRotatedNode.SetName ('Translated and Rotated');
translatedRotatedNode.SetTransformation (new OV.Transformation (new OV.Matrix ().CreateTranslation (2.0, 0.0, 0.0)));
translatedRotatedNode.AddMeshIndex (0);
root.AddChildNode (translatedNode);
root.AddChildNode (rotatedNode);
rotatedNode.AddChildNode (translatedRotatedNode);
OV.FinalizeModel (model);
return model;
}
|
define(["lodash","backbone","jquery","text!html/message.html"],function(e,t,a,s){var n;return n=t.View.extend({template:e.template(s),tagName:"div",name:"message",show:function(t){var s,n=t.templateData;e.defaults(n,this.getDefaultTemplateData()),s=this.template(n),this.$el.addClass("message"),this.$el.html(s),a("#messages").append(this.$el),e.isFunction(t.postRender)&&t.postRender(this),e.defer(e.bind(this.$el.addClass,this.$el,"show"))},hide:function(){var e=this;this.$el.one("transitionend webkitTransitionEnd",function(){e.remove()}),this.$el.addClass("hide")},getDefaultTemplateData:function(){return{header:"",body:"",buttons:[]}}})}); |
// Generated by CoffeeScript 1.7.1
(function() {
module.exports = {
required: function(definition, context) {
var i, property, _i, _len;
if (!this.test_type("array", definition)) {
throw new Error("The 'required' attribute must be an array");
}
if (definition.length === 0) {
throw new Error("The 'required' array must have at least one element");
}
for (i = _i = 0, _len = definition.length; _i < _len; i = ++_i) {
property = definition[i];
if (!this.test_type("string", property)) {
throw new Error("The 'required' array may only contain strings");
}
}
return (function(_this) {
return function(data, runtime) {
var _j, _len1;
for (i = _j = 0, _len1 = definition.length; _j < _len1; i = ++_j) {
property = definition[i];
if (data[property] === void 0) {
runtime.error(context.child(i));
}
}
return null;
};
})(this);
},
properties: function(definition, context) {
var new_context, property, schema, test, tests;
if (!this.test_type("object", definition)) {
throw new Error("The 'properties' attribute must be an object");
}
tests = {};
for (property in definition) {
schema = definition[property];
if (!this.test_type("object", schema)) {
throw new Error("The 'properties' attribute must be an object");
}
new_context = context.child(property);
test = this.compile(new_context, schema);
tests[property] = test;
}
return (function(_this) {
return function(data, runtime) {
var value;
if (_this.test_type("object", data)) {
for (property in data) {
value = data[property];
if ((test = tests[property]) != null) {
test(value, runtime.child(property));
}
}
return null;
}
};
})(this);
},
minProperties: function(definition, context) {
return (function(_this) {
return function(data, runtime) {
if (_this.test_type("object", data)) {
if (Object.keys(data).length < definition) {
return runtime.error(context, data);
}
}
};
})(this);
},
maxProperties: function(definition, context) {
return (function(_this) {
return function(data, runtime) {
if (_this.test_type("object", data)) {
if (Object.keys(data).length > definition) {
return runtime.error(context, data);
}
}
};
})(this);
},
dependencies: function(definition, context) {
var dependency, fn, name, property, tests, _i, _len;
if (!this.test_type("object", definition)) {
throw new Error("Value of 'dependencies' must be an object");
} else {
tests = [];
for (property in definition) {
dependency = definition[property];
if (this.test_type("array", dependency)) {
if (dependency.length === 0) {
throw new Error("Arrays in 'dependencies' may not be empty");
}
for (_i = 0, _len = dependency.length; _i < _len; _i++) {
name = dependency[_i];
if (!this.test_type("string", name)) {
throw new Error("Vales of 'dependencies' arrays must be strings");
}
}
tests.push((function(_this) {
return function(data, runtime) {
var item, _j, _len1;
if (data[property] != null) {
for (_j = 0, _len1 = dependency.length; _j < _len1; _j++) {
item = dependency[_j];
if (data[item] == null) {
runtime.child(property).error(context);
}
}
return null;
}
};
})(this));
} else if (this.test_type("object", dependency)) {
fn = this.compile(context, dependency);
tests.push((function(_this) {
return function(data, runtime) {
if (data[property]) {
return fn(data, runtime);
} else {
return true;
}
};
})(this));
} else {
throw new Error("Invalid dependency");
}
}
}
return (function(_this) {
return function(data, runtime) {
var test, _j, _len1;
if (_this.test_type("object", data)) {
for (_j = 0, _len1 = tests.length; _j < _len1; _j++) {
test = tests[_j];
test(data, runtime);
}
return null;
}
};
})(this);
}
};
}).call(this);
|
'use strict'
const Botkit = require('botkit')
const MongoStore = require('./lib/mongo_storage')
const { parsedUptime } = require('./lib/bot_tools')
const { imageSearch, urban, liveStatus, seen } = require('./lib/bot_plugins')
const controller = Botkit.slackbot({
debug: process.env.NODE_ENV === 'development',
storage: new MongoStore({host: 'mongodb'})
})
controller.spawn({
token: process.env.SLACK_TOKEN
}).startRTM()
controller.setupWebserver(5000, (err, express_webserver) => {
if (err) throw err
controller.createWebhookEndpoints(express_webserver)
})
// image search
controller.hears('^!(img|gif)(.*)', 'ambient', (bot, message) => {
const keyword = message.match[1]
const query = message.match[2]
imageSearch(keyword === 'gif' ? `gif ${query}` : query)
.then((link) => bot.reply(message, link))
.catch((err) => bot.reply(message, err))
})
// urban dictionary search
controller.hears('^!urban (.*)', 'ambient', (bot, message) => {
const query = message.match[1]
urban(query)
.then((link) => bot.reply(message, link))
.catch((err) => bot.reply(message, err))
})
// used for checking status
controller.hears('^!ping', 'ambient', (bot, message) => {
bot.reply(message, `Pong!\n\`Uptime: ${parsedUptime(process.uptime())}\``)
})
// xbox live status checker
controller.hears('^!live (.*)', 'ambient', (bot, message) => {
const gamertag = message.match[1]
liveStatus(gamertag)
.then((response) => bot.reply(message, response))
.catch((err) => bot.reply(message, err))
})
// returns last activity for a user
controller.hears('^!seen (.*)', 'ambient', (bot, message) => {
const query = message.match[1]
seen(controller, query)
.then((res) => bot.reply(message, res))
})
// //////////////////////////////////////////////////
// sets up admin tools/listeners
require('./lib/admin_listeners')(controller)
// message logging; no output; must be last
controller.hears('.*', 'ambient', (bot, message) => {
if (message.channel[0] === 'G') return // don't log messages from private rooms
controller.storage.messages.save(message)
})
|
exports.check = function (markoCompiler, expect) {
var taglibLookup = markoCompiler.taglibLookup;
var lookup = taglibLookup.buildLookup(__dirname);
var tag = lookup.getTag("test-hello");
// console.log(Object.keys(lookup.tags));
expect(tag != null).to.equal(true);
expect(tag.name).to.equal("test-hello");
};
|
//listens for the dom to load and calls init
// window is an object with functions. One of them is addEventListener which listens for events
// This event is DOMContentLoaded which means that the DOMContent has been loaded
// then we call function init
// the window triggers DOMContentLoaded and then we listen for it
// then we remove it so we only call it once
window.addEventListener(
'DOMContentLoaded',
init
);
function init() {
window.removeEventListener(
'DOMContentLoaded',
init
);
// use this to store your first number
var firstNumber = '';
// use this to store your second number
var secondNumber = '';
// set the flag for storing first number vs second number
var storeSecondNumber = false;
var operation = false;
var numbers = document.body.querySelector('.numbers');
var operators = document.body.querySelector('.operators');
numbers.addEventListener(
'click',
function (event) {
var target = event.target;
var value = target.dataset.value;
if (target.className == 'clear') {
//this clears the output(what you see)
document.body.querySelector('.output').innerHTML = '';
//this clears the number that is stored
secondNumber = '';
firstNumber = '';
operation = '';
return;
}
if (storeSecondNumber === true) {
if (secondNumber.includes('.') && value == '.') {
return;
}
if (secondNumber.includes('-') && value == '-') {
secondNumber.replace('-', '');
return;
} else if (value == '-') {
secondNumber = '-';
return;
}
secondNumber += value;
display(secondNumber);
} else {
if (firstNumber.includes('.') && value == '.') {
return;
}
if (firstNumber.includes('-') && value == '-') {
firstNumber.replace('-', '');
return;
} else if (value == '-') {
firstNumber = '-';
return;
}
firstNumber += value;
display(firstNumber);
}
}
);
operators.addEventListener(
'click',
function (event) {
var target = event.target;
switch (target.className) {
case 'division':
operation = 'division';
storeSecondNumber = true;
break;
case 'multiplication':
operation = 'multiplication';
storeSecondNumber = true;
break;
case 'minus':
operation = 'minus';
storeSecondNumber = true;
break;
case 'add':
operation = 'add';
storeSecondNumber = true;
break;
case 'equal':
calculate(firstNumber, secondNumber, operation);
break;
}
}
);
}
function calculate(firstNumber, secondNumber, operation) {
var answer = 0;
switch (operation) {
case 'division':
answer = Number(firstNumber) / Number(secondNumber);
break;
case 'multiplication':
answer = Number(firstNumber) * Number(secondNumber);
break;
case 'minus':
answer = Number(firstNumber) - Number(secondNumber);
break;
case 'add':
answer = Number(firstNumber) + Number(secondNumber);
break;
}
display(answer);
}
function display(number) {
document.body.querySelector('.output').innerHTML = number;
}
|
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Polyfill
if (!Function.prototype.bind) {
Function.prototype.bind = function(oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function() {},
fBound = function() {
return fToBind.apply(this instanceof fNOP
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
|
var express = require('express');
mongoose = require('mongoose');
mongoose.connect(process.env.mongodb);
var Thread = mongoose.model('thread', new mongoose.Schema({
id: {
type: String,
unique: true
},
title: String
}));
var topLevelItems = require('./top-level-items');
/*
mongodb://guest:guest@ds053978.mongolab.com:53978/heroku_r84ptgfg
*/
module.exports = express.Router()
.get('/threads.json', function (request, response) {
Thread.find({}).exec(function (error, threads) {
if (error) {
throw error;
}
response.json(threads);
}); // can not find id's => can not develope
/*
response.json([
{
id: 'engineering',
title: 'Engineering'
},
{
id: 'science',
title: 'Science'
},
{
id: 'music',
title: 'Music'
},
{
id: 'places',
title: 'Places'
},
{
id: 'beyond',
title: 'Beyond'
}
]);*/
})
.get('/thread/:id.json', function (request, response) {
response.json(topLevelItems.get(request.params.id));
})
.all('/(*)', function (request, response) {
response.status(404).send('Requested resource not found!');
});
|
define(["../../_base/array", "../../_base/lang", "../../when"
], function(array, lang, when){
// module:
// dojo/store/util/QueryResults
var QueryResults = function(results){console.log('QueryResults');
// summary:
// A function that wraps the results of a store query with additional
// methods.
// description:
// QueryResults is a basic wrapper that allows for array-like iteration
// over any kind of returned data from a query. While the simplest store
// will return a plain array of data, other stores may return deferreds or
// promises; this wrapper makes sure that *all* results can be treated
// the same.
//
// Additional methods include `forEach`, `filter` and `map`.
// results: Array|dojo/promise/Promise
// The result set as an array, or a promise for an array.
// returns:
// An array-like object that can be used for iterating over.
// example:
// Query a store and iterate over the results.
//
// | store.query({ prime: true }).forEach(function(item){
// | // do something
// | });
if(!results){
return results;
}
var isPromise = !!results.then;
// if it is a promise it may be frozen
if(isPromise){
results = lang.delegate(results);
}
function addIterativeMethod(method){console.log('QueryResults addIterativeMethod');
// Always add the iterative methods so a QueryResults is
// returned whether the environment is ES3 or ES5
results[method] = function(){
var args = arguments;
var result = when(results, function(results){
Array.prototype.unshift.call(args, results);
return QueryResults(array[method].apply(array, args));
});
// forEach should only return the result of when()
// when we're wrapping a promise
if(method !== "forEach" || isPromise){
return result;
}
};
}
addIterativeMethod("forEach");
addIterativeMethod("filter");
addIterativeMethod("map");
if(results.total == null){
results.total = when(results, function(results){console.log('QueryResults results.total');
return results.length;
});
}
return results; // Object
};
lang.setObject("dojo.store.util.QueryResults", QueryResults);
return QueryResults;
});
|
/**
* Copyright (c) 2013, FeedHenry Ltd. All Rights Reserved.
*
* Class which exposes collection of functions for performing tests on fetch TODO details endpoint.
* - Tests valid request parameters.
* - Tests empty session id in request parameters.
* - Tests invalid session id in request parameters.
*/
// Dependencies.
var fh = require("fh-fhc");
var constants = require('../../config/constants.js');
var testConfig = require('../../config/testConfig.js');
var winston = require("winston");
var MODULE_NAME = " - Fetch fetchToDos Test - ";
// Construct an empty authentication request format object.
var authReq =
{
"request":
{
"header":
{
"appType": ""
},
"payload":
{
"login":
{
"userName": "",
"password": ""
}
}
}
};
// Construct an empty fetch todo request format object.
var fetchToDoReq =
{
"request":
{
"header":
{
"sessionId": ""
},
"payload":
{
"fetchToDo":
{
}
}
}
};
/**
* Function which tests valid fetch todos request.
*/
exports.test_FetchToDosValidTest = function(test, assert)
{
var METHOD_NAME = "FetchToDoValidTest :";
winston.info("\n----------: START" + MODULE_NAME + METHOD_NAME + "----------\n");
// Add valid authentication request parameters.
authReq.request.header.appType = "Client";
authReq.request.payload.login.userName = "Spengler";
authReq.request.payload.login.password = "TheKeymaster";
fh.fhc.load(function(err)
{
var start = new Date();
var datePrefix = start.toJSON();
winston.info("Authentication request - " + datePrefix + " : " + JSON.stringify(authReq, null, '\t'));
// Invoke authentication endpoint
fh.act([testConfig.appId, 'authenticateAction', JSON.stringify(authReq)], function(error, data)
{
// Error object?
assert.ifError(err);
var now = new Date();
var datePrefix = now.toJSON();
winston.info("Authentication response - " + datePrefix + " : " + JSON.stringify(data, null, '\t'));
// Response object?
assert.ok(data.hasOwnProperty('response'));
// Did we get a sessionId and status as expected?
assert.isDefined(data.response);
assert.isDefined(data.response.header);
assert.isDefined(data.response.header.sessionId);
assert.isDefined(data.response.payload);
assert.isDefined(data.response.payload.login);
assert.isDefined(data.response.payload.login.status);
assert.equal(data.response.payload.login.status.code, constants.RESP_SUCCESS);
// Now, invoke fetch Todos endpoint.
fetchToDoReq.request.header.sessionId = data.response.header.sessionId;
var fetchToDosStart = new Date();
var datePrefix = fetchToDosStart.toJSON();
winston.info("Fetch TODOs request - " + datePrefix + " : " + JSON.stringify(fetchToDoReq, null, '\t'));
fh.act([testConfig.appId, 'fetchToDoAction', JSON.stringify(fetchToDoReq)], function(err, data)
{
// Error object?
assert.ifError(err);
var now = new Date();
var datePrefix = now.toJSON();
winston.info("Fetch TODOs response - " + datePrefix + " : " + JSON.stringify(data, null, '\t'));
//response objects?
assert.ok(data.hasOwnProperty("response"));
assert.isDefined(data.response);
assert.isDefined(data.response.payload);
assert.isDefined(data.response.payload.fetchToDos);
assert.isDefined(data.response.payload.fetchToDos.status);
assert.equal(data.response.payload.fetchToDos.status.code, constants.RESP_SUCCESS);
var end = new Date();
var diff = end.getTime() - start.getTime();
winston.info("Fetch TODOs test latency - " + diff);
test.finish();
winston.info("\n----------: END" + MODULE_NAME + METHOD_NAME + "----------\n");
});
});
});
};
/**
* Function which tests invalid fetch todos request (Missing session id).
*/
exports.test_FetchToDoBlankSessionId = function(test, assert)
{
var METHOD_NAME = "FetchToDoInvalidTest (Missing session id) :";
winston.info("\n----------: START" + MODULE_NAME + METHOD_NAME + "----------\n");
// Clear session id from request parameters.
fetchToDoReq.request.header.sessionId = "";
fh.fhc.load(function(err)
{
var start = new Date();
var datePrefix = start.toJSON();
winston.info("Fetch TODOs request - " + datePrefix + " : " + JSON.stringify(fetchToDoReq, null, '\t'));
fh.act([testConfig.appId, 'fetchToDoAction', JSON.stringify(fetchToDoReq)], function(err, data)
{
var now = new Date();
var datePrefix = now.toJSON();
var errorResponse = err.split("error:")[1].split("'")[1];
var Error = JSON.parse(errorResponse);
winston.info("Fetch TODOs response - " + datePrefix + " : " + JSON.stringify(Error, null, '\t'));
// Response object?
assert.ok(Error.hasOwnProperty('response'));
//Did we get a error response as expected?
assert.isDefined(Error.response);
assert.isDefined(Error.response.payload);
assert.isDefined(Error.response.payload.error);
assert.isDefined(Error.response.payload.error.status);
assert.equal(Error.response.payload.error.status, constants.RESP_AUTH_FAILED);
assert.equal(Error.response.payload.error.category, "Authorization failure. sessionId not specified.");
var end = new Date();
var diff = end.getTime() - start.getTime();
winston.info("Fetch TODOs test latency - " + diff);
test.finish();
winston.info("\n----------: END" + MODULE_NAME + METHOD_NAME + "----------\n");
});
});
};
/**
* Function which tests invalid fetch todos request (Invalid session id).
*/
exports.test_FetchToDoInvalidSessionId = function(test, assert)
{
var METHOD_NAME = "FetchToDoInvalidTest (Invalid session id) :";
winston.info("\n----------: START" + MODULE_NAME + METHOD_NAME + "----------\n");
// Add invalid session id in request parameters.
sessionId = "vsvycsgyugegew";
fetchToDoReq.request.header.sessionId = sessionId
fh.fhc.load(function(err)
{
var start = new Date();
var datePrefix = start.toJSON();
winston.info("Fetch TODO request - " + datePrefix + " : " + JSON.stringify(fetchToDoReq, null, '\t'));
fh.act([testConfig.appId, 'fetchToDoAction', JSON.stringify(fetchToDoReq)], function(err, data)
{
var now = new Date();
var datePrefix = now.toJSON();
var errorResponse = err.split("error:")[1].split("'")[1];
var Error = JSON.parse(errorResponse);
winston.info("Fetch TODO response - " + datePrefix + " : " + JSON.stringify(Error, null, '\t'));
// Response object?
assert.ok(Error.hasOwnProperty('response'));
//Did we get a error response as expected?
assert.isDefined(Error.response);
assert.isDefined(Error.response.payload);
assert.isDefined(Error.response.payload.error);
assert.isDefined(Error.response.payload.error.status);
assert.equal(Error.response.payload.error.status, constants.RESP_AUTH_FAILED);
assert.equal(Error.response.payload.error.category, "Authorization failure. Session does not exist for sessionId: " + sessionId);
var end = new Date();
var diff = end.getTime() - start.getTime();
winston.info("Fetch TODOs test latency - " + diff);
test.finish();
winston.info("\n----------: END" + MODULE_NAME + METHOD_NAME + "----------\n");
});
});
}; |
import * as ofxConverter from 'ofx';
import moment from 'moment';
import { KError } from '../../helpers';
const accountsTypesMap = {
CHECKING: 'account-type.checking',
SAVINGS: 'account-type.savings',
CREDITLINE: 'account-type.loan', // line of credit
MONEYMRKT: 'account-type.unknown', // money market
CD: 'account-type.unknown' // certificate of deposit
};
const transactionsTypesMap = {
CREDIT: 'type.card',
DEBIT: 'type.card',
INT: 'type.bankfee', // Interest earned or paid (depends on signage of amount)
DIV: 'type.bankfee', // Dividend
FEE: 'type.bankfee',
SRVCHG: 'type.bankfee',
DEP: 'type.cash_deposit',
ATM: 'type.withdrawal', // ATM debit or credit (depends on signage of amount)
POS: 'type.card', // Point of sale debit or credit (depends on signage of amount)
XFER: 'type.transfer',
CHECK: 'type.check',
PAYMENT: 'type.card',
CASH: 'type.withdrawal', // Actually an electronic payment
DIRECTDEP: 'type.withdrawal',
DIRECTDEBIT: 'type.cash_deposit',
REPEATPMT: 'type.card', // Repeating payment/standing order
OTHER: 'type.unknown',
HOLD: 'type.unknown'
};
export function ofxToKresus(ofx) {
// See http://www.ofx.net/downloads/OFX%202.2.pdf.
let data = null;
try {
data = ofxConverter.parse(ofx);
data = data.OFX.BANKMSGSRSV1.STMTTRNRS;
} catch (err) {
throw new KError('Invalid OFX file.');
}
// If there is only one account it is an object, else an array of object.
if (!(data instanceof Array)) {
data = [data];
} else if (!data.length) {
return null;
}
let accountId = 0;
let accounts = [];
let transactions = [];
for (let account of data) {
account = account.STMTRS;
if (!account) {
throw new KError('Cannot find state response message in OFX file.');
}
let currencyCode = account.CURDEF;
if (!currencyCode) {
throw new KError('Cannot find currency code in OFX file.');
}
let accountInfo = account.BANKACCTFROM;
let vendorAccountId = accountInfo.ACCTID;
if (!vendorAccountId) {
throw new KError('Cannot find account id in OFX file.');
}
let accountType = accountsTypesMap[accountInfo.ACCTTYPE] || 'account-type.unknown';
let balance = parseFloat(account.AVAILBAL.BALAMT) || 0;
let accountTransactions = account.BANKTRANLIST.STMTTRN;
if (!(accountTransactions instanceof Array)) {
accountTransactions = [accountTransactions];
}
if (accountTransactions.length) {
transactions = transactions.concat(
accountTransactions
// eslint-disable-next-line no-loop-func
.map(transaction => {
let debitDate = transaction.DTPOSTED;
let realizationDate = transaction.DTUSER;
if (!realizationDate) {
realizationDate = debitDate;
}
return {
accountId,
date: moment(realizationDate).toISOString(),
debitDate: debitDate ? moment(debitDate).toISOString() : null,
rawLabel: transaction.NAME || transaction.MEMO,
label: transaction.MEMO || transaction.NAME,
amount: parseFloat(transaction.TRNAMT),
type:
transactionsTypesMap[transaction.TRNTYPE] ||
transactionsTypesMap.OTHER
};
})
.filter(transaction => !isNaN(transaction.amount))
);
accounts.push({
id: accountId,
vendorId: 'manual',
vendorAccountId,
accessId: 0,
type: accountType,
initialBalance: balance,
currency: currencyCode,
label: `OFX imported account - ${accountInfo.ACCTTYPE}`
});
}
++accountId;
}
return {
accesses: [
{
id: 0,
vendorId: 'manual',
login: ''
}
],
accounts,
operations: transactions
};
}
|
// Generated by CoffeeScript 1.10.0
(function() {
var app;
app = angular.module('myApp');
app.factory('postComment', function($http) {
return function(comment) {
return $http.post('http://localhost:3000/comment/save', comment);
};
});
app.factory('getComments', function($http) {
return function(id) {
return $http.post('http://localhost:3000/comment/all', {
id: id
});
};
});
app.factory('likeComment', function($http) {
return function(id) {
return $http.post('http://localhost:3000/comment/like', {
id: id
});
};
});
}).call(this);
//# sourceMappingURL=forComment.js.map
|
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = require('react');
var d3 = require('d3');
var Chart = require('./Chart');
var Axis = require('./Axis');
var HeightWidthMixin = require('./HeightWidthMixin');
// Adapted for React from https://github.com/mbostock/d3/blob/master/src/svg/brush.js
// TODO: Add D3 License
var _d3_svg_brushCursor = {
n: "ns-resize",
e: "ew-resize",
s: "ns-resize",
w: "ew-resize",
nw: "nwse-resize",
ne: "nesw-resize",
se: "nwse-resize",
sw: "nesw-resize"
};
var _d3_svg_brushResizes = [["n", "e", "s", "w", "nw", "ne", "se", "sw"], ["e", "w"], ["n", "s"], []];
// TODO: add y axis support
var Brush = React.createClass({
displayName: 'Brush',
mixins: [HeightWidthMixin],
getInitialState: function getInitialState() {
return {
resizers: _d3_svg_brushResizes[0],
xExtent: [0, 0],
yExtent: [0, 0],
xExtentDomain: undefined,
yExtentDomain: undefined
};
},
getDefaultProps: function getDefaultProps() {
return {
xScale: null,
yScale: null
};
},
componentWillMount: function componentWillMount() {
this._extent(this.props.extent);
this.setState({
resizers: _d3_svg_brushResizes[!this.props.xScale << 1 | !this.props.yScale]
});
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
// when <Brush/> is used inside a component
// we should not set the extent prop on every redraw of the parent, because it will
// stop us from actually setting the extent with the brush.
if (nextProps.xScale !== this.props.xScale) {
this._extent(nextProps.extent, nextProps.xScale);
this.setState({
resizers: _d3_svg_brushResizes[!this.props.xScale << 1 | !this.props.yScale]
});
}
},
render: function render() {
var _this = this;
// TODO: remove this.state this.props
var xRange = this.props.xScale ? this._d3_scaleRange(this.props.xScale) : null;
var yRange = this.props.yScale ? this._d3_scaleRange(this.props.yScale) : null;
var background = React.createElement('rect', {
className: 'background',
style: { visibility: 'visible', cursor: 'crosshair' },
x: xRange ? xRange[0] : "",
width: xRange ? xRange[1] - xRange[0] : "",
y: yRange ? yRange[0] : "",
height: yRange ? yRange[1] - yRange[0] : this._innerHeight,
onMouseDown: this._onMouseDownBackground
});
// TODO: it seems like actually we can have both x and y scales at the same time. need to find example.
var extent = undefined;
if (this.props.xScale) {
extent = React.createElement('rect', {
className: 'extent',
style: { cursor: 'move' },
x: this.state.xExtent[0],
width: this.state.xExtent[1] - this.state.xExtent[0],
height: this._innerHeight,
onMouseDown: this._onMouseDownExtent
});
}
var resizers = this.state.resizers.map(function (e) {
return React.createElement(
'g',
{
key: e,
className: 'resize ' + e,
style: { cursor: _d3_svg_brushCursor[e] },
transform: 'translate(' + _this.state.xExtent[+/e$/.test(e)] + ', ' + _this.state.yExtent[+/^s/.test(e)] + ')',
onMouseDown: function (event) {
_this._onMouseDownResizer(event, e);
}
},
React.createElement('rect', {
x: /[ew]$/.test(e) ? -3 : null,
y: /^[ns]/.test(e) ? -3 : null,
width: '6',
height: _this._innerHeight,
style: { visibility: 'hidden', display: _this._empty() ? "none" : null }
})
);
});
return React.createElement(
'div',
null,
React.createElement(
Chart,
{ height: this.props.height, width: this.props.width, margin: this.props.margin },
React.createElement(
'g',
{
style: { pointerEvents: 'all' },
onMouseUp: this._onMouseUp,
onMouseMove: this._onMouseMove
},
background,
extent,
resizers
),
React.createElement(Axis, _extends({
className: "x axis",
orientation: "bottom",
scale: this.props.xScale,
height: this._innerHeight,
width: this._innerWidth
}, this.props.xAxis))
)
);
},
// TODO: Code duplicated in TooltipMixin.jsx, move outside.
_getMousePosition: function _getMousePosition(e) {
var svg = this.getDOMNode().getElementsByTagName("svg")[0];
var position = undefined;
if (svg.createSVGPoint) {
var point = svg.createSVGPoint();
point.x = e.clientX, point.y = e.clientY;
point = point.matrixTransform(svg.getScreenCTM().inverse());
position = [point.x - this.props.margin.left, point.y - this.props.margin.top];
} else {
var rect = svg.getBoundingClientRect();
position = [e.clientX - rect.left - svg.clientLeft - this.props.margin.left, e.clientY - rect.top - svg.clientTop - this.props.margin.left];
}
return position;
},
_onMouseDownBackground: function _onMouseDownBackground(e) {
e.preventDefault();
var range = this._d3_scaleRange(this.props.xScale);
var point = this._getMousePosition(e);
var size = this.state.xExtent[1] - this.state.xExtent[0];
range[1] -= size;
var min = Math.max(range[0], Math.min(range[1], point[0]));
this.setState({ xExtent: [min, min + size] });
},
// TODO: use constants instead of strings
_onMouseDownExtent: function _onMouseDownExtent(e) {
e.preventDefault();
this._mouseMode = "drag";
var point = this._getMousePosition(e);
var distanceFromBorder = point[0] - this.state.xExtent[0];
this._startPosition = distanceFromBorder;
},
_onMouseDownResizer: function _onMouseDownResizer(e, dir) {
e.preventDefault();
this._mouseMode = "resize";
this._resizeDir = dir;
},
_onDrag: function _onDrag(e) {
var range = this._d3_scaleRange(this.props.xScale);
var point = this._getMousePosition(e);
var size = this.state.xExtent[1] - this.state.xExtent[0];
range[1] -= size;
var min = Math.max(range[0], Math.min(range[1], point[0] - this._startPosition));
this.setState({ xExtent: [min, min + size], xExtentDomain: null });
},
_onResize: function _onResize(e) {
var range = this._d3_scaleRange(this.props.xScale);
var point = this._getMousePosition(e);
// Don't let the extent go outside of its limits
// TODO: support clamp argument of D3
var min = Math.max(range[0], Math.min(range[1], point[0]));
if (this._resizeDir == "w") {
if (min > this.state.xExtent[1]) {
this.setState({ xExtent: [this.state.xExtent[1], min], xExtentDomain: null });
this._resizeDir = "e";
} else {
this.setState({ xExtent: [min, this.state.xExtent[1]], xExtentDomain: null });
}
} else if (this._resizeDir == "e") {
if (min < this.state.xExtent[0]) {
this.setState({ xExtent: [min, this.state.xExtent[0]], xExtentDomain: null });
this._resizeDir = "w";
} else {
this.setState({ xExtent: [this.state.xExtent[0], min], xExtentDomain: null });
}
}
},
_onMouseMove: function _onMouseMove(e) {
e.preventDefault();
if (this._mouseMode == "resize") {
this._onResize(e);
} else if (this._mouseMode == "drag") {
this._onDrag(e);
}
},
_onMouseUp: function _onMouseUp(e) {
e.preventDefault();
this._mouseMode = null;
this.props.onChange(this._extent());
},
_extent: function _extent(z, xScale) {
var x = xScale || this.props.xScale;
var y = this.props.yScale;
var _state = this.state;
var xExtent = _state.xExtent;
var yExtent = _state.yExtent;
var xExtentDomain = _state.xExtentDomain;
var yExtentDomain = _state.yExtentDomain;
var x0, x1, y0, y1, t;
// Invert the pixel extent to data-space.
if (!arguments.length) {
if (x) {
if (xExtentDomain) {
x0 = xExtentDomain[0], x1 = xExtentDomain[1];
} else {
x0 = xExtent[0], x1 = xExtent[1];
if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1);
if (x1 < x0) t = x0, x0 = x1, x1 = t;
}
}
if (y) {
if (yExtentDomain) {
y0 = yExtentDomain[0], y1 = yExtentDomain[1];
} else {
y0 = yExtent[0], y1 = yExtent[1];
if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1);
if (y1 < y0) t = y0, y0 = y1, y1 = t;
}
}
return x && y ? [[x0, y0], [x1, y1]] : x ? [x0, x1] : y && [y0, y1];
}
// Scale the data-space extent to pixels.
if (x) {
x0 = z[0], x1 = z[1];
if (y) x0 = x0[0], x1 = x1[0];
xExtentDomain = [x0, x1];
if (x.invert) x0 = x(x0), x1 = x(x1);
if (x1 < x0) t = x0, x0 = x1, x1 = t;
if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [x0, x1]; // copy-on-write
}
if (y) {
y0 = z[0], y1 = z[1];
if (x) y0 = y0[1], y1 = y1[1];
yExtentDomain = [y0, y1];
if (y.invert) y0 = y(y0), y1 = y(y1);
if (y1 < y0) t = y0, y0 = y1, y1 = t;
if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [y0, y1]; // copy-on-write
}
this.setState({ xExtent: xExtent, yExtent: yExtent, xExtentDomain: xExtentDomain, yExtentDomain: yExtentDomain });
},
_empty: function _empty() {
return !!this.props.xScale && this.state.xExtent[0] == this.state.xExtent[1] || !!this.props.yScale && this.state.yExtent[0] == this.state.yExtent[1];
},
// TODO: Code duplicated in Axis.jsx, move outside.
_d3_scaleExtent: function _d3_scaleExtent(domain) {
var start = domain[0],
stop = domain[domain.length - 1];
return start < stop ? [start, stop] : [stop, start];
},
_d3_scaleRange: function _d3_scaleRange(scale) {
return scale.rangeExtent ? scale.rangeExtent() : this._d3_scaleExtent(scale.range());
}
});
module.exports = Brush; |
// @flow weak
import keycode from 'keycode';
import contains from 'dom-helpers/query/contains';
import addEventListener from '../utils/addEventListener';
const FOCUS_KEYS = ['tab', 'enter', 'space', 'esc', 'up', 'down', 'left', 'right'];
const internal = {
listening: false,
focusKeyPressed: false,
};
function isFocusKey(event) {
return FOCUS_KEYS.indexOf(keycode(event)) !== -1;
}
export function detectKeyboardFocus(instance, element, cb, attempt = 1) {
instance.keyboardFocusTimeout = setTimeout(() => {
if (
focusKeyPressed() &&
(document.activeElement === element || contains(element, document.activeElement))
) {
cb();
} else if (attempt < 5) {
detectKeyboardFocus(instance, element, cb, attempt + 1);
}
}, 40);
}
export function listenForFocusKeys() {
if (!internal.listening) {
addEventListener(window, 'keyup', (event) => {
if (isFocusKey(event)) {
internal.focusKeyPressed = true;
}
});
internal.listening = true;
}
}
export function focusKeyPressed(pressed) {
if (typeof pressed !== 'undefined') {
internal.focusKeyPressed = Boolean(pressed);
}
return internal.focusKeyPressed;
}
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 16);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _graphics = __webpack_require__(3);
var _graphics2 = _interopRequireDefault(_graphics);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Shape = function (_Graphics) {
_inherits(Shape, _Graphics);
function Shape() {
_classCallCheck(this, Shape);
return _possibleConstructorReturn(this, (Shape.__proto__ || Object.getPrototypeOf(Shape)).apply(this, arguments));
}
_createClass(Shape, [{
key: 'draw',
// constructor() {
// super()
// }
value: function draw() {}
}, {
key: 'render',
value: function render(ctx) {
this.clear();
this.draw();
_get(Shape.prototype.__proto__ || Object.getPrototypeOf(Shape.prototype), 'render', this).call(this, ctx);
}
}]);
return Shape;
}(_graphics2.default);
exports.default = Shape;
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _displayObject = __webpack_require__(2);
var _displayObject2 = _interopRequireDefault(_displayObject);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Group = function (_DisplayObject) {
_inherits(Group, _DisplayObject);
function Group(data) {
_classCallCheck(this, Group);
var _this = _possibleConstructorReturn(this, (Group.__proto__ || Object.getPrototypeOf(Group)).call(this, data));
_this.children = [];
return _this;
}
_createClass(Group, [{
key: 'add',
value: function add(child) {
var len = arguments.length;
for (var i = 0; i < len; i++) {
this.children.push(arguments[i]);
arguments[i].parent = this;
}
}
}, {
key: 'addChildAt',
value: function addChildAt(child, index) {
var par = child.parent;
par && par.removeChildAt(par.children.indexOf(child));
child.parent = this;
this.children.splice(index, 0, child);
}
}, {
key: 'removeChildAt',
value: function removeChildAt(index) {
var child = this.children[index];
if (child) {
child.parent = null;
}
this.children.splice(index, 1);
}
}, {
key: 'replace',
value: function replace(current, pre) {
var index = pre.parent.children.indexOf(pre);
this.removeChildAt(index);
this.addChildAt(current, index);
}
}, {
key: 'remove',
value: function remove(child) {
var len = arguments.length;
var cLen = this.children.length;
for (var i = 0; i < len; i++) {
for (var j = 0; j < cLen; j++) {
if (child.id === this.children[j].id) {
child.parent = null;
this.children.splice(j, 1);
j--;
cLen--;
}
}
}
}
}, {
key: 'empty',
value: function empty() {
this.children.forEach(function (child) {
child.parent = null;
});
this.children.length = 0;
}
}, {
key: 'destroy',
value: function destroy() {
this.empty();
_get(Group.prototype.__proto__ || Object.getPrototypeOf(Group.prototype), 'destroy', this).call(this);
}
}]);
return Group;
}(_displayObject2.default);
exports.default = Group;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _matrix2d = __webpack_require__(22);
var _matrix2d2 = _interopRequireDefault(_matrix2d);
var _eventDispatcher = __webpack_require__(23);
var _eventDispatcher2 = _interopRequireDefault(_eventDispatcher);
var _uid = __webpack_require__(24);
var _uid2 = _interopRequireDefault(_uid);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var DisplayObject = function (_EventDispatcher) {
_inherits(DisplayObject, _EventDispatcher);
function DisplayObject() {
_classCallCheck(this, DisplayObject);
var _this = _possibleConstructorReturn(this, (DisplayObject.__proto__ || Object.getPrototypeOf(DisplayObject)).call(this));
_this.alpha = _this.complexAlpha = _this.scaleX = _this.scaleY = 1;
_this.x = _this.y = _this.rotation = _this.skewX = _this.skewY = _this.originX = _this.originY = 0;
_this.cursor = null;
_this.visible = true;
_this._matrix = new _matrix2d2.default();
_this._hitMatrix = new _matrix2d2.default();
_this.id = _uid2.default.get();
_this.clipGraphics = null;
_this.clipRuleNonzero = true;
_this.fixed = false;
return _this;
}
_createClass(DisplayObject, [{
key: 'isVisible',
value: function isVisible() {
return this.visible && this.alpha > 0 && this.scaleX !== 0 && this.scaleY !== 0;
}
}, {
key: 'initAABB',
value: function initAABB() {
if (this.width === undefined || this.height === undefined) {
return;
}
var x = void 0,
y = void 0,
width = this.width,
height = this.height,
mtx = this._matrix,
xA = width * mtx.a,
xB = width * mtx.b,
yC = height * mtx.c,
yD = height * mtx.d,
tx = mtx.tx,
ty = mtx.ty,
minX = tx,
maxX = tx,
minY = ty,
maxY = ty;
if ((x = xA + tx) < minX) {
minX = x;
} else if (x > maxX) {
maxX = x;
}
if ((x = xA + yC + tx) < minX) {
minX = x;
} else if (x > maxX) {
maxX = x;
}
if ((x = yC + tx) < minX) {
minX = x;
} else if (x > maxX) {
maxX = x;
}
if ((y = xB + ty) < minY) {
minY = y;
} else if (y > maxY) {
maxY = y;
}
if ((y = xB + yD + ty) < minY) {
minY = y;
} else if (y > maxY) {
maxY = y;
}
if ((y = yD + ty) < minY) {
minY = y;
} else if (y > maxY) {
maxY = y;
}
this.AABB = [minX, minY, maxX - minX, maxY - minY];
this.rectPoints = [{
x: tx,
y: ty
}, {
x: xA + tx,
y: xB + ty
}, {
x: xA + yC + tx,
y: xB + yD + ty
}, {
x: yC + tx,
y: yD + ty
}];
}
}, {
key: 'destroy',
value: function destroy() {
this.parent.remove(this);
}
}, {
key: 'hover',
value: function hover(over, out, move) {
this.on('mouseover', over);
this.on('mouseout', out);
move && this.on('mousemove', move);
}
// https://developer.mozilla.org/zh-CN/docs/Web/API/CanvasRenderingContext2D/clip
}, {
key: 'clip',
value: function clip(graphics, notClipRuleNonzero) {
this.clipGraphics = graphics;
this.clipRuleNonzero = !notClipRuleNonzero;
}
}, {
key: 'unclip',
value: function unclip() {
this.clipGraphics = null;
}
}, {
key: 'cache',
value: function cache(x, y, width, height, scale) {
this._cacheData = {
x: x || 0,
y: y || 0,
width: width || this.width,
height: height || this.height,
scale: scale || 1
};
if (!this.cacheCanvas) {
if (typeof wx !== 'undefined' && wx.createCanvas) {
this.cacheCanvas = wx.createCanvas();
} else {
this.cacheCanvas = document.createElement('canvas');
}
this.cacheCtx = this.cacheCanvas.getContext('2d');
}
this.cacheCanvas.width = this._cacheData.width * this._cacheData.scale;
this.cacheCanvas.height = this._cacheData.height * this._cacheData.scale;
this._readyToCache = true;
}
}, {
key: 'uncache',
value: function uncache() {
this.cacheCanvas = null;
}
}, {
key: 'filter',
value: function filter(filterName, filterBox) {
this.cache(filterBox.x || 0, filterBox.y || 0, filterBox.width || this.width, filterBox.height || this.height);
this._readyToFilter = true;
this._filterName = filterName;
}
}, {
key: 'unfilter',
value: function unfilter() {
this.uncache();
}
}]);
return DisplayObject;
}(_eventDispatcher2.default);
exports.default = DisplayObject;
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _displayObject = __webpack_require__(2);
var _displayObject2 = _interopRequireDefault(_displayObject);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var assMap = {
fillStyle: true,
strokeStyle: true,
lineWidth: true,
lineCap: true,
lineDashOffset: true,
lineJoin: true,
miterLimit: true
};
var Graphics = function (_DisplayObject) {
_inherits(Graphics, _DisplayObject);
function Graphics() {
_classCallCheck(this, Graphics);
var _this = _possibleConstructorReturn(this, (Graphics.__proto__ || Object.getPrototypeOf(Graphics)).call(this));
_this.cmds = [];
_this.currentGradient = null;
return _this;
}
_createClass(Graphics, [{
key: 'clearRect',
value: function clearRect() {
this.cmds.push(['clearRect', arguments]);
return this;
}
}, {
key: 'rect',
value: function rect() {
this.cmds.push(['rect', arguments]);
return this;
}
}, {
key: 'clear',
value: function clear() {
this.cmds.length = 0;
return this;
}
}, {
key: 'setLineDash',
value: function setLineDash() {
this.cmds.push(['setLineDash', arguments]);
return this;
}
}, {
key: 'strokeRect',
value: function strokeRect() {
this.cmds.push(['strokeRect', arguments]);
return this;
}
}, {
key: 'fillRect',
value: function fillRect() {
this.cmds.push(['fillRect', arguments]);
return this;
}
}, {
key: 'beginPath',
value: function beginPath() {
this.cmds.push(['beginPath', arguments]);
return this;
}
}, {
key: 'arc',
value: function arc() {
this.cmds.push(['arc', arguments]);
return this;
}
}, {
key: 'closePath',
value: function closePath() {
this.cmds.push(['closePath', arguments]);
return this;
}
}, {
key: 'fillStyle',
value: function fillStyle() {
this.cmds.push(['fillStyle', arguments]);
return this;
}
}, {
key: 'fill',
value: function fill() {
this.cmds.push(['fill', arguments]);
return this;
}
}, {
key: 'strokeStyle',
value: function strokeStyle() {
this.cmds.push(['strokeStyle', arguments]);
return this;
}
}, {
key: 'lineWidth',
value: function lineWidth() {
this.cmds.push(['lineWidth', arguments]);
return this;
}
}, {
key: 'lineCap',
value: function lineCap() {
this.cmds.push(['lineCap', arguments]);
return this;
}
}, {
key: 'lineDashOffset',
value: function lineDashOffset() {
this.cmds.push(['lineDashOffset', arguments]);
return this;
}
}, {
key: 'lineJoin',
value: function lineJoin() {
this.cmds.push(['lineJoin', arguments]);
return this;
}
}, {
key: 'miterLimit',
value: function miterLimit() {
this.cmds.push(['miterLimit', arguments]);
return this;
}
}, {
key: 'stroke',
value: function stroke() {
this.cmds.push(['stroke', arguments]);
return this;
}
}, {
key: 'moveTo',
value: function moveTo() {
this.cmds.push(['moveTo', arguments]);
return this;
}
}, {
key: 'lineTo',
value: function lineTo() {
this.cmds.push(['lineTo', arguments]);
return this;
}
}, {
key: 'bezierCurveTo',
value: function bezierCurveTo() {
this.cmds.push(['bezierCurveTo', arguments]);
return this;
}
}, {
key: 'quadraticCurveTo',
value: function quadraticCurveTo() {
this.cmds.push(['quadraticCurveTo', arguments]);
return this;
}
}, {
key: 'createRadialGradient',
value: function createRadialGradient() {
this.cmds.push(['createRadialGradient', arguments]);
return this;
}
}, {
key: 'createLinearGradient',
value: function createLinearGradient() {
this.cmds.push(['createLinearGradient', arguments]);
return this;
}
}, {
key: 'addColorStop',
value: function addColorStop() {
this.cmds.push(['addColorStop', arguments]);
return this;
}
}, {
key: 'fillGradient',
value: function fillGradient() {
this.cmds.push(['fillGradient']);
return this;
}
}, {
key: 'arcTo',
value: function arcTo() {
this.cmds.push(['arcTo', arguments]);
return this;
}
}, {
key: 'render',
value: function render(ctx) {
var _this2 = this;
this.cmds.forEach(function (cmd) {
var methodName = cmd[0];
if (assMap[methodName]) {
ctx[methodName] = cmd[1][0];
} else if (methodName === 'addColorStop') {
_this2.currentGradient && _this2.currentGradient.addColorStop(cmd[1][0], cmd[1][1]);
} else if (methodName === 'fillGradient') {
ctx.fillStyle = _this2.currentGradient;
} else {
var result = ctx[methodName].apply(ctx, Array.prototype.slice.call(cmd[1]));
if (methodName === 'createRadialGradient' || methodName === 'createLinearGradient') {
_this2.currentGradient = result;
}
}
});
}
}]);
return Graphics;
}(_displayObject2.default);
exports.default = Graphics;
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _displayObject = __webpack_require__(2);
var _displayObject2 = _interopRequireDefault(_displayObject);
var _util = __webpack_require__(9);
var _util2 = _interopRequireDefault(_util);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Bitmap = function (_DisplayObject) {
_inherits(Bitmap, _DisplayObject);
function Bitmap(img, onLoad) {
_classCallCheck(this, Bitmap);
var _this = _possibleConstructorReturn(this, (Bitmap.__proto__ || Object.getPrototypeOf(Bitmap)).call(this));
if (typeof img === 'string') {
if (Bitmap.cache[img]) {
if (_util2.default.isWeapp) {
_this.img = Bitmap.cache[img].img;
_this.rect = [0, 0, Bitmap.cache[img].width, Bitmap.cache[img].height];
_this.width = _this.rect[2];
_this.height = _this.rect[3];
} else {
_this.img = Bitmap.cache[img];
_this.rect = [0, 0, _this.img.width, _this.img.height];
_this.width = _this.img.width;
_this.height = _this.img.height;
}
onLoad && onLoad.call(_this);
} else if (_util2.default.isWeapp) {
_util2.default.getImageInWx(img, function (result) {
_this.img = result.img;
if (!_this.rect) {
_this.rect = [0, 0, result.width, result.height];
}
_this.width = result.width;
_this.height = result.height;
onLoad && onLoad.call(_this);
Bitmap.cache[img] = result;
});
} else {
_this.img = _util2.default.isWegame ? wx.createImage() : new window.Image();
_this.visible = false;
_this.img.onload = function () {
_this.visible = true;
if (!_this.rect) {
_this.rect = [0, 0, _this.img.width, _this.img.height];
}
_this.width = _this.img.width;
_this.height = _this.img.height;
onLoad && onLoad.call(_this);
Bitmap.cache[img] = _this.img;
};
_this.img.src = img;
}
} else {
_this.img = img;
_this.rect = [0, 0, img.width, img.height];
_this.width = img.width;
_this.height = img.height;
Bitmap.cache[img.src] = img;
}
return _this;
}
_createClass(Bitmap, [{
key: 'clone',
value: function clone() {
var bitmap = new Bitmap(this.img);
bitmap.x = this.x;
bitmap.y = this.y;
bitmap.scaleX = this.scaleX;
bitmap.scaleY = this.scaleY;
bitmap.rotation = this.rotation;
bitmap.skewX = this.skewX;
bitmap.skewY = this.skewY;
bitmap.originX = this.originX;
bitmap.originY = this.originY;
bitmap.width = this.width;
bitmap.height = this.height;
return bitmap;
}
}]);
return Bitmap;
}(_displayObject2.default);
Bitmap.cache = {};
exports.default = Bitmap;
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _displayObject = __webpack_require__(2);
var _displayObject2 = _interopRequireDefault(_displayObject);
var _util = __webpack_require__(9);
var _util2 = _interopRequireDefault(_util);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var measureCtx = void 0;
if (_util2.default.isWeapp) {
measureCtx = wx.createCanvasContext('measure0');
} else if (typeof document !== 'undefined') {
measureCtx = document.createElement('canvas').getContext('2d');
}
var Text = function (_DisplayObject) {
_inherits(Text, _DisplayObject);
function Text(text, option) {
_classCallCheck(this, Text);
var _this = _possibleConstructorReturn(this, (Text.__proto__ || Object.getPrototypeOf(Text)).call(this));
_this.text = text;
option = option || {};
_this.font = option.font || '10px sans-serif';
_this.color = option.color || 'black';
_this.baseline = option.baseline || 'top';
return _this;
}
_createClass(Text, [{
key: 'getWidth',
value: function getWidth() {
if (!measureCtx) {
if (_util2.default.isWegame) {
measureCtx = wx.createCanvas().getContext('2d');
}
}
if (this.font) {
measureCtx.font = this.font;
}
return measureCtx.measureText(this.text).width;
}
}]);
return Text;
}(_displayObject2.default);
exports.default = Text;
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _displayObject = __webpack_require__(2);
var _displayObject2 = _interopRequireDefault(_displayObject);
var _util = __webpack_require__(9);
var _util2 = _interopRequireDefault(_util);
var _bitmap = __webpack_require__(4);
var _bitmap2 = _interopRequireDefault(_bitmap);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Sprite = function (_DisplayObject) {
_inherits(Sprite, _DisplayObject);
function Sprite(option) {
_classCallCheck(this, Sprite);
var _this = _possibleConstructorReturn(this, (Sprite.__proto__ || Object.getPrototypeOf(Sprite)).call(this));
_this.option = option;
var len = _this.option.imgs.length;
var count = 0;
var firstImg = _this.option.imgs[0];
_this.imgMap = {};
if (_util2.default.isWeapp) {
_this.option.imgs.forEach(function (img) {
_util2.default.getImageInWx(img, function (result) {
_this.imgMap[img] = result.img;
count++;
if (count === len) {
_this.img = _this.imgMap[firstImg];
_this.rect = [0, 0, 0, 0];
}
});
});
} else {
if (typeof firstImg === 'string') {
var _len = _this.option.imgs.length;
var loadedCount = 0;
_this.option.imgs.forEach(function (src) {
if (_bitmap2.default.cache[src]) {
_this.imgMap[src] = _bitmap2.default.cache[src];
loadedCount++;
if (loadedCount === _len) {
_this.img = _this.imgMap[firstImg];
_this.rect = [0, 0, 0, 0];
}
} else {
var img = _util2.default.isWegame ? wx.createImage() : new window.Image();
img.onload = function () {
_this.imgMap[src] = img;
loadedCount++;
if (loadedCount === _len) {
_this.img = _this.imgMap[firstImg];
_this.rect = [0, 0, 0, 0];
}
_bitmap2.default.cache[src] = img;
};
img.src = src;
}
});
} else if (firstImg instanceof _bitmap2.default) {
_this.rect = [0, 0, 0, 0];
_this.img = firstImg.img;
} else {
_this.rect = [0, 0, 0, 0];
_this.img = firstImg;
}
}
_this.x = option.x || 0;
_this.y = option.y || 0;
_this.currentFrameIndex = 0;
_this.animationFrameIndex = 0;
_this.currentAnimation = option.currentAnimation || null;
_this.interval = 1e3 / option.framerate;
_this.paused = false;
_this.animationEnd = option.animationEnd || function () {};
if (_this.currentAnimation) {
if (option.playOnce) {
_this.gotoAndPlayOnce(_this.currentAnimation);
} else {
_this.gotoAndPlay(_this.currentAnimation);
}
}
return _this;
}
_createClass(Sprite, [{
key: 'play',
value: function play() {
this.paused = false;
}
}, {
key: 'pause',
value: function pause() {
this.paused = true;
}
}, {
key: 'reset',
value: function reset() {
this.currentFrameIndex = 0;
this.animationFrameIndex = 0;
}
}, {
key: 'updateFrame',
value: function updateFrame() {
if (!this.paused) {
var opt = this.option;
this.dt = Date.now() - this.startTime;
var frames = opt.animations[this.currentAnimation].frames;
var len = frames.length;
var index = Math.floor(this.dt / this.interval % len);
this.rect = opt.frames[frames[index]];
var rectLen = this.rect.length;
rectLen > 4 && (this.originX = this.rect[2] * this.rect[4]);
rectLen > 5 && (this.originY = this.rect[3] * this.rect[5]);
rectLen > 6 && (this.img = this.imgMap[this.option.imgs[this.rect[6]]]);
if (index === len - 1 && (!this.endTime || Date.now() - this.endTime > this.interval)) {
this.endTime = Date.now();
this.animationEnd();
if (this._willDestroy) {
this.destroy();
}
}
}
}
}, {
key: 'gotoAndPlay',
value: function gotoAndPlay(animation) {
this.paused = false;
this.reset();
this.currentAnimation = animation;
this.startTime = Date.now();
}
}, {
key: 'gotoAndStop',
value: function gotoAndStop(animation) {
this.reset();
this.paused = true;
this.currentAnimation = animation;
var opt = this.option;
var frames = opt.animations[this.currentAnimation].frames;
this.rect = opt.frames[frames[this.animationFrameIndex]];
var rect = this.rect;
this.width = rect[2];
this.height = rect[3];
var rectLen = rect.length;
rectLen > 4 && (this.originX = rect[2] * rect[4]);
rectLen > 5 && (this.originY = rect[3] * rect[5]);
rectLen > 6 && (this.img = this.imgMap[this.option.imgs[rect[6]]]);
}
}, {
key: 'gotoAndPlayOnce',
value: function gotoAndPlayOnce(animation) {
this.gotoAndPlay(animation);
this._willDestroy = true;
}
}]);
return Sprite;
}(_displayObject2.default);
exports.default = Sprite;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Event = function () {
function Event() {
_classCallCheck(this, Event);
this.propagationStopped = false;
this.stageX = null;
this.stageY = null;
this.pureEvent = null;
}
_createClass(Event, [{
key: "stopPropagation",
value: function stopPropagation() {
this.propagationStopped = true;
}
}, {
key: "preventDefault",
value: function preventDefault() {
this.pureEvent.preventDefault();
}
}]);
return Event;
}();
exports.default = Event;
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Render = function () {
function Render() {
_classCallCheck(this, Render);
}
_createClass(Render, [{
key: "render",
value: function render() {}
}, {
key: "renderGraphics",
value: function renderGraphics() {}
}, {
key: "clear",
value: function clear() {}
}]);
return Render;
}();
exports.default = Render;
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.getImageInWx = getImageInWx;
function getImageInWx(img, callback) {
if (img.indexOf('https://') === -1 && img.indexOf('http://') === -1) {
wx.getImageInfo({
src: img,
success: function success(info) {
callback({
img: img,
width: info.width,
height: info.height
});
}
});
} else {
wx.downloadFile({
url: img,
success: function success(res) {
if (res.statusCode === 200) {
wx.getImageInfo({
src: res.tempFilePath,
success: function success(info) {
callback({
img: res.tempFilePath,
width: info.width,
height: info.height
});
}
});
}
}
});
}
}
function getGlobal() {
if ((typeof global === 'undefined' ? 'undefined' : _typeof(global)) !== 'object' || !global || global.Math !== Math || global.Array !== Array) {
if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else if (typeof global !== 'undefined') {
return global;
}
return function () {
return this;
}();
}
return global;
}
var root = getGlobal();
exports.default = {
getImageInWx: getImageInWx,
root: root,
isWeapp: typeof wx !== 'undefined' && !wx.createCanvas,
isWegame: typeof wx !== 'undefined' && wx.createCanvas
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(26)))
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process) {
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
/**
* Tween.js - Licensed under the MIT license
* https://github.com/tweenjs/tween.js
* ----------------------------------------------
*
* See https://github.com/tweenjs/tween.js/graphs/contributors for the full list of contributors.
* Thank you all, you're awesome!
*/
var _Group = function _Group() {
this._tweens = {};
this._tweensAddedDuringUpdate = {};
};
_Group.prototype = {
getAll: function getAll() {
return Object.keys(this._tweens).map(function (tweenId) {
return this._tweens[tweenId];
}.bind(this));
},
removeAll: function removeAll() {
this._tweens = {};
},
add: function add(tween) {
this._tweens[tween.getId()] = tween;
this._tweensAddedDuringUpdate[tween.getId()] = tween;
},
remove: function remove(tween) {
delete this._tweens[tween.getId()];
delete this._tweensAddedDuringUpdate[tween.getId()];
},
update: function update(time, preserve) {
var tweenIds = Object.keys(this._tweens);
if (tweenIds.length === 0) {
return false;
}
time = time !== undefined ? time : TWEEN.now();
// Tweens are updated in "batches". If you add a new tween during an update, then the
// new tween will be updated in the next batch.
// If you remove a tween during an update, it may or may not be updated. However,
// if the removed tween was added during the current batch, then it will not be updated.
while (tweenIds.length > 0) {
this._tweensAddedDuringUpdate = {};
for (var i = 0; i < tweenIds.length; i++) {
var tween = this._tweens[tweenIds[i]];
if (tween && tween.update(time) === false) {
tween._isPlaying = false;
if (!preserve) {
delete this._tweens[tweenIds[i]];
}
}
}
tweenIds = Object.keys(this._tweensAddedDuringUpdate);
}
return true;
}
};
var TWEEN = new _Group();
TWEEN.Group = _Group;
TWEEN._nextId = 0;
TWEEN.nextId = function () {
return TWEEN._nextId++;
};
// Include a performance.now polyfill.
// In node.js, use process.hrtime.
if (typeof window === 'undefined' && typeof process !== 'undefined') {
if (typeof wx !== 'undefined') {
TWEEN.now = Date.now;
} else {
TWEEN.now = function () {
var time = process.hrtime();
// Convert [seconds, nanoseconds] to milliseconds.
return time[0] * 1000 + time[1] / 1000000;
};
}
} else if (typeof window !== 'undefined' &&
// In a browser, use window.performance.now if it is available.
window.performance !== undefined && window.performance.now !== undefined) {
// This must be bound, because directly assigning this function
// leads to an invocation exception in Chrome.
TWEEN.now = window.performance.now.bind(window.performance);
} else if (Date.now !== undefined) {
// Use Date.now if it is available.
TWEEN.now = Date.now;
} else {
// Otherwise, use 'new Date().getTime()'.
TWEEN.now = function () {
return new Date().getTime();
};
}
TWEEN.Tween = function (object, group) {
this._object = object;
this._valuesStart = {};
this._valuesEnd = {};
this._valuesStartRepeat = {};
this._duration = 1000;
this._repeat = 0;
this._repeatDelayTime = undefined;
this._yoyo = false;
this._isPlaying = false;
this._reversed = false;
this._delayTime = 0;
this._startTime = null;
this._easingFunction = TWEEN.Easing.Linear.None;
this._interpolationFunction = TWEEN.Interpolation.Linear;
this._chainedTweens = [];
this._onStartCallback = null;
this._onStartCallbackFired = false;
this._onUpdateCallback = null;
this._onCompleteCallback = null;
this._onStopCallback = null;
this._group = group || TWEEN;
this._id = TWEEN.nextId();
this._paused = false;
this._passTime = null;
};
TWEEN.Tween.prototype = {
getId: function getId() {
return this._id;
},
toggle: function toggle() {
if (this._paused) {
this.play();
} else {
this.pause();
}
},
pause: function pause() {
this._paused = true;
var pauseTime = TWEEN.now();
this._passTime = pauseTime - this._startTime;
},
play: function play() {
this._paused = false;
var nowTime = TWEEN.now();
this._startTime = nowTime - this._passTime;
},
isPlaying: function isPlaying() {
return this._isPlaying;
},
to: function to(properties, duration) {
this._valuesEnd = properties;
if (duration !== undefined) {
this._duration = duration;
}
return this;
},
start: function start(time) {
this._group.add(this);
this._isPlaying = true;
this._onStartCallbackFired = false;
this._startTime = time !== undefined ? typeof time === 'string' ? TWEEN.now() + parseFloat(time) : time : TWEEN.now();
this._startTime += this._delayTime;
for (var property in this._valuesEnd) {
// Check if an Array was provided as property value
if (this._valuesEnd[property] instanceof Array) {
if (this._valuesEnd[property].length === 0) {
continue;
}
// Create a local copy of the Array with the start value at the front
this._valuesEnd[property] = [this._object[property]].concat(this._valuesEnd[property]);
}
// If `to()` specifies a property that doesn't exist in the source object,
// we should not set that property in the object
if (this._object[property] === undefined) {
continue;
}
// Save the starting value.
this._valuesStart[property] = this._object[property];
if (this._valuesStart[property] instanceof Array === false) {
this._valuesStart[property] *= 1.0; // Ensures we're using numbers, not strings
}
this._valuesStartRepeat[property] = this._valuesStart[property] || 0;
}
return this;
},
stop: function stop() {
if (!this._isPlaying) {
return this;
}
this._group.remove(this);
this._isPlaying = false;
if (this._onStopCallback !== null) {
this._onStopCallback(this._object);
}
this.stopChainedTweens();
return this;
},
end: function end() {
this.update(this._startTime + this._duration);
return this;
},
stopChainedTweens: function stopChainedTweens() {
for (var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i++) {
this._chainedTweens[i].stop();
}
},
group: function group(group) {
this._group = group;
return this;
},
delay: function delay(amount) {
this._delayTime = amount;
return this;
},
repeat: function repeat(times) {
this._repeat = times;
return this;
},
repeatDelay: function repeatDelay(amount) {
this._repeatDelayTime = amount;
return this;
},
yoyo: function yoyo(yy) {
this._yoyo = yy;
return this;
},
easing: function easing(eas) {
this._easingFunction = eas;
return this;
},
interpolation: function interpolation(inter) {
this._interpolationFunction = inter;
return this;
},
chain: function chain() {
this._chainedTweens = arguments;
return this;
},
onStart: function onStart(callback) {
this._onStartCallback = callback;
return this;
},
onUpdate: function onUpdate(callback) {
this._onUpdateCallback = callback;
return this;
},
onComplete: function onComplete(callback) {
this._onCompleteCallback = callback;
return this;
},
onStop: function onStop(callback) {
this._onStopCallback = callback;
return this;
},
update: function update(time) {
if (this._paused) return true;
var property;
var elapsed;
var value;
if (time < this._startTime) {
return true;
}
if (this._onStartCallbackFired === false) {
if (this._onStartCallback !== null) {
this._onStartCallback(this._object);
}
this._onStartCallbackFired = true;
}
elapsed = (time - this._startTime) / this._duration;
elapsed = this._duration === 0 || elapsed > 1 ? 1 : elapsed;
value = this._easingFunction(elapsed);
for (property in this._valuesEnd) {
// Don't update properties that do not exist in the source object
if (this._valuesStart[property] === undefined) {
continue;
}
var start = this._valuesStart[property] || 0;
var end = this._valuesEnd[property];
if (end instanceof Array) {
this._object[property] = this._interpolationFunction(end, value);
} else {
// Parses relative end values with start as base (e.g.: +10, -3)
if (typeof end === 'string') {
if (end.charAt(0) === '+' || end.charAt(0) === '-') {
end = start + parseFloat(end);
} else {
end = parseFloat(end);
}
}
// Protect against non numeric properties.
if (typeof end === 'number') {
this._object[property] = start + (end - start) * value;
}
}
}
if (this._onUpdateCallback !== null) {
this._onUpdateCallback(this._object);
}
if (elapsed === 1) {
if (this._repeat > 0) {
if (isFinite(this._repeat)) {
this._repeat--;
}
// Reassign starting values, restart by making startTime = now
for (property in this._valuesStartRepeat) {
if (typeof this._valuesEnd[property] === 'string') {
this._valuesStartRepeat[property] = this._valuesStartRepeat[property] + parseFloat(this._valuesEnd[property]);
}
if (this._yoyo) {
var tmp = this._valuesStartRepeat[property];
this._valuesStartRepeat[property] = this._valuesEnd[property];
this._valuesEnd[property] = tmp;
}
this._valuesStart[property] = this._valuesStartRepeat[property];
}
if (this._yoyo) {
this._reversed = !this._reversed;
}
if (this._repeatDelayTime !== undefined) {
this._startTime = time + this._repeatDelayTime;
} else {
this._startTime = time + this._delayTime;
}
return true;
} else {
if (this._onCompleteCallback !== null) {
this._onCompleteCallback(this._object);
}
for (var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i++) {
// Make the chained tweens start exactly at the time they should,
// even if the `update()` method was called way past the duration of the tween
this._chainedTweens[i].start(this._startTime + this._duration);
}
return false;
}
}
return true;
}
};
TWEEN.Easing = {
Linear: {
None: function None(k) {
return k;
}
},
Quadratic: {
In: function In(k) {
return k * k;
},
Out: function Out(k) {
return k * (2 - k);
},
InOut: function InOut(k) {
if ((k *= 2) < 1) {
return 0.5 * k * k;
}
return -0.5 * (--k * (k - 2) - 1);
}
},
Cubic: {
In: function In(k) {
return k * k * k;
},
Out: function Out(k) {
return --k * k * k + 1;
},
InOut: function InOut(k) {
if ((k *= 2) < 1) {
return 0.5 * k * k * k;
}
return 0.5 * ((k -= 2) * k * k + 2);
}
},
Quartic: {
In: function In(k) {
return k * k * k * k;
},
Out: function Out(k) {
return 1 - --k * k * k * k;
},
InOut: function InOut(k) {
if ((k *= 2) < 1) {
return 0.5 * k * k * k * k;
}
return -0.5 * ((k -= 2) * k * k * k - 2);
}
},
Quintic: {
In: function In(k) {
return k * k * k * k * k;
},
Out: function Out(k) {
return --k * k * k * k * k + 1;
},
InOut: function InOut(k) {
if ((k *= 2) < 1) {
return 0.5 * k * k * k * k * k;
}
return 0.5 * ((k -= 2) * k * k * k * k + 2);
}
},
Sinusoidal: {
In: function In(k) {
return 1 - Math.cos(k * Math.PI / 2);
},
Out: function Out(k) {
return Math.sin(k * Math.PI / 2);
},
InOut: function InOut(k) {
return 0.5 * (1 - Math.cos(Math.PI * k));
}
},
Exponential: {
In: function In(k) {
return k === 0 ? 0 : Math.pow(1024, k - 1);
},
Out: function Out(k) {
return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
},
InOut: function InOut(k) {
if (k === 0) {
return 0;
}
if (k === 1) {
return 1;
}
if ((k *= 2) < 1) {
return 0.5 * Math.pow(1024, k - 1);
}
return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
}
},
Circular: {
In: function In(k) {
return 1 - Math.sqrt(1 - k * k);
},
Out: function Out(k) {
return Math.sqrt(1 - --k * k);
},
InOut: function InOut(k) {
if ((k *= 2) < 1) {
return -0.5 * (Math.sqrt(1 - k * k) - 1);
}
return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
}
},
Elastic: {
In: function In(k) {
if (k === 0) {
return 0;
}
if (k === 1) {
return 1;
}
return -Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI);
},
Out: function Out(k) {
if (k === 0) {
return 0;
}
if (k === 1) {
return 1;
}
return Math.pow(2, -10 * k) * Math.sin((k - 0.1) * 5 * Math.PI) + 1;
},
InOut: function InOut(k) {
if (k === 0) {
return 0;
}
if (k === 1) {
return 1;
}
k *= 2;
if (k < 1) {
return -0.5 * Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI);
}
return 0.5 * Math.pow(2, -10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI) + 1;
}
},
Back: {
In: function In(k) {
var s = 1.70158;
return k * k * ((s + 1) * k - s);
},
Out: function Out(k) {
var s = 1.70158;
return --k * k * ((s + 1) * k + s) + 1;
},
InOut: function InOut(k) {
var s = 1.70158 * 1.525;
if ((k *= 2) < 1) {
return 0.5 * (k * k * ((s + 1) * k - s));
}
return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
}
},
Bounce: {
In: function In(k) {
return 1 - TWEEN.Easing.Bounce.Out(1 - k);
},
Out: function Out(k) {
if (k < 1 / 2.75) {
return 7.5625 * k * k;
} else if (k < 2 / 2.75) {
return 7.5625 * (k -= 1.5 / 2.75) * k + 0.75;
} else if (k < 2.5 / 2.75) {
return 7.5625 * (k -= 2.25 / 2.75) * k + 0.9375;
} else {
return 7.5625 * (k -= 2.625 / 2.75) * k + 0.984375;
}
},
InOut: function InOut(k) {
if (k < 0.5) {
return TWEEN.Easing.Bounce.In(k * 2) * 0.5;
}
return TWEEN.Easing.Bounce.Out(k * 2 - 1) * 0.5 + 0.5;
}
}
};
TWEEN.Interpolation = {
Linear: function Linear(v, k) {
var m = v.length - 1;
var f = m * k;
var i = Math.floor(f);
var fn = TWEEN.Interpolation.Utils.Linear;
if (k < 0) {
return fn(v[0], v[1], f);
}
if (k > 1) {
return fn(v[m], v[m - 1], m - f);
}
return fn(v[i], v[i + 1 > m ? m : i + 1], f - i);
},
Bezier: function Bezier(v, k) {
var b = 0;
var n = v.length - 1;
var pw = Math.pow;
var bn = TWEEN.Interpolation.Utils.Bernstein;
for (var i = 0; i <= n; i++) {
b += pw(1 - k, n - i) * pw(k, i) * v[i] * bn(n, i);
}
return b;
},
CatmullRom: function CatmullRom(v, k) {
var m = v.length - 1;
var f = m * k;
var i = Math.floor(f);
var fn = TWEEN.Interpolation.Utils.CatmullRom;
if (v[0] === v[m]) {
if (k < 0) {
i = Math.floor(f = m * (1 + k));
}
return fn(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i);
} else {
if (k < 0) {
return v[0] - (fn(v[0], v[0], v[1], v[1], -f) - v[0]);
}
if (k > 1) {
return v[m] - (fn(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m]);
}
return fn(v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i);
}
},
Utils: {
Linear: function Linear(p0, p1, t) {
return (p1 - p0) * t + p0;
},
Bernstein: function Bernstein(n, i) {
var fc = TWEEN.Interpolation.Utils.Factorial;
return fc(n) / fc(i) / fc(n - i);
},
Factorial: function () {
var a = [1];
return function (n) {
var s = 1;
if (a[n]) {
return a[n];
}
for (var i = n; i > 1; i--) {
s *= i;
}
a[n] = s;
return s;
};
}(),
CatmullRom: function CatmullRom(p0, p1, p2, p3, t) {
var v0 = (p2 - p0) * 0.5;
var v1 = (p3 - p1) * 0.5;
var t2 = t * t;
var t3 = t * t2;
return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
}
}
};
// UMD (Universal Module Definition)
(function (root) {
if (typeof module !== 'undefined' && ( false ? 'undefined' : _typeof(exports)) === 'object') {
// Node.js
module.exports = TWEEN;
} else if (root !== undefined) {
// Global variable
root.TWEEN = TWEEN;
}
})(undefined);
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18)))
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _tween = __webpack_require__(10);
var _tween2 = _interopRequireDefault(_tween);
var _rafInterval = __webpack_require__(12);
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 To = function () {
function To(element) {
_classCallCheck(this, To);
this.element = element;
this.cmds = [];
this.index = 0;
this.tweens = [];
this._pause = false;
this.loop = (0, _rafInterval.setRafInterval)(function () {
_tween2.default.update();
}, 15);
this.cycleCount = 0;
}
_createClass(To, [{
key: 'to',
value: function to(target, duration, easing) {
this.cmds.push(['to']);
if (arguments.length !== 0) {
for (var key in target) {
this.set(key, target[key], duration, easing);
}
}
return this;
}
}, {
key: 'set',
value: function set(prop, value, duration, easing) {
this.cmds[this.cmds.length - 1].push([prop, [value, duration, easing]]);
return this;
}
}, {
key: 'x',
value: function x() {
this.cmds[this.cmds.length - 1].push(['x', arguments]);
return this;
}
}, {
key: 'y',
value: function y() {
this.cmds[this.cmds.length - 1].push(['y', arguments]);
return this;
}
}, {
key: 'z',
value: function z() {
this.cmds[this.cmds.length - 1].push(['z', arguments]);
return this;
}
}, {
key: 'rotation',
value: function rotation() {
this.cmds[this.cmds.length - 1].push(['rotation', arguments]);
return this;
}
}, {
key: 'scaleX',
value: function scaleX() {
this.cmds[this.cmds.length - 1].push(['scaleX', arguments]);
return this;
}
}, {
key: 'scaleY',
value: function scaleY() {
this.cmds[this.cmds.length - 1].push(['scaleY', arguments]);
return this;
}
}, {
key: 'skewX',
value: function skewX() {
this.cmds[this.cmds.length - 1].push(['skewX', arguments]);
return this;
}
}, {
key: 'skewY',
value: function skewY() {
this.cmds[this.cmds.length - 1].push(['skewY', arguments]);
return this;
}
}, {
key: 'originX',
value: function originX() {
this.cmds[this.cmds.length - 1].push(['originX', arguments]);
return this;
}
}, {
key: 'originY',
value: function originY() {
this.cmds[this.cmds.length - 1].push(['originY', arguments]);
return this;
}
}, {
key: 'alpha',
value: function alpha() {
this.cmds[this.cmds.length - 1].push(['alpha', arguments]);
return this;
}
}, {
key: 'begin',
value: function begin(fn) {
this.cmds[this.cmds.length - 1].begin = fn;
return this;
}
}, {
key: 'progress',
value: function progress(fn) {
this.cmds[this.cmds.length - 1].progress = fn;
return this;
}
}, {
key: 'end',
value: function end(fn) {
this.cmds[this.cmds.length - 1].end = fn;
return this;
}
}, {
key: 'wait',
value: function wait() {
this.cmds.push(['wait', arguments]);
return this;
}
}, {
key: 'then',
value: function then() {
this.cmds.push(['then', arguments]);
return this;
}
}, {
key: 'cycle',
value: function cycle() {
this.cmds.push(['cycle', arguments]);
return this;
}
}, {
key: 'start',
value: function start() {
if (this._pause) return;
var len = this.cmds.length;
if (this.index < len) {
this.exec(this.cmds[this.index], this.index === len - 1);
} else {
(0, _rafInterval.clearRafInterval)(this.loop);
}
return this;
}
}, {
key: 'pause',
value: function pause() {
this._pause = true;
for (var i = 0, len = this.tweens.length; i < len; i++) {
this.tweens[i].pause();
}
if (this.currentTask === 'wait') {
this.timeout -= new Date() - this.currentTaskBegin;
this.currentTaskBegin = new Date();
}
}
}, {
key: 'toggle',
value: function toggle() {
if (this._pause) {
this.play();
} else {
this.pause();
}
}
}, {
key: 'play',
value: function play() {
this._pause = false;
for (var i = 0, len = this.tweens.length; i < len; i++) {
this.tweens[i].play();
}
var self = this;
if (this.currentTask === 'wait') {
setTimeout(function () {
if (self._pause) return;
self.index++;
self.start();
if (self.index === self.cmds.length && self.complete) self.complete();
}, this.timeout);
}
}
}, {
key: 'stop',
value: function stop() {
for (var i = 0, len = this.tweens.length; i < len; i++) {
this.tweens[i].stop();
}
this.cmds.length = 0;
}
}, {
key: 'animate',
value: function animate(name) {
this.cmds = this.cmds.concat(To.animationMap[name] || []);
return this;
}
}, {
key: 'exec',
value: function exec(cmd, last) {
var len = cmd.length,
self = this;
this.currentTask = cmd[0];
switch (this.currentTask) {
case 'to':
self.stepCompleteCount = 0;
for (var i = 1; i < len; i++) {
var task = cmd[i];
var ease = task[1][2];
var target = {};
var prop = task[0];
target[prop] = task[1][0];
var t = new _tween2.default.Tween(this.element).to(target, task[1][1]).onStart(function () {
if (cmd.begin) cmd.begin.call(self.element, self.element);
}).onUpdate(function () {
if (cmd.progress) cmd.progress.call(self.element, self.element);
// self.element[prop] = this[prop];
}).easing(ease || _tween2.default.Easing.Linear.None).onComplete(function () {
self.stepCompleteCount++;
if (self.stepCompleteCount === len - 1) {
if (cmd.end) cmd.end.call(self.element, self.element);
if (last && self.complete) self.complete();
self.index++;
self.start();
}
}).start();
this.tweens.push(t);
}
break;
case 'wait':
this.currentTaskBegin = new Date();
this.timeout = cmd[1][0];
setTimeout(function () {
if (self._pause) return;
self.index++;
self.start();
if (cmd.end) cmd.end.call(self.element, self.element);
if (last && self.complete) self.complete();
}, cmd[1][0]);
break;
case 'then':
var arg = cmd[1][0];
arg.index = 0;
arg.complete = function () {
self.index++;
self.start();
if (last && self.complete) self.complete();
};
arg.start();
break;
case 'cycle':
var count = cmd[1][1];
if (count === undefined) {
self.index = cmd[1][0] || 0;
self.start();
} else {
if (count && self.cycleCount === count) {
self.index++;
self.start();
if (last && self.complete) self.complete();
} else {
self.cycleCount++;
self.index = cmd[1][0];
self.start();
}
}
break;
}
}
}]);
return To;
}();
To.get = function (element) {
var to = new To(element);
return to;
};
To.animationMap = {};
To.extend = function (animationName, cmds) {
To.animationMap[animationName] = cmds;
};
exports.default = To;
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.setRafInterval = setRafInterval;
exports.clearRafInterval = clearRafInterval;
/*!
* raf-interval v0.3.0 By dntzhang
* Github: https://github.com/dntzhang/raf-interval
* MIT Licensed.
*/
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
var queue = [],
id = -1,
ticking = false,
tickId = null,
now = Date.now,
lastTime = 0,
vendors = ['ms', 'moz', 'webkit', 'o'],
x = 0,
isWeapp = typeof wx !== 'undefined' && !wx.createCanvas,
isWegame = typeof wx !== 'undefined' && wx.createCanvas,
isBrowser = typeof window !== 'undefined';
var raf = isBrowser ? window.requestAnimationFrame : null;
var caf = isBrowser ? window.cancelAnimationFrame : null;
function mockRaf(callback, element) {
var currTime = now();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = setTimeout(function () {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
}
function mockCaf(id) {
clearTimeout(id);
}
if (isBrowser) {
window.setRafInterval = setRafInterval;
window.clearRafInterval = clearRafInterval;
for (; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
}
if (!raf) {
raf = mockRaf;
caf = mockCaf;
window.requestAnimationFrame = raf;
window.cancelAnimationFrame = caf;
}
} else if (isWeapp) {
raf = mockRaf;
caf = mockCaf;
} else if (isWegame) {
raf = requestAnimationFrame;
caf = cancelAnimationFrame;
}
function setRafInterval(fn, interval) {
id++;
queue.push({ id: id, fn: fn, interval: interval, lastTime: now() });
if (!ticking) {
var tick = function tick() {
tickId = raf(tick);
each(queue, function (item) {
if (item.interval < 17 || now() - item.lastTime >= item.interval) {
item.fn();
item.lastTime = now();
}
});
};
ticking = true;
tick();
}
return id;
}
function clearRafInterval(id) {
var i = 0,
len = queue.length;
for (; i < len; i++) {
if (id === queue[i].id) {
queue.splice(i, 1);
break;
}
}
if (queue.length === 0) {
caf(tickId);
ticking = false;
}
}
function each(arr, fn) {
if (Array.prototype.forEach) {
arr.forEach(fn);
} else {
var i = 0,
len = arr.length;
for (; i < len; i++) {
fn(arr[i], i);
}
}
}
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _canvasRender = __webpack_require__(25);
var _canvasRender2 = _interopRequireDefault(_canvasRender);
var _group = __webpack_require__(1);
var _group2 = _interopRequireDefault(_group);
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 Renderer = function () {
function Renderer(canvasOrContext, width, height) {
_classCallCheck(this, Renderer);
this.renderList = [];
if (arguments.length === 3) {
this.renderer = new _canvasRender2.default(canvasOrContext, width, height);
this.width = width;
this.height = height;
} else {
this.renderer = new _canvasRender2.default(canvasOrContext);
this.width = canvasOrContext.width;
this.height = canvasOrContext.height;
}
this.ctx = this.renderer.ctx;
}
_createClass(Renderer, [{
key: 'update',
value: function update(stage) {
this.renderer.clear(this.ctx, this.width, this.height);
this.renderer.render(this.ctx, stage);
this.ctx.draw && this.ctx.draw();
}
}, {
key: 'getHitRenderList',
value: function getHitRenderList(stage) {
var objs = this.renderList;
objs.length = 0;
this.computeMatrix(stage);
return objs;
}
}, {
key: 'computeMatrix',
value: function computeMatrix(stage) {
for (var i = 0, len = stage.children.length; i < len; i++) {
this._computeMatrix(stage.children[i]);
}
}
}, {
key: 'initComplex',
value: function initComplex(o) {
o.complexCompositeOperation = this._getCompositeOperation(o);
o.complexAlpha = this._getAlpha(o, 1);
}
}, {
key: '_computeMatrix',
value: function _computeMatrix(o, mtx) {
if (!o.isVisible()) {
return;
}
if (mtx && !o.fixed) {
o._matrix.initialize(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx, mtx.ty);
} else {
o._matrix.initialize(1, 0, 0, 1, 0, 0);
}
o._matrix.appendTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation, o.skewX, o.skewY, o.originX, o.originY);
if (o instanceof _group2.default) {
var list = o.children,
len = list.length,
i = 0;
for (; i < len; i++) {
this._computeMatrix(list[i], o._matrix);
}
} else {
// if (o instanceof Graphics) {
// this.renderList.push(o)
// this.initComplex(o)
// } else {
o.initAABB();
// if (this.isInStage(o)) {
this.renderList.push(o);
this.initComplex(o);
// }
// }
}
}
}, {
key: '_getCompositeOperation',
value: function _getCompositeOperation(o) {
if (o.compositeOperation) return o.compositeOperation;
if (o.parent) return this._getCompositeOperation(o.parent);
}
}, {
key: '_getAlpha',
value: function _getAlpha(o, alpha) {
var result = o.alpha * alpha;
if (o.parent) {
return this._getAlpha(o.parent, result);
}
return result;
}
}, {
key: 'isInStage',
value: function isInStage(o) {
return this.collisionBetweenAABB(o.AABB, this.stage.AABB);
}
}, {
key: 'collisionBetweenAABB',
value: function collisionBetweenAABB(AABB1, AABB2) {
var maxX = AABB1[0] + AABB1[2];
if (maxX < AABB2[0]) return false;
var minX = AABB1[0];
if (minX > AABB2[0] + AABB2[2]) return false;
var maxY = AABB1[1] + AABB1[3];
if (maxY < AABB2[1]) return false;
var minY = AABB1[1];
if (minY > AABB2[1] + AABB2[3]) return false;
return true;
}
}]);
return Renderer;
}();
exports.default = Renderer;
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _group = __webpack_require__(1);
var _group2 = _interopRequireDefault(_group);
var _renderer = __webpack_require__(13);
var _renderer2 = _interopRequireDefault(_renderer);
var _wxHitRender = __webpack_require__(32);
var _wxHitRender2 = _interopRequireDefault(_wxHitRender);
var _event = __webpack_require__(7);
var _event2 = _interopRequireDefault(_event);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var WeStage = function (_Group) {
_inherits(WeStage, _Group);
function WeStage(width, height, id, page) {
_classCallCheck(this, WeStage);
var _this = _possibleConstructorReturn(this, (WeStage.__proto__ || Object.getPrototypeOf(WeStage)).call(this));
var component = page.selectComponent('#' + id);
component.setData({
width: width,
height: height
});
component.stage = _this;
var canvasId = component.getCaxCanvasId();
var ctx = wx.createCanvasContext(canvasId, component);
var hitCtx = wx.createCanvasContext(canvasId + 'Hit', component);
_this.renderer = new _renderer2.default(ctx, width, height);
_this._hitRender = new _wxHitRender2.default(hitCtx, component, canvasId);
_this._overObject = null;
_this.ctx = ctx;
_this.hitAABB = true;
_this.width = width;
_this.height = height;
return _this;
}
_createClass(WeStage, [{
key: 'touchStartHandler',
value: function touchStartHandler(evt) {
var _this2 = this;
var p1 = evt.changedTouches[0];
evt.stageX = p1.x;
evt.stageY = p1.y;
this._getObjectUnderPoint(evt, function (obj) {
_this2.willDragObject = obj;
_this2._mouseDownX = evt.stageX;
_this2._mouseDownY = evt.stageY;
_this2.preStageX = evt.stageX;
_this2.preStageY = evt.stageY;
});
}
}, {
key: 'touchMoveHandler',
value: function touchMoveHandler(evt) {
var _this3 = this;
var p1 = evt.changedTouches[0];
evt.stageX = p1.x;
evt.stageY = p1.y;
this._getObjectUnderPoint(evt, function (obj) {
var mockEvt = new _event2.default();
mockEvt.stageX = evt.stageX;
mockEvt.stageY = evt.stageY;
mockEvt.pureEvent = evt;
if (_this3.willDragObject) {
mockEvt.type = 'drag';
mockEvt.dx = mockEvt.stageX - _this3.preStageX;
mockEvt.dy = mockEvt.stageY - _this3.preStageY;
_this3.preStageX = mockEvt.stageX;
_this3.preStageY = mockEvt.stageY;
_this3.willDragObject.dispatchEvent(mockEvt);
}
if (obj) {
if (_this3._overObject === null) {
_this3._overObject = obj;
} else {
if (obj.id !== _this3._overObject.id) {
_this3._overObject = obj;
} else {
mockEvt.type = 'touchmove';
obj.dispatchEvent(mockEvt);
}
}
} else if (_this3._overObject) {
_this3._overObject = null;
}
});
}
}, {
key: 'touchEndHandler',
value: function touchEndHandler(evt) {
var _this4 = this;
var p1 = evt.changedTouches[0];
evt.stageX = p1.x;
evt.stageY = p1.y;
var mockEvt = new _event2.default();
mockEvt.stageX = evt.stageX;
mockEvt.stageY = evt.stageY;
mockEvt.pureEvent = evt;
this._getObjectUnderPoint(evt, function (obj) {
_this4._mouseUpX = evt.stageX;
_this4._mouseUpY = evt.stageY;
_this4.willDragObject = null;
_this4.preStageX = null;
_this4.preStageY = null;
if (obj && Math.abs(_this4._mouseDownX - _this4._mouseUpX) < 30 && Math.abs(_this4._mouseDownY - _this4._mouseUpY) < 30) {
mockEvt.type = 'tap';
obj.dispatchEvent(mockEvt);
}
});
}
}, {
key: '_handleMouseOut',
value: function _handleMouseOut(evt) {
this.dispatchEvent({
pureEvent: evt,
type: 'mouseout',
stageX: evt.stageX,
stageY: evt.stageY
});
}
}, {
key: '_getObjectUnderPoint',
value: function _getObjectUnderPoint(evt, cb) {
var list = this.renderer.getHitRenderList(this);
if (this.hitAABB) {
return this._hitRender.hitAABB(list, evt, cb);
} else {
this._hitRender.clear();
this._hitRender.hit(list, evt, cb, list.length - 1);
}
}
}, {
key: 'update',
value: function update() {
this.renderer.update(this);
}
}]);
return WeStage;
}(_group2.default);
exports.default = WeStage;
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _shape = __webpack_require__(0);
var _shape2 = _interopRequireDefault(_shape);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var RoundedRect = function (_Shape) {
_inherits(RoundedRect, _Shape);
function RoundedRect(width, height, r, option) {
_classCallCheck(this, RoundedRect);
var _this = _possibleConstructorReturn(this, (RoundedRect.__proto__ || Object.getPrototypeOf(RoundedRect)).call(this));
_this.option = Object.assign({
lineWidth: 1
}, option);
_this.r = r || 0;
_this.width = width;
_this.height = height;
return _this;
}
_createClass(RoundedRect, [{
key: 'draw',
value: function draw() {
var width = this.width,
height = this.height,
r = this.r;
var ax = r,
ay = 0,
bx = width,
by = 0,
cx = width,
cy = height,
dx = 0,
dy = height,
ex = 0,
ey = 0;
this.beginPath();
this.moveTo(ax, ay);
this.arcTo(bx, by, cx, cy, r);
this.arcTo(cx, cy, dx, dy, r);
this.arcTo(dx, dy, ex, ey, r);
this.arcTo(ex, ey, ax, ay, r);
if (this.option.fillStyle) {
this.closePath();
this.fillStyle(this.option.fillStyle);
this.fill();
}
if (this.option.strokeStyle) {
this.lineWidth(this.option.lineWidth);
this.strokeStyle(this.option.strokeStyle);
this.stroke();
}
}
}]);
return RoundedRect;
}(_shape2.default);
exports.default = RoundedRect;
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _index = __webpack_require__(17);
var _index2 = _interopRequireDefault(_index);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var stage = new _index2.default.Stage(300, 400, '#canvasCtn');
var ball = new _index2.default.Graphics();
ball.beginPath().arc(0, 0, 140, 0, Math.PI * 2).closePath().fillStyle('#f4862c').fill().strokeStyle("#046ab4").lineWidth(8).stroke().lineWidth(6).beginPath().moveTo(298 - 377, 506 - 391).bezierCurveTo(236 - 377, 396 - 391, 302 - 377, 272 - 391, 407 - 377, 254 - 391).stroke().beginPath().moveTo(328 - 377, 258 - 391).bezierCurveTo(360 - 377, 294 - 391, 451 - 377, 272 - 391, 503 - 377, 332 - 391).stroke().beginPath().moveTo(282 - 377, 288 - 391).bezierCurveTo(391 - 377, 292 - 391, 481 - 377, 400 - 391, 488 - 377, 474 - 391).stroke().beginPath().moveTo(242 - 377, 352 - 391).bezierCurveTo(352 - 377, 244 - 391, 319 - 377, 423 - 391, 409 - 377, 527 - 391).stroke();
ball.x = 150;
ball.y = 200;
ball.scaleX = ball.scaleY = 0.4;
stage.add(ball);
ball.on('drag', function (evt) {
evt.target.x += evt.dx;
evt.target.y += evt.dy;
evt.preventDefault();
});
ball.cursor = 'move';
document.querySelector('#addScaleBtn').addEventListener('click', function () {
ball.scaleX += 0.1;
ball.scaleY += 0.1;
});
document.querySelector('#subScaleBtn').addEventListener('click', function () {
ball.scaleX -= 0.1;
ball.scaleY -= 0.1;
if (ball.scaleX < 0.1) {
ball.scaleX = ball.scaleY = 0.1;
}
});
_index2.default.tick(stage.update.bind(stage));
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _tween = __webpack_require__(10);
var _tween2 = _interopRequireDefault(_tween);
var _to = __webpack_require__(11);
var _to2 = _interopRequireDefault(_to);
__webpack_require__(19);
var _stage = __webpack_require__(20);
var _stage2 = _interopRequireDefault(_stage);
var _weStage = __webpack_require__(14);
var _weStage2 = _interopRequireDefault(_weStage);
var _graphics = __webpack_require__(3);
var _graphics2 = _interopRequireDefault(_graphics);
var _bitmap = __webpack_require__(4);
var _bitmap2 = _interopRequireDefault(_bitmap);
var _text = __webpack_require__(5);
var _text2 = _interopRequireDefault(_text);
var _group = __webpack_require__(1);
var _group2 = _interopRequireDefault(_group);
var _sprite = __webpack_require__(6);
var _sprite2 = _interopRequireDefault(_sprite);
var _roundedRect = __webpack_require__(15);
var _roundedRect2 = _interopRequireDefault(_roundedRect);
var _arrowPath = __webpack_require__(33);
var _arrowPath2 = _interopRequireDefault(_arrowPath);
var _ellipse = __webpack_require__(34);
var _ellipse2 = _interopRequireDefault(_ellipse);
var _path = __webpack_require__(35);
var _path2 = _interopRequireDefault(_path);
var _button = __webpack_require__(38);
var _button2 = _interopRequireDefault(_button);
var _rect = __webpack_require__(39);
var _rect2 = _interopRequireDefault(_rect);
var _circle = __webpack_require__(40);
var _circle2 = _interopRequireDefault(_circle);
var _polygon = __webpack_require__(41);
var _polygon2 = _interopRequireDefault(_polygon);
var _equilateralPolygon = __webpack_require__(42);
var _equilateralPolygon2 = _interopRequireDefault(_equilateralPolygon);
var _rafInterval = __webpack_require__(12);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
_to2.default.easing = {
linear: _tween2.default.Easing.Linear.None
};
var cax = {
easing: {
linear: _tween2.default.Easing.Linear.None
},
util: {
randomInt: function randomInt(min, max) {
return min + Math.floor(Math.random() * (max - min + 1));
}
},
Stage: _stage2.default,
WeStage: _weStage2.default,
Graphics: _graphics2.default,
Bitmap: _bitmap2.default,
Text: _text2.default,
Group: _group2.default,
Sprite: _sprite2.default,
ArrowPath: _arrowPath2.default,
Ellipse: _ellipse2.default,
Path: _path2.default,
Button: _button2.default,
RoundedRect: _roundedRect2.default,
Rect: _rect2.default,
Circle: _circle2.default,
Polygon: _polygon2.default,
EquilateralPolygon: _equilateralPolygon2.default,
setInterval: _rafInterval.setRafInterval,
clearInterval: _rafInterval.clearRafInterval,
tick: function tick(fn) {
return (0, _rafInterval.setRafInterval)(fn, 16);
},
untick: function untick(tickId) {
(0, _rafInterval.clearRafInterval)(tickId);
},
caxCanvasId: 0,
TWEEN: _tween2.default,
To: _to2.default
};
['Quadratic', 'Cubic', 'Quartic', 'Quintic', 'Sinusoidal', 'Exponential', 'Circular', 'Elastic', 'Back', 'Bounce'].forEach(function (item) {
var itemLower = item.toLowerCase();
cax.easing[itemLower + 'In'] = _tween2.default.Easing[item].In;
cax.easing[itemLower + 'Out'] = _tween2.default.Easing[item].Out;
cax.easing[itemLower + 'InOut'] = _tween2.default.Easing[item].InOut;
_to2.default.easing[itemLower + 'In'] = _tween2.default.Easing[item].In;
_to2.default.easing[itemLower + 'Out'] = _tween2.default.Easing[item].Out;
_to2.default.easing[itemLower + 'InOut'] = _tween2.default.Easing[item].InOut;
});
module.exports = cax;
/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout() {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
})();
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while (len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) {
return [];
};
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () {
return '/';
};
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function () {
return 0;
};
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _to = __webpack_require__(11);
var _to2 = _interopRequireDefault(_to);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
_to2.default.extend('rubber', [['to', ['scaleX', {
'0': 1.25,
'1': 300
}], ['scaleY', {
'0': 0.75,
'1': 300
}]], ['to', ['scaleX', {
'0': 0.75,
'1': 100
}], ['scaleY', {
'0': 1.25,
'1': 100
}]], ['to', ['scaleX', {
'0': 1.15,
'1': 100
}], ['scaleY', {
'0': 0.85,
'1': 100
}]], ['to', ['scaleX', {
'0': 0.95,
'1': 150
}], ['scaleY', {
'0': 1.05,
'1': 150
}]], ['to', ['scaleX', {
'0': 1.05,
'1': 100
}], ['scaleY', {
'0': 0.95,
'1': 100
}]], ['to', ['scaleX', {
'0': 1,
'1': 250
}], ['scaleY', {
'0': 1,
'1': 250
}]]]);
_to2.default.extend('bounceIn', [['to', ['scaleX', {
'0': 0,
'1': 0
}], ['scaleY', {
'0': 0,
'1': 0
}]], ['to', ['scaleX', {
'0': 1.35,
'1': 200
}], ['scaleY', {
'0': 1.35,
'1': 200
}]], ['to', ['scaleX', {
'0': 0.9,
'1': 100
}], ['scaleY', {
'0': 0.9,
'1': 100
}]], ['to', ['scaleX', {
'0': 1.1,
'1': 100
}], ['scaleY', {
'0': 1.1,
'1': 100
}]], ['to', ['scaleX', {
'0': 0.95,
'1': 100
}], ['scaleY', {
'0': 0.95,
'1': 100
}]], ['to', ['scaleX', {
'0': 1,
'1': 100
}], ['scaleY', {
'0': 1,
'1': 100
}]]]);
_to2.default.extend('flipInX', [['to', ['rotateX', {
'0': -90,
'1': 0
}]], ['to', ['rotateX', {
'0': 20,
'1': 300
}]], ['to', ['rotateX', {
'0': -20,
'1': 300
}]], ['to', ['rotateX', {
'0': 10,
'1': 300
}]], ['to', ['rotateX', {
'0': -5,
'1': 300
}]], ['to', ['rotateX', {
'0': 0,
'1': 300
}]]]);
_to2.default.extend('zoomOut', [['to', ['scaleX', {
'0': 0,
'1': 400
}], ['scaleY', {
'0': 0,
'1': 400
}]]]);
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _wegameCanvas = __webpack_require__(21);
var _wegameCanvas2 = _interopRequireDefault(_wegameCanvas);
var _group = __webpack_require__(1);
var _group2 = _interopRequireDefault(_group);
var _renderer = __webpack_require__(13);
var _renderer2 = _interopRequireDefault(_renderer);
var _hitRender = __webpack_require__(31);
var _hitRender2 = _interopRequireDefault(_hitRender);
var _event = __webpack_require__(7);
var _event2 = _interopRequireDefault(_event);
var _weStage = __webpack_require__(14);
var _weStage2 = _interopRequireDefault(_weStage);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Stage = function (_Group) {
_inherits(Stage, _Group);
function Stage(width, height, renderTo) {
_classCallCheck(this, Stage);
var _this = _possibleConstructorReturn(this, (Stage.__proto__ || Object.getPrototypeOf(Stage)).call(this));
var len = arguments.length;
_this.isWegame = typeof wx !== 'undefined' && wx.createCanvas;
if (len === 0) {
// wegame
_this.canvas = _wegameCanvas2.default;
_this.disableMoveDetection = true;
} else if (len === 4) {
var _ret;
// weapp
return _ret = new _weStage2.default(arguments[0], arguments[1], arguments[2], arguments[3]), _possibleConstructorReturn(_this, _ret);
} else {
if (len === 1) {
_this.canvas = typeof width === 'string' ? document.querySelector(width) : width;
} else {
_this.renderTo = typeof renderTo === 'string' ? document.querySelector(renderTo) : renderTo;
if (_this.renderTo.tagName === 'CANVAS') {
_this.canvas = _this.renderTo;
_this.canvas.width = width;
_this.canvas.height = height;
} else {
_this.canvas = document.createElement('canvas');
_this.canvas.width = width;
_this.canvas.height = height;
_this.renderTo.appendChild(_this.canvas);
}
}
// get rect again when trigger onscroll onresize event!?
_this._boundingClientRect = _this.canvas.getBoundingClientRect();
_this.offset = _this._getOffset(_this.canvas);
}
_this.renderer = new _renderer2.default(_this.canvas);
if (_this.isWegame) {
wx.onTouchStart(function (evt) {
return _this._handleMouseDown(evt);
});
wx.onTouchMove(function (evt) {
return _this._handleMouseMove(evt);
});
wx.onTouchEnd(function (evt) {
return _this._handleMouseUp(evt);
});
} else {
_this.canvas.addEventListener('click', function (evt) {
return _this._handleClick(evt);
});
_this.canvas.addEventListener('mousedown', function (evt) {
return _this._handleMouseDown(evt);
});
_this.canvas.addEventListener('mousemove', function (evt) {
return _this._handleMouseMove(evt);
});
_this.canvas.addEventListener('mouseup', function (evt) {
return _this._handleMouseUp(evt);
});
_this.canvas.addEventListener('mouseout', function (evt) {
return _this._handleMouseOut(evt);
});
_this.canvas.addEventListener('touchstart', function (evt) {
return _this._handleMouseDown(evt);
});
_this.canvas.addEventListener('touchmove', function (evt) {
return _this._handleMouseMove(evt);
});
_this.canvas.addEventListener('touchend', function (evt) {
return _this._handleMouseUp(evt);
});
_this.canvas.addEventListener('dblclick', function (evt) {
return _this._handleDblClick(evt);
});
// this.addEvent(this.canvas, "mousewheel", this._handleMouseWheel.bind(this));
document.addEventListener('contextmenu', function (evt) {
return _this._handleContextmenu(evt);
});
}
_this.borderTopWidth = 0;
_this.borderLeftWidth = 0;
_this.hitAABB = false;
_this._hitRender = new _hitRender2.default();
_this._overObject = null;
_this._scaleX = 1;
_this._scaleY = 1;
_this._mouseDownX = 0;
_this._mouseDownY = 0;
_this._mouseUpX = 0;
_this._mouseUpY = 0;
_this.willDragObject = null;
_this.preStageX = null;
_this.preStageY = null;
_this.width = _this.canvas.width;
_this.height = _this.canvas.height;
return _this;
}
_createClass(Stage, [{
key: '_handleContextmenu',
value: function _handleContextmenu(evt) {
this._getObjectUnderPoint(evt);
}
}, {
key: '_handleDblClick',
value: function _handleDblClick(evt) {
this._getObjectUnderPoint(evt);
}
}, {
key: '_handleClick',
value: function _handleClick(evt) {
if (Math.abs(this._mouseDownX - this._mouseUpX) < 20 && Math.abs(this._mouseDownY - this._mouseUpY) < 20) {
this._getObjectUnderPoint(evt);
}
}
}, {
key: '_handleMouseDown',
value: function _handleMouseDown(evt) {
this.offset = this._getOffset(this.canvas);
var obj = this._getObjectUnderPoint(evt);
this.willDragObject = obj;
this._mouseDownX = evt.stageX;
this._mouseDownY = evt.stageY;
this.preStageX = evt.stageX;
this.preStageY = evt.stageY;
}
}, {
key: 'scaleEventPoint',
value: function scaleEventPoint(x, y) {
this._scaleX = x;
this._scaleY = y;
}
}, {
key: '_handleMouseUp',
value: function _handleMouseUp(evt) {
var obj = this._getObjectUnderPoint(evt);
this._mouseUpX = evt.stageX;
this._mouseUpY = evt.stageY;
var mockEvt = new _event2.default();
mockEvt.stageX = evt.stageX;
mockEvt.stageY = evt.stageY;
mockEvt.pureEvent = evt;
this.willDragObject = null;
this.preStageX = null;
this.preStageY = null;
if (obj && Math.abs(this._mouseDownX - this._mouseUpX) < 30 && Math.abs(this._mouseDownY - this._mouseUpY) < 30) {
mockEvt.type = 'tap';
obj.dispatchEvent(mockEvt);
}
}
}, {
key: '_handleMouseOut',
value: function _handleMouseOut(evt) {
this._computeStageXY(evt);
this.dispatchEvent({
pureEvent: evt,
type: 'mouseout',
stageX: evt.stageX,
stageY: evt.stageY
});
}
}, {
key: '_handleMouseMove',
value: function _handleMouseMove(evt) {
if (this.disableMoveDetection) return;
var obj = this._getObjectUnderPoint(evt);
var mockEvt = new _event2.default();
mockEvt.stageX = evt.stageX;
mockEvt.stageY = evt.stageY;
mockEvt.pureEvent = evt;
if (this.willDragObject) {
mockEvt.type = 'drag';
mockEvt.dx = mockEvt.stageX - this.preStageX;
mockEvt.dy = mockEvt.stageY - this.preStageY;
this.preStageX = mockEvt.stageX;
this.preStageY = mockEvt.stageY;
this.willDragObject.dispatchEvent(mockEvt);
}
if (obj) {
if (this._overObject === null) {
mockEvt.type = 'mouseover';
obj.dispatchEvent(mockEvt);
this._overObject = obj;
this._setCursor(obj);
} else {
if (obj.id !== this._overObject.id) {
this._overObject.dispatchEvent({
pureEvent: evt,
type: 'mouseout',
stageX: evt.stageX,
stageY: evt.stageY
});
mockEvt.type = 'mouseover';
obj.dispatchEvent(mockEvt);
this._setCursor(obj);
this._overObject = obj;
} else {
mockEvt.type = 'mousemove';
obj.dispatchEvent(mockEvt);
mockEvt.type = 'touchmove';
obj.dispatchEvent(mockEvt);
}
}
} else if (this._overObject) {
mockEvt.type = 'mouseout';
this._overObject.dispatchEvent(mockEvt);
this._overObject = null;
this._setCursor({ cursor: 'default' });
}
}
}, {
key: '_setCursor',
value: function _setCursor(obj) {
if (obj.cursor) {
this.canvas.style.cursor = obj.cursor;
} else if (obj.parent) {
this._setCursor(obj.parent);
}
}
}, {
key: '_getObjectUnderPoint',
value: function _getObjectUnderPoint(evt) {
this._computeStageXY(evt);
if (this.hitAABB) {
return this._hitRender.hitAABB(this, evt);
} else {
return this._hitRender.hitPixel(this, evt);
}
}
}, {
key: '_computeStageXY',
value: function _computeStageXY(evt) {
this._boundingClientRect = this.isWegame ? { left: 0, top: 0 } : this.canvas.getBoundingClientRect();
if (evt.touches || evt.changedTouches) {
var firstTouch = evt.touches[0] || evt.changedTouches[0];
if (firstTouch) {
evt.stageX = (firstTouch.pageX - this.offset[0]) / this._scaleX;
evt.stageY = (firstTouch.pageY - this.offset[1]) / this._scaleY;
}
} else {
evt.stageX = (evt.clientX - this._boundingClientRect.left - this.borderLeftWidth) / this._scaleX;
evt.stageY = (evt.clientY - this._boundingClientRect.top - this.borderTopWidth) / this._scaleY;
}
}
}, {
key: '_getOffset',
value: function _getOffset(el) {
if (this.isWegame) {
return [0, 0];
}
var _t = 0,
_l = 0;
if (document.documentElement.getBoundingClientRect && el.getBoundingClientRect) {
var box = el.getBoundingClientRect();
_l = box.left;
_t = box.top;
} else {
while (el.offsetParent) {
_t += el.offsetTop;
_l += el.offsetLeft;
el = el.offsetParent;
}
return [_l, _t];
}
return [_l + Math.max(document.documentElement.scrollLeft, document.body.scrollLeft), _t + Math.max(document.documentElement.scrollTop, document.body.scrollTop)];
}
}, {
key: 'update',
value: function update() {
this.renderer.update(this);
}
}, {
key: 'on',
value: function on(type, fn) {
var _this2 = this;
this.canvas.addEventListener(type, function (evt) {
_this2._computeStageXY(evt);
fn(evt);
});
}
}, {
key: 'off',
value: function off(type, fn) {
this.canvas.removeEventListener(type, fn);
}
}]);
return Stage;
}(_group2.default);
exports.default = Stage;
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var wegameCanvas = null;
if (typeof wx !== 'undefined' && wx.createCanvas) {
wegameCanvas = wx.createCanvas();
}
exports.default = wegameCanvas;
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var DEG_TO_RAD = 0.017453292519943295;
var Matrix2D = function () {
function Matrix2D(a, b, c, d, tx, ty) {
_classCallCheck(this, Matrix2D);
this.a = a == null ? 1 : a;
this.b = b || 0;
this.c = c || 0;
this.d = d == null ? 1 : d;
this.tx = tx || 0;
this.ty = ty || 0;
return this;
}
_createClass(Matrix2D, [{
key: "identity",
value: function identity() {
this.a = this.d = 1;
this.b = this.c = this.tx = this.ty = 0;
return this;
}
}, {
key: "appendTransform",
value: function appendTransform(x, y, scaleX, scaleY, rotation, skewX, skewY, originX, originY) {
if (rotation % 360) {
var r = rotation * DEG_TO_RAD;
var cos = Math.cos(r);
var sin = Math.sin(r);
} else {
cos = 1;
sin = 0;
}
if (skewX || skewY) {
skewX *= DEG_TO_RAD;
skewY *= DEG_TO_RAD;
this.append(Math.cos(skewY), Math.sin(skewY), -Math.sin(skewX), Math.cos(skewX), x, y);
this.append(cos * scaleX, sin * scaleX, -sin * scaleY, cos * scaleY, 0, 0);
} else {
this.append(cos * scaleX, sin * scaleX, -sin * scaleY, cos * scaleY, x, y);
}
if (originX || originY) {
this.tx -= originX * this.a + originY * this.c;
this.ty -= originX * this.b + originY * this.d;
}
return this;
}
}, {
key: "append",
value: function append(a, b, c, d, tx, ty) {
var a1 = this.a;
var b1 = this.b;
var c1 = this.c;
var d1 = this.d;
this.a = a * a1 + b * c1;
this.b = a * b1 + b * d1;
this.c = c * a1 + d * c1;
this.d = c * b1 + d * d1;
this.tx = tx * a1 + ty * c1 + this.tx;
this.ty = tx * b1 + ty * d1 + this.ty;
return this;
}
}, {
key: "initialize",
value: function initialize(a, b, c, d, tx, ty) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.tx = tx;
this.ty = ty;
return this;
}
}, {
key: "setValues",
value: function setValues(a, b, c, d, tx, ty) {
this.a = a == null ? 1 : a;
this.b = b || 0;
this.c = c || 0;
this.d = d == null ? 1 : d;
this.tx = tx || 0;
this.ty = ty || 0;
return this;
}
}, {
key: "invert",
value: function invert() {
var a1 = this.a;
var b1 = this.b;
var c1 = this.c;
var d1 = this.d;
var tx1 = this.tx;
var n = a1 * d1 - b1 * c1;
this.a = d1 / n;
this.b = -b1 / n;
this.c = -c1 / n;
this.d = a1 / n;
this.tx = (c1 * this.ty - d1 * tx1) / n;
this.ty = -(a1 * this.ty - b1 * tx1) / n;
return this;
}
}, {
key: "copy",
value: function copy(matrix) {
return this.setValues(matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty);
}
}]);
return Matrix2D;
}();
exports.default = Matrix2D;
/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var MOUSEOUT = 'mouseout';
var EventDispatcher = function () {
function EventDispatcher() {
_classCallCheck(this, EventDispatcher);
this._listeners = null;
this._captureListeners = null;
}
_createClass(EventDispatcher, [{
key: 'addEventListener',
value: function addEventListener(type, listener, useCapture) {
var listeners;
if (useCapture) {
listeners = this._captureListeners = this._captureListeners || {};
} else {
listeners = this._listeners = this._listeners || {};
}
var arr = listeners[type];
if (arr) {
this.removeEventListener(type, listener, useCapture);
}
arr = listeners[type]; // remove may have deleted the array
if (!arr) {
listeners[type] = [listener];
} else {
arr.push(listener);
}
return listener;
}
}, {
key: 'removeEventListener',
value: function removeEventListener(type, listener, useCapture) {
var listeners = useCapture ? this._captureListeners : this._listeners;
if (!listeners) {
return;
}
var arr = listeners[type];
if (!arr) {
return;
}
arr.every(function (item, index) {
if (item === listener) {
arr.splice(index, 1);
return false;
}
return true;
});
}
}, {
key: 'on',
value: function on(type, listener, useCapture) {
this.addEventListener(type, listener, useCapture);
}
}, {
key: 'off',
value: function off(type, listener, useCapture) {
this.removeEventListener(type, listener, useCapture);
}
}, {
key: 'dispatchEvent',
value: function dispatchEvent(evt) {
if (evt.type === MOUSEOUT || !this.parent) {
this._dispatchEvent(evt, 0);
this._dispatchEvent(evt, 1);
} else {
var top = this,
list = [top];
while (top.parent) {
list.push(top = top.parent);
}
var i,
l = list.length;
// capture & atTarget
for (i = l - 1; i >= 0 && !evt.propagationStopped; i--) {
list[i]._dispatchEvent(evt, 0);
}
// bubbling
for (i = 0; i < l && !evt.propagationStopped; i++) {
list[i]._dispatchEvent(evt, 1);
}
}
}
}, {
key: '_dispatchEvent',
value: function _dispatchEvent(evt, type) {
var _this = this;
evt.target = this;
if (this._captureListeners && type === 0) {
var cls = this._captureListeners[evt.type];
cls && cls.forEach(function (fn) {
fn.call(_this, evt);
});
}
if (this._listeners && type === 1) {
var ls = this._listeners[evt.type];
ls && ls.forEach(function (fn) {
fn.call(_this, evt);
});
}
}
}]);
return EventDispatcher;
}();
exports.default = EventDispatcher;
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var UID = {};
UID._nextID = 0;
UID.get = function () {
return UID._nextID++;
};
exports.default = UID;
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _group = __webpack_require__(1);
var _group2 = _interopRequireDefault(_group);
var _graphics = __webpack_require__(3);
var _graphics2 = _interopRequireDefault(_graphics);
var _render2 = __webpack_require__(8);
var _render3 = _interopRequireDefault(_render2);
var _sprite = __webpack_require__(6);
var _sprite2 = _interopRequireDefault(_sprite);
var _bitmap = __webpack_require__(4);
var _bitmap2 = _interopRequireDefault(_bitmap);
var _text = __webpack_require__(5);
var _text2 = _interopRequireDefault(_text);
var _index = __webpack_require__(27);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var CanvasRender = function (_Render) {
_inherits(CanvasRender, _Render);
function CanvasRender(canvasOrContext, width, height) {
_classCallCheck(this, CanvasRender);
var _this = _possibleConstructorReturn(this, (CanvasRender.__proto__ || Object.getPrototypeOf(CanvasRender)).call(this));
if (arguments.length === 3) {
_this.ctx = canvasOrContext;
_this.width = width;
_this.height = height;
} else {
_this.ctx = canvasOrContext.getContext('2d');
_this.width = canvasOrContext.width;
_this.height = canvasOrContext.height;
}
return _this;
}
_createClass(CanvasRender, [{
key: 'clear',
value: function clear(ctx, width, height) {
//restore cache cavans transform
ctx.restore();
ctx.clearRect(0, 0, width, height);
}
}, {
key: 'render',
value: function render(ctx, o, cacheRender) {
var mtx = o._matrix;
if (o.children) {
var list = o.children.slice(0),
l = list.length;
for (var i = 0; i < l; i++) {
var child = list[i];
mtx.initialize(1, 0, 0, 1, 0, 0);
mtx.appendTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation, o.skewX, o.skewY, o.originX, o.originY);
// if (!this.checkBoundEvent(child)) continue
ctx.save();
this._render(ctx, child, cacheRender ? null : mtx, cacheRender);
ctx.restore();
}
} else {
this._render(ctx, o, mtx, cacheRender);
}
}
}, {
key: '_render',
value: function _render(ctx, o, mtx, cacheRender) {
if (!o.isVisible()) return;
if (mtx && !o.fixed) {
o._matrix.initialize(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx, mtx.ty);
} else {
o._matrix.initialize(1, 0, 0, 1, 0, 0);
}
mtx = o._matrix;
if (!cacheRender) {
mtx.appendTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation, o.skewX, o.skewY, o.originX, o.originY);
}
var ocg = o.clipGraphics;
if (ocg) {
ctx.beginPath();
ocg._matrix.copy(mtx);
ocg._matrix.appendTransform(ocg.x, ocg.y, ocg.scaleX, ocg.scaleY, ocg.rotation, ocg.skewX, ocg.skewY, ocg.originX, ocg.originY);
ctx.setTransform(ocg._matrix.a, ocg._matrix.b, ocg._matrix.c, ocg._matrix.d, ocg._matrix.tx, ocg._matrix.ty);
ocg.render(ctx);
ctx.clip(o.clipRuleNonzero ? 'nonzero' : 'evenodd');
}
o.complexCompositeOperation = ctx.globalCompositeOperation = this.getCompositeOperation(o);
o.complexAlpha = ctx.globalAlpha = this.getAlpha(o, 1);
if (!cacheRender) {
ctx.setTransform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx, mtx.ty);
}
if (o._readyToCache) {
o._readyToCache = false;
o.cacheCtx.setTransform(o._cacheData.scale, 0, 0, o._cacheData.scale, o._cacheData.x * -1, o._cacheData.y * -1);
this.render(o.cacheCtx, o, true);
//debug cacheCanvas
//document.body.appendChild(o.cacheCanvas)
if (o._readyToFilter) {
o.cacheCtx.putImageData((0, _index.filter)(o.cacheCtx.getImageData(0, 0, o.cacheCanvas.width, o.cacheCanvas.height), o._filterName), 0, 0);
this._readyToFilter = false;
}
ctx.drawImage(o.cacheCanvas, o._cacheData.x, o._cacheData.y);
} else if (o.cacheCanvas && !cacheRender) {
ctx.drawImage(o.cacheCanvas, o._cacheData.x, o._cacheData.y);
} else if (o instanceof _group2.default) {
var list = o.children.slice(0),
l = list.length;
for (var i = 0; i < l; i++) {
ctx.save();
var target = this._render(ctx, list[i], mtx);
if (target) return target;
ctx.restore();
}
} else if (o instanceof _graphics2.default) {
o.render(ctx);
} else if (o instanceof _sprite2.default && o.rect) {
o.updateFrame();
var rect = o.rect;
ctx.drawImage(o.img, rect[0], rect[1], rect[2], rect[3], 0, 0, rect[2], rect[3]);
} else if (o instanceof _bitmap2.default && o.rect) {
var bRect = o.rect;
ctx.drawImage(o.img, bRect[0], bRect[1], bRect[2], bRect[3], 0, 0, bRect[2], bRect[3]);
} else if (o instanceof _text2.default) {
ctx.font = o.font;
ctx.fillStyle = o.color;
ctx.textBaseline = o.baseline;
ctx.fillText(o.text, 0, 0);
}
}
}, {
key: 'getCompositeOperation',
value: function getCompositeOperation(o) {
if (o.compositeOperation) return o.compositeOperation;
if (o.parent) return this.getCompositeOperation(o.parent);
}
}, {
key: 'getAlpha',
value: function getAlpha(o, alpha) {
var result = o.alpha * alpha;
if (o.parent) {
return this.getAlpha(o.parent, result);
}
return result;
}
}]);
return CanvasRender;
}(_render3.default);
exports.default = CanvasRender;
/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var g;
// This works in non-strict mode
g = function () {
return this;
}();
try {
// This works if eval is allowed (see CSP)
g = g || Function("return this")() || (1, eval)("this");
} catch (e) {
// This works if the window reference is available
if ((typeof window === "undefined" ? "undefined" : _typeof(window)) === "object") g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.filter = filter;
var _invert = __webpack_require__(28);
var _blur = __webpack_require__(29);
function filter(pixels, name) {
if (name.indexOf('invert(') === 0) {
return (0, _invert.invert)(pixels, Number(name.replace('invert(', '').replace('%)', '')) / 100);
} else if (name.indexOf('blur(') === 0) {
return (0, _blur.blur)(pixels, Number(name.replace('blur(', '').replace('px)', '')));
}
}
/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.invert = invert;
function invert(pixels, ratio) {
var d = pixels.data;
ratio = ratio === undefined ? 1 : ratio;
for (var i = 0; i < d.length; i += 4) {
d[i] = d[i] + ratio * (255 - 2 * d[i]);
d[i + 1] = d[i + 1] + ratio * (255 - 2 * d[i + 1]);
d[i + 2] = d[i + 2] + ratio * (255 - 2 * d[i + 2]);
d[i + 3] = d[i + 3];
}
return pixels;
}
/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.blur = blur;
var _createImageData = __webpack_require__(30);
function blur(pixels, diameter) {
diameter = Math.abs(diameter);
if (diameter <= 1) return pixels;
var radius = diameter / 2;
var len = Math.ceil(diameter) + (1 - Math.ceil(diameter) % 2);
var weights = new Float32Array(len);
var rho = (radius + 0.5) / 3;
var rhoSq = rho * rho;
var gaussianFactor = 1 / Math.sqrt(2 * Math.PI * rhoSq);
var rhoFactor = -1 / (2 * rho * rho);
var wsum = 0;
var middle = Math.floor(len / 2);
for (var i = 0; i < len; i++) {
var x = i - middle;
var gx = gaussianFactor * Math.exp(x * x * rhoFactor);
weights[i] = gx;
wsum += gx;
}
for (var i = 0; i < weights.length; i++) {
weights[i] /= wsum;
}
return separableConvolve(pixels, weights, weights, false);
}
function separableConvolve(pixels, horizWeights, vertWeights, opaque) {
return horizontalConvolve(verticalConvolve(pixels, vertWeights, opaque), horizWeights, opaque);
}
function horizontalConvolve(pixels, weightsVector, opaque) {
var side = weightsVector.length;
var halfSide = Math.floor(side / 2);
var src = pixels.data;
var sw = pixels.width;
var sh = pixels.height;
var w = sw;
var h = sh;
var output = (0, _createImageData.createImageData)(w, h);
var dst = output.data;
var alphaFac = opaque ? 1 : 0;
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
var sy = y;
var sx = x;
var dstOff = (y * w + x) * 4;
var r = 0,
g = 0,
b = 0,
a = 0;
for (var cx = 0; cx < side; cx++) {
var scy = sy;
var scx = Math.min(sw - 1, Math.max(0, sx + cx - halfSide));
var srcOff = (scy * sw + scx) * 4;
var wt = weightsVector[cx];
r += src[srcOff] * wt;
g += src[srcOff + 1] * wt;
b += src[srcOff + 2] * wt;
a += src[srcOff + 3] * wt;
}
dst[dstOff] = r;
dst[dstOff + 1] = g;
dst[dstOff + 2] = b;
dst[dstOff + 3] = a + alphaFac * (255 - a);
}
}
return output;
}
function verticalConvolve(pixels, weightsVector, opaque) {
var side = weightsVector.length;
var halfSide = Math.floor(side / 2);
var src = pixels.data;
var sw = pixels.width;
var sh = pixels.height;
var w = sw;
var h = sh;
var output = (0, _createImageData.createImageData)(w, h);
var dst = output.data;
var alphaFac = opaque ? 1 : 0;
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
var sy = y;
var sx = x;
var dstOff = (y * w + x) * 4;
var r = 0,
g = 0,
b = 0,
a = 0;
for (var cy = 0; cy < side; cy++) {
var scy = Math.min(sh - 1, Math.max(0, sy + cy - halfSide));
var scx = sx;
var srcOff = (scy * sw + scx) * 4;
var wt = weightsVector[cy];
r += src[srcOff] * wt;
g += src[srcOff + 1] * wt;
b += src[srcOff + 2] * wt;
a += src[srcOff + 3] * wt;
}
dst[dstOff] = r;
dst[dstOff + 1] = g;
dst[dstOff + 2] = b;
dst[dstOff + 3] = a + alphaFac * (255 - a);
}
}
return output;
};
/***/ }),
/* 30 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createImageData = createImageData;
var tmpCtx = null;
if (typeof document != 'undefined') {
tmpCtx = document.createElement('canvas').getContext('2d');
} else if (typeof wx !== 'undefined' && wx.createCanvas) {
tmpCtx = wx.createCanvas().getContext('2d');
}
function createImageData(w, h) {
return tmpCtx.createImageData(w, h);
}
/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _group = __webpack_require__(1);
var _group2 = _interopRequireDefault(_group);
var _graphics = __webpack_require__(3);
var _graphics2 = _interopRequireDefault(_graphics);
var _render = __webpack_require__(8);
var _render2 = _interopRequireDefault(_render);
var _event = __webpack_require__(7);
var _event2 = _interopRequireDefault(_event);
var _sprite = __webpack_require__(6);
var _sprite2 = _interopRequireDefault(_sprite);
var _bitmap = __webpack_require__(4);
var _bitmap2 = _interopRequireDefault(_bitmap);
var _text = __webpack_require__(5);
var _text2 = _interopRequireDefault(_text);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var HitRender = function (_Render) {
_inherits(HitRender, _Render);
function HitRender() {
_classCallCheck(this, HitRender);
var _this = _possibleConstructorReturn(this, (HitRender.__proto__ || Object.getPrototypeOf(HitRender)).call(this));
if (typeof wx !== 'undefined' && wx.createCanvas) {
_this.canvas = wx.createCanvas();
} else {
_this.canvas = document.createElement('canvas');
}
_this.canvas.width = 1;
_this.canvas.height = 1;
_this.ctx = _this.canvas.getContext('2d');
// debug event
// this.canvas.width = 441
// this.canvas.height = 441
// this.ctx = this.canvas.getContext('2d')
// document.body.appendChild(this.canvas)
_this.disableEvents = ['mouseover', 'mouseout', 'mousemove', 'touchmove'];
return _this;
}
_createClass(HitRender, [{
key: 'clear',
value: function clear() {
this.ctx.clearRect(0, 0, this.width, this.height);
}
}, {
key: 'hitAABB',
value: function hitAABB(o, evt) {
var list = o.children.slice(0),
l = list.length;
for (var i = l - 1; i >= 0; i--) {
var child = list[i];
// if (!this.isbindingEvent(child)) continue;
var target = this._hitAABB(child, evt);
if (target) return target;
}
}
}, {
key: '_hitAABB',
value: function _hitAABB(o, evt) {
if (!o.isVisible()) {
return;
}
if (o instanceof _group2.default) {
var list = o.children.slice(0),
l = list.length;
for (var i = l - 1; i >= 0; i--) {
var child = list[i];
var target = this._hitAABB(child, evt);
if (target) return target;
}
} else {
if (o.AABB && this.checkPointInAABB(evt.stageX, evt.stageY, o.AABB)) {
// this._bubbleEvent(o, type, evt);
this._dispatchEvent(o, evt);
return o;
}
}
}
}, {
key: 'checkPointInAABB',
value: function checkPointInAABB(x, y, AABB) {
var minX = AABB[0];
if (x < minX) return false;
var minY = AABB[1];
if (y < minY) return false;
var maxX = minX + AABB[2];
if (x > maxX) return false;
var maxY = minY + AABB[3];
if (y > maxY) return false;
return true;
}
}, {
key: 'hitPixel',
value: function hitPixel(o, evt) {
var ctx = this.ctx;
//CanvasRenderingContext2D.restore() 是 Canvas 2D API 通过在绘图状态栈中弹出顶端的状态,将 canvas 恢复到最近的保存状态的方法。 如果没有保存状态,此方法不做任何改变。
//避免 save restore嵌套导致的 clip 区域影响 clearRect 擦除的区域
ctx.restore();
ctx.clearRect(0, 0, 2, 2);
var mtx = o._hitMatrix;
var list = o.children.slice(0),
l = list.length;
for (var i = l - 1; i >= 0; i--) {
var child = list[i];
mtx.initialize(1, 0, 0, 1, 0, 0);
mtx.appendTransform(o.x - evt.stageX, o.y - evt.stageY, o.scaleX, o.scaleY, o.rotation, o.skewX, o.skewY, o.originX, o.originY);
// if (!this.checkBoundEvent(child)) continue
ctx.save();
var target = this._hitPixel(child, evt, mtx);
ctx.restore();
if (target) return target;
}
}
}, {
key: '_hitPixel',
value: function _hitPixel(o, evt, mtx) {
if (!o.isVisible()) return;
var ctx = this.ctx;
if (mtx && !o.fixed) {
o._hitMatrix.initialize(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx, mtx.ty);
} else {
o._hitMatrix.initialize(1, 0, 0, 1, 0, 0);
}
mtx = o._hitMatrix;
mtx.appendTransform(o.x, o.y, o.scaleX, o.scaleY, o.rotation, o.skewX, o.skewY, o.originX, o.originY);
var ocg = o.clipGraphics;
if (ocg) {
ctx.beginPath();
ocg._matrix.copy(mtx);
ocg._matrix.appendTransform(ocg.x, ocg.y, ocg.scaleX, ocg.scaleY, ocg.rotation, ocg.skewX, ocg.skewY, ocg.originX, ocg.originY);
ctx.setTransform(ocg._matrix.a, ocg._matrix.b, ocg._matrix.c, ocg._matrix.d, ocg._matrix.tx, ocg._matrix.ty);
ocg.render(ctx);
ctx.clip(o.clipRuleNonzero ? 'nonzero' : 'evenodd');
}
if (o.cacheCanvas) {
ctx.setTransform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx, mtx.ty);
ctx.drawImage(o.cacheCanvas, o._cacheData.x, o._cacheData.y);
} else if (o instanceof _group2.default) {
var list = o.children.slice(0),
l = list.length;
for (var i = l - 1; i >= 0; i--) {
ctx.save();
var target = this._hitPixel(list[i], evt, mtx);
if (target) return target;
ctx.restore();
}
} else {
ctx.setTransform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx, mtx.ty);
if (o instanceof _graphics2.default) {
ctx.globalCompositeOperation = o.complexCompositeOperation;
ctx.globalAlpha = o.complexAlpha;
o.render(ctx);
} else if (o instanceof _sprite2.default && o.rect) {
ctx.globalCompositeOperation = o.complexCompositeOperation;
ctx.globalAlpha = o.complexAlpha;
o.updateFrame();
var rect = o.rect;
ctx.drawImage(o.img, rect[0], rect[1], rect[2], rect[3], 0, 0, rect[2], rect[3]);
} else if (o instanceof _bitmap2.default && o.rect) {
ctx.globalCompositeOperation = o.complexCompositeOperation;
ctx.globalAlpha = o.complexAlpha;
var bRect = o.rect;
ctx.drawImage(o.img, bRect[0], bRect[1], bRect[2], bRect[3], 0, 0, bRect[2], bRect[3]);
} else if (o instanceof _text2.default) {
ctx.globalCompositeOperation = o.complexCompositeOperation;
ctx.globalAlpha = o.complexAlpha;
ctx.font = o.font;
ctx.fillStyle = o.color;
ctx.textBaseline = o.baseline;
ctx.fillText(o.text, 0, 0);
}
}
if (ctx.getImageData(0, 0, 1, 1).data[3] > 1) {
this._dispatchEvent(o, evt);
return o;
}
}
}, {
key: '_dispatchEvent',
value: function _dispatchEvent(obj, evt) {
if (this.disableEvents.indexOf(evt.type) !== -1) return;
var mockEvt = new _event2.default();
mockEvt.stageX = evt.stageX;
mockEvt.stageY = evt.stageY;
mockEvt.pureEvent = evt;
mockEvt.type = evt.type;
obj.dispatchEvent(mockEvt);
}
}]);
return HitRender;
}(_render2.default);
exports.default = HitRender;
/***/ }),
/* 32 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _graphics = __webpack_require__(3);
var _graphics2 = _interopRequireDefault(_graphics);
var _render = __webpack_require__(8);
var _render2 = _interopRequireDefault(_render);
var _event = __webpack_require__(7);
var _event2 = _interopRequireDefault(_event);
var _sprite = __webpack_require__(6);
var _sprite2 = _interopRequireDefault(_sprite);
var _bitmap = __webpack_require__(4);
var _bitmap2 = _interopRequireDefault(_bitmap);
var _text = __webpack_require__(5);
var _text2 = _interopRequireDefault(_text);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var WxHitRender = function (_Render) {
_inherits(WxHitRender, _Render);
function WxHitRender(ctx, component, canvasId) {
_classCallCheck(this, WxHitRender);
var _this = _possibleConstructorReturn(this, (WxHitRender.__proto__ || Object.getPrototypeOf(WxHitRender)).call(this));
_this.ctx = ctx;
_this._isWeapp = true;
_this._component = component;
_this._hitCanvasId = canvasId + 'Hit';
_this.disableEvents = ['mouseover', 'mouseout', 'mousemove', 'touchmove'];
return _this;
}
_createClass(WxHitRender, [{
key: 'clear',
value: function clear() {
this.ctx.clearRect(0, 0, 2, 2);
}
}, {
key: 'hitAABB',
value: function hitAABB(list, evt, cb) {
var len = list.length;
for (var i = len - 1; i >= 0; i--) {
var o = list[i];
if (o.AABB && this.checkPointInAABB(evt.stageX, evt.stageY, o.AABB)) {
this._dispatchEvent(o, evt);
cb(o);
return o;
}
}
}
}, {
key: 'checkPointInAABB',
value: function checkPointInAABB(x, y, AABB) {
var minX = AABB[0];
if (x < minX) return false;
var minY = AABB[1];
if (y < minY) return false;
var maxX = minX + AABB[2];
if (x > maxX) return false;
var maxY = minY + AABB[3];
if (y > maxY) return false;
return true;
}
}, {
key: 'hit',
value: function hit(list, evt, cb, current) {
var _this2 = this;
var ctx = this.ctx;
var obj = list[current];
var mtx = obj._hitMatrix.initialize(1, 0, 0, 1, 0, 0);
ctx.save();
mtx.appendTransform(obj.x - evt.stageX, obj.y - evt.stageY, obj.scaleX, obj.scaleY, obj.rotation, obj.skewX, obj.skewY, obj.originX, obj.originY);
ctx.globalCompositeOperation = obj.complexCompositeOperation;
ctx.globalAlpha = obj.complexAlpha;
ctx.setTransform(mtx.a, mtx.b, mtx.c, mtx.d, mtx.tx, mtx.ty);
if (obj instanceof _graphics2.default) {
obj.render(ctx);
} else if (obj instanceof _sprite2.default && obj.rect) {
obj.updateFrame();
var rect = obj.rect;
ctx.drawImage(obj.img, rect[0], rect[1], rect[2], rect[3], 0, 0, rect[2], rect[3]);
} else if (obj instanceof _bitmap2.default && obj.rect) {
var bRect = obj.rect;
ctx.drawImage(obj.img, bRect[0], bRect[1], bRect[2], bRect[3], 0, 0, bRect[2], bRect[3]);
} else if (obj instanceof _text2.default) {
ctx.font = obj.font;
ctx.fillStyle = obj.color;
ctx.fillText(obj.text, 0, 0);
}
ctx.restore();
current--;
ctx.draw(false, function () {
wx.canvasGetImageData({
canvasId: _this2._hitCanvasId,
x: 0,
y: 0,
width: 1,
height: 1,
success: function success(res) {
if (res.data[3] > 1) {
_this2._dispatchEvent(obj, evt);
cb(obj);
} else {
if (current > -1) {
_this2.hit(list, evt, cb, current);
}
}
}
}, _this2._component);
});
}
}, {
key: '_dispatchEvent',
value: function _dispatchEvent(obj, evt) {
if (this.disableEvents.indexOf(evt.type) !== -1) return;
var mockEvt = new _event2.default();
mockEvt.stageX = evt.stageX;
mockEvt.stageY = evt.stageY;
mockEvt.pureEvent = evt;
mockEvt.type = evt.type;
obj.dispatchEvent(mockEvt);
}
}]);
return WxHitRender;
}(_render2.default);
exports.default = WxHitRender;
/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _shape = __webpack_require__(0);
var _shape2 = _interopRequireDefault(_shape);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ArrowPath = function (_Shape) {
_inherits(ArrowPath, _Shape);
function ArrowPath(path, option) {
_classCallCheck(this, ArrowPath);
var _this = _possibleConstructorReturn(this, (ArrowPath.__proto__ || Object.getPrototypeOf(ArrowPath)).call(this));
_this.path = path;
_this.option = Object.assign({
strokeStyle: 'black',
lineWidth: 1,
headSize: 10
}, option);
return _this;
}
_createClass(ArrowPath, [{
key: 'draw',
value: function draw() {
var path = this.path;
this.beginPath();
var len = path.length;
if (len === 2) {
this.drawArrow(path[0].x, path[0].y, path[1].x, path[1].y, 30);
} else {
this.moveTo(path[0].x, path[0].y);
for (var i = 1; i < len - 1; i++) {
this.lineTo(path[i].x, path[i].y);
}
this.drawArrow(path[len - 2].x, path[len - 2].y, path[len - 1].x, path[len - 1].y, 30);
}
this.stroke();
}
}, {
key: 'drawArrow',
value: function drawArrow(fromX, fromY, toX, toY, theta) {
var angle = Math.atan2(fromY - toY, fromX - toX) * 180 / Math.PI,
angle1 = (angle + theta) * Math.PI / 180,
angle2 = (angle - theta) * Math.PI / 180,
hs = this.option.headSize,
topX = hs * Math.cos(angle1),
topY = hs * Math.sin(angle1),
botX = hs * Math.cos(angle2),
botY = hs * Math.sin(angle2);
var arrowX = fromX - topX,
arrowY = fromY - topY;
this.moveTo(arrowX, arrowY);
this.moveTo(fromX, fromY);
this.lineTo(toX, toY);
arrowX = toX + topX;
arrowY = toY + topY;
this.moveTo(arrowX, arrowY);
this.lineTo(toX, toY);
arrowX = toX + botX;
arrowY = toY + botY;
this.lineTo(arrowX, arrowY);
this.strokeStyle(this.option.strokeStyle);
this.lineWidth(this.option.lineWidth);
}
}]);
return ArrowPath;
}(_shape2.default);
exports.default = ArrowPath;
/***/ }),
/* 34 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _shape = __webpack_require__(0);
var _shape2 = _interopRequireDefault(_shape);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Ellipse = function (_Shape) {
_inherits(Ellipse, _Shape);
function Ellipse(width, height, option) {
_classCallCheck(this, Ellipse);
var _this = _possibleConstructorReturn(this, (Ellipse.__proto__ || Object.getPrototypeOf(Ellipse)).call(this));
_this.option = option || {};
_this.width = width;
_this.height = height;
return _this;
}
_createClass(Ellipse, [{
key: 'draw',
value: function draw() {
var w = this.width;
var h = this.height;
var k = 0.5522848;
var ox = w / 2 * k;
var oy = h / 2 * k;
var xe = w;
var ye = h;
var xm = w / 2;
var ym = h / 2;
this.beginPath();
this.moveTo(0, ym);
this.bezierCurveTo(0, ym - oy, xm - ox, 0, xm, 0);
this.bezierCurveTo(xm + ox, 0, xe, ym - oy, xe, ym);
this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
this.bezierCurveTo(xm - ox, ye, 0, ym + oy, 0, ym);
if (this.option.strokeStyle) {
if (this.option.lineWidth !== undefined) {
this.lineWidth(this.option.lineWidth);
}
this.strokeStyle(this.option.strokeStyle);
this.stroke();
}
if (this.option.fillStyle) {
this.fillStyle(this.option.fillStyle);
this.fill();
}
}
}]);
return Ellipse;
}(_shape2.default);
exports.default = Ellipse;
/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _pathParser = __webpack_require__(36);
var _pathParser2 = _interopRequireDefault(_pathParser);
var _shape = __webpack_require__(0);
var _shape2 = _interopRequireDefault(_shape);
var _arcToBezier = __webpack_require__(37);
var _arcToBezier2 = _interopRequireDefault(_arcToBezier);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Path = function (_Shape) {
_inherits(Path, _Shape);
function Path(d, option) {
_classCallCheck(this, Path);
var _this = _possibleConstructorReturn(this, (Path.__proto__ || Object.getPrototypeOf(Path)).call(this));
_this.d = d;
option = Object.assign({
fillStyle: 'black',
strokeStyle: 'black',
lineWidth: 1
}, option);
_this.option = option;
return _this;
}
_createClass(Path, [{
key: 'draw',
value: function draw() {
var _this2 = this;
var cmds = (0, _pathParser2.default)(this.d);
this.beginPath();
// https://developer.mozilla.org/zh-CN/docs/Web/SVG/Tutorial/Paths
// M = moveto
// L = lineto
// H = horizontal lineto
// V = vertical lineto
// C = curveto
// S = smooth curveto
// Q = quadratic Belzier curve
// T = smooth quadratic Belzier curveto
// A = elliptical Arc 暂时未实现,用贝塞尔拟合椭圆
// Z = closepath
// 以上所有命令均允许小写字母。大写表示绝对定位,小写表示相对定位(从上一个点开始)。
var preX = void 0,
preY = void 0,
curves = void 0,
lastCurve = void 0;
// 参考我的 pasition https://github.com/AlloyTeam/pasition/blob/master/src/index.js
for (var j = 0, cmdLen = cmds.length; j < cmdLen; j++) {
var item = cmds[j];
var action = item[0];
var preItem = cmds[j - 1];
switch (action) {
case 'M':
preX = item[1];
preY = item[2];
this.moveTo(preX, preY);
break;
case 'L':
preX = item[1];
preY = item[2];
this.lineTo(preX, preY);
break;
case 'H':
preX = item[1];
this.lineTo(preX, preY);
break;
case 'V':
preY = item[1];
this.lineTo(preX, preY);
break;
case 'C':
preX = item[5];
preY = item[6];
this.bezierCurveTo(item[1], item[2], item[3], item[4], preX, preY);
break;
case 'S':
if (preItem[0] === 'C' || preItem[0] === 'c') {
this.bezierCurveTo(preX, preY, preX + preItem[5] - preItem[3], preY + preItem[6] - preItem[4], item[1], item[2], item[3], item[4]);
} else if (preItem[0] === 'S' || preItem[0] === 's') {
this.bezierCurveTo(preX, preY, preX + preItem[3] - preItem[1], preY + preItem[4] - preItem[2], item[1], item[2], item[3], item[4]);
}
preX = item[3];
preY = item[4];
break;
case 'Q':
preX = item[3];
preY = item[4];
this.quadraticCurveTo(item[1], item[2], preX, preY);
break;
case 'm':
preX += item[1];
preY += item[2];
this.moveTo(preX, preY);
break;
case 'l':
preX += item[1];
preY += item[2];
this.lineTo(preX, preY);
break;
case 'h':
preX += item[1];
this.lineTo(preX, preY);
break;
case 'v':
preY += item[1];
this.lineTo(preX, preY);
break;
case 'c':
this.bezierCurveTo(preX + item[1], preY + item[2], preX + item[3], preY + item[4], preX + item[5], preY + item[6]);
preX = preX + item[5];
preY = preY + item[6];
break;
case 's':
if (preItem[0] === 'C' || preItem[0] === 'c') {
this.bezierCurveTo(preX, preY, preX + preItem[5] - preItem[3], preY + preItem[6] - preItem[4], preX + item[1], preY + item[2], preX + item[3], preY + item[4]);
} else if (preItem[0] === 'S' || preItem[0] === 's') {
this.bezierCurveTo(preX, preY, preX + preItem[3] - preItem[1], preY + preItem[4] - preItem[2], preX + item[1], preY + item[2], preX + item[3], preY + item[4]);
}
preX += item[3];
preY += item[4];
break;
case 'q':
this.quadraticCurveTo(preX + item[1], preY + item[2], item[3] + preX, item[4] + preY);
preX += item[3];
preY += item[4];
break;
case 'Z':
this.closePath();
break;
case 'z':
this.closePath();
break;
case 'a':
curves = (0, _arcToBezier2.default)({
rx: item[1],
ry: item[2],
px: preX,
py: preY,
xAxisRotation: item[3],
largeArcFlag: item[4],
sweepFlag: item[5],
cx: preX + item[6],
cy: preX + item[7]
});
lastCurve = curves[curves.length - 1];
curves.forEach(function (curve, index) {
if (index === 0) {
_this2.bezierCurveTo(preX, preY, curve.x1, curve.y1, curve.x2, curve.y2, curve.x, curve.y);
} else {
_this2.bezierCurveTo(curves[index - 1].x, curves[index - 1].y, curve.x1, curve.y1, curve.x2, curve.y2, curve.x, curve.y);
}
});
preX = lastCurve.x;
preY = lastCurve.y;
break;
case 'A':
curves = (0, _arcToBezier2.default)({
rx: item[1],
ry: item[2],
px: preX,
py: preY,
xAxisRotation: item[3],
largeArcFlag: item[4],
sweepFlag: item[5],
cx: item[6],
cy: item[7]
});
lastCurve = curves[curves.length - 1];
curves.forEach(function (curve, index) {
if (index === 0) {
_this2.bezierCurveTo(preX, preY, curve.x1, curve.y1, curve.x2, curve.y2, curve.x, curve.y);
} else {
_this2.bezierCurveTo(curves[index - 1].x, curves[index - 1].y, curve.x1, curve.y1, curve.x2, curve.y2, curve.x, curve.y);
}
});
preX = lastCurve.x;
preY = lastCurve.y;
break;
case 'T':
if (preItem[0] === 'Q' || preItem[0] === 'q') {
preCX = preX + preItem[3] - preItem[1];
preCY = preY + preItem[4] - preItem[2];
this.quadraticCurveTo(preX, preY, preCX, preCY, item[1], item[2]);
} else if (preItem[0] === 'T' || preItem[0] === 't') {
this.quadraticCurveTo(preX, preY, preX + preX - preCX, preY + preY - preCY, item[1], item[2]);
preCX = preX + preX - preCX;
preCY = preY + preY - preCY;
}
preX = item[1];
preY = item[2];
break;
case 't':
if (preItem[0] === 'Q' || preItem[0] === 'q') {
preCX = preX + preItem[3] - preItem[1];
preCY = preY + preItem[4] - preItem[2];
this.quadraticCurveTo(preX, preY, preCX, preCY, preX + item[1], preY + item[2]);
} else if (preItem[0] === 'T' || preItem[0] === 't') {
this.quadraticCurveTo(preX, preY, preX + preX - preCX, preY + preY - preCY, preX + item[1], preY + item[2]);
preCX = preX + preX - preCX;
preCY = preY + preY - preCY;
}
preX += item[1];
preY += item[2];
break;
}
}
if (this.option.fillStyle) {
this.fillStyle(this.option.fillStyle);
this.fill();
}
if (this.option.strokeStyle) {
this.lineWidth(this.option.lineWidth);
this.strokeStyle(this.option.strokeStyle);
this.stroke();
}
}
}]);
return Path;
}(_shape2.default);
exports.default = Path;
/***/ }),
/* 36 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
// https://github.com/jkroso/parse-svg-path/blob/master/index.js
/**
* expected argument lengths
* @type {Object}
*/
var length = { a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0
/**
* segment pattern
* @type {RegExp}
*/
};var segment = /([astvzqmhlc])([^astvzqmhlc]*)/ig;
/**
* parse an svg path data string. Generates an Array
* of commands where each command is an Array of the
* form `[command, arg1, arg2, ...]`
*
* @param {String} path
* @return {Array}
*/
function parse(path) {
var data = [];
path.replace(segment, function (_, command, args) {
var type = command.toLowerCase();
args = parseValues(args);
// overloaded moveTo
if (type === 'm' && args.length > 2) {
data.push([command].concat(args.splice(0, 2)));
type = 'l';
command = command === 'm' ? 'l' : 'L';
}
while (true) {
if (args.length === length[type]) {
args.unshift(command);
return data.push(args);
}
if (args.length < length[type]) throw new Error('malformed path data');
data.push([command].concat(args.splice(0, length[type])));
}
});
return data;
}
var number = /-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig;
function parseValues(args) {
var numbers = args.match(number);
return numbers ? numbers.map(Number) : [];
}
exports.default = parse;
/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
//https://github.com/colinmeinke/svg-arc-to-cubic-bezier
var TAU = Math.PI * 2;
var mapToEllipse = function mapToEllipse(_ref, rx, ry, cosphi, sinphi, centerx, centery) {
var x = _ref.x,
y = _ref.y;
x *= rx;
y *= ry;
var xp = cosphi * x - sinphi * y;
var yp = sinphi * x + cosphi * y;
return {
x: xp + centerx,
y: yp + centery
};
};
var approxUnitArc = function approxUnitArc(ang1, ang2) {
var a = 4 / 3 * Math.tan(ang2 / 4);
var x1 = Math.cos(ang1);
var y1 = Math.sin(ang1);
var x2 = Math.cos(ang1 + ang2);
var y2 = Math.sin(ang1 + ang2);
return [{
x: x1 - y1 * a,
y: y1 + x1 * a
}, {
x: x2 + y2 * a,
y: y2 - x2 * a
}, {
x: x2,
y: y2
}];
};
var vectorAngle = function vectorAngle(ux, uy, vx, vy) {
var sign = ux * vy - uy * vx < 0 ? -1 : 1;
var umag = Math.sqrt(ux * ux + uy * uy);
var vmag = Math.sqrt(ux * ux + uy * uy);
var dot = ux * vx + uy * vy;
var div = dot / (umag * vmag);
if (div > 1) {
div = 1;
}
if (div < -1) {
div = -1;
}
return sign * Math.acos(div);
};
var getArcCenter = function getArcCenter(px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp) {
var rxsq = Math.pow(rx, 2);
var rysq = Math.pow(ry, 2);
var pxpsq = Math.pow(pxp, 2);
var pypsq = Math.pow(pyp, 2);
var radicant = rxsq * rysq - rxsq * pypsq - rysq * pxpsq;
if (radicant < 0) {
radicant = 0;
}
radicant /= rxsq * pypsq + rysq * pxpsq;
radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1);
var centerxp = radicant * rx / ry * pyp;
var centeryp = radicant * -ry / rx * pxp;
var centerx = cosphi * centerxp - sinphi * centeryp + (px + cx) / 2;
var centery = sinphi * centerxp + cosphi * centeryp + (py + cy) / 2;
var vx1 = (pxp - centerxp) / rx;
var vy1 = (pyp - centeryp) / ry;
var vx2 = (-pxp - centerxp) / rx;
var vy2 = (-pyp - centeryp) / ry;
var ang1 = vectorAngle(1, 0, vx1, vy1);
var ang2 = vectorAngle(vx1, vy1, vx2, vy2);
if (sweepFlag === 0 && ang2 > 0) {
ang2 -= TAU;
}
if (sweepFlag === 1 && ang2 < 0) {
ang2 += TAU;
}
return [centerx, centery, ang1, ang2];
};
var arcToBezier = function arcToBezier(_ref2) {
var px = _ref2.px,
py = _ref2.py,
cx = _ref2.cx,
cy = _ref2.cy,
rx = _ref2.rx,
ry = _ref2.ry,
_ref2$xAxisRotation = _ref2.xAxisRotation,
xAxisRotation = _ref2$xAxisRotation === undefined ? 0 : _ref2$xAxisRotation,
_ref2$largeArcFlag = _ref2.largeArcFlag,
largeArcFlag = _ref2$largeArcFlag === undefined ? 0 : _ref2$largeArcFlag,
_ref2$sweepFlag = _ref2.sweepFlag,
sweepFlag = _ref2$sweepFlag === undefined ? 0 : _ref2$sweepFlag;
var curves = [];
if (rx === 0 || ry === 0) {
return [];
}
var sinphi = Math.sin(xAxisRotation * TAU / 360);
var cosphi = Math.cos(xAxisRotation * TAU / 360);
var pxp = cosphi * (px - cx) / 2 + sinphi * (py - cy) / 2;
var pyp = -sinphi * (px - cx) / 2 + cosphi * (py - cy) / 2;
if (pxp === 0 && pyp === 0) {
return [];
}
rx = Math.abs(rx);
ry = Math.abs(ry);
var lambda = Math.pow(pxp, 2) / Math.pow(rx, 2) + Math.pow(pyp, 2) / Math.pow(ry, 2);
if (lambda > 1) {
rx *= Math.sqrt(lambda);
ry *= Math.sqrt(lambda);
}
var _getArcCenter = getArcCenter(px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp),
_getArcCenter2 = _slicedToArray(_getArcCenter, 4),
centerx = _getArcCenter2[0],
centery = _getArcCenter2[1],
ang1 = _getArcCenter2[2],
ang2 = _getArcCenter2[3];
var segments = Math.max(Math.ceil(Math.abs(ang2) / (TAU / 4)), 1);
ang2 /= segments;
for (var i = 0; i < segments; i++) {
curves.push(approxUnitArc(ang1, ang2));
ang1 += ang2;
}
return curves.map(function (curve) {
var _mapToEllipse = mapToEllipse(curve[0], rx, ry, cosphi, sinphi, centerx, centery),
x1 = _mapToEllipse.x,
y1 = _mapToEllipse.y;
var _mapToEllipse2 = mapToEllipse(curve[1], rx, ry, cosphi, sinphi, centerx, centery),
x2 = _mapToEllipse2.x,
y2 = _mapToEllipse2.y;
var _mapToEllipse3 = mapToEllipse(curve[2], rx, ry, cosphi, sinphi, centerx, centery),
x = _mapToEllipse3.x,
y = _mapToEllipse3.y;
return { x1: x1, y1: y1, x2: x2, y2: y2, x: x, y: y };
});
};
exports.default = arcToBezier;
/***/ }),
/* 38 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _group = __webpack_require__(1);
var _group2 = _interopRequireDefault(_group);
var _text = __webpack_require__(5);
var _text2 = _interopRequireDefault(_text);
var _roundedRect = __webpack_require__(15);
var _roundedRect2 = _interopRequireDefault(_roundedRect);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Button = function (_Group) {
_inherits(Button, _Group);
function Button(option) {
_classCallCheck(this, Button);
var _this = _possibleConstructorReturn(this, (Button.__proto__ || Object.getPrototypeOf(Button)).call(this));
_this.width = option.width;
_this.roundedRect = new _roundedRect2.default(option.width, option.height, option.borderRadius, {
strokeStyle: option.borderColor || 'black',
fillStyle: option.backgroundColor || '#F5F5F5'
});
_this.text = new _text2.default(option.text, {
font: option.font,
color: option.color
});
_this.text.x = option.width / 2 - _this.text.getWidth() / 2 * _this.text.scaleX + (option.textX || 0);
_this.text.y = option.height / 2 - 10 + 5 * _this.text.scaleY + (option.textY || 0);
_this.add(_this.roundedRect, _this.text);
return _this;
}
return Button;
}(_group2.default);
exports.default = Button;
/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _shape = __webpack_require__(0);
var _shape2 = _interopRequireDefault(_shape);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Rect = function (_Shape) {
_inherits(Rect, _Shape);
function Rect(width, height, option) {
_classCallCheck(this, Rect);
var _this = _possibleConstructorReturn(this, (Rect.__proto__ || Object.getPrototypeOf(Rect)).call(this));
_this.width = width;
_this.height = height;
_this.option = option || {};
return _this;
}
_createClass(Rect, [{
key: 'draw',
value: function draw() {
if (this.option.fillStyle) {
this.fillStyle(this.option.fillStyle);
this.fillRect(0, 0, this.width, this.height);
}
if (this.option.strokeStyle) {
this.strokeStyle(this.option.strokeStyle);
this.strokeRect(0, 0, this.width, this.height);
}
}
}]);
return Rect;
}(_shape2.default);
exports.default = Rect;
/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _shape = __webpack_require__(0);
var _shape2 = _interopRequireDefault(_shape);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Circle = function (_Shape) {
_inherits(Circle, _Shape);
function Circle(r, option) {
_classCallCheck(this, Circle);
var _this = _possibleConstructorReturn(this, (Circle.__proto__ || Object.getPrototypeOf(Circle)).call(this));
_this.option = option || {};
_this.r = r;
_this._dp = Math.PI * 2;
return _this;
}
_createClass(Circle, [{
key: 'draw',
value: function draw() {
this.beginPath();
this.arc(0, 0, this.r, 0, this._dp, false);
if (this.option.strokeStyle) {
if (this.option.lineWidth !== undefined) {
this.lineWidth(this.option.lineWidth);
}
this.strokeStyle(this.option.strokeStyle);
this.stroke();
}
if (this.option.fillStyle) {
this.fillStyle(this.option.fillStyle);
this.fill();
}
}
}]);
return Circle;
}(_shape2.default);
exports.default = Circle;
/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _shape = __webpack_require__(0);
var _shape2 = _interopRequireDefault(_shape);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Polygon = function (_Shape) {
_inherits(Polygon, _Shape);
function Polygon(vertex, options) {
_classCallCheck(this, Polygon);
var _this = _possibleConstructorReturn(this, (Polygon.__proto__ || Object.getPrototypeOf(Polygon)).call(this));
_this.vertex = vertex || [];
_this.options = options || {};
_this.strokeColor = _this.options.strokeColor;
_this.fillColor = _this.options.fillColor;
return _this;
}
_createClass(Polygon, [{
key: 'draw',
value: function draw() {
this.clear().beginPath();
this.strokeStyle(this.strokeColor);
this.moveTo(this.vertex[0][0], this.vertex[0][1]);
for (var i = 1, len = this.vertex.length; i < len; i++) {
this.lineTo(this.vertex[i][0], this.vertex[i][1]);
}
this.closePath();
// 路径闭合
// if (this.options.strokeStyle) {
// this.strokeStyle = strokeStyle;
// this.lineWidth(this.options.width);
// this.lineJoin('round');
// this.stroke();
// }
if (this.strokeColor) {
this.strokeStyle(this.strokeColor);
this.stroke();
}
if (this.fillColor) {
this.fillStyle(this.fillColor);
this.fill();
}
}
}]);
return Polygon;
}(_shape2.default);
exports.default = Polygon;
/***/ }),
/* 42 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
var _shape = __webpack_require__(0);
var _shape2 = _interopRequireDefault(_shape);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var EquilateralPolygon = function (_Shape) {
_inherits(EquilateralPolygon, _Shape);
function EquilateralPolygon(num, r, options) {
_classCallCheck(this, EquilateralPolygon);
var _this = _possibleConstructorReturn(this, (EquilateralPolygon.__proto__ || Object.getPrototypeOf(EquilateralPolygon)).call(this));
_this.num = num;
_this.r = r;
_this.options = options || {};
_this.strokeColor = options.strokeColor || 'black';
_this.vertex = [];
_this.initVertex();
return _this;
}
_createClass(EquilateralPolygon, [{
key: 'initVertex',
value: function initVertex() {
this.vertex.length = [];
var num = this.num;
var r = this.r;
var i = void 0,
startX = void 0,
startY = void 0,
newX = void 0,
newY = void 0;
if (num % 2 === 0) {
startX = r * Math.cos(2 * Math.PI * 0 / num);
startY = r * Math.sin(2 * Math.PI * 0 / num);
this.vertex.push([startX, startY]);
for (i = 1; i < num; i++) {
newX = r * Math.cos(2 * Math.PI * i / num);
newY = r * Math.sin(2 * Math.PI * i / num);
this.vertex.push([newX, newY]);
}
} else {
startX = r * Math.cos(2 * Math.PI * 0 / num - Math.PI / 2);
startY = r * Math.sin(2 * Math.PI * 0 / num - Math.PI / 2);
this.vertex.push([startX, startY]);
for (i = 1; i < num; i++) {
newX = r * Math.cos(2 * Math.PI * i / num - Math.PI / 2);
newY = r * Math.sin(2 * Math.PI * i / num - Math.PI / 2);
this.vertex.push([newX, newY]);
}
}
}
}, {
key: 'draw',
value: function draw() {
this.beginPath();
this.strokeStyle(this.strokeColor);
this.moveTo(this.vertex[0][0], this.vertex[0][1]);
for (var i = 1, len = this.vertex.length; i < len; i++) {
this.lineTo(this.vertex[i][0], this.vertex[i][1]);
}
this.closePath();
// 路径闭合
// if (this.options.strokeStyle) {
// this.strokeStyle = strokeStyle;
// this.lineWidth(this.options.width);
// this.lineJoin('round');
this.stroke();
// }
if (this.options.fillStyle) {
this.fillStyle(this.options.fillStyle);
this.fill();
}
}
}]);
return EquilateralPolygon;
}(_shape2.default);
exports.default = EquilateralPolygon;
/***/ })
/******/ ]); |
"use strict";
angular.module('swamp.services').service('swampManager', [
'$rootScope', 'EVENTS', 'LOG_TYPE', 'serializeService', 'aggregatedDataFactory', 'AGGREGATED_LIST_TYPE', 'SOCKET_EVENTS', 'CLIENT_REQUEST',
function($rootScope, EVENTS, LOG_TYPE, serializeService, aggregatedDataFactory, AGGREGATED_LIST_TYPE, SOCKET_EVENTS, CLIENT_REQUEST) {
this.outLogData = null;
this.errorLogData = null;
this._info = {
totalmem: 0,
mode: '*'
};
this._commands = [];
this._commandsExecution = [];
this._presets = [];
this.getInfo = function() {
return this._info;
};
this.getCommands = function() {
return this._commands;
};
this.getCommandsExecution = function() {
return this._commandsExecution;
};
this.getPresets = function() {
return this._presets;
};
this.runPreset = function(preset) {
$rootScope.$broadcast(SOCKET_EVENTS.RUN_PRESET, { id: preset.id });
};
this.createPreset = function(presetDefinition) {
$rootScope.$broadcast(SOCKET_EVENTS.CREATE_PRESET, { preset: presetDefinition });
};
this.deletePreset = function(presetId) {
$rootScope.$broadcast(SOCKET_EVENTS.DELETE_PRESET, { presetId: presetId });
};
this.log = function(logType, log) {
var serialized = serializeService.serializeLogData(logType, log);
switch(logType) {
case LOG_TYPE.OUT:
this.outLogData.add(serialized);
break;
case LOG_TYPE.ERROR:
this.errorLogData.add(serialized);
break;
}
};
this._createLogDataContainers = function() {
this.outLogData = aggregatedDataFactory.create(AGGREGATED_LIST_TYPE.FIFO);
this.errorLogData = aggregatedDataFactory.create(AGGREGATED_LIST_TYPE.FIFO);
};
this.initialize = function() {
this._createLogDataContainers();
};
function _onSwampOut(event, log) {
this.log(LOG_TYPE.OUT, log);
};
function _onSwampError(event, log) {
this.log(LOG_TYPE.ERROR, log);
};
function _setSwampLogs(logs) {
var self = this;
if(logs) {
_.forEach(logs.out || [], function(log) {
self.log(LOG_TYPE.OUT, log);
});
_.forEach(logs.err || [], function(log) {
self.log(LOG_TYPE.ERROR, log);
});
}
}
function _setSwampInfo(info) {
if(info) {
_.extend(this._info, info);
}
}
function _setSwampCommands(commands) {
if(commands && commands.definitions) {
this._commands = commands.definitions;
}
if(commands && commands.executions) {
_.pushAll(this._commandsExecution, commands.executions);
}
}
function _setSwampPresets(presets) {
if(presets) {
_.pushAll(this._presets, presets);
}
}
function _onSwampDataReceived(event, swampData, commands, presets) {
_setSwampLogs.call(this, swampData.logs);
_setSwampInfo.call(this, swampData.info);
_setSwampCommands.call(this, commands);
_setSwampPresets.call(this, presets);
$rootScope.$broadcast(EVENTS.SWAMP_MANAGER_INITIALIZED);
}
function _getExecutionCommandById(id) {
return _.where(this._commandsExecution, function(execution) {
return execution.id == id;
})[0];
}
function _onCommandStarted(event, data) {
var execution = _getExecutionCommandById.call(this, data.exeId);
if(!execution) {
this._commandsExecution.push(data.command);
}
}
function _onCommandOut(event, data) {
var execution = _getExecutionCommandById.call(this, data.exeId);
if(execution) {
execution.log.push(data.log)
}
}
function _onCommandDisposed(event, data) {
var execution = _getExecutionCommandById.call(this, data.exeId);
if(execution) {
execution.disposed = true;
execution.success = data.success;
}
}
function _onClientRequestCommandTermination(event, exeId) {
$rootScope.$broadcast(SOCKET_EVENTS.TERMINATE_COMMAND, { id: exeId });
}
function _onPresetCreated(event, preset) {
this._presets.push(preset);
}
function _onPresetDeleted(event, presetId) {
_.remove(this._presets, function(preset) { return preset.id == presetId });
}
$rootScope.$on(EVENTS.SWAMP_OUT, _onSwampOut.bind(this));
$rootScope.$on(EVENTS.SWAMP_ERROR, _onSwampError.bind(this));
$rootScope.$on(EVENTS.SWAMP_DATA_RECEIVED, _onSwampDataReceived.bind(this));
$rootScope.$on(EVENTS.COMMAND_STARTED, _onCommandStarted.bind(this));
$rootScope.$on(EVENTS.COMMAND_OUT, _onCommandOut.bind(this));
$rootScope.$on(EVENTS.COMMAND_DISPOSED, _onCommandDisposed.bind(this));
$rootScope.$on(EVENTS.PRESET_CREATED, _onPresetCreated.bind(this));
$rootScope.$on(EVENTS.PRESET_DELETED, _onPresetDeleted.bind(this));
$rootScope.$on(CLIENT_REQUEST.REQUEST_COMMAND_TERMINATION, _onClientRequestCommandTermination);
}]);
|
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('ember-interface', 'Integration | Component | ember interface', {
integration: true
});
test('it renders', function(assert) {
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.render(hbs`{{ember-interface}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:
this.render(hbs`
{{#ember-interface}}
template block text
{{/ember-interface}}
`);
assert.equal(this.$().text().trim(), 'template block text');
});
|
import { foreach } from "../../../func/util";
import { buildPlugin } from "../../../func/private";
import correctParam from "../../../correctParam";
import pluginBuilder from "../core";
import Loader from "../../../require/Loader";
function getGlobal ( globalName ) {
const globalObj = window [ globalName ];
delete window [ globalName ];
return globalObj;
}
export default function iife ( pluginDef, buildings ) {
const building = {};
buildings.push ( building );
// 该返回的函数将会在script的onload回调函数中执行
return () => {
const pluginObj = getGlobal ( pluginDef.global || pluginDef.name );
building.install = () => {
buildPlugin ( {
name: pluginDef.name,
build () {
return pluginObj;
}
}, {} );
};
};
} |
$(document).on('turbolinks:load', function() {
if (document.getElementById('cf0925')) {
// console.log('Setting up the item total calculations.');
var item_ids = [
'#cf0925_item_cost_1',
'#cf0925_item_cost_2',
'#cf0925_item_cost_3'
].join(', ');
update_item_total = function() {
// console.log('Updating the item total: ' + $('#cf0925_item_total').val());
$('#cf0925_item_total').val($(item_ids).toArray().reduce(function(a, b) {
// console.log('a, b: ', + a + ', ' + b.value);
return $.isNumeric(b.value)? a + Number(b.value.replace(/[,$]/g, "")): a;
}, 0).toFixed(2));
// console.log('Updated the item total: ' + $('#cf0925_item_total').val());
};
// console.log('item_ids: ' + item_ids);
$(item_ids).change(function() {
// console.log('Something changed');
update_item_total();
});
}
// console.log('Done setting up the item total calculations.');
});
|
/* jshint devel: true, indent: 2, undef: true, unused: strict, strict: false, eqeqeq: true, trailing: true, curly: true, latedef: true, quotmark: single, maxlen: 120 */
/* global define, $ */
define('views/login', ['chimera/global', 'backbone', 'chimera/template', 'chimera/page', 'chimera/authenticate'],
function (Chi, Backbone, Template, Page, Auth) {
var LoginView = Backbone.View.extend({
el: '#content',
template: new Template('login').base(),
events: {
'submit #login-form' : 'submit'
},
render: function () {
Page.changeTo(this.template({}), {
class: 'login'
});
$('input#identifier').focus();
return this;
},
submit: function (e) {
e.preventDefault();
var loginError = $('#login_error');
loginError.empty();
Auth.login($('input#identifier').val(), $('input#password').val(), {
success: function () {
Chi.Router.navigate('/', {trigger: true});
},
failure: function () {
loginError.html('Invalid login.');
}
});
}
});
return LoginView;
});
|
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("preview","sl",{preview:"Predogled"}); |
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
nodeunit: {
files: ['test/**/*-test.js'],
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
src: ['src/**/*.js']
},
test: {
src: ['test/**/*.js']
},
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
lib: {
files: '<%= jshint.lib.src %>',
tasks: ['jshint:lib', 'nodeunit']
},
test: {
files: '<%= jshint.test.src %>',
tasks: ['jshint:test', 'nodeunit']
},
},
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
// Default task.
grunt.registerTask('default', ['jshint', 'nodeunit']);
};
|
(function($) {
"use strict";
//windows load event
$(window).load(function() {
/* ---------------------------------------------------------------------- */
/* -------------------------- 01 - Preloader ---------------------------- */
/* ---------------------------------------------------------------------- */
$('#preloader').delay(20).fadeOut('slow');
/* ---------------------------------------------------------------------- */
/* ---------------------------- 02 - OwlCarousel ----------------------- */
/* ---------------------------------------------------------------------- */
/* latest */
$(".epi-carousel4").owlCarousel({
autoPlay: true,
items : 4,
pagination : false,
responsive : true,
itemsDesktop : [1199, 4],
itemsDesktopSmall : [979, 4],
itemsTablet : [768, 3],
itemsTabletSmall : [600, 3],
itemsMobile : [479, 3]
});
/* portfolio Logos */
$(".epi-carousel").owlCarousel({
autoPlay: true,
items : 1,
pagination : false,
navigation:true,
navigationText: [
"<span class='leftarrow'></span>",
"<span class='rightarrow'></span>"
],
responsive : false
});
});
/* -------------------------- 04 - Sticky ---------------------------- */
$(".sticky").sticky({topSpacing:0});
/* -------------------------- 06 - scrollToTop ------------------------- */
$(window).scroll(function(){
if ($(this).scrollTop() > 600) {
$('.scrollToTop').fadeIn();
} else {
$('.scrollToTop').fadeOut();
}
});
$('.scrollToTop').click(function(){
$('html, body').animate({scrollTop : 0},800);
return false;
});
/* ---------------------------------------------------------------------- */
/* -------------------------- search_btn ------------------------ */
/* ---------------------------------------------------------------------- */
$(".search_btn").click(function(){
if($(this).parent().hasClass('closed')){
$(this).parent().removeClass('closed');
$(this).parent().find('.btmsearch').slideDown(200);
} else {
$(this).parent().addClass('closed');
$(this).parent().find('.btmsearch').slideUp(200);
}
});
/* ---------------------------------------------------------------------- */
/* -------------------------- 10 - Fit Vids ----------------------------- */
/* ---------------------------------------------------------------------- */
$('#wrapper').fitVids();
/*----------------------------- selectpicker------------------*/
$('.selectpicker').selectpicker({
style: 'btn-info',
size: 4
});
/* ---------------------------------------------------------------------- */
/* -------------------------- 12 - Contact Form ------------------------- */
/* ---------------------------------------------------------------------- */
// Needed variables
var $contactform = $('#contact-form'),
$response = '';
// After contact form submit
$contactform.submit(function() {
// Hide any previous response text
$contactform.children(".alert").remove();
// Are all the fields filled in?
if (!$('#contact_name').val()) {
$response = '<div class="alert alert-danger">Please enter your name.</div>';
$('#contact_name').focus();
$contactform.prepend($response);
} else if (!$('#contact_message').val()) {
$response = '<div class="alert alert-danger">Please enter your message.</div>';
$('#contact_message').focus();
$contactform.prepend($response);
} else if (!$('#contact_email').val()) {
$response = '<div class="alert alert-danger">Please enter valid e-mail.</div>';
$('#contact_email').focus();
$contactform.prepend($response);
} else {
// Yes, submit the form to the PHP script via Ajax
$contactform.children('button[type="submit"]').button('loading');
$.ajax({
type: "POST",
url: "php/contact-form.php",
data: $(this).serialize(),
success: function(msg) {
if (msg == 'sent') {
$response = '<div class="alert alert-success">Your message has been sent. Thank you!</div>';
$contactform[0].reset();
} else {
$response = '<div class="alert alert-danger">' + msg + '</div>';
}
// Show response message
$contactform.prepend($response);
$contactform.children('button[type="submit"]').button('reset');
}
});
}
return false;
});
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("body").toggleClass("toggled");
});
/* ---------------------------------------------------------------------- */
/* -------------------------- bootstrap dropdown menu ----------------------------- */
/* ---------------------------------------------------------------------- */
$('.navbar .dropdown').hover(function() {
$(this).find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();
}, function() {
$(this).find('.dropdown-menu').first().stop(true, true).delay(100).slideUp();
});
$('.navbar a').click(function(){
location.href = this.href;
});
$('nav#menu').mmenu();
$("[name='my-checkbox']").bootstrapSwitch();
/* ---------------------------------------------------------------------- */
/* -------------------------- bootstrap tooltip ----------------------------- */
/* ---------------------------------------------------------------------- */
$('[data-toggle="tooltip"]').tooltip()
})(jQuery);
|
/**
* @fileoverview Validate closing bracket location in JSX
* @author Yannick Croissant
*/
'use strict';
// ------------------------------------------------------------------------------
// Requirements
// ------------------------------------------------------------------------------
var rule = require('../../../lib/rules/jsx-closing-bracket-location');
var RuleTester = require('eslint').RuleTester;
var MESSAGE_AFTER_PROPS = [{message: 'The closing bracket must be placed after the last prop'}];
var MESSAGE_AFTER_TAG = [{message: 'The closing bracket must be placed after the opening tag'}];
var MESSAGE_PROPS_ALIGNED = [{message: 'The closing bracket must be aligned with the last prop'}];
var MESSAGE_TAG_ALIGNED = [{message: 'The closing bracket must be aligned with the opening tag'}];
var MESSAGE_LINE_ALIGNED = [{message: 'The closing bracket must be aligned with the line containing the opening tag'}];
// ------------------------------------------------------------------------------
// Tests
// ------------------------------------------------------------------------------
var ruleTester = new RuleTester();
ruleTester.run('jsx-closing-bracket-location', rule, {
valid: [{
code: [
'<App />'
].join('\n'),
ecmaFeatures: {jsx: true}
}, {
code: [
'<App foo />'
].join('\n'),
ecmaFeatures: {jsx: true}
}, {
code: [
'<App ',
' foo',
'/>'
].join('\n'),
ecmaFeatures: {jsx: true}
}, {
code: [
'<App foo />'
].join('\n'),
options: [{location: 'after-props'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'<App foo />'
].join('\n'),
options: [{location: 'tag-aligned'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'<App foo />'
].join('\n'),
options: [{location: 'line-aligned'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'<App ',
' foo />'
].join('\n'),
options: ['after-props'],
ecmaFeatures: {jsx: true}
}, {
code: [
'<App ',
' foo',
' />'
].join('\n'),
options: ['props-aligned'],
ecmaFeatures: {jsx: true}
}, {
code: [
'<App ',
' foo />'
].join('\n'),
options: [{location: 'after-props'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'<App ',
' foo',
'/>'
].join('\n'),
options: [{location: 'tag-aligned'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'<App ',
' foo',
'/>'
].join('\n'),
options: [{location: 'line-aligned'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'<App ',
' foo',
' />'
].join('\n'),
options: [{location: 'props-aligned'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'<App foo></App>'
].join('\n'),
ecmaFeatures: {jsx: true}
}, {
code: [
'<App',
' foo',
'></App>'
].join('\n'),
options: [{location: 'tag-aligned'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'<App',
' foo',
'></App>'
].join('\n'),
options: [{location: 'line-aligned'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'<App',
' foo',
' ></App>'
].join('\n'),
options: [{location: 'props-aligned'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'<App',
' foo={function() {',
' console.log(\'bar\');',
' }} />'
].join('\n'),
options: [{location: 'after-props'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'<App',
' foo={function() {',
' console.log(\'bar\');',
' }}',
' />'
].join('\n'),
options: [{location: 'props-aligned'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'<App',
' foo={function() {',
' console.log(\'bar\');',
' }}',
'/>'
].join('\n'),
options: [{location: 'tag-aligned'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'<App',
' foo={function() {',
' console.log(\'bar\');',
' }}',
'/>'
].join('\n'),
options: [{location: 'line-aligned'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'<Provider store>',
' <App',
' foo />',
'</Provider>'
].join('\n'),
options: [{selfClosing: 'after-props'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'<Provider ',
' store',
'>',
' <App',
' foo />',
'</Provider>'
].join('\n'),
options: [{selfClosing: 'after-props'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'<Provider ',
' store>',
' <App ',
' foo',
' />',
'</Provider>'
].join('\n'),
options: [{nonEmpty: 'after-props'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'<Provider store>',
' <App ',
' foo',
' />',
'</Provider>'
].join('\n'),
options: [{selfClosing: 'props-aligned'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'<Provider',
' store',
' >',
' <App ',
' foo',
' />',
'</Provider>'
].join('\n'),
options: [{nonEmpty: 'props-aligned'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'var x = function() {',
' return <App',
' foo',
' >',
' bar',
' </App>',
'}'
].join('\n'),
options: [{location: 'tag-aligned'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'var x = function() {',
' return <App',
' foo',
' />',
'}'
].join('\n'),
options: [{location: 'tag-aligned'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'var x = <App',
' foo',
' />'
].join('\n'),
options: [{location: 'tag-aligned'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'var x = function() {',
' return <App',
' foo={function() {',
' console.log(\'bar\');',
' }}',
' />',
'}'
].join('\n'),
options: [{location: 'line-aligned'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'var x = <App',
' foo={function() {',
' console.log(\'bar\');',
' }}',
'/>'
].join('\n'),
options: [{location: 'line-aligned'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'<Provider',
' store',
'>',
' <App',
' foo={function() {',
' console.log(\'bar\');',
' }}',
' />',
'</Provider>'
].join('\n'),
options: [{location: 'line-aligned'}],
ecmaFeatures: {jsx: true}
}, {
code: [
'<Provider',
' store',
'>',
' {baz && <App',
' foo={function() {',
' console.log(\'bar\');',
' }}',
' />}',
'</Provider>'
].join('\n'),
options: [{location: 'line-aligned'}],
ecmaFeatures: {jsx: true}
}],
invalid: [{
code: [
'<App ',
'/>'
].join('\n'),
ecmaFeatures: {jsx: true},
errors: MESSAGE_AFTER_TAG
}, {
code: [
'<App foo ',
'/>'
].join('\n'),
ecmaFeatures: {jsx: true},
errors: MESSAGE_AFTER_PROPS
}, {
code: [
'<App foo',
'></App>'
].join('\n'),
ecmaFeatures: {jsx: true},
errors: MESSAGE_AFTER_PROPS
}, {
code: [
'<App ',
' foo />'
].join('\n'),
options: [{location: 'props-aligned'}],
ecmaFeatures: {jsx: true},
errors: MESSAGE_PROPS_ALIGNED
}, {
code: [
'<App ',
' foo />'
].join('\n'),
options: [{location: 'tag-aligned'}],
ecmaFeatures: {jsx: true},
errors: MESSAGE_TAG_ALIGNED
}, {
code: [
'<App ',
' foo />'
].join('\n'),
options: [{location: 'line-aligned'}],
ecmaFeatures: {jsx: true},
errors: MESSAGE_LINE_ALIGNED
}, {
code: [
'<App ',
' foo',
'/>'
].join('\n'),
options: [{location: 'after-props'}],
ecmaFeatures: {jsx: true},
errors: MESSAGE_AFTER_PROPS
}, {
code: [
'<App ',
' foo',
'/>'
].join('\n'),
options: [{location: 'props-aligned'}],
ecmaFeatures: {jsx: true},
errors: MESSAGE_PROPS_ALIGNED
}, {
code: [
'<App ',
' foo',
' />'
].join('\n'),
options: [{location: 'after-props'}],
ecmaFeatures: {jsx: true},
errors: MESSAGE_AFTER_PROPS
}, {
code: [
'<App ',
' foo',
' />'
].join('\n'),
options: [{location: 'tag-aligned'}],
ecmaFeatures: {jsx: true},
errors: MESSAGE_TAG_ALIGNED
}, {
code: [
'<App ',
' foo',
' />'
].join('\n'),
options: [{location: 'line-aligned'}],
ecmaFeatures: {jsx: true},
errors: MESSAGE_LINE_ALIGNED
}, {
code: [
'<App',
' foo',
'></App>'
].join('\n'),
options: [{location: 'after-props'}],
ecmaFeatures: {jsx: true},
errors: MESSAGE_AFTER_PROPS
}, {
code: [
'<App',
' foo',
'></App>'
].join('\n'),
options: [{location: 'props-aligned'}],
ecmaFeatures: {jsx: true},
errors: MESSAGE_PROPS_ALIGNED
}, {
code: [
'<App',
' foo',
' ></App>'
].join('\n'),
options: [{location: 'after-props'}],
ecmaFeatures: {jsx: true},
errors: MESSAGE_AFTER_PROPS
}, {
code: [
'<App',
' foo',
' ></App>'
].join('\n'),
options: [{location: 'tag-aligned'}],
ecmaFeatures: {jsx: true},
errors: MESSAGE_TAG_ALIGNED
}, {
code: [
'<App',
' foo',
' ></App>'
].join('\n'),
options: [{location: 'line-aligned'}],
ecmaFeatures: {jsx: true},
errors: MESSAGE_LINE_ALIGNED
}, {
code: [
'<Provider ',
' store>', // <--
' <App ',
' foo',
' />',
'</Provider>'
].join('\n'),
options: [{selfClosing: 'props-aligned'}],
ecmaFeatures: {jsx: true},
errors: MESSAGE_TAG_ALIGNED
}, {
code: [
'<Provider',
' store',
' >',
' <App ',
' foo',
' />', // <--
'</Provider>'
].join('\n'),
options: [{nonEmpty: 'props-aligned'}],
ecmaFeatures: {jsx: true},
errors: MESSAGE_TAG_ALIGNED
}, {
code: [
'<Provider ',
' store>', // <--
' <App',
' foo />',
'</Provider>'
].join('\n'),
options: [{selfClosing: 'after-props'}],
ecmaFeatures: {jsx: true},
errors: MESSAGE_TAG_ALIGNED
}, {
code: [
'<Provider ',
' store>',
' <App ',
' foo',
' />', // <--
'</Provider>'
].join('\n'),
options: [{nonEmpty: 'after-props'}],
ecmaFeatures: {jsx: true},
errors: MESSAGE_TAG_ALIGNED
}, {
code: [
'var x = function() {',
' return <App',
' foo',
' />',
'}'
].join('\n'),
options: [{location: 'line-aligned'}],
ecmaFeatures: {jsx: true},
errors: MESSAGE_LINE_ALIGNED
}, {
code: [
'var x = <App',
' foo',
' />'
].join('\n'),
options: [{location: 'line-aligned'}],
ecmaFeatures: {jsx: true},
errors: MESSAGE_LINE_ALIGNED
}]
});
|
var Promise = require('bluebird')
, request = Promise.promisifyAll(require('request'))
, md = require('markdown').markdown
, _ = require('lodash')
, yt = require('youtube-dl')
, fs = require('fs')
, ProgressBar = require('progress')
var getInfoAsync = Promise.promisify(yt.getInfo)
var _link = 'https://raw.githubusercontent.com/poteto/emberconf-2015/master/README.md'
var _urls = request
.getAsync(_link)
.spread(function (res, body) {
var tree = _(md.parse(body))
var titles =
tree
.filter(_.isArray)
.filter(function (n) { return n[0] === 'header' && n[1].level == 4 })
.map(function (n) { return n[2] + ((n[3] != undefined) ? n[3][2]: '') })
var links =
tree
.filter(function(n) { return n[0] === 'bulletlist' })
.map(_.rest)
.flatten()
.filter(function(n) { return _.contains(n[1], 'Video') })
.map(_.rest)
.map(_extractVideo)
.value()
return titles
.zip(links)
.map(function (n) { return {title: n[0], url: n[1]} })
.value()
})
/**
* This entire function is a hack to accommodate for the fact that I'm doing something utterly useless.
*/
function _extractVideo(n) {
var url = '';
if(n.length == 1)
url = n[0].split(' ')[1]
else {
url =
_(n[1])
.filter(_.isArray)
.map(function (n) { return _.flatten(_.rest(n)) })
.map(function (n) {
if(n.length == 1)
return n[0].split(' ')[1]
else if(_.contains(n, 'Official')) {
return n[1].href
}
})
.flatten()
.compact()
.value()[0]
}
return url
}
function list(urls) {
urls.each(function (url, i) { console.log(i + 1 + ':', url.title) })
}
function get(urls, index) {
urls
.then(function (urls) {
return getInfoAsync(urls[index - 1].url)
})
.then(function (info) {
return { title: _.startCase(info.title.toLowerCase())
, url: info.url
}
})
.then(function (video) {
request
.get(video.url)
.on('response', function (response) {
var downloadMsg = 'Downloading: ' + video.title;
console.log(downloadMsg)
var length = parseInt(response.headers['content-length'], 10)
var barOptions = { complete: '='
, incomplete: ' '
, width: downloadMsg.length - 12
, total: length
}
var bar = new ProgressBar('[:bar] :percent :etas', barOptions)
response.on('data', function (data) {
bar.tick(data.length)
})
response.on('end', function () {
console.log('\n')
})
})
.pipe(fs.createWriteStream(video.title + '.mp4'))
})
.catch(function (err) {
console.log(err)
})
}
module.exports = { list: _.partial(list, _urls)
, get: _.partial(get, _urls)
}
|
/**
* Swaggy Jenkins
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*
*/
import ApiClient from '../ApiClient';
/**
* The GithubContent model module.
* @module model/GithubContent
* @version 1.1.2-pre.0
*/
class GithubContent {
/**
* @member {String} name
* @type {String}
*/
name;
/**
* @member {String} sha
* @type {String}
*/
sha;
/**
* @member {String} _class
* @type {String}
*/
_class;
/**
* @member {String} repo
* @type {String}
*/
repo;
/**
* @member {Number} size
* @type {Number}
*/
size;
/**
* @member {String} owner
* @type {String}
*/
owner;
/**
* @member {String} path
* @type {String}
*/
path;
/**
* @member {String} base64Data
* @type {String}
*/
base64Data;
/**
* Constructs a new <code>GithubContent</code>.
* @alias module:model/GithubContent
*/
constructor() {
GithubContent.initialize(this);
}
/**
* Initializes the fields of this object.
* This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins).
* Only for internal use.
*/
static initialize(obj) {
}
/**
* Constructs a <code>GithubContent</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/GithubContent} obj Optional instance to populate.
* @return {module:model/GithubContent} The populated <code>GithubContent</code> instance.
*/
static constructFromObject(data, obj) {
if (data) {
obj = obj || new GithubContent();
if (data.hasOwnProperty('name')) {
obj['name'] = ApiClient.convertToType(data['name'], 'String');
}
if (data.hasOwnProperty('sha')) {
obj['sha'] = ApiClient.convertToType(data['sha'], 'String');
}
if (data.hasOwnProperty('_class')) {
obj['_class'] = ApiClient.convertToType(data['_class'], 'String');
}
if (data.hasOwnProperty('repo')) {
obj['repo'] = ApiClient.convertToType(data['repo'], 'String');
}
if (data.hasOwnProperty('size')) {
obj['size'] = ApiClient.convertToType(data['size'], 'Number');
}
if (data.hasOwnProperty('owner')) {
obj['owner'] = ApiClient.convertToType(data['owner'], 'String');
}
if (data.hasOwnProperty('path')) {
obj['path'] = ApiClient.convertToType(data['path'], 'String');
}
if (data.hasOwnProperty('base64Data')) {
obj['base64Data'] = ApiClient.convertToType(data['base64Data'], 'String');
}
}
return obj;
}
}
export default GithubContent;
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
//@ts-check
'use strict';
const perf = require('./vs/base/common/performance');
perf.mark('main:started');
const fs = require('fs');
const path = require('path');
const bootstrap = require('./bootstrap');
const paths = require('./paths');
// @ts-ignore
const product = require('../product.json');
// @ts-ignore
const app = require('electron').app;
// Enable portable support
const portable = bootstrap.configurePortable();
// Enable ASAR support
bootstrap.enableASARSupport();
// Set userData path before app 'ready' event and call to process.chdir
const args = parseCLIArgs();
const userDataPath = getUserDataPath(args);
app.setPath('userData', userDataPath);
// Update cwd based on environment and platform
setCurrentWorkingDirectory();
// Global app listeners
registerListeners();
/**
* Support user defined locale
*
* @type {Promise}
*/
let nlsConfiguration = undefined;
const userDefinedLocale = getUserDefinedLocale();
userDefinedLocale.then((locale) => {
if (locale && !nlsConfiguration) {
nlsConfiguration = getNLSConfiguration(locale);
}
});
// Configure command line switches
const nodeCachedDataDir = getNodeCachedDir();
configureCommandlineSwitches(args, nodeCachedDataDir);
// Load our code once ready
app.once('ready', function () {
if (args['trace']) {
// @ts-ignore
const contentTracing = require('electron').contentTracing;
const traceOptions = {
categoryFilter: args['trace-category-filter'] || '*',
traceOptions: args['trace-options'] || 'record-until-full,enable-sampling'
};
contentTracing.startRecording(traceOptions, () => onReady());
} else {
onReady();
}
});
function onReady() {
perf.mark('main:appReady');
Promise.all([nodeCachedDataDir.ensureExists(), userDefinedLocale]).then(([cachedDataDir, locale]) => {
if (locale && !nlsConfiguration) {
nlsConfiguration = getNLSConfiguration(locale);
}
if (!nlsConfiguration) {
nlsConfiguration = Promise.resolve(undefined);
}
// We first need to test a user defined locale. If it fails we try the app locale.
// If that fails we fall back to English.
nlsConfiguration.then((nlsConfig) => {
const startup = nlsConfig => {
nlsConfig._languagePackSupport = true;
process.env['VSCODE_NLS_CONFIG'] = JSON.stringify(nlsConfig);
if (cachedDataDir) {
process.env['VSCODE_NODE_CACHED_DATA_DIR'] = cachedDataDir;
}
// Load main in AMD
require('./bootstrap-amd').load('vs/code/electron-main/main');
};
// We recevied a valid nlsConfig from a user defined locale
if (nlsConfig) {
startup(nlsConfig);
}
// Try to use the app locale. Please note that the app locale is only
// valid after we have received the app ready event. This is why the
// code is here.
else {
let appLocale = app.getLocale();
if (!appLocale) {
startup({ locale: 'en', availableLanguages: {} });
} else {
// See above the comment about the loader and case sensitiviness
appLocale = appLocale.toLowerCase();
getNLSConfiguration(appLocale).then((nlsConfig) => {
if (!nlsConfig) {
nlsConfig = { locale: appLocale, availableLanguages: {} };
}
startup(nlsConfig);
});
}
}
});
}, console.error);
}
/**
* @typedef {import('minimist').ParsedArgs} ParsedArgs
*
* @param {ParsedArgs} cliArgs
* @param {{ jsFlags: () => string }} nodeCachedDataDir
*/
function configureCommandlineSwitches(cliArgs, nodeCachedDataDir) {
// TODO@Ben Electron 2.0.x: prevent localStorage migration from SQLite to LevelDB due to issues
app.commandLine.appendSwitch('disable-mojo-local-storage');
// Force pre-Chrome-60 color profile handling (for https://github.com/Microsoft/vscode/issues/51791)
app.commandLine.appendSwitch('disable-features', 'ColorCorrectRendering');
// Support JS Flags
const jsFlags = resolveJSFlags(cliArgs, nodeCachedDataDir.jsFlags());
if (jsFlags) {
app.commandLine.appendSwitch('--js-flags', jsFlags);
}
}
/**
* @param {ParsedArgs} cliArgs
* @param {string[]} jsFlags
* @returns {string}
*/
function resolveJSFlags(cliArgs, ...jsFlags) {
if (cliArgs['js-flags']) {
jsFlags.push(cliArgs['js-flags']);
}
if (cliArgs['max-memory'] && !/max_old_space_size=(\d+)/g.exec(cliArgs['js-flags'])) {
jsFlags.push(`--max_old_space_size=${cliArgs['max-memory']}`);
}
return jsFlags.length > 0 ? jsFlags.join(' ') : null;
}
/**
* @param {ParsedArgs} cliArgs
*
* @returns {string}
*/
function getUserDataPath(cliArgs) {
if (portable.isPortable) {
return path.join(portable.portableDataPath, 'user-data');
}
return path.resolve(cliArgs['user-data-dir'] || paths.getDefaultUserDataPath(process.platform));
}
/**
* @returns {ParsedArgs}
*/
function parseCLIArgs() {
const minimist = require('minimist');
return minimist(process.argv, {
string: [
'user-data-dir',
'locale',
'js-flags',
'max-memory'
]
});
}
function setCurrentWorkingDirectory() {
try {
if (process.platform === 'win32') {
process.env['VSCODE_CWD'] = process.cwd(); // remember as environment letiable
process.chdir(path.dirname(app.getPath('exe'))); // always set application folder as cwd
} else if (process.env['VSCODE_CWD']) {
process.chdir(process.env['VSCODE_CWD']);
}
} catch (err) {
console.error(err);
}
}
function registerListeners() {
/**
* Mac: when someone drops a file to the not-yet running VSCode, the open-file event fires even before
* the app-ready event. We listen very early for open-file and remember this upon startup as path to open.
*
* @type {string[]}
*/
const macOpenFiles = [];
global['macOpenFiles'] = macOpenFiles;
app.on('open-file', function (event, path) {
macOpenFiles.push(path);
});
/**
* React to open-url requests.
*
* @type {string[]}
*/
const openUrls = [];
const onOpenUrl = function (event, url) {
event.preventDefault();
openUrls.push(url);
};
app.on('will-finish-launching', function () {
app.on('open-url', onOpenUrl);
});
global['getOpenUrls'] = function () {
app.removeListener('open-url', onOpenUrl);
return openUrls;
};
}
/**
* @returns {{ jsFlags: () => string; ensureExists: () => Promise<string | void>, _compute: () => string; }}
*/
function getNodeCachedDir() {
return new class {
constructor() {
this.value = this._compute();
}
jsFlags() {
return this.value ? '--nolazy' : undefined;
}
ensureExists() {
return mkdirp(this.value).then(() => this.value, () => { /*ignore*/ });
}
_compute() {
if (process.argv.indexOf('--no-cached-data') > 0) {
return undefined;
}
// IEnvironmentService.isBuilt
if (process.env['VSCODE_DEV']) {
return undefined;
}
// find commit id
const commit = product.commit;
if (!commit) {
return undefined;
}
return path.join(userDataPath, 'CachedData', commit);
}
};
}
//#region NLS Support
/**
* @param {string} content
* @returns {string}
*/
function stripComments(content) {
const regexp = /("(?:[^\\\"]*(?:\\.)?)*")|('(?:[^\\\']*(?:\\.)?)*')|(\/\*(?:\r?\n|.)*?\*\/)|(\/{2,}.*?(?:(?:\r?\n)|$))/g;
return content.replace(regexp, function (match, m1, m2, m3, m4) {
// Only one of m1, m2, m3, m4 matches
if (m3) {
// A block comment. Replace with nothing
return '';
} else if (m4) {
// A line comment. If it ends in \r?\n then keep it.
const length_1 = m4.length;
if (length_1 > 2 && m4[length_1 - 1] === '\n') {
return m4[length_1 - 2] === '\r' ? '\r\n' : '\n';
}
else {
return '';
}
} else {
// We match a string
return match;
}
});
}
/**
* @param {string} dir
* @returns {Promise<string>}
*/
function mkdir(dir) {
return new Promise((c, e) => fs.mkdir(dir, err => (err && err.code !== 'EEXIST') ? e(err) : c(dir)));
}
/**
* @param {string} file
* @returns {Promise<boolean>}
*/
function exists(file) {
return new Promise(c => fs.exists(file, c));
}
/**
* @param {string} file
* @returns {Promise<void>}
*/
function touch(file) {
return new Promise((c, e) => { const d = new Date(); fs.utimes(file, d, d, err => err ? e(err) : c()); });
}
/**
* @param {string} file
* @returns {Promise<object>}
*/
function lstat(file) {
return new Promise((c, e) => fs.lstat(file, (err, stats) => err ? e(err) : c(stats)));
}
/**
* @param {string} dir
* @returns {Promise<string[]>}
*/
function readdir(dir) {
return new Promise((c, e) => fs.readdir(dir, (err, files) => err ? e(err) : c(files)));
}
/**
* @param {string} dir
* @returns {Promise<void>}
*/
function rmdir(dir) {
return new Promise((c, e) => fs.rmdir(dir, err => err ? e(err) : c(undefined)));
}
/**
* @param {string} file
* @returns {Promise<void>}
*/
function unlink(file) {
return new Promise((c, e) => fs.unlink(file, err => err ? e(err) : c(undefined)));
}
/**
* @param {string} dir
* @returns {Promise<string>}
*/
function mkdirp(dir) {
return mkdir(dir).then(null, err => {
if (err && err.code === 'ENOENT') {
const parent = path.dirname(dir);
if (parent !== dir) { // if not arrived at root
return mkdirp(parent).then(() => mkdir(dir));
}
}
throw err;
});
}
/**
* @param {string} location
* @returns {Promise<void>}
*/
function rimraf(location) {
return lstat(location).then(stat => {
if (stat.isDirectory() && !stat.isSymbolicLink()) {
return readdir(location)
.then(children => Promise.all(children.map(child => rimraf(path.join(location, child)))))
.then(() => rmdir(location));
} else {
return unlink(location);
}
}, err => {
if (err.code === 'ENOENT') {
return void 0;
}
throw err;
});
}
// Language tags are case insensitve however an amd loader is case sensitive
// To make this work on case preserving & insensitive FS we do the following:
// the language bundles have lower case language tags and we always lower case
// the locale we receive from the user or OS.
/**
* @returns {Promise<string>}
*/
function getUserDefinedLocale() {
const locale = args['locale'];
if (locale) {
return Promise.resolve(locale.toLowerCase());
}
const localeConfig = path.join(userDataPath, 'User', 'locale.json');
return exists(localeConfig).then((result) => {
if (result) {
return bootstrap.readFile(localeConfig).then((content) => {
content = stripComments(content);
try {
const value = JSON.parse(content).locale;
return value && typeof value === 'string' ? value.toLowerCase() : undefined;
} catch (e) {
return undefined;
}
});
} else {
return undefined;
}
});
}
/**
* @returns {object}
*/
function getLanguagePackConfigurations() {
const configFile = path.join(userDataPath, 'languagepacks.json');
try {
return require(configFile);
} catch (err) {
// Do nothing. If we can't read the file we have no
// language pack config.
}
return undefined;
}
/**
* @param {object} config
* @param {string} locale
*/
function resolveLanguagePackLocale(config, locale) {
try {
while (locale) {
if (config[locale]) {
return locale;
} else {
const index = locale.lastIndexOf('-');
if (index > 0) {
locale = locale.substring(0, index);
} else {
return undefined;
}
}
}
} catch (err) {
console.error('Resolving language pack configuration failed.', err);
}
return undefined;
}
/**
* @param {string} locale
*/
function getNLSConfiguration(locale) {
if (locale === 'pseudo') {
return Promise.resolve({ locale: locale, availableLanguages: {}, pseudo: true });
}
if (process.env['VSCODE_DEV']) {
return Promise.resolve({ locale: locale, availableLanguages: {} });
}
// We have a built version so we have extracted nls file. Try to find
// the right file to use.
// Check if we have an English or English US locale. If so fall to default since that is our
// English translation (we don't ship *.nls.en.json files)
if (locale && (locale === 'en' || locale === 'en-us')) {
return Promise.resolve({ locale: locale, availableLanguages: {} });
}
const initialLocale = locale;
perf.mark('nlsGeneration:start');
const defaultResult = function (locale) {
perf.mark('nlsGeneration:end');
return Promise.resolve({ locale: locale, availableLanguages: {} });
};
try {
const commit = product.commit;
if (!commit) {
return defaultResult(initialLocale);
}
const configs = getLanguagePackConfigurations();
if (!configs) {
return defaultResult(initialLocale);
}
locale = resolveLanguagePackLocale(configs, locale);
if (!locale) {
return defaultResult(initialLocale);
}
const packConfig = configs[locale];
let mainPack;
if (!packConfig || typeof packConfig.hash !== 'string' || !packConfig.translations || typeof (mainPack = packConfig.translations['vscode']) !== 'string') {
return defaultResult(initialLocale);
}
return exists(mainPack).then((fileExists) => {
if (!fileExists) {
return defaultResult(initialLocale);
}
const packId = packConfig.hash + '.' + locale;
const cacheRoot = path.join(userDataPath, 'clp', packId);
const coreLocation = path.join(cacheRoot, commit);
const translationsConfigFile = path.join(cacheRoot, 'tcf.json');
const corruptedFile = path.join(cacheRoot, 'corrupted.info');
const result = {
locale: initialLocale,
availableLanguages: { '*': locale },
_languagePackId: packId,
_translationsConfigFile: translationsConfigFile,
_cacheRoot: cacheRoot,
_resolvedLanguagePackCoreLocation: coreLocation,
_corruptedFile: corruptedFile
};
return exists(corruptedFile).then((corrupted) => {
// The nls cache directory is corrupted.
let toDelete;
if (corrupted) {
toDelete = rimraf(cacheRoot);
} else {
toDelete = Promise.resolve(undefined);
}
return toDelete.then(() => {
return exists(coreLocation).then((fileExists) => {
if (fileExists) {
// We don't wait for this. No big harm if we can't touch
touch(coreLocation).catch(() => { });
perf.mark('nlsGeneration:end');
return result;
}
return mkdirp(coreLocation).then(() => {
return Promise.all([bootstrap.readFile(path.join(__dirname, 'nls.metadata.json')), bootstrap.readFile(mainPack)]);
}).then((values) => {
const metadata = JSON.parse(values[0]);
const packData = JSON.parse(values[1]).contents;
const bundles = Object.keys(metadata.bundles);
const writes = [];
for (let bundle of bundles) {
const modules = metadata.bundles[bundle];
const target = Object.create(null);
for (let module of modules) {
const keys = metadata.keys[module];
const defaultMessages = metadata.messages[module];
const translations = packData[module];
let targetStrings;
if (translations) {
targetStrings = [];
for (let i = 0; i < keys.length; i++) {
const elem = keys[i];
const key = typeof elem === 'string' ? elem : elem.key;
let translatedMessage = translations[key];
if (translatedMessage === undefined) {
translatedMessage = defaultMessages[i];
}
targetStrings.push(translatedMessage);
}
} else {
targetStrings = defaultMessages;
}
target[module] = targetStrings;
}
writes.push(bootstrap.writeFile(path.join(coreLocation, bundle.replace(/\//g, '!') + '.nls.json'), JSON.stringify(target)));
}
writes.push(bootstrap.writeFile(translationsConfigFile, JSON.stringify(packConfig.translations)));
return Promise.all(writes);
}).then(() => {
perf.mark('nlsGeneration:end');
return result;
}).catch((err) => {
console.error('Generating translation files failed.', err);
return defaultResult(locale);
});
});
});
});
});
} catch (err) {
console.error('Generating translation files failed.', err);
return defaultResult(locale);
}
}
//#endregion |
// Copyright IBM Corp. 2014,2016. All Rights Reserved.
// Node module: loopback-sdk-angular
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
/* eslint quotes: ["error", "single"] */
var fs = require('fs');
var g = require('strong-globalize')();
var path = require('path');
var loopbackCoreJs = path.resolve(__dirname, 'loopback-core.js');
try {
var generator = require('..');
var loopback = require('loopback');
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND' && fs.existsSync(loopbackCoreJs)) {
g.log('Cannot load the generator, {{node_modules}} were not installed.');
g.log('Ignoring the error since the output file is already there.');
process.exit();
}
throw err;
}
g.log('Generating API docs for {{LoopBack}} built-in models.');
var app = loopback();
app.dataSource('db', { connector: 'memory', defaultForType: 'db' });
var modelNames = [];
for (var key in loopback) {
var model = loopback[key];
if (!model) continue;
if (model === loopback.Model) continue;
if (model.prototype instanceof loopback.Model)
modelNames.push(key);
}
modelNames.sort(function(l, r) {
if (l === r) return 0;
if (l === 'PersistedModel') return -1;
if (r === 'PersistedModel') return 1;
return l < r ? -1 : 1;
});
modelNames.forEach(function(key) {
var model = loopback[key];
if (model.prototype instanceof loopback.PersistedModel) {
app.model(model, { dataSource: 'db' });
g.log(' added persisted model %s', key);
} else if (model.prototype instanceof loopback.Model) {
app.model(model);
g.log(' added model %s', key);
}
});
var script = generator.services(app, 'lbServices', '/api');
// Transform ngdoc comments and make them compatible with dox/strong-docs
script = script
// Insert an empty line (serving as jsdoc description) before @ngdoc
.replace(/^(\s+\*)( @ngdoc)/gm, '$1\n$1$2')
// Remove module name from all names
.replace(/\blbServices\./g, '')
// Fix `## Example` sections
.replace(/## Example/g, '**Example**')
// Annotate Angular objects as jsdoc classes
.replace(/^((\s+\*) @ngdoc object)/mg, '$1\n$2 @class')
// Annonotate Angular methods as jsodc methods
.replace(/^((\s+\*) @ngdoc method)/mg, '$1\n$2 @method')
// Hide the top-level module description
.replace(/^(\s+\*) @module.*$/mg, '$1 @private')
// Change `Model#method` to `Model.method` in @name
.replace(/^(\s+\* @name) ([^# \n]+)#([^# \n]+) *$/mg, '$1 $2.$3')
// Change `Model#method` to `Model.method` in @link
// Do not modify URLs with anchors, e.g. `http://foo/bar#anchor`
.replace(/({@link [^\/# }\n]+)#([^# }\n]+)/g, '$1.$2');
fs.writeFileSync(loopbackCoreJs, script);
g.log('Done: %s', loopbackCoreJs);
|
import AbstractView from './AbstractView';
export default class HomeView extends AbstractView {
static get className() {
return __filename.match(new RegExp(/.*\/([A-z]+)\.js$/))[1];
}
static get requiredAssets() {
return [];
}
constructor() {
super('home');
}
}
|
'use strict'
module.exports = {
extends: 'plugin:ramda/recommended',
plugins: ['eslint-plugin-ramda'],
rules: {
'ramda/always-simplification': 'error',
'ramda/compose-simplification': 'error',
'ramda/eq-by-simplification': 'error',
'ramda/pipe-simplification': 'error',
'ramda/prefer-both-either': 'error',
'ramda/prefer-complement': 'error'
}
}
|
'use strict';
const common = require('../common.js');
const assert = require('assert');
const bench = common.createBenchmark(main, {
source: [
'array',
'arraybuffer',
'arraybuffer-middle',
'buffer',
'uint8array',
'string',
'string-utf8',
'string-base64',
'object'
],
len: [10, 2048],
n: [2048]
});
function main({ len, n, source }) {
const array = new Array(len).fill(42);
const arrayBuf = new ArrayBuffer(len);
const str = 'a'.repeat(len);
const buffer = Buffer.allocUnsafe(len);
const uint8array = new Uint8Array(len);
const obj = { length: null }; // Results in a new, empty Buffer
var i;
switch (source) {
case 'array':
bench.start();
for (i = 0; i < n * 1024; i++) {
Buffer.from(array);
}
bench.end(n);
break;
case 'arraybuffer':
bench.start();
for (i = 0; i < n * 1024; i++) {
Buffer.from(arrayBuf);
}
bench.end(n);
break;
case 'arraybuffer-middle':
const offset = ~~(len / 4);
const length = ~~(len / 2);
bench.start();
for (i = 0; i < n * 1024; i++) {
Buffer.from(arrayBuf, offset, length);
}
bench.end(n);
break;
case 'buffer':
bench.start();
for (i = 0; i < n * 1024; i++) {
Buffer.from(buffer);
}
bench.end(n);
break;
case 'uint8array':
bench.start();
for (i = 0; i < n * 1024; i++) {
Buffer.from(uint8array);
}
bench.end(n);
break;
case 'string':
bench.start();
for (i = 0; i < n * 1024; i++) {
Buffer.from(str);
}
bench.end(n);
break;
case 'string-utf8':
bench.start();
for (i = 0; i < n * 1024; i++) {
Buffer.from(str, 'utf8');
}
bench.end(n);
break;
case 'string-base64':
bench.start();
for (i = 0; i < n * 1024; i++) {
Buffer.from(str, 'base64');
}
bench.end(n);
break;
case 'object':
bench.start();
for (i = 0; i < n * 1024; i++) {
Buffer.from(obj);
}
bench.end(n);
break;
default:
assert.fail(null, null, 'Should not get here');
}
}
|
/* eslint-env mocha */
/* eslint-disable no-unused-expressions */
/* global expect */
(function () {
'use strict';
var Dyframe = window.Dyframe;
var element = document.createElement('div');
var dyframe;
// Helpers
var hasClass = function (element, className) {
if (element.classList) {
return element.classList.contains(className);
}
return new RegExp('(^|\\s)' + className + '(?!\\S)', 'g').test(element.className);
};
var addClass = function (element, className) {
if (element.classList) {
element.classList.add(className);
} else {
element.className += ' ' + className;
}
};
// Set up fixtures
element.style.width = '100px';
element.style.height = '200px';
document.body.appendChild(element);
// Specs
describe('Dyframe', function () {
describe('.addProfile()', function () {
afterEach(function () {
dyframe.destroy();
});
it('adds active profile for dyframe objects', function () {
Dyframe.addProfile('custom', {});
dyframe = new Dyframe(element, {
profile: 'custom'
});
expect(dyframe.hasActiveProfile()).to.be.true;
});
});
describe('Constructor', function () {
afterEach(function () {
dyframe.destroy();
});
it('creates <div> and <iframe> in the target element', function () {
dyframe = new Dyframe(element);
expect(element.querySelector('div')).not.to.be.null;
expect(element.querySelector('iframe')).not.to.be.null;
});
it('creates HTML content in <iframe>', function () {
dyframe = new Dyframe(element, {
html: '<html><body>Hello, world!</body></html>'
});
var iframe = element.querySelector('iframe');
var body = iframe.contentWindow.document.body;
expect(body.innerHTML).to.equal('Hello, world!');
});
it('sets default options when no options given', function () {
var defaults = {
html: '',
width: 980,
deviceWidth: null,
profile: null,
interval: 0
};
dyframe = new Dyframe(element);
expect(dyframe.options).to.deep.equal(defaults);
});
it('overrides default options when options given', function () {
var options = {
html: '<html><body>Hello, Dyframe!</body></html>',
deviceWidth: 360
};
var expected = {
html: '<html><body>Hello, Dyframe!</body></html>',
width: 980,
deviceWidth: 360,
profile: null,
interval: 0
};
dyframe = new Dyframe(element, options);
expect(dyframe.options).to.deep.equal(expected);
});
it('adds "df-element" class to the target element', function () {
dyframe = new Dyframe(element);
expect(hasClass(element, 'df-element')).to.be.true;
});
it('adds "df-profile-<name>" class when profile option given', function () {
dyframe = new Dyframe(element, {
profile: 'smartphone'
});
expect(hasClass(element, 'df-profile-smartphone')).to.be.true;
});
});
});
describe('dyframe', function () {
describe('.render()', function () {
var iframe;
var body;
beforeEach(function () {
dyframe = new Dyframe(element, {
html: '<html><body>Hello, world!</body></html>'
});
iframe = element.querySelector('iframe');
});
afterEach(function () {
dyframe.destroy();
});
it('overrides options when argument given', function () {
dyframe.render({
width: 1200
});
expect(dyframe.options.width).to.equal(1200);
});
// Somehow this is not working on PhantomJS...
// it('makes <iframe> same size with target element', function () {
// dyframe.render();
// var rect = iframe.getBoundingClientRect();
// expect(rect.width).to.equal(100);
// expect(rect.height).to.equal(200);
// });
it('renders HTML according to default options', function (done) {
dyframe.render();
setTimeout(function () {
expect(iframe.contentWindow.innerWidth).to.equal(980);
done();
}, 0);
});
it('renders HTML according to width option', function (done) {
dyframe.render({
width: 1200
});
setTimeout(function () {
expect(iframe.contentWindow.innerWidth).to.equal(1200);
done();
}, 0);
});
it('renders HTML accroding to deviceWidth option if HTML has meta-viewport', function (done) {
dyframe.render({
html: '<html><head><meta name="viewport" content="width=device-width"></head></html>',
width: 980,
deviceWidth: 360
});
setTimeout(function () {
expect(iframe.contentWindow.innerWidth).to.equal(360);
done();
}, 0);
});
it('renders HTML accroding to width option if HTML does not have meta-viewport', function (done) {
dyframe.render({
html: '<html><head></head></html>',
width: 980,
deviceWidth: 360
});
setTimeout(function () {
expect(iframe.contentWindow.innerWidth).to.equal(980);
done();
}, 0);
});
it('renders HTML accroding to width value in meta-viewport', function (done) {
dyframe.render({
html: '<html><head><meta name="viewport" content="width=720"></head></html>',
width: 980,
deviceWidth: 360
});
setTimeout(function () {
expect(iframe.contentWindow.innerWidth).to.equal(720);
done();
}, 0);
});
it('renders HTML accroding to initial-scale value in meta-viewport', function (done) {
dyframe.render({
html: '<html><head><meta name="viewport" content="initial-scale=0.5"></head></html>',
width: 980,
deviceWidth: 360
});
setTimeout(function () {
expect(iframe.contentWindow.innerWidth).to.equal(720);
done();
}, 0);
});
it('renders HTML ignoring meta-viewport that does not have content', function (done) {
dyframe.render({
html: '<html><head><meta name="viewport"></head></html>',
width: 980,
deviceWidth: 360
});
setTimeout(function () {
expect(iframe.contentWindow.innerWidth).to.equal(980);
done();
}, 0);
});
it('renders HTML ignoring meta-viewport that has invalid content', function (done) {
dyframe.render({
html: '<html><head><meta name="viewport" content="width:device-width"></head></html>',
width: 980,
deviceWidth: 360
});
setTimeout(function () {
expect(iframe.contentWindow.innerWidth).to.equal(980);
done();
}, 0);
});
it('renders HTML accroding to "smartphone" profile', function (done) {
dyframe.render({
html: '<html><head><meta name="viewport" content="width=device-width"></head></html>',
profile: 'smartphone'
});
setTimeout(function () {
expect(iframe.contentWindow.innerWidth).to.equal(375);
done();
}, 0);
});
it('renders HTML accroding to "tablet" profile', function (done) {
dyframe.render({
html: '<html><head><meta name="viewport" content="width=device-width"></head></html>',
profile: 'tablet'
});
setTimeout(function () {
expect(iframe.contentWindow.innerWidth).to.equal(768);
done();
}, 0);
});
it('renders HTML accroding to custom profile', function (done) {
Dyframe.addProfile('nexus-6', {
width: 980,
deviceWidth: 412
});
dyframe.render({
html: '<html><head><meta name="viewport" content="width=device-width"></head></html>',
profile: 'nexus-6'
});
setTimeout(function () {
expect(iframe.contentWindow.innerWidth).to.equal(412);
done();
}, 0);
});
it('skips and postpones rendering when interval option given', function (done) {
dyframe.render({
html: '<html><body>First rendering</body></html>',
interval: 1000
});
setTimeout(function () {
body = iframe.contentWindow.document.body;
expect(body.innerHTML).to.equal('First rendering');
dyframe.render({
html: '<html><body>Second rendering</body></html>'
});
setTimeout(function () {
body = iframe.contentWindow.document.body;
expect(body.innerHTML).to.equal('First rendering');
setTimeout(function () {
body = iframe.contentWindow.document.body;
expect(body.innerHTML).to.equal('Second rendering');
done();
}, 1000);
}, 0);
}, 0);
});
});
describe('.destroy()', function () {
beforeEach(function () {
dyframe = new Dyframe(element, {
html: '<html><body>Hello, world!</body></html>'
});
});
it('cleans up the target element', function () {
dyframe.destroy();
expect(element.innerHTML).to.be.empty;
});
it('removes "df" related classes', function () {
dyframe.render({
profile: 'smartphone'
});
dyframe.destroy();
expect(hasClass(element, 'df-element')).to.be.false;
expect(hasClass(element, 'df-profile-smartphone')).to.be.false;
});
it('preserves non-"df" classes', function () {
addClass(element, 'non-df-class');
dyframe.destroy();
expect(hasClass(element, 'df-element')).to.be.false;
expect(hasClass(element, 'non-df-class')).to.be.true;
});
it('can be called twice, but does nothing', function () {
dyframe.destroy();
expect(element.innerHTML).to.be.empty;
expect(function () {
dyframe.destroy();
}).to.not.throw(Error);
expect(element.innerHTML).to.be.empty;
});
});
});
}());
|
const normalizePhone = (value, previousValue) => {
if (!value) {
return value;
}
const onlyNums = value.replace(/[^\d]/g, '');
if (!previousValue || value.length > previousValue.length) {
// typing forward
if (onlyNums.length === 3) {
return onlyNums + '-';
}
if (onlyNums.length === 6) {
return onlyNums.slice(0, 3) + '-' + onlyNums.slice(3) + '-';
}
}
if (onlyNums.length <= 3) {
return onlyNums;
}
if (onlyNums.length <= 6) {
return onlyNums.slice(0, 3) + '-' + onlyNums.slice(3);
}
return (
onlyNums.slice(0, 3) +
'-' +
onlyNums.slice(3, 6) +
'-' +
onlyNums.slice(6, 11)
);
};
export default normalizePhone;
|
// neverdie
process.on('uncaughtException', function(err){
console.log('uncaughtException', new Date(), 'Caught exception: ' + err);
});
require('./lib/native-x');
var defaultConfig = {
sosTelnet:{
host: "127.0.0.1",
port: 2468
},
controlInterface:{
server:{
port: 3500
}
},
cmsInterface:{
server:{
bind: '0.0.0.0',
port: 3510
},
library:[
'/shared'
],
playlistFsLocation: __dirname + '/../ml-sos-cms-data/playlists'
},
database:{
fsLocation: __dirname + '/../ml-sos-cms-data/database'
}
}
var loadedConfig;
try{
loadedConfig = require(__dirname+'/config');
} catch(e){
console.log('************************************************************');
console.log('missing config.json, please add it, continuing with defaults');
console.log('************************************************************')
loadedConfig = {};
}
//load config or default config
var config = {}._xtend(defaultConfig, loadedConfig);
console.log(config);
// start database
var DB = require(__dirname+ '/lib/data')(config);
// start control interface
var controlInterface = require(__dirname+'/lib/control-interface')(config);
// start CMS interface
var cmsInterface = require(__dirname+'/lib/cms-interface')(config, DB);
// scrape FS for datasets and playlists
var scrapers = require(__dirname+'/lib/scrapers')(config, DB); |
import React, {Component, PropTypes} from 'react';
import '../../styles/base.scss';
class App extends Component {
static propTypes = {
children: PropTypes.element.isRequired
};
render () {
return (
<div className="app">
{this.props.children}
</div>
);
}
}
export default App;
|
var express = require('express');
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var yargs = require('yargs');
var args = yargs
.alias('p', 'production')
.argv;
var app = new express();
var port = 8000;
process.env.NODE_ENV = args.production ? 'production' : 'development';
console.log('NODE_ENV => ', process.env.NODE_ENV);
// In development mode serve the scripts using webpack-dev-middleware
if (process.env.NODE_ENV === 'development') {
var config = require('../../webpack.config');
var compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
app.use(webpackHotMiddleware(compiler));
} else {
app.use('/dist', express.static('dist', {maxAge: '200d'}));
}
app.use('/assets', express.static('assets', {maxAge: '200d'}));
app.get("*", function(req, res) {
res.sendFile(__dirname + '/index.html');
})
app.listen(port, function(error) {
if (error) {
console.error(error);
} else {
console.info("==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port);
}
})
|
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import PageLink from './PageLink';
/**
* Determine if there are multiple page links for pagination, apart
* from previous/next links and current page.
*
* @param {array} pageLinks
* @returns boolean
*/
function hasMultiplePageLinks(pageLinks) {
return pageLinks.length > 3;
}
const Pagination = ({ className, links }) => {
return hasMultiplePageLinks(links) ? (
<div className={classnames('col-span-full', className)}>
<ul className="border border-gray-300 inline-flex rounded text-sm uppercase">
{links.map((link, index) => {
return <PageLink key={index} link={link} index={index} />;
})}
</ul>
</div>
) : null;
};
Pagination.propTypes = {
className: PropTypes.string,
links: PropTypes.array.isRequired,
};
Pagination.defaultProps = {
className: null,
};
export default Pagination;
|
module.exports = {"test/fixtures/hello":"<div>hello {{name}}</div>"}; |
/* eslint-disable */
import React from 'react';
class FootnoteExample extends React.Component {
render() {
return (
<AnnouncementModalLayout
illustration={'generic_post.svg'}
primaryButtonText="Start Now"
linkText="Learn More"
title="Import Posts From WordPress"
onCloseButtonClick={() => {}}
footnote={
<Text size="small">
By sending an invite, you agree to the <a>Wix Terms of Use</a>
</Text>
}
>
<Text>
Your public posts, images and videos will be copied and added to your
Wix blog. Your site and current posts won't be affected.
</Text>
</AnnouncementModalLayout>
);
}
}
|
import React from 'react';
import float from 'float';
import { clamp, path, pipe } from 'ramda';
import PropTypes from 'prop-types';
import { noop } from 'lodash';
import { NODE_CPT_PRECISION } from 'constants/node';
import { getComponentTestId } from 'utils/test-utils';
import styles from './styles.scss';
const clamp0And1 = clamp(0, 1);
const pathTargetValue = path(['target', 'value']);
const formatValue = value => float.round(clamp0And1(value), NODE_CPT_PRECISION);
const getValueAndFormat = pipe(pathTargetValue, formatValue);
const onChangeHandler = onChange => event => onChange(getValueAndFormat(event));
const InputCpt = ({ onChange, id, ...props }) => (
<input
className={styles.inputCpt}
type="number"
step="0.01"
max="1"
min="0"
data-testid={getComponentTestId('InputCpt', id)}
onChange={onChangeHandler(onChange)}
{...props}
/>
);
InputCpt.propTypes = {
onChange: PropTypes.func,
id: PropTypes.string.isRequired,
};
InputCpt.defaultProps = {
onChange: noop,
};
export default InputCpt;
|
/*
* Utilities: A classic collection of JavaScript utilities
* Copyright 2112 Matthew Eernisse (mde@fleegix.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
var i18n = require('../lib/i18n')
, assert = require('assert')
, tests
, inst = {};
tests = {
'before': function () {
i18n.loadLocale('en-us', {foo: 'FOO', bar: 'BAR', baz: 'BAZ'});
i18n.loadLocale('ja-jp', {foo: 'フー', bar: 'バー'});
inst.en = new i18n.I18n('en-us');
inst.jp = new i18n.I18n('ja-jp');
inst.de = new i18n.I18n('de-de');
}
, 'test default-locale fallback, defined strings': function () {
var expected = 'BAZ'
, actual = inst.jp.t('baz');
assert.equal(expected, actual);
}
, 'test default-locale fallback, no defined strings': function () {
var expected = 'BAZ'
, actual = inst.de.t('baz');
assert.equal(expected, actual);
}
, 'test key lookup, default-locale': function () {
var expected = 'FOO'
, actual = inst.en.t('foo');
assert.equal(expected, actual);
}
, 'test key lookup, non-default-locale': function () {
var expected = 'フー'
, actual = inst.jp.t('foo');
assert.equal(expected, actual);
}
};
module.exports = tests;
|
import styles from './Columns.less';
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
const renderColumn = (el, index) => (
<div key={index}>{el}</div>
);
export default function Columns({ children, tight, flexible }) {
return (
<div
className={classnames({
[styles.columns]: true,
[styles.columns_tight]: tight,
[styles.columns_flexible]: flexible
})}>
{children.map(renderColumn)}
</div>
);
}
Columns.propTypes = {
children: PropTypes.array.isRequired,
tight: PropTypes.bool,
flexible: PropTypes.bool
};
|
'use strict';
const ENABLE = true;
const ReactNative = require('react-native');
const {
NativeModules,
} = ReactNative;
module.exports = ENABLE ? NativeModules.Des : {
encrypt: (text, key, callback) => callback(text),
decrypt: (code, key, callback) => callback(code),
};
|
"use strict";
/* eslint-disable */
const TwitterApp = angular.module("TwitterWidget", ["ui.router"]);
TwitterApp.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('twIndex', {
url: "/",
templateUrl: "./widgets/twitter_widget/partials/default.html",
controller: "DefaultCtrl"
});
});
|
import React from "react";
import Spinner from "./WrapperSpinner";
import DefaultLayout from "./DefaultLayout";
import * as setupConnection from "../constants/socketConnection";
export default class Main extends React.Component {
componentDidMount() {
const actions = this.props.actions;
actions.serverOpenConnection({
url: setupConnection.SOCKET_URL,
reconnectTimeout: setupConnection.RECONNECT_TIMEOUT,
reconnectAttempts: setupConnection.RECONNECT_ATTEMPTS,
testMessage: setupConnection.TEST_MESSAGE
});
// actions.messageShow("test message");
}
componentWillUnmount() {
const actions = this.props.actions;
actions.serverCloseConnection();
}
render() {
const storeState = this.props.storeState;
const spinner = storeState.serverConnection.state === setupConnection.State.CONNECTING ? <Spinner /> : null;
const connectError = storeState.serverConnection.state === setupConnection.State.CLOSED;
return (
<div>
{spinner}
<DefaultLayout connectError = {connectError} />
</div>
);
}
}
|
/**
* simple_locator
* http://roman.tao.at
*
* Copyright (c) 2010, Roman Weinberger
* Licensed under the MIT License.
*/
var simple_locator = function(usr_options) {
// default options
var options = {
threshold : 50,
google_geocoding : false, // needs included google api
running_callback : false,
finished_callback : false,
error_callback : false,
unknown_location_string : "unknown location",
set_from : function(usr_options) { for( var key in usr_options ) this[key] = usr_options[key]; }
};
options.set_from(usr_options);
var run_callbacks = function(coords, location, watch_id) {
if( options.threshold > coords.accuracy ) {
options.finished_callback(coords, location);
navigator.geolocation.clearWatch(watch_id);
} else {
options.running_callback(coords, location);
}
};
var init_locator = function() {
var watch_id = navigator.geolocation.watchPosition(
function(loc) {
if( options.google_geocoding ) {
(new google.maps.Geocoder()).geocode({
'latLng' : new google.maps.LatLng(loc.coords.latitude, loc.coords.longitude)
}, function(res, x) {
var loc_found = options.unknown_location_string;
if( x == google.maps.GeocoderStatus.OK ) {
if( typeof res[0] != "undefined" ) {
var loc_found = res[0].formatted_address;
}
}
run_callbacks(loc.coords, loc_found, watch_id);
}
);
} else {
run_callbacks(loc.coords, options.unknown_location_string, watch_id);
}
}, function(error) { // oops something bad happende
if( options.error_callback ) options.error_callback(error);
}
);
};
// check if browser supports the geolocation api
if( typeof navigator.geolocation != "undefined" ) {
init_locator();
return true;
} else {
return false;
}
}; |
export { default } from './GoPlain'
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@angular/core");
var column_header_directive_1 = require("./column-header.directive");
var column_cell_directive_1 = require("./column-cell.directive");
var DataTableColumnDirective = (function () {
function DataTableColumnDirective() {
}
DataTableColumnDirective.decorators = [
{ type: core_1.Directive, args: [{ selector: 'ngx-datatable-column' },] },
];
/** @nocollapse */
DataTableColumnDirective.ctorParameters = function () { return []; };
DataTableColumnDirective.propDecorators = {
'name': [{ type: core_1.Input },],
'prop': [{ type: core_1.Input },],
'frozenLeft': [{ type: core_1.Input },],
'frozenRight': [{ type: core_1.Input },],
'flexGrow': [{ type: core_1.Input },],
'resizeable': [{ type: core_1.Input },],
'comparator': [{ type: core_1.Input },],
'pipe': [{ type: core_1.Input },],
'sortable': [{ type: core_1.Input },],
'draggable': [{ type: core_1.Input },],
'canAutoResize': [{ type: core_1.Input },],
'minWidth': [{ type: core_1.Input },],
'width': [{ type: core_1.Input },],
'maxWidth': [{ type: core_1.Input },],
'checkboxable': [{ type: core_1.Input },],
'headerCheckboxable': [{ type: core_1.Input },],
'headerClass': [{ type: core_1.Input },],
'cellClass': [{ type: core_1.Input },],
'cellTemplate': [{ type: core_1.Input }, { type: core_1.ContentChild, args: [column_cell_directive_1.DataTableColumnCellDirective, { read: core_1.TemplateRef },] },],
'headerTemplate': [{ type: core_1.Input }, { type: core_1.ContentChild, args: [column_header_directive_1.DataTableColumnHeaderDirective, { read: core_1.TemplateRef },] },],
};
return DataTableColumnDirective;
}());
exports.DataTableColumnDirective = DataTableColumnDirective;
//# sourceMappingURL=column.directive.js.map |
var sync = require('synchronize');
var request = require('request');
// The Type Ahead API.
module.exports = function(req, res) {
var user = req.query.text.trim();
if (!user) {
res.json([{
title: '<i>(enter a username or organization)</i>',
text: ''
}]);
return;
}
// Compared to the tutorial, there's no need for underscore. Our Mixmax typeahead dropdown should only contain one
// entry per query
var response;
try {
response = sync.await(request({
url: 'https://api.github.com/users/' + user,
'headers': {
'user-agent': 'alexadusei'
},
json: true,
timeout: 10 * 1000,
}, sync.defer()));
} catch (e) {
res.status(500).send('Error');
return;
}
// Essentially happens when the user doesn't exist, return no results
if (response.statusCode !== 200 || !response.body) {
res.json([{
title: '<i>(no results)</i>',
text: ''
}]);
return;
}
// Display their bios. If they have none, just display their name
var textInfo = !response.body.bio ? response.body.name : response.body.bio;
// Some GitHub users don't even have names.. (bots?). If so, leave the field blank.
var textInfo = !textInfo ? '' : textInfo;
res.json([ {
title: '<img style="height:75px;float:left" src="' + response.body.avatar_url + '">' +
'<p style="height:75px;margin-left:80px">' + textInfo + '</p>',
text: user
}]);
};
|
import React from 'react'
import ReactDataGrid from 'react-data-grid';
import {connect} from 'react-redux'
import { Editors, Formatters } from 'react-data-grid-addons';
import cs from '../../../../services/CommunicationService'
import $ from "jquery";
class _HousingInfo extends React.Component{
constructor(props) {
super(props);
this.state = {
data:[]
}
this._columns = [
{ key: 'address', name: 'Address', resizable: true },
{ key: 'value', name: 'Value', resizable: true },
{ key: 'link', name: 'Link', resizable: true} ];
this.rowGetter = this.rowGetter.bind(this);
cs.registerGlobal("housingJSONPCallback", function(data){
cs.dispatch({"type":"LoadHousing", "data":data.properties.comparables});
});
}
rowGetter(i) {
let d = this.props.data[i];
let a = d.address;
return {"address":a.street+", "+ [a.city, a.state, a.zipcode].join(" "), "value":d.zestimate.amount["#text"]+" "+d.zestimate.amount["@currency"], "link":d.links.homedetails}
}
componentWillMount () {
$.ajax({
url: 'https://verdant.tchmachines.com/~coolsha/markqian/AngularJS/Directives/RoutedTab/data/House_JSONP.json',
dataType: "jsonp",
crossDomain: true,
jsonpCallback:'aaa',//<<<
success: function() { console.log("success"); },
error: function() { console.log("error"); }
});
}
/**
* render
* @return {ReactElement} markup
*/
render(){
return (
<div id="todoList" style={{backgroundColor:'#b0e0e6', minHeight:'500px', marginTop:'-10px', marginLeft:'-20px'}}>
<h4>Housing Info (JSONP)</h4>
<div style={{minHeight:'250px'}}>
<ReactDataGrid
columns={this._columns}
rowGetter={this.rowGetter}
rowsCount={this.props.data.length}
minHeight={500}
emptyRowsView={EmptyRowsView}
/>
</div>
</div>
)
}
}
import createReactClass from 'create-react-class'
const EmptyRowsView = createReactClass({
render() {
return (<div>[House list is empty]</div>);
}
});
const HousingInfo = connect(
store => {
return {
data: store.HousingReducer.data
};
}
)(_HousingInfo);
export default HousingInfo |
module.exports = function resizeRendererFn( app, canvas ) {
return function resizeRenderer() {
const w = 0.5 * window.innerWidth * window.devicePixelRatio
const h = 0.5 * window.innerHeight * window.devicePixelRatio
canvas.width = w
canvas.height = h
app.aspectRatio = w / h
app.gl.viewport(0, 0, w, h);
app.width = w
app.height = h
}
} |
define(['js/data/Entity', 'app/validator/IpAddressValidator', 'app/validator/NetmaskAddressValidator'],
function (Entity, IpAddressValidator, NetmaskAddressValidator) {
var whenStatic = function () {
return this.$.mode === 'static';
};
var whenPPPoE = function () {
return this.$.mode === 'pppoe';
};
var whenUseDhcpDns = function () {
return !this.$.useDhcpDns;
};
var whenMacAddressOverride = function () {
return this.$.overrideMacAddress;
};
return Entity.inherit('app.entity.WanConfiguration', {
schema: {
name: String,
enableNat: Boolean,
mode: String,
staticIpAddress: {
required: whenStatic,
type: String
},
staticNetmask: {
required: whenStatic,
type: String
},
staticGateway: {
required: whenStatic,
type: String
},
pppoeUsername: {
required: whenPPPoE,
type: String
},
pppoePassword: {
required: whenPPPoE,
type: String
},
overrideMacAddress: Boolean,
macAddress: {
required: whenMacAddressOverride,
type: String
},
'interface': String,
useDhcpDns: Boolean,
dnsServer1: {
required: whenUseDhcpDns,
type: String
},
dnsServer2: {required: false, type: String},
dnsServer3: {required: false, type: String}
},
defaults: {
name: 'WAN',
enableNat: true,
mode: 'dhcp',
overrideMacAddress: false,
'interface': 'eth0',
useDhcpDns: true
},
validators: [
new IpAddressValidator({field: "dnsServer1"}),
new IpAddressValidator({field: "dnsServer2"}),
new IpAddressValidator({field: "dnsServer3"}),
new IpAddressValidator({field: "staticIpAddress"}),
new NetmaskAddressValidator({field: "staticNetmask"}),
new IpAddressValidator({field: "staticGateway"})
],
_commitMode: function(newMode, oldMode){
if (newMode !== 'pppoe') {
this.set('pppoeUsername', '');
this.set('pppoePassword', '');
}
if (newMode !== 'static') {
this.set('staticIpAddress', '');
this.set('staticNetmask', '');
this.set('staticGateway', '');
} else {
this.set('useDhcpDns', false);
}
}
});
});
|
/* global document Image */
import MouseHandler from '../../../Interaction/Core/MouseHandler';
import SizeHelper from '../../../Common/Misc/SizeHelper';
export default class NativeImageRenderer {
constructor(domElement, imageProvider, mouseListeners = null, drawFPS = true) {
this.size = SizeHelper.getSize(domElement);
this.container = domElement;
this.canvas = document.createElement('canvas');
this.image = new Image();
this.fps = '';
this.drawFPS = drawFPS;
this.subscriptions = [];
this.imageProvider = imageProvider;
this.image.onload = () => {
this.updateDrawnImage();
};
// Update DOM
this.container.appendChild(this.canvas);
this.ctx = this.canvas.getContext('2d');
this.ctx.font = '30px Arial';
// Attach mouse listener if needed
if (mouseListeners) {
this.mouseHandler = new MouseHandler(this.canvas);
this.mouseHandler.attach(mouseListeners);
}
// Add image listener
this.subscriptions.push(imageProvider.onImageReady((data, envelope) => {
this.image.src = data.url;
this.fps = `${data.fps} fps`;
}));
// Add size listener
this.subscriptions.push(SizeHelper.onSizeChange(() => {
this.size = SizeHelper.getSize(domElement);
this.canvas.setAttribute('width', this.size.clientWidth);
this.canvas.setAttribute('height', this.size.clientHeight);
if (this.image.src && this.image.complete) {
this.updateDrawnImage();
}
}));
SizeHelper.startListening();
}
destroy() {
while (this.subscriptions.length) {
this.subscriptions.pop().unsubscribe();
}
if (this.mouseHandler) {
this.mouseHandler.destroy();
this.mouseHandler = null;
}
this.container = null;
this.imageProvider = null;
}
updateDrawnImage() {
this.ctx.drawImage(this.image, 0, 0);
if (this.drawFPS) {
this.ctx.textBaseline = 'top';
this.ctx.textAlign = 'left';
this.ctx.fillText(this.fps, 5, 5);
}
}
}
|
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
}
// lib: {
// src: ['lib/**/*.js']
// }
},
coffee: {
compile: {
options: {
bare: false
},
files: {
'ish/js/browserio.js': 'src/browserio.coffee',
'ish/js/remoteio.js': 'src/remoteio.coffee'
}
},
compilebare: {
options: {
bare: true
},
files: {
'config.js': 'src/config.coffee',
'lib/ishremote.js': 'src/ishremote.coffee'
}
}
},
less: {
compile: {
src: ['less/*.less'],
dest: 'ish/css/remote.css'
}
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
coffee: {
options: {
spawn: false
},
files: ['src/**/*.coffee'],
tasks: ['coffee']
},
less: {
files: ['less/**/*.less'],
tasks: ['less']
}
// lib: {
// files: '<%= jshint.lib.src %>',
// tasks: ['jshint:lib', 'nodeunit']
// }
}
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-coffee');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
// Default task.
grunt.registerTask('default', ['jshint']);
};
|
import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import { purple } from '@material-ui/core/colors';
import FormGroup from '@material-ui/core/FormGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Switch from '@material-ui/core/Switch';
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
const PurpleSwitch = withStyles({
switchBase: {
color: purple[300],
'&$checked': {
color: purple[500],
},
'&$checked + $track': {
backgroundColor: purple[500],
},
},
checked: {},
track: {},
})(Switch);
const IOSSwitch = withStyles((theme) => ({
root: {
width: 42,
height: 26,
padding: 0,
margin: theme.spacing(1),
},
switchBase: {
padding: 1,
'&$checked': {
transform: 'translateX(16px)',
color: theme.palette.common.white,
'& + $track': {
backgroundColor: '#52d869',
opacity: 1,
border: 'none',
},
},
'&$focusVisible $thumb': {
color: '#52d869',
border: '6px solid #fff',
},
},
thumb: {
width: 24,
height: 24,
},
track: {
borderRadius: 26 / 2,
border: `1px solid ${theme.palette.grey[400]}`,
backgroundColor: theme.palette.grey[50],
opacity: 1,
transition: theme.transitions.create(['background-color', 'border']),
},
checked: {},
focusVisible: {},
}))(({ classes, ...props }) => {
return (
<Switch
focusVisibleClassName={classes.focusVisible}
disableRipple
classes={{
root: classes.root,
switchBase: classes.switchBase,
thumb: classes.thumb,
track: classes.track,
checked: classes.checked,
}}
{...props}
/>
);
});
const AntSwitch = withStyles((theme) => ({
root: {
width: 28,
height: 16,
padding: 0,
display: 'flex',
},
switchBase: {
padding: 2,
color: theme.palette.grey[500],
'&$checked': {
transform: 'translateX(12px)',
color: theme.palette.common.white,
'& + $track': {
opacity: 1,
backgroundColor: theme.palette.primary.main,
borderColor: theme.palette.primary.main,
},
},
},
thumb: {
width: 12,
height: 12,
boxShadow: 'none',
},
track: {
border: `1px solid ${theme.palette.grey[500]}`,
borderRadius: 16 / 2,
opacity: 1,
backgroundColor: theme.palette.common.white,
},
checked: {},
}))(Switch);
export default function CustomizedSwitches() {
const [state, setState] = React.useState({
checkedA: true,
checkedB: true,
checkedC: true,
});
const handleChange = (event) => {
setState({ ...state, [event.target.name]: event.target.checked });
};
return (
<FormGroup>
<FormControlLabel
control={<PurpleSwitch checked={state.checkedA} onChange={handleChange} name="checkedA" />}
label="Custom color"
/>
<FormControlLabel
control={<IOSSwitch checked={state.checkedB} onChange={handleChange} name="checkedB" />}
label="iOS style"
/>
<Typography component="div">
<Grid component="label" container alignItems="center" spacing={1}>
<Grid item>Off</Grid>
<Grid item>
<AntSwitch checked={state.checkedC} onChange={handleChange} name="checkedC" />
</Grid>
<Grid item>On</Grid>
</Grid>
</Typography>
</FormGroup>
);
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:c9adf4f15de21f2bc8e07c750387fc118e03cdbfaec876b77ab7d038ae4143ac
size 2509
|
version https://git-lfs.github.com/spec/v1
oid sha256:802c0d1f6a2affbf937d5a43b7fced052d84d52d3cc341fa982289508e68d482
size 9906
|
'use strict';
var SurveyLoader = function() {
this.surveys = [
{
title: 'Food Survey',
desc: 'Please answer the below questions about your most recent meal.',
label: '[Health Food]',
questions: [
{
type: 'radio',
question: 'What meal did you just eat?',
options: ['Breakfast','Lunch','Dinner','Snack','Other']
},
{
type: 'text',
question: 'Please describe the food that you consumed during this meal:'
},
{
type: 'range',
question: 'How did you feel after this meal?'
}
],
trigger: {
type: 'time',
interval: 'daily',
hour: 21,
minute: 14,
second: 0,
occurrences: 1
}
}
];
};
SurveyLoader.prototype.get = function get() {
return this.surveys;
};
|
/* @flow weak */
require('dotenv').config();
const Koa = require('koa');
const serve = require('koa-static');
const bodyParser = require('koa-bodyparser');
const router = require('koa-router')();
const oracledb = require('oracledb');
const remoteBase64 = require('node-remote-base64');
const api = require('./api');
const renderView = require('./util/render-view');
const executePLSQL = require('./util/db');
const dataOps = require('./data-ops');
const formsData = require('./util/form-data-helper');
router
.get('home', '/', async (ctx, next) => {
ctx.body = await renderView('./www/views/index.hbs');
await next();
})
.get('forms', '/forms', async (ctx, next) => {
ctx.body = await renderView('./www/views/forms.hbs', formsData);
await next();
})
.get('errors', '/errors', async (ctx, next) => {
const data = await executePLSQL(...dataOps.getErrorsRegistry());
ctx.body = await renderView('./www/views/errors.hbs', { table: data.rows} );
await next();
})
.get('sales', '/sales', async (ctx, next) => {
const data = await executePLSQL(...dataOps.getReadableSalesRegistry());
ctx.body = await renderView('./www/views/sales.hbs', { table: data.rows} );
await next();
})
.get('users', '/users', async (ctx, next) => {
const data = await executePLSQL(...dataOps.getAllUsers());
ctx.body = await renderView('./www/views/users.hbs', { table: data.rows} );
await next();
});
const app = new Koa();
app
.use(bodyParser())
.use(router.routes())
.use(api.routes())
.use(api.allowedMethods())
.use(router.allowedMethods())
.use(serve(__dirname + '/static'));
app.listen(3000);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.