code
stringlengths 2
1.05M
|
---|
import database from "../api/database";
import * as types from "../actions/ActionTypes"
const receiveAspects = aspects => ({
type: types.GET_COMMON_ASPECTS,
aspects
});
export const getCommonAspects = () => dispatch => {
database.getCommonAspects(aspects => {
dispatch(receiveAspects(aspects))
})
};
export const loadAll = () => ({
type: types.LOAD_ALL_ASPECTS
}); |
var https = require('https'),
q = require('q'),
cache = require('./cache').cache;
var API_KEY = process.env.TF_MEETUP_API_KEY;
var fetch_events = function () {
var deferred = q.defer();
var options = {
host: 'api.meetup.com',
path: '/2/events?&sign=true&photo-host=public&group_urlname=GOTO-Night-Stockholm&page=20&key=' + API_KEY
};
var callback = function (response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
var json = JSON.parse(str);
deferred.resolve(json.results);
});
};
var req = https.request(options, callback);
req.on('error', function (e) {
deferred.reject(e);
});
req.end();
return deferred.promise;
};
module.exports.fetch_events = cache(fetch_events, 10000, true, []);
|
/* globals Ember, require */
(function() {
var _Ember;
var id = 0;
var dateKey = new Date().getTime();
if (typeof Ember !== 'undefined') {
_Ember = Ember;
} else {
_Ember = require('ember').default;
}
function symbol() {
return '__ember' + dateKey + id++;
}
function UNDEFINED() {}
function FakeWeakMap(iterable) {
this._id = symbol();
if (iterable === null || iterable === undefined) {
return;
} else if (Array.isArray(iterable)) {
for (var i = 0; i < iterable.length; i++) {
var key = iterable[i][0];
var value = iterable[i][1];
this.set(key, value);
}
} else {
throw new TypeError('The weak map constructor polyfill only supports an array argument');
}
}
if (!_Ember.WeakMap) {
var meta = _Ember.meta;
var metaKey = symbol();
/*
* @method get
* @param key {Object}
* @return {*} stored value
*/
FakeWeakMap.prototype.get = function(obj) {
var metaInfo = meta(obj);
var metaObject = metaInfo[metaKey];
if (metaInfo && metaObject) {
if (metaObject[this._id] === UNDEFINED) {
return undefined;
}
return metaObject[this._id];
}
}
/*
* @method set
* @param key {Object}
* @param value {Any}
* @return {Any} stored value
*/
FakeWeakMap.prototype.set = function(obj, value) {
var type = typeof obj;
if (!obj || (type !== 'object' && type !== 'function')) {
throw new TypeError('Invalid value used as weak map key');
}
var metaInfo = meta(obj);
if (value === undefined) {
value = UNDEFINED;
}
if (!metaInfo[metaKey]) {
metaInfo[metaKey] = {};
}
metaInfo[metaKey][this._id] = value;
return this;
}
/*
* @method has
* @param key {Object}
* @return {Boolean} if the key exists
*/
FakeWeakMap.prototype.has = function(obj) {
var metaInfo = meta(obj);
var metaObject = metaInfo[metaKey];
return (metaObject && metaObject[this._id] !== undefined);
}
/*
* @method delete
* @param key {Object}
*/
FakeWeakMap.prototype.delete = function(obj) {
var metaInfo = meta(obj);
if (this.has(obj)) {
delete metaInfo[metaKey][this._id];
return true;
}
return false;
}
if (typeof WeakMap === 'function' && typeof window !== 'undefined' && window.OVERRIDE_WEAKMAP !== true) {
_Ember.WeakMap = WeakMap;
} else {
_Ember.WeakMap = FakeWeakMap;
}
}
})();
|
import Resolver from 'ember/resolver';
var resolver = Resolver.create();
resolver.namespace = {
modulePrefix: 'todo-app'
};
export default resolver;
|
export { default } from './ui'
export * from './ui.selectors'
export * from './tabs'
|
/*
Credits: Most of the original code seems to have been
written by George Michael Brower. The changes I've made
include adding background particle animations, text
placement and modification, and integration with a
sparkfun heart rate monitor by using Pubnub and johnny-five.
INSTRUCTIONS
- npm install [email protected]
- npm install johnny-five
- node Board.js to hook up to johnnyfive
*/
function FizzyText(message) {
var that = this;
// These are the variables that we manipulate with gui-dat.
// Notice they're all defined with "this". That makes them public.
// Otherwise, gui-dat can't see them.
this.growthSpeed = 0.98; // how fast do particles change size?
// this.maxSize = getRandomIntInclusive(3, 4); // how big can they get?
this.maxSize = 1.3;
this.noiseStrength = 1.9; // how turbulent is the flow?
this.bgNoiseStrength = 10;
this.speed = 0; // how fast do particles move?
this.bgSpeed = 0.4;
this.displayOutline = false; // should we draw the message as a stroke?
this.framesRendered = 0;
// this.color0 = "#00aeff";
// this.color1 = "#0fa954";
// this.color2 = "#54396e";
// this.color3 = "#e61d5f";
// this.color0 = "#ffdcfc";
// this.color1 = "#c8feff";
// this.color2 = "#ffffff";
// this.color3 = "#c8feff";
this.color0 = "#f0cf5b";
this.color1 = "#2abbf2";
this.color2 = "#660aaf";
this.color3 = "#f57596";
this.bgParticleColor = "#ffffff";
this.fontSize = 100;
this.fontWeight = 800;
// __defineGetter__ and __defineSetter__ make JavaScript believe that
// we've defined a variable 'this.message'. This way, whenever we
// change the message variable, we can call some more functions.
this.__defineGetter__("message", function() {
return message;
});
this.__defineSetter__("message", function(m) {
message = m;
createBitmap(message);
});
// We can even add functions to the DAT.GUI! As long as they have 0 argumets,
// we can call them from the dat-gui panel.
this.explode = function() {
var mag = Math.random() * 30 + 30;
for (var i in particles) {
var angle = Math.random() * Math.PI * 2;
particles[i].vx = Math.cos(angle) * mag;
particles[i].vy = Math.sin(angle) * mag;
}
};
////////////////////////////////
var _this = this;
var width = window.innerWidth;
var height = window.innerHeight;
// var textAscent = Math.random() * height; // for trans
var textAscent = height / 2; // for cisco
// var textOffsetLeft = Math.random() * width;
var textOffsetLeft = 0;
var noiseScale = 300;
var frameTime = 30;
// Keep the message within the canvas height bounds
while ((textAscent > height - 100) || textAscent < 100) {
textAscent = Math.random() * height;
}
var colors = [_this.color0, _this.color1, _this.color2, _this.color3];
// This is the context we use to get a bitmap of text using the
// getImageData function.
var r = document.createElement('canvas');
var s = r.getContext('2d');
// This is the context we actually use to draw.
var c = document.createElement('canvas');
var g = c.getContext('2d');
r.setAttribute('width', width);
c.setAttribute('width', width);
r.setAttribute('height', height);
c.setAttribute('height', height);
// Add our demo to the HTML
document.getElementById('fizzytext').appendChild(c);
// Stores bitmap image
var pixels = [];
// Stores a list of particles
var particles = [];
var bgParticles = [];
// Set g.font to the same font as the bitmap canvas, incase we want to draw some outlines
var fontAttr = _this.fontWeight + " " + _this.fontSize + "px helvetica, arial, sans-serif";
s.font = g.font = fontAttr;
// Instantiate some particles
for (var i = 0; i < 2000; i++) {
particles.push(new Particle(Math.random() * width, Math.random() * height));
}
// 2nd perlin field
for (var i = 0; i < 1000; i++) { // 10k particles
bgParticles.push(new bgParticle(Math.random() * width, Math.random() * height));
}
// This function creates a bitmap of pixels based on your message
// It's called every time we change the message property.
var createBitmap = function(msg) {
s.fillStyle = "#fff";
s.fillRect(0, 0, width, height);
s.fillStyle = "#222";
// Keep the message within canvas width bounds
var msgWidth = s.measureText(msg).width;
// while (textOffsetLeft + msgWidth > widthw) {
// // textOffsetLeft = Math.random() * width;
// }
textOffsetLeft = (width - msgWidth) / 2;
s.fillText(msg, textOffsetLeft, textAscent);
// Pull reference
var imageData = s.getImageData(0, 0, width, height);
pixels = imageData.data;
};
// Called once per frame, updates the animation.
var render = function() {
that.framesRendered++;
// g.clearRect(0, 0, width, height);
// Set the shown canvas background as black
g.rect(0, 0, width, height);
g.fillStyle = "black"; // for trans
// g.fillStyle = "#eee"; // for cisco
g.fill();
if (_this.displayOutline) {
g.globalCompositeOperation = "source-over";
// g.strokeStyle = "#000"; // for trans
g.strokeStyle = "#fff";
g.font = _this.fontSize + "px helvetica, arial, sans-serif"; // took out font weight
g.lineWidth = .5;
g.strokeText(message, textOffsetLeft, textAscent);
}
g.globalCompositeOperation = "darker";
// Choose particle color
for (var i = 0; i < particles.length; i++) {
g.fillStyle = colors[i % colors.length];
particles[i].render();
}
// Choose bg particle color (white for testing)
for (var i = 0; i < bgParticles.length; i++) {
g.fillStyle = _this.bgParticleColor;
bgParticles[i].render();
}
};
// Func tells me where x, y is for each pixel of the text
// Returns x, y coordinates for a given index in the pixel array.
var getPosition = function(i) {
return {
x: (i - (width * 4) * Math.floor(i / (width * 4))) / 4,
y: Math.floor(i / (width * 4))
};
};
// Returns a color for a given pixel in the pixel array
var getColor = function(x, y) {
var base = (Math.floor(y) * width + Math.floor(x)) * 4;
var c = {
r: pixels[base + 0],
g: pixels[base + 1],
b: pixels[base + 2],
a: pixels[base + 3]
};
return "rgb(" + c.r + "," + c.g + "," + c.b + ")";
};
// This calls the setter we've defined above, so it also calls
// the createBitmap function
this.message = message;
// Set the canvas bg
// document.getElementById('fizzytext').style.backgroundColor = colors[Math.floor(Math.random() * 4)]
function resizeCanvas() {
r.width = window.innerWidth;
c.width = window.innerWidth;
r.height = window.innerHeight;
c.height = window.innerHeight;
}
var loop = function() {
// Reset color array
colors = [_this.color0, _this.color1, _this.color2, _this.color3]; // Change colors from dat.gui
s.font = g.font = _this.fontWeight + " " + _this.fontSize + "px helvetica, arial, sans-serif";
createBitmap(message);
// _this.fontSize += 1;
resizeCanvas();
render();
requestAnimationFrame(loop);
}
// This calls the render function every 30ms
loop();
/////////////////////////////////////////////
// This class is responsible for drawing and moving those little
// colored dots.
function Particle(x, y, c) {
// Position
this.x = x;
this.y = y;
// Size of particle
this.r = 0;
// This velocity is used by the explode function.
this.vx = 0;
this.vy = 0;
this.constrain = function(v, o1, o2) {
if (v < o1) v = o1;
else if (v > o2) v = o2;
return v;
};
// Called every frame
this.render = function () {
// What color is the pixel we're sitting on top of?
var c = getColor(this.x, this.y);
// Where should we move?
var angle = noise(this.x / noiseScale, this.y / noiseScale) * _this.noiseStrength;
// Are we within the boundaries of the image?
var onScreen = this.x > 0 && this.x < width && this.y > 0 && this.y < height;
var isBlack = c != "rgb(255,255,255)" && onScreen;
// If we're on top of a black pixel, grow.
// If not, shrink.
if (isBlack) {
this.r += _this.growthSpeed;
} else {
this.r -= _this.growthSpeed;
}
// This velocity is used by the explode function.
this.vx *= 0.5;
this.vy *= 0.5;
// Change our position based on the flow field and our explode velocity.
this.x += Math.cos(angle) * _this.speed + this.vx;
this.y += -Math.sin(angle) * _this.speed + this.vy;
// this.r = 3;
// debugger
// console.log(DAT.GUI.constrain(this.r, 0, _this.maxSize));
this.r = this.constrain(this.r, 0, _this.maxSize);
// If we're tiny, keep moving around until we find a black pixel.
if (this.r <= 0) {
this.x = Math.random() * width;
this.y = Math.random() * height;
return; // Don't draw!
}
// Draw the circle.
g.beginPath();
g.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
g.fill();
}
}
function bgParticle(x, y, c) {
// Position
this.x = x;
this.y = y;
// Size of particle
this.r = 0;
// This velocity is used by the explode function.
this.vx = 0;
this.vy = 0;
this.constrain = function(v, o1, o2) {
if (v < o1) v = o1;
else if (v > o2) v = o2;
return v;
};
// Called every frame
this.render = function () {
// What color is the pixel we're sitting on top of?
var c = getColor(this.x, this.y);
// Where should we move?
var angle = noise(this.x / noiseScale, this.y / noiseScale) * _this.bgNoiseStrength;
// Are we within the boundaries of the image?
var onScreen = this.x > 0 && this.x < width && this.y > 0 && this.y < height;
var isBlack = c != "rgb(255,255,255)" && onScreen;
// If we're on top of a black pixel, grow.
// If not, shrink.
if (isBlack) {
this.r -= _this.growthSpeed / 2;
// this.r -= Math.abs(Math.sin(_this.growthSpeed));
} else {
// this.r += _this.growthSpeed / 2;
this.r += Math.abs(Math.sin(_this.growthSpeed));
}
// if not on screen respawn somewhere random
if (!onScreen) {
this.x = Math.random() * width;
this.y = Math.random() * height;
}
// This velocity is used by the explode function.
this.vx *= 0.5;
this.vy *= 0.5;
// Change our position based on the flow field and our explode velocity.
this.x += Math.cos(angle) * _this.bgSpeed + this.vx;
this.y += -Math.sin(angle) * _this.bgSpeed + this.vy;
// this.r = 3;
// debugger
// console.log(DAT.GUI.constrain(this.r, 0, _this.maxSize));
this.r = this.constrain(this.r, 0, 2);
// If we're tiny, keep moving around until we find a black pixel.
if (this.r <= 0) {
this.x = Math.random() * width;
this.y = Math.random() * height;
return; // Don't draw!
}
// Draw the circle.
g.beginPath();
g.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
g.fill();
}
}
}
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
} |
define("resolver",
[],
function() {
"use strict";
/*
* This module defines a subclass of Ember.DefaultResolver that adds two
* important features:
*
* 1) The resolver makes the container aware of es6 modules via the AMD
* output. The loader's _seen is consulted so that classes can be
* resolved directly via the module loader, without needing a manual
* `import`.
* 2) is able provide injections to classes that implement `extend`
* (as is typical with Ember).
*/
function classFactory(klass) {
return {
create: function (injections) {
if (typeof klass.extend === 'function') {
return klass.extend(injections);
} else {
return klass;
}
}
};
}
var underscore = Ember.String.underscore;
var classify = Ember.String.classify;
var get = Ember.get;
function parseName(fullName) {
var nameParts = fullName.split(":"),
type = nameParts[0], fullNameWithoutType = nameParts[1],
name = fullNameWithoutType,
namespace = get(this, 'namespace'),
root = namespace;
return {
fullName: fullName,
type: type,
fullNameWithoutType: fullNameWithoutType,
name: name,
root: root,
resolveMethodName: "resolve" + classify(type)
};
}
function chooseModuleName(seen, moduleName) {
var underscoredModuleName = Ember.String.underscore(moduleName);
if (moduleName !== underscoredModuleName && seen[moduleName] && seen[underscoredModuleName]) {
throw new TypeError("Ambigous module names: `" + moduleName + "` and `" + underscoredModuleName + "`");
}
if (seen[moduleName]) {
return moduleName;
} else if (seen[underscoredModuleName]) {
return underscoredModuleName;
} else {
return moduleName;
}
}
function resolveOther(parsedName) {
var prefix = this.namespace.modulePrefix;
Ember.assert('module prefix must be defined', prefix);
var pluralizedType = parsedName.type + 's';
var name = parsedName.fullNameWithoutType;
var moduleName = prefix + '/' + pluralizedType + '/' + name;
// allow treat all dashed and all underscored as the same thing
// supports components with dashes and other stuff with underscores.
var normalizedModuleName = chooseModuleName(requirejs._eak_seen, moduleName);
if (requirejs._eak_seen[normalizedModuleName]) {
var module = require(normalizedModuleName, null, null, true /* force sync */);
if (module === undefined) {
throw new Error("Module: '" + name + "' was found but returned undefined. Did you forget to `export default`?");
}
if (Ember.ENV.LOG_MODULE_RESOLVER) {
Ember.Logger.info('hit', moduleName);
}
return module;
} else {
if (Ember.ENV.LOG_MODULE_RESOLVER) {
Ember.Logger.info('miss', moduleName);
}
return this._super(parsedName);
}
}
function resolveTemplate(parsedName) {
return Ember.TEMPLATES[parsedName.name] || Ember.TEMPLATES[Ember.String.underscore(parsedName.name)];
}
// Ember.DefaultResolver docs:
// https://github.com/emberjs/ember.js/blob/master/packages/ember-application/lib/system/resolver.js
var Resolver = Ember.DefaultResolver.extend({
resolveTemplate: resolveTemplate,
resolveOther: resolveOther,
parseName: parseName,
normalize: function(fullName) {
// replace `.` with `/` in order to make nested controllers work in the following cases
// 1. `needs: ['posts/post']`
// 2. `{{render "posts/post"}}`
// 3. `this.render('posts/post')` from Route
return Ember.String.dasherize(fullName.replace(/\./g, '/'));
}
});
return Resolver;
});
|
(function() {
'use strict';
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '../client')));
app.use('/', routes);
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
module.exports = app;
}());
|
"use strict";
var C = function () {
function C() {
babelHelpers.classCallCheck(this, C);
}
babelHelpers.createClass(C, [{
key: "m",
value: function m(x) {
return 'a';
}
}]);
return C;
}();
|
var assert = require('assert');
var fs = require('fs');
var requireFiles = require(__dirname + '/../lib/requireFiles');
var files = [
__dirname + '/moch/custom_test.txt',
__dirname + '/moch/json_test.json',
__dirname + '/moch/test.js'
];
describe('requireFiles testing', function(){
describe('Structure type', function(){
it('requireFiles should be a function', function(){
assert.equal(typeof requireFiles, 'function');
});
});
describe('Error', function(){
it('Should throw error when an engine isn\'t supported', function(){
assert.throws(function(){
requireFiles(files, {
'.js' : require,
'.json' : require
});
}, /there is no engine registered/);
});
it('Should not throw an error when everything is ok', function(){
assert.doesNotThrow(function(){
result = requireFiles(files.slice(1, 3), {
'.js' : require,
'.json' : require
});
});
});
});
describe('Custom engine', function(){
it('Custom engines should work', function(){
var result = requireFiles(files, {
'.js' : require,
'.json' : require,
'.txt' : function(path){
return fs.readFileSync(path).toString();
}
});
assert.equal(result[files[0]], 'worked\n');
assert.equal(result[files[1]].worked, true);
assert.equal(result[files[2]], 'worked');
});
});
});
|
export default function() {
var links = [
{
icon: "fa-sign-in",
title: "Login",
url: "/login"
},
{
icon: "fa-dashboard",
title: "Dashboard",
url: "/"
},
{
icon: "fa-calendar",
title: "Scheduler",
url: "/scheduler"
}
];
return m("#main-sidebar", [
m("ul", {class: "navigation"},
links.map(function(link) {
return m("li", [
m("a", {href: link.url, config: m.route}, [
m("i.menu-icon", {class: "fa " + link.icon}), " ", link.title
])
]);
})
)
]);
}
|
const Koa = require('koa');
const http = require('http');
const destroyable = require('server-destroy');
const bodyParser = require('koa-bodyparser');
const session = require('koa-session');
const passport = require('koa-passport');
const serve = require('koa-static');
const db = require('./db');
const config = require('./config');
const router = require('./routes');
const authStrategies = require('./authStrategies');
const User = require('./models/User');
const app = new Koa();
app.use(bodyParser());
app.keys = [config.get('session_secret')];
app.use(session({}, app));
authStrategies.forEach(passport.use, passport);
passport.serializeUser((user, done) => {
done(null, user.twitterId);
});
passport.deserializeUser(async (twitterId, done) => {
const user = await User.findOne({ twitterId });
done(null, user);
});
app.use(passport.initialize());
app.use(passport.session());
app.use(router.routes());
app.use(router.allowedMethods());
app.use(serve('public'));
app.use(async (ctx, next) => {
await next();
if (ctx.status === 404) {
ctx.redirect('/');
}
});
const server = http.createServer(app.callback());
module.exports = {
start() {
db.start().then(() => {
server.listen(config.get('port'));
destroyable(server);
});
},
stop() {
server.destroy();
db.stop();
},
};
|
PhotoAlbums.Router.map(function() {
this.resource('login');
this.resource('album', {path: '/:album_id'});
this.resource('photo', {path: 'photos/:photo_id'});
});
|
import Icon from '../components/Icon.vue'
Icon.register({"arrows":{"width":1792,"height":1792,"paths":[{"d":"M1792 896q0 26-19 45l-256 256q-19 19-45 19t-45-19-19-45v-128h-384v384h128q26 0 45 19t19 45-19 45l-256 256q-19 19-45 19t-45-19l-256-256q-19-19-19-45t19-45 45-19h128v-384h-384v128q0 26-19 45t-45 19-45-19l-256-256q-19-19-19-45t19-45l256-256q19-19 45-19t45 19 19 45v128h384v-384h-128q-26 0-45-19t-19-45 19-45l256-256q19-19 45-19t45 19l256 256q19 19 19 45t-19 45-45 19h-128v384h384v-128q0-26 19-45t45-19 45 19l256 256q19 19 19 45z"}]}})
|
import { h, Component } from 'preact';
import moment from 'moment';
const MonthPicker = ({ onChange, ...props }) => (
<select onChange={onChange} id="select-month">{ optionsFor("month", props.date) }</select>
);
const DayPicker = ({ onChange, ...props }) => (
<select onChange={onChange} id="select-date">{ optionsFor("day", props.date) }</select>
);
const YearPicker = ({ onChange, ...props }) => (
<select onChange={onChange} id="select-year">{ optionsFor("year", props.date) }</select>
);
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
const startYear = 1930;
const endYear = 2018;
function optionsFor(field, selectedDate) {
if (field === 'year') {
selected = selectedDate.year();
return [...Array(endYear-startYear).keys()].map((item, i) => {
var isSelected = (startYear + item) == selected;
return (
<option value={startYear + item} selected={isSelected ? 'selected' : ''}>{startYear + item}</option>
);
});
}
else if (field === 'month') {
selected = selectedDate.month();
return months.map((item, i) => {
var isSelected = i == selected;
return (
<option value={i} selected={isSelected ? 'selected' : ''}>{item}</option>
);
});
}
else if (field === 'day') {
var selected = selectedDate.date();
var firstDay = 1;
var lastDay = moment(selectedDate).add(1, 'months').date(1).subtract(1, 'days').date() + 1;
return [...Array(lastDay-firstDay).keys()].map((item, i) => {
var isSelected = (item + 1) == selected;
return (
<option value={item + 1} selected={isSelected ? 'selected': ''}>{item + 1}</option>
)
});
}
}
export default class DatePicker extends Component {
constructor(props) {
super(props);
this.state = {
date: props.date
};
this.onChange = this.onChange.bind(this);
}
onChange(event) {
var month = document.getElementById('select-month').value;
var day = document.getElementById('select-date').value;
var year = document.getElementById('select-year').value;
var newDate = moment().year(year).month(month).date(day);
this.setState({ date: newDate })
this.props.onChange(newDate);
}
render() {
return (
<div>
<MonthPicker date={this.state.date} onChange={this.onChange} />
<DayPicker date={this.state.date} onChange={this.onChange} />
<YearPicker date={this.state.date} onChange={this.onChange} />
</div>
)
}
} |
'use strict';
angular.module('users').factory('Permissions', ['Authentication', '$location',
function(Authentication, $location) {
// Permissions service logic
// ...
// Public API
return {
//check if user suits the right permissions for visiting the page, Otherwise go to 401
userRolesContains: function (role) {
if (!Authentication.user || Authentication.user.roles.indexOf(role) === -1) {
return false;
} else {
return true;
}
},
//This function returns true if the user is either admin or maintainer
adminOrMaintainer: function () {
if (Authentication.user && (Authentication.user.roles.indexOf('admin')> -1 || Authentication.user.roles.indexOf('maintainer')> -1)) {
return true;
} else {
return false;
}
},
isPermissionGranted: function (role) {
if (!Authentication.user || Authentication.user.roles.indexOf(role) === -1) {
$location.path('/401');
}
},
isAdmin: function () {
if (Authentication.user && (Authentication.user.roles.indexOf('admin') > -1)) {
return true;
} else {
return false;
}
}
};
}
]); |
import $ from 'jquery';
import keyboard from 'virtual-keyboard';
$.fn.addKeyboard = function () {
return this.keyboard({
openOn: null,
stayOpen: false,
layout: 'custom',
customLayout: {
'normal': ['7 8 9 {c}', '4 5 6 {del}', '1 2 3 {sign}', '0 0 {dec} {a}'],
},
position: {
// null (attach to input/textarea) or a jQuery object (attach elsewhere)
of: null,
my: 'center top',
at: 'center top',
// at2 is used when "usePreview" is false (centers keyboard at the bottom
// of the input/textarea)
at2: 'center top',
collision: 'flipfit flipfit'
},
reposition: true,
css: {
input: 'form-control input-sm',
container: 'center-block dropdown-menu',
buttonDefault: 'btn btn-default',
buttonHover: 'btn-light',
// used when disabling the decimal button {dec}
// when a decimal exists in the input area
buttonDisabled: 'enabled',
},
});
};
|
/**
* Trait class
*/
function Trait(methods, allTraits) {
allTraits = allTraits || [];
this.traits = [methods];
var extraTraits = methods.$traits;
if (extraTraits) {
if (typeof extraTraits === "string") {
extraTraits = extraTraits.replace(/ /g, '').split(',');
}
for (var i = 0, c = extraTraits.length; i < c; i++) {
this.use(allTraits[extraTraits[i]]);
}
}
}
Trait.prototype = {
constructor: Trait,
use: function (trait) {
if (trait) {
this.traits = this.traits.concat(trait.traits);
}
return this;
},
useBy: function (obj) {
for (var i = 0, c = this.traits.length; i < c; i++) {
var methods = this.traits[i];
for (var prop in methods) {
if (prop !== '$traits' && !obj[prop] && methods.hasOwnProperty(prop)) {
obj[prop] = methods[prop];
}
}
}
}
};
module.exports = Trait;
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Game = mongoose.model('Game'),
Team = mongoose.model('Team'),
Player = mongoose.model('Player'),
async = require('async');
exports.all = function(req, res) {
Game.find({'played': true}).exec(function(err, games) {
if (err) {
return res.json(500, {
error: 'fucked up grabbing dem games'
});
}
res.json(games);
});
};
exports.logGame = function(req, res, next) {
var loggedGame = req.body;
Game.findAllMatchesBetweenTeams([loggedGame.teams[0].teamId, loggedGame.teams[1].teamId], function(err, games) {
if (err) {
console.log('error finding matchups\n' + err);
res.json(500, 'fucked up finding dem games');
return;
}
var matchedGame;
var teamOneIndex;
var teamTwoIndex;
for (var gameIdx = 0; gameIdx < games.length; gameIdx += 1) {
if (games[gameIdx].teams[0].home === loggedGame.teams[0].home && games[gameIdx].teams[0].teamId.toString() === loggedGame.teams[0].teamId) {
matchedGame = games[gameIdx];
teamOneIndex = 0;
teamTwoIndex = 1;
break;
} else if (games[gameIdx].teams[1].home === loggedGame.teams[0].home && games[gameIdx].teams[1].teamId.toString() === loggedGame.teams[0].teamId) {
matchedGame = games[gameIdx];
teamOneIndex = 1;
teamTwoIndex = 0;
break;
}
}
if (!matchedGame) {
res.json(500, 'no matchup between those teams found');
return;
}
if (matchedGame.played) {
console.log('match already played!');
res.json(500, 'game already played');
return;
}
matchedGame.teams[teamOneIndex].goals = loggedGame.teams[0].goals;
matchedGame.teams[teamOneIndex].events = loggedGame.teams[0].events;
matchedGame.teams[teamTwoIndex].goals = loggedGame.teams[1].goals;
matchedGame.teams[teamTwoIndex].events = loggedGame.teams[1].events;
matchedGame.played = true;
var datePlayed = new Date();
matchedGame.datePlayed = datePlayed;
matchedGame.save(function(err) {
if (err) {
console.log('failed to save game -- ' + matchedGame + ' -- ' + err );
res.json(500, 'error saving game -- ' + err);
} else {
async.series([
function(callback) {
console.log('PROCESSING EVENTS');
processEvents(matchedGame, callback);
},
function(callback) {
console.log('UPDATING STANDINGS');
updateStandings(callback);
}
],
function(err, results) {
if (err) {
res.sendStatus(400);
console.log(err);
} else {
res.sendStatus(200);
}
});
}
});
});
var processEvents = function(game, callback) {
/*jshint -W083 */
var updatePlayerEvents = function(playerEvents, playerCallback) {
console.log('UPDATING EVENTS FOR PLAYER ' + playerEvents.events[0].player);
findOrCreateAndUpdatePlayer(playerEvents, playerEvents.teamId, playerCallback);
};
var processEventsForTeam = function(team, teamCallback) {
console.log('PROCESSING EVENTS FOR ' + team);
var playerEventMap = {};
for (var eventIdx = 0; eventIdx < team.events.length; eventIdx += 1) {
var playerEvent = team.events[eventIdx];
console.log('PROCESSING EVENT ' + playerEvent);
if (playerEventMap[playerEvent.player] === undefined) {
console.log('PLAYER NOT IN MAP, ADDING ' + playerEvent.player);
playerEventMap[playerEvent.player] = {teamId: team.teamId, events: [], gameDate: game.datePlayed};
}
playerEventMap[playerEvent.player].events.push(playerEvent);
}
console.log('player event map created: ' + playerEventMap);
var playerEventMapValues = [];
for (var key in playerEventMap) {
playerEventMapValues.push(playerEventMap[key]);
}
async.each(playerEventMapValues, updatePlayerEvents, function(err) {
if (err) {
teamCallback(err);
} else {
teamCallback();
}
});
};
async.each(game.teams, processEventsForTeam, function(err) {
if (err) {
callback(err);
} else {
callback();
}
});
};
var findOrCreateAndUpdatePlayer = function(playerEvents, teamId, playerCallback) {
console.log('finding/creating player -- ' + playerEvents + ' -- ' + teamId);
Player.findOne({name: playerEvents.events[0].player, teamId: teamId}, function(err, player) {
if (err) {
console.log('error processing events -- ' + JSON.stringify(playerEvents) + ' -- ' + err);
playerCallback(err);
}
if (!player) {
createAndUpdatePlayer(playerEvents, teamId, playerCallback);
} else {
incrementEvents(player, playerEvents, playerCallback);
}
});
};
var createAndUpdatePlayer = function(playerEvents, teamId, playerCallback) {
Player.create({name: playerEvents.events[0].player, teamId: teamId}, function(err, createdPlayer) {
if (err) {
console.log('error creating player while processing event -- ' + JSON.stringify(playerEvents) + ' -- ' + err);
}
incrementEvents(createdPlayer, playerEvents, playerCallback);
});
};
var incrementEvents = function(player, playerEvents, playerCallback) {
var suspended = false;
for (var eventIdx = 0; eventIdx < playerEvents.events.length; eventIdx += 1) {
var eventType = playerEvents.events[eventIdx].eventType;
if (eventType === 'yellow card') {
player.yellows += 1;
if (player.yellows % 5 === 0) {
suspended = true;
}
} else if (eventType === 'red card') {
player.reds += 1;
suspended = true;
} else if (eventType === 'goal') {
player.goals += 1;
} else if (eventType === 'own goal') {
player.ownGoals += 1;
}
}
player.save(function(err) {
if (err) {
console.log('error incrementing event for player -- ' + JSON.stringify(player) + ' -- ' + eventType);
playerCallback(err);
} else {
if (suspended) {
suspendPlayer(player, playerEvents.gameDate, playerCallback);
} else {
playerCallback();
}
}
});
};
var updateStandings = function(callback) {
Team.find({}, function(err, teams) {
if (err) {
console.log('error retrieving teams for standings update -- ' + err);
callback(err);
} else {
resetStandings(teams);
Game.find({'played': true}, null, {sort: {datePlayed : 1}}, function(err, games) {
if (err) {
console.log('error retrieving played games for standings update -- ' + err);
callback(err);
} else {
for (var gameIdx = 0; gameIdx < games.length; gameIdx += 1) {
processGameForStandings(games[gameIdx], teams);
}
saveStandings(teams, callback);
}
});
}
});
};
var saveStandings = function(teams, standingsCallback) {
var saveTeam = function(team, saveCallback) {
team.save(function(err){
if (err) {
console.log('error saving team -- ' + team + ' -- ' + err);
saveCallback(err);
} else {
saveCallback();
}
});
};
async.each(teams, saveTeam, function(err) {
if (err) {
standingsCallback(err);
} else {
standingsCallback();
}
});
};
var resetStandings = function(teams) {
for (var teamIdx in teams) {
teams[teamIdx].wins = 0;
teams[teamIdx].losses = 0;
teams[teamIdx].draws = 0;
teams[teamIdx].points = 0;
teams[teamIdx].goalsFor = 0;
teams[teamIdx].goalsAgainst = 0;
//teams[teamIdx].suspensions = [];
}
};
var processGameForStandings = function(game, teams) {
for (var teamResultIdx = 0; teamResultIdx < game.teams.length; teamResultIdx += 1) {
var teamResult = game.teams[teamResultIdx];
var opponentResult = game.teams[1 - teamResultIdx];
var team;
for (var teamIdx = 0; teamIdx < teams.length; teamIdx += 1) {
if (teams[teamIdx]._id.equals(teamResult.teamId)) {
team = teams[teamIdx];
break;
}
}
team.lastGamePlayed = game.datePlayed;
team.goalsFor += teamResult.goals;
team.goalsAgainst += opponentResult.goals;
if (teamResult.goals > opponentResult.goals) {
team.wins += 1;
team.points += 3;
} else if (teamResult.goals === opponentResult.goals) {
team.draws += 1;
team.points += 1;
} else {
team.losses += 1;
}
}
// game.played=false;
// game.datePlayed=undefined;
// for (var teamIdx = 0; teamIdx < game.teams.length; teamIdx += 1) {
// game.teams[teamIdx].goals = 0;
// game.teams[teamIdx].events = [];
// }
// game.save();
};
var suspendPlayer = function(player, gameDate, suspensionCallback) {
Team.findOne({_id: player.teamId}, function(err, team){
if (err) {
console.log('error loading team to suspend a dude -- ' + player);
suspensionCallback(err);
} else {
if (!team.suspensions) {
team.suspensions = [];
}
team.suspensions.push({player: player.name, dateSuspended: gameDate});
team.save(function(err) {
if (err) {
console.log('error saving suspension 4 dude -- ' + player + ' -- ' + team);
suspensionCallback(err);
} else {
suspensionCallback();
}
});
}
});
};
}; |
(function(){
'use strict';
angular.module('GamemasterApp')
.controller('DashboardCtrl', function ($scope, $timeout, $mdSidenav, $http) {
$scope.users = ['Fabio', 'Leonardo', 'Thomas', 'Gabriele', 'Fabrizio', 'John', 'Luis', 'Kate', 'Max'];
})
})(); |
const express = require('express');
const router = express.Router();
const routes = require('./routes')(router);
module.exports = router;
|
var HDWalletProvider = require("truffle-hdwallet-provider");
var mnemonic = "candy maple cake sugar pudding cream honey rich smooth crumble sweet treat";
module.exports = {
networks: {
development: {
provider: function () {
return new HDWalletProvider(mnemonic, "http://127.0.0.1:7545/", 0, 50);
},
network_id: "*",
},
},
compilers: {
solc: {
version: "^0.5.2",
},
},
};
|
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var HtmlWebpackPlugin = require("html-webpack-plugin");
var path = require("path");
var webpack = require("webpack");
var projectTemplatesRoot = "../../ppb/templates/";
module.exports = {
context: path.resolve(__dirname, "src"),
entry: {
app: "./js/main.js"
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "js/site.js?[hash]",
publicPath: "/site_media/static"
},
module: {
loaders: [
{
test: /\.(gif|png|ico|jpg|svg)$/,
include: [
path.resolve(__dirname, "src/images")
],
loader: "file-loader?name=/images/[name].[ext]"
},
{ test: /\.less$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader") },
{
test: /\.(woff|woff2|ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
include: [
path.resolve(__dirname, "/src/fonts"),
path.resolve(__dirname, "../node_modules")
],
loader: "file-loader?name=/fonts/[name].[ext]?[hash]"
},
{ test: /\.jsx?$/, loader: "babel-loader", query: {compact: false} },
]
},
resolve: {
extensions: ["", ".js", ".jsx"],
},
plugins: [
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new ExtractTextPlugin("css/site.css?[hash]"),
new HtmlWebpackPlugin({
filename: projectTemplatesRoot + "_styles.html",
templateContent: function(templateParams, compilation) {
var link = "";
for (var css in templateParams.htmlWebpackPlugin.files.css) {
link += "<link href='" + templateParams.htmlWebpackPlugin.files.css[css] + "' rel='stylesheet' />\n"
}
return link;
}
}),
new HtmlWebpackPlugin({
filename: projectTemplatesRoot + "_scripts.html",
templateContent: function(templateParams, compilation) {
var script = "";
for (var js in templateParams.htmlWebpackPlugin.files.js) {
script += "<script src='" + templateParams.htmlWebpackPlugin.files.js[js] + "'></script>\n"
}
return script;
}
})
]
};
|
var h = require('hyperscript')
var human = require('human-time')
exports.needs = {}
exports.gives = 'message_meta'
exports.create = function () {
function updateTimestampEl(el) {
el.firstChild.nodeValue = human(new Date(el.timestamp))
return el
}
setInterval(function () {
var els = [].slice.call(document.querySelectorAll('.timestamp'))
els.forEach(updateTimestampEl)
}, 60e3)
return function (msg) {
return updateTimestampEl(h('a.enter.timestamp', {
href: '#'+msg.key,
timestamp: msg.value.timestamp,
title: new Date(msg.value.timestamp)
}, ''))
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:e40a08695f05163cfb0eaeeef4588fcfad55a6576cfadfb079505495605beb33
size 27133
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Famous Industries Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
'use strict';
import { Geometry } from '../Geometry';
import { GeometryHelper } from '../GeometryHelper';
/**
* This function generates custom buffers and passes them to
* a new static geometry, which is returned to the user.
*
* @class Tetrahedron
* @constructor
*
* @param {Object} options Parameters that alter the
* vertex buffers of the generated geometry.
*
* @return {Object} constructed geometry
*/
class Tetrahedron extends Geometry {
constructor(options) {
//handled by es6 transpiler
//if (!(this instanceof Tetrahedron)) return new Tetrahedron(options);
var textureCoords = [];
var normals = [];
var detail;
var i;
var t = Math.sqrt(3);
var vertices = [
// Back
1, -1, -1 / t,
-1, -1, -1 / t,
0, 1, 0,
// Right
0, 1, 0,
0, -1, t - 1 / t,
1, -1, -1 / t,
// Left
0, 1, 0,
-1, -1, -1 / t,
0, -1, t - 1 / t,
// Bottom
0, -1, t - 1 / t,
-1, -1, -1 / t,
1, -1, -1 / t
];
var indices = [
0, 1, 2,
3, 4, 5,
6, 7, 8,
9, 10, 11
];
for (i = 0; i < 4; i++) {
textureCoords.push(
0.0, 0.0,
0.5, 1.0,
1.0, 0.0
);
}
options = options || {};
while (--detail) GeometryHelper.subdivide(indices, vertices, textureCoords);
normals = GeometryHelper.computeNormals(vertices, indices);
options.buffers = [
{
name: 'a_pos',
data: vertices
},
{
name: 'a_texCoord',
data: textureCoords,
size: 2
},
{
name: 'a_normals',
data: normals
},
{
name: 'indices',
data: indices,
size: 1
}
];
super(options);
}
}
export { Tetrahedron };
|
var map;
var bounds;
var markers = {};
var cluster_polygons = {};
var zoomTimeout;
var cluster_center_overlay;
var white_overlay;
var overlay_opacity = 50;
var OPACITY_MAX_PIXELS = 57;
var active_cluster_poly;
var marker_image;
var center_marker;
var cluster_center_marker_icon;
function createMap() {
bounds = new google.maps.LatLngBounds ();
markers;
cluster_polygons;
marker_image = {
url: STATIC_URL + "images/red_marker.png",
anchor: new google.maps.Point(4,4)};
center_marker = {
url: STATIC_URL + "images/black_marker.png",
size: new google.maps.Size(20, 20),
anchor: new google.maps.Point(10,10)};
cluster_center_marker_icon = {
url: STATIC_URL + "images/transparent_marker_20_20.gif",
size: new google.maps.Size(20, 20),
anchor: new google.maps.Point(10,10)};
var mapOptions = {
center: new google.maps.LatLng(0, 0),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scaleControl: true
};
map = new google.maps.Map(document.getElementById("canvas"),
mapOptions);
// google.maps.event.addListener(map, 'bounds_changed', function(e) {
// if (zoomTimeout) {
// window.clearTimeout(zoomTimeout);
// }
// zoomTimeout = window.setTimeout(query_points_for_view, 5000);
// })
$.getScript(STATIC_URL + "script/CustomTileOverlay.js", function() {
white_overlay = new CustomTileOverlay(map, overlay_opacity);
white_overlay.show();
google.maps.event.addListener(map, 'tilesloaded', function () {
white_overlay.deleteHiddenTiles(map.getZoom());
});
createOpacityControl(map, overlay_opacity);
});
}
// Thanks https://github.com/gavinharriss/google-maps-v3-opacity-control/!
function createOpacityControl(map, opacity) {
var sliderImageUrl = STATIC_URL + "images/opacity-slider3d14.png";
// Create main div to hold the control.
var opacityDiv = document.createElement('DIV');
opacityDiv.setAttribute("style", "margin:5px;overflow-x:hidden;overflow-y:hidden;background:url(" + sliderImageUrl + ") no-repeat;width:71px;height:21px;cursor:pointer;");
// Create knob
var opacityKnobDiv = document.createElement('DIV');
opacityKnobDiv.setAttribute("style", "padding:0;margin:0;overflow-x:hidden;overflow-y:hidden;background:url(" + sliderImageUrl + ") no-repeat -71px 0;width:14px;height:21px;");
opacityDiv.appendChild(opacityKnobDiv);
var opacityCtrlKnob = new ExtDraggableObject(opacityKnobDiv, {
restrictY: true,
container: opacityDiv
});
google.maps.event.addListener(opacityCtrlKnob, "dragend", function () {
set_overlay_opacity(opacityCtrlKnob.valueX());
});
// google.maps.event.addDomListener(opacityDiv, "click", function (e) {
// var left = findPosLeft(this);
// var x = e.pageX - left - 5; // - 5 as we're using a margin of 5px on the div
// opacityCtrlKnob.setValueX(x);
// set_overlay_opacity(x);
// });
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(opacityDiv);
// Set initial value
var initialValue = OPACITY_MAX_PIXELS / (100 / opacity);
opacityCtrlKnob.setValueX(initialValue);
set_overlay_opacity(initialValue);
}
// Thanks https://github.com/gavinharriss/google-maps-v3-opacity-control/!
function findPosLeft(obj) {
var curleft = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
} while (obj = obj.offsetParent);
return curleft;
}
return undefined;
}
function set_overlay_opacity(value) {
overlay_opacity = (100.0 / OPACITY_MAX_PIXELS) * value;
if (value < 0) value = 0;
if (value == 0) {
if (white_overlay.visible == true) {
white_overlay.hide();
}
}
else {
white_overlay.setOpacity(overlay_opacity);
if (white_overlay.visible == false) {
white_overlay.show();
}
}
}
function query_points_for_view() {
var bounds = map.getBounds();
var x0 = bounds.getNorthEast().lng();
var y0 = bounds.getNorthEast().lat();
var x1 = bounds.getSouthWest().lng();
var y1 = bounds.getSouthWest().lat();
// Remove stuff off screen
var to_remove = [];
// What to remove
$.each(markers, function(idx, marker){
if (!bounds.contains(marker.getPosition()))
{
marker.setMap(null);
to_remove.push(idx);
}
});
$.each(to_remove, function(i, idx){
delete markers[idx];
})
// $.getJSON("/rest/photos_box_contains?x0=" + x0 + "&y0=" + y0 + "&x1=" + x1 + "&y1=" + y1, function(data){
// console.log("got " + data.features.length);
// add_photo_to_map(data.features, 0, 128);
// })
$.getJSON("/rest/clusters_box_contains?x0=" + x0 + "&y0=" + y0 + "&x1=" + x1 + "&y1=" + y1, function(data){
console.log("got " + data.features.length);
add_cluster_to_map(data.features, 0);
})
}
function create_photo_marker(photo_info) {
var loc = new google.maps.LatLng(photo_info.geometry.coordinates[1], photo_info.geometry.coordinates[0]);
var marker = new google.maps.Marker({
map: map,
position: loc,
icon: marker_image
});
var infowindow = new google.maps.InfoWindow({
content: "<div style='width:200px;height:200px'><a href='" + photo_info.properties.photo_url + "'><img src='" + photo_info.properties.photo_thumb_url + "' style='max-width:100%;max-height:100%;'/></div>"
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
markers[photo_info.id] = marker;
}
function add_photo_to_map(photos, i, step) {
for (var j = 0; j < step; j++) {
if (i + j >= photos.length)
{
break;
}
var photo_info = photos[i + j];
if (!markers[photo_info.id]) {
create_photo_marker(photo_info);
}
}
i += step;
if (i < photos.length) {
window.setTimeout(function(){add_photo_to_map(photos, i, step);}, 1);
}
}
function add_clustering_run_to_map(data){
$.each(cluster_polygons, function(idx, poly){
poly.setMap(null);
});
bounds = new google.maps.LatLngBounds ();
cluster_polygons = [];
cluster_center_overlay = new google.maps.OverlayView();
cluster_center_overlay.onAdd = function() {
var layer = d3.select(this.getPanes().overlayMouseTarget).append("div")
.attr("class", "cluster_center");
var projection = this.getProjection();
var max_size = 300;
var max_size_per_2 = max_size / 2;
var marker = layer.selectAll("svg")
.data(data.features)
.each(transform)
.enter().append("svg:svg")
.each(transform)
.each(tie_to_g_marker)
.attr("class", "marker")
.style("z-index", function(cluster) {
return set_default_z_index(cluster);
})
.append("svg:g");
function set_default_z_index(cluster) {
return parseInt(cluster.properties.point_count_relative * 1000 + 100000);
}
marker.append("svg:polygon")
.attr("points", function(cluster){
var out = [];
var last_phase = 0.0;
var last_length = 1.0 / 12.0 * (max_size_per_2 - 1);
var min_l = 0.0;//0.3 * max_size_per_2 * (Math.sqrt(cluster.properties.point_count_relative) * 0.7 + 0.3);
for (var j = 1.0; j <= 12.0; j += 1.0){
var phase = j / 12.0 * 2 * Math.PI;
out.push([max_size_per_2 + Math.sin(last_phase) * min_l, max_size_per_2 - Math.cos(last_phase) * min_l]);
out.push([max_size_per_2 + Math.sin(phase) * min_l, max_size_per_2 - Math.cos(phase) * min_l]);
var second_poly = [];
var l = ( (cluster.properties["points_month_" + parseInt(j) + "_relative"]) * 0.9 + 0.1) *
max_size_per_2 * (cluster.properties.point_count_relative * 0.8 + 0.2);
second_poly.push([max_size_per_2 + Math.sin(last_phase) * min_l, max_size_per_2 - Math.cos(last_phase) * min_l]);
second_poly.push([max_size_per_2 + Math.sin(last_phase) * l, max_size_per_2 - Math.cos(last_phase) * l]);
second_poly.push([max_size_per_2 + Math.sin(phase) * l, max_size_per_2 - Math.cos(phase) * l]);
second_poly.push([max_size_per_2 + Math.sin(phase) * min_l, max_size_per_2 - Math.cos(phase) * min_l]);
second_poly.push(second_poly[0]);
last_phase = phase;
d3.select(this.parentElement)
.append("svg:polygon")
.attr("points", second_poly.join(" "))
.attr("class", "month_" + parseInt(j));
}
return out.join(" ");
})
.attr("class", "cluster_center_marker");
function transform(cluster) {
var coords = cluster.geometry.geometries[0].coordinates;
var d = new google.maps.LatLng(coords[1], coords[0]);
d = projection.fromLatLngToDivPixel(d);
return d3.select(this)
.style("left", (d.x - max_size_per_2) + "px")
.style("top", (d.y - max_size_per_2) + "px");
}
function tie_to_g_marker(cluster){
var coords = cluster.geometry.geometries[0].coordinates;
var d = new google.maps.LatLng(coords[1], coords[0]);
var marker = new google.maps.Marker({
map: map,
position: d,
icon: cluster_center_marker_icon,
zIndex: set_default_z_index(d3.select(this).data()[0])
});
var cluster_center = this;
google.maps.event.addListener(marker, 'mouseover', function() {
d3_cluster_center = d3.select(cluster_center);
d3_cluster_center
.style("transform", "scale(3.0)")
.style("animation-name", "cluster_center_highlight")
.style("z-index", 1001001);
});
google.maps.event.addListener(marker, 'click', function() {
if (active_cluster_poly) {
active_cluster_poly.setMap(null);
}
sidebar_display_cluster_info(d3_cluster_center.data()[0]["id"]);
d3_cluster_center = d3.select(cluster_center);
poly_bounds = new google.maps.LatLngBounds ();
// Define the LatLng coordinates for the polygon's path.
var coords = d3_cluster_center.data()[0].geometry.geometries[1].coordinates[0];
var g_coords = [];
for (j in coords)
{
var c = coords[j];
var co = new google.maps.LatLng(c[1], c[0]);
g_coords.push(co);
poly_bounds.extend(co);
}
// Construct the polygon.
var poly = new google.maps.Polygon({
paths: g_coords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
poly.setMap(map);
active_cluster_poly = poly;
map.fitBounds(poly_bounds);
});
google.maps.event.addListener(marker, 'mouseout', function() {
d3.select(cluster_center)
.style("transform", "scale(1.0)")
.style("animation-name", "cluster_center_unhighlight")
.style("z-index", function(cluster) {
return set_default_z_index(cluster);
});
});
bounds.extend(d);
}
map.fitBounds(bounds);
cluster_center_overlay.draw = function() {
var projection = this.getProjection();
layer.selectAll("svg")
.data(data.features)
.each(transform);
};
};
cluster_center_overlay.setMap(map);
}
function finalize_clustering_run_to_map(clusters){
console.log("finalizing");
map.fitBounds(bounds);
}
function show_clusters_lame() {
var $form = $("#clustering_run_get_form"), url = $form.attr("action");
// Fire some AJAX!
$.ajax({
type: "GET",
url: url,
dataType: "json",
data: {id: $("#clustering_run_get_form_select").val()}
})
.done(function(msg){
add_cluster_to_map(msg.features, 0);
});
}
function show_cluster_centers_lame() {
var $form = $("#clustering_run_get_form"), url = $form.attr("action");
// Fire some AJAX!
$.ajax({
type: "GET",
url: url,
dataType: "json",
data: {id: $("#clustering_run_get_form_select").val()}
})
.done(function(msg){
add_cluster_center_to_map(msg.features, 0);
});
}
function add_cluster_to_map(clusters, i){
// Define the LatLng coordinates for the polygon's path.
var cluster = clusters[i];
var coords = [];
var points = cluster.geometry.geometries[1].coordinates[0];
for (var j = 0; j < points.length; j += 1)
{
coords.push(new google.maps.LatLng(
points[j][1], points[j][0]));
}
var center = cluster.geometry.geometries[0].coordinates;
var loc = new google.maps.LatLng(
center[1],
center[0])
bounds.extend(loc);
// Construct the polygon.
var poly = new google.maps.Polygon({
paths: coords,
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 1,
fillColor: '#FF0000',
fillOpacity: 0.1
});
poly.setMap(map);
// cluster_polygons.push(poly);
if (i < clusters.length - 1) {
window.setTimeout(function(){add_cluster_to_map(clusters, i + 1);}, 1);
} else {
finalize_clustering_run_to_map(clusters);
}
}
function add_cluster_center_to_map(clusters, i){
// Define the LatLng coordinates for the polygon's path.
var cluster = clusters[i];
var coords = [];
var center = cluster.geometry.geometries[0].coordinates;
var loc = new google.maps.LatLng(
center[1],
center[0])
bounds.extend(loc);
var marker = new google.maps.Marker({
map: map,
position: loc
});
if (i < clusters.length - 1) {
window.setTimeout(function(){add_cluster_center_to_map(clusters, i + 1);}, 1);
} else {
finalize_clustering_run_to_map(clusters);
}
}
function show_all() {
map.fitBounds(bounds);
} |
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { MultiSelect } from '../../src'
class MultiSelectWithStringValues extends Component {
constructor(props) {
super(props)
this.state = {
value: []
}
}
handleChange = (event) => {
const { valueKey } = this.props
this.setState({ value: event.value.map((val) => val[valueKey]) })
}
render() {
const { value } = this.state
return <MultiSelect {...this.props} onChange={this.handleChange} value={value} />
}
}
MultiSelectWithStringValues.propTypes = {
valueKey: PropTypes.string.isRequired
}
export default MultiSelectWithStringValues
|
/*!
* Module dependencies.
*/
var util = require('util'),
moment = require('moment'),
super_ = require('../Type');
/**
* Date FieldType Constructor
* @extends Field
* @api public
*/
function datearray(list, path, options) {
this._nativeType = [Date];
this._defaultSize = 'medium';
this._underscoreMethods = ['format'];
this._properties = ['formatString'];
this.parseFormatString = options.parseFormat || 'YYYY-MM-DD';
this.formatString = (options.format === false) ? false : (options.format || 'Do MMM YYYY');
if (this.formatString && 'string' !== typeof this.formatString) {
throw new Error('FieldType.Date: options.format must be a string.');
}
datearray.super_.call(this, list, path, options);
}
/*!
* Inherit from Field
*/
util.inherits(datearray, super_);
/**
* Formats the field value
*
* @api public
*/
datearray.prototype.format = function(item, format) {
if (format || this.formatString) {
return item.get(this.path) ? moment(item.get(this.path)).format(format || this.formatString) : '';
} else {
return item.get(this.path) || '';
}
};
/**
* Checks that a valid array of dates has been provided in a data object
*
* An empty value clears the stored value and is considered valid
*
* @api public
*/
datearray.prototype.inputIsValid = function(data, required, item) {
var value = this.getValueFromData(data);
var parseFormatString = this.parseFormatString;
if ('string' === typeof value) {
if (!moment(value, parseFormatString).isValid()) {
return false;
}
value = [value];
}
if (required) {
if (value === undefined && item && item.get(this.path) && item.get(this.path).length) {
return true;
}
if (value === undefined || !Array.isArray(value)) {
return false;
}
if (Array.isArray(value) && !value.length) {
return false;
}
}
if (Array.isArray(value)) {
// filter out empty fields
value = value.filter(function(date) {
return date.trim() !== '';
});
// if there are no values left, and requried is true, return false
if (required && !value.length) {
return false;
}
// if any date in the array is invalid, return false
if (value.some(function (dateValue) { return !moment(dateValue, parseFormatString).isValid(); })) {
return false;
}
}
return (value === undefined || Array.isArray(value));
};
/**
* Updates the value for this field in the item from a data object
*
* @api public
*/
datearray.prototype.updateItem = function(item, data, callback) {
var value = this.getValueFromData(data);
if (value !== undefined) {
if (Array.isArray(value)) {
// Only save valid dates
value = value.filter(function(date) {
return moment(date).isValid();
});
}
if (value === null) {
value = [];
}
if ('string' === typeof value) {
if (moment(value).isValid()) {
value = [value];
}
}
if (Array.isArray(value)) {
item.set(this.path, value);
}
} else item.set(this.path, []);
process.nextTick(callback);
};
/*!
* Export class
*/
module.exports = datearray;
|
if ( !window.console ) window.console = { log:function(){} };
jQuery(document).ready(function($) {
console.log('Keep being awesome.');
}); |
'use strict';
var emojiArr = require('./emojis');
var i = 0;
var existingRules = {};
var generateEmoji = function(selector) {
if (!existingRules[selector]) {
existingRules[selector] = emojiArr[i];
if (i !== emojiArr.length) {
i++
} else {
i = 0;
}
}
return existingRules[selector];
}
module.exports = generateEmoji;
|
var fractal = fractal || {};
fractal.workerPaths = {
"mandelbrot": "public/js/mandel.js",
};
fractal.Fractal = function (canvas, workerCount) {
this.canvas = canvas;
this.workerCount = workerCount;
this.workerDoneCount = 0;
this.ctx = canvas.getContext("2d");
this.width = canvas.width;
this.height = canvas.height;
this.workerPath = fractal.workerPaths["mandelbrot"];
this.topLeft = new Complex(-1.5, 1.1);
this.bottomRight = new Complex(0.8, -1.1);
this.maxIter = 1200;
var lingrad = this.ctx.createLinearGradient(0, 0, this.width, 0);
lingrad.addColorStop(0, '#00f');
lingrad.addColorStop(0.1, '#fa0');
lingrad.addColorStop(0.5, '#ff0');
lingrad.addColorStop(0.7, '#f1b');
lingrad.addColorStop(1, '#fff');
this.ctx.fillStyle = lingrad;
this.ctx.fillRect(0, 0, this.width, 2);
this.gradientImage = this.ctx.getImageData(0, 0, this.width, 1);
this.imgData = this.ctx.getImageData(0, 0, this.width, this.height);
this.ondone = null;
this.workers = [];
};
fractal.Fractal.prototype = function () {
var computeRow = function (workerIndex, row) {
var args = {
action: "computeRow",
row: row,
workerIndex: workerIndex
};
this.workers[workerIndex].postMessage(args);
};
var initializeWorker = function (workerIndex) {
var drow = (this.bottomRight.imag - this.topLeft.imag) / this.height;
var dcol = (this.bottomRight.real - this.topLeft.real) / this.width;
var args = {
action: "setup",
maxIter: this.maxIter,
width: this.width,
height: this.height,
topLeft: this.topLeft,
bottomRight: this.bottomRight,
drow: drow,
dcol: dcol,
workerIndex: workerIndex,
juliaPoint: this.juliaPoint
};
this.workers[workerIndex].postMessage(args);
};
var createWorkers = function (workerPath) {
var obj = this;
var rowData = obj.ctx.createImageData(obj.width, 1);
for (var workerIndex = 0; workerIndex < obj.workerCount; workerIndex++) {
obj.workers[workerIndex] = new Worker(obj.workerPath);
this.workers[workerIndex].onmessage = function (event) {
if (event.data.logData) {
console.log("Worker: " + event.data.logData);
}
if (event.data.row >= 0) {
var wIndex = event.data.workerIndex;
for (var index = 0; index < obj.width; index++) {
var color = getColor.call(obj, event.data.iterData[index]);
var destIndex = 4 * index;
rowData.data[destIndex] = color.red;
rowData.data[destIndex + 1] = color.green;
rowData.data[destIndex + 2] = color.blue;
rowData.data[destIndex + 3] = color.alpha;
}
obj.ctx.putImageData(rowData, 0, event.data.row);
if (obj.nextRow < obj.height) {
console.log("Worker: " + wIndex, " nextRow: " + obj.nextRow);
computeRow.call(obj, wIndex, obj.nextRow);
obj.nextRow = obj.nextRow + 1;
} else {
obj.workerDoneCount++;
if (obj.workerDoneCount == obj.workerCount) {
var duration = new Date().getTime() - obj.startTime;
if (typeof obj.ondone === 'function') {
obj.ondone(duration);
}
}
}
}
};
}
};
var getColor = function (iter) {
if (iter == this.maxIter) {
return { red: 0, green: 0, blue: 0, alpha: 255 };
}
var index = (iter % this.gradientImage.width) * 4;
return {
red: this.gradientImage.data[index],
green: this.gradientImage.data[index + 1],
blue: this.gradientImage.data[index + 2],
alpha: this.gradientImage.data[index + 3]
};
},
render = function () {
this.startTime = new Date().getTime();
this.workerDoneCount = 0;
createWorkers.call(this, this.workerPath);
this.nextRow = this.workerCount;
for (var workerIndex = 0; workerIndex < this.workerCount; workerIndex++) {
initializeWorker.call(this, workerIndex);
computeRow.call(this, workerIndex, workerIndex);
}
}
return {
render: render
};
} ();
jQuery(function($) {
var fra = new fractal.Fractal(document.getElementById("fractal"), 2);
$('#draw-fractal').on('click',function() {
fra.render();
});
});
|
describe('raureif', function () {
it('test', function () {
});
});
|
/**
* @file ui/core/styleguide/index//html/01-body/40-main/main.js
* @description Listeners on the body, iframe, and rightpull bar.
*/
/* istanbul ignore if */
if (typeof window === 'object') {
document.addEventListener('DOMContentLoaded', () => {
const $orgs = FEPPER_UI.requerio.$orgs;
const {
uiFns,
uiProps
} = FEPPER_UI;
$orgs['#sg-rightpull'].on('mouseenter', function () {
$orgs['#sg-cover'].dispatchAction('addClass', 'shown-by-rightpull-hover');
});
$orgs['#sg-rightpull'].on('mouseleave', function () {
$orgs['#sg-cover'].dispatchAction('removeClass', 'shown-by-rightpull-hover');
});
// Handle manually resizing the viewport.
// 1. On "mousedown" store the click location.
// 2. Make a hidden div visible so that the cursor doesn't get lost in the iframe.
// 3. On "mousemove" calculate the math, save the results to a cookie, and update the viewport.
$orgs['#sg-rightpull'].on('mousedown', function (e) {
uiProps.sgRightpull.posX = e.pageX;
uiProps.sgRightpull.vpWidth = uiProps.vpWidth;
// Show the cover.
$orgs['#sg-cover'].dispatchAction('addClass', 'shown-by-rightpull-drag');
});
// Add the mouse move event and capture data. Also update the viewport width.
$orgs['#patternlab-body'].on('mousemove', function (e) {
if ($orgs['#sg-cover'].getState().classArray.includes('shown-by-rightpull-drag')) {
let vpWidthNew = uiProps.sgRightpull.vpWidth;
if (uiProps.dockPosition === 'bottom') {
vpWidthNew += 2 * (e.pageX - uiProps.sgRightpull.posX);
}
else {
vpWidthNew += e.pageX - uiProps.sgRightpull.posX;
}
if (vpWidthNew > uiProps.minViewportWidth) {
uiFns.sizeIframe(vpWidthNew, false);
}
}
});
// Handle letting go of rightpull bar after dragging to resize.
$orgs['#patternlab-body'].on('mouseup', function () {
uiProps.sgRightpull.posX = null;
uiProps.sgRightpull.vpWidth = null;
$orgs['#sg-cover'].dispatchAction('removeClass', 'shown-by-rightpull-hover');
$orgs['#sg-cover'].dispatchAction('removeClass', 'shown-by-rightpull-drag');
});
});
}
|
"use strict";
(function() {
// "todos-angular" is just a hard-code id for storage
var LOCAL_STORAGE_KEY = 'todos-angular';
var ENTER_KEY = 13;
var ESC_KEY = 27;
var internalFilters = {
active: function(toDoItem) {
return !toDoItem.completed;
},
completed: function(toDoItem) {
return toDoItem.completed;
}
};
angular.module('ToDoAngular', ['ngRoute'])
.service('storage', function($q) {
// Storage service
return {
save: function(toDoCollection) {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(toDoCollection));
},
load: function() {
var itemCollectionString = localStorage.getItem(LOCAL_STORAGE_KEY);
return itemCollectionString && JSON.parse(itemCollectionString) || [];
}
}
})
.directive('escHandler', function() {
// Define directive for esc key
return {
restrict: 'A',
link: function(scope, iElement, iAttrs) {
function keyEventHandler(event) {
if (event.keyCode === ESC_KEY) {
scope.$apply(iAttrs.escHandler);
}
}
iElement.on('keydown', keyEventHandler);
scope.$on('$destroy', function() {
iElement.off('keydown', keyEventHandler);
});
}
};
})
.directive('enterHandler', function() {
// Define directive for enter key
return {
restrict: 'A',
link: function (scope, iElement, iAttrs) {
function keyEventHandler(event) {
if (event.keyCode === ENTER_KEY) {
scope.$apply(iAttrs.enterHandler);
}
}
iElement.on('keydown', keyEventHandler);
scope.$on('$destroy', function () {
iElement.off('keydown', keyEventHandler);
});
}
};
})
.directive('selectAndFocus', function($timeout) {
// Define directive for focus
return {
restrict: 'A',
link: function(scope, iElement, iAttrs) {
var focusPromise;
scope.$watch(iAttrs.selectAndFocus, function(newValue) {
if (newValue && !focusPromise) {
focusPromise = $timeout(function focus() {
focusPromise = null;
iElement[0].focus();
}, 0, false);
}
});
scope.$on('$destroy', function() {
if (focusPromise) {
$timeout.cancel(focusPromise);
focusPromise = null;
}
});
}
};
})
.directive('toDoItem', function() {
// Define directive for to-do item
return {
restrict: 'A',
templateUrl: 'angular-item-template.html',
scope: {
itemViewModel: '=toDoItem'
},
link: function (scope, iElement, iAttrs) {
scope.editing = false;
scope.originalTitle = '';
scope.$watch('itemViewModel.toDoItem.completed', function(newCompleted) {
iElement.toggleClass('completed', newCompleted);
});
scope.$watch('editing', function(newEditing) {
iElement.toggleClass('editing', newEditing);
});
scope.$watch('itemViewModel.isHidden', function(newHidden) {
iElement.toggleClass('hidden', newHidden);
});
scope.$watchGroup([
'itemViewModel.toDoItem.title',
'itemViewModel.toDoItem.completed'], function() {
scope.$emit('item-updated');
});
scope.destroy = function() {
scope.$emit('remove-item', scope.itemViewModel);
};
scope.edit = function() {
scope.originalTitle = scope.itemViewModel.toDoItem.title;
scope.editing = true;
};
scope.update = function() {
var title = scope.itemViewModel.toDoItem.title || '';
var trimmedTitle = title.trim();
if (scope.editing) {
if (title !== trimmedTitle) {
scope.itemViewModel.toDoItem.title = trimmedTitle;
}
if (!trimmedTitle) {
scope.destroy();
}
scope.editing = false;
}
};
scope.revert = function() {
scope.editing = false;
scope.itemViewModel.toDoItem.title = scope.originalTitle;
};
}
};
})
.controller('AppController', function AppController(
$scope, $routeParams, storedToDoCollection, storage) {
// Define app controller
$scope.toDoCollection = storedToDoCollection.map(function(storedToDo) {
return {
toDoItem: storedToDo,
isHidden: $scope.filter ? !$scope.filter(storedToDo): false
};
});
$scope.currentTitle = '';
$scope.$on('$routeChangeSuccess', function() {
var filterString = $routeParams.filter;
if (filterString && (filterString in internalFilters)) {
$scope.filterString = filterString;
$scope.filter = internalFilters[filterString];
} else {
$scope.filterString = '';
$scope.filter = null;
}
});
function save() {
storage.save($scope.toDoCollection.map(function(toDoViewModel) {
return toDoViewModel.toDoItem;
}));
}
$scope.$watch('filter', function(newFilter) {
$scope.toDoCollection.forEach(function(toDoViewModel) {
toDoViewModel.isHidden = newFilter ? !newFilter(toDoViewModel.toDoItem) : false;
});
});
$scope.$watch(function() {
return $scope.toDoCollection.filter(function(toDoViewModel){
return !toDoViewModel.toDoItem.completed;
}).length;
}, function(newValue) {
if (newValue == null) {
$scope.remainingLabel = '';
} else {
$scope.remainingLabel = newValue === 1 ?
(newValue + ' item left') :
(newValue + ' items left');
}
});
$scope.$watchCollection('toDoCollection', function() {
save();
});
$scope.$on('item-updated', function() {
save();
});
$scope.$on('remove-item', function(scope, toDoViewModel) {
for(var index = 0; index < $scope.toDoCollection.length; index++) {
if ($scope.toDoCollection[index] === toDoViewModel) {
$scope.toDoCollection.splice(index, 1);
return;
}
}
});
$scope.create = function() {
var currentTitle = $scope.currentTitle.trim();
if (currentTitle) {
var toDoItem = {
title: currentTitle,
completed: false
};
var toDoItemViewModel = {
toDoItem: toDoItem,
isHidden: $scope.filter ? !$scope.filter(toDoItem): false
};
$scope.toDoCollection.push(toDoItemViewModel);
$scope.currentTitle = '';
}
};
})
.config(function($routeProvider) {
// Define routing
var routeConfig = {
controller: 'AppController',
templateUrl: 'angular-app-template.html',
resolve: {
storedToDoCollection: function(storage) {
return storage.load();
}
}
};
$routeProvider
.when('/', routeConfig)
.when('/:filter', routeConfig)
.otherwise({
redirectTo: '/'
});
});
})();
|
define(function() {
return {
draw: function(context, t) {
var x = this.getNumber("x", t, 100),
y = this.getNumber("y", t, 100),
size = this.getNumber("size", t, 60),
h = this.getNumber("h", t, 40),
colorLeft = this.getColor("colorLeft", t, "#999999"),
colorRight = this.getColor("colorRight", t, "#cccccc"),
colorTop = this.getColor("colorTop", t, "#eeeeee"),
scaleX = this.getNumber("scaleX", t, 1),
scaleY = this.getNumber("scaleY", t, 1);
context.translate(x, y);
context.scale(scaleX, scaleY);
if(h >= 0) {
context.fillStyle = colorTop;
context.beginPath();
context.moveTo(-size / 2, -h);
context.lineTo(0, -size / 4 - h);
context.lineTo(size / 2, -h);
context.lineTo(size / 2, -1);
context.lineTo(0, size / 4 - 1);
context.lineTo(-size / 2, -1);
context.lineTo(-size / 2, -h);
this.drawFillAndStroke(context, t, true, false);
context.fillStyle = colorLeft;
context.beginPath();
context.moveTo(-size / 2, 0);
context.lineTo(0, size / 4);
context.lineTo(0, size / 4 - h);
context.lineTo(-size / 2, -h);
context.lineTo(-size / 2, 0);
this.drawFillAndStroke(context, t, true, false);
context.fillStyle = colorRight;
context.beginPath();
context.moveTo(size / 2, 0);
context.lineTo(0, size / 4);
context.lineTo(0, size / 4 - h);
context.lineTo(size / 2, -h);
context.lineTo(size / 2, 0);
this.drawFillAndStroke(context, t, true, false);
}
else {
// clip path
context.beginPath();
context.moveTo(-size / 2, 0);
context.lineTo(0, -size / 4);
context.lineTo(size / 2, 0);
context.lineTo(0, size / 4);
context.lineTo(-size / 2, 0);
context.clip();
context.fillStyle = colorRight;
context.beginPath();
context.moveTo(-size / 2, 0);
context.lineTo(0, -size / 4);
context.lineTo(0, -size / 4 -h);
context.lineTo(-size / 2, -h);
context.lineTo(-size / 2, 0);
this.drawFillAndStroke(context, t, true, false);
context.fillStyle = colorLeft;
context.beginPath();
context.moveTo(size / 2, 0);
context.lineTo(0, -size / 4);
context.lineTo(0, -size / 4 -h);
context.lineTo(size / 2, -h);
context.lineTo(size / 2, 0);
this.drawFillAndStroke(context, t, true, false);
context.fillStyle = colorTop;
context.beginPath();
context.moveTo(-size / 2, -h);
context.lineTo(0, -size / 4 - h);
context.lineTo(size / 2, -h);
context.lineTo(0, size / 4 - h);
context.lineTo(-size / 2, -h);
this.drawFillAndStroke(context, t, true, false);
}
}
}
});
|
import React from 'react';
import {connect} from 'cerebral-view-react';
import styles from './styles.css';
import {
isObject,
isArray,
isString,
isBoolean,
isNumber,
isNull
} from 'common/utils';
import JSONInput from './JSONInput';
import connector from 'connector';
function isInPath(source, target) {
if (!source || !target) {
return false;
}
return target.reduce((isInPath, key, index) => {
if (!isInPath) {
return false;
}
return String(source[index]) === String(key);
}, true);
}
function renderType(value, hasNext, path, propertyKey, highlightPath) {
if (value === undefined) {
return null;
}
if (isArray(value)) {
return (
<ArrayValue
value={value}
hasNext={hasNext}
path={path}
propertyKey={propertyKey}
highlightPath={highlightPath}/>
);
}
if (isObject(value)) {
return (
<ObjectValue
value={value}
hasNext={hasNext}
path={path}
propertyKey={propertyKey}
highlightPath={highlightPath}/>
);
}
return (
<Value
value={value}
hasNext={hasNext}
path={path}
propertyKey={propertyKey}
highlightPath={highlightPath}/>
);
}
class ObjectValue extends React.Component {
static contextTypes = {
options: React.PropTypes.object.isRequired
}
constructor(props, context) {
super(props);
const numberOfKeys = Object.keys(props.value).length;
const isHighlightPath = !!(this.props.highlightPath && isInPath(this.props.highlightPath, this.props.path));
const preventCollapse = this.props.path.length === 0 && context.options.expanded;
this.state = {
isCollapsed: !preventCollapse && !isHighlightPath && (numberOfKeys > 3 || numberOfKeys === 0 ? true : context.options.expanded ? false : true)
};
this.onCollapseClick = this.onCollapseClick.bind(this);
this.onExpandClick = this.onExpandClick.bind(this);
}
shouldComponentUpdate(nextProps, nextState) {
return (
nextState.isCollapsed !== this.state.isCollapsed ||
this.context.options.canEdit ||
nextProps.path !== this.props.path ||
nextProps.highlightPath !== this.props.highlightPath
);
}
componentWillReceiveProps(nextProps) {
const context = this.context;
const props = nextProps;
const numberOfKeys = Object.keys(props.value).length;
const isHighlightPath = !!(props.highlightPath && isInPath(props.highlightPath, props.path));
const preventCollapse = props.path.length === 0 && context.options.expanded;
if (this.state.isCollapsed) {
this.setState({
isCollapsed: !preventCollapse && !isHighlightPath && (numberOfKeys > 3 || numberOfKeys === 0 ? true : context.options.expanded ? false : true)
});
}
}
onExpandClick() {
this.setState({isCollapsed: false})
}
onCollapseClick() {
this.setState({isCollapsed: true});
}
renderProperty(key, value, index, hasNext, path) {
this.props.path.push(key);
const property = (
<div className={styles.objectProperty} key={index}>
<div className={styles.objectPropertyValue}>{renderType(value, hasNext, path.slice(), key, this.props.highlightPath)}</div>
</div>
);
this.props.path.pop();
return property;
}
renderKeys(keys) {
if (keys.length > 3) {
return keys.slice(0, 3).join(', ') + '...'
}
return keys.join(', ');
}
render() {
const {value, hasNext} = this.props;
const isExactHighlightPath = this.props.highlightPath && String(this.props.highlightPath) === String(this.props.path);
if (this.state.isCollapsed) {
return (
<div className={isExactHighlightPath ? styles.highlightObject : styles.object} onClick={this.onExpandClick}>
{this.props.propertyKey ? this.props.propertyKey + ': ' : null}
<strong>{'{ '}</strong>{this.renderKeys(Object.keys(value))}<strong>{' }'}</strong>
{hasNext ? ',' : null}
</div>
);
} else if (this.props.propertyKey) {
const keys = Object.keys(value);
return (
<div className={isExactHighlightPath ? styles.highlightObject : styles.object}>
<div onClick={this.onCollapseClick}>{this.props.propertyKey}: <strong>{'{ '}</strong></div>
{keys.map((key, index) => this.renderProperty(key, value[key], index, index < keys.length - 1, this.props.path))}
<div><strong>{' }'}</strong>{hasNext ? ',' : null}</div>
</div>
);
} else {
const keys = Object.keys(value);
return (
<div className={isExactHighlightPath ? styles.highlightObject : styles.object}>
<div onClick={this.onCollapseClick}><strong>{'{ '}</strong></div>
{keys.map((key, index) => this.renderProperty(key, value[key], index, index < keys.length - 1, this.props.path, this.props.highlightPath))}
<div><strong>{' }'}</strong>{hasNext ? ',' : null}</div>
</div>
);
}
}
}
class ArrayValue extends React.Component {
static contextTypes = {
options: React.PropTypes.object.isRequired
}
constructor(props, context) {
super(props);
const numberOfItems = props.value.length;
const isHighlightPath = this.props.highlightPath && isInPath(this.props.highlightPath, this.props.path);
this.state = {
isCollapsed: !isHighlightPath && (numberOfItems > 3 || numberOfItems === 0) ? true : context.options.expanded ? false : true
};
this.onCollapseClick = this.onCollapseClick.bind(this);
this.onExpandClick = this.onExpandClick.bind(this);
}
shouldComponentUpdate(nextProps, nextState) {
return (
nextState.isCollapsed !== this.state.isCollapsed ||
this.context.options.canEdit ||
nextProps.path !== this.props.path ||
nextProps.highlightPath !== this.props.highlightPath
);
}
componentWillReceiveProps(nextProps) {
const context = this.context;
const props = nextProps;
const numberOfItems = props.value.length;
const isHighlightPath = props.highlightPath && isInPath(props.highlightPath, props.path);
if (this.state.isCollapsed) {
this.setState({
isCollapsed: !isHighlightPath && (numberOfItems > 3 || numberOfItems === 0) ? true : context.options.expanded ? false : true
});
}
}
onExpandClick() {
this.setState({isCollapsed: false})
}
onCollapseClick() {
this.setState({isCollapsed: true});
}
renderItem(item, index, hasNext, path) {
this.props.path.push(index);
const arrayItem = (
<div className={styles.arrayItem} key={index}>
{renderType(item, hasNext, path.slice())}
</div>
);
this.props.path.pop();
return arrayItem;
}
render() {
const {value, hasNext} = this.props;
const isExactHighlightPath = this.props.highlightPath && String(this.props.highlightPath) === String(this.props.path);
if (this.state.isCollapsed) {
return (
<div className={isExactHighlightPath ? styles.highlightArray : styles.array} onClick={this.onExpandClick}>
{this.props.propertyKey ? this.props.propertyKey + ': ' : null}
<strong>{'[ '}</strong>{value.length}<strong>{' ]'}</strong>
{hasNext ? ',' : null}
</div>
);
} else if (this.props.propertyKey) {
const keys = Object.keys(value);
return (
<div className={isExactHighlightPath ? styles.highlightArray : styles.array}>
<div onClick={this.onCollapseClick}>{this.props.propertyKey}: <strong>{'[ '}</strong></div>
{value.map((item, index) => this.renderItem(item, index, index < value.length - 1, this.props.path))}
<div><strong>{' ]'}</strong>{hasNext ? ',' : null}</div>
</div>
);
} else {
return (
<div className={isExactHighlightPath ? styles.highlightArray : styles.array}>
<div onClick={this.onCollapseClick}><strong>{'[ '}</strong></div>
{value.map((item, index) => this.renderItem(item, index, index < value.length - 1, this.props.path))}
<div><strong>{' ]'}</strong>{hasNext ? ',' : null}</div>
</div>
);
}
}
}
@connect()
class Value extends React.Component {
static contextTypes = {
options: React.PropTypes.object.isRequired
}
constructor(props) {
super(props);
this.state = {
isEditing: false,
path: props.path.slice()
};
this.onSubmit = this.onSubmit.bind(this);
this.onBlur = this.onBlur.bind(this);
this.onClick = this.onClick.bind(this);
}
shouldComponentUpdate(nextProps, nextState) {
return (
nextProps.value !== this.props.value ||
nextState.isEditing !== this.state.isEditing ||
nextProps.path !== this.props.path
);
}
onClick() {
this.setState({
isEditing: this.context.options.canEdit ? true : false
});
}
onSubmit(value) {
this.props.signals.debugger.modelChanged({
path: this.state.path,
value
})
this.setState({isEditing: false});
connector.sendEvent('changeModel', {
path: this.state.path,
value: value
});
}
onBlur() {
this.setState({isEditing: false});
}
renderValue(value, hasNext) {
const isExactHighlightPath = this.props.highlightPath && String(this.props.highlightPath) === String(this.props.path);
if (this.state.isEditing) {
return (
<div className={isExactHighlightPath ? styles.highlightValue : null}>
{this.props.propertyKey ? this.props.propertyKey + ': ' : <span/>}
<span>
<JSONInput
value={value}
onBlur={this.onBlur}
onSubmit={this.onSubmit}/>
</span>
{hasNext ? ',' : null}
</div>
);
} else {
return (
<div className={isExactHighlightPath ? styles.highlightValue : null}>
{this.props.propertyKey ? this.props.propertyKey + ': ' : <span/>}
<span onClick={this.onClick}>{isString(value) ? '"' + value + '"' : String(value)}</span>
{hasNext ? ',' : null}
</div>
);
}
}
render() {
let className = styles.string;
if (isNumber(this.props.value)) className = styles.number;
if (isBoolean(this.props.value)) className = styles.boolean;
if (isNull(this.props.value)) className = styles.null;
return (
<div className={className}>
{this.renderValue(this.props.value, this.props.hasNext)}
</div>
);
}
}
class Inspector extends React.Component {
static childContextTypes = {
options: React.PropTypes.object.isRequired
}
getChildContext() {
return {
options: {
expanded: this.props.expanded || false,
canEdit: this.props.canEdit || false
}
}
}
render() {
return renderType(this.props.value, false, [], null, this.props.path);
}
}
export default Inspector;
|
'use strict';
function valuefy(value) {
if (typeof value !== 'object') {
return (typeof value === 'string') ? `"${value}"` : value;
}
let values = [];
if (Array.isArray(value)) {
for (const v of value) {
values.push(valuefy(v));
}
values = `[${values.join(',')}]`;
} else {
for (let v in value) {
if ({}.hasOwnProperty.call(value, v)) {
values.push(`"${v}":${valuefy(value[v])}`);
}
}
values = `{${values.join(',')}}`;
}
return values;
}
function serialize(target) {
if (!target || typeof target !== 'object') {
throw new TypeError('Invalid type of target');
}
let values = [];
for (let t in target) {
if ({}.hasOwnProperty.call(target, t)) {
values.push(`${t}=${valuefy(target[t])}`);
}
}
return values;
}
function extract(t, outter, onlyContent) {
const start = onlyContent ? 1 : 0;
const pad = onlyContent ? 0 : 1;
return t.slice(start, t.lastIndexOf(outter) + pad);
}
function objectify(v) {
if (v[0] === '{') {
return JSON.parse(extract(v, '}'));
} else if (v[0] === '[') {
const set = [];
const es = extract(v, ']', true);
if (es[0] === '[' || es[0] === '{') {
set.push(objectify(es));
} else {
for (const e of es.split(',')) {
set.push(objectify(e));
}
}
return set;
} else if (v[0] === '"') {
v = extract(v, '"', true);
}
return v;
}
function deserialize(values) {
if (!values) {
throw new TypeError('Invalid type of values');
} else if (!Array.isArray(values)) {
values = [values];
}
const target = {};
for (const v of values) {
const fieldValue = v.split('=', 2);
target[fieldValue[0]] = objectify(fieldValue[1]);
}
return target;
}
module.exports = {
pairify: serialize,
parse: deserialize
};
|
export default class TasksService {
static async fetchTasks() {
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
await delay(1000);
return [
{ id: 0, description: "task1", status: "Active" },
{ id: 1, description: "task2", status: "Active" },
];
}
}
|
/**
* Vasya Hobot
*
* Copyright (c) 2013-2014 Vyacheslav Slinko
* Licensed under the MIT License
*/
function Message(chat, body) {
this._chat = chat;
this._body = body;
}
Message.prototype.getChat = function() {
return this._chat;
};
Message.prototype.getBody = function() {
return this._body;
};
module.exports = Message;
|
import React from 'react';
import { shallow } from 'enzyme';
import UserProfile from '../UserProfile';
import Wrapper from '../Wrapper';
describe('<UserProfile />', () => {
it('should render <Wrapper />', () => {
const wrapper = shallow(<UserProfile />);
expect(wrapper.find(Wrapper).length).toEqual(1);
});
});
|
import React from 'react';
import {
ActivityIndicator,
StyleSheet,
Image,
Text,
View,
ListView,
TouchableOpacity
} from 'react-native';
import Dimensions from 'Dimensions';
const {width, height} = Dimensions.get('window');
import globalVariables from '../globalVariables.js';
import LookCell from './LookCell.js';
import User from './User.js';
import DoneFooter from './DoneFooter.js';
import Icon from 'react-native-vector-icons/Ionicons';
const LookDetail = React.createClass({
getInitialState() {
return {
dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}),
comments: [],
next:true,
pageNo:1,
animating:true
};
},
getDefaultProps() {
return {
look:{},
navigator:"",
};
},
componentWillMount() {
this.queryRromServer(1);
},
getDataSource(comments) {
// return false;
return this.state.dataSource.cloneWithRows(comments);
},
renderFooter() {
if (!this.state.next) {
return (
<DoneFooter/>
);
}
return <ActivityIndicator style={styles.scrollSpinner} animating={this.state.animating}/>;
},
renderHeader() {
return (
<LookCell
look={this.props.look}
navigator={this.props.navigator}
onSelect={function(){}}
userCell={true}
/>
);
},
onEndReached() {
if(this.props.look.comments_count==0){
this.setState({
next:false,
});
return;
}
if (this.state.next && !this.state.animating) {
this.setState({ animating: true });
this.queryRromServer(this.state.pageNo);
}
},
onSelectUser(user) {
this.props.navigator.push({
component: User,
title: user.name,
backButtonTitle:' ',
passProps: {
user:user,
navigator:this.props.navigator,
},
});
},
// shouldComponentUpdate: function(nextProps, nextState) {
// console.log('LookDetail.js.js-shouldComponentUpdate');
// return JSON.stringify(nextState)!=JSON.stringify(this.state);
// },
renderRow(comments) {
if(!comments.comment||!comments.comment.user){
return false;
}
return (
<TouchableOpacity activeOpacity={0.8} onPress={()=>this.onSelectUser(comments.comment.user)} style={styles.flexContainer}>
<Image source={{uri:comments.comment.user.photo}} style={styles.avatar}/>
<View style={styles.commentBody}>
<View style={styles.commentHeader}>
<View style={{flex:1}}>
<Text style={styles.userName}>{comments.comment.user.name}</Text>
</View>
<View style={styles.timeView}>
<Icon name="ios-clock-outline" color={globalVariables.textBase} size={15}/>
<Text style={styles.time}> {globalVariables.formatDateToString(comments.comment.created_at)}</Text>
</View>
</View>
<Text style={styles.commentText}>{comments.comment.body}</Text>
</View>
</TouchableOpacity>
);
},
render() {
console.log(new Date()-0);
console.log('LookDetail.js.js-render');
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
onEndReached={this.onEndReached}
renderHeader={this.renderHeader}
renderFooter={this.renderFooter}
onEndReachedThreshold={10}
automaticallyAdjustContentInsets={false}
keyboardDismissMode='on-drag'
keyboardShouldPersistTaps={false}
showsVerticalScrollIndicator={true}
style={styles.container}
/>
);
},
queryRromServer(page) {
globalVariables.queryRromServer(globalVariables.apiLookServer+this.props.look.id+'/comments/'+(page||1),this.processsResults);
},
processsResults(data) {
if (!data||!data.comments||!data.comments.length) {
this.setState({
animating: false,
next:false,
});
return;
}
var newComments= this.state.comments.concat(data.comments);
var next=newComments.length>=this.props.look.comments_count?false:true;
this.setState({
comments: newComments,
animating: false,
dataSource: this.getDataSource(newComments),
pageNo: this.state.pageNo+1,
next:next,
});
}
});
const styles = StyleSheet.create({
container: {
paddingTop: 64,
backgroundColor: globalVariables.background,
},
flexContainer: {
opacity:0.97,
padding: 10,
flexDirection: 'row',
justifyContent: 'flex-start',
},
commentBody: {
flex: 1,
flexDirection: "column",
justifyContent: "center",
},
commentHeader: {
flexDirection: "row",
alignItems: "flex-start"
},
userName: {
color:globalVariables.base,
// fontSize:12,
},
timeView:{
// width:50,
flexDirection: "row",
alignItems:'center',
marginRight:5,
},
time:{
color:globalVariables.textBase,
fontSize:12,
// ,
},
commentText: {
// fontSize:12,
marginTop:8,
flexDirection: "row",
color:globalVariables.textBase,
},
avatar: {
borderRadius: 18,
width: 36,
height: 36,
marginRight: 10,
marginLeft: 5,
backgroundColor:globalVariables.textBase2,
},
scrollSpinner: {
marginVertical: 20,
},
});
export default LookDetail;
|
var cv = require('../lib/opencv');
var COLOR = [0, 255, 0]; // default red
var thickness = 2; // default 1
cv.readImage('./files/mona.png', function(err, im) {
if (err) throw err;
if (im.width() < 1 || im.height() < 1) throw new Error('Image has no size');
im.detectObject('../data/haarcascade_frontalface_alt2.xml', {}, function(err, faces) {
if (err) throw err;
for (var i = 0; i < faces.length; i++) {
var face = faces[i];
im.rectangle([face.x, face.y], [face.width, face.height], COLOR, 2);
}
im.save('./tmp/face-detection-rectangle.png');
console.log('Image saved to ./tmp/face-detection-rectangle.png');
});
});
|
// ========================================================================
// SproutCore -- JavaScript Application Framework
// Copyright ©2006-2011, Strobe Inc. and contributors.
// Portions copyright ©2008 Apple Inc. All rights reserved.
// ========================================================================
sc_require('controllers/object');
sc_require('mixins/selection_support');
sc_require('private/tree_item_observer');
/**
@class
A TreeController manages a tree of model objects that you might want to
display in the UI using a collection view. For the most part, you should
work with a TreeController much like you would an ObjectController, except
that the TreeController will also provide an arrangedObjects property that
can be used as the content of a CollectionView.
TODO: Document More
@extends SC.ObjectController
@extends SC.SelectionSupport
@since SproutCore 1.0
*/
SC.TreeController = SC.ObjectController.extend(SC.SelectionSupport,
/** @scope SC.TreeController.prototype */ {
// ..........................................................
// PROPERTIES
//
/**
Set to YES if you want the top-level items in the tree to be displayed as
group items in the collection view.
@property {Boolean}
*/
treeItemIsGrouped: NO,
/**
If your content support expanding and collapsing of content, then set this
property to the name of the key on your model that should be used to
determine the expansion state of the item. The default is
"treeItemIsExpanded"
@property {String}
*/
treeItemIsExpandedKey: "treeItemIsExpanded",
/**
Set to the name of the property on your content object that holds the
children array for each tree node. The default is "treeItemChildren".
@property {String}
*/
treeItemChildrenKey: "treeItemChildren",
/**
Returns an SC.Array object that actually will represent the tree as a
flat array suitable for use by a CollectionView. Other than binding this
property as the content of a CollectionView, you generally should not
use this property directly. Instead, work on the tree content using the
TreeController like you would any other ObjectController.
@property {SC.Array}
*/
arrangedObjects: function() {
var ret, content = this.get('content');
if (content) {
ret = SC.TreeItemObserver.create({ item: content, delegate: this });
} else ret = null; // empty!
this._sctc_arrangedObjects = ret ;
return ret ;
}.property().cacheable(),
// ..........................................................
// PRIVATE
//
/**
@private
Manually invalidate the arrangedObjects cache so that we can teardown
any existing value. We do it via an observer so that this will fire
immediately instead of waiting on some other component to get
arrangedObjects again.
*/
_sctc_invalidateArrangedObjects: function() {
this.propertyWillChange('arrangedObjects');
var ret = this._sctc_arrangedObjects;
if (ret) ret.destroy();
this._sctc_arrangedObjects = null;
this.propertyDidChange('arrangedObjects');
}.observes('content', 'treeItemIsExpandedKey', 'treeItemChildrenKey', 'treeItemIsGrouped'),
_sctc_arrangedObjectsContentDidChange: function() {
this.updateSelectionAfterContentChange();
}.observes('*arrangedObjects.[]'),
/**
@private
Returns the first item in arrangeObjects that is not a group. This uses
a brute force approach right now; we assume you probably don't have a lot
of groups up front.
*/
firstSelectableObject: function() {
var objects = this.get('arrangedObjects'),
indexes, len, idx = 0;
if (!objects) return null; // fast track
indexes = objects.contentGroupIndexes(null, objects);
len = objects.get('length');
while(indexes.contains(idx) && (idx<len)) idx++;
return idx>=len ? null : objects.objectAt(idx);
}.property()
});
|
import React, {Component} from 'react';
import PdfJS from './pdfJS';
import Contract from "../../contract";
import Event from '../../event';
import AnnotationLoader from '../../annotator/loader';
class Viewer extends Component {
constructor(props) {
super(props);
this.state = ({
page_no: 0,
pdf_url: "",
scale: 0,
loading: true
});
}
componentDidMount() {
this.subscribe_zoom = Event.subscribe('zoom:change', (scale) => {
this.setState({scale: scale});
});
this.updateState(this.props);
}
updateState(props) {
var {page_no, pdf_url} = props.page;
var scale = Contract.getPdfScale();
this.setState({
page_no,
pdf_url,
scale,
loading: false
});
}
componentWillUnmount() {
this.subscribe_zoom.remove();
}
getPageID() {
return 'pdf-' + this.state.page_no;
}
getAnnotations() {
let page = [];
let annotations = Contract.getAnnotations();
annotations.result.forEach(annotation=> {
if (typeof annotation.shapes == 'object' && this.state.page_no == annotation.page_no) {
page.push(annotation);
}
});
return page;
}
onPageRendered() {
if (!this.annotator) {
this.annotator = new AnnotationLoader('.pdf-annotator');
this.annotator.init();
Contract.setAnnotatorInstance(this.annotator);
}
const annotations = this.getAnnotations();
if (annotations.length > 0) {
this.annotator.content.annotator("loadAnnotations", annotations);
}
Event.publish('annotation:loaded', 'pdf');
}
componentWillReceiveProps(props) {
this.updateState(props);
}
shouldComponentUpdate(nextProps, nextState) {
return (nextProps.page.page_no !== this.state.page_no || this.state.scale !== nextState.scale);
}
render() {
if (this.state.loading) {
return ( <div className="pdf-viewer pdf-annotator">
<div className="pdf-wrapper">
Loading...
</div>
</div>);
}
return (
<div className="pdf-viewer pdf-annotator">
<div id={this.getPageID()} className="pdf-wrapper">
<PdfJS onPageRendered={this.onPageRendered.bind(this)}
file={this.state.pdf_url}
page={this.state.page_no}
scale={this.state.scale}/>
</div>
<a href="#" className="change-view-icon exit-fullscreen"></a>
</div>
);
}
}
export default Viewer;
|
var ratio = require('ratio')
function error(actual, expected) {
return Math.abs(actual - expected) / expected
}
function approx(target, max) {
max = (max || 10)
// find a good approximation
var best = 1, j, e, result
for (var i = 1; i < max; i++) {
j = Math.round(i * target)
e = error(j / i, target)
if (e >= best) continue
best = e
result = ratio(j, i)
}
return result
}
module.exports = approx
|
/*
* Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com)
*
* openAUSIAS: The stunning micro-library that helps you to develop easily
* AJAX web applications by using Java and jQuery
* openAUSIAS is distributed under the MIT License (MIT)
* Sources at https://github.com/rafaelaznar/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
'use strict';
/* Controllers */
moduloUsuariocursoxusuario.controller('UsuariocursoxusuarioPListController', ['$scope', '$routeParams', 'serverService', '$location', 'redirectService', 'sharedSpaceService', 'checkSessionStorageService',
function ($scope, $routeParams, serverService, $location, redirectService, sharedSpaceService, checkSessionStorageService) {
checkSessionStorageService.isSessionSessionStoraged();
$scope.visibles = {};
$scope.visibles.id = true;
$scope.visibles.titulo = true;
$scope.visibles.descripcion = true;
$scope.visibles.nota = true;
$scope.ob = "usuariocursoxusuario";
$scope.op = "plist";
$scope.title = "Listado de usuariocursoxusuario";
$scope.icon = "fa-file-text-o";
$scope.neighbourhood = 2;
if (!$routeParams.page) {
$routeParams.page = 1;
}
if (!$routeParams.rpp) {
$routeParams.rpp = 999;
}
$scope.numpage = $routeParams.page;
$scope.rpp = $routeParams.rpp;
$scope.predicate = 'id';
$scope.reverse = false;
$scope.orderCliente = function (predicate) {
$scope.predicate = predicate;
$scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
};
$scope.getListaCursos = function () {
serverService.getDataFromPromise(serverService.promise_getListaCursos()).then(function (data) {
redirectService.checkAndRedirect(data);
if (data.status != 200) {
$scope.statusListaCursos = "Error en la recepción de datos del servidor";
} else {
$scope.listaCursos = data.message;
for (var i = 0; i < $scope.listaCursos.length; i++) {
if (i > 0) {
if ($scope.listaCursos[i].obj_curso.id == $scope.listaCursos[i - 1].obj_curso.id) {
$scope.listaCursos[i - 1].alProfesores.push($scope.listaCursos[i].alProfesores[0]);
$scope.listaCursos.splice(i, 1);
i = i - 1;
}
}
}
}
});
};
//$scope.rppPad = serverService.getNrppBar($scope.ob, $scope.op, $scope.numpage, $scope.rpp);
// $scope.order = $routeParams.order;
// $scope.ordervalue = $routeParams.value;
//
// $scope.filter = $routeParams.filter;
// $scope.filteroperator = $routeParams.filteroperator;
// $scope.filtervalue = $routeParams.filtervalue;
//
// $scope.systemfilter = $routeParams.systemfilter;
// $scope.systemfilteroperator = $routeParams.systemfilteroperator;
// $scope.systemfiltervalue = $routeParams.systemfiltervalue;
$scope.order = "";
$scope.ordervalue = "";
$scope.filter = "id";
$scope.filteroperator = "like";
$scope.filtervalue = "";
$scope.systemfilter = "";
$scope.systemfilteroperator = "";
$scope.systemfiltervalue = "";
$scope.params = "";
$scope.paramsWithoutOrder = "";
$scope.paramsWithoutFilter = "";
$scope.paramsWithoutSystemFilter = "";
if ($routeParams.order && $routeParams.ordervalue) {
$scope.order = $routeParams.order;
$scope.ordervalue = $routeParams.ordervalue;
$scope.orderParams = "&order=" + $routeParams.order + "&ordervalue=" + $routeParams.ordervalue;
$scope.paramsWithoutFilter += $scope.orderParams;
$scope.paramsWithoutSystemFilter += $scope.orderParams;
} else {
$scope.orderParams = "";
}
if ($routeParams.filter && $routeParams.filteroperator && $routeParams.filtervalue) {
$scope.filter = $routeParams.filter;
$scope.filteroperator = $routeParams.filteroperator;
$scope.filtervalue = $routeParams.filtervalue;
$scope.filterParams = "&filter=" + $routeParams.filter + "&filteroperator=" + $routeParams.filteroperator + "&filtervalue=" + $routeParams.filtervalue;
$scope.paramsWithoutOrder += $scope.filterParams;
$scope.paramsWithoutSystemFilter += $scope.filterParams;
} else {
$scope.filterParams = "";
}
if ($routeParams.systemfilter && $routeParams.systemfilteroperator && $routeParams.systemfiltervalue) {
$scope.systemFilterParams = "&systemfilter=" + $routeParams.systemfilter + "&systemfilteroperator=" + $routeParams.systemfilteroperator + "&systemfiltervalue=" + $routeParams.systemfiltervalue;
$scope.paramsWithoutOrder += $scope.systemFilterParams;
$scope.paramsWithoutFilter += $scope.systemFilterParams;
} else {
$scope.systemFilterParams = "";
}
$scope.params = ($scope.orderParams + $scope.filterParams + $scope.systemFilterParams);
//$scope.paramsWithoutOrder = $scope.paramsWithoutOrder.replace('&', '?');
//$scope.paramsWithoutFilter = $scope.paramsWithoutFilter.replace('&', '?');
//$scope.paramsWithoutSystemFilter = $scope.paramsWithoutSystemFilter.replace('&', '?');
$scope.params = $scope.params.replace('&', '?');
$scope.getCursosPage = function () {
serverService.getDataFromPromise(serverService.promise_getSomeUsuariocursoXUsuario($scope.ob, $scope.rpp, $scope.numpage, $scope.filterParams, $scope.orderParams, $scope.systemFilterParams)).then(function (data) {
redirectService.checkAndRedirect(data);
if (data.status != 200) {
$scope.status = "Error en la recepción de datos del servidor";
} else {
$scope.pages = data.message.pages.message;
if (parseInt($scope.numpage) > parseInt($scope.pages))
$scope.numpage = $scope.pages;
$scope.page = data.message.page.message;
$scope.registers = data.message.registers.message;
$scope.status = "";
}
});
}
$scope.getCursosPage();
// $scope.pages = serverService.getPages($scope.ob, $scope.rpp, null, null, null, null, null, null).then(function (datos5) {
// $scope.pages = data['data'];
// if (parseInt($scope.page) > parseInt($scope.pages))
// $scope.page = $scope.pages;
// //$location.path( "#/clientes/" +$scope.pages + "/" + $scope.pages);
// });
// $scope.$watch('pages', function () {
// $scope.$broadcast('myApp.construirBotoneraPaginas');
// }, true)
//
$scope.getRangeArray = function (lowEnd, highEnd) {
var rangeArray = [];
for (var i = lowEnd; i <= highEnd; i++) {
rangeArray.push(i);
}
return rangeArray;
};
$scope.evaluateMin = function (lowEnd, highEnd) {
return Math.min(lowEnd, highEnd);
};
$scope.evaluateMax = function (lowEnd, highEnd) {
return Math.max(lowEnd, highEnd);
};
$scope.dofilter = function () {
if ($scope.filter != "" && $scope.filteroperator != "" && $scope.filtervalue != "") {
//console.log('#/' + $scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp + '?filter=' + $scope.filter + '&filteroperator=' + $scope.filteroperator + '&filtervalue=' + $scope.filtervalue + $scope.paramsWithoutFilter);
if ($routeParams.order && $routeParams.ordervalue) {
if ($routeParams.systemfilter && $routeParams.systemfilteroperator) {
$location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue).search('order', $routeParams.order).search('ordervalue', $routeParams.ordervalue).search('systemfilter', $routeParams.systemfilter).search('systemfilteroperator', $routeParams.systemfilteroperator).search('systemfiltervalue', $routeParams.systemfiltervalue);
} else {
$location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue).search('order', $routeParams.order).search('ordervalue', $routeParams.ordervalue);
}
} else {
$location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue);
}
}
return false;
};
//$scope.$on('myApp.construirBotoneraPaginas', function () {
// $scope.botoneraPaginas = serverService.getPaginationBar($scope.ob, $scope.op, $scope.page, $scope.pages, 2, $scope.rpp);
//})
//
// $scope.prettyFieldNames = serverService.getPrettyFieldNames($scope.ob).then(function (datos4) {
// datos4['data'].push('acciones');
// $scope.prettyFieldNames = datos4['data'];
// });
//
// $scope.clientes = serverService.getPage($scope.ob, $scope.page, null, null, $scope.rpp, null, null, null, null, null, null).then(function (datos3) {
// $scope.clientes = datos3['list'];
//
// });
//
// $scope.fieldNames = serverService.getFieldNames($scope.ob).then(function (datos6) {
// $scope.fieldNames = datos6['data'];
// $scope.selectedFilterFieldName = null;
// });
//
//
// $scope.$watch('numPagina', function () {
// $scope.$broadcast('myApp.construirPagina');
// }, true)
//
// $scope.$on('myApp.construirPagina', function () {
//
// $scope.clientes = serverService.getPage($scope.ob, $scope.page, null, null, $scope.rpp, null, null, null, null, null, null).then(function (datos3) {
// $scope.clientes = datos3['list'];
//
// });
//
// })
//
// $scope.filtrar = function () {
// alert("f")
//
//
// };
// $scope.$watch('filteroperator', function () {
// console.log($scope.filter);
// console.log($scope.filteroperator);
// console.log($scope.filtervalue);
// }, true)
$scope.newObj = function (args) {
$scope.objEdit = {};
$scope.position = undefined;
switch (args.strClass) {
case 'curso':
$scope.objEdit.id = 0;
break;
case 'inscribirse':
$scope.mostrarPass={};
if (sharedSpaceService.getFase() == 0) {
serverService.getDataFromPromise(serverService.promise_getOne('curso', args.id)).then(function (data) {
$scope.objEdit = data.message;
$scope.objEdit.password;
$scope.mostrarPass.mostrar=true;
$scope.mostrarPass.idCurso=args.id;
});
} else {
$scope.objEdit = sharedSpaceService.getObject();
sharedSpaceService.setFase(0);
}
break;
}
;
};
$scope.edit = function (args) {
$scope.objEdit = {};
switch (args.strClass) {
case 'curso':
$scope.position = $scope.page.alUsuariocursos.indexOf(args.levelOne);
if (sharedSpaceService.getFase() == 0) {
serverService.getDataFromPromise(serverService.promise_getOne(args.strClass, args.id)).then(function (data) {
$scope.objEdit = data.message;
//date conversion
});
} else {
$scope.objEdit = sharedSpaceService.getObject();
sharedSpaceService.setFase(0);
}
break;
}
;
};
$scope.save = function (type) {
switch (type) {
case 'curso':
serverService.getDataFromPromise(serverService.promise_setCurso('curso', {json: JSON.stringify(serverService.array_identificarArray($scope.objEdit))})).then(function (data) {
redirectService.checkAndRedirect(data);
if (data.status = 200) {
$scope.result = data;
if ($scope.position !== undefined) {
$scope.page.alUsuariocursos[$scope.position].obj_curso = $scope.objEdit;
$scope.position = undefined;
} else {
$scope.objFinal = {};
$scope.objFinal.id = $scope.result.message.idUsuarioCurso;
$scope.objFinal.obj_curso = {id: $scope.result.message.idCurso};
$scope.objFinal.obj_curso.titulo = $scope.objEdit.titulo;
$scope.objFinal.obj_curso.descripcion = $scope.objEdit.descripcion;
$scope.page.alUsuariocursos.push($scope.objFinal);
}
}
});
break;
case 'inscribirse':
serverService.getDataFromPromise(serverService.promise_setUsuariocurso('usuariocurso', {json: JSON.stringify(serverService.array_identificarArray($scope.objEdit))})).then(function (data) {
redirectService.checkAndRedirect(data);
if (data.status = 200) {
$scope.getCursosPage();
$scope.mostrarContraseña.mostrar=undefined;
$scope.mostrarContraseña.idCurso=undefined;
}
});
break;
}
;
};
$scope.remove = function (type, id, idUsuarioCurso) {
switch (type) {
case 'curso':
serverService.getDataFromPromise(serverService.promise_removeCurso(type, id, idUsuarioCurso)).then(function (data) {
redirectService.checkAndRedirect(data);
if (data.status = 200) {
$scope.result = data;
$scope.page.alUsuariocursos.splice($scope.position, 1);
$scope.position = undefined;
}
});
break;
}
};
}]); |
/**
* Write the input to the paramsified file
*
* ---
* INPUTS:
*
* - FILES
* Write the list of files to the paramsified file (line feed after each filename).
*
* - STRINGS
* Write the strings (concatenated) to the paramsified file.
*
* - STRING
* Write the string to the paramsified file.
*
* - UNDEFINED
* Touch the file.
*
* OUTPUT:
*
* - FILES
* The filename that was written.
* ---
*
* @module tasks
* @submodule write
*/
var State = require('../state'),
path = require('path'),
mkdirp = require('mkdirp').mkdirp,
fs = require('fs');
/**
* Write out the input to the destination filename.
*
* This can only apply to single string inputs.
*
* @method writeTask
* @param options {Object} Write task options
* @param options.name {String} Filename to write to.
* @param options.encoding {String} [default='utf8'] Encoding to use when writing the file
* @param options.mkdir {Boolean} [default=true] Make destination directory if it does not exist
* @param options.dirmode {String} [default='0755'] Create new directories with this mode (chmod)
* @param status {EventEmitter} Status object, handles 'complete' and 'failed' task exit statuses.
* @param logger {winston.Logger} Logger instance, if additional logging required (other than task exit status)
* @return {undefined}
* @public
*/
function writeTask(options, status, logger) {
var self = this,
pathname = path.resolve(path.dirname(options.name)),
name = options.name,
encoding = options && options.encoding || 'utf8',
mkdir = options && options.mkdir || true,
dirmode = options && options.dirmode || '0755';
// Write the content to the specified file.
function writeFile(filename, data) {
fs.writeFile(filename, data, encoding, function(err) {
if (err) {
status.emit('failed', 'write', 'error writing destination file: ' + err);
} else {
self._state.set(State.TYPES.FILES, [ filename ]);
status.emit('complete', 'write', 'wrote ' + filename);
}
});
}
// Create the paramsified path if it does not exist.
function mkdirIfNotExist(filename, callback) {
path.exists(filename, function(exists) {
if (!exists) {
if (mkdir === true) {
mkdirp(filename, dirmode, function(err) {
if (err) {
callback(err);
} else {
callback(null);
}
});
} else {
callback('tried to write a file to a non-existing directory and mkdir is false');
}
} else {
callback(null);
}
});
}
switch (this._state.get().type) {
case State.TYPES.FILES:
mkdirIfNotExist(pathname, function(err) {
if (err) {
status.emit('failed', 'write', 'error creating destination directory: ' + err);
} else {
writeFile(name, self._state.get().value.join("\n"));
}
});
break;
case State.TYPES.STRING:
mkdirIfNotExist(pathname, function(err) {
if (err) {
status.emit('failed', 'write', 'error creating destination directory: ' + err);
} else {
writeFile(name, self._state.get().value);
}
});
break;
case State.TYPES.STRINGS:
mkdirIfNotExist(pathname, function(err) {
if (err) {
status.emit('failed', 'write', 'error creating destination directory: ' + err);
} else {
writeFile(name, self._state.get().value.join(""));
}
});
break;
case State.TYPES.UNDEFINED:
mkdirIfNotExist(pathname, function(err) {
if (err) {
status.emit('failed', 'write', 'error creating destination directory: ' + err);
} else {
writeFile(name, "");
}
});
break;
default:
status.emit('failed', 'write', 'unrecognised input type: ' + this._type);
break;
}
}
exports.tasks = {
'write' : {
callback: writeTask
}
}; |
(function () {
"use strict";
/**
* This module have an ability to contain constants.
* No one can reinitialize any of already initialized constants
*/
var module = (function () {
var constants = {},
hasOwnProperty = Object.prototype.hasOwnProperty,
prefix = (Math.random() + "_").slice(2),
isAllowed;
/**
* This private method checks if value is acceptable
* @param value {String|Number|Boolean} - the value of the constant
* @returns {boolean}
* @private
*/
isAllowed = function (value) {
switch (typeof value) {
case "number":
return true;
case "string":
return true;
case "boolean":
return true;
default:
return false;
}
};
return {
/**
* Constant getter
* @param name {String} - the name of the constant
* @returns {String|Number|Boolean|null}
*/
getConstant: function (name) {
if (this.isDefined(name) === true) {
return constants[prefix + name];
}
return undefined;
},
/**
* Setter
* @param name {String} - the name of the constant
* @param value {String|Number|Boolean} - the value of the constant
* @returns {boolean}
*/
setConstant: function (name, value) {
if (isAllowed(value) !== true) {
return false;
}
if (this.isDefined(name) === true) {
return false;
}
constants[prefix + name] = value;
return true;
},
/**
* This method checks if constant is already defined
* @param name {String} - the name of the constant
* @returns {boolean}
*/
isDefined: function (name) {
return hasOwnProperty.call(constants, prefix + name);
}
};
})();
/**Testing*/
module.setConstant("test", 123);
print("test == " + module.getConstant("test"));
print("idDefined(\"test\") == " + module.isDefined("test"));
print("test2 == " + module.getConstant("test2"));
print("idDefined(\"test2\") == " + module.isDefined("test2"));
print("");
module.setConstant("test", 321);
print("test == " + module.getConstant("test"));
print("");
module.setConstant("test3", {a: 123});
print("test3 == " + module.getConstant("test3"));
})(); |
var address = '';
var config = {};
var requestGroupId = 0;
var readRequestsTodo = 0;
var readRequestsDone = 0;
var scanRequestsTodo = [0, 0, 0];
var scanRequestsDone = [0, 0, 0];
var scanResults = [];
var requestSentCounter = 0;
var requestSuccessCounter = 0;
var requestFailureCounter = 0;
var requestInProgress = false;
var requestQueue = [];
var socket = io({
transports: ['websocket'],
timeout: 10000,
reconnectionDelay: 500,
autoConnect: true
});
socket.on('reconnect', function()
{
window.location.reload();
});
var READ_RESPONSE_HANDLERS = {
in: handleReadInputResponse,
out: handleReadOutputResponse,
anal: handleReadAnalogResponse,
func: handleReadFunctionResponse
};
$(function()
{
$('#config-address').on('change', function(e)
{
updateAddress(e.target.value);
reset();
});
$('#config-scan').on('click', scan);
$('#config-file').on('change', function(e)
{
var file = e.target.files[0];
if (!file || !/\.conf/.test(file.name))
{
updateInput('');
reset();
return;
}
var reader = new FileReader();
reader.onload = function(e)
{
updateInput(e.target.result);
reset();
};
reader.readAsText(file);
});
$('#config-input').on('change', function(e)
{
$('#config-file').val('');
updateInput(e.target.value);
reset();
});
$('#outputs').on('click', '.output', function(e)
{
toggleOutput(config[e.currentTarget.dataset.id]);
});
$('#analogs')
.on('change', '.form-control', function(e)
{
setAnalog(config[$(e.currentTarget).closest('.analog')[0].dataset.id], e.currentTarget.value);
})
.on('keyup', '.form-control', function(e)
{
if (e.keyCode === 13)
{
setAnalog(config[$(e.currentTarget).closest('.analog')[0].dataset.id], e.currentTarget.value);
}
});
$('#functions')
.on('change', '.form-control', function(e)
{
setFunction(config[$(e.currentTarget).closest('.function')[0].dataset.id], e.currentTarget.value);
})
.on('keyup', '.form-control', function(e)
{
if (e.keyCode === 13)
{
setFunction(config[$(e.currentTarget).closest('.function')[0].dataset.id], e.currentTarget.value);
}
});
$(window).on('resize', resizeInput);
resizeInput();
updateAddress(localStorage.ADDRESS || '');
updateInput(localStorage.INPUT || '');
reset();
});
function resizeInput()
{
var height = window.innerHeight - 90 - 54 - 20 - 53 - 15 - 53 - 15 - 30;
$('#config-input').css('height', height + 'px');
}
function updateAddress(newAddress)
{
newAddress = newAddress.trim();
localStorage.ADDRESS = newAddress;
$('#config-address').val(newAddress);
if (newAddress.length && newAddress.indexOf('.') === -1)
{
newAddress = '[' + newAddress + ']';
}
address = newAddress;
}
function updateInput(newInput)
{
parseInput(newInput);
if (!Object.keys(config).length)
{
newInput = 'Nieprawidłowy lub pusty plik!';
}
else
{
localStorage.INPUT = newInput;
}
$('#config-input').val(newInput);
}
function parseInput(input)
{
config = {};
var re = /([A-Z0-9_-]+)\s+([0-9]+)\s+([0-9]+)\s+(in|out|anal|func)/ig;
var matches;
while (matches = re.exec(input))
{
var name = matches[1];
config[name] = {
type: matches[4],
name: name,
tim: parseInt(matches[2], 10),
channel: parseInt(matches[3], 10),
writing: false,
value: null
};
}
}
function renderIo()
{
var html = {
inputs: [],
outputs: [],
analogs: [],
functions: []
};
Object.keys(config).forEach(function(key)
{
var io = config[key];
if (io.type === 'in')
{
renderInput(html.inputs, io);
}
else if (io.type === 'out')
{
renderOutput(html.outputs, io);
}
else if (io.type === 'anal')
{
renderAnalog(html.analogs, io);
}
else if (io.type === 'func')
{
renderFunction(html.functions, io);
}
});
Object.keys(html).forEach(function(ioType)
{
$('#' + ioType).html(html[ioType].join(''));
});
}
function renderInput(html, io)
{
html.push(
'<span class="input label label-default" data-id="', io.name, '">',
io.name,
'</span>'
);
}
function renderOutput(html, io)
{
html.push(
'<button class="output btn btn-default" data-id="', io.name, '">',
io.name,
'</button>'
);
}
function renderAnalog(html, io)
{
html.push(
'<div class="analog" data-id="', io.name, '"><div class="input-group"><span class="input-group-addon">',
io.name,
'</span><input type="number" class="form-control" min="0" max="65535" step="1"></div></div>'
);
}
function renderFunction(html, io)
{
html.push(
'<div class="function" data-id="', io.name, '"><div class="input-group"><span class="input-group-addon">',
io.name,
'</span><input type="text" class="form-control"></div></div>'
);
}
function reset()
{
++requestGroupId;
Object.keys(config).forEach(function(key)
{
config[key].value = null;
});
readRequestsDone = 0;
readRequestsTodo = 0;
requestSentCounter = 0;
requestSuccessCounter = 0;
requestFailureCounter = 0;
updateRequestCounter();
renderIo();
readAll();
}
function updateRequestCounter()
{
$('#requestCounter-success').text(requestSuccessCounter);
$('#requestCounter-failure').text(requestFailureCounter);
$('#requestCounter-sent').text(requestSentCounter);
}
function readAll()
{
if (readRequestsDone !== readRequestsTodo)
{
return;
}
if (!address.length)
{
return;
}
var keys = Object.keys(config);
readRequestsDone = 0;
readRequestsTodo = keys.length;
keys.forEach(function(key)
{
read(config[key]);
});
requestSentCounter += readRequestsTodo;
updateRequestCounter();
}
function read(io)
{
var reqGroupId = requestGroupId;
var req = {
type: 'NON',
code: 'GET',
uri: 'coap://' + address + '/io/RD?tim=' + io.tim + '&ch=' + io.channel + '&t=' + io.type
};
socket.emit('request', req, function(err, res)
{
if (requestGroupId !== reqGroupId)
{
return;
}
++readRequestsDone;
if (err)
{
++requestFailureCounter;
//console.error('Error reading %s: %s', io.name, err.message);
}
else if (res.payload.indexOf('0') !== 0)
{
++requestFailureCounter;
console.error('Error reading %s (%s): %d', io.name, res.code, res.payload.split('\n')[0]);
}
else
{
++requestSuccessCounter;
READ_RESPONSE_HANDLERS[io.type](io, res);
}
updateRequestCounter();
if (readRequestsDone === readRequestsTodo)
{
setTimeout(readAll, 333);
}
});
}
function handleReadInputResponse(io, res)
{
var $input = $('.input[data-id="' + io.name + '"]');
if (!$input.length)
{
return;
}
$input.removeClass('label-default label-success label-danger');
io.value = res.payload.indexOf('ON') !== -1
? true
: res.payload.indexOf('OFF') !== -1
? false
: null;
if (io.value === true)
{
$input.addClass('label-success');
}
else if (io.value === false)
{
$input.addClass('label-danger');
}
else
{
$input.addClass('label-default');
}
}
function handleReadOutputResponse(io, res)
{
if (io.writing)
{
return;
}
var $output = $('.output[data-id="' + io.name + '"]');
if (!$output.length)
{
return;
}
io.value = res.payload.indexOf('ON') !== -1
? true
: res.payload.indexOf('OFF') !== -1
? false
: null;
$output
.removeClass('btn-default btn-success btn-danger')
.addClass(io.value === null ? 'btn-default' : io.value ? 'btn-success' : 'btn-danger');
}
function handleReadAnalogResponse(io, res)
{
if (io.writing)
{
return;
}
var $analog = $('.analog[data-id="' + io.name + '"]');
var $input = $analog.find('.form-control');
if (!$analog.length || document.activeElement === $input[0])
{
return;
}
io.value = parseInt(res.payload.split('\n')[3], 10) || 0;
$input.val(io.value);
}
function handleReadFunctionResponse(io, res)
{
if (io.writing)
{
return;
}
var $function = $('.function[data-id="' + io.name + '"]');
var $input = $function.find('.form-control');
if (!$function.length || document.activeElement === $input[0])
{
return;
}
io.value = res.payload.trim().split('\n')[3];
if (io.value === undefined)
{
io.value = '';
}
$input.val(io.value);
}
function toggleOutput(io)
{
if (io.writing)
{
return;
}
io.writing = true;
var $output = $('.output[data-id="' + io.name + '"]');
$output
.removeClass('btn-default btn-success btn-danger')
.addClass('btn-warning');
++requestSentCounter;
updateRequestCounter();
var reqGroupId = requestGroupId;
var req = {
type: 'NON',
code: 'POST',
uri: 'coap://' + address + '/io/WD?tim=' + io.tim
+ '&ch=' + io.channel
+ '&t=' + io.type
+ '&tD=' + (io.value ? 'OFF' : 'ON')
};
socket.emit('request', req, function(err, res)
{
if (requestGroupId !== reqGroupId)
{
return;
}
io.writing = false;
if (err)
{
++requestFailureCounter;
console.error('Error writing %s: %s', io.name, err.message);
}
else if (res.payload.indexOf('0') !== 0)
{
++requestFailureCounter;
console.error('Error writing %s (%s): %d', io.name, res.code, res.payload.split('\n')[0]);
}
else
{
++requestSuccessCounter;
io.value = !io.value;
}
$output
.removeClass('btn-warning')
.addClass(io.value === null ? 'btn-default' : io.value ? 'btn-success' : 'btn-danger');
updateRequestCounter();
});
}
function setAnalog(io, value)
{
value = parseInt(value, 10);
if (io.writing || isNaN(value) || value < 0 || value > 0xFFFF)
{
return;
}
io.writing = true;
var $analog = $('.analog[data-id="' + io.name + '"]');
var $input = $analog.find('.form-control');
$analog.addClass('is-writing');
$input.attr('readonly', true);
++requestSentCounter;
updateRequestCounter();
var reqGroupId = requestGroupId;
var req = {
type: 'NON',
code: 'POST',
uri: 'coap://' + address + '/io/WD?tim=' + io.tim
+ '&ch=' + io.channel
+ '&t=' + io.type
+ '&tD=' + value
};
socket.emit('request', req, function(err, res)
{
if (requestGroupId !== reqGroupId)
{
return;
}
$analog.removeClass('is-writing');
io.writing = false;
if (err)
{
++requestFailureCounter;
console.error('Error writing %s: %s', io.name, err.message);
}
else if (res.payload.indexOf('0') !== 0)
{
++requestFailureCounter;
console.error('Error writing %s (%s): %d', io.name, res.code, res.payload.split('\n')[0]);
}
else
{
++requestSuccessCounter;
io.value = value;
$input.val(value).attr('readonly', false);
}
updateRequestCounter();
});
}
function setFunction(io, value)
{
if (io.writing)
{
return;
}
io.writing = true;
var $function = $('.function[data-id="' + io.name + '"]');
var $input = $function.find('.form-control');
$function.addClass('is-writing');
$input.attr('readonly', true);
++requestSentCounter;
updateRequestCounter();
var reqGroupId = requestGroupId;
var req = {
type: 'NON',
code: 'POST',
uri: 'coap://' + address + '/io/WD?tim=' + io.tim
+ '&ch=' + io.channel
+ '&t=' + io.type
+ '&tD=' + value
};
socket.emit('request', req, function(err, res)
{
if (requestGroupId !== reqGroupId)
{
return;
}
$function.removeClass('is-writing');
io.writing = false;
if (err)
{
++requestFailureCounter;
console.error('Error writing %s: %s', io.name, err.message);
}
else if (res.payload.indexOf('0') !== 0)
{
++requestFailureCounter;
console.error('Error writing %s (%s): %d', io.name, res.code, res.payload.split('\n')[0]);
}
else
{
++requestSuccessCounter;
io.value = value;
$input.val(value).attr('readonly', false);
}
updateRequestCounter();
});
}
function unlockAfterScan()
{
scanRequestsDone = [0, 0];
scanRequestsTodo = [0, 0];
scanResults = [];
$('#config').find('.form-control').prop('disabled', false);
}
function scan()
{
if (!address.length || scanRequestsTodo[0] !== 0)
{
return;
}
updateInput('');
reset();
$('#config').find('.form-control').prop('disabled', true);
var req = {
type: 'CON',
code: 'GET',
uri: 'coap://' + address + '/io/TDisc'
};
var options = {
exchangeTimeout: 10000,
transactionTimeout: 1000,
maxRetransmit: 3,
blockSize: 64
};
updateRequestCounter(++requestSentCounter);
queueRequest(req, options, function(err, res)
{
if (err)
{
updateRequestCounter(++requestFailureCounter);
unlockAfterScan();
return console.error("Error scanning: %s", err.message);
}
updateRequestCounter(++requestSuccessCounter);
var tims = res.payload.split('\n')[1].split(',');
scanRequestsDone = [0, 0];
scanRequestsTodo = [tims.length, 0];
scanResults = [];
tims.forEach(function(timId)
{
scanTim(parseInt(timId.trim(), 10));
});
});
}
function scanTim(timId)
{
var req = {
type: 'CON',
code: 'GET',
uri: 'coap://' + address + '/io/CDisc?tim=' + timId
};
var options = {
exchangeTimeout: 10000,
transactionTimeout: 1000,
maxRetransmit: 3,
blockSize: 64
};
updateRequestCounter(++requestSentCounter);
queueRequest(req, options, function(err, res)
{
if (err)
{
updateRequestCounter(++requestFailureCounter);
unlockAfterScan();
return console.error("Error scanning TIM %d: %s", timId, err.message);
}
updateRequestCounter(++requestSuccessCounter);
++scanRequestsDone[0];
var lines = res.payload.split('\n');
var channelIds = lines[2].split(',');
var transducerNames = lines[3].replace(/"/g, '').split(',');
scanRequestsTodo[1] += channelIds.length;
channelIds.forEach(function(channelId, i)
{
setTimeout(
scanChannel,
Math.round(10 + Math.random() * 200),
timId,
parseInt(channelId.trim(), 10),
transducerNames[i]
);
});
});
}
function scanChannel(timId, channelId, transducerName)
{
var req = {
type: 'CON',
code: 'GET',
uri: 'coap://' + address + '/io/RTeds?tim=' + timId + '&ch=' + channelId + '&TT=4'
};
var options = {
exchangeTimeout: 10000,
transactionTimeout: 1000,
maxRetransmit: 3,
blockSize: 64
};
updateRequestCounter(++requestSentCounter);
queueRequest(req, options, function(err, res)
{
if (err)
{
updateRequestCounter(++requestFailureCounter);
unlockAfterScan();
return console.error("Error scanning channel %d of TIM %d: %s", channelId, timId, err.message);
}
updateRequestCounter(++requestSuccessCounter);
++scanRequestsDone[1];
var type = null;
if (/Digital Input/i.test(res.payload))
{
type = 'in';
}
else if (/Digital Output/i.test(res.payload))
{
type = 'out';
}
else if (/(Digit.*?|Analog|Step g) (Input|Output)/i.test(res.payload))
{
type = 'anal';
}
if (type)
{
scanResults.push({
timId: timId,
channelId: channelId,
name: (transducerName || ('T_' + timId + '_' + channelId)).trim(),
type: type
});
}
if (scanRequestsDone[1] === scanRequestsTodo[1])
{
buildInputFromScanResults();
}
});
}
function buildInputFromScanResults()
{
var input = [];
scanResults.sort(function(a, b)
{
var r = a.timId - b.timId;
if (r === 0)
{
r = a.channelId - b.channelId;
}
return r;
});
scanResults.forEach(function(io)
{
input.push(io.name + ' ' + io.timId + ' ' + io.channelId + ' ' + io.type);
});
unlockAfterScan();
updateInput(input.join('\n'));
renderIo();
readAll();
}
function queueRequest(req, options, callback)
{
requestQueue.push(req, options, callback);
if (!requestInProgress)
{
sendNextRequest();
}
}
function sendNextRequest()
{
var req = requestQueue.shift();
var options = requestQueue.shift();
var callback = requestQueue.shift();
if (!callback)
{
return;
}
requestInProgress = true;
socket.emit('request', req, options, function(err, res)
{
requestInProgress = false;
callback(err, res);
sendNextRequest();
});
}
|
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/get-iterator"), __esModule: true };
},{"core-js/library/fn/get-iterator":6}],2:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/define-property"), __esModule: true };
},{"core-js/library/fn/object/define-property":7}],3:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/keys"), __esModule: true };
},{"core-js/library/fn/object/keys":8}],4:[function(require,module,exports){
"use strict";
exports.__esModule = true;
exports.default = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
},{}],5:[function(require,module,exports){
"use strict";
exports.__esModule = true;
var _defineProperty = require("../core-js/object/define-property");
var _defineProperty2 = _interopRequireDefault(_defineProperty);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = 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;
(0, _defineProperty2.default)(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
},{"../core-js/object/define-property":2}],6:[function(require,module,exports){
require('../modules/web.dom.iterable');
require('../modules/es6.string.iterator');
module.exports = require('../modules/core.get-iterator');
},{"../modules/core.get-iterator":57,"../modules/es6.string.iterator":61,"../modules/web.dom.iterable":62}],7:[function(require,module,exports){
require('../../modules/es6.object.define-property');
var $Object = require('../../modules/_core').Object;
module.exports = function defineProperty(it, key, desc){
return $Object.defineProperty(it, key, desc);
};
},{"../../modules/_core":15,"../../modules/es6.object.define-property":59}],8:[function(require,module,exports){
require('../../modules/es6.object.keys');
module.exports = require('../../modules/_core').Object.keys;
},{"../../modules/_core":15,"../../modules/es6.object.keys":60}],9:[function(require,module,exports){
module.exports = function(it){
if(typeof it != 'function')throw TypeError(it + ' is not a function!');
return it;
};
},{}],10:[function(require,module,exports){
module.exports = function(){ /* empty */ };
},{}],11:[function(require,module,exports){
var isObject = require('./_is-object');
module.exports = function(it){
if(!isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
},{"./_is-object":29}],12:[function(require,module,exports){
// false -> Array#indexOf
// true -> Array#includes
var toIObject = require('./_to-iobject')
, toLength = require('./_to-length')
, toIndex = require('./_to-index');
module.exports = function(IS_INCLUDES){
return function($this, el, fromIndex){
var O = toIObject($this)
, length = toLength(O.length)
, index = toIndex(fromIndex, length)
, value;
// Array#includes uses SameValueZero equality algorithm
if(IS_INCLUDES && el != el)while(length > index){
value = O[index++];
if(value != value)return true;
// Array#toIndex ignores holes, Array#includes - not
} else for(;length > index; index++)if(IS_INCLUDES || index in O){
if(O[index] === el)return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
},{"./_to-index":48,"./_to-iobject":50,"./_to-length":51}],13:[function(require,module,exports){
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = require('./_cof')
, TAG = require('./_wks')('toStringTag')
// ES3 wrong here
, ARG = cof(function(){ return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function(it, key){
try {
return it[key];
} catch(e){ /* empty */ }
};
module.exports = function(it){
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
},{"./_cof":14,"./_wks":55}],14:[function(require,module,exports){
var toString = {}.toString;
module.exports = function(it){
return toString.call(it).slice(8, -1);
};
},{}],15:[function(require,module,exports){
var core = module.exports = {version: '2.4.0'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
},{}],16:[function(require,module,exports){
// optional / simple context binding
var aFunction = require('./_a-function');
module.exports = function(fn, that, length){
aFunction(fn);
if(that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
}
return function(/* ...args */){
return fn.apply(that, arguments);
};
};
},{"./_a-function":9}],17:[function(require,module,exports){
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
};
},{}],18:[function(require,module,exports){
// Thank's IE8 for his funny defineProperty
module.exports = !require('./_fails')(function(){
return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
});
},{"./_fails":22}],19:[function(require,module,exports){
var isObject = require('./_is-object')
, document = require('./_global').document
// in old IE typeof document.createElement is 'object'
, is = isObject(document) && isObject(document.createElement);
module.exports = function(it){
return is ? document.createElement(it) : {};
};
},{"./_global":23,"./_is-object":29}],20:[function(require,module,exports){
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
},{}],21:[function(require,module,exports){
var global = require('./_global')
, core = require('./_core')
, ctx = require('./_ctx')
, hide = require('./_hide')
, PROTOTYPE = 'prototype';
var $export = function(type, name, source){
var IS_FORCED = type & $export.F
, IS_GLOBAL = type & $export.G
, IS_STATIC = type & $export.S
, IS_PROTO = type & $export.P
, IS_BIND = type & $export.B
, IS_WRAP = type & $export.W
, exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
, expProto = exports[PROTOTYPE]
, target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
, key, own, out;
if(IS_GLOBAL)source = name;
for(key in source){
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
if(own && key in exports)continue;
// export native or passed
out = own ? target[key] : source[key];
// prevent global pollution for namespaces
exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
// bind timers to global for call from export context
: IS_BIND && own ? ctx(out, global)
// wrap global constructors for prevent change them in library
: IS_WRAP && target[key] == out ? (function(C){
var F = function(a, b, c){
if(this instanceof C){
switch(arguments.length){
case 0: return new C;
case 1: return new C(a);
case 2: return new C(a, b);
} return new C(a, b, c);
} return C.apply(this, arguments);
};
F[PROTOTYPE] = C[PROTOTYPE];
return F;
// make static versions for prototype methods
})(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
if(IS_PROTO){
(exports.virtual || (exports.virtual = {}))[key] = out;
// export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out);
}
}
};
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
},{"./_core":15,"./_ctx":16,"./_global":23,"./_hide":25}],22:[function(require,module,exports){
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
},{}],23:[function(require,module,exports){
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
},{}],24:[function(require,module,exports){
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function(it, key){
return hasOwnProperty.call(it, key);
};
},{}],25:[function(require,module,exports){
var dP = require('./_object-dp')
, createDesc = require('./_property-desc');
module.exports = require('./_descriptors') ? function(object, key, value){
return dP.f(object, key, createDesc(1, value));
} : function(object, key, value){
object[key] = value;
return object;
};
},{"./_descriptors":18,"./_object-dp":36,"./_property-desc":42}],26:[function(require,module,exports){
module.exports = require('./_global').document && document.documentElement;
},{"./_global":23}],27:[function(require,module,exports){
module.exports = !require('./_descriptors') && !require('./_fails')(function(){
return Object.defineProperty(require('./_dom-create')('div'), 'a', {get: function(){ return 7; }}).a != 7;
});
},{"./_descriptors":18,"./_dom-create":19,"./_fails":22}],28:[function(require,module,exports){
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = require('./_cof');
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
},{"./_cof":14}],29:[function(require,module,exports){
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
},{}],30:[function(require,module,exports){
'use strict';
var create = require('./_object-create')
, descriptor = require('./_property-desc')
, setToStringTag = require('./_set-to-string-tag')
, IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
require('./_hide')(IteratorPrototype, require('./_wks')('iterator'), function(){ return this; });
module.exports = function(Constructor, NAME, next){
Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)});
setToStringTag(Constructor, NAME + ' Iterator');
};
},{"./_hide":25,"./_object-create":35,"./_property-desc":42,"./_set-to-string-tag":44,"./_wks":55}],31:[function(require,module,exports){
'use strict';
var LIBRARY = require('./_library')
, $export = require('./_export')
, redefine = require('./_redefine')
, hide = require('./_hide')
, has = require('./_has')
, Iterators = require('./_iterators')
, $iterCreate = require('./_iter-create')
, setToStringTag = require('./_set-to-string-tag')
, getPrototypeOf = require('./_object-gpo')
, ITERATOR = require('./_wks')('iterator')
, BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next`
, FF_ITERATOR = '@@iterator'
, KEYS = 'keys'
, VALUES = 'values';
var returnThis = function(){ return this; };
module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){
$iterCreate(Constructor, NAME, next);
var getMethod = function(kind){
if(!BUGGY && kind in proto)return proto[kind];
switch(kind){
case KEYS: return function keys(){ return new Constructor(this, kind); };
case VALUES: return function values(){ return new Constructor(this, kind); };
} return function entries(){ return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator'
, DEF_VALUES = DEFAULT == VALUES
, VALUES_BUG = false
, proto = Base.prototype
, $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]
, $default = $native || getMethod(DEFAULT)
, $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined
, $anyNative = NAME == 'Array' ? proto.entries || $native : $native
, methods, key, IteratorPrototype;
// Fix native
if($anyNative){
IteratorPrototype = getPrototypeOf($anyNative.call(new Base));
if(IteratorPrototype !== Object.prototype){
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if(DEF_VALUES && $native && $native.name !== VALUES){
VALUES_BUG = true;
$default = function values(){ return $native.call(this); };
}
// Define iterator
if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if(DEFAULT){
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if(FORCED)for(key in methods){
if(!(key in proto))redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
},{"./_export":21,"./_has":24,"./_hide":25,"./_iter-create":30,"./_iterators":33,"./_library":34,"./_object-gpo":38,"./_redefine":43,"./_set-to-string-tag":44,"./_wks":55}],32:[function(require,module,exports){
module.exports = function(done, value){
return {value: value, done: !!done};
};
},{}],33:[function(require,module,exports){
module.exports = {};
},{}],34:[function(require,module,exports){
module.exports = true;
},{}],35:[function(require,module,exports){
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = require('./_an-object')
, dPs = require('./_object-dps')
, enumBugKeys = require('./_enum-bug-keys')
, IE_PROTO = require('./_shared-key')('IE_PROTO')
, Empty = function(){ /* empty */ }
, PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function(){
// Thrash, waste and sodomy: IE GC bug
var iframe = require('./_dom-create')('iframe')
, i = enumBugKeys.length
, lt = '<'
, gt = '>'
, iframeDocument;
iframe.style.display = 'none';
require('./_html').appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties){
var result;
if(O !== null){
Empty[PROTOTYPE] = anObject(O);
result = new Empty;
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
},{"./_an-object":11,"./_dom-create":19,"./_enum-bug-keys":20,"./_html":26,"./_object-dps":37,"./_shared-key":45}],36:[function(require,module,exports){
var anObject = require('./_an-object')
, IE8_DOM_DEFINE = require('./_ie8-dom-define')
, toPrimitive = require('./_to-primitive')
, dP = Object.defineProperty;
exports.f = require('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes){
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if(IE8_DOM_DEFINE)try {
return dP(O, P, Attributes);
} catch(e){ /* empty */ }
if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
if('value' in Attributes)O[P] = Attributes.value;
return O;
};
},{"./_an-object":11,"./_descriptors":18,"./_ie8-dom-define":27,"./_to-primitive":53}],37:[function(require,module,exports){
var dP = require('./_object-dp')
, anObject = require('./_an-object')
, getKeys = require('./_object-keys');
module.exports = require('./_descriptors') ? Object.defineProperties : function defineProperties(O, Properties){
anObject(O);
var keys = getKeys(Properties)
, length = keys.length
, i = 0
, P;
while(length > i)dP.f(O, P = keys[i++], Properties[P]);
return O;
};
},{"./_an-object":11,"./_descriptors":18,"./_object-dp":36,"./_object-keys":40}],38:[function(require,module,exports){
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = require('./_has')
, toObject = require('./_to-object')
, IE_PROTO = require('./_shared-key')('IE_PROTO')
, ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function(O){
O = toObject(O);
if(has(O, IE_PROTO))return O[IE_PROTO];
if(typeof O.constructor == 'function' && O instanceof O.constructor){
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
},{"./_has":24,"./_shared-key":45,"./_to-object":52}],39:[function(require,module,exports){
var has = require('./_has')
, toIObject = require('./_to-iobject')
, arrayIndexOf = require('./_array-includes')(false)
, IE_PROTO = require('./_shared-key')('IE_PROTO');
module.exports = function(object, names){
var O = toIObject(object)
, i = 0
, result = []
, key;
for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while(names.length > i)if(has(O, key = names[i++])){
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
},{"./_array-includes":12,"./_has":24,"./_shared-key":45,"./_to-iobject":50}],40:[function(require,module,exports){
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = require('./_object-keys-internal')
, enumBugKeys = require('./_enum-bug-keys');
module.exports = Object.keys || function keys(O){
return $keys(O, enumBugKeys);
};
},{"./_enum-bug-keys":20,"./_object-keys-internal":39}],41:[function(require,module,exports){
// most Object methods by ES6 should accept primitives
var $export = require('./_export')
, core = require('./_core')
, fails = require('./_fails');
module.exports = function(KEY, exec){
var fn = (core.Object || {})[KEY] || Object[KEY]
, exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
};
},{"./_core":15,"./_export":21,"./_fails":22}],42:[function(require,module,exports){
module.exports = function(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
};
},{}],43:[function(require,module,exports){
module.exports = require('./_hide');
},{"./_hide":25}],44:[function(require,module,exports){
var def = require('./_object-dp').f
, has = require('./_has')
, TAG = require('./_wks')('toStringTag');
module.exports = function(it, tag, stat){
if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag});
};
},{"./_has":24,"./_object-dp":36,"./_wks":55}],45:[function(require,module,exports){
var shared = require('./_shared')('keys')
, uid = require('./_uid');
module.exports = function(key){
return shared[key] || (shared[key] = uid(key));
};
},{"./_shared":46,"./_uid":54}],46:[function(require,module,exports){
var global = require('./_global')
, SHARED = '__core-js_shared__'
, store = global[SHARED] || (global[SHARED] = {});
module.exports = function(key){
return store[key] || (store[key] = {});
};
},{"./_global":23}],47:[function(require,module,exports){
var toInteger = require('./_to-integer')
, defined = require('./_defined');
// true -> String#at
// false -> String#codePointAt
module.exports = function(TO_STRING){
return function(that, pos){
var s = String(defined(that))
, i = toInteger(pos)
, l = s.length
, a, b;
if(i < 0 || i >= l)return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
},{"./_defined":17,"./_to-integer":49}],48:[function(require,module,exports){
var toInteger = require('./_to-integer')
, max = Math.max
, min = Math.min;
module.exports = function(index, length){
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
},{"./_to-integer":49}],49:[function(require,module,exports){
// 7.1.4 ToInteger
var ceil = Math.ceil
, floor = Math.floor;
module.exports = function(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
},{}],50:[function(require,module,exports){
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = require('./_iobject')
, defined = require('./_defined');
module.exports = function(it){
return IObject(defined(it));
};
},{"./_defined":17,"./_iobject":28}],51:[function(require,module,exports){
// 7.1.15 ToLength
var toInteger = require('./_to-integer')
, min = Math.min;
module.exports = function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
},{"./_to-integer":49}],52:[function(require,module,exports){
// 7.1.13 ToObject(argument)
var defined = require('./_defined');
module.exports = function(it){
return Object(defined(it));
};
},{"./_defined":17}],53:[function(require,module,exports){
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = require('./_is-object');
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function(it, S){
if(!isObject(it))return it;
var fn, val;
if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
throw TypeError("Can't convert object to primitive value");
};
},{"./_is-object":29}],54:[function(require,module,exports){
var id = 0
, px = Math.random();
module.exports = function(key){
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
},{}],55:[function(require,module,exports){
var store = require('./_shared')('wks')
, uid = require('./_uid')
, Symbol = require('./_global').Symbol
, USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function(name){
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
},{"./_global":23,"./_shared":46,"./_uid":54}],56:[function(require,module,exports){
var classof = require('./_classof')
, ITERATOR = require('./_wks')('iterator')
, Iterators = require('./_iterators');
module.exports = require('./_core').getIteratorMethod = function(it){
if(it != undefined)return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
},{"./_classof":13,"./_core":15,"./_iterators":33,"./_wks":55}],57:[function(require,module,exports){
var anObject = require('./_an-object')
, get = require('./core.get-iterator-method');
module.exports = require('./_core').getIterator = function(it){
var iterFn = get(it);
if(typeof iterFn != 'function')throw TypeError(it + ' is not iterable!');
return anObject(iterFn.call(it));
};
},{"./_an-object":11,"./_core":15,"./core.get-iterator-method":56}],58:[function(require,module,exports){
'use strict';
var addToUnscopables = require('./_add-to-unscopables')
, step = require('./_iter-step')
, Iterators = require('./_iterators')
, toIObject = require('./_to-iobject');
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = require('./_iter-define')(Array, 'Array', function(iterated, kind){
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function(){
var O = this._t
, kind = this._k
, index = this._i++;
if(!O || index >= O.length){
this._t = undefined;
return step(1);
}
if(kind == 'keys' )return step(0, index);
if(kind == 'values')return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
},{"./_add-to-unscopables":10,"./_iter-define":31,"./_iter-step":32,"./_iterators":33,"./_to-iobject":50}],59:[function(require,module,exports){
var $export = require('./_export');
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
$export($export.S + $export.F * !require('./_descriptors'), 'Object', {defineProperty: require('./_object-dp').f});
},{"./_descriptors":18,"./_export":21,"./_object-dp":36}],60:[function(require,module,exports){
// 19.1.2.14 Object.keys(O)
var toObject = require('./_to-object')
, $keys = require('./_object-keys');
require('./_object-sap')('keys', function(){
return function keys(it){
return $keys(toObject(it));
};
});
},{"./_object-keys":40,"./_object-sap":41,"./_to-object":52}],61:[function(require,module,exports){
'use strict';
var $at = require('./_string-at')(true);
// 21.1.3.27 String.prototype[@@iterator]()
require('./_iter-define')(String, 'String', function(iterated){
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function(){
var O = this._t
, index = this._i
, point;
if(index >= O.length)return {value: undefined, done: true};
point = $at(O, index);
this._i += point.length;
return {value: point, done: false};
});
},{"./_iter-define":31,"./_string-at":47}],62:[function(require,module,exports){
require('./es6.array.iterator');
var global = require('./_global')
, hide = require('./_hide')
, Iterators = require('./_iterators')
, TO_STRING_TAG = require('./_wks')('toStringTag');
for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){
var NAME = collections[i]
, Collection = global[NAME]
, proto = Collection && Collection.prototype;
if(proto && !proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = Iterators.Array;
}
},{"./_global":23,"./_hide":25,"./_iterators":33,"./_wks":55,"./es6.array.iterator":58}],63:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _keys = require("babel-runtime/core-js/object/keys");
var _keys2 = _interopRequireDefault(_keys);
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require("babel-runtime/helpers/createClass");
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Emitter
*/
var Emitter = function () {
function Emitter() {
(0, _classCallCheck3.default)(this, Emitter);
this._data = {};
}
(0, _createClass3.default)(Emitter, [{
key: "on",
value: function on(name, data) {
if (!name) return;
if (!this._data[name]) {
this._data[name] = {};
}
this._data[name] = data;
}
}, {
key: "emit",
value: function emit(name, method, context) {
if (!name || !method) return;
this._data[name].run(method, context);
}
}, {
key: "broadcast",
value: function broadcast(method, context) {
if (!method) return;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = (0, _getIterator3.default)((0, _keys2.default)(this._data)), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var name = _step.value;
this._data[name].run(method, context);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
}, {
key: "keys",
value: function keys() {
return (0, _keys2.default)(this._data);
}
}, {
key: "is",
value: function is(name) {
return !!this._data[name];
}
}, {
key: "get",
value: function get(name) {
return this._data[name];
}
}]);
return Emitter;
}();
exports.default = Emitter;
},{"babel-runtime/core-js/get-iterator":1,"babel-runtime/core-js/object/keys":3,"babel-runtime/helpers/classCallCheck":4,"babel-runtime/helpers/createClass":5}],64:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _getIterator2 = require('babel-runtime/core-js/get-iterator');
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _Emitter = require('../class/_Emitter');
var _Emitter2 = _interopRequireDefault(_Emitter);
var _Subscriber = require('../class/_Subscriber');
var _Subscriber2 = _interopRequireDefault(_Subscriber);
var _RequestAnim = require('../class/_RequestAnim');
var _RequestAnim2 = _interopRequireDefault(_RequestAnim);
var _calc = require('../module/_calc');
var _calc2 = _interopRequireDefault(_calc);
var _help = require('../module/_help');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Flyby = function () {
function Flyby(options) {
(0, _classCallCheck3.default)(this, Flyby);
this.enabled = false;
this.mode = '';
this.painting = false;
this.startX = 0;
this.startY = 0;
this.ghostX = 0;
this.ghostY = 0;
this.currentX = 0;
this.currentY = 0;
this.distanceX = 0;
this.distanceY = 0;
this.distanceAngle = 0;
this.invertX = 0;
this.invertY = 0;
this.originX = 0;
this.originY = 0;
this.between = 0;
this.betweenX = 0;
this.betweenY = 0;
this.betweenAngle = 0;
this.previousX = 0;
this.previousY = 0;
this.direction = '';
this.directionX = '';
this.directionY = '';
this.targetElement = null; // <event.target>
this.startTime = 0; // timestamp by OnStart
this.elapsed = 0; // <endTime> - <startTime>
this.ghostTime = 0; // previously <startTime>
this.onStart = this.onStart.bind(this);
this.onMove = this.onMove.bind(this);
this.onEnd = this.onEnd.bind(this);
this.update = this.update.bind(this);
// In this element, that enabled to mouse and touch events.
this.rangeElement = options.rangeElement || document;
this._addEventListeners();
// Browser painting update
// call requestAnimationFrame
this.paint = new _RequestAnim2.default();
this.paint.tick = this.update;
this.first = false;
this.pinchOnDesktop = false;
this.flickTime = 250;
// event emitter
this.emitter = new _Emitter2.default();
this._initSubscribe(options.subscribers);
// emit configuration
this.emitter.broadcast('onConfig', this);
this.subscriber = null;
}
(0, _createClass3.default)(Flyby, [{
key: 'onStart',
value: function onStart(event) {
// set the flags to initialize
this.enabled = true;
this.painting = true;
this.touched = event.touches ? true : false;
this.first = true;
this.pinchOnDesktop = false;
// set the position to initalize
this.startTime = Date.now();
this.startX = (0, _help.pageX)(event);
this.startY = (0, _help.pageY)(event);
this.distanceX = 0;
this.distanceY = 0;
this.distanceAngle = 0;
this.distance = 0;
this.currentX = this.startX;
this.currentY = this.startY;
this.invertX = this.startX;
this.invertY = this.startY;
this.previousX = this.startX;
this.previousY = this.startY;
this.between = 0;
this.betweenX = 0;
this.betweenY = 0;
this.betweenAngle = 0;
this.direction = '';
this.directionX = '';
this.directionY = '';
this.targetElement = event.target;
if (!this.touched) {
if (this.startTime - this.ghostTime < 750) {
this.pinchOnDesktop = true;
}
}
// find a target & subscriber
this._find(event.target);
// subscribe
this._emit('onStart');
// paint
this.paint.cancel();
this.paint.play();
this.ghostTime = this.startTime;
event.preventDefault();
}
}, {
key: 'onMove',
value: function onMove(event) {
if (!this.enabled) return;
if ((0, _help.hasTouches)(event, 2) || this.pinchOnDesktop) {
this.mode = 'pinch';
} else {
this.mode = 'swipe';
}
this.currentX = (0, _help.pageX)(event);
this.currentY = (0, _help.pageY)(event);
if (this.mode === 'pinch') {
this._invert(event);
this._between();
}
this._distance();
this.originX = this.currentX - parseInt(this.betweenX / 2, 10);
this.originY = this.currentY - parseInt(this.betweenY / 2, 10);
this._direction();
this.targetElement = event.target;
// check ignore list to subscribe
if (!this._inIgnore(this.mode)) {
if (this.first) {
// do of only once on `onMove` method.
this.direction = _calc2.default.which(this.distanceAngle);
}
if (this.mode !== 'swipe' || !this._inIgnore(this.direction)) {
if (this.first) {
this._emit('onOnce');
} else {
this._emit('on' + (0, _help.camel)(this.mode));
}
event.preventDefault();
}
}
// to next step
this.first = false;
this.previousX = this.currentX;
this.previousY = this.currentY;
}
}, {
key: 'onEnd',
value: function onEnd(event) {
this.enabled = false;
this.touched = false;
this.elapsed = Date.now() - this.startTime;
this.ghostX = this.startX;
this.ghostY = this.startY;
this.targetElement = event.target;
if (this._isFlick(this.elapsed)) {
this._emit('onFlick');
}
// element & subscriber
this._emit('onEnd');
}
/**
* update
* Call in requestAnimationFrame
* Related Paiting Dom is here.
*/
}, {
key: 'update',
value: function update() {
if (!this.painting) return;
this.paint.play();
// subscribe
this._emit('onUpdate');
}
/**
* invert
* The posision is another one that is B.
* @private
* @param {Object} event<EventObject>
*/
}, {
key: '_invert',
value: function _invert(event) {
if (this.touched && event.touches[1]) {
this.currentX = event.touches[0].pageX;
this.currentY = event.touches[0].pageY;
this.invertX = event.touches[1].pageX;
this.invertY = event.touches[1].pageY;
} else {
this.invertX = this.ghostX;
this.invertY = this.ghostY;
}
}
/**
* distance
* @private
*/
}, {
key: '_distance',
value: function _distance() {
this.distanceX = this.currentX - this.startX;
this.distanceY = this.currentY - this.startY;
this.distance = _calc2.default.diagonal(this.distanceX, this.distanceY);
this.distanceAngle = _calc2.default.angle(this.distanceY * -1, this.distanceX, true);
}
/**
* between
* Distance of between A and B
* @private
*/
}, {
key: '_between',
value: function _between() {
this.betweenX = this.currentX - this.invertX;
this.betweenY = this.currentY - this.invertY;
this.between = _calc2.default.diagonal(this.betweenX, this.betweenY);
this.betweenAngle = _calc2.default.angle(this.betweenY * -1, this.betweenX, true);
}
/**
* direction
* @private
*/
}, {
key: '_direction',
value: function _direction() {
if (this.currentX > this.previousX) {
this.directionX = 'to right';
} else if (this.currentX < this.previousX) {
this.directionX = 'to left';
}
if (this.currentY > this.previousY) {
this.directionY = 'to bottom';
} else if (this.currentY < this.previousY) {
this.directionY = 'to top';
}
}
/**
* emit
* @private
* @param {String} suffix
* 指定された文字列をキャメルケースに変換し, on と結合してメソッド名にする
* subscriber 内のメソッドを実行する
*/
}, {
key: '_emit',
value: function _emit(method) {
if (!method || !this.subscriber) return;
this.emitter.emit(this.subscriber.selector, method, this);
}
/**
* find
* @private
* @param {Object} node<HTMLElement>
* 今回実行するべき subscriber を探します
*/
}, {
key: '_find',
value: function _find(el) {
var found = false;
this.subscriber = null;
// nodeTree を上方向に探索します
while (el && !found) {
if (el === (0, _help.documentElement)()) {
return found;
}
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = (0, _getIterator3.default)(this.emitter.keys()), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var name = _step.value;
var prefix = name.slice(0, 1);
var selector = name.substr(1);
if ((0, _help.matchElement)(el, selector)) {
if (this.emitter.is(name)) {
this.subscriber = this.emitter.get(name);
this.subscriber.el = el;
found = true;
return found;
}
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
el = el.parentNode;
}
return found;
}
/**
* initSubscribe
* @private
*/
}, {
key: '_initSubscribe',
value: function _initSubscribe(subscribers) {
if (subscribers) {
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = (0, _getIterator3.default)((0, _keys2.default)(subscribers)), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var name = _step2.value;
this.emitter.on(name, new _Subscriber2.default(name, subscribers[name]));
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
}
}
/**
* The `str` includes in ignore list.
* @param {String} str
* @return {Boolean}
*/
}, {
key: '_inIgnore',
value: function _inIgnore(str) {
return this.subscriber.ignore.includes(str);
}
/**
* is Flick?
* @return {Boolean}
*/
}, {
key: '_isFlick',
value: function _isFlick(elapsed) {
return elapsed < this.flickTime && elapsed > 50;
}
/**
* addEventListeners
* @private
*/
}, {
key: '_addEventListeners',
value: function _addEventListeners() {
this.rangeElement.addEventListener('mousedown', this.onStart);
this.rangeElement.addEventListener('mousemove', this.onMove);
this.rangeElement.addEventListener('mouseup', this.onEnd);
this.rangeElement.addEventListener('touchstart', this.onStart);
this.rangeElement.addEventListener('touchmove', this.onMove);
this.rangeElement.addEventListener('touchend', this.onEnd);
}
}]);
return Flyby;
}();
exports.default = Flyby;
},{"../class/_Emitter":63,"../class/_RequestAnim":65,"../class/_Subscriber":66,"../module/_calc":68,"../module/_help":69,"babel-runtime/core-js/get-iterator":1,"babel-runtime/core-js/object/keys":3,"babel-runtime/helpers/classCallCheck":4,"babel-runtime/helpers/createClass":5}],65:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require("babel-runtime/helpers/createClass");
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.setTimeout;
var cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.clearTimeout;
window.requestAnimationFrame = requestAnimationFrame;
window.cancelAnimationFrame = cancelAnimationFrame;
var ReqestAnim = function () {
function ReqestAnim() {
(0, _classCallCheck3.default)(this, ReqestAnim);
this._id = null;
this._tick = null;
}
(0, _createClass3.default)(ReqestAnim, [{
key: "play",
value: function play(callback) {
var _this = this;
this.id = requestAnimationFrame(function () {
if (callback) callback();
_this._tick();
});
}
}, {
key: "cancel",
value: function cancel() {
if (this._id != null) {
cancelAnimationFrame(this._id);
}
}
}, {
key: "id",
set: function set(id) {
this._id = id;
},
get: function get() {
return this._id;
}
}, {
key: "tick",
set: function set(callback) {
this._tick = callback;
}
}]);
return ReqestAnim;
}();
exports.default = ReqestAnim;
},{"babel-runtime/helpers/classCallCheck":4,"babel-runtime/helpers/createClass":5}],66:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _keys = require('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Target
* @member {String} _name
* @member {HTMLElement} _el
* @member {Object} _methods
* @member {Array} _ignore
*/
var Subscriber = function () {
function Subscriber(name, body) {
(0, _classCallCheck3.default)(this, Subscriber);
this._name = '';
this._selector = '';
this._element = null;
this._methods = this._defaultMethods();
this._ignore = [];
this._scope = {};
this.name = name.replace(/^[.#]/, '');
this.selector = name;
this.ignore = body.ignore;
this.methods = body;
}
(0, _createClass3.default)(Subscriber, [{
key: 'run',
value: function run(methodName, context) {
if (this._methods[methodName]) {
this._methods[methodName].bind(context)(this._scope, this._elementement);
}
}
}, {
key: '_defaultMethods',
value: function _defaultMethods() {
var noop = function noop() {};
var methods = ['Config', 'Start', 'Once', 'Swipe', 'Pinch', 'Flick', 'End', 'Update'];
return function (res) {
methods.forEach(function (name) {
var key = ['on', name].join('');
res[key] = noop;
});
return res;
}({});
}
}, {
key: 'name',
set: function set(str) {
this._name = str;
},
get: function get() {
return this._name;
}
}, {
key: 'selector',
set: function set(str) {
this._selector = str;
},
get: function get() {
return this._selector;
}
}, {
key: 'methods',
set: function set(obj) {
var _this = this;
(0, _keys2.default)(obj).forEach(function (key) {
if (typeof obj[key] === 'function') {
_this._methods[key] = obj[key];
}
});
},
get: function get() {
return this._methods;
}
}, {
key: 'ignore',
set: function set(array) {
this._ignore = array || [];
},
get: function get() {
return this._ignore;
}
}, {
key: 'el',
set: function set(element) {
this._element = element;
},
get: function get() {
return this._element;
}
}]);
return Subscriber;
}();
exports.default = Subscriber;
},{"babel-runtime/core-js/object/keys":3,"babel-runtime/helpers/classCallCheck":4,"babel-runtime/helpers/createClass":5}],67:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _Flyby = require('./class/_Flyby');
var _Flyby2 = _interopRequireDefault(_Flyby);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _Flyby2.default; /**
* NOTE: Positions declarations
* Start - 始点 <x, y>
* End - 終点 <x, y> **不要?**
* Current - 現在地 <x, y>
* Distance - 始点から現在地への距離 <x, y> [swipe]
* Invert - 2つ目の始点 <x, y> [pinch]
* Between - Start と Invert の距離 <d> [pinch]
* Origin - Start と Invert の開始時の中間地点 <x, y> [pinch]
* Offset - 対象ノードの座標 <x, y> **外側でやる**
*/
/**
* NOTE: API methods
* onConfig(scope)
* onStart(scope, element)
* onEnd(scope, element)
* onFirstStep(scope, element)
* onPinch(scope, element)
* onSwipe(scope, element)
* onFlick(scope, element)
* onUpdate(scope, element)
* ignore [x, y, swipe, pinch]
*/
},{"./class/_Flyby":64}],68:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _help = require('./_help');
exports.default = function () {
return { degree: degree, radian: radian, angle: angle, diagonal: diagonal, which: which };
}();
/**
* diagonal
* @param {Number} x
* @param {Number} y
* @return {Number} d
*/
function diagonal(x, y) {
return parseInt((0, _help.sqrt)((0, _help.pow)(x, 2) + (0, _help.pow)(y, 2)));
}
/**
* Wrapped `Math.atan2`
* @private
* @param {Number} y
* @param {Number} x
*/
function angle(y, x) {
var toDegree = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
if (toDegree) {
return degree((0, _help.atan2)(y, x));
}
return (0, _help.atan2)(y, x);
}
/**
* which
* swipe の軸の向きを検出します
* @return {String}
*/
function which(angle) {
angle = (0, _help.abs)(angle);
if (angle < 180 + 5 && angle > 180 - 5 || angle < 10) {
return 'x';
}
return 'y';
}
/**
* degree
* The radian convert to degree.
* @private
* @param {Number} radian
* @param {Number} degree
*/
function degree(radian) {
return radian * 180 / _help.PI;
}
/**
* radian
* The degree convert to radian
* @private
* @param {Number} degree
* @return {Number} radian
*/
function radian(degree) {
return degree * _help.PI / 180;
}
},{"./_help":69}],69:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.camel = camel;
exports.hasClass = hasClass;
exports.hasId = hasId;
exports.matchElement = matchElement;
exports.documentElement = documentElement;
exports.pageX = pageX;
exports.pageY = pageY;
exports.touches = touches;
exports.hasTouches = hasTouches;
exports.noop = noop;
/**
* help.js
*/
var PI = Math.PI;
var sqrt = Math.sqrt;
var atan2 = Math.atan2;
var abs = Math.abs;
var pow = Math.pow;
exports.PI = PI;
exports.sqrt = sqrt;
exports.atan2 = atan2;
exports.abs = abs;
exports.pow = pow;
function camel(str) {
return [str.substr(0, 1).toUpperCase(), str.substr(1)].join('');
}
function hasClass(el, selector) {
return el.classList.contains(selector);
}
function hasId(el, selector) {
return el.getAttribute('id') === selector;
}
function matchElement(el, selector) {
return hasClass(el, selector) || hasId(el, selector);
}
function documentElement() {
return document.documentElement;
}
/**
* pageX
* @private
* @param {Object} event<EventObject>
*/
function pageX(event) {
if (event.pageX != null) {
return event.pageX;
}
return event.touches[0].pageX;
}
/**
* pageY
* @private
* @param {Object} event<EventObject>
*/
function pageY(event) {
if (event.pageY != null) {
return event.pageY;
}
return event.touches[0].pageY;
}
/**
* touches
* @param {Object} event<EventObject>
* @return {Boolean}
* Event オブジェクトから touches 抽出して返す
*/
function touches(event) {
return event.originalEvent ? event.originalEvent.touches : event.touches;
}
/**
* hasTouches
* @private
* @param {Object} event<EventObject>
* @param {Number} length
* @return {Boolean}
*/
function hasTouches(event, length) {
var _touches = touches(event);
if (_touches != null && _touches.length === length) {
return true;
}
return false;
}
/**
* No operation
*/
function noop() {
return;
}
},{}]},{},[67]);
|
module.exports = {
parserOptions: {
sourceType: 'script',
},
};
|
window.ImageViewer = function(url, alt, title){
var img = $('<img />').attr('src', url).attr('alt', title).css({
display: 'inline-block',
'max-width': '90vw',
'max-height': '90vh'
});
var a = $('<a></a>').attr('target', '_blank')
.attr('title', title)
.attr('href', url)
.css({
display: 'inline-block',
height: '100%'
})
.append(img);
var close_it = function(){
overlay.remove();
container.remove();
};
var closeBtn = $('<a class="icon-remove-sign"></a>').css({
color: 'red',
'font-size': 'x-large',
'margin-left': '-0.1em'
}).bind('click', close_it);
var closeWrapper = $('<div></div>').css({
height: '100%',
width: '2em',
'text-align': 'left',
'display': 'inline-block',
'vertical-algin': 'top',
'margin-top': '-0.6em',
'float': 'right'
}).append(closeBtn);
var container = $('<div></div>').append(
$('<div></div>').css({
margin: '5vh 1vw',
display: 'inline-block',
'vertical-align': 'top'
}).append(a).append(closeWrapper))
.css({
'z-index': 30000000,
'position': 'fixed',
'padding': 0,
'margin': 0,
'width': '100vw',
'height': '100vh',
'top': 0,
'left': 0,
'text-align': 'center',
'cursor': 'default',
'vertical-align': 'middle'
})
.bind('click',close_it)
.appendTo('body');
var overlay = $('<div class="blockUI blockMsg blockPage">').css({
'z-index': 9999,
'position': 'fixed',
padding: 0,
margin: 0,
width: '100vw',
height: '100vh',
top: '0vh',
left: '0vw',
'text-align': 'center',
'cursor': 'default',
'vertical-align': 'middle',
'background-color': 'gray',
'opacity': '0.4'
}).bind('click', close_it).appendTo('body');
this.close = close_it;
return this;
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
}
};
app.initialize();
|
define("helios/Helios-Debugger", ["amber/boot", "amber_core/Kernel-Objects", "helios/Helios-Core", "helios/Helios-Workspace"], function($boot){
var smalltalk=$boot.vm,nil=$boot.nil,_st=$boot.asReceiver,globals=$boot.globals;
smalltalk.addPackage('Helios-Debugger');
smalltalk.packages["Helios-Debugger"].transport = {"type":"amd","amdNamespace":"helios"};
smalltalk.addClass('HLContextInspectorDecorator', globals.Object, ['context'], 'Helios-Debugger');
smalltalk.addMethod(
smalltalk.method({
selector: "context",
protocol: 'accessing',
fn: function (){
var self=this;
var $1;
$1=self["@context"];
return $1;
},
args: [],
source: "context\x0a\x09^ context",
messageSends: [],
referencedClasses: []
}),
globals.HLContextInspectorDecorator);
smalltalk.addMethod(
smalltalk.method({
selector: "evaluate:on:",
protocol: 'evaluating',
fn: function (aString,anEvaluator){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._context())._evaluate_on_(aString,anEvaluator);
return $1;
}, function($ctx1) {$ctx1.fill(self,"evaluate:on:",{aString:aString,anEvaluator:anEvaluator},globals.HLContextInspectorDecorator)})},
args: ["aString", "anEvaluator"],
source: "evaluate: aString on: anEvaluator\x0a\x09^ self context evaluate: aString on: anEvaluator",
messageSends: ["evaluate:on:", "context"],
referencedClasses: []
}),
globals.HLContextInspectorDecorator);
smalltalk.addMethod(
smalltalk.method({
selector: "initializeFromContext:",
protocol: 'initialization',
fn: function (aContext){
var self=this;
self["@context"]=aContext;
return self},
args: ["aContext"],
source: "initializeFromContext: aContext\x0a\x09context := aContext",
messageSends: [],
referencedClasses: []
}),
globals.HLContextInspectorDecorator);
smalltalk.addMethod(
smalltalk.method({
selector: "inspectOn:",
protocol: 'inspecting',
fn: function (anInspector){
var self=this;
var variables,inspectedContext;
function $Dictionary(){return globals.Dictionary||(typeof Dictionary=="undefined"?nil:Dictionary)}
return smalltalk.withContext(function($ctx1) {
var $1,$2,$3,$4,$receiver;
variables=_st($Dictionary())._new();
inspectedContext=self._context();
$1=variables;
$2=_st(inspectedContext)._locals();
$ctx1.sendIdx["locals"]=1;
_st($1)._addAll_($2);
$ctx1.sendIdx["addAll:"]=1;
_st((function(){
return smalltalk.withContext(function($ctx2) {
return _st(_st(inspectedContext)._notNil())._and_((function(){
return smalltalk.withContext(function($ctx3) {
return _st(inspectedContext)._isBlockContext();
}, function($ctx3) {$ctx3.fillBlock({},$ctx2,2)})}));
}, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})}))._whileTrue_((function(){
return smalltalk.withContext(function($ctx2) {
inspectedContext=_st(inspectedContext)._outerContext();
inspectedContext;
$3=inspectedContext;
if(($receiver = $3) == null || $receiver.isNil){
return $3;
} else {
return _st(variables)._addAll_(_st(inspectedContext)._locals());
};
}, function($ctx2) {$ctx2.fillBlock({},$ctx1,3)})}));
_st(anInspector)._setLabel_("Context");
$4=_st(anInspector)._setVariables_(variables);
return self}, function($ctx1) {$ctx1.fill(self,"inspectOn:",{anInspector:anInspector,variables:variables,inspectedContext:inspectedContext},globals.HLContextInspectorDecorator)})},
args: ["anInspector"],
source: "inspectOn: anInspector\x0a\x09| variables inspectedContext |\x0a\x09\x0a\x09variables := Dictionary new.\x0a\x09inspectedContext := self context.\x0a\x09\x0a\x09variables addAll: inspectedContext locals.\x0a\x09\x0a\x09[ inspectedContext notNil and: [ inspectedContext isBlockContext ] ] whileTrue: [\x0a\x09\x09inspectedContext := inspectedContext outerContext.\x0a\x09\x09inspectedContext ifNotNil: [\x0a\x09\x09\x09variables addAll: inspectedContext locals ] ].\x0a\x09\x0a\x09anInspector\x0a\x09\x09setLabel: 'Context';\x0a\x09\x09setVariables: variables",
messageSends: ["new", "context", "addAll:", "locals", "whileTrue:", "and:", "notNil", "isBlockContext", "outerContext", "ifNotNil:", "setLabel:", "setVariables:"],
referencedClasses: ["Dictionary"]
}),
globals.HLContextInspectorDecorator);
smalltalk.addMethod(
smalltalk.method({
selector: "on:",
protocol: 'instance creation',
fn: function (aContext){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$3,$1;
$2=self._new();
_st($2)._initializeFromContext_(aContext);
$3=_st($2)._yourself();
$1=$3;
return $1;
}, function($ctx1) {$ctx1.fill(self,"on:",{aContext:aContext},globals.HLContextInspectorDecorator.klass)})},
args: ["aContext"],
source: "on: aContext\x0a\x09^ self new\x0a\x09\x09initializeFromContext: aContext;\x0a\x09\x09yourself",
messageSends: ["initializeFromContext:", "new", "yourself"],
referencedClasses: []
}),
globals.HLContextInspectorDecorator.klass);
smalltalk.addClass('HLDebugger', globals.HLFocusableWidget, ['model', 'stackListWidget', 'codeWidget', 'inspectorWidget'], 'Helios-Debugger');
globals.HLDebugger.comment="I am the main widget for the Helios debugger.";
smalltalk.addMethod(
smalltalk.method({
selector: "codeWidget",
protocol: 'widgets',
fn: function (){
var self=this;
function $HLDebuggerCodeWidget(){return globals.HLDebuggerCodeWidget||(typeof HLDebuggerCodeWidget=="undefined"?nil:HLDebuggerCodeWidget)}
function $HLDebuggerCodeModel(){return globals.HLDebuggerCodeModel||(typeof HLDebuggerCodeModel=="undefined"?nil:HLDebuggerCodeModel)}
return smalltalk.withContext(function($ctx1) {
var $2,$3,$4,$6,$7,$8,$9,$5,$10,$1,$receiver;
$2=self["@codeWidget"];
if(($receiver = $2) == null || $receiver.isNil){
$3=_st($HLDebuggerCodeWidget())._new();
$ctx1.sendIdx["new"]=1;
$4=$3;
$6=_st($HLDebuggerCodeModel())._new();
$7=$6;
$8=self._model();
$ctx1.sendIdx["model"]=1;
_st($7)._debuggerModel_($8);
$9=_st($6)._yourself();
$ctx1.sendIdx["yourself"]=1;
$5=$9;
_st($4)._model_($5);
_st($3)._browserModel_(self._model());
$10=_st($3)._yourself();
self["@codeWidget"]=$10;
$1=self["@codeWidget"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"codeWidget",{},globals.HLDebugger)})},
args: [],
source: "codeWidget\x0a\x09^ codeWidget ifNil: [ codeWidget := HLDebuggerCodeWidget new\x0a\x09\x09model: (HLDebuggerCodeModel new\x0a\x09\x09\x09debuggerModel: self model;\x0a\x09\x09\x09yourself);\x0a\x09\x09browserModel: self model;\x0a\x09\x09yourself ]",
messageSends: ["ifNil:", "model:", "new", "debuggerModel:", "model", "yourself", "browserModel:"],
referencedClasses: ["HLDebuggerCodeWidget", "HLDebuggerCodeModel"]
}),
globals.HLDebugger);
smalltalk.addMethod(
smalltalk.method({
selector: "cssClass",
protocol: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=($ctx1.supercall = true, globals.HLDebugger.superclass.fn.prototype._cssClass.apply(_st(self), []));
$ctx1.supercall = false;
$1=_st($2).__comma(" hl_debugger");
return $1;
}, function($ctx1) {$ctx1.fill(self,"cssClass",{},globals.HLDebugger)})},
args: [],
source: "cssClass\x0a\x09^ super cssClass, ' hl_debugger'",
messageSends: [",", "cssClass"],
referencedClasses: []
}),
globals.HLDebugger);
smalltalk.addMethod(
smalltalk.method({
selector: "focus",
protocol: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self._stackListWidget())._focus();
return self}, function($ctx1) {$ctx1.fill(self,"focus",{},globals.HLDebugger)})},
args: [],
source: "focus\x0a\x09self stackListWidget focus",
messageSends: ["focus", "stackListWidget"],
referencedClasses: []
}),
globals.HLDebugger);
smalltalk.addMethod(
smalltalk.method({
selector: "initializeFromError:",
protocol: 'initialization',
fn: function (anError){
var self=this;
function $HLDebuggerModel(){return globals.HLDebuggerModel||(typeof HLDebuggerModel=="undefined"?nil:HLDebuggerModel)}
return smalltalk.withContext(function($ctx1) {
self["@model"]=_st($HLDebuggerModel())._on_(anError);
self._observeModel();
return self}, function($ctx1) {$ctx1.fill(self,"initializeFromError:",{anError:anError},globals.HLDebugger)})},
args: ["anError"],
source: "initializeFromError: anError\x0a\x09model := HLDebuggerModel on: anError.\x0a\x09self observeModel",
messageSends: ["on:", "observeModel"],
referencedClasses: ["HLDebuggerModel"]
}),
globals.HLDebugger);
smalltalk.addMethod(
smalltalk.method({
selector: "inspectorWidget",
protocol: 'widgets',
fn: function (){
var self=this;
function $HLInspectorWidget(){return globals.HLInspectorWidget||(typeof HLInspectorWidget=="undefined"?nil:HLInspectorWidget)}
return smalltalk.withContext(function($ctx1) {
var $2,$1,$receiver;
$2=self["@inspectorWidget"];
if(($receiver = $2) == null || $receiver.isNil){
self["@inspectorWidget"]=_st($HLInspectorWidget())._new();
$1=self["@inspectorWidget"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"inspectorWidget",{},globals.HLDebugger)})},
args: [],
source: "inspectorWidget\x0a\x09^ inspectorWidget ifNil: [ \x0a\x09\x09inspectorWidget := HLInspectorWidget new ]",
messageSends: ["ifNil:", "new"],
referencedClasses: ["HLInspectorWidget"]
}),
globals.HLDebugger);
smalltalk.addMethod(
smalltalk.method({
selector: "model",
protocol: 'accessing',
fn: function (){
var self=this;
function $HLDebuggerModel(){return globals.HLDebuggerModel||(typeof HLDebuggerModel=="undefined"?nil:HLDebuggerModel)}
return smalltalk.withContext(function($ctx1) {
var $2,$1,$receiver;
$2=self["@model"];
if(($receiver = $2) == null || $receiver.isNil){
self["@model"]=_st($HLDebuggerModel())._new();
$1=self["@model"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"model",{},globals.HLDebugger)})},
args: [],
source: "model\x0a\x09^ model ifNil: [ model := HLDebuggerModel new ]",
messageSends: ["ifNil:", "new"],
referencedClasses: ["HLDebuggerModel"]
}),
globals.HLDebugger);
smalltalk.addMethod(
smalltalk.method({
selector: "observeModel",
protocol: 'actions',
fn: function (){
var self=this;
function $HLDebuggerContextSelected(){return globals.HLDebuggerContextSelected||(typeof HLDebuggerContextSelected=="undefined"?nil:HLDebuggerContextSelected)}
function $HLDebuggerStepped(){return globals.HLDebuggerStepped||(typeof HLDebuggerStepped=="undefined"?nil:HLDebuggerStepped)}
function $HLDebuggerProceeded(){return globals.HLDebuggerProceeded||(typeof HLDebuggerProceeded=="undefined"?nil:HLDebuggerProceeded)}
return smalltalk.withContext(function($ctx1) {
var $1,$2;
$1=_st(self._model())._announcer();
_st($1)._on_send_to_($HLDebuggerContextSelected(),"onContextSelected:",self);
$ctx1.sendIdx["on:send:to:"]=1;
_st($1)._on_send_to_($HLDebuggerStepped(),"onDebuggerStepped:",self);
$ctx1.sendIdx["on:send:to:"]=2;
$2=_st($1)._on_send_to_($HLDebuggerProceeded(),"onDebuggerProceeded",self);
return self}, function($ctx1) {$ctx1.fill(self,"observeModel",{},globals.HLDebugger)})},
args: [],
source: "observeModel\x0a\x09self model announcer \x0a\x09\x09on: HLDebuggerContextSelected\x0a\x09\x09send: #onContextSelected:\x0a\x09\x09to: self;\x0a\x09\x09\x0a\x09\x09on: HLDebuggerStepped\x0a\x09\x09send: #onDebuggerStepped:\x0a\x09\x09to: self;\x0a\x09\x09\x0a\x09\x09on: HLDebuggerProceeded\x0a\x09\x09send: #onDebuggerProceeded\x0a\x09\x09to: self",
messageSends: ["on:send:to:", "announcer", "model"],
referencedClasses: ["HLDebuggerContextSelected", "HLDebuggerStepped", "HLDebuggerProceeded"]
}),
globals.HLDebugger);
smalltalk.addMethod(
smalltalk.method({
selector: "onContextSelected:",
protocol: 'reactions',
fn: function (anAnnouncement){
var self=this;
function $HLContextInspectorDecorator(){return globals.HLContextInspectorDecorator||(typeof HLContextInspectorDecorator=="undefined"?nil:HLContextInspectorDecorator)}
return smalltalk.withContext(function($ctx1) {
_st(self._inspectorWidget())._inspect_(_st($HLContextInspectorDecorator())._on_(_st(anAnnouncement)._context()));
return self}, function($ctx1) {$ctx1.fill(self,"onContextSelected:",{anAnnouncement:anAnnouncement},globals.HLDebugger)})},
args: ["anAnnouncement"],
source: "onContextSelected: anAnnouncement\x0a\x09self inspectorWidget inspect: (HLContextInspectorDecorator on: anAnnouncement context)",
messageSends: ["inspect:", "inspectorWidget", "on:", "context"],
referencedClasses: ["HLContextInspectorDecorator"]
}),
globals.HLDebugger);
smalltalk.addMethod(
smalltalk.method({
selector: "onDebuggerProceeded",
protocol: 'reactions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
self._removeTab();
return self}, function($ctx1) {$ctx1.fill(self,"onDebuggerProceeded",{},globals.HLDebugger)})},
args: [],
source: "onDebuggerProceeded\x0a\x09self removeTab",
messageSends: ["removeTab"],
referencedClasses: []
}),
globals.HLDebugger);
smalltalk.addMethod(
smalltalk.method({
selector: "onDebuggerStepped:",
protocol: 'reactions',
fn: function (anAnnouncement){
var self=this;
function $HLContextInspectorDecorator(){return globals.HLContextInspectorDecorator||(typeof HLContextInspectorDecorator=="undefined"?nil:HLContextInspectorDecorator)}
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._model())._atEnd();
if(smalltalk.assert($1)){
self._removeTab();
};
_st(self._inspectorWidget())._inspect_(_st($HLContextInspectorDecorator())._on_(_st(anAnnouncement)._context()));
_st(self._stackListWidget())._refresh();
return self}, function($ctx1) {$ctx1.fill(self,"onDebuggerStepped:",{anAnnouncement:anAnnouncement},globals.HLDebugger)})},
args: ["anAnnouncement"],
source: "onDebuggerStepped: anAnnouncement\x0a\x09self model atEnd ifTrue: [ self removeTab ].\x0a\x09\x0a\x09self inspectorWidget inspect: (HLContextInspectorDecorator on: anAnnouncement context).\x0a\x09self stackListWidget refresh",
messageSends: ["ifTrue:", "atEnd", "model", "removeTab", "inspect:", "inspectorWidget", "on:", "context", "refresh", "stackListWidget"],
referencedClasses: ["HLContextInspectorDecorator"]
}),
globals.HLDebugger);
smalltalk.addMethod(
smalltalk.method({
selector: "registerBindingsOn:",
protocol: 'keybindings',
fn: function (aBindingGroup){
var self=this;
function $HLToolCommand(){return globals.HLToolCommand||(typeof HLToolCommand=="undefined"?nil:HLToolCommand)}
return smalltalk.withContext(function($ctx1) {
_st($HLToolCommand())._registerConcreteClassesOn_for_(aBindingGroup,self._model());
return self}, function($ctx1) {$ctx1.fill(self,"registerBindingsOn:",{aBindingGroup:aBindingGroup},globals.HLDebugger)})},
args: ["aBindingGroup"],
source: "registerBindingsOn: aBindingGroup\x0a\x09HLToolCommand \x0a\x09\x09registerConcreteClassesOn: aBindingGroup \x0a\x09\x09for: self model",
messageSends: ["registerConcreteClassesOn:for:", "model"],
referencedClasses: ["HLToolCommand"]
}),
globals.HLDebugger);
smalltalk.addMethod(
smalltalk.method({
selector: "renderContentOn:",
protocol: 'rendering',
fn: function (html){
var self=this;
function $HLContainer(){return globals.HLContainer||(typeof HLContainer=="undefined"?nil:HLContainer)}
function $HLVerticalSplitter(){return globals.HLVerticalSplitter||(typeof HLVerticalSplitter=="undefined"?nil:HLVerticalSplitter)}
function $HLHorizontalSplitter(){return globals.HLHorizontalSplitter||(typeof HLHorizontalSplitter=="undefined"?nil:HLHorizontalSplitter)}
return smalltalk.withContext(function($ctx1) {
var $2,$1;
self._renderHeadOn_(html);
$2=_st($HLVerticalSplitter())._with_with_(self._codeWidget(),_st($HLHorizontalSplitter())._with_with_(self._stackListWidget(),self._inspectorWidget()));
$ctx1.sendIdx["with:with:"]=1;
$1=_st($HLContainer())._with_($2);
_st(html)._with_($1);
$ctx1.sendIdx["with:"]=1;
return self}, function($ctx1) {$ctx1.fill(self,"renderContentOn:",{html:html},globals.HLDebugger)})},
args: ["html"],
source: "renderContentOn: html\x0a\x09self renderHeadOn: html.\x0a\x09html with: (HLContainer with: (HLVerticalSplitter\x0a\x09\x09with: self codeWidget\x0a\x09\x09with: (HLHorizontalSplitter\x0a\x09\x09\x09with: self stackListWidget\x0a\x09\x09\x09with: self inspectorWidget)))",
messageSends: ["renderHeadOn:", "with:", "with:with:", "codeWidget", "stackListWidget", "inspectorWidget"],
referencedClasses: ["HLContainer", "HLVerticalSplitter", "HLHorizontalSplitter"]
}),
globals.HLDebugger);
smalltalk.addMethod(
smalltalk.method({
selector: "renderHeadOn:",
protocol: 'rendering',
fn: function (html){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1,$2;
$1=_st(html)._div();
_st($1)._class_("head");
$2=_st($1)._with_((function(){
return smalltalk.withContext(function($ctx2) {
return _st(_st(html)._h2())._with_(_st(_st(self._model())._error())._messageText());
}, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})}));
$ctx1.sendIdx["with:"]=1;
return self}, function($ctx1) {$ctx1.fill(self,"renderHeadOn:",{html:html},globals.HLDebugger)})},
args: ["html"],
source: "renderHeadOn: html\x0a\x09html div \x0a\x09\x09class: 'head'; \x0a\x09\x09with: [ html h2 with: self model error messageText ]",
messageSends: ["class:", "div", "with:", "h2", "messageText", "error", "model"],
referencedClasses: []
}),
globals.HLDebugger);
smalltalk.addMethod(
smalltalk.method({
selector: "stackListWidget",
protocol: 'widgets',
fn: function (){
var self=this;
function $HLStackListWidget(){return globals.HLStackListWidget||(typeof HLStackListWidget=="undefined"?nil:HLStackListWidget)}
return smalltalk.withContext(function($ctx1) {
var $2,$3,$4,$1,$receiver;
$2=self["@stackListWidget"];
if(($receiver = $2) == null || $receiver.isNil){
$3=_st($HLStackListWidget())._on_(self._model());
_st($3)._next_(self._codeWidget());
$4=_st($3)._yourself();
self["@stackListWidget"]=$4;
$1=self["@stackListWidget"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"stackListWidget",{},globals.HLDebugger)})},
args: [],
source: "stackListWidget\x0a\x09^ stackListWidget ifNil: [ \x0a\x09\x09stackListWidget := (HLStackListWidget on: self model)\x0a\x09\x09\x09next: self codeWidget;\x0a\x09\x09\x09yourself ]",
messageSends: ["ifNil:", "next:", "on:", "model", "codeWidget", "yourself"],
referencedClasses: ["HLStackListWidget"]
}),
globals.HLDebugger);
smalltalk.addMethod(
smalltalk.method({
selector: "unregister",
protocol: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
($ctx1.supercall = true, globals.HLDebugger.superclass.fn.prototype._unregister.apply(_st(self), []));
$ctx1.supercall = false;
$ctx1.sendIdx["unregister"]=1;
_st(self._inspectorWidget())._unregister();
return self}, function($ctx1) {$ctx1.fill(self,"unregister",{},globals.HLDebugger)})},
args: [],
source: "unregister\x0a\x09super unregister.\x0a\x09self inspectorWidget unregister",
messageSends: ["unregister", "inspectorWidget"],
referencedClasses: []
}),
globals.HLDebugger);
smalltalk.addMethod(
smalltalk.method({
selector: "on:",
protocol: 'instance creation',
fn: function (anError){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$3,$1;
$2=self._new();
_st($2)._initializeFromError_(anError);
$3=_st($2)._yourself();
$1=$3;
return $1;
}, function($ctx1) {$ctx1.fill(self,"on:",{anError:anError},globals.HLDebugger.klass)})},
args: ["anError"],
source: "on: anError\x0a\x09^ self new\x0a\x09\x09initializeFromError: anError;\x0a\x09\x09yourself",
messageSends: ["initializeFromError:", "new", "yourself"],
referencedClasses: []
}),
globals.HLDebugger.klass);
smalltalk.addMethod(
smalltalk.method({
selector: "tabClass",
protocol: 'accessing',
fn: function (){
var self=this;
return "debugger";
},
args: [],
source: "tabClass\x0a\x09^ 'debugger'",
messageSends: [],
referencedClasses: []
}),
globals.HLDebugger.klass);
smalltalk.addMethod(
smalltalk.method({
selector: "tabLabel",
protocol: 'accessing',
fn: function (){
var self=this;
return "Debugger";
},
args: [],
source: "tabLabel\x0a\x09^ 'Debugger'",
messageSends: [],
referencedClasses: []
}),
globals.HLDebugger.klass);
smalltalk.addClass('HLDebuggerCodeModel', globals.HLCodeModel, ['debuggerModel'], 'Helios-Debugger');
smalltalk.addMethod(
smalltalk.method({
selector: "debuggerModel",
protocol: 'accessing',
fn: function (){
var self=this;
var $1;
$1=self["@debuggerModel"];
return $1;
},
args: [],
source: "debuggerModel\x0a\x09^ debuggerModel",
messageSends: [],
referencedClasses: []
}),
globals.HLDebuggerCodeModel);
smalltalk.addMethod(
smalltalk.method({
selector: "debuggerModel:",
protocol: 'accessing',
fn: function (anObject){
var self=this;
self["@debuggerModel"]=anObject;
return self},
args: ["anObject"],
source: "debuggerModel: anObject\x0a\x09debuggerModel := anObject",
messageSends: [],
referencedClasses: []
}),
globals.HLDebuggerCodeModel);
smalltalk.addMethod(
smalltalk.method({
selector: "doIt:",
protocol: 'actions',
fn: function (aString){
var self=this;
function $ErrorHandler(){return globals.ErrorHandler||(typeof ErrorHandler=="undefined"?nil:ErrorHandler)}
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st((function(){
return smalltalk.withContext(function($ctx2) {
return _st(self._debuggerModel())._evaluate_(aString);
}, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})}))._tryCatch_((function(e){
return smalltalk.withContext(function($ctx2) {
_st($ErrorHandler())._handleError_(e);
return nil;
}, function($ctx2) {$ctx2.fillBlock({e:e},$ctx1,2)})}));
return $1;
}, function($ctx1) {$ctx1.fill(self,"doIt:",{aString:aString},globals.HLDebuggerCodeModel)})},
args: ["aString"],
source: "doIt: aString\x0a\x09^ [ self debuggerModel evaluate: aString ]\x0a\x09\x09tryCatch: [ :e | \x0a\x09\x09\x09ErrorHandler handleError: e.\x0a\x09\x09\x09nil ]",
messageSends: ["tryCatch:", "evaluate:", "debuggerModel", "handleError:"],
referencedClasses: ["ErrorHandler"]
}),
globals.HLDebuggerCodeModel);
smalltalk.addClass('HLDebuggerCodeWidget', globals.HLBrowserCodeWidget, [], 'Helios-Debugger');
smalltalk.addMethod(
smalltalk.method({
selector: "addStopAt:",
protocol: 'actions',
fn: function (anInteger){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self["@editor"])._setGutterMarker_gutter_value_(anInteger,"stops",_st(_st("<div class=\x22stop\x22></stop>"._asJQuery())._toArray())._first());
return self}, function($ctx1) {$ctx1.fill(self,"addStopAt:",{anInteger:anInteger},globals.HLDebuggerCodeWidget)})},
args: ["anInteger"],
source: "addStopAt: anInteger\x0a\x09editor\x0a\x09\x09setGutterMarker: anInteger\x0a\x09\x09gutter: 'stops'\x0a\x09\x09value: '<div class=\x22stop\x22></stop>' asJQuery toArray first",
messageSends: ["setGutterMarker:gutter:value:", "first", "toArray", "asJQuery"],
referencedClasses: []
}),
globals.HLDebuggerCodeWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "clearHighlight",
protocol: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self._editor())._clearGutter_("stops");
return self}, function($ctx1) {$ctx1.fill(self,"clearHighlight",{},globals.HLDebuggerCodeWidget)})},
args: [],
source: "clearHighlight\x0a\x09self editor clearGutter: 'stops'",
messageSends: ["clearGutter:", "editor"],
referencedClasses: []
}),
globals.HLDebuggerCodeWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "contents:",
protocol: 'accessing',
fn: function (aString){
var self=this;
return smalltalk.withContext(function($ctx1) {
self._clearHighlight();
($ctx1.supercall = true, globals.HLDebuggerCodeWidget.superclass.fn.prototype._contents_.apply(_st(self), [aString]));
$ctx1.supercall = false;
return self}, function($ctx1) {$ctx1.fill(self,"contents:",{aString:aString},globals.HLDebuggerCodeWidget)})},
args: ["aString"],
source: "contents: aString\x0a\x09self clearHighlight.\x0a\x09super contents: aString",
messageSends: ["clearHighlight", "contents:"],
referencedClasses: []
}),
globals.HLDebuggerCodeWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "editorOptions",
protocol: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$3,$1;
$2=($ctx1.supercall = true, globals.HLDebuggerCodeWidget.superclass.fn.prototype._editorOptions.apply(_st(self), []));
$ctx1.supercall = false;
_st($2)._at_put_("gutters",["CodeMirror-linenumbers", "stops"]);
$3=_st($2)._yourself();
$1=$3;
return $1;
}, function($ctx1) {$ctx1.fill(self,"editorOptions",{},globals.HLDebuggerCodeWidget)})},
args: [],
source: "editorOptions\x0a\x09^ super editorOptions\x0a\x09\x09at: 'gutters' put: #('CodeMirror-linenumbers' 'stops');\x0a\x09\x09yourself",
messageSends: ["at:put:", "editorOptions", "yourself"],
referencedClasses: []
}),
globals.HLDebuggerCodeWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "highlight",
protocol: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1,$receiver;
$1=_st(self._browserModel())._nextNode();
if(($receiver = $1) == null || $receiver.isNil){
$1;
} else {
var node;
node=$receiver;
self._highlightNode_(node);
};
return self}, function($ctx1) {$ctx1.fill(self,"highlight",{},globals.HLDebuggerCodeWidget)})},
args: [],
source: "highlight\x0a\x09self browserModel nextNode ifNotNil: [ :node |\x0a\x09\x09self highlightNode: node ]",
messageSends: ["ifNotNil:", "nextNode", "browserModel", "highlightNode:"],
referencedClasses: []
}),
globals.HLDebuggerCodeWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "highlightNode:",
protocol: 'actions',
fn: function (aNode){
var self=this;
var token;
return smalltalk.withContext(function($ctx1) {
var $4,$3,$2,$1,$5,$9,$8,$7,$11,$10,$6,$15,$14,$13,$12,$receiver;
if(($receiver = aNode) == null || $receiver.isNil){
aNode;
} else {
self._clearHighlight();
$4=_st(aNode)._positionStart();
$ctx1.sendIdx["positionStart"]=1;
$3=_st($4)._x();
$ctx1.sendIdx["x"]=1;
$2=_st($3).__minus((1));
$ctx1.sendIdx["-"]=1;
$1=self._addStopAt_($2);
$1;
$5=self._editor();
$9=_st(aNode)._positionStart();
$ctx1.sendIdx["positionStart"]=2;
$8=_st($9)._x();
$ctx1.sendIdx["x"]=2;
$7=_st($8).__minus((1));
$ctx1.sendIdx["-"]=2;
$11=_st(_st(aNode)._positionStart())._y();
$ctx1.sendIdx["y"]=1;
$10=_st($11).__minus((1));
$ctx1.sendIdx["-"]=3;
$6=globals.HashedCollection._newFromPairs_(["line",$7,"ch",$10]);
$15=_st(aNode)._positionEnd();
$ctx1.sendIdx["positionEnd"]=1;
$14=_st($15)._x();
$13=_st($14).__minus((1));
$12=globals.HashedCollection._newFromPairs_(["line",$13,"ch",_st(_st(aNode)._positionEnd())._y()]);
_st($5)._setSelection_to_($6,$12);
};
return self}, function($ctx1) {$ctx1.fill(self,"highlightNode:",{aNode:aNode,token:token},globals.HLDebuggerCodeWidget)})},
args: ["aNode"],
source: "highlightNode: aNode\x0a\x09| token |\x0a\x09\x0a\x09aNode ifNotNil: [\x0a\x09\x09self\x0a\x09\x09\x09clearHighlight;\x0a\x09\x09\x09addStopAt: aNode positionStart x - 1.\x0a\x0a\x09\x09self editor \x0a\x09\x09\x09setSelection: #{ 'line' -> (aNode positionStart x - 1). 'ch' -> (aNode positionStart y - 1) }\x0a\x09\x09\x09to: #{ 'line' -> (aNode positionEnd x - 1). 'ch' -> (aNode positionEnd y) } ]",
messageSends: ["ifNotNil:", "clearHighlight", "addStopAt:", "-", "x", "positionStart", "setSelection:to:", "editor", "y", "positionEnd"],
referencedClasses: []
}),
globals.HLDebuggerCodeWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "observeBrowserModel",
protocol: 'actions',
fn: function (){
var self=this;
function $HLDebuggerContextSelected(){return globals.HLDebuggerContextSelected||(typeof HLDebuggerContextSelected=="undefined"?nil:HLDebuggerContextSelected)}
function $HLDebuggerStepped(){return globals.HLDebuggerStepped||(typeof HLDebuggerStepped=="undefined"?nil:HLDebuggerStepped)}
function $HLDebuggerWhere(){return globals.HLDebuggerWhere||(typeof HLDebuggerWhere=="undefined"?nil:HLDebuggerWhere)}
return smalltalk.withContext(function($ctx1) {
var $2,$1,$4,$3;
($ctx1.supercall = true, globals.HLDebuggerCodeWidget.superclass.fn.prototype._observeBrowserModel.apply(_st(self), []));
$ctx1.supercall = false;
$2=self._browserModel();
$ctx1.sendIdx["browserModel"]=1;
$1=_st($2)._announcer();
$ctx1.sendIdx["announcer"]=1;
_st($1)._on_send_to_($HLDebuggerContextSelected(),"onContextSelected",self);
$ctx1.sendIdx["on:send:to:"]=1;
$4=self._browserModel();
$ctx1.sendIdx["browserModel"]=2;
$3=_st($4)._announcer();
$ctx1.sendIdx["announcer"]=2;
_st($3)._on_send_to_($HLDebuggerStepped(),"onContextSelected",self);
$ctx1.sendIdx["on:send:to:"]=2;
_st(_st(self._browserModel())._announcer())._on_send_to_($HLDebuggerWhere(),"onContextSelected",self);
return self}, function($ctx1) {$ctx1.fill(self,"observeBrowserModel",{},globals.HLDebuggerCodeWidget)})},
args: [],
source: "observeBrowserModel\x0a\x09super observeBrowserModel.\x0a\x09\x0a\x09self browserModel announcer \x0a\x09\x09on: HLDebuggerContextSelected\x0a\x09\x09send: #onContextSelected\x0a\x09\x09to: self.\x0a\x09\x0a\x09self browserModel announcer \x0a\x09\x09on: HLDebuggerStepped\x0a\x09\x09send: #onContextSelected\x0a\x09\x09to: self.\x0a\x09\x0a\x09self browserModel announcer \x0a\x09\x09on: HLDebuggerWhere\x0a\x09\x09send: #onContextSelected\x0a\x09\x09to: self",
messageSends: ["observeBrowserModel", "on:send:to:", "announcer", "browserModel"],
referencedClasses: ["HLDebuggerContextSelected", "HLDebuggerStepped", "HLDebuggerWhere"]
}),
globals.HLDebuggerCodeWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "onContextSelected",
protocol: 'reactions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
self._highlight();
return self}, function($ctx1) {$ctx1.fill(self,"onContextSelected",{},globals.HLDebuggerCodeWidget)})},
args: [],
source: "onContextSelected\x0a\x09self highlight",
messageSends: ["highlight"],
referencedClasses: []
}),
globals.HLDebuggerCodeWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "renderOn:",
protocol: 'rendering',
fn: function (html){
var self=this;
return smalltalk.withContext(function($ctx1) {
($ctx1.supercall = true, globals.HLDebuggerCodeWidget.superclass.fn.prototype._renderOn_.apply(_st(self), [html]));
$ctx1.supercall = false;
self._contents_(_st(_st(self._browserModel())._selectedMethod())._source());
return self}, function($ctx1) {$ctx1.fill(self,"renderOn:",{html:html},globals.HLDebuggerCodeWidget)})},
args: ["html"],
source: "renderOn: html\x0a\x09super renderOn: html.\x0a\x09self contents: self browserModel selectedMethod source",
messageSends: ["renderOn:", "contents:", "source", "selectedMethod", "browserModel"],
referencedClasses: []
}),
globals.HLDebuggerCodeWidget);
smalltalk.addClass('HLDebuggerModel', globals.HLToolModel, ['rootContext', 'debugger', 'error'], 'Helios-Debugger');
globals.HLDebuggerModel.comment="I am a model for debugging Amber code in Helios.\x0a\x0aMy instances hold a reference to an `ASTDebugger` instance, itself referencing the current `context`. The context should be the root of the context stack.";
smalltalk.addMethod(
smalltalk.method({
selector: "atEnd",
protocol: 'testing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._debugger())._atEnd();
return $1;
}, function($ctx1) {$ctx1.fill(self,"atEnd",{},globals.HLDebuggerModel)})},
args: [],
source: "atEnd\x0a\x09^ self debugger atEnd",
messageSends: ["atEnd", "debugger"],
referencedClasses: []
}),
globals.HLDebuggerModel);
smalltalk.addMethod(
smalltalk.method({
selector: "contexts",
protocol: 'accessing',
fn: function (){
var self=this;
var contexts,context;
function $OrderedCollection(){return globals.OrderedCollection||(typeof OrderedCollection=="undefined"?nil:OrderedCollection)}
return smalltalk.withContext(function($ctx1) {
var $1;
contexts=_st($OrderedCollection())._new();
context=self._rootContext();
_st((function(){
return smalltalk.withContext(function($ctx2) {
return _st(context)._notNil();
}, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})}))._whileTrue_((function(){
return smalltalk.withContext(function($ctx2) {
_st(contexts)._add_(context);
context=_st(context)._outerContext();
return context;
}, function($ctx2) {$ctx2.fillBlock({},$ctx1,2)})}));
$1=contexts;
return $1;
}, function($ctx1) {$ctx1.fill(self,"contexts",{contexts:contexts,context:context},globals.HLDebuggerModel)})},
args: [],
source: "contexts\x0a\x09| contexts context |\x0a\x09\x0a\x09contexts := OrderedCollection new.\x0a\x09context := self rootContext.\x0a\x09\x0a\x09[ context notNil ] whileTrue: [\x0a\x09\x09contexts add: context.\x0a\x09\x09context := context outerContext ].\x0a\x09\x09\x0a\x09^ contexts",
messageSends: ["new", "rootContext", "whileTrue:", "notNil", "add:", "outerContext"],
referencedClasses: ["OrderedCollection"]
}),
globals.HLDebuggerModel);
smalltalk.addMethod(
smalltalk.method({
selector: "currentContext",
protocol: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._debugger())._context();
return $1;
}, function($ctx1) {$ctx1.fill(self,"currentContext",{},globals.HLDebuggerModel)})},
args: [],
source: "currentContext\x0a\x09^ self debugger context",
messageSends: ["context", "debugger"],
referencedClasses: []
}),
globals.HLDebuggerModel);
smalltalk.addMethod(
smalltalk.method({
selector: "currentContext:",
protocol: 'accessing',
fn: function (aContext){
var self=this;
function $HLDebuggerContextSelected(){return globals.HLDebuggerContextSelected||(typeof HLDebuggerContextSelected=="undefined"?nil:HLDebuggerContextSelected)}
return smalltalk.withContext(function($ctx1) {
var $1,$2;
self._withChangesDo_((function(){
return smalltalk.withContext(function($ctx2) {
self._selectedMethod_(_st(aContext)._method());
_st(self._debugger())._context_(aContext);
$ctx2.sendIdx["context:"]=1;
$1=_st($HLDebuggerContextSelected())._new();
_st($1)._context_(aContext);
$2=_st($1)._yourself();
return _st(self._announcer())._announce_($2);
}, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})}));
return self}, function($ctx1) {$ctx1.fill(self,"currentContext:",{aContext:aContext},globals.HLDebuggerModel)})},
args: ["aContext"],
source: "currentContext: aContext\x0a\x09self withChangesDo: [ \x0a\x09\x09self selectedMethod: aContext method.\x0a\x09\x09self debugger context: aContext.\x0a\x09\x09self announcer announce: (HLDebuggerContextSelected new\x0a\x09\x09\x09context: aContext;\x0a\x09\x09\x09yourself) ]",
messageSends: ["withChangesDo:", "selectedMethod:", "method", "context:", "debugger", "announce:", "announcer", "new", "yourself"],
referencedClasses: ["HLDebuggerContextSelected"]
}),
globals.HLDebuggerModel);
smalltalk.addMethod(
smalltalk.method({
selector: "debugger",
protocol: 'accessing',
fn: function (){
var self=this;
function $ASTDebugger(){return globals.ASTDebugger||(typeof ASTDebugger=="undefined"?nil:ASTDebugger)}
return smalltalk.withContext(function($ctx1) {
var $2,$1,$receiver;
$2=self["@debugger"];
if(($receiver = $2) == null || $receiver.isNil){
self["@debugger"]=_st($ASTDebugger())._new();
$1=self["@debugger"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"debugger",{},globals.HLDebuggerModel)})},
args: [],
source: "debugger\x0a\x09^ debugger ifNil: [ debugger := ASTDebugger new ]",
messageSends: ["ifNil:", "new"],
referencedClasses: ["ASTDebugger"]
}),
globals.HLDebuggerModel);
smalltalk.addMethod(
smalltalk.method({
selector: "error",
protocol: 'accessing',
fn: function (){
var self=this;
var $1;
$1=self["@error"];
return $1;
},
args: [],
source: "error\x0a\x09^ error",
messageSends: [],
referencedClasses: []
}),
globals.HLDebuggerModel);
smalltalk.addMethod(
smalltalk.method({
selector: "evaluate:",
protocol: 'evaluating',
fn: function (aString){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._environment())._evaluate_for_(aString,self._currentContext());
return $1;
}, function($ctx1) {$ctx1.fill(self,"evaluate:",{aString:aString},globals.HLDebuggerModel)})},
args: ["aString"],
source: "evaluate: aString\x0a\x09^ self environment \x0a\x09\x09evaluate: aString \x0a\x09\x09for: self currentContext",
messageSends: ["evaluate:for:", "environment", "currentContext"],
referencedClasses: []
}),
globals.HLDebuggerModel);
smalltalk.addMethod(
smalltalk.method({
selector: "flushInnerContexts",
protocol: 'private',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self._currentContext();
$ctx1.sendIdx["currentContext"]=1;
_st($1)._innerContext_(nil);
self["@rootContext"]=self._currentContext();
self._initializeContexts();
return self}, function($ctx1) {$ctx1.fill(self,"flushInnerContexts",{},globals.HLDebuggerModel)})},
args: [],
source: "flushInnerContexts\x0a\x09\x22When stepping, the inner contexts are not relevent anymore,\x0a\x09and can be flushed\x22\x0a\x09\x0a\x09self currentContext innerContext: nil.\x0a\x09rootContext := self currentContext.\x0a\x09self initializeContexts",
messageSends: ["innerContext:", "currentContext", "initializeContexts"],
referencedClasses: []
}),
globals.HLDebuggerModel);
smalltalk.addMethod(
smalltalk.method({
selector: "initializeFromError:",
protocol: 'initialization',
fn: function (anError){
var self=this;
var errorContext;
function $AIContext(){return globals.AIContext||(typeof AIContext=="undefined"?nil:AIContext)}
return smalltalk.withContext(function($ctx1) {
self["@error"]=anError;
errorContext=_st($AIContext())._fromMethodContext_(_st(self["@error"])._context());
self["@rootContext"]=_st(self["@error"])._signalerContextFrom_(errorContext);
self._selectedMethod_(_st(self["@rootContext"])._method());
return self}, function($ctx1) {$ctx1.fill(self,"initializeFromError:",{anError:anError,errorContext:errorContext},globals.HLDebuggerModel)})},
args: ["anError"],
source: "initializeFromError: anError\x0a\x09| errorContext |\x0a\x09\x0a\x09error := anError.\x0a\x09errorContext := (AIContext fromMethodContext: error context).\x0a\x09rootContext := error signalerContextFrom: errorContext.\x0a\x09self selectedMethod: rootContext method",
messageSends: ["fromMethodContext:", "context", "signalerContextFrom:", "selectedMethod:", "method"],
referencedClasses: ["AIContext"]
}),
globals.HLDebuggerModel);
smalltalk.addMethod(
smalltalk.method({
selector: "nextNode",
protocol: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._debugger())._node();
return $1;
}, function($ctx1) {$ctx1.fill(self,"nextNode",{},globals.HLDebuggerModel)})},
args: [],
source: "nextNode\x0a\x09^ self debugger node",
messageSends: ["node", "debugger"],
referencedClasses: []
}),
globals.HLDebuggerModel);
smalltalk.addMethod(
smalltalk.method({
selector: "onStep",
protocol: 'reactions',
fn: function (){
var self=this;
function $HLDebuggerContextSelected(){return globals.HLDebuggerContextSelected||(typeof HLDebuggerContextSelected=="undefined"?nil:HLDebuggerContextSelected)}
return smalltalk.withContext(function($ctx1) {
var $2,$1,$3,$4;
self["@rootContext"]=self._currentContext();
$ctx1.sendIdx["currentContext"]=1;
$2=self._currentContext();
$ctx1.sendIdx["currentContext"]=2;
$1=_st($2)._method();
self._selectedMethod_($1);
$3=_st($HLDebuggerContextSelected())._new();
_st($3)._context_(self._currentContext());
$4=_st($3)._yourself();
_st(self._announcer())._announce_($4);
return self}, function($ctx1) {$ctx1.fill(self,"onStep",{},globals.HLDebuggerModel)})},
args: [],
source: "onStep\x0a\x09rootContext := self currentContext.\x0a\x09\x0a\x09\x22Force a refresh of the context list and code widget\x22\x0a\x09self selectedMethod: self currentContext method.\x0a\x09self announcer announce: (HLDebuggerContextSelected new\x0a\x09\x09context: self currentContext;\x0a\x09\x09yourself)",
messageSends: ["currentContext", "selectedMethod:", "method", "announce:", "announcer", "context:", "new", "yourself"],
referencedClasses: ["HLDebuggerContextSelected"]
}),
globals.HLDebuggerModel);
smalltalk.addMethod(
smalltalk.method({
selector: "proceed",
protocol: 'actions',
fn: function (){
var self=this;
function $HLDebuggerProceeded(){return globals.HLDebuggerProceeded||(typeof HLDebuggerProceeded=="undefined"?nil:HLDebuggerProceeded)}
return smalltalk.withContext(function($ctx1) {
_st(self._debugger())._proceed();
_st(self._announcer())._announce_(_st($HLDebuggerProceeded())._new());
return self}, function($ctx1) {$ctx1.fill(self,"proceed",{},globals.HLDebuggerModel)})},
args: [],
source: "proceed\x0a\x09self debugger proceed.\x0a\x09\x0a\x09self announcer announce: HLDebuggerProceeded new",
messageSends: ["proceed", "debugger", "announce:", "announcer", "new"],
referencedClasses: ["HLDebuggerProceeded"]
}),
globals.HLDebuggerModel);
smalltalk.addMethod(
smalltalk.method({
selector: "restart",
protocol: 'actions',
fn: function (){
var self=this;
function $HLDebuggerStepped(){return globals.HLDebuggerStepped||(typeof HLDebuggerStepped=="undefined"?nil:HLDebuggerStepped)}
return smalltalk.withContext(function($ctx1) {
var $1,$2;
_st(self._debugger())._restart();
self._onStep();
$1=_st($HLDebuggerStepped())._new();
_st($1)._context_(self._currentContext());
$2=_st($1)._yourself();
_st(self._announcer())._announce_($2);
return self}, function($ctx1) {$ctx1.fill(self,"restart",{},globals.HLDebuggerModel)})},
args: [],
source: "restart\x0a\x09self debugger restart.\x0a\x09self onStep.\x0a\x09\x0a\x09self announcer announce: (HLDebuggerStepped new\x0a\x09\x09context: self currentContext;\x0a\x09\x09yourself)",
messageSends: ["restart", "debugger", "onStep", "announce:", "announcer", "context:", "new", "currentContext", "yourself"],
referencedClasses: ["HLDebuggerStepped"]
}),
globals.HLDebuggerModel);
smalltalk.addMethod(
smalltalk.method({
selector: "rootContext",
protocol: 'accessing',
fn: function (){
var self=this;
var $1;
$1=self["@rootContext"];
return $1;
},
args: [],
source: "rootContext\x0a\x09^ rootContext",
messageSends: [],
referencedClasses: []
}),
globals.HLDebuggerModel);
smalltalk.addMethod(
smalltalk.method({
selector: "stepOver",
protocol: 'actions',
fn: function (){
var self=this;
function $HLDebuggerStepped(){return globals.HLDebuggerStepped||(typeof HLDebuggerStepped=="undefined"?nil:HLDebuggerStepped)}
return smalltalk.withContext(function($ctx1) {
var $1,$2;
_st(self._debugger())._stepOver();
self._onStep();
$1=_st($HLDebuggerStepped())._new();
_st($1)._context_(self._currentContext());
$2=_st($1)._yourself();
_st(self._announcer())._announce_($2);
return self}, function($ctx1) {$ctx1.fill(self,"stepOver",{},globals.HLDebuggerModel)})},
args: [],
source: "stepOver\x0a\x09self debugger stepOver.\x0a\x09self onStep.\x0a\x09\x0a\x09self announcer announce: (HLDebuggerStepped new\x0a\x09\x09context: self currentContext;\x0a\x09\x09yourself)",
messageSends: ["stepOver", "debugger", "onStep", "announce:", "announcer", "context:", "new", "currentContext", "yourself"],
referencedClasses: ["HLDebuggerStepped"]
}),
globals.HLDebuggerModel);
smalltalk.addMethod(
smalltalk.method({
selector: "where",
protocol: 'actions',
fn: function (){
var self=this;
function $HLDebuggerWhere(){return globals.HLDebuggerWhere||(typeof HLDebuggerWhere=="undefined"?nil:HLDebuggerWhere)}
return smalltalk.withContext(function($ctx1) {
_st(self._announcer())._announce_(_st($HLDebuggerWhere())._new());
return self}, function($ctx1) {$ctx1.fill(self,"where",{},globals.HLDebuggerModel)})},
args: [],
source: "where\x0a\x09self announcer announce: HLDebuggerWhere new",
messageSends: ["announce:", "announcer", "new"],
referencedClasses: ["HLDebuggerWhere"]
}),
globals.HLDebuggerModel);
smalltalk.addMethod(
smalltalk.method({
selector: "on:",
protocol: 'instance creation',
fn: function (anError){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$3,$1;
$2=self._new();
_st($2)._initializeFromError_(anError);
$3=_st($2)._yourself();
$1=$3;
return $1;
}, function($ctx1) {$ctx1.fill(self,"on:",{anError:anError},globals.HLDebuggerModel.klass)})},
args: ["anError"],
source: "on: anError\x0a\x09^ self new\x0a\x09\x09initializeFromError: anError;\x0a\x09\x09yourself",
messageSends: ["initializeFromError:", "new", "yourself"],
referencedClasses: []
}),
globals.HLDebuggerModel.klass);
smalltalk.addClass('HLErrorHandler', globals.Object, [], 'Helios-Debugger');
smalltalk.addMethod(
smalltalk.method({
selector: "confirmDebugError:",
protocol: 'error handling',
fn: function (anError){
var self=this;
function $HLConfirmationWidget(){return globals.HLConfirmationWidget||(typeof HLConfirmationWidget=="undefined"?nil:HLConfirmationWidget)}
return smalltalk.withContext(function($ctx1) {
var $1,$2;
$1=_st($HLConfirmationWidget())._new();
_st($1)._confirmationString_(_st(anError)._messageText());
_st($1)._actionBlock_((function(){
return smalltalk.withContext(function($ctx2) {
return self._debugError_(anError);
}, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})}));
_st($1)._cancelButtonLabel_("Abandon");
_st($1)._confirmButtonLabel_("Debug");
$2=_st($1)._show();
return self}, function($ctx1) {$ctx1.fill(self,"confirmDebugError:",{anError:anError},globals.HLErrorHandler)})},
args: ["anError"],
source: "confirmDebugError: anError\x0a\x09HLConfirmationWidget new\x0a\x09\x09confirmationString: anError messageText;\x0a\x09\x09actionBlock: [ self debugError: anError ];\x0a\x09\x09cancelButtonLabel: 'Abandon';\x0a\x09\x09confirmButtonLabel: 'Debug';\x0a\x09\x09show",
messageSends: ["confirmationString:", "new", "messageText", "actionBlock:", "debugError:", "cancelButtonLabel:", "confirmButtonLabel:", "show"],
referencedClasses: ["HLConfirmationWidget"]
}),
globals.HLErrorHandler);
smalltalk.addMethod(
smalltalk.method({
selector: "debugError:",
protocol: 'error handling',
fn: function (anError){
var self=this;
function $HLDebugger(){return globals.HLDebugger||(typeof HLDebugger=="undefined"?nil:HLDebugger)}
function $Error(){return globals.Error||(typeof Error=="undefined"?nil:Error)}
function $ConsoleErrorHandler(){return globals.ConsoleErrorHandler||(typeof ConsoleErrorHandler=="undefined"?nil:ConsoleErrorHandler)}
return smalltalk.withContext(function($ctx1) {
_st((function(){
return smalltalk.withContext(function($ctx2) {
return _st(_st($HLDebugger())._on_(anError))._openAsTab();
}, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})}))._on_do_($Error(),(function(error){
return smalltalk.withContext(function($ctx2) {
return _st(_st($ConsoleErrorHandler())._new())._handleError_(error);
}, function($ctx2) {$ctx2.fillBlock({error:error},$ctx1,2)})}));
return self}, function($ctx1) {$ctx1.fill(self,"debugError:",{anError:anError},globals.HLErrorHandler)})},
args: ["anError"],
source: "debugError: anError\x0a\x0a\x09[ \x0a\x09\x09(HLDebugger on: anError) openAsTab \x0a\x09] \x0a\x09\x09on: Error \x0a\x09\x09do: [ :error | ConsoleErrorHandler new handleError: error ]",
messageSends: ["on:do:", "openAsTab", "on:", "handleError:", "new"],
referencedClasses: ["HLDebugger", "Error", "ConsoleErrorHandler"]
}),
globals.HLErrorHandler);
smalltalk.addMethod(
smalltalk.method({
selector: "handleError:",
protocol: 'error handling',
fn: function (anError){
var self=this;
return smalltalk.withContext(function($ctx1) {
self._confirmDebugError_(anError);
return self}, function($ctx1) {$ctx1.fill(self,"handleError:",{anError:anError},globals.HLErrorHandler)})},
args: ["anError"],
source: "handleError: anError\x0a\x09self confirmDebugError: anError",
messageSends: ["confirmDebugError:"],
referencedClasses: []
}),
globals.HLErrorHandler);
smalltalk.addMethod(
smalltalk.method({
selector: "onErrorHandled",
protocol: 'error handling',
fn: function (){
var self=this;
function $HLProgressWidget(){return globals.HLProgressWidget||(typeof HLProgressWidget=="undefined"?nil:HLProgressWidget)}
return smalltalk.withContext(function($ctx1) {
var $1,$2;
$1=_st($HLProgressWidget())._default();
_st($1)._flush();
$2=_st($1)._remove();
return self}, function($ctx1) {$ctx1.fill(self,"onErrorHandled",{},globals.HLErrorHandler)})},
args: [],
source: "onErrorHandled\x0a\x09\x22when an error is handled, we need to make sure that\x0a\x09any progress bar widget gets removed. Because HLProgressBarWidget is asynchronous,\x0a\x09it has to be done here.\x22\x0a\x09\x0a\x09HLProgressWidget default \x0a\x09\x09flush; \x0a\x09\x09remove",
messageSends: ["flush", "default", "remove"],
referencedClasses: ["HLProgressWidget"]
}),
globals.HLErrorHandler);
smalltalk.addClass('HLStackListWidget', globals.HLToolListWidget, [], 'Helios-Debugger');
smalltalk.addMethod(
smalltalk.method({
selector: "items",
protocol: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._model())._contexts();
return $1;
}, function($ctx1) {$ctx1.fill(self,"items",{},globals.HLStackListWidget)})},
args: [],
source: "items\x0a\x09^ self model contexts",
messageSends: ["contexts", "model"],
referencedClasses: []
}),
globals.HLStackListWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "label",
protocol: 'accessing',
fn: function (){
var self=this;
return "Call stack";
},
args: [],
source: "label\x0a\x09^ 'Call stack'",
messageSends: [],
referencedClasses: []
}),
globals.HLStackListWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "observeModel",
protocol: 'actions',
fn: function (){
var self=this;
function $HLDebuggerStepped(){return globals.HLDebuggerStepped||(typeof HLDebuggerStepped=="undefined"?nil:HLDebuggerStepped)}
return smalltalk.withContext(function($ctx1) {
($ctx1.supercall = true, globals.HLStackListWidget.superclass.fn.prototype._observeModel.apply(_st(self), []));
$ctx1.supercall = false;
_st(_st(self._model())._announcer())._on_send_to_($HLDebuggerStepped(),"onDebuggerStepped:",self);
return self}, function($ctx1) {$ctx1.fill(self,"observeModel",{},globals.HLStackListWidget)})},
args: [],
source: "observeModel\x0a\x09super observeModel.\x0a\x09\x0a\x09self model announcer \x0a\x09\x09on: HLDebuggerStepped\x0a\x09\x09send: #onDebuggerStepped:\x0a\x09\x09to: self",
messageSends: ["observeModel", "on:send:to:", "announcer", "model"],
referencedClasses: ["HLDebuggerStepped"]
}),
globals.HLStackListWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "onDebuggerStepped:",
protocol: 'reactions',
fn: function (anAnnouncement){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@items"]=nil;
self._refresh();
return self}, function($ctx1) {$ctx1.fill(self,"onDebuggerStepped:",{anAnnouncement:anAnnouncement},globals.HLStackListWidget)})},
args: ["anAnnouncement"],
source: "onDebuggerStepped: anAnnouncement\x0a\x09items := nil.\x0a\x09self refresh",
messageSends: ["refresh"],
referencedClasses: []
}),
globals.HLStackListWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "proceed",
protocol: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self._model())._proceed();
return self}, function($ctx1) {$ctx1.fill(self,"proceed",{},globals.HLStackListWidget)})},
args: [],
source: "proceed\x0a\x09self model proceed",
messageSends: ["proceed", "model"],
referencedClasses: []
}),
globals.HLStackListWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "renderButtonsOn:",
protocol: 'rendering',
fn: function (html){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1,$3,$4,$5,$6,$7,$8,$9,$10,$2;
$1=_st(html)._div();
_st($1)._class_("debugger_bar");
$ctx1.sendIdx["class:"]=1;
$2=_st($1)._with_((function(){
return smalltalk.withContext(function($ctx2) {
$3=_st(html)._button();
$ctx2.sendIdx["button"]=1;
_st($3)._class_("btn restart");
$ctx2.sendIdx["class:"]=2;
_st($3)._with_("Restart");
$ctx2.sendIdx["with:"]=2;
$4=_st($3)._onClick_((function(){
return smalltalk.withContext(function($ctx3) {
return self._restart();
}, function($ctx3) {$ctx3.fillBlock({},$ctx2,2)})}));
$ctx2.sendIdx["onClick:"]=1;
$4;
$5=_st(html)._button();
$ctx2.sendIdx["button"]=2;
_st($5)._class_("btn where");
$ctx2.sendIdx["class:"]=3;
_st($5)._with_("Where");
$ctx2.sendIdx["with:"]=3;
$6=_st($5)._onClick_((function(){
return smalltalk.withContext(function($ctx3) {
return self._where();
}, function($ctx3) {$ctx3.fillBlock({},$ctx2,3)})}));
$ctx2.sendIdx["onClick:"]=2;
$6;
$7=_st(html)._button();
$ctx2.sendIdx["button"]=3;
_st($7)._class_("btn stepOver");
$ctx2.sendIdx["class:"]=4;
_st($7)._with_("Step over");
$ctx2.sendIdx["with:"]=4;
$8=_st($7)._onClick_((function(){
return smalltalk.withContext(function($ctx3) {
return self._stepOver();
}, function($ctx3) {$ctx3.fillBlock({},$ctx2,4)})}));
$ctx2.sendIdx["onClick:"]=3;
$8;
$9=_st(html)._button();
_st($9)._class_("btn proceed");
_st($9)._with_("Proceed");
$10=_st($9)._onClick_((function(){
return smalltalk.withContext(function($ctx3) {
return self._proceed();
}, function($ctx3) {$ctx3.fillBlock({},$ctx2,5)})}));
return $10;
}, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})}));
$ctx1.sendIdx["with:"]=1;
return self}, function($ctx1) {$ctx1.fill(self,"renderButtonsOn:",{html:html},globals.HLStackListWidget)})},
args: ["html"],
source: "renderButtonsOn: html\x0a\x09html div \x0a\x09\x09class: 'debugger_bar'; \x0a\x09\x09with: [\x0a\x09\x09\x09html button \x0a\x09\x09\x09\x09class: 'btn restart';\x0a\x09\x09\x09\x09with: 'Restart';\x0a\x09\x09\x09\x09onClick: [ self restart ].\x0a\x09\x09\x09html button \x0a\x09\x09\x09\x09class: 'btn where';\x0a\x09\x09\x09\x09with: 'Where';\x0a\x09\x09\x09\x09onClick: [ self where ].\x0a\x09\x09\x09html button \x0a\x09\x09\x09\x09class: 'btn stepOver';\x0a\x09\x09\x09\x09with: 'Step over';\x0a\x09\x09\x09\x09onClick: [ self stepOver ].\x0a\x09\x09\x09html button \x0a\x09\x09\x09\x09class: 'btn proceed';\x0a\x09\x09\x09\x09with: 'Proceed';\x0a\x09\x09\x09\x09onClick: [ self proceed ] ]",
messageSends: ["class:", "div", "with:", "button", "onClick:", "restart", "where", "stepOver", "proceed"],
referencedClasses: []
}),
globals.HLStackListWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "restart",
protocol: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self._model())._restart();
return self}, function($ctx1) {$ctx1.fill(self,"restart",{},globals.HLStackListWidget)})},
args: [],
source: "restart\x0a\x09self model restart",
messageSends: ["restart", "model"],
referencedClasses: []
}),
globals.HLStackListWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "selectItem:",
protocol: 'actions',
fn: function (aContext){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self._model())._currentContext_(aContext);
($ctx1.supercall = true, globals.HLStackListWidget.superclass.fn.prototype._selectItem_.apply(_st(self), [aContext]));
$ctx1.supercall = false;
return self}, function($ctx1) {$ctx1.fill(self,"selectItem:",{aContext:aContext},globals.HLStackListWidget)})},
args: ["aContext"],
source: "selectItem: aContext\x0a \x09self model currentContext: aContext.\x0a\x09super selectItem: aContext",
messageSends: ["currentContext:", "model", "selectItem:"],
referencedClasses: []
}),
globals.HLStackListWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "selectedItem",
protocol: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._model())._currentContext();
return $1;
}, function($ctx1) {$ctx1.fill(self,"selectedItem",{},globals.HLStackListWidget)})},
args: [],
source: "selectedItem\x0a \x09^ self model currentContext",
messageSends: ["currentContext", "model"],
referencedClasses: []
}),
globals.HLStackListWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "stepOver",
protocol: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self._model())._stepOver();
return self}, function($ctx1) {$ctx1.fill(self,"stepOver",{},globals.HLStackListWidget)})},
args: [],
source: "stepOver\x0a\x09self model stepOver",
messageSends: ["stepOver", "model"],
referencedClasses: []
}),
globals.HLStackListWidget);
smalltalk.addMethod(
smalltalk.method({
selector: "where",
protocol: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self._model())._where();
return self}, function($ctx1) {$ctx1.fill(self,"where",{},globals.HLStackListWidget)})},
args: [],
source: "where\x0a\x09self model where",
messageSends: ["where", "model"],
referencedClasses: []
}),
globals.HLStackListWidget);
});
|
/**
* Error for services to through when they encounter a problem with the request.
* Distinguishes between a bad service request and a general error
*/
function ServiceError(message) {
this.name = "ServiceError";
this.message = (message || "");
}
ServiceError.prototype = Object.create(Error.prototype, {
constructor: {value: ServiceError}
});
/**
* Error for when an item is not found
*/
function NotFoundError(message) {
this.name = "NotFoundError";
this.message = (message || "Not found");
}
NotFoundError.prototype = Object.create(ServiceError.prototype, {
constructor: { value: NotFoundError}
});
exports.ServiceError = ServiceError;
exports.NotFoundError = NotFoundError; |
import shaven from 'shaven'
const svgNS = 'http://www.w3.org/2000/svg'
export default function (svg, config) {
const yDensity = 0.1
const yRange = config.max.value - config.min.value
const graphHeight = config.height * 0.8
const graphWidth = config.width * 0.95
const coSysHeight = config.height * 0.6
const coSysWidth = config.width * 0.85
const barchart = shaven(
['g', {
transform: 'translate(' +
[graphWidth * 0.1, graphHeight].join() +
')',
}], svgNS,
)[0]
const coordinateSystem = shaven(['g'], svgNS)[0]
const bars = shaven(['g'], svgNS)[0]
function buildCoordinateSystem () {
function ordinates () {
let cssClass
let index
for (index = 0; index < config.size; index++) {
cssClass = index === 0
? 'vectual_coordinate_axis_y'
: 'vectual_coordinate_lines_y'
shaven(
[coordinateSystem,
['line', {
class: cssClass,
x1: (coSysWidth / config.size) * index,
y1: '5',
x2: (coSysWidth / config.size) * index,
y2: -coSysHeight,
}],
['text', config.keys[index], {
class: 'vectual_coordinate_labels_x',
transform: 'rotate(40 ' +
((coSysWidth / config.size) * index) +
', 10)',
// eslint-disable-next-line id-length
x: (coSysWidth / config.size) * index,
y: 10, // eslint-disable-line id-length
}],
], svgNS,
)
}
}
function abscissas () {
let styleClass
let index
for (index = 0; index <= (yRange * yDensity); index++) {
styleClass = index === 0
? 'vectual_coordinate_axis_x'
: 'vectual_coordinate_lines_x'
shaven(
[coordinateSystem,
['line', {
class: styleClass,
x1: -5,
y1: -(coSysHeight / yRange) * (index / yDensity),
x2: coSysWidth,
y2: -(coSysHeight / yRange) * (index / yDensity),
}],
['text', String(index / yDensity + config.min.value), {
class: 'vectual_coordinate_labels_y',
x: -coSysWidth * 0.05, // eslint-disable-line id-length
// eslint-disable-next-line id-length
y: -(coSysHeight / yRange) * (index / yDensity),
}],
], svgNS,
)
}
}
abscissas()
ordinates()
}
function buildBars () {
function drawBar (element, index) {
const height = config.animations
? 0
: (config.values[index] - config.min.value) * (coSysHeight / yRange)
const bar = shaven(
['rect',
{
class: 'vectual_bar_bar',
// eslint-disable-next-line id-length
x: index * (coSysWidth / config.size),
// eslint-disable-next-line id-length
y: -(config.values[index] - config.min.value) *
(coSysHeight / yRange),
height: height,
width: 0.7 * (coSysWidth / config.size),
},
['title', config.keys[index] + ': ' + config.values[index]],
],
svgNS,
)[0]
function localSetAnimations () {
shaven(
[bar,
['animate', {
attributeName: 'height',
to: (config.values[index] - config.min.value) *
(coSysHeight / yRange),
begin: '0s',
dur: '1s',
fill: 'freeze',
}],
['animate', {
attributeName: 'y',
from: 0,
to: -(config.values[index] - config.min.value) *
(coSysHeight / yRange),
begin: '0s',
dur: '1s',
fill: 'freeze',
}],
['animate', {
attributeName: 'fill',
to: 'rgb(100,210,255)',
begin: 'mouseover',
dur: '100ms',
fill: 'freeze',
additive: 'replace',
}],
['animate', {
attributeName: 'fill',
to: 'rgb(0,150,250)',
begin: 'mouseout',
dur: '200ms',
fill: 'freeze',
additive: 'replace',
}],
], svgNS,
)
}
function localInject () {
shaven([bars, [bar]])
}
if (config.animations) localSetAnimations()
localInject()
}
config.data.forEach(drawBar)
}
function setAnimations () {
shaven(
[bars,
['animate', {
attributeName: 'opacity',
from: 0,
to: 0.8,
begin: '0s',
dur: '1s',
fill: 'freeze',
additive: 'replace',
}],
],
svgNS,
)
}
function inject () {
shaven(
[svg,
[barchart,
[coordinateSystem],
[bars],
],
],
)
}
buildCoordinateSystem()
buildBars()
if (config.animations) setAnimations()
inject()
return svg
}
|
import Ember from "ember";
export default Ember.Route.extend({
model: function() {
return this.store.query('answer', {correct: true});
}
});
|
//This file is automatically rebuilt by the Cesium build process.
/*global define*/
define(function() {
'use strict';
return "/**\n\
* Converts an RGB color to HSB (hue, saturation, brightness)\n\
* HSB <-> RGB conversion with minimal branching: {@link http://lolengine.net/blog/2013/07/27/rgb-to-hsv-in-glsl}\n\
*\n\
* @name czm_RGBToHSB\n\
* @glslFunction\n\
* \n\
* @param {vec3} rgb The color in RGB.\n\
*\n\
* @returns {vec3} The color in HSB.\n\
*\n\
* @example\n\
* vec3 hsb = czm_RGBToHSB(rgb);\n\
* hsb.z *= 0.1;\n\
* rgb = czm_HSBToRGB(hsb);\n\
*/\n\
\n\
const vec4 K_RGB2HSB = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);\n\
\n\
vec3 czm_RGBToHSB(vec3 rgb)\n\
{\n\
vec4 p = mix(vec4(rgb.bg, K_RGB2HSB.wz), vec4(rgb.gb, K_RGB2HSB.xy), step(rgb.b, rgb.g));\n\
vec4 q = mix(vec4(p.xyw, rgb.r), vec4(rgb.r, p.yzx), step(p.x, rgb.r));\n\
\n\
float d = q.x - min(q.w, q.y);\n\
return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + czm_epsilon7)), d / (q.x + czm_epsilon7), q.x);\n\
}\n\
";
}); |
/**
* Demo App for TopcoatTouch
*/
$(document).ready(function() {
<% if (kitchenSink) {
if (mvc) { %>
// Create the topcoatTouch object
var tt = new TopcoatTouch({menu: [{id: 'help', name: 'Help'}, {id: 'info', name: 'Info'}, {id: 'about', name: 'About'}]});
tt.on(tt.EVENTS.MENU_ITEM_CLICKED, function(page, id) {
if (id == 'help') {
tt.goTo('help', 'slidedown', true);
} else if (id == 'about') {
tt.goTo('about', 'pop', true);
}
});
tt.createController('home');
tt.createController('about').addEvent('click', 'button', function() {
tt.goBack();
});
tt.createController('info').addEvent('click', 'button', function() {
tt.goBack();
});
tt.createController('help').addEvent('click', 'button', function() {
tt.goBack();
});
tt.createController('buttonExample', {
postrender: function($page) {
// Show a message when anyone clicks on button of the test form...
$page.find('.testForm').submit(function() {
tt.showDialog('<h3>Button Clicked</h3>');
return false;
});
}
});
tt.createController('carouselExample', {
postadd: function() {
// When the page is loaded, run the following...
// Setup iScroll..
this.carouselScroll = new IScroll('#carouselWrapper', {
scrollX: true,
scrollY: false,
momentum: false,
snap: true,
snapSpeed: 400,
keyBindings: true,
indicators: {
el: document.getElementById('carouselIndicator'),
resize: false
}
});
},
pageend: function() {
if (this.carouselScroll != null) {
this.carouselScroll.destroy();
this.carouselScroll = null;
}
}
});
tt.createController('checkRadioExample');
tt.createController('formExample');
tt.createController('galleryExample', {
postrender: function($page) {
$page.find('#changeButton').click(function() {
createPlaceHolder($page, $('#gallery-picker').data('value'));
});
createPlaceHolder($page, 'kittens');
}
});
tt.createController('waitingDialogExample', {
postadd: function() {
// Show the loading message...
$(document).on('click', '#showLoading', function() {
tt.showLoading('10 seconds');
var count = 10;
var interval = setInterval(function() {
if (--count <= 0) {
clearInterval(interval);
tt.hideLoading();
} else {
$('#topcoat-loading-message').text(count + ' seconds');
}
},1000);
});
// Show the dialog...
$(document).on('click', '#showDialog', function() {
tt.showDialog('This is a dialog', 'Example Dialog', {OK: function() { console.log('OK Pressed') }
, Cancel: function() { console.log('Cancel Pressed')}});
});
}
});
// First page we go to home... This could be done in code by setting the class to 'page page-center', but here is how to do it in code...
tt.goTo('home');
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
// Create the placeholders in the gallery...
function createPlaceHolder($page, type) {
var placeHolders = { kittens : 'placekitten.com', bears: 'placebear.com', lorem: 'lorempixel.com',
bacon: 'baconmockup.com', murray: 'www.fillmurray.com'};
var gallery = '';
for (var i = 0; i < getRandomInt(50,100); i++) {
gallery += '<li class="photoClass" style="background:url(http://' + placeHolders[type] + '/' +
getRandomInt(200,300) + '/' + getRandomInt(200,300) + ') 50% 50% no-repeat"></li>';
}
$page.find('.photo-gallery').html(gallery);
tt.refreshScroll(); // Refresh the scroller
tt.scrollTo(0,0); // Move back to the top of the page...
}
<%
// End If MVC KitchenSink
} else {
// Start SingleDocument KitchenSink
%>
// Create the topcoatTouch object
var tt = new TopcoatTouch({menu: [{id: 'help', name: 'Help'}, {id: 'info', name: 'Info'}, {id: 'about', name: 'About'}]});
// First page we go to home... This could be done in code by setting the class to 'page page-center', but here is how to do it in code...
tt.goTo('home');
var carouselScroll = null;
tt.on(tt.EVENTS.MENU_ITEM_CLICKED, function(page, id) {
if (id == 'help') {
tt.goTo('help', 'slidedown', true);
} else if (id == 'info') {
tt.goTo('info', 'flip', true);
} else if (id == 'about') {
tt.goTo('about', 'pop', true);
}
});
tt.on('click', 'button', 'help about info', function() {
tt.goBack();
});
// Show the loading message...
$('#showLoading').click(function() {
tt.showLoading('10 seconds');
var count = 10;
var interval = setInterval(function() {
if (--count <= 0) {
clearInterval(interval);
tt.hideLoading();
} else {
$('#topcoat-loading-message').text(count + ' seconds');
}
},1000);
});
// Show the dialog...
$('#showDialog').click(function() {
tt.showDialog('This is a dialog', 'Example Dialog', {OK: function() { console.log('OK Pressed') }
, Cancel: function() { console.log('Cancel Pressed')}});
});
tt.on(tt.EVENTS.PAGE_START, 'carouselExample', function() {
// When the page is loaded, run the following...
// Setup iScroll..
carouselScroll = new IScroll('#carouselWrapper', {
scrollX: true,
scrollY: false,
momentum: false,
snap: true,
snapSpeed: 400,
keyBindings: true,
indicators: {
el: document.getElementById('carouselIndicator'),
resize: false
}
});
}).on(tt.EVENTS.PAGE_END, 'carouselExample', function() {
// When the page is unloaded, run the following...
if (carouselScroll != null) {
carouselScroll.destroy();
carouselScroll = null;
}
});
// Show a message when anyone clicks on button of the test form...
$('.testForm').submit(function() {
tt.showDialog('<h3>Button Clicked</h3>');
return false;
});
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
// Create the placeholders in the gallery...
function createPlaceHolder(type) {
var placeHolders = { kittens : 'placekitten.com', bears: 'placebear.com', lorem: 'lorempixel.com',
bacon: 'baconmockup.com', murray: 'www.fillmurray.com'};
var gallery = '';
for (var i = 0; i < getRandomInt(50,100); i++) {
gallery += '<li class="photoClass" style="background:url(http://' + placeHolders[type] + '/' +
getRandomInt(200,300) + '/' + getRandomInt(200,300) + ') 50% 50% no-repeat"></li>';
}
$('.photo-gallery').html(gallery);
tt.refreshScroll(); // Refresh the scroller
tt.scrollTo(0,0); // Move back to the top of the page...
}
$('#gallery-picker').change(function(e, id) {
createPlaceHolder(id);
});
createPlaceHolder('kittens');
<%
}
} else {
%>
// Create the topcoatTouch object
var tt = new TopcoatTouch();
<% if (mvc) { %>
tt.createController('home');
<% } else { %>
// First page we go to home... This could be done in code by setting the class to 'page page-center', but here is how to do it in code...
<% } %>
tt.goTo('home');
<% } %>
});
|
const sizeOf = {
object: function () {
return function (object) {
let $start = 0
$start += 1 * object.array.length + 2
return $start
}
} ()
}
const serializer = {
all: {
object: function () {
return function (object, $buffer, $start) {
let $i = []
for ($i[0] = 0; $i[0] < object.array.length; $i[0]++) {
$buffer[$start++] = object.array[$i[0]] & 0xff
}
$buffer[$start++] = 0xd
$buffer[$start++] = 0xa
return { start: $start, serialize: null }
}
} ()
},
inc: {
object: function () {
return function (object, $step = 0, $i = []) {
let $_, $bite
return function $serialize ($buffer, $start, $end) {
for (;;) {
switch ($step) {
case 0:
$i[0] = 0
$step = 1
case 1:
$bite = 0
$_ = object.array[$i[0]]
case 2:
while ($bite != -1) {
if ($start == $end) {
$step = 2
return { start: $start, serialize: $serialize }
}
$buffer[$start++] = $_ >>> $bite * 8 & 0xff
$bite--
}
if (++$i[0] != object.array.length) {
$step = 1
continue
}
$step = 3
case 3:
if ($start == $end) {
$step = 3
return { start: $start, serialize: $serialize }
}
$buffer[$start++] = 0xd
case 4:
if ($start == $end) {
$step = 4
return { start: $start, serialize: $serialize }
}
$buffer[$start++] = 0xa
case 5:
}
break
}
return { start: $start, serialize: null }
}
}
} ()
}
}
const parser = {
all: {
object: function () {
return function ($buffer, $start) {
let $i = []
let object = {
array: []
}
$i[0] = 0
for (;;) {
if (
$buffer[$start] == 0xd &&
$buffer[$start + 1] == 0xa
) {
$start += 2
break
}
object.array[$i[0]] = $buffer[$start++]
$i[0]++
}
return object
}
} ()
},
inc: {
object: function () {
return function (object, $step = 0, $i = []) {
let $length = 0
return function $parse ($buffer, $start, $end) {
for (;;) {
switch ($step) {
case 0:
object = {
array: []
}
case 1:
$i[0] = 0
case 2:
$step = 2
if ($start == $end) {
return { start: $start, object: null, parse: $parse }
}
if ($buffer[$start] != 0xd) {
$step = 4
continue
}
$start++
$step = 3
case 3:
$step = 3
if ($start == $end) {
return { start: $start, object: null, parse: $parse }
}
if ($buffer[$start] != 0xa) {
$step = 4
$parse(Buffer.from([ 0xd ]), 0, 1)
continue
}
$start++
$step = 7
continue
case 4:
case 5:
if ($start == $end) {
$step = 5
return { start: $start, object: null, parse: $parse }
}
object.array[$i[0]] = $buffer[$start++]
case 6:
$i[0]++
$step = 2
continue
case 7:
}
return { start: $start, object: object, parse: null }
break
}
}
}
} ()
}
}
module.exports = {
sizeOf: sizeOf,
serializer: {
all: serializer.all,
inc: serializer.inc,
bff: function ($incremental) {
return {
object: function () {
return function (object) {
return function ($buffer, $start, $end) {
let $i = []
if ($end - $start < 2 + object.array.length * 1) {
return $incremental.object(object, 0, $i)($buffer, $start, $end)
}
for ($i[0] = 0; $i[0] < object.array.length; $i[0]++) {
$buffer[$start++] = object.array[$i[0]] & 0xff
}
$buffer[$start++] = 0xd
$buffer[$start++] = 0xa
return { start: $start, serialize: null }
}
}
} ()
}
} (serializer.inc)
},
parser: {
all: parser.all,
inc: parser.inc,
bff: function ($incremental) {
return {
object: function () {
return function () {
return function ($buffer, $start, $end) {
let $i = []
let object = {
array: []
}
$i[0] = 0
for (;;) {
if ($end - $start < 2) {
return $incremental.object(object, 2, $i)($buffer, $start, $end)
}
if (
$buffer[$start] == 0xd &&
$buffer[$start + 1] == 0xa
) {
$start += 2
break
}
if ($end - $start < 1) {
return $incremental.object(object, 4, $i)($buffer, $start, $end)
}
object.array[$i[0]] = $buffer[$start++]
$i[0]++
}
return { start: $start, object: object, parse: null }
}
} ()
}
}
} (parser.inc)
}
}
|
import modelExtend from 'dva-model-extend'
import { create, remove, update } from '../services/user'
import * as usersService from '../services/users'
import { pageModel } from './common'
import { config } from 'utils'
const { query } = usersService
const { prefix } = config
export default modelExtend(pageModel, {
namespace: 'user',
state: {
currentItem: {},
modalVisible: false,
modalType: 'create',
selectedRowKeys: [],
isMotion: localStorage.getItem(`${prefix}userIsMotion`) === 'true',
},
subscriptions: {
setup ({ dispatch, history }) {
history.listen(location => {
if (location.pathname === '/user') {
dispatch({
type: 'query',
payload: location.query,
})
}
})
},
},
effects: {
*query ({ payload = {} }, { call, put }) {
const data = yield call(query, payload)
if (data) {
yield put({
type: 'querySuccess',
payload: {
list: data.data,
pagination: {
current: Number(payload.page) || 1,
pageSize: Number(payload.pageSize) || 10,
total: data.total,
},
},
})
}
},
*'delete' ({ payload }, { call, put, select }) {
const data = yield call(remove, { id: payload })
const { selectedRowKeys } = yield select(_ => _.user)
if (data.success) {
yield put({ type: 'updateState', payload: { selectedRowKeys: selectedRowKeys.filter(_ => _ !== payload) } })
yield put({ type: 'query' })
} else {
throw data
}
},
*'multiDelete' ({ payload }, { call, put }) {
const data = yield call(usersService.remove, payload)
if (data.success) {
yield put({ type: 'updateState', payload: { selectedRowKeys: [] } })
yield put({ type: 'query' })
} else {
throw data
}
},
*create ({ payload }, { call, put }) {
const data = yield call(create, payload)
if (data.success) {
yield put({ type: 'hideModal' })
yield put({ type: 'query' })
} else {
throw data
}
},
*update ({ payload }, { select, call, put }) {
const id = yield select(({ user }) => user.currentItem.id)
const newUser = { ...payload, id }
const data = yield call(update, newUser)
if (data.success) {
yield put({ type: 'hideModal' })
yield put({ type: 'query' })
} else {
throw data
}
},
},
reducers: {
showModal (state, { payload }) {
return { ...state, ...payload, modalVisible: true }
},
hideModal (state) {
return { ...state, modalVisible: false }
},
switchIsMotion (state) {
localStorage.setItem(`${prefix}userIsMotion`, !state.isMotion)
return { ...state, isMotion: !state.isMotion }
},
},
})
|
var blueMarker = L.AwesomeMarkers.icon({
icon: 'record',
prefix: 'glyphicon',
markerColor: 'blue'
});
var airportMarker = L.AwesomeMarkers.icon({
icon: 'plane',
prefix: 'fa',
markerColor: 'cadetblue'
});
var cityMarker = L.AwesomeMarkers.icon({
icon: 'home',
markerColor: 'red'
});
var stationMarker = L.AwesomeMarkers.icon({
icon: 'train',
prefix: 'fa',
markerColor: 'cadetblue'
});
|
/**
* jspsych plugin for categorization trials with feedback and animated stimuli
* Josh de Leeuw
*
* documentation: docs.jspsych.org
**/
jsPsych.plugins["categorize-animation"] = (function() {
var plugin = {};
jsPsych.pluginAPI.registerPreload('categorize-animation', 'stimuli', 'image');
plugin.info = {
name: 'categorize-animation',
description: '',
parameters: {
stimuli: {
type: jsPsych.plugins.parameterType.IMAGE,
pretty_name: 'Stimuli',
default: undefined,
description: 'Array of paths to image files.'
},
key_answer: {
type: jsPsych.plugins.parameterType.KEYCODE,
pretty_name: 'Key answer',
default: undefined,
description: 'The key to indicate correct response'
},
choices: {
type: jsPsych.plugins.parameterType.KEYCODE,
pretty_name: 'Choices',
default: jsPsych.ALL_KEYS,
array: true,
description: 'The keys subject is allowed to press to respond to stimuli.'
},
text_answer: {
type: jsPsych.plugins.parameterType.STRING,
pretty_name: 'Text answer',
default: null,
description: 'Text to describe correct answer.'
},
correct_text: {
type: jsPsych.plugins.parameterType.STRING,
pretty_name: 'Correct text',
default: 'Correct.',
description: 'String to show when subject gives correct answer'
},
incorrect_text: {
type: jsPsych.plugins.parameterType.STRING,
pretty_name: 'Incorrect text',
default: 'Wrong.',
description: 'String to show when subject gives incorrect answer.'
},
frame_time: {
type: jsPsych.plugins.parameterType.INT,
pretty_name: 'Frame time',
default: 500,
description: 'Duration to display each image.'
},
sequence_reps: {
type: jsPsych.plugins.parameterType.INT,
pretty_name: 'Sequence repetitions',
default: 1,
description: 'How many times to display entire sequence.'
},
allow_response_before_complete: {
type: jsPsych.plugins.parameterType.BOOL,
pretty_name: 'Allow response before complete',
default: false,
description: 'If true, subject can response before the animation sequence finishes'
},
feedback_duration: {
type: jsPsych.plugins.parameterType.INT,
pretty_name: 'Feedback duration',
default: 2000,
description: 'How long to show feedback'
},
prompt: {
type: jsPsych.plugins.parameterType.STRING,
pretty_name: 'Prompt',
default: null,
description: 'Any content here will be displayed below the stimulus.'
},
render_on_canvas: {
type: jsPsych.plugins.parameterType.BOOL,
pretty_name: 'Render on canvas',
default: true,
description: 'If true, the images will be drawn onto a canvas element (prevents blank screen between consecutive images in some browsers).'+
'If false, the image will be shown via an img element.'
}
}
}
plugin.trial = function(display_element, trial) {
var animate_frame = -1;
var reps = 0;
var showAnimation = true;
var responded = false;
var timeoutSet = false;
var correct;
if (trial.render_on_canvas) {
// first clear the display element (because the render_on_canvas method appends to display_element instead of overwriting it with .innerHTML)
if (display_element.hasChildNodes()) {
// can't loop through child list because the list will be modified by .removeChild()
while (display_element.firstChild) {
display_element.removeChild(display_element.firstChild);
}
}
var canvas = document.createElement("canvas");
canvas.id = "jspsych-categorize-animation-stimulus";
canvas.style.margin = 0;
canvas.style.padding = 0;
display_element.insertBefore(canvas, null);
var ctx = canvas.getContext("2d");
if (trial.prompt !== null) {
var prompt_div = document.createElement("div");
prompt_div.id = "jspsych-categorize-animation-prompt";
prompt_div.style.visibility = "hidden";
prompt_div.innerHTML = trial.prompt;
display_element.insertBefore(prompt_div, canvas.nextElementSibling);
}
var feedback_div = document.createElement("div");
display_element.insertBefore(feedback_div, display_element.nextElementSibling);
}
// show animation
var animate_interval = setInterval(function() {
if (!trial.render_on_canvas) {
display_element.innerHTML = ''; // clear everything
}
animate_frame++;
if (animate_frame == trial.stimuli.length) {
animate_frame = 0;
reps++;
// check if reps complete //
if (trial.sequence_reps != -1 && reps >= trial.sequence_reps) {
// done with animation
showAnimation = false;
}
}
if (showAnimation) {
if (trial.render_on_canvas) {
display_element.querySelector('#jspsych-categorize-animation-stimulus').style.visibility = 'visible';
var img = new Image();
img.src = trial.stimuli[animate_frame];
canvas.height = img.naturalHeight;
canvas.width = img.naturalWidth;
ctx.drawImage(img,0,0);
} else {
display_element.innerHTML += '<img src="'+trial.stimuli[animate_frame]+'" class="jspsych-categorize-animation-stimulus"></img>';
}
}
if (!responded && trial.allow_response_before_complete) {
// in here if the user can respond before the animation is done
if (trial.prompt !== null) {
if (trial.render_on_canvas) {
prompt_div.style.visibility = "visible";
} else {
display_element.innerHTML += trial.prompt;
}
}
if (trial.render_on_canvas) {
if (!showAnimation) {
canvas.remove();
}
}
} else if (!responded) {
// in here if the user has to wait to respond until animation is done.
// if this is the case, don't show the prompt until the animation is over.
if (!showAnimation) {
if (trial.prompt !== null) {
if (trial.render_on_canvas) {
prompt_div.style.visibility = "visible";
} else {
display_element.innerHTML += trial.prompt;
}
}
if (trial.render_on_canvas) {
canvas.remove();
}
}
} else {
// user has responded if we get here.
// show feedback
var feedback_text = "";
if (correct) {
feedback_text = trial.correct_text.replace("%ANS%", trial.text_answer);
} else {
feedback_text = trial.incorrect_text.replace("%ANS%", trial.text_answer);
}
if (trial.render_on_canvas) {
if (trial.prompt !== null) {
prompt_div.remove();
}
feedback_div.innerHTML = feedback_text;
} else {
display_element.innerHTML += feedback_text;
}
// set timeout to clear feedback
if (!timeoutSet) {
timeoutSet = true;
jsPsych.pluginAPI.setTimeout(function() {
endTrial();
}, trial.feedback_duration);
}
}
}, trial.frame_time);
var keyboard_listener;
var trial_data = {};
var after_response = function(info) {
// ignore the response if animation is playing and subject
// not allowed to respond before it is complete
if (!trial.allow_response_before_complete && showAnimation) {
return false;
}
correct = false;
if (trial.key_answer == info.key) {
correct = true;
}
responded = true;
trial_data = {
"stimulus": JSON.stringify(trial.stimuli),
"rt": info.rt,
"correct": correct,
"key_press": info.key
};
jsPsych.pluginAPI.cancelKeyboardResponse(keyboard_listener);
}
keyboard_listener = jsPsych.pluginAPI.getKeyboardResponse({
callback_function: after_response,
valid_responses: trial.choices,
rt_method: 'performance',
persist: true,
allow_held_key: false
});
function endTrial() {
clearInterval(animate_interval); // stop animation!
display_element.innerHTML = ''; // clear everything
jsPsych.finishTrial(trial_data);
}
};
return plugin;
})();
|
'use strict';
var app = angular.module('Fablab');
app.controller('GlobalPurchaseEditController', function ($scope, $location, $filter, $window,
PurchaseService, NotificationService, StaticDataService, SupplyService) {
$scope.selected = {purchase: undefined};
$scope.currency = App.CONFIG.CURRENCY;
$scope.loadPurchase = function (id) {
PurchaseService.get(id, function (data) {
$scope.purchase = data;
});
};
$scope.save = function () {
var purchaseCurrent = angular.copy($scope.purchase);
updateStock();
PurchaseService.save(purchaseCurrent, function (data) {
$scope.purchase = data;
NotificationService.notify("success", "purchase.notification.saved");
$location.path("purchases");
});
};
var updateStock = function () {
var stockInit = $scope.purchase.supply.quantityStock;
$scope.purchase.supply.quantityStock = parseFloat(stockInit) - parseFloat($scope.purchase.quantity);
var supplyCurrent = angular.copy($scope.purchase.supply);
SupplyService.save(supplyCurrent, function (data) {
$scope.purchase.supply = data;
});
};
$scope.maxMoney = function () {
return parseFloat($scope.purchase.quantity) * parseFloat($scope.purchase.supply.sellingPrice);
};
$scope.updatePrice = function () {
var interTotal = parseFloat($scope.purchase.quantity) * parseFloat($scope.purchase.supply.sellingPrice);
if ($scope.purchase.discount === undefined || !$scope.purchase.discount) {
//0.05 cts ceil
var val = $window.Math.ceil(interTotal * 20) / 20;
$scope.purchase.purchasePrice = $filter('number')(val, 2);
;
} else {
if ($scope.purchase.discountPercent) {
var discountInter = parseFloat(interTotal) * (parseFloat($scope.purchase.discount) / parseFloat(100));
var total = parseFloat(interTotal) - parseFloat(discountInter);
//0.05 cts ceil
var val = $window.Math.ceil(total * 20) / 20;
$scope.purchase.purchasePrice = $filter('number')(val, 2);
} else {
var total = parseFloat(interTotal) - parseFloat($scope.purchase.discount);
//0.05 cts ceil
var val = $window.Math.ceil(total * 20) / 20;
$scope.purchase.purchasePrice = $filter('number')(val, 2);
}
}
};
$scope.firstPercent = App.CONFIG.FIRST_PERCENT.toUpperCase() === "PERCENT";
$scope.optionsPercent = [{
name: "%",
value: true
}, {
name: App.CONFIG.CURRENCY,
value: false
}];
$scope.today = function () {
$scope.dt = new Date();
};
$scope.today();
$scope.clear = function () {
$scope.dt = null;
};
$scope.open = function ($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.dateOptions = {
formatYear: 'yy',
startingDay: 1
};
$scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
$scope.format = $scope.formats[2];
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
var afterTomorrow = new Date();
afterTomorrow.setDate(tomorrow.getDate() + 2);
$scope.events =
[
{
date: tomorrow,
status: 'full'
},
{
date: afterTomorrow,
status: 'partially'
}
];
$scope.getDayClass = function (date, mode) {
if (mode === 'day') {
var dayToCheck = new Date(date).setHours(0, 0, 0, 0);
for (var i = 0; i < $scope.events.length; i++) {
var currentDay = new Date($scope.events[i].date).setHours(0, 0, 0, 0);
if (dayToCheck === currentDay) {
return $scope.events[i].status;
}
}
}
return '';
};
StaticDataService.loadSupplyStock(function (data) {
$scope.supplyStock = data;
});
StaticDataService.loadCashiers(function (data) {
$scope.cashierList = data;
});
}
);
app.controller('PurchaseNewController', function ($scope, $controller, $rootScope) {
$controller('GlobalPurchaseEditController', {$scope: $scope});
$scope.newPurchase = true;
$scope.paidDirectly = false;
$scope.purchase = {
purchaseDate: new Date(),
user: $rootScope.connectedUser.user
};
}
);
app.controller('PurchaseEditController', function ($scope, $routeParams, $controller) {
$controller('GlobalPurchaseEditController', {$scope: $scope});
$scope.newPurchase = false;
$scope.loadPurchase($routeParams.id);
}
);
|
export const ic_my_location_twotone = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M13 3.06V1h-2v2.06C6.83 3.52 3.52 6.83 3.06 11H1v2h2.06c.46 4.17 3.77 7.48 7.94 7.94V23h2v-2.06c4.17-.46 7.48-3.77 7.94-7.94H23v-2h-2.06c-.46-4.17-3.77-7.48-7.94-7.94zM12 19c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"},"children":[]},{"name":"circle","attribs":{"cx":"12","cy":"12","opacity":".3","r":"2"},"children":[]},{"name":"path","attribs":{"d":"M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"},"children":[]}]}; |
import Form from 'cerebral-module-forms/Form'
import submitForm from './chains/submitForm'
import resetForm from './chains/resetForm'
import validateForm from './chains/validateForm'
export default (options = {}) => {
return (module, controller) => {
module.addState(Form({
name: {
value: '',
isRequired: true
},
email: {
value: '',
validations: ['isEmail'],
errorMessages: ['Not valid email'],
isRequired: true
},
password: {
value: '',
validations: ['equalsField:repeatPassword'],
dependsOn: 'simple.repeatPassword',
errorMessages: ['Not equal to repeated password'],
isRequired: true
},
repeatPassword: {
value: '',
validations: ['equalsField:password'],
dependsOn: 'simple.password',
errorMessages: ['Not equal to password'],
isRequired: true
},
address: Form({
street: {
value: ''
},
postalCode: {
value: '',
validations: ['isLength:4', 'isNumeric'],
errorMessages: ['Has to be length 4', 'Can only contain numbers']
}
})
}))
module.addSignals({
formSubmitted: submitForm,
resetClicked: resetForm,
validateFormClicked: validateForm
})
}
}
|
"use strict";
define("ace/snippets/scala", ["require", "exports", "module"], function (require, exports, module) {
"use strict";
exports.snippetText = undefined;
exports.scope = "scala";
}); |
'use strict';
module.exports = {
set: function (v) {
this.setProperty('src', v);
},
get: function () {
return this.getPropertyValue('src');
},
enumerable: true
};
|
'use strict';
exports.connect = function () {
var mongoose = require('mongoose'),
config = require('../config'),
options = {
user : config.mongo.user,
pass : config.mongo.pass
};
mongoose.connect(config.db, options);
return mongoose.connection;
};
|
//APP
var app = angular.module('PortfolioApp', ['ngRoute', 'slick']);
//ROUTING
app.config(function ($routeProvider) {
"ngInject";
$routeProvider
.when('/', {
controller: "HomeController",
templateUrl: "js/angular/views/home-view.html"
})
.when('/work/:projectId', {
controller: 'ProjectController',
templateUrl: 'js/angular/views/project-view.html'
})
.otherwise({
redirectTo: '/'
});
});
//CONTROLLERS
app.controller('HomeController', ['$scope', 'projects', function($scope, projects) {
"ngInject";
projects.success(function(data) {
$scope.projects = data;
});
//init function for binding
function bindListeners() {
$("header").on("click", ".mobile-toggle", function() {
$(this).toggleClass("active");
})
$("header, .about").on("click", ".nav-link", function(e) {
e.preventDefault();
e.stopImmediatePropagation();
if($(window).width() <= 740)
$(".mobile-toggle").removeClass("active");
var anchor = $(this).attr("href");
$('html, body').animate({
scrollTop: $(anchor).offset().top - 70
}, 500);
})
}
//Home page initializations
angular.element(document).ready(function () {
bindListeners();
});
}]);
app.controller('ProjectController', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http, $sce) {
"ngInject";
$scope.video = false;
$http.get('projects/' + $routeParams.projectId + '.json').success(function(data) {
$scope.detail = data;
})
.error(function(data) {
console.log("Failed to get data")
});
}
]);
//SERVICES
app.factory('projects', ['$http', function($http) {
"ngInject";
return $http.get('projects/project-list.json')
.success(function(data) {
return data;
})
.error(function(data) {
return data;
console.log("Failed to get data")
});
}]);
//FILTERS
app.filter('safe', function($sce) {
"ngInject";
return function(val) {
return $sce.trustAsHtml(val);
};
});
|
import { moduleForModel, test } from 'ember-qunit';
import Pretender from 'pretender';
// ToDo: Install ember-cli-faker
import mocks from './mocks';
const {
inventoryMock,
productMock,
componentsMock
} = mocks;
let mockServer;
moduleForModel('inventory', 'Unit | Serializer | inventory', {
needs: ['serializer:application',
'model:product',
'model:inventory',
'model:component'],
beforeEach() {
mockServer = new Pretender(function() {
this.get('/products', function() {
const response = {
records: [productMock]
};
return [200, { "Content-Type": "application/json" }, JSON.stringify(response)];
});
this.get(`/products/${productMock.id}`, function() {
return [200, { "Content-Type": "application/json" }, JSON.stringify(productMock)];
});
this.get('/inventories', function() {
const response = {
records: [inventoryMock]
};
return [200, { "Content-Type": "application/json" }, JSON.stringify(response)];
});
this.get(`/components/${componentsMock[0].id}`, function() {
return [200, { "Content-Type": "application/json" }, JSON.stringify(componentsMock[0])];
});
this.get(`/components/${componentsMock[1].id}`, function() {
return [200, { "Content-Type": "application/json" }, JSON.stringify(componentsMock[1])];
});
});
},
afterEach() {
mockServer.shutdown();
}
});
test('it serializes records', function(assert) {
return this.store().findAll('inventory').then((inventories) => {
assert.equal(inventories.get('length'), 1);
const inventory = inventories.objectAt(0);
assert.ok(inventory.get('created'));
assert.equal(inventory.get('qty'), inventoryMock.fields['qty']);
assert.equal(inventory.get('restock-at'), inventoryMock.fields['restock-at']);
});
});
test('it serializes belongsTo relationship', function(assert) {
return this.store().findAll('inventory').then((inventories) => {
const inventory = inventories.objectAt(0);
inventory.get('product').then((product) => {
assert.equal(product.get('name'), productMock.fields.name);
assert.equal(product.get('description'), productMock.fields.description);
});
});
});
test('it serializes hasMany relationship', function(assert) {
return this.store().findAll('product').then((products) => {
const product = products.objectAt(0);
product.get('components').then((components) => {
components.forEach((component, index) => {
assert.equal(component.get('name'), componentsMock[index].fields.name);
});
});
});
});
|
+(function () {
'use strict';
angular
.module('DashboardApplication')
.controller('FileManagerRemoveFolderController', ['$scope', '$q', 'Event', 'FoldersRest', FileManagerRemoveFolderController]);
function FileManagerRemoveFolderController($scope, $q, Event, FoldersRest) {
var vm = this;
var folderId = $scope.ngDialogData.folderId;
vm.removeFolder = removeFolder;
function removeFolder() {
var id = folderId;
var $defer = $q.defer();
FoldersRest.one(id).remove().then(function () {
console.log("FoldersRest");
debugger;
Event.publish('FOLDERS_TREEVIEW_UPDATED');
alert('فولدر با موفقیت حذف شد', 'انجام شد!');
$defer.resolve();
}, function (error) {
$defer.reject(error);
});
return $defer.promise;
}
}
})(); |
/**
* @module {Module} utils/math
* @parent utils
*
* The module's description is the first paragraph.
*
* The body of the module's documentation.
*/
import _ from 'lodash';
/**
* @function
*
* This function's description is the first
* paragraph.
*
* This starts the body. This text comes after the signature.
*
* @param {Number} first This param's description.
* @param {Number} second This param's description.
* @return {Number} This return value's description.
*/
export function sum(first, second){ ... };
/**
* @property {{}}
*
* This function's description is the first
* paragraph.
*
* @option {Number} pi The description of pi.
*
* @option {Number} e The description of e.
*/
export var constants = {
pi: 3.14159265359,
e: 2.71828
}; |
// ***********************************************************
// This example plugins/index.js can be used to load plugins
//
// You can change the location of this file or turn off loading
// the plugins file with the 'pluginsFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/plugins-guide
// ***********************************************************
// This function is called when a project is opened or re-opened (e.g. due to
// the project's config changing)
module.exports = (on, config) => {
// `on` is used to hook into various events Cypress emits
// `config` is the resolved Cypress config
if (process.env.CYPRESS_CONNECTION_TYPE) {
on(`before:browser:launch`, (browser = {}, args) => {
if (
browser.name === `chrome` &&
process.env.CYPRESS_CONNECTION_TYPE === `slow`
) {
args.push(`--force-effective-connection-type=2G`)
}
return args
})
}
}
|
var box, mbox;
function demo() {
cam ( 0, 20, 40 );
world = new OIMO.World();
world.add({ size:[50, 10, 50], pos:[0,-5,0] }); // ground
var options = {
type:'box',
size:[10, 10, 10],
pos:[0,20,0],
density:1,
move:true
}
box = world.add( options );
mbox = view.add( options ); // three mesh
};
function update () {
world.step();
mbox.position.copy( box.getPosition() );
mbox.quaternion.copy( box.getQuaternion() );
} |
var fs = require('fs'),
cons = require('consolidate'),
dust = require('dustjs-linkedin');
var pages = [
'index',
'contact',
'faq',
'registration',
'sponsors',
'travel',
'visit',
'volunteers'
];
pages.forEach(function(page) {
cons.dust('views/'+page+'.dust', { views: __dirname+'/views'}, function(err, html) {
if(err) return console.log('error: ', err);
fs.writeFile(__dirname+'/dist/'+page+'.html', html, function(err) {
if(err) return console.log('error saving file: ', page, err);
console.log('create page: ', page);
});
});
});
|
'use strict';
module.exports = function (grunt) {
var exec = require('child_process').exec;
grunt.registerMultiTask('install-dependencies', 'Installs npm dependencies.', function () {
var cb, options, cp;
cb = this.async();
options = this.options({
cwd: '',
stdout: true,
stderr: true,
failOnError: true,
isDevelopment: false
});
var cmd = "npm install";
if(!options.isDevelopment ) cmd += " -production";
cp = exec(cmd, {cwd: options.cwd}, function (err, stdout, stderr) {
if (err && options.failOnError) {
grunt.warn(err);
}
cb();
});
grunt.verbose.writeflags(options, 'Options');
if (options.stdout || grunt.option('verbose')) {
console.log("Running npm install in: " + options.cwd);
cp.stdout.pipe(process.stdout);
}
if (options.stderr || grunt.option('verbose')) {
cp.stderr.pipe(process.stderr);
}
});
};
|
const electron = require('electron');
const ipcRenderer = electron.ipcRenderer;
window.onload = function() {
ipcRenderer.send('game-preview-loaded');
}
ipcRenderer.on('game-preview-start', function(event, data) {
var app = new Application({
// resize: true,
fullscreen: true,
antyAliasing: true,
preload: function(){
console.log(data.assets);
//load images
for (var i = 0; i < data.assets.length; i++) {
var meta = data.assets[i];
if(meta.type == 'script') {
require(meta.path);
// connect script with uuid
} else {
this.loader.load(meta.type, meta.path, meta.name, meta.uuid);
}
}
//load scene (json)
// this.loader.load('json', scene file path, 'scene.json');
},
//instantiate scene objects
loaded: function(){
//instantiate all object
for(var i = 0; i < data.sceneFile.length; i++) {
if(data.sceneFile[i].tag == 'mainCamera') {
this.mainCamera = this.scene.instantiate(data.sceneFile[i]);
} else {
this.scene.instantiate(data.sceneFile[i]);
}
}
},
//actual start function
start: function(){
//show must go on
},
preupdate: function(){
},
postupdate: function(){
},
postrender: function(){
// var layer = this.mainCamera.camera.layer;
// layer.ctx.save();
// layer.textAlign('left');
// layer.font('30px Arial');
// layer.fillStyle('white');
//
// var fps = (Time.deltaTime).toFixed(3);
//
// layer.fillText(fps || 0, 0,30);
// layer.ctx.restore();
}
});
})
|
module.exports = {
token: 'TELEGRAM_BOT_TOKEN',
polling: {
timeout: 3,
limit: 100
}
};
|
Template.friendPosts.onCreated(function() {
Bisia.Notification.resetNotify('note', 'post');
})
Template.friendPosts.helpers({
getPost: function(postId) {
var post = Posts.findOne(postId);
if (post) {
var user = Users.findOne({ '_id': post.authorId }, { 'fields': {
'username': 1,
'profile.city': 1,
'profile.gender': 1,
'profile.status': 1,
'profile.avatar': 1,
'profile.online': 1,
'profile.birthday': 1
}});
post.showHeader = true;
post.usern = user.username;
post.profile = user.profile;
return post;
}
},
detectFirstPage: function() {
var increment = Bisia.getController('increment');
var limit = Bisia.getController('params')['pageLimit'];
// Don't show spinner by default
var pageDisplay = true;
// If we are on the first page...
if (!limit || limit == increment) {
// pageDisplay becomes reactive
pageDisplay = this.pageReady;
}
// Add pageDisplay to this
return _.extend(this, {
pageDisplay: pageDisplay
});
}
});
Template.friendPosts.events({
'scroll .content': function(e, t) {
Bisia.Ui.toggleAtBottom(e, '#helpbars', 'bottom-show');
}
}); |
import { all, takeEvery } from 'redux-saga/effects';
import actions from '#actions';
import handleShareFormChange from './startAlbumsSharingService/handleShareFormChange';
import handleShareFormSubmit from './startAlbumsSharingService/handleShareFormSubmit';
import handleShareItemsSelect from './startAlbumsSharingService/handleShareItemsSelect';
function* startAlbumsSharingService(apis) {
yield all([
takeEvery(actions.uiShareItemsSelected, handleShareItemsSelect, apis),
takeEvery(actions.uiShareFormSubmited, handleShareFormSubmit, apis),
takeEvery(actions.uiShareFormChanged, handleShareFormChange, apis),
]);
}
export default startAlbumsSharingService;
|
var fs = require('fs'),
eol = require('eol'),
path = require('path'),
mkdirp = require('mkdirp'),
watch = require('watch');
var specialFiles = {
'welcome.md': function(fileContent, consoleContent) {
consoleContent.welcome = processFileContent(fileContent);
},
'config.json': function(fileContent, consoleContent) {
var config = JSON.parse(fileContent);
consoleContent.executables = config.executables;
consoleContent.__config = config;
}
};
function processFileContent(fileContent) {
fileContent = eol.lf(fileContent);
fileContent = new Buffer(fileContent).toString('base64');
return fileContent;
}
function createContentFile(fileName, fileContent) {
var parsed = path.parse(fileName);
return {
content: processFileContent(fileContent),
base: fileName,
name: parsed.name,
ext: parsed.ext
};
}
function hasExecutableForFile(executables, fileName) {
if (!executables) {
return false;
}
for (var i in executables) {
if (executables[i].file === fileName) {
return true;
}
}
return false;
}
function setFilePermissions(files, config) {
if (!files) {
return;
}
for (var fileName in files) {
var file = files[fileName];
if (!config.noRead || config.noRead.indexOf(file.base) === -1) {
file.readable = true;
}
if (config.writeable && config.writeable.indexOf(file.base) !== -1) {
file.writeable = true;
}
if (hasExecutableForFile(config.executables, file.base)) {
file.executable = true;
}
}
}
/**
* This badass here reads all files from the console folders and creates the content.json file.
*/
function createConsoleContent() {
var srcPath = './src/content';
var targetPath = './dist/content';
var consoleFolders = fs.readdirSync(srcPath);
if (!consoleFolders) {
return;
}
consoleFolders.forEach(function(folderName) {
var consoleSrcPath = srcPath + '/' + folderName;
var consoleTargetPath = targetPath + '/' + folderName;
var stats = fs.statSync(consoleSrcPath);
if (!stats.isDirectory()) {
return;
}
var files = fs.readdirSync(consoleSrcPath);
if (!files || files.length === 0) {
console.log('No files found for ' + consoleSrcPath);
} else {
console.log('Processing content ' + folderName);
var consoleContent = {
files: {}
};
files.forEach(function(file) {
var fileContent = fs.readFileSync(consoleSrcPath + '/' + file, 'utf8');
if (specialFiles[file]) {
specialFiles[file](fileContent, consoleContent);
} else {
consoleContent.files[file] = createContentFile(file, fileContent);
}
});
if (consoleContent.__config) {
setFilePermissions(consoleContent.files, consoleContent.__config);
delete consoleContent.__config;
}
mkdirp.sync(consoleTargetPath);
fs.writeFileSync(consoleTargetPath + '/content.json', JSON.stringify(consoleContent), 'utf8');
}
});
}
if (process.argv.indexOf('--watching') !== -1) {
watch.watchTree('./src/content', function() {
createConsoleContent();
});
}
else {
createConsoleContent();
} |
const determineTestFilesToRun = ({ inputFile, inputArgs = [], config }) => {
const path = require("path");
const fs = require("fs");
const glob = require("glob");
let filesToRun = [];
if (inputFile) {
filesToRun.push(inputFile);
} else if (inputArgs.length > 0) {
inputArgs.forEach(inputArg => filesToRun.push(inputArg));
}
if (filesToRun.length === 0) {
const directoryContents = glob.sync(
`${config.test_directory}${path.sep}**${path.sep}*`
);
filesToRun =
directoryContents.filter(item => fs.statSync(item).isFile()) || [];
}
return filesToRun.filter(file => {
return file.match(config.test_file_extension_regexp) !== null;
});
};
module.exports = {
determineTestFilesToRun
};
|
// nodejs按行读取文件流
var Stream = require('stream').Stream,
util = require('util');
var LineStream = function() {
this.writable = true;
this.readable = true;
this.buffer = '';
};
util.inherits(LineStream, Stream);
LineStream.prototype.write = function(data, encoding) {
if (Buffer.isBuffer(data)) {
data = data.toString(encoding || 'utf8');
}
var parts = data.split(/\n/g);
var len = parts.length;
for (var i = 0; i < len; i++) {
this.emit('data', parts[i]+'\n');
}
};
LineStream.prototype.end = function() {
if(this.buffer.length > 0){
this.emit('data',this.buffer);
this.buffer = '';
}
this.emit('end');
};
module.exports = LineStream;
|
'use strict';
/**
* Module dependencies.
*/
var users = require('../../app/controllers/users'),
goaliedash = require('../../app/controllers/goaliedash');
module.exports = function(app) {
app.route('/goaliedash')
.get(users.requiresLogin, users.hasAuthorization);
}; |
// @flow
import React from 'react'
import withPropsStream from '@vega/utils/withPropsStream'
import {map} from 'rxjs/operators'
import styles from './styles/Communicator.css'
import ThreadList from './ThreadList'
import CreateComment from './CreateComment'
function getPropsStream(props$) {
// todo: implement open/close behavior
return props$.pipe(map(props => ({...props, isOpen: true})))
}
type Props = {
isOpen: boolean,
subjectIds: string[],
focusedCommentId: string
}
export default withPropsStream(
getPropsStream,
class Communicator extends React.Component<Props> {
state = {
createCommentIsSticky: false
}
handleCloseCreateComment = event => {
this.setState({
createCommentIsSticky: false
})
event.stopPropagation()
}
handleStickCreateComment = () => {
this.setState({
createCommentIsSticky: true
})
}
render() {
const {isOpen, subjectIds, focusedCommentId} = this.props
const {createCommentIsSticky} = this.state
return isOpen ? (
<div className={styles.root}>
<div
className={
createCommentIsSticky
? styles.feedWithWithStickyCreateComment
: styles.feed
}
>
<ThreadList
subjectId={subjectIds}
focusedCommentId={focusedCommentId}
/>
</div>
{subjectIds.length === 1 && (
<CreateComment
subjectId={subjectIds[0]}
showCloseButton={createCommentIsSticky}
className={
createCommentIsSticky
? styles.createCommentSticky
: styles.createComment
}
onClose={this.handleCloseCreateComment}
onSubmit={this.handleCloseCreateComment}
onClick={this.handleStickCreateComment}
/>
)}
</div>
) : null
}
}
)
|
var models = require('../models');
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
console.log(req.session);
res.render('layout');
});
module.exports = router; |
(function() {
'use strict';
process.env.debug_sql = true;
var Class = require('ee-class')
, log = require('ee-log')
, assert = require('assert')
, fs = require('fs')
, QueryContext = require('related-query-context')
, ORM = require('related');
var TimeStamps = require('../')
, sqlStatments
, extension
, orm
, db;
// sql for test db
sqlStatments = fs.readFileSync(__dirname+'/db.postgres.sql').toString().split(';').map(function(input){
return input.trim().replace(/\n/gi, ' ').replace(/\s{2,}/g, ' ')
}).filter(function(item){
return item.length;
});
describe('Travis', function(){
it('should have set up the test db', function(done){
var config;
try {
config = require('../config.js').db
} catch(e) {
config = [{
type: 'postgres'
, schema: 'related_timestamps_test'
, database : 'test'
, hosts: [{}]
}];
}
this.timeout(5000);
orm = new ORM(config);
done();
});
it('should be able to drop & create the testing schema ('+sqlStatments.length+' raw SQL queries)', function(done){
orm.getDatabase('related_timestamps_test').getConnection('write').then((connection) => {
return new Promise((resolve, reject) => {
let exec = (index) => {
if (sqlStatments[index]) {
connection.query(new QueryContext({sql:sqlStatments[index]})).then(() => {
exec(index + 1);
}).catch(reject);
}
else resolve();
}
exec(0);
});
}).then(() => {
done();
}).catch(done);
});
});
var expect = function(val, cb){
return function(err, result){
try {
assert.equal(JSON.stringify(result), val);
} catch (err) {
return cb(err);
}
cb();
}
};
describe('The TimeStamps Extension', function() {
var oldDate;
it('should not crash when instatiated', function() {
db = orm.related_timestamps_test;
extension = new TimeStamps();
});
it('should not crash when injected into the orm', function(done) {
orm.use(extension);
orm.load(done);
});
it('should set correct timestamps when inserting a new record', function(done) {
db = orm.related_timestamps_test;
new db.event().save(function(err, evt) {
if (err) done(err);
else {
assert.notEqual(evt.created, null);
assert.notEqual(evt.updated, null);
assert.equal(evt.deleted, null);
oldDate = evt.updated;
done();
}
});
});
it('should set correct timestamps when updating a record', function(done) {
// wait, we nede a new timestamp
setTimeout(function() {
db.event({id:1}, ['*']).findOne(function(err, evt) {
if (err) done(err);
else {
evt.name = 'func with timestamps? no, that ain\'t fun!';
evt.save(function(err){
assert.notEqual(evt.created, null);
assert.notEqual(evt.updated, null);
assert.notEqual(evt.updated.toUTCString(), oldDate.toUTCString());
assert.equal(evt.deleted, null);
done();
});
}
});
}, 1500);
});
it('should set correct timestamps when deleting a record', function(done) {
db.event({id:1}, ['*']).findOne(function(err, evt) {
if (err) done(err);
else {
evt.delete(function(err) {
assert.notEqual(evt.created, null);
assert.notEqual(evt.updated, null);
assert.notEqual(evt.deleted, null);
done();
});
}
});
});
it('should not return soft deleted records when not requested', function(done) {
db.event({id:1}, ['*']).findOne(function(err, evt) {
if (err) done(err);
else {
assert.equal(evt, undefined);
done();
}
});
});
it('should return soft deleted records when requested', function(done) {
db.event({id:1}, ['*']).includeSoftDeleted().findOne(function(err, evt) {
if (err) done(err);
else {
assert.equal(evt.id, 1);
done();
}
});
});
it('should hard delete records when requested', function(done) {
db.event({id:1}, ['*']).includeSoftDeleted().findOne(function(err, evt) {
if (err) done(err);
else {
evt.hardDelete(function(err) {
if (err) done(err);
else {
db.event({id:1}, ['*']).findOne(function(err, evt) {
if (err) done(err);
else {
assert.equal(evt, undefined);
done();
}
});
}
});
}
});
});
it('should not load softdeleted references', function(done) {
new db.event({
name: 'so what'
, eventInstance: [new db.eventInstance({startdate: new Date(), deleted: new Date()})]
}).save(function(err, evt) {
if (err) done(err);
else {
db.event(['*'], {id:evt.id}).fetchEventInstance(['*']).findOne(function(err, event) {
if (err) done(err);
else {
assert.equal(event.eventInstance.length, 0);
done();
}
});
}
});
})
it ('should work when using bulk deletes', function(done) {
new db.event({name: 'bulk delete 1'}).save().then(function() {
return new db.event({name: 'bulk delete 2'}).save()
}).then(function() {
return new db.event({name: 'bulk delete 3'}).save()
}).then(function() {
return db.event('id').find();
}).then(function(records) {
if (JSON.stringify(records) !== '[{"id":2},{"id":3},{"id":4},{"id":5}]') return Promise.reject(new Error('Expected «[{"id":2},{"id":3},{"id":4},{"id":5}]», got «'+JSON.stringify(records)+'»!'))
else return db.event({
id: ORM.gt(3)
}).delete();
}).then(function() {
return db.event('id').find();
}).then(function(emptyList) {
if (JSON.stringify(emptyList) !== '[{"id":2},{"id":3}]') return Promise.reject(new Error('Expected «[{"id":2},{"id":3}]», got «'+JSON.stringify(emptyList)+'»!'))
else return db.event('id').includeSoftDeleted().find();
}).then(function(list) {
if (JSON.stringify(list) !== '[{"id":2},{"id":3},{"id":4},{"id":5}]') return Promise.reject(new Error('Expected «[{"id":2},{"id":3},{"id":4},{"id":5}]», got «'+JSON.stringify(list)+'»!'))
done();
}).catch(done);
})
});
})();
|
var passport = require('passport');
var WebIDStrategy = require('passport-webid').Strategy;
var tokens = require('../../util/tokens');
var ids = require('../../util/id');
var console = require('../../log');
var createError = require('http-errors');
var dateUtils = require('../../util/date');
var url = require('url');
function loadStrategy(conf, entityStorageConf) {
var auth_type = "webid";
var db = require('../../db')(conf, entityStorageConf);
var enabled = conf.enabledStrategies.filter(function (v) {
return (v === auth_type);
});
if (enabled.length === 0) {
console.log('ignoring ' + auth_type + ' strategy for user authentication. Not enabled in the configuration');
return false;
} else {
try {
passport.use(auth_type, new WebIDStrategy(
function (webid, certificate, req, done) {
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
var id = {
user_name: webid,
auth_type: auth_type
};
var oauth2ReturnToParsed = url.parse(req.session.returnTo, true).query;
console.log(" sesion in strategy " + auth_type + JSON.stringify(oauth2ReturnToParsed));
console.log(" client id from session in " + auth_type + JSON.stringify(oauth2ReturnToParsed.client_id));
console.log(" response_type for oauth2 in " + auth_type + JSON.stringify(oauth2ReturnToParsed.response_type));
var accessToken = tokens.uid(30);
var d = Date.parse(certificate.valid_to);
var default_exp = dateUtils.dateToEpochMilis(d);
db.users.findByUsernameAndAuthType(webid, auth_type, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false);
}
db.accessTokens.saveOauth2Token(accessToken, user.id, oauth2ReturnToParsed.client_id, "bearer", [conf.gateway_id], default_exp, null, oauth2ReturnToParsed.response_type, function (err) {
if (err) {
return done(err);
}
return done(null, user);
});
});
}
));
console.log('finished registering passport ' + auth_type + ' strategy');
return true;
} catch (e) {
console.log('FAIL TO register a strategy');
console.log('ERROR: error loading ' + auth_type + ' passport strategy: ' + e);
return false;
}
}
}
module.exports = loadStrategy;
|
const chai = require('chai');
const expect = chai.expect;
const ComplexArray = require('../complex-array/complex-array');
function assertArrayEquals(first, second) {
const message = `${first} != ${second}`;
first.forEach((item, i) => {
expect(item).to.equal(second[i], message);
});
}
describe('Complex Array', () => {
describe('Consructor', () => {
it('should construct from a number', () => {
const a = new ComplexArray(10);
expect(a).to.exist;
expect(a.real.length).to.equal(10);
expect(a.imag.length).to.equal(10);
expect(a.real[0]).to.equal(0);
expect(a.imag[0]).to.equal(0);
});
it('should construct from a number with a type', () => {
const a = new ComplexArray(10, Int32Array);
expect(a.ArrayType).to.equal(Int32Array);
expect(a.real.length).to.equal(10);
expect(a.imag.length).to.equal(10);
expect(a.real[0]).to.equal(0);
expect(a.imag[0]).to.equal(0);
});
it('should contruct from a real array', () => {
const a = new ComplexArray([1, 2]);
assertArrayEquals([1, 2], a.real);
assertArrayEquals([0, 0], a.imag);
});
it('should contruct from a real array with a type', () => {
const a = new ComplexArray([1, 2], Int32Array);
expect(a.ArrayType).to.equal(Int32Array)
assertArrayEquals([1, 2], a.real);
assertArrayEquals([0, 0], a.imag);
});
it('should contruct from another complex array', () => {
const a = new ComplexArray(new ComplexArray([1, 2]));
assertArrayEquals([1, 2], a.real);
assertArrayEquals([0, 0], a.imag);
});
});
describe('`map` method', () => {
it('should alter all values', () => {
const a = new ComplexArray([1, 2]).map((value, i) => {
value.real *= 10;
value.imag = i;
});
assertArrayEquals([10, 20], a.real);
assertArrayEquals([0, 1], a.imag);
});
});
describe('`forEach` method', () => {
it('should touch every value', () => {
const a = new ComplexArray([1, 2]);
a.imag[0] = 4;
a.imag[1] = 8;
let sum = 0;
a.forEach((value, i) => {
sum += value.real;
sum += value.imag;
});
expect(sum).to.equal(15);
});
});
describe('`conjugate` method', () => {
it('should multiply a number', () => {
const a = new ComplexArray([1, 2]);
a.imag[0] = 1;
a.imag[1] = -2;
const b = a.conjugate();
assertArrayEquals([1, 2], b.real);
assertArrayEquals([-1, 2], b.imag);
});
});
describe('`magnitude` method', () => {
it('should give the an array of magnitudes', () => {
const a = new ComplexArray([1, 3]);
a.imag[0] = 0;
a.imag[1] = 4;
assertArrayEquals([1, 5], a.magnitude());
});
it('should return an iterable ArrayType object', () => {
const a = new ComplexArray([1, 2]);
let sum = 0;
a.magnitude().forEach((value, i) => {
sum += value;
});
expect(sum).to.equal(3);
});
});
});
|
/** @jsx h */
import h from '../../helpers/h'
export const schema = {
blocks: {
paragraph: {
marks: [{ type: 'bold' }, { type: 'underline' }],
},
},
}
export const input = (
<value>
<document>
<paragraph>
one <i>two</i> three
</paragraph>
</document>
</value>
)
export const output = (
<value>
<document>
<paragraph>one two three</paragraph>
</document>
</value>
)
|
/* ========================================================================
* DOM-based Routing
* Based on http://goo.gl/EUTi53 by Paul Irish
*
* Only fires on body classes that match. If a body class contains a dash,
* replace the dash with an underscore when adding it to the object below.
*
* .noConflict()
* The routing is enclosed within an anonymous function so that you can
* always reference jQuery with $, even when in .noConflict() mode.
*
* Google CDN, Latest jQuery
* To use the default WordPress version of jQuery, go to lib/config.php and
* remove or comment out: add_theme_support('jquery-cdn');
* ======================================================================== */
(function($) {
// Use this variable to set up the common and page specific functions. If you
// rename this variable, you will also need to rename the namespace below.
var Sage = {
// All pages
'common': {
init: function() {
// JavaScript to be fired on all pages
},
finalize: function() {
// JavaScript to be fired on all pages, after page specific JS is fired
}
},
// Home page
'home': {
init: function() {
// JavaScript to be fired on the home page
},
finalize: function() {
// JavaScript to be fired on the home page, after the init JS
}
},
// About us page, note the change from about-us to about_us.
'about_us': {
init: function() {
// JavaScript to be fired on the about us page
}
}
};
// The routing fires all common scripts, followed by the page specific scripts.
// Add additional events for more control over timing e.g. a finalize event
var UTIL = {
fire: function(func, funcname, args) {
var fire;
var namespace = Sage;
funcname = (funcname === undefined) ? 'init' : funcname;
fire = func !== '';
fire = fire && namespace[func];
fire = fire && typeof namespace[func][funcname] === 'function';
if (fire) {
namespace[func][funcname](args);
}
},
loadEvents: function() {
// Fire common init JS
UTIL.fire('common');
// Fire page-specific init JS, and then finalize JS
$.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
UTIL.fire(classnm);
UTIL.fire(classnm, 'finalize');
});
// Fire common finalize JS
UTIL.fire('common', 'finalize');
}
};
// Load Events
$(document).ready(UTIL.loadEvents);
})(jQuery); // Fully reference jQuery after this point.
$(document).ready(function(){
$("#sidebar-home ul li").addClass( "col-md-3 col-sm-6" );
$("#sidebar-home div").addClass( "clearfix" );
});
|
module.exports = {
before: [function () {
console.log('global beforeAll1');
}, 'alias1'],
'alias1': 'alias2',
'alias2': function () {
console.log('global beforeAll2');
},
'One': function () {
this.sum = 1;
},
'plus one': function () {
this.sum += 1;
},
'equals two': function () {
if (this.sum !== 2) {
throw new Error(this.sum + ' !== 2');
}
}
}; |
exports.__esModule = true;
exports.parseServerOptionsForRunCommand = parseServerOptionsForRunCommand;
exports.parseRunTargets = parseRunTargets;
var _cordova = require('../cordova');
var cordova = babelHelpers.interopRequireWildcard(_cordova);
var _cordovaProjectJs = require('../cordova/project.js');
var _cordovaRunnerJs = require('../cordova/runner.js');
var _cordovaRunTargetsJs = require('../cordova/run-targets.js');
// The architecture used by MDG's hosted servers; it's the architecture used by
// 'meteor deploy'.
var main = require('./main.js');
var _ = require('underscore');
var files = require('../fs/files.js');
var deploy = require('../meteor-services/deploy.js');
var buildmessage = require('../utils/buildmessage.js');
var auth = require('../meteor-services/auth.js');
var authClient = require('../meteor-services/auth-client.js');
var config = require('../meteor-services/config.js');
var Future = require('fibers/future');
var runLog = require('../runners/run-log.js');
var utils = require('../utils/utils.js');
var httpHelpers = require('../utils/http-helpers.js');
var archinfo = require('../utils/archinfo.js');
var catalog = require('../packaging/catalog/catalog.js');
var stats = require('../meteor-services/stats.js');
var Console = require('../console/console.js').Console;
var projectContextModule = require('../project-context.js');
var release = require('../packaging/release.js');
var DEPLOY_ARCH = 'os.linux.x86_64';
// The default port that the development server listens on.
var DEFAULT_PORT = '3000';
// Valid architectures that Meteor officially supports.
var VALID_ARCHITECTURES = {
"os.osx.x86_64": true,
"os.linux.x86_64": true,
"os.linux.x86_32": true,
"os.windows.x86_32": true
};
// __dirname - the location of the current executing file
var __dirnameConverted = files.convertToStandardPath(__dirname);
// Given a site name passed on the command line (eg, 'mysite'), return
// a fully-qualified hostname ('mysite.meteor.com').
//
// This is fairly simple for now. It appends 'meteor.com' if the name
// doesn't contain a dot, and it deletes any trailing dots (the
// technically legal hostname 'mysite.com.' is canonicalized to
// 'mysite.com').
//
// In the future, you should be able to make this default to some
// other domain you control, rather than 'meteor.com'.
var qualifySitename = function (site) {
if (site.indexOf(".") === -1) site = site + ".meteor.com";
while (site.length && site[site.length - 1] === ".") site = site.substring(0, site.length - 1);
return site;
};
// Display a message showing valid Meteor architectures.
var showInvalidArchMsg = function (arch) {
Console.info("Invalid architecture: " + arch);
Console.info("The following are valid Meteor architectures:");
_.each(_.keys(VALID_ARCHITECTURES), function (va) {
Console.info(Console.command(va), Console.options({ indent: 2 }));
});
};
// Utility functions to parse options in run/build/test-packages commands
function parseServerOptionsForRunCommand(options, runTargets) {
var parsedServerUrl = parsePortOption(options.port);
// XXX COMPAT WITH 0.9.2.2 -- the 'mobile-port' option is deprecated
var mobileServerOption = options['mobile-server'] || options['mobile-port'];
var parsedMobileServerUrl = undefined;
if (mobileServerOption) {
parsedMobileServerUrl = parseMobileServerOption(mobileServerOption);
} else {
var isRunOnDeviceRequested = _.any(runTargets, function (runTarget) {
return runTarget.isDevice;
});
parsedMobileServerUrl = detectMobileServerUrl(parsedServerUrl, isRunOnDeviceRequested);
}
return { parsedServerUrl: parsedServerUrl, parsedMobileServerUrl: parsedMobileServerUrl };
}
function parsePortOption(portOption) {
var parsedServerUrl = utils.parseUrl(portOption);
if (!parsedServerUrl.port) {
Console.error("--port must include a port.");
throw new main.ExitWithCode(1);
}
return parsedServerUrl;
}
function parseMobileServerOption(mobileServerOption) {
var optionName = arguments.length <= 1 || arguments[1] === undefined ? 'mobile-server' : arguments[1];
var parsedMobileServerUrl = utils.parseUrl(mobileServerOption, { protocol: 'http://' });
if (!parsedMobileServerUrl.host) {
Console.error('--' + optionName + ' must include a hostname.');
throw new main.ExitWithCode(1);
}
return parsedMobileServerUrl;
}
function detectMobileServerUrl(parsedServerUrl, isRunOnDeviceRequested) {
// If we are running on a device, use the auto-detected IP
if (isRunOnDeviceRequested) {
var myIp = undefined;
try {
myIp = utils.ipAddress();
} catch (error) {
Console.error('Error detecting IP address for mobile app to connect to:\n' + error.message + '\nPlease specify the address that the mobile app should connect\nto with --mobile-server.');
throw new main.ExitWithCode(1);
}
return {
protocol: 'http://',
host: myIp,
port: parsedServerUrl.port
};
} else {
// We are running a simulator, use localhost
return {
protocol: 'http://',
host: 'localhost',
port: parsedServerUrl.port
};
}
}
function parseRunTargets(targets) {
return targets.map(function (target) {
var targetParts = target.split('-');
var platform = targetParts[0];
var isDevice = targetParts[1] === 'device';
if (platform == 'ios') {
return new _cordovaRunTargetsJs.iOSRunTarget(isDevice);
} else if (platform == 'android') {
return new _cordovaRunTargetsJs.AndroidRunTarget(isDevice);
} else {
Console.error('Unknown run target: ' + target);
throw new main.ExitWithCode(1);
}
});
}
;
///////////////////////////////////////////////////////////////////////////////
// options that act like commands
///////////////////////////////////////////////////////////////////////////////
// Prints the Meteor architecture name of this host
main.registerCommand({
name: '--arch',
requiresRelease: false,
pretty: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
Console.rawInfo(archinfo.host() + "\n");
});
//Prints the Meteor log about the versions
main.registerCommand({
name:'--about',
requiresRelease: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options){
if (release.current === null) {
if (!options.appDir) throw new Error("missing release, but not in an app?");
Console.error("This project was created with a checkout of Meteor, rather than an " + "official release, and doesn't have a release number associated with " + "it. You can set its release with " + Console.command("'meteor update'") + ".");
return 1;
}
if (release.current.isCheckout()) {
var gitLog = utils.runGitInCheckout('log', '--format=%h%d', '-n 1').trim();
Console.error("Unreleased, running from a checkout at " + gitLog);
return 1;
}
var dirname = files.convertToStandardPath(__dirname);
var about = files.readFile(files.pathJoin(dirname, 'about.txt'), 'utf8');
console.log(about);
});
// Prints the current release in use. Note that if there is not
// actually a specific release, we print to stderr and exit non-zero,
// while if there is a release we print to stdout and exit zero
// (making this useful to scripts).
// XXX: What does this mean in our new release-free world?
main.registerCommand({
name: '--version',
requiresRelease: false,
pretty: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
if (release.current === null) {
if (!options.appDir) throw new Error("missing release, but not in an app?");
Console.error("This project was created with a checkout of Meteor, rather than an " + "official release, and doesn't have a release number associated with " + "it. You can set its release with " + Console.command("'meteor update'") + ".");
return 1;
}
if (release.current.isCheckout()) {
var gitLog = utils.runGitInCheckout('log', '--format=%h%d', '-n 1').trim();
Console.error("Unreleased, running from a checkout at " + gitLog);
return 1;
}
Console.info(release.current.getDisplayName());
});
// Internal use only. For automated testing.
main.registerCommand({
name: '--long-version',
requiresRelease: false,
pretty: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
if (files.inCheckout()) {
Console.error("checkout");
return 1;
} else if (release.current === null) {
// .meteor/release says "none" but not in a checkout.
Console.error("none");
return 1;
} else {
Console.rawInfo(release.current.name + "\n");
Console.rawInfo(files.getToolsVersion() + "\n");
return 0;
}
});
// Internal use only. For automated testing.
main.registerCommand({
name: '--requires-release',
requiresRelease: true,
pretty: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
return 0;
});
///////////////////////////////////////////////////////////////////////////////
// run
///////////////////////////////////////////////////////////////////////////////
var runCommandOptions = {
requiresApp: true,
maxArgs: Infinity,
options: {
port: { type: String, short: "p", 'default': DEFAULT_PORT },
'mobile-server': { type: String },
// XXX COMPAT WITH 0.9.2.2
'mobile-port': { type: String },
'app-port': { type: String },
'debug-port': { type: String },
production: { type: Boolean },
'raw-logs': { type: Boolean },
settings: { type: String },
test: { type: Boolean, 'default': false },
verbose: { type: Boolean, short: "v" },
// With --once, meteor does not re-run the project if it crashes
// and does not monitor for file changes. Intentionally
// undocumented: intended for automated testing (eg, cli-test.sh),
// not end-user use. #Once
once: { type: Boolean },
// Don't run linter on rebuilds
'no-lint': { type: Boolean },
// Allow the version solver to make breaking changes to the versions
// of top-level dependencies.
'allow-incompatible-update': { type: Boolean }
},
catalogRefresh: new catalog.Refresh.Never()
};
main.registerCommand(_.extend({ name: 'run' }, runCommandOptions), doRunCommand);
function doRunCommand(options) {
Console.setVerbose(!!options.verbose);
// Additional args are interpreted as run targets
var runTargets = parseRunTargets(options.args);
var _parseServerOptionsForRunCommand = parseServerOptionsForRunCommand(options, runTargets);
var parsedServerUrl = _parseServerOptionsForRunCommand.parsedServerUrl;
var parsedMobileServerUrl = _parseServerOptionsForRunCommand.parsedMobileServerUrl;
var projectContext = new projectContextModule.ProjectContext({
projectDir: options.appDir,
allowIncompatibleUpdate: options['allow-incompatible-update'],
lintAppAndLocalPackages: !options['no-lint']
});
main.captureAndExit("=> Errors while initializing project:", function () {
// We're just reading metadata here --- we'll wait to do the full build
// preparation until after we've started listening on the proxy, etc.
projectContext.readProjectMetadata();
});
if (release.explicit) {
if (release.current.name !== projectContext.releaseFile.fullReleaseName) {
console.log("=> Using %s as requested (overriding %s)", release.current.getDisplayName(), projectContext.releaseFile.displayReleaseName);
console.log();
}
}
var appHost = undefined,
appPort = undefined;
if (options['app-port']) {
var appPortMatch = options['app-port'].match(/^(?:(.+):)?([0-9]+)?$/);
if (!appPortMatch) {
Console.error("run: --app-port must be a number or be of the form 'host:port' ", "where port is a number. Try", Console.command("'meteor help run'") + " for help.");
return 1;
}
appHost = appPortMatch[1] || null;
// It's legit to specify `--app-port host:` and still let the port be
// randomized.
appPort = appPortMatch[2] ? parseInt(appPortMatch[2]) : null;
}
if (options['raw-logs']) runLog.setRawLogs(true);
// Velocity testing. Sets up a DDP connection to the app process and
// runs phantomjs.
//
// NOTE: this calls process.exit() when testing is done.
if (options['test']) {
options.once = true;
var serverUrlForVelocity = 'http://' + (parsedServerUrl.host || "localhost") + ':' + parsedServerUrl.port;
var velocity = require('../runners/run-velocity.js');
velocity.runVelocity(serverUrlForVelocity);
}
var cordovaRunner = undefined;
if (!_.isEmpty(runTargets)) {
main.captureAndExit('', 'preparing Cordova project', function () {
var cordovaProject = new _cordovaProjectJs.CordovaProject(projectContext, {
settingsFile: options.settings,
mobileServerUrl: utils.formatUrl(parsedMobileServerUrl) });
cordovaRunner = new _cordovaRunnerJs.CordovaRunner(cordovaProject, runTargets);
cordovaRunner.checkPlatformsForRunTargets();
});
}
var runAll = require('../runners/run-all.js');
return runAll.run({
projectContext: projectContext,
proxyPort: parsedServerUrl.port,
proxyHost: parsedServerUrl.host,
appPort: appPort,
appHost: appHost,
debugPort: options['debug-port'],
settingsFile: options.settings,
buildOptions: {
minifyMode: options.production ? 'production' : 'development',
buildMode: options.production ? 'production' : 'development'
},
rootUrl: process.env.ROOT_URL,
mongoUrl: process.env.MONGO_URL,
oplogUrl: process.env.MONGO_OPLOG_URL,
mobileServerUrl: utils.formatUrl(parsedMobileServerUrl),
once: options.once,
cordovaRunner: cordovaRunner
});
}
///////////////////////////////////////////////////////////////////////////////
// debug
///////////////////////////////////////////////////////////////////////////////
main.registerCommand(_.extend({ name: 'debug' }, runCommandOptions), function (options) {
options['debug-port'] = options['debug-port'] || '5858';
return doRunCommand(options);
});
///////////////////////////////////////////////////////////////////////////////
// shell
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'shell',
requiresRelease: false,
requiresApp: true,
pretty: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
if (!options.appDir) {
Console.error("The " + Console.command("'meteor shell'") + " command must be run", "in a Meteor app directory.");
} else {
var projectContext = new projectContextModule.ProjectContext({
projectDir: options.appDir
});
// Convert to OS path here because shell/server.js doesn't know how to
// convert paths, since it exists in the app and in the tool.
require('../shell-client.js').connect(files.convertToOSPath(projectContext.getMeteorShellDirectory()));
throw new main.WaitForExit();
}
});
///////////////////////////////////////////////////////////////////////////////
// create
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'create',
maxArgs: 1,
options: {
list: { type: Boolean },
example: { type: String },
'package': { type: Boolean }
},
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
// Creating a package is much easier than creating an app, so if that's what
// we are doing, do that first. (For example, we don't springboard to the
// latest release to create a package if we are inside an app)
if (options['package']) {
var packageName = options.args[0];
// No package examples exist yet.
if (options.list && options.example) {
Console.error("No package examples exist at this time.");
Console.error();
throw new main.ShowUsage();
}
if (!packageName) {
Console.error("Please specify the name of the package.");
throw new main.ShowUsage();
}
utils.validatePackageNameOrExit(packageName, { detailedColonExplanation: true });
// When we create a package, avoid introducing a colon into the file system
// by naming the directory after the package name without the prefix.
var fsName = packageName;
if (packageName.indexOf(":") !== -1) {
var split = packageName.split(":");
if (split.length > 2) {
// It may seem like this check should be inside package version parser's
// validatePackageName, but we decided to name test packages like this:
// local-test:prefix:name, so we have to support building packages
// with at least two colons. Therefore we will at least try to
// discourage people from putting a ton of colons in their package names
// here.
Console.error(packageName + ": Package names may not have more than one colon.");
return 1;
}
fsName = split[1];
}
var packageDir;
if (options.appDir) {
packageDir = files.pathResolve(options.appDir, 'packages', fsName);
} else {
packageDir = files.pathResolve(fsName);
}
var inYourApp = options.appDir ? " in your app" : "";
if (files.exists(packageDir)) {
Console.error(packageName + ": Already exists" + inYourApp);
return 1;
}
var transform = function (x) {
var xn = x.replace(/~name~/g, packageName).replace(/~fs-name~/g, fsName);
// If we are running from checkout, comment out the line sourcing packages
// from a release, with the latest release filled in (in case they do want
// to publish later). If we are NOT running from checkout, fill it out
// with the current release.
var relString;
if (release.current.isCheckout()) {
xn = xn.replace(/~cc~/g, "//");
var rel = catalog.official.getDefaultReleaseVersion();
// the no-release case should never happen except in tests.
relString = rel ? rel.version : "no-release";
} else {
xn = xn.replace(/~cc~/g, "");
relString = release.current.getDisplayName({ noPrefix: true });
}
// If we are not in checkout, write the current release here.
return xn.replace(/~release~/g, relString);
};
try {
files.cp_r(files.pathJoin(__dirnameConverted, '..', 'static-assets', 'skel-pack'), packageDir, {
transformFilename: function (f) {
return transform(f);
},
transformContents: function (contents, f) {
if (/(\.html|\.js|\.css)/.test(f)) return new Buffer(transform(contents.toString()));else return contents;
},
ignore: [/^local$/]
});
} catch (err) {
Console.error("Could not create package: " + err.message);
return 1;
}
var displayPackageDir = files.convertToOSPath(files.pathRelative(files.cwd(), packageDir));
// Since the directory can't have colons, the directory name will often not
// match the name of the package exactly, therefore we should tell people
// where it was created.
Console.info(packageName + ": created in", Console.path(displayPackageDir));
return 0;
}
// Suppose you have an app A, and from some directory inside that
// app, you run 'meteor create /my/new/app'. The new app should use
// the latest available Meteor release, not the release that A
// uses. So if we were run from inside an app directory, and the
// user didn't force a release with --release, we need to
// springboard to the correct release and tools version.
//
// (In particular, it's not sufficient to create the new app with
// this version of the tools, and then stamp on the correct release
// at the end.)
if (!release.current.isCheckout() && !release.forced) {
if (release.current.name !== release.latestKnown()) {
throw new main.SpringboardToLatestRelease();
}
}
var exampleDir = files.pathJoin(__dirnameConverted, '..', '..', 'examples');
var examples = _.reject(files.readdir(exampleDir), function (e) {
return e === 'unfinished' || e === 'other' || e[0] === '.';
});
if (options.list) {
Console.info("Available examples:");
_.each(examples, function (e) {
Console.info(Console.command(e), Console.options({ indent: 2 }));
});
Console.info();
Console.info("Create a project from an example with " + Console.command("'meteor create --example <name>'") + ".");
return 0;
};
var appPathAsEntered;
if (options.args.length === 1) appPathAsEntered = options.args[0];else if (options.example) appPathAsEntered = options.example;else throw new main.ShowUsage();
var appPath = files.pathResolve(appPathAsEntered);
if (files.findAppDir(appPath)) {
Console.error("You can't create a Meteor project inside another Meteor project.");
return 1;
}
var appName;
if (appPathAsEntered === "." || appPathAsEntered === "./") {
// If trying to create in current directory
appName = files.pathBasename(files.cwd());
} else {
appName = files.pathBasename(appPath);
}
var transform = function (x) {
return x.replace(/~name~/g, appName);
};
// These file extensions are usually metadata, not app code
var nonCodeFileExts = ['.txt', '.md', '.json', '.sh'];
var destinationHasCodeFiles = false;
// If the directory doesn't exist, it clearly doesn't have any source code
// inside itself
if (files.exists(appPath)) {
destinationHasCodeFiles = _.any(files.readdir(appPath), function thisPathCountsAsAFile(filePath) {
// We don't mind if there are hidden files or directories (this includes
// .git) and we don't need to check for .meteor here because the command
// will fail earlier
var isHidden = /^\./.test(filePath);
if (isHidden) {
// Not code
return false;
}
// We do mind if there are non-hidden directories, because we don't want
// to recursively check everything to do some crazy heuristic to see if
// we should try to creat an app.
var stats = files.stat(filePath);
if (stats.isDirectory()) {
// Could contain code
return true;
}
// Check against our file extension white list
var ext = files.pathExtname(filePath);
if (ext == '' || _.contains(nonCodeFileExts, ext)) {
return false;
}
// Everything not matched above is considered to be possible source code
return true;
});
}
if (options.example) {
if (destinationHasCodeFiles) {
Console.error('When creating an example app, the destination directory can only contain dot-files or files with the following extensions: ' + nonCodeFileExts.join(', ') + '\n');
return 1;
}
if (examples.indexOf(options.example) === -1) {
Console.error(options.example + ": no such example.");
Console.error();
Console.error("List available applications with", Console.command("'meteor create --list'") + ".");
return 1;
} else {
files.cp_r(files.pathJoin(exampleDir, options.example), appPath, {
// We try not to check the project ID into git, but it might still
// accidentally exist and get added (if running from checkout, for
// example). To be on the safe side, explicitly remove the project ID
// from example apps.
ignore: [/^local$/, /^\.id$/]
});
}
} else {
var toIgnore = [/^local$/, /^\.id$/];
if (destinationHasCodeFiles) {
// If there is already source code in the directory, don't copy our
// skeleton app code over it. Just create the .meteor folder and metadata
toIgnore.push(/(\.html|\.js|\.css)/);
}
files.cp_r(files.pathJoin(__dirnameConverted, '..', 'static-assets', 'skel'), appPath, {
transformFilename: function (f) {
return transform(f);
},
transformContents: function (contents, f) {
if (/(\.html|\.js|\.css)/.test(f)) return new Buffer(transform(contents.toString()));else return contents;
},
ignore: toIgnore
});
}
// We are actually working with a new meteor project at this point, so
// set up its context.
var projectContext = new projectContextModule.ProjectContext({
projectDir: appPath,
// Write .meteor/versions even if --release is specified.
alwaysWritePackageMap: true,
// examples come with a .meteor/versions file, but we shouldn't take it
// too seriously
allowIncompatibleUpdate: true
});
main.captureAndExit("=> Errors while creating your project", function () {
projectContext.readProjectMetadata();
if (buildmessage.jobHasMessages()) return;
projectContext.releaseFile.write(release.current.isCheckout() ? "none" : release.current.name);
if (buildmessage.jobHasMessages()) return;
// Any upgrader that is in this version of Meteor doesn't need to be run on
// this project.
var upgraders = require('../upgraders.js');
projectContext.finishedUpgraders.appendUpgraders(upgraders.allUpgraders());
projectContext.prepareProjectForBuild();
});
// No need to display the PackageMapDelta here, since it would include all of
// the packages (or maybe an unpredictable subset based on what happens to be
// in the template's versions file).
var appNameToDisplay = appPathAsEntered === "." ? "current directory" : '\'' + appPathAsEntered + '\'';
var message = 'Created a new Meteor app in ' + appNameToDisplay;
if (options.example && options.example !== appPathAsEntered) {
message += ' (from \'' + options.example + '\' template)';
}
message += ".";
Console.info(message + "\n");
// Print a nice message telling people we created their new app, and what to
// do next.
Console.info("To run your new app:");
if (appPathAsEntered !== ".") {
// Wrap the app path in quotes if it contains spaces
var appPathWithQuotesIfSpaces = appPathAsEntered.indexOf(' ') === -1 ? appPathAsEntered : '\'' + appPathAsEntered + '\'';
// Don't tell people to 'cd .'
Console.info(Console.command("cd " + appPathWithQuotesIfSpaces), Console.options({ indent: 2 }));
}
Console.info(Console.command("meteor"), Console.options({ indent: 2 }));
Console.info("");
Console.info("If you are new to Meteor, try some of the learning resources here:");
Console.info(Console.url("https://www.meteor.com/learn"), Console.options({ indent: 2 }));
Console.info("");
});
///////////////////////////////////////////////////////////////////////////////
// build
///////////////////////////////////////////////////////////////////////////////
var buildCommands = {
minArgs: 1,
maxArgs: 1,
requiresApp: true,
options: {
debug: { type: Boolean },
directory: { type: Boolean },
architecture: { type: String },
'mobile-settings': { type: String },
server: { type: String },
// XXX COMPAT WITH 0.9.2.2
"mobile-port": { type: String },
verbose: { type: Boolean, short: "v" },
'allow-incompatible-update': { type: Boolean }
},
catalogRefresh: new catalog.Refresh.Never()
};
main.registerCommand(_.extend({ name: 'build' }, buildCommands), function (options) {
return buildCommand(options);
});
// Deprecated -- identical functionality to 'build' with one exception: it
// doesn't output a directory with all builds but rather only one tarball with
// server/client programs.
// XXX COMPAT WITH 0.9.1.1
main.registerCommand(_.extend({ name: 'bundle', hidden: true
}, buildCommands), function (options) {
Console.error("This command has been deprecated in favor of " + Console.command("'meteor build'") + ", which allows you to " + "build for multiple platforms and outputs a directory instead of " + "a single tarball. See " + Console.command("'meteor help build'") + " " + "for more information.");
Console.error();
return buildCommand(_.extend(options, { _serverOnly: true }));
});
var buildCommand = function (options) {
Console.setVerbose(!!options.verbose);
// XXX output, to stderr, the name of the file written to (for human
// comfort, especially since we might change the name)
// XXX name the root directory in the bundle based on the basename
// of the file, not a constant 'bundle' (a bit obnoxious for
// machines, but worth it for humans)
// Error handling for options.architecture. We must pass in only one of three
// architectures. See archinfo.js for more information on what the
// architectures are, what they mean, et cetera.
if (options.architecture && !_.has(VALID_ARCHITECTURES, options.architecture)) {
showInvalidArchMsg(options.architecture);
return 1;
}
var bundleArch = options.architecture || archinfo.host();
var projectContext = new projectContextModule.ProjectContext({
projectDir: options.appDir,
serverArchitectures: _.uniq([bundleArch, archinfo.host()]),
allowIncompatibleUpdate: options['allow-incompatible-update']
});
main.captureAndExit("=> Errors while initializing project:", function () {
projectContext.prepareProjectForBuild();
});
projectContext.packageMapDelta.displayOnConsole();
// options['mobile-settings'] is used to set the initial value of
// `Meteor.settings` on mobile apps. Pass it on to options.settings,
// which is used in this command.
if (options['mobile-settings']) {
options.settings = options['mobile-settings'];
}
var appName = files.pathBasename(options.appDir);
var cordovaPlatforms = undefined;
var parsedMobileServerUrl = undefined;
if (!options._serverOnly) {
cordovaPlatforms = projectContext.platformList.getCordovaPlatforms();
if (process.platform === 'win32' && !_.isEmpty(cordovaPlatforms)) {
Console.warn('Can\'t build for mobile on Windows. Skipping the following platforms: ' + cordovaPlatforms.join(", "));
cordovaPlatforms = [];
} else if (process.platform !== 'darwin' && _.contains(cordovaPlatforms, 'ios')) {
cordovaPlatforms = _.without(cordovaPlatforms, 'ios');
Console.warn("Currently, it is only possible to build iOS apps \
on an OS X system.");
}
if (!_.isEmpty(cordovaPlatforms)) {
// XXX COMPAT WITH 0.9.2.2 -- the --mobile-port option is deprecated
var mobileServerOption = options.server || options["mobile-port"];
if (!mobileServerOption) {
// For Cordova builds, require '--server'.
// XXX better error message?
Console.error("Supply the server hostname and port in the --server option " + "for mobile app builds.");
return 1;
}
parsedMobileServerUrl = parseMobileServerOption(mobileServerOption, 'server');
}
} else {
cordovaPlatforms = [];
}
var buildDir = projectContext.getProjectLocalDirectory('build_tar');
var outputPath = files.pathResolve(options.args[0]); // get absolute path
// Unless we're just making a tarball, warn if people try to build inside the
// app directory.
if (options.directory || !_.isEmpty(cordovaPlatforms)) {
var relative = files.pathRelative(options.appDir, outputPath);
// We would like the output path to be outside the app directory, which
// means the first step to getting there is going up a level.
if (relative.substr(0, 3) !== '..' + files.pathSep) {
Console.warn();
Console.labelWarn("The output directory is under your source tree.", "Your generated files may get interpreted as source code!", "Consider building into a different directory instead (" + Console.command("meteor build ../output") + ")", Console.options({ indent: 2 }));
Console.warn();
}
}
var bundlePath = options.directory ? options._serverOnly ? outputPath : files.pathJoin(outputPath, 'bundle') : files.pathJoin(buildDir, 'bundle');
stats.recordPackages({
what: "sdk.bundle",
projectContext: projectContext
});
var bundler = require('../isobuild/bundler.js');
var bundleResult = bundler.bundle({
projectContext: projectContext,
outputPath: bundlePath,
buildOptions: {
minifyMode: options.debug ? 'development' : 'production',
// XXX is this a good idea, or should linux be the default since
// that's where most people are deploying
// default? i guess the problem with using DEPLOY_ARCH as default
// is then 'meteor bundle' with no args fails if you have any local
// packages with binary npm dependencies
serverArch: bundleArch,
buildMode: options.debug ? 'development' : 'production'
},
providePackageJSONForUnavailableBinaryDeps: !!process.env.METEOR_BINARY_DEP_WORKAROUND
});
if (bundleResult.errors) {
Console.error("Errors prevented bundling:");
Console.error(bundleResult.errors.formatMessages());
return 1;
}
if (!options._serverOnly) files.mkdir_p(outputPath);
if (!options.directory) {
main.captureAndExit('', 'creating server tarball', function () {
try {
var outputTar = options._serverOnly ? outputPath : files.pathJoin(outputPath, appName + '.tar.gz');
files.createTarball(files.pathJoin(buildDir, 'bundle'), outputTar);
} catch (err) {
buildmessage.exception(err);
files.rm_recursive(buildDir);
}
});
}
if (!_.isEmpty(cordovaPlatforms)) {
(function () {
var cordovaProject = undefined;
main.captureAndExit('', function () {
buildmessage.enterJob({ title: "preparing Cordova project" }, function () {
cordovaProject = new _cordovaProjectJs.CordovaProject(projectContext, {
settingsFile: options.settings,
mobileServerUrl: utils.formatUrl(parsedMobileServerUrl) });
var plugins = cordova.pluginVersionsFromStarManifest(bundleResult.starManifest);
cordovaProject.prepareFromAppBundle(bundlePath, plugins);
});
for (var _iterator = cordovaPlatforms, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
if (_isArray) {
if (_i >= _iterator.length) break;
platform = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
platform = _i.value;
}
buildmessage.enterJob({ title: 'building Cordova app for ' + cordova.displayNameForPlatform(platform) }, function () {
var buildOptions = [];
if (!options.debug) buildOptions.push('--release');
cordovaProject.buildForPlatform(platform, buildOptions);
var buildPath = files.pathJoin(projectContext.getProjectLocalDirectory('cordova-build'), 'platforms', platform);
var platformOutputPath = files.pathJoin(outputPath, platform);
files.cp_r(buildPath, files.pathJoin(platformOutputPath, 'project'));
if (platform === 'ios') {
files.writeFile(files.pathJoin(platformOutputPath, 'README'), 'This is an auto-generated XCode project for your iOS application.\n\nInstructions for publishing your iOS app to App Store can be found at:\nhttps://github.com/meteor/meteor/wiki/How-to-submit-your-iOS-app-to-App-Store\n', "utf8");
} else if (platform === 'android') {
var apkPath = files.pathJoin(buildPath, 'build/outputs/apk', options.debug ? 'android-debug.apk' : 'android-release-unsigned.apk');
if (files.exists(apkPath)) {
files.copyFile(apkPath, files.pathJoin(platformOutputPath, options.debug ? 'debug.apk' : 'release-unsigned.apk'));
}
files.writeFile(files.pathJoin(platformOutputPath, 'README'), 'This is an auto-generated Gradle project for your Android application.\n\nInstructions for publishing your Android app to Play Store can be found at:\nhttps://github.com/meteor/meteor/wiki/How-to-submit-your-Android-app-to-Play-Store\n', "utf8");
}
});
}
});
})();
}
files.rm_recursive(buildDir);
};
///////////////////////////////////////////////////////////////////////////////
// lint
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'lint',
maxArgs: 0,
requiresAppOrPackage: true,
options: {
'allow-incompatible-updates': { type: Boolean }
},
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
var packageDir = options.packageDir;
var appDir = options.appDir;
var projectContext = null;
// if the goal is to lint the package, don't include the whole app
if (packageDir) {
// similar to `meteor publish`, create a fake project
var tempProjectDir = files.mkdtemp('meteor-package-build');
projectContext = new projectContextModule.ProjectContext({
projectDir: tempProjectDir,
explicitlyAddedLocalPackageDirs: [packageDir],
packageMapFilename: files.pathJoin(packageDir, '.versions'),
alwaysWritePackageMap: true,
forceIncludeCordovaUnibuild: true,
allowIncompatibleUpdate: options['allow-incompatible-update'],
lintPackageWithSourceRoot: packageDir
});
main.captureAndExit("=> Errors while setting up package:", function () {
return(
// Read metadata and initialize catalog.
projectContext.initializeCatalog()
);
});
var versionRecord = projectContext.localCatalog.getVersionBySourceRoot(packageDir);
if (!versionRecord) {
throw Error("explicitly added local package dir missing?");
}
var packageName = versionRecord.packageName;
var constraint = utils.parsePackageConstraint(packageName);
projectContext.projectConstraintsFile.removeAllPackages();
projectContext.projectConstraintsFile.addConstraints([constraint]);
}
// linting the app
if (!projectContext && appDir) {
projectContext = new projectContextModule.ProjectContext({
projectDir: appDir,
serverArchitectures: [archinfo.host()],
allowIncompatibleUpdate: options['allow-incompatible-update'],
lintAppAndLocalPackages: true
});
}
main.captureAndExit("=> Errors prevented the build:", function () {
projectContext.prepareProjectForBuild();
});
var bundlePath = projectContext.getProjectLocalDirectory('build');
var bundler = require('../isobuild/bundler.js');
var bundle = bundler.bundle({
projectContext: projectContext,
outputPath: null,
buildOptions: {
minifyMode: 'development'
}
});
var displayName = options.packageDir ? 'package' : 'app';
if (bundle.errors) {
Console.error('=> Errors building your ' + displayName + ':\n\n' + bundle.errors.formatMessages());
throw new main.ExitWithCode(2);
}
if (bundle.warnings) {
Console.warn(bundle.warnings.formatMessages());
return 1;
}
return 0;
});
///////////////////////////////////////////////////////////////////////////////
// mongo
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'mongo',
maxArgs: 1,
options: {
url: { type: Boolean, short: 'U' }
},
requiresApp: function (options) {
return options.args.length === 0;
},
pretty: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
var mongoUrl;
var usedMeteorAccount = false;
if (options.args.length === 0) {
// localhost mode
var findMongoPort = require('../runners/run-mongo.js').findMongoPort;
var mongoPort = findMongoPort(options.appDir);
// XXX detect the case where Meteor is running, but MONGO_URL was
// specified?
if (!mongoPort) {
Console.info("mongo: Meteor isn't running a local MongoDB server.");
Console.info();
Console.info('This command only works while Meteor is running your application locally. Start your application first with \'meteor\' and then run this command in a new terminal. This error will also occur if you asked Meteor to use a different MongoDB server with $MONGO_URL when you ran your application.');
Console.info();
Console.info('If you\'re trying to connect to the database of an app you deployed with ' + Console.command("'meteor deploy'") + ', specify your site\'s name as an argument to this command.');
return 1;
}
mongoUrl = "mongodb://127.0.0.1:" + mongoPort + "/meteor";
} else {
// remote mode
var site = qualifySitename(options.args[0]);
config.printUniverseBanner();
mongoUrl = deploy.temporaryMongoUrl(site);
usedMeteorAccount = true;
if (!mongoUrl)
// temporaryMongoUrl() will have printed an error message
return 1;
}
if (options.url) {
console.log(mongoUrl);
} else {
if (usedMeteorAccount) auth.maybePrintRegistrationLink();
process.stdin.pause();
var runMongo = require('../runners/run-mongo.js');
runMongo.runMongoShell(mongoUrl);
throw new main.WaitForExit();
}
});
///////////////////////////////////////////////////////////////////////////////
// reset
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'reset',
// Doesn't actually take an argument, but we want to print an custom
// error message if they try to pass one.
maxArgs: 1,
requiresApp: true,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
if (options.args.length !== 0) {
Console.error("meteor reset only affects the locally stored database.");
Console.error();
Console.error("To reset a deployed application use");
Console.error(Console.command("meteor deploy --delete appname"), Console.options({ indent: 2 }));
Console.error("followed by");
Console.error(Console.command("meteor deploy appname"), Console.options({ indent: 2 }));
return 1;
}
// XXX detect the case where Meteor is running the app, but
// MONGO_URL was set, so we don't see a Mongo process
var findMongoPort = require('../runners/run-mongo.js').findMongoPort;
var isRunning = !!findMongoPort(options.appDir);
if (isRunning) {
Console.error("reset: Meteor is running.");
Console.error();
Console.error("This command does not work while Meteor is running your application.", "Exit the running Meteor development server.");
return 1;
}
var localDir = files.pathJoin(options.appDir, '.meteor', 'local');
files.rm_recursive(localDir);
Console.info("Project reset.");
});
///////////////////////////////////////////////////////////////////////////////
// deploy
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'deploy',
minArgs: 1,
maxArgs: 1,
options: {
'delete': { type: Boolean, short: 'D' },
debug: { type: Boolean },
settings: { type: String },
// No longer supported, but we still parse it out so that we can
// print a custom error message.
password: { type: String },
// Override architecture to deploy whatever stuff we have locally, even if
// it contains binary packages that should be incompatible. A hack to allow
// people to deploy from checkout or do other weird shit. We are not
// responsible for the consequences.
'override-architecture-with-local': { type: Boolean },
'allow-incompatible-update': { type: Boolean }
},
requiresApp: function (options) {
return !options['delete'];
},
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
var site = qualifySitename(options.args[0]);
config.printUniverseBanner();
if (options['delete']) {
return deploy.deleteApp(site);
}
if (options.password) {
Console.error("Setting passwords on apps is no longer supported. Now there are " + "user accounts and your apps are associated with your account so " + "that only you (and people you designate) can access them. See the " + Console.command("'meteor claim'") + " and " + Console.command("'meteor authorized'") + " commands.");
return 1;
}
var loggedIn = auth.isLoggedIn();
if (!loggedIn) {
Console.error("To instantly deploy your app on a free testing server,", "just enter your email address!");
Console.error();
if (!auth.registerOrLogIn()) return 1;
}
// Override architecture iff applicable.
var buildArch = DEPLOY_ARCH;
if (options['override-architecture-with-local']) {
Console.warn();
Console.labelWarn("OVERRIDING DEPLOY ARCHITECTURE WITH LOCAL ARCHITECTURE.", "If your app contains binary code, it may break in unexpected " + "and terrible ways.");
buildArch = archinfo.host();
}
var projectContext = new projectContextModule.ProjectContext({
projectDir: options.appDir,
serverArchitectures: _.uniq([buildArch, archinfo.host()]),
allowIncompatibleUpdate: options['allow-incompatible-update']
});
main.captureAndExit("=> Errors while initializing project:", function () {
projectContext.prepareProjectForBuild();
});
projectContext.packageMapDelta.displayOnConsole();
var buildOptions = {
minifyMode: options.debug ? 'development' : 'production',
buildMode: options.debug ? 'development' : 'production',
serverArch: buildArch
};
var deployResult = deploy.bundleAndDeploy({
projectContext: projectContext,
site: site,
settingsFile: options.settings,
buildOptions: buildOptions
});
if (deployResult === 0) {
auth.maybePrintRegistrationLink({
leadingNewline: true,
// If the user was already logged in at the beginning of the
// deploy, then they've already been prompted to set a password
// at least once before, so we use a slightly different message.
firstTime: !loggedIn
});
}
return deployResult;
});
///////////////////////////////////////////////////////////////////////////////
// logs
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'logs',
minArgs: 1,
maxArgs: 1,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
var site = qualifySitename(options.args[0]);
return deploy.logs(site);
});
///////////////////////////////////////////////////////////////////////////////
// authorized
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'authorized',
minArgs: 1,
maxArgs: 1,
options: {
add: { type: String, short: "a" },
remove: { type: String, short: "r" },
list: { type: Boolean }
},
pretty: function (options) {
// pretty if we're mutating; plain if we're listing (which is more likely to
// be used by scripts)
return options.add || options.remove;
},
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
if (options.add && options.remove) {
Console.error("Sorry, you can only add or remove one user at a time.");
return 1;
}
if ((options.add || options.remove) && options.list) {
Console.error("Sorry, you can't change the users at the same time as", "you're listing them.");
return 1;
}
config.printUniverseBanner();
auth.pollForRegistrationCompletion();
var site = qualifySitename(options.args[0]);
if (!auth.isLoggedIn()) {
Console.error("You must be logged in for that. Try " + Console.command("'meteor login'"));
return 1;
}
if (options.add) return deploy.changeAuthorized(site, "add", options.add);else if (options.remove) return deploy.changeAuthorized(site, "remove", options.remove);else return deploy.listAuthorized(site);
});
///////////////////////////////////////////////////////////////////////////////
// claim
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'claim',
minArgs: 1,
maxArgs: 1,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
config.printUniverseBanner();
auth.pollForRegistrationCompletion();
var site = qualifySitename(options.args[0]);
if (!auth.isLoggedIn()) {
Console.error("You must be logged in to claim sites. Use " + Console.command("'meteor login'") + " to log in. If you don't have a " + "Meteor developer account yet, create one by clicking " + Console.command("'Sign in'") + " and then " + Console.command("'Create account'") + " at www.meteor.com.");
Console.error();
return 1;
}
return deploy.claim(site);
});
///////////////////////////////////////////////////////////////////////////////
// test-packages
///////////////////////////////////////////////////////////////////////////////
//
// Test your local packages.
//
main.registerCommand({
name: 'test-packages',
maxArgs: Infinity,
options: {
port: { type: String, short: "p", 'default': DEFAULT_PORT },
'mobile-server': { type: String },
// XXX COMPAT WITH 0.9.2.2
'mobile-port': { type: String },
'debug-port': { type: String },
deploy: { type: String },
production: { type: Boolean },
settings: { type: String },
velocity: { type: Boolean },
verbose: { type: Boolean, short: "v" },
// Undocumented. See #Once
once: { type: Boolean },
// Undocumented. To ensure that QA covers both
// PollingObserveDriver and OplogObserveDriver, this option
// disables oplog for tests. (It still creates a replset, it just
// doesn't do oplog tailing.)
'disable-oplog': { type: Boolean },
// Undocumented flag to use a different test driver.
'driver-package': { type: String, 'default': 'test-in-browser' },
// Sets the path of where the temp app should be created
'test-app-path': { type: String },
// Undocumented, runs tests under selenium
'selenium': { type: Boolean },
'selenium-browser': { type: String },
// Undocumented. Usually we just show a banner saying 'Tests' instead of
// the ugly path to the temporary test directory, but if you actually want
// to see it you can ask for it.
'show-test-app-path': { type: Boolean },
// hard-coded options with all known Cordova platforms
ios: { type: Boolean },
'ios-device': { type: Boolean },
android: { type: Boolean },
'android-device': { type: Boolean },
// This could theoretically be useful/necessary in conjunction with
// --test-app-path.
'allow-incompatible-update': { type: Boolean },
// Don't print linting messages for tested packages
'no-lint': { type: Boolean },
// allow excluding packages when testing all packages.
// should be a comma-separated list of package names.
'exclude': { type: String }
},
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
Console.setVerbose(!!options.verbose);
var runTargets = parseRunTargets(_.intersection(Object.keys(options), ['ios', 'ios-device', 'android', 'android-device']));
var _parseServerOptionsForRunCommand2 = parseServerOptionsForRunCommand(options, runTargets);
var parsedServerUrl = _parseServerOptionsForRunCommand2.parsedServerUrl;
var parsedMobileServerUrl = _parseServerOptionsForRunCommand2.parsedMobileServerUrl;
// Find any packages mentioned by a path instead of a package name. We will
// load them explicitly into the catalog.
var packagesByPath = _.filter(options.args, function (p) {
return p.indexOf('/') !== -1;
});
// Make a temporary app dir (based on the test runner app). This will be
// cleaned up on process exit. Using a temporary app dir means that we can
// run multiple "test-packages" commands in parallel without them stomping
// on each other.
var testRunnerAppDir = options['test-app-path'] || files.mkdtemp('meteor-test-run');
// Download packages for our architecture, and for the deploy server's
// architecture if we're deploying.
var serverArchitectures = [archinfo.host()];
if (options.deploy && DEPLOY_ARCH !== archinfo.host()) serverArchitectures.push(DEPLOY_ARCH);
// XXX Because every run uses a new app with its own IsopackCache directory,
// this always does a clean build of all packages. Maybe we can speed up
// repeated test-packages calls with some sort of shared or semi-shared
// isopack cache that's specific to test-packages? See #3012.
var projectContext = new projectContextModule.ProjectContext({
projectDir: testRunnerAppDir,
// If we're currently in an app, we still want to use the real app's
// packages subdirectory, not the test runner app's empty one.
projectDirForLocalPackages: options.appDir,
explicitlyAddedLocalPackageDirs: packagesByPath,
serverArchitectures: serverArchitectures,
allowIncompatibleUpdate: options['allow-incompatible-update'],
lintAppAndLocalPackages: !options['no-lint']
});
main.captureAndExit("=> Errors while setting up tests:", function () {
// Read metadata and initialize catalog.
projectContext.initializeCatalog();
});
// Overwrite .meteor/release.
projectContext.releaseFile.write(release.current.isCheckout() ? "none" : release.current.name);
var packagesToAdd = getTestPackageNames(projectContext, options.args);
// filter out excluded packages
var excludedPackages = options.exclude && options.exclude.split(',');
if (excludedPackages) {
packagesToAdd = _.filter(packagesToAdd, function (p) {
return !_.some(excludedPackages, function (excluded) {
return p.replace(/^local-test:/, '') === excluded;
});
});
}
// Use the driver package
// Also, add `autoupdate` so that you don't have to manually refresh the tests
packagesToAdd.unshift("autoupdate", options['driver-package']);
var constraintsToAdd = _.map(packagesToAdd, function (p) {
return utils.parsePackageConstraint(p);
});
// Add the packages to our in-memory representation of .meteor/packages. (We
// haven't yet resolved constraints, so this will affect constraint
// resolution.) This will get written to disk once we prepareProjectForBuild,
// either in the Cordova code below, right before deploying below, or in the
// app runner. (Note that removeAllPackages removes any comments from
// .meteor/packages, but that's OK since this isn't a real user project.)
projectContext.projectConstraintsFile.removeAllPackages();
projectContext.projectConstraintsFile.addConstraints(constraintsToAdd);
// Write these changes to disk now, so that if the first attempt to prepare
// the project for build hits errors, we don't lose them on
// projectContext.reset.
projectContext.projectConstraintsFile.writeIfModified();
// The rest of the projectContext preparation process will happen inside the
// runner, once the proxy is listening. The changes we made were persisted to
// disk, so projectContext.reset won't make us forget anything.
var cordovaRunner = undefined;
if (!_.isEmpty(runTargets)) {
main.captureAndExit('', 'preparing Cordova project', function () {
var cordovaProject = new _cordovaProjectJs.CordovaProject(projectContext, {
settingsFile: options.settings,
mobileServerUrl: utils.formatUrl(parsedMobileServerUrl) });
cordovaRunner = new _cordovaRunnerJs.CordovaRunner(cordovaProject, runTargets);
projectContext.platformList.write(cordovaRunner.platformsForRunTargets);
cordovaRunner.checkPlatformsForRunTargets();
});
}
options.cordovaRunner = cordovaRunner;
if (options.velocity) {
var serverUrlForVelocity = 'http://' + (parsedServerUrl.host || "localhost") + ':' + parsedServerUrl.port;
var velocity = require('../runners/run-velocity.js');
velocity.runVelocity(serverUrlForVelocity);
}
return runTestAppForPackages(projectContext, _.extend(options, { mobileServerUrl: utils.formatUrl(parsedMobileServerUrl) }));
});
// Returns the "local-test:*" package names for the given package names (or for
// all local packages if packageNames is empty/unspecified).
var getTestPackageNames = function (projectContext, packageNames) {
var packageNamesSpecifiedExplicitly = !_.isEmpty(packageNames);
if (_.isEmpty(packageNames)) {
// If none specified, test all local packages. (We don't have tests for
// non-local packages.)
packageNames = projectContext.localCatalog.getAllPackageNames();
}
var testPackages = [];
main.captureAndExit("=> Errors while collecting tests:", function () {
_.each(packageNames, function (p) {
buildmessage.enterJob("trying to test package `" + p + "`", function () {
// If it's a package name, look it up the normal way.
if (p.indexOf('/') === -1) {
if (p.indexOf('@') !== -1) {
buildmessage.error("You may not specify versions for local packages: " + p);
return; // recover by ignoring
}
// Check to see if this is a real local package, and if it is a real
// local package, if it has tests.
var version = projectContext.localCatalog.getLatestVersion(p);
if (!version) {
buildmessage.error("Not a known local package, cannot test");
} else if (version.testName) {
testPackages.push(version.testName);
} else if (packageNamesSpecifiedExplicitly) {
// It's only an error to *ask* to test a package with no tests, not
// to come across a package with no tests when you say "test all
// packages".
buildmessage.error("Package has no tests");
}
} else {
// Otherwise, it's a directory; find it by source root.
version = projectContext.localCatalog.getVersionBySourceRoot(files.pathResolve(p));
if (!version) {
throw Error("should have been caught when initializing catalog?");
}
if (version.testName) {
testPackages.push(version.testName);
}
// It is not an error to mention a package by directory that is a
// package but has no tests; this means you can run `meteor
// test-packages $APP/packages/*` without having to worry about the
// packages that don't have tests.
}
});
});
});
return testPackages;
};
var runTestAppForPackages = function (projectContext, options) {
var buildOptions = {
minifyMode: options.production ? 'production' : 'development',
buildMode: options.production ? 'production' : 'development'
};
if (options.deploy) {
// Run the constraint solver and build local packages.
main.captureAndExit("=> Errors while initializing project:", function () {
projectContext.prepareProjectForBuild();
});
// No need to display the PackageMapDelta here, since it would include all
// of the packages!
buildOptions.serverArch = DEPLOY_ARCH;
return deploy.bundleAndDeploy({
projectContext: projectContext,
site: options.deploy,
settingsFile: options.settings,
buildOptions: buildOptions,
recordPackageUsage: false
});
} else {
var runAll = require('../runners/run-all.js');
return runAll.run({
projectContext: projectContext,
proxyPort: options.port,
debugPort: options['debug-port'],
disableOplog: options['disable-oplog'],
settingsFile: options.settings,
banner: options['show-test-app-path'] ? null : "Tests",
buildOptions: buildOptions,
rootUrl: process.env.ROOT_URL,
mongoUrl: process.env.MONGO_URL,
oplogUrl: process.env.MONGO_OPLOG_URL,
mobileServerUrl: options.mobileServerUrl,
once: options.once,
recordPackageUsage: false,
selenium: options.selenium,
seleniumBrowser: options['selenium-browser'],
cordovaRunner: options.cordovaRunner,
// On the first run, we shouldn't display the delta between "no packages
// in the temp app" and "all the packages we're testing". If we make
// changes and reload, though, it's fine to display them.
omitPackageMapDeltaDisplayOnFirstRun: true
});
}
};
///////////////////////////////////////////////////////////////////////////////
// rebuild
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'rebuild',
maxArgs: Infinity,
hidden: true,
requiresApp: true,
catalogRefresh: new catalog.Refresh.Never(),
'allow-incompatible-update': { type: Boolean }
}, function (options) {
var projectContextModule = require('../project-context.js');
var projectContext = new projectContextModule.ProjectContext({
projectDir: options.appDir,
forceRebuildPackages: options.args.length ? options.args : true,
allowIncompatibleUpdate: options['allow-incompatible-update']
});
main.captureAndExit("=> Errors while rebuilding packages:", function () {
projectContext.prepareProjectForBuild();
});
projectContext.packageMapDelta.displayOnConsole();
Console.info("Packages rebuilt.");
});
///////////////////////////////////////////////////////////////////////////////
// login
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'login',
options: {
email: { type: Boolean }
},
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
return auth.loginCommand(_.extend({
overwriteExistingToken: true
}, options));
});
///////////////////////////////////////////////////////////////////////////////
// logout
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'logout',
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
return auth.logoutCommand(options);
});
///////////////////////////////////////////////////////////////////////////////
// whoami
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'whoami',
catalogRefresh: new catalog.Refresh.Never(),
pretty: false
}, function (options) {
return auth.whoAmICommand(options);
});
///////////////////////////////////////////////////////////////////////////////
// organizations
///////////////////////////////////////////////////////////////////////////////
var loggedInAccountsConnectionOrPrompt = function (action) {
var token = auth.getSessionToken(config.getAccountsDomain());
if (!token) {
Console.error("You must be logged in to " + action + ".");
auth.doUsernamePasswordLogin({ retry: true });
Console.info();
}
token = auth.getSessionToken(config.getAccountsDomain());
var conn = auth.loggedInAccountsConnection(token);
if (conn === null) {
// Server rejected our token.
Console.error("You must be logged in to " + action + ".");
auth.doUsernamePasswordLogin({ retry: true });
Console.info();
token = auth.getSessionToken(config.getAccountsDomain());
conn = auth.loggedInAccountsConnection(token);
}
return conn;
};
// List the organizations of which the current user is a member.
main.registerCommand({
name: 'admin list-organizations',
minArgs: 0,
maxArgs: 0,
pretty: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
var token = auth.getSessionToken(config.getAccountsDomain());
if (!token) {
Console.error("You must be logged in to list your organizations.");
auth.doUsernamePasswordLogin({ retry: true });
Console.info();
}
var url = config.getAccountsApiUrl() + "/organizations";
try {
var result = httpHelpers.request({
url: url,
method: "GET",
useSessionHeader: true,
useAuthHeader: true
});
var body = JSON.parse(result.body);
} catch (err) {
Console.error("Error listing organizations.");
return 1;
}
if (result.response.statusCode === 401 && body && body.error === "invalid_credential") {
Console.error("You must be logged in to list your organizations.");
// XXX It would be nice to do a username/password prompt here like
// we do for the other orgs commands.
return 1;
}
if (result.response.statusCode !== 200 || !body || !body.organizations) {
Console.error("Error listing organizations.");
return 1;
}
if (body.organizations.length === 0) {
Console.info("You are not a member of any organizations.");
} else {
Console.rawInfo(_.pluck(body.organizations, "name").join("\n") + "\n");
}
return 0;
});
main.registerCommand({
name: 'admin members',
minArgs: 1,
maxArgs: 1,
options: {
add: { type: String },
remove: { type: String },
list: { type: Boolean }
},
pretty: function (options) {
// pretty if we're mutating; plain if we're listing (which is more likely to
// be used by scripts)
return options.add || options.remove;
},
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
if (options.add && options.remove) {
Console.error("Sorry, you can only add or remove one member at a time.");
throw new main.ShowUsage();
}
config.printUniverseBanner();
var username = options.add || options.remove;
var conn = loggedInAccountsConnectionOrPrompt(username ? "edit organizations" : "show an organization's members");
if (username) {
// Adding or removing members
try {
conn.call(options.add ? "addOrganizationMember" : "removeOrganizationMember", options.args[0], username);
} catch (err) {
Console.error("Error " + (options.add ? "adding" : "removing") + " member: " + err.reason);
return 1;
}
Console.info(username + " " + (options.add ? "added to" : "removed from") + " organization " + options.args[0] + ".");
} else {
// Showing the members of an org
try {
var result = conn.call("showOrganization", options.args[0]);
} catch (err) {
Console.error("Error showing organization: " + err.reason);
return 1;
}
var members = _.pluck(result, "username");
Console.rawInfo(members.join("\n") + "\n");
}
return 0;
});
///////////////////////////////////////////////////////////////////////////////
// self-test
///////////////////////////////////////////////////////////////////////////////
// XXX we should find a way to make self-test fully self-contained, so that it
// ignores "packageDirs" (ie, it shouldn't fail just because you happen to be
// sitting in an app with packages that don't build)
main.registerCommand({
name: 'self-test',
minArgs: 0,
maxArgs: 1,
options: {
changed: { type: Boolean },
'force-online': { type: Boolean },
slow: { type: Boolean },
galaxy: { type: Boolean },
browserstack: { type: Boolean },
history: { type: Number },
list: { type: Boolean },
file: { type: String },
exclude: { type: String }
},
hidden: true,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
if (!files.inCheckout()) {
Console.error("self-test is only supported running from a checkout");
return 1;
}
var selftest = require('../tool-testing/selftest.js');
// Auto-detect whether to skip 'net' tests, unless --force-online is passed.
var offline = false;
if (!options['force-online']) {
try {
require('../utils/http-helpers.js').getUrl("http://www.google.com/");
} catch (e) {
if (e instanceof files.OfflineError) offline = true;
}
}
var compileRegexp = function (str) {
try {
return new RegExp(str);
} catch (e) {
if (!(e instanceof SyntaxError)) throw e;
Console.error("Bad regular expression: " + str);
return null;
}
};
var testRegexp = undefined;
if (options.args.length) {
testRegexp = compileRegexp(options.args[0]);
if (!testRegexp) {
return 1;
}
}
var fileRegexp = undefined;
if (options.file) {
fileRegexp = compileRegexp(options.file);
if (!fileRegexp) {
return 1;
}
}
var excludeRegexp = undefined;
if (options.exclude) {
excludeRegexp = compileRegexp(options.exclude);
if (!excludeRegexp) {
return 1;
}
}
if (options.list) {
selftest.listTests({
onlyChanged: options.changed,
offline: offline,
includeSlowTests: options.slow,
galaxyOnly: options.galaxy,
testRegexp: testRegexp,
fileRegexp: fileRegexp
});
return 0;
}
var clients = {
browserstack: options.browserstack
};
return selftest.runTests({
// filtering options
onlyChanged: options.changed,
offline: offline,
includeSlowTests: options.slow,
galaxyOnly: options.galaxy,
testRegexp: testRegexp,
fileRegexp: fileRegexp,
excludeRegexp: excludeRegexp,
// other options
historyLines: options.history,
clients: clients
});
});
///////////////////////////////////////////////////////////////////////////////
// list-sites
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'list-sites',
minArgs: 0,
maxArgs: 0,
pretty: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
auth.pollForRegistrationCompletion();
if (!auth.isLoggedIn()) {
Console.error("You must be logged in for that. Try " + Console.command("'meteor login'") + ".");
return 1;
}
return deploy.listSites();
});
///////////////////////////////////////////////////////////////////////////////
// admin get-machine
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'admin get-machine',
minArgs: 1,
maxArgs: 1,
options: {
json: { type: Boolean },
verbose: { type: Boolean, short: "v" },
// By default, we give you a machine for 5 minutes. You can request up to
// 15. (MDG can reserve machines for longer than that.)
minutes: { type: Number }
},
pretty: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
// Check that we are asking for a valid architecture.
var arch = options.args[0];
if (!_.has(VALID_ARCHITECTURES, arch)) {
showInvalidArchMsg(arch);
return 1;
}
// Set the minutes. We will check validity on the server.
var minutes = options.minutes || 5;
// In verbose mode, we let you know what is going on.
var maybeLog = function (string) {
if (options.verbose) {
Console.info(string);
}
};
try {
maybeLog("Logging into the get-machines server ...");
var conn = authClient.loggedInConnection(config.getBuildFarmUrl(), config.getBuildFarmDomain(), "build-farm");
} catch (err) {
authClient.handleConnectionError(err, "get-machines server");
return 1;
}
try {
maybeLog("Reserving machine ...");
// The server returns to us an object with the following keys:
// username & sshKey : use this to log in.
// host: what you login into
// port: port you should use
// hostKey: RSA key to compare for safety.
var ret = conn.call('createBuildServer', arch, minutes);
} catch (err) {
authClient.handleConnectionError(err, "build farm");
return 1;
}
conn.close();
// Possibly, the user asked us to return a JSON of the data and is going to process it
// themselves. In that case, let's do that and exit.
if (options.json) {
var retJson = {
'username': ret.username,
'host': ret.host,
'port': ret.port,
'key': ret.sshKey,
'hostKey': ret.hostKey
};
Console.rawInfo(JSON.stringify(retJson, null, 2) + "\n");
return 0;
}
// Record the SSH Key in a temporary file on disk and give it the permissions
// that ssh-agent requires it to have.
var tmpDir = files.mkdtemp('meteor-ssh-');
var idpath = tmpDir + '/id';
maybeLog("Writing ssh key to " + idpath);
files.writeFile(idpath, ret.sshKey, { encoding: 'utf8', mode: 256 });
// Add the known host key to a custom known hosts file.
var hostpath = tmpDir + '/host';
var addendum = ret.host + " " + ret.hostKey + "\n";
maybeLog("Writing host key to " + hostpath);
files.writeFile(hostpath, addendum, 'utf8');
// Finally, connect to the machine.
var login = ret.username + "@" + ret.host;
var maybeVerbose = options.verbose ? "-v" : "-q";
var connOptions = [login, "-i" + idpath, "-p" + ret.port, "-oUserKnownHostsFile=" + hostpath, maybeVerbose];
var printOptions = connOptions.join(' ');
maybeLog("Connecting: " + Console.command("ssh " + printOptions));
var child_process = require('child_process');
var future = new Future();
if (arch.match(/win/)) {
// The ssh output from Windows machines is buggy, it can overlay your
// existing output on the top of the screen which is very ugly. Force the
// screen cleaning to assist.
Console.clear();
}
var sshCommand = child_process.spawn("ssh", connOptions, { stdio: 'inherit' }); // Redirect spawn stdio to process
sshCommand.on('error', function (err) {
if (err.code === "ENOENT") {
if (process.platform === "win32") {
Console.error("Could not find the `ssh` command in your PATH.", "Please read this page about using the get-machine command on Windows:", Console.url("https://github.com/meteor/meteor/wiki/Accessing-Meteor-provided-build-machines-from-Windows"));
} else {
Console.error("Could not find the `ssh` command in your PATH.");
}
future['return'](1);
}
});
sshCommand.on('exit', function (code, signal) {
if (signal) {
// XXX: We should process the signal in some way, but I am not sure we
// care right now.
future['return'](1);
} else {
future['return'](code);
}
});
var sshEnd = future.wait();
return sshEnd;
});
///////////////////////////////////////////////////////////////////////////////
// admin progressbar-test
///////////////////////////////////////////////////////////////////////////////
// A test command to print a progressbar. Useful for manual testing.
main.registerCommand({
name: 'admin progressbar-test',
options: {
secs: { type: Number, 'default': 20 },
spinner: { type: Boolean, 'default': false }
},
hidden: true,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
buildmessage.enterJob({ title: "A test progressbar" }, function () {
var doneFuture = new Future();
var progress = buildmessage.getCurrentProgressTracker();
var totalProgress = { current: 0, end: options.secs, done: false };
var i = 0;
var n = options.secs;
if (options.spinner) {
totalProgress.end = undefined;
}
var updateProgress = function () {
i++;
if (!options.spinner) {
totalProgress.current = i;
}
if (i === n) {
totalProgress.done = true;
progress.reportProgress(totalProgress);
doneFuture['return']();
} else {
progress.reportProgress(totalProgress);
setTimeout(updateProgress, 1000);
}
};
setTimeout(updateProgress);
doneFuture.wait();
});
});
///////////////////////////////////////////////////////////////////////////////
// dummy
///////////////////////////////////////////////////////////////////////////////
// Dummy test command. Used for automated testing of the command line
// option parser.
main.registerCommand({
name: 'dummy',
options: {
ething: { type: String, short: "e", required: true },
port: { type: Number, short: "p", 'default': DEFAULT_PORT },
url: { type: Boolean, short: "U" },
'delete': { type: Boolean, short: "D" },
changed: { type: Boolean }
},
maxArgs: 2,
hidden: true,
pretty: false,
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
var p = function (key) {
if (_.has(options, key)) return JSON.stringify(options[key]);
return 'none';
};
Console.info(p('ething') + " " + p('port') + " " + p('changed') + " " + p('args'));
if (options.url) Console.info('url');
if (options['delete']) Console.info('delete');
});
///////////////////////////////////////////////////////////////////////////////
// throw-error
///////////////////////////////////////////////////////////////////////////////
// Dummy test command. Used to test that stack traces work from an installed
// Meteor tool.
main.registerCommand({
name: 'throw-error',
hidden: true,
catalogRefresh: new catalog.Refresh.Never()
}, function () {
throw new Error("testing stack traces!"); // #StackTraceTest this line is found in tests/source-maps.js
});
//# sourceMappingURL=commands.js.map |
'use strict';
angular.module('terminaaliApp')
.factory('Auth', function Auth($location, $rootScope, $http, User, $cookieStore, $q) {
var currentUser = {};
if($cookieStore.get('token')) {
currentUser = User.get();
}
return {
/**
* Authenticate user and save token
*
* @param {Object} user - login info
* @param {Function} callback - optional
* @return {Promise}
*/
login: function(user, callback) {
var cb = callback || angular.noop;
var deferred = $q.defer();
$http.post('/auth/local', {
email: user.email,
password: user.password
}).
success(function(data) {
$cookieStore.put('token', data.token);
currentUser = User.get();
deferred.resolve(data);
return cb();
}).
error(function(err) {
this.logout();
deferred.reject(err);
return cb(err);
}.bind(this));
return deferred.promise;
},
/**
* Delete access token and user info
*
* @param {Function}
*/
logout: function() {
$cookieStore.remove('token');
currentUser = {};
},
/**
* Create a new user
*
* @param {Object} user - user info
* @param {Function} callback - optional
* @return {Promise}
*/
createUser: function(user, callback) {
var cb = callback || angular.noop;
return User.save(user,
function(data) {
$cookieStore.put('token', data.token);
currentUser = User.get();
return cb(user);
},
function(err) {
this.logout();
return cb(err);
}.bind(this)).$promise;
},
/**
* Change password
*
* @param {String} oldPassword
* @param {String} newPassword
* @param {Function} callback - optional
* @return {Promise}
*/
changePassword: function(oldPassword, newPassword, callback) {
var cb = callback || angular.noop;
return User.changePassword({ id: currentUser._id }, {
oldPassword: oldPassword,
newPassword: newPassword
}, function(user) {
return cb(user);
}, function(err) {
return cb(err);
}).$promise;
},
/**
* Gets all available info on authenticated user
*
* @return {Object} user
*/
getCurrentUser: function() {
return currentUser;
},
/**
* Check if a user is logged in
*
* @return {Boolean}
*/
isLoggedIn: function() {
return currentUser.hasOwnProperty('role');
},
/**
* Waits for currentUser to resolve before checking if user is logged in
*/
isLoggedInAsync: function(cb) {
if(currentUser.hasOwnProperty('$promise')) {
currentUser.$promise.then(function() {
cb(true);
}).catch(function() {
cb(false);
});
} else if(currentUser.hasOwnProperty('role')) {
cb(true);
} else {
cb(false);
}
},
/**
* Check if a user is an admin
*
* @return {Boolean}
*/
isAdmin: function() {
return currentUser.role === 'admin';
},
/**
* Get auth token
*/
getToken: function() {
return $cookieStore.get('token');
}
};
});
|
$(document).ready(function(){
var toggleMuffEditor = function(stat=false){
$("#muff-opt").remove();
// bind event
if(stat){
$(".muff").mouseover(function() {
$("#muff-opt").remove();
muffShowOptions($(this));
$(window).scroll(function(){
$("#muff-opt").remove();
})
});
}else{// unbind event
$(".muff").unbind("mouseover");
}
};
function muffShowOptions( e ){
var t = "";
var id = e.attr("data-muff-id");
var title = e.attr("data-muff-title");
var p = e.offset();
var opttop = p.top + 15;
var optleft = p.left + 5;
if(e.hasClass("muff-div")){ t="div";
}else if(e.hasClass("muff-text")){ t="text";
}else if(e.hasClass("muff-a")){ t="link";
}else if(e.hasClass("muff-img")){ t="image";
}
if(!title){ title = t;}
// check position is beyond document
if((p.left + 25 + 75) > $(window).width()){
optleft -= 75;
}
var opt = "<div id='muff-opt' style='position:absolute;top:"+opttop+"px;left:"+optleft+"px;z-index:99998;display:none;'>";
opt += "<a href='admin/"+t+"/"+id+"/edit' class='mbtn edit'></a>";
opt += "<a href='admin/"+t+"/delete/' class='mbtn delete' data-mod='"+t+"' data-id='"+id+"'></a>";
opt += "<span>"+title+"</span>";
opt += "</div>";
$("body").prepend(opt);
$("#muff-opt").slideDown(300);
$("body").find("#muff-opt > a.delete").click(function(e){
var path = $(this).attr('href');
var mod = $(this).attr('data-mod');
// e.preventDefault();
swal({
title: "Are you sure?",
text: "You are about to delete this "+mod,
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "Cancel",
closeOnConfirm: true,
closeOnCancel: true
},
function(isConfirm){
if (isConfirm) {
// window.location.href = path;
proceedDelete(path, id);
}
});
return false;
});
}
toggleMuffEditor(false);
// set checkbox editor event
$("input[name=cb-muff-editor]").click(function(){
if($(this).is(':checked')){ toggleMuffEditor(true); }
else{ toggleMuffEditor(false) }
});
function proceedDelete(path, id){
var newForm = jQuery('<form>', {
'action': path,
'method': 'POST',
'target': '_top'
}).append(jQuery('<input>', {
'name': '_token',
'value': $("meta[name=csrf-token]").attr("content"),
'type': 'hidden'
})).append(jQuery('<input>', {
'name': 'id',
'value': id,
'type': 'hidden'
}));
newForm.hide().appendTo("body").submit();
}
// $(".opt-div a.delete, .w-conf a.delete, .w-conf-hvr a.delete").click(function(e){
// var path = $(this).attr('href');
// var mod = $(this).attr('data-mod');
// // e.preventDefault();
// swal({
// title: "Are you sure?",
// text: "You are about to delete this "+mod,
// type: "warning",
// showCancelButton: true,
// confirmButtonColor: "#DD6B55",
// confirmButtonText: "Yes, delete it!",
// cancelButtonText: "Cancel",
// closeOnConfirm: true,
// closeOnCancel: true
// },
// function(isConfirm){
// if (isConfirm) {
// window.location.href = path;
// }
// });
// return false;
// });
// top nav click
$(".top-nav>li").click(function(){
var i = $(this).find('.dropdown-menu');
toggleClassExcept('.top-nav .dropdown-menu', 'rmv', 'active', i);
i.toggleClass("active");
});
/** toggle a certain class except the given object
* works with li and lists
* @param id identifier
* @param a action
* @param c class
* @param ex object
*/
function toggleClassExcept(id, a, c, ex){
$(id).each(function(){
switch(a){
case 'remove':
case 'rmv':
if(!$(this).is(ex)) $(this).removeClass(c);
break;
case 'add':
if(!$(this).is(ex)) $(this).addClass(c);
break;
default:
break;
}
});
}
$(".w-add .muff-add").click(function(event){
event.preventDefault();
var b = $(this);
var newForm = jQuery('<form>', {
'action': b.data('href'),
'method': 'GET',
'target': '_top'
}).append(jQuery('<input>', {
'name': '_token',
'value': $("meta[name=csrf-token]").attr("content"),
'type': 'hidden'
})).append(jQuery('<input>', {
'name': 'url',
'value': $("meta[name=muffin-url]").attr("content"),
'type': 'hidden'
})).append(jQuery('<input>', {
'name': 'location',
'value': b.data("loc"),
'type': 'hidden'
}));
// console.log(newForm);
newForm.hide().appendTo("body").submit();
})
// TAGs
//var tagArea = '.tag-area';
if($('.tagarea')[0]){
var backSpace;
var close = '<a class="close"></a>';
var PreTags = $('.tagarea').val().trim().split(" ");
$('.tagarea').after('<ul class="tag-box"></ul>');
for (i=0 ; i < PreTags.length; i++ ){
var pretag = PreTags[i].split("_").join(" ");
if($('.tagarea').val().trim() != "" )
$('.tag-box').append('<li class="tags"><input type="hidden" name="tags[]" value="'+pretag+'">'+pretag+close+'</li>');
}
$('.tag-box').append('<li class="new-tag"><input class="input-tag" type="text"></li>');
// unbind submit form when pressing enter
$('.input-tag').on('keyup keypress', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
e.preventDefault();
return false;
}
});
// Taging
$('.input-tag').bind("keydown", function (kp) {
var tag = $('.input-tag').val().trim();
if(tag.length > 0){
$(".tags").removeClass("danger");
if(kp.keyCode == 13 || kp.keyCode == 9){
$(".new-tag").before('<li class="tags"><input type="hidden" name="tags[]" value="'+tag+'">'+tag+close+'</li>');
$(this).val('');
}}
else {if(kp.keyCode == 8 ){
if($(".new-tag").prev().hasClass("danger")){
$(".new-tag").prev().remove();
}else{
$(".new-tag").prev().addClass("danger");
}
}
}
});
//Delete tag
$(".tag-box").on("click", ".close", function() {
$(this).parent().remove();
});
$(".tag-box").click(function(){
$('.input-tag').focus();
});
// Edit
$('.tag-box').on("dblclick" , ".tags", function(cl){
var tags = $(this);
var tag = tags.text().trim();
$('.tags').removeClass('edit');
tags.addClass('edit');
tags.html('<input class="input-tag" value="'+tag+'" type="text">')
$(".new-tag").hide();
tags.find('.input-tag').focus();
tag = $(this).find('.input-tag').val() ;
$('.tags').dblclick(function(){
tags.html(tag + close);
$('.tags').removeClass('edit');
$(".new-tag").show();
});
tags.find('.input-tag').bind("keydown", function (edit) {
tag = $(this).val() ;
if(edit.keyCode == 13){
$(".new-tag").show();
$('.input-tag').focus();
$('.tags').removeClass('edit');
if(tag.length > 0){
tags.html('<input type="hidden" name="tags[]" value="'+tag+'">'+tag + close);
}
else{
tags.remove();
}
}
});
});
}
// sorting
// $(function() {
// $( ".tag-box" ).sortable({
// items: "li:not(.new-tag)",
// containment: "parent",
// scrollSpeed: 100
// });
// $( ".tag-box" ).disableSelection();
// });
});
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = undefined;
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _objectAssign = require('object-assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _rcTable = require('rc-table');
var _rcTable2 = _interopRequireDefault(_rcTable);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var __assign = undefined && undefined.__assign || Object.assign || function (t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
}
return t;
};
var Table = function (_React$Component) {
(0, _inherits3["default"])(Table, _React$Component);
function Table() {
(0, _classCallCheck3["default"])(this, Table);
return (0, _possibleConstructorReturn3["default"])(this, _React$Component.apply(this, arguments));
}
Table.prototype.render = function render() {
var _props = this.props,
columns = _props.columns,
dataSource = _props.dataSource,
direction = _props.direction,
scrollX = _props.scrollX,
titleFixed = _props.titleFixed;
var _props2 = this.props,
style = _props2.style,
className = _props2.className;
var restProps = (0, _objectAssign2["default"])({}, this.props);
['style', 'className'].forEach(function (prop) {
if (restProps.hasOwnProperty(prop)) {
delete restProps[prop];
}
});
var table = void 0;
// 默认纵向
if (!direction || direction === 'vertical') {
if (titleFixed) {
table = _react2["default"].createElement(_rcTable2["default"], __assign({}, restProps, { columns: columns, data: dataSource, className: "am-table", scroll: { x: true }, showHeader: false }));
} else {
table = _react2["default"].createElement(_rcTable2["default"], __assign({}, restProps, { columns: columns, data: dataSource, className: "am-table", scroll: { x: scrollX } }));
}
} else if (direction === 'horizon') {
columns[0].className = 'am-table-horizonTitle';
table = _react2["default"].createElement(_rcTable2["default"], __assign({}, restProps, { columns: columns, data: dataSource, className: "am-table", showHeader: false, scroll: { x: scrollX } }));
} else if (direction === 'mix') {
columns[0].className = 'am-table-horizonTitle';
table = _react2["default"].createElement(_rcTable2["default"], __assign({}, restProps, { columns: columns, data: dataSource, className: "am-table", scroll: { x: scrollX } }));
}
return _react2["default"].createElement("div", { className: className, style: style }, table);
};
return Table;
}(_react2["default"].Component);
exports["default"] = Table;
Table.defaultProps = {
dataSource: [],
prefixCls: 'am-table'
};
module.exports = exports['default']; |
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M19.99 9.79c.51-.4.51-1.18 0-1.58l-6.76-5.26c-.72-.56-1.73-.56-2.46 0L9.41 4.02l7.88 7.88 2.7-2.11zm0 3.49l-.01-.01a.991.991 0 00-1.22 0l-.05.04 1.4 1.4c.37-.41.34-1.07-.12-1.43zm1.45 5.6L4.12 1.56a.9959.9959 0 00-1.41 0c-.39.39-.39 1.02 0 1.41l3.52 3.52-2.22 1.72c-.51.4-.51 1.18 0 1.58l6.76 5.26c.72.56 1.73.56 2.46 0l.87-.68 1.42 1.42-2.92 2.27c-.36.28-.87.28-1.23 0l-6.15-4.78a.991.991 0 00-1.22 0c-.51.4-.51 1.17 0 1.57l6.76 5.26c.72.56 1.73.56 2.46 0l3.72-2.89 3.07 3.07c.39.39 1.02.39 1.41 0 .41-.39.41-1.02.02-1.41z" />
, 'LayersClearRounded');
|
import {
assign,
forEach,
isArray
} from 'min-dash';
var abs= Math.abs,
round = Math.round;
var TOLERANCE = 10;
export default function BendpointSnapping(eventBus) {
function snapTo(values, value) {
if (isArray(values)) {
var i = values.length;
while (i--) if (abs(values[i] - value) <= TOLERANCE) {
return values[i];
}
} else {
values = +values;
var rem = value % values;
if (rem < TOLERANCE) {
return value - rem;
}
if (rem > values - TOLERANCE) {
return value - rem + values;
}
}
return value;
}
function mid(element) {
if (element.width) {
return {
x: round(element.width / 2 + element.x),
y: round(element.height / 2 + element.y)
};
}
}
// connection segment snapping //////////////////////
function getConnectionSegmentSnaps(context) {
var snapPoints = context.snapPoints,
connection = context.connection,
waypoints = connection.waypoints,
segmentStart = context.segmentStart,
segmentStartIndex = context.segmentStartIndex,
segmentEnd = context.segmentEnd,
segmentEndIndex = context.segmentEndIndex,
axis = context.axis;
if (snapPoints) {
return snapPoints;
}
var referenceWaypoints = [
waypoints[segmentStartIndex - 1],
segmentStart,
segmentEnd,
waypoints[segmentEndIndex + 1]
];
if (segmentStartIndex < 2) {
referenceWaypoints.unshift(mid(connection.source));
}
if (segmentEndIndex > waypoints.length - 3) {
referenceWaypoints.unshift(mid(connection.target));
}
context.snapPoints = snapPoints = { horizontal: [] , vertical: [] };
forEach(referenceWaypoints, function(p) {
// we snap on existing bendpoints only,
// not placeholders that are inserted during add
if (p) {
p = p.original || p;
if (axis === 'y') {
snapPoints.horizontal.push(p.y);
}
if (axis === 'x') {
snapPoints.vertical.push(p.x);
}
}
});
return snapPoints;
}
eventBus.on('connectionSegment.move.move', 1500, function(event) {
var context = event.context,
snapPoints = getConnectionSegmentSnaps(context),
x = event.x,
y = event.y,
sx, sy;
if (!snapPoints) {
return;
}
// snap
sx = snapTo(snapPoints.vertical, x);
sy = snapTo(snapPoints.horizontal, y);
// correction x/y
var cx = (x - sx),
cy = (y - sy);
// update delta
assign(event, {
dx: event.dx - cx,
dy: event.dy - cy,
x: sx,
y: sy
});
});
// bendpoint snapping //////////////////////
function getBendpointSnaps(context) {
var snapPoints = context.snapPoints,
waypoints = context.connection.waypoints,
bendpointIndex = context.bendpointIndex;
if (snapPoints) {
return snapPoints;
}
var referenceWaypoints = [ waypoints[bendpointIndex - 1], waypoints[bendpointIndex + 1] ];
context.snapPoints = snapPoints = { horizontal: [] , vertical: [] };
forEach(referenceWaypoints, function(p) {
// we snap on existing bendpoints only,
// not placeholders that are inserted during add
if (p) {
p = p.original || p;
snapPoints.horizontal.push(p.y);
snapPoints.vertical.push(p.x);
}
});
return snapPoints;
}
eventBus.on('bendpoint.move.move', 1500, function(event) {
var context = event.context,
snapPoints = getBendpointSnaps(context),
target = context.target,
targetMid = target && mid(target),
x = event.x,
y = event.y,
sx, sy;
if (!snapPoints) {
return;
}
// snap
sx = snapTo(targetMid ? snapPoints.vertical.concat([ targetMid.x ]) : snapPoints.vertical, x);
sy = snapTo(targetMid ? snapPoints.horizontal.concat([ targetMid.y ]) : snapPoints.horizontal, y);
// correction x/y
var cx = (x - sx),
cy = (y - sy);
// update delta
assign(event, {
dx: event.dx - cx,
dy: event.dy - cy,
x: event.x - cx,
y: event.y - cy
});
});
}
BendpointSnapping.$inject = [ 'eventBus' ]; |