code stringlengths 2 1.05M |
|---|
module.exports = function NullCache() {
this.get = function (key, cb) {
cb();
};
this.set = function (key, private, value, ttlMillis, cb) {
cb();
};
this.flush = function (cb) {
cb();
};
};
|
(function(){
var PersonService = function ($http){
var service = {};
service.getPersons = function (callback) {
$http.get('Persons/GetPersons/').success(function (responseData) {
callback(responseData.map(function (item) {
return {
id: item.Id,
name: item.Name,
lastname: item.LastName,
email: item.Email,
personSkills: item.PersonSkills.map(function (skill) {
return {
name: skill.Name,
level: skill.Level
};
})
};
}));
});
}
service.getPerson = function (id, callback) {
$http.get('Persons/GetPerson?id=' + id).success(function (responseData) {
callback({
id: responseData.Id,
name: responseData.Name,
lastname: responseData.LastName,
email: responseData.Email,
personSkills: responseData.PersonSkills.map(function (skill) {
return {
name: skill.Name,
level: skill.Level
};
})
});
});
}
service.savePerson = function (person, callback){
$http.post('Persons/SavePerson/', person).success(function (responseData) {
callback(responseData);
});
}
return service;
}
TiempoSkills.factory('personService',['$http', PersonService ]);
}()); |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _react = require('react');
var _utils = require('../utils');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var windowKey = Symbol.for("er_register_map");
var registerMap = window[windowKey] = window[windowKey] || {
ids: {}
};
var not_null = function not_null(t) {
return t != null;
};
var hasRegistered = function hasRegistered(_ref) {
var id = _ref.id;
return not_null(registerMap.ids[id]);
};
var cleanRegister = function cleanRegister(props) {
var target = props.target,
eventName = props.eventName,
func = props.func,
isUseCapture = props.isUseCapture,
id = props.id;
if (hasRegistered(props)) {
target.removeEventListener(eventName, func, isUseCapture);
delete registerMap.ids[id];
}
};
var doRegister = function doRegister(props) {
var id = props.id,
eventName = props.eventName,
func = props.func,
isUseCapture = props.isUseCapture;
registerMap.ids[id] = id;
document.addEventListener(eventName, func, isUseCapture);
};
/**
* register events that hooked up react lifecycle
*/
var EventRegister = function (_Component) {
_inherits(EventRegister, _Component);
function EventRegister() {
_classCallCheck(this, EventRegister);
return _possibleConstructorReturn(this, (EventRegister.__proto__ || Object.getPrototypeOf(EventRegister)).apply(this, arguments));
}
_createClass(EventRegister, [{
key: 'componentDidMount',
value: function componentDidMount() {
var _props = this.props,
eventName = _props.eventName,
id = _props.id;
eventName = eventName.toLowerCase();
eventName = /^on/.test(eventName) ? eventName.substring(2) : eventName;
this.cached = Object.assign({}, this.props, { eventName: eventName });
(0, _utils.require_condition)(typeof id === 'string', 'id prop is required');
(0, _utils.require_condition)(!hasRegistered(this.cached), 'id: ' + id + ' has been registered');
doRegister(this.cached);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
cleanRegister(this.cached);
}
}, {
key: 'render',
value: function render() {
return null;
}
}]);
return EventRegister;
}(_react.Component);
exports.default = EventRegister;
EventRegister.propTypes = {
id: _propTypes2.default.string.isRequired,
target: _propTypes2.default.object.isRequired,
eventName: _propTypes2.default.string.isRequired,
func: _propTypes2.default.func.isRequired,
isUseCapture: _propTypes2.default.bool
}; |
/**
* The mongodb module implements all of the operations needed to interface our cms with mongo.
*
* @returns {{}}
*/
module.exports = (function(){
'use strict';
var db = {},
config = require('../config'),
event = require('../event'),
Strings = require('../strings'),
strings = new Strings('en'),
createError = require('../utils/error'),
logger = require('../utils/logger'),
mongoose = require('mongoose'),
url = config.db.host,
options = {
user: config.db.username,
pass: config.db.password
};
db.tokens = require('./mongodb/tokens');
db.users = require('./mongodb/users');
db.contentTypes = require('./mongodb/contentTypes');
db.nodes = require('./mongodb/nodes');
db.content = require('./mongodb/content');
mongoose.connect(url, options);
if(config.db.debug){
mongoose.set('debug', true);
}
// When successfully connected
mongoose.connection.on('connected', function () {
require('../utils/typeCache');
logger.info(strings.group('notice').db_connected);
event.emit('start', { system: 'db' } );
});
// If the connection throws an error
mongoose.connection.on('error',function (err) {
logger.error(strings.group('errors').db_connection_error, err);
event.emit('error', { system: 'db' } , createError(500, err) );
});
// When the connection is disconnected
mongoose.connection.on('disconnected', function () {
logger.info(strings.group('notice').db_disconnected);
event.emit('stop', { system: 'db' } );
});
// If the Node process ends, close the Mongoose connection
process.on('SIGINT', function() {
mongoose.connection.close(function () {
logger.info(strings.group('notice').db_disconnected);
process.exit(0);
});
});
db.mongoose = mongoose;
return db;
})();
|
/*
* NODE SDK for the KATANA(tm) Framework (http://katana.kusanagi.io)
* Copyright (c) 2016-2018 KUSANAGI S.L. All rights reserved.
*
* Distributed under the MIT license
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code
*
* @link https://github.com/kusanagi/katana-sdk-node
* @license http://www.opensource.org/licenses/mit-license.php MIT License
* @copyright Copyright (c) 2016-2018 KUSANAGI S.L. (http://kusanagi.io)
*/
'use strict';
const assert = require('assert');
const _ = require('lodash');
const Transport = require('./transport');
const File = require('./file');
const expect = require('chai').expect;
const m = require('./mappings');
describe('Transport', () => {
const mockTransport = {
[m.meta]: {
[m.version]: '1.0.0',
[m.level]: 0,
[m.gateway]: ['', '']
}
};
it('should create an instance', () => {
const transport = new Transport(mockTransport);
assert.ok(transport instanceof Transport);
});
describe('getRequestId()', () => {
it('should return the UUID of the request', () => {
const _id = '110ec58a-a0f2-4ac4-8393-c866d813b8d1';
const _mockTransport = _.merge({}, mockTransport, {[m.meta]: {[m.id]: _id}});
const transport = new Transport(_mockTransport);
assert.equal(transport.getRequestId(), _id);
});
});
describe('getRequestTimestamp()', () => {
it('should return the creation datetime of the request', () => {
const _datetime = '2016-10-03T12:57:18.363Z';
const _mockTransport = _.merge({}, mockTransport, {[m.meta]: {[m.datetime]: _datetime}});
const transport = new Transport(_mockTransport);
assert.equal(transport.getRequestTimestamp(), _datetime);
});
});
describe('getOriginService()', () => {
it('should return the origin of the request', () => {
const _origin = ['test', '1.2.0'];
const _mockTransport = _.merge({}, mockTransport, {[m.meta]: {[m.origin]: _origin}});
const transport = new Transport(_mockTransport);
const [name, version] = _origin;
const [originName, originVersion] = transport.getOriginService();
assert.equal(name, originName);
assert.equal(version, originVersion);
});
});
describe('getProperty()', () => {
it('should return the value of a property by `name`', () => {
const properties = {test: true};
const _mockTransport = _.merge({meta: {properties}}, mockTransport);
const transport = new Transport(_mockTransport);
assert.equal(transport.getProperty('test'), true);
});
it('should return the `defaultValue` when no property found with `name`', () => {
const transport = new Transport(mockTransport);
assert.equal(transport.getProperty('test', 'default'), 'default');
});
it('should throw an error if property `name` is not specified', () => {
const transport = new Transport(mockTransport);
assert.throws(() => transport.getProperty(void 0, 'default'), /Specify a property `name`/);
});
});
describe('hasDownload()', () => {
it('should determine if a file download has been registered for the response', () => {
const _mockTransport = _.merge({[m.body]: ''}, mockTransport);
const transport = new Transport(_mockTransport);
assert.equal(transport.hasDownload(), true);
});
});
describe('getDownload()', () => {
it('should return the file registered for the response as a File instance', () => {
const _body = {[m.path]: '', [m.token]: '', [m.filename]: '', [m.size]: '', [m.mime]: ''};
const _mockTransport = _.merge({[m.body]: _body}, mockTransport);
const transport = new Transport(_mockTransport);
assert.ok(transport.getDownload() instanceof File);
});
it('should return null if no file registered', () => {
const transport = new Transport(mockTransport);
assert.equal(transport.getDownload(), null);
});
});
describe('getData()', () => {
it('should return all the data stored in the transport', () => {
const d = {
'address': {
users: {
'1.0.0': {
'get': [
{foo: 'bar'},
[
{foo: 'bar'},
{foo: 'biz'}
]
]
}
}
}
};
const expectedResult = [
{
['_address']: 'address',
['_name']: 'users',
['_version']: '1.0.0',
['_actions']: [
{
['_name']: 'get',
['_collection']: false,
['_data']: {foo: 'bar'}
},
{
['_name']: 'get',
['_collection']: true,
['_data']: [
{foo: 'bar'},
{foo: 'biz'}
]
}
],
}
];
const _mockTransport = _.merge({[m.data]: d}, mockTransport);
const transport = new Transport(_mockTransport);
expect(transport.getData()).to.eql(expectedResult);
});
it('should return empty array if no data', () => {
const transport = new Transport(mockTransport);
assert.deepEqual(transport.getData(), []);
});
});
describe('getRelations()', () => {
it('should return all relations', () => {
const r = {
addressFrom: {
serviceFrom: {
primaryKey: {
addressTo: {
serviceToSingle: 'singleKey',
serviceToMulti: ['key1', 'key2']
}
}
}
}
};
const expectedResult = [
{
['_address']: 'addressFrom',
['_name']: 'serviceFrom',
['_primaryKey']: 'primaryKey',
['_foreignRelations']: [
{
['_address']: 'addressTo',
['_name']: 'serviceToSingle',
['_type']: 'one',
['_foreignKeys']: ['singleKey'],
},
{
['_address']: 'addressTo',
['_name']: 'serviceToMulti',
['_type']: 'many',
['_foreignKeys']: ['key1', 'key2'],
}
],
}
];
const _mockTransport = _.merge({r}, mockTransport);
const transport = new Transport(_mockTransport);
expect(transport.getRelations()).to.eql(expectedResult);
});
});
describe('getLinks()', () => {
it('should return all links', () => {
const l = {
address: {
name: {
link1: 'http://example.com/1',
link2: 'http://example.com/2'
}
}
};
const expectedResult = [
{
['_address']: 'address',
['_name']: 'name',
['_link']: 'link1',
['_uri']: 'http://example.com/1',
},
{
['_address']: 'address',
['_name']: 'name',
['_link']: 'link2',
['_uri']: 'http://example.com/2',
}
];
const _mockTransport = _.merge({l}, mockTransport);
const transport = new Transport(_mockTransport);
expect(transport.getLinks()).to.eql(expectedResult);
});
});
describe('getCalls()', () => {
it('should return all calls', () => {
const C = {
users: {
'1.0.0': [
{
'D': 1120,
'x': 1500,
'g': 'address',
'n': 'posts',
'v': '1.2.0',
'a': 'list',
'C': 'read',
'p': [
{
'n': 'token',
'v': 'abcd',
't': 'string'
},
{
'n': 'user_id',
'v': 123,
't': 'integer'
}
]
},
{
'n': 'comments',
'v': '1.2.3',
'a': 'find',
'C': 'read'
},
]
}
};
const expectedResult = [
{
['_name']: 'users',
['_version']: '1.0.0',
['_action']: 'read',
['_callee']: {
['_duration']: 1120,
['_timeout']: 1500,
['_name']: 'posts',
['_address']: 'address',
['_version']: '1.2.0',
['_action']: 'list',
['_params']: [
{
['_name']: 'token',
['_value']: 'abcd',
['_type']: 'string',
['_exists']: true,
},
{
['_name']: 'user_id',
['_value']: 123,
['_type']: 'integer',
['_exists']: true,
},
]
},
},
{
['_name']: 'users',
['_version']: '1.0.0',
['_action']: 'read',
['_callee']: {
['_duration']: undefined,
['_timeout']: undefined,
['_address']: undefined,
['_name']: 'comments',
['_version']: '1.2.3',
['_action']: 'find',
['_params']: [],
},
}
];
const _mockTransport = _.merge({C}, mockTransport);
const transport = new Transport(_mockTransport);
expect(transport.getCalls()).to.eql(expectedResult);
});
});
describe('getTransactions()', () => {
const t = {
'c': [
{
'n': 'users',
'v': '1.0.0',
'a': 'save',
'C': 'create',
'p': [
{
'n': 'user_id',
'v': 123,
't': 'integer'
}
]
}
],
'r': [
{
'n': 'users',
'v': '1.0.0',
'a': 'undo',
'C': 'create',
'p': [
{
'n': 'user_id',
'v': 123,
't': 'integer'
}
]
}
]
};
const _mockTransport = _.merge({t}, mockTransport);
const transport = new Transport(_mockTransport);
it('should return all transactions of the given type', () => {
const expectedResult = [
{
['_type']: 'commit',
['_name']: 'users',
['_version']: '1.0.0',
['_callerAction']: 'create',
['_calleeAction']: 'save',
['_params']: [
{
['_name']: 'user_id',
['_value']: 123,
['_type']: 'integer',
['_exists']: true,
},
]
}
];
expect(transport.getTransactions('commit')).to.eql(expectedResult);
});
it('should not return transactions of other types', () => {
expect(transport.getTransactions('complete')).to.eql([]);
});
});
describe('getErrors()', () => {
it('should return all errors', () => {
const e = {
'http://127.0.0.1:80': {
'users': {
'1.0.0': [
{
'm': 'The user does not exist',
'c': 9,
's': '404 Not Found'
}
]
}
}
};
const _mockTransport = _.merge({e}, mockTransport);
const transport = new Transport(_mockTransport);
const expectedResult = [
{
['_address']: 'http://127.0.0.1:80',
['_name']: 'users',
['_version']: '1.0.0',
['_message']: 'The user does not exist',
['_code']: 9,
['_status']: '404 Not Found',
}
];
expect(transport.getErrors()).to.eql(expectedResult);
});
});
});
|
'use strict';
const fs = require('fs');
const docs = process.argv[2] || './docs';
const out = process.argv[3] || './dist';
const marked = require('marked');
const renderer = new marked.Renderer();
renderer.heading = function(text, level, raw, slugger) {
if (this.options.headerIds) {
const id = this.options.headerPrefix + slugger.slug(raw);
const link = `<a class="anchor" aria-hidden="true" href="#${id}"><span class="octicon octicon-link"></span></a>`;
return '<h' + level + ' id="' + id + '">' + link + text + '</h' + level + '>\n';
}
// ignore IDs
return '<h' + level + '>' + text + '</h' + level + '>\n';
};
/**
* Make first letter uppercase leaving other intact
*
* @param {string} s - String to capitalize
*/
function capitalize(s) {
if (typeof s !== 'string') return s;
return s.charAt(0).toUpperCase() + s.slice(1);
}
/**
* When running locally, localize markdown links to local files
*
* @param {string} md - markdown content
*/
function localize(md) {
return md.split('https://maasglobal.github.io/maas-tsp-api/').join('');
}
/**
* Turns body fragment into HTML page
*
* @param {string} title - Title of the page
* @param {string} body - Body fragment of the page
*/
function htmlDocument(title, body) {
return `<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>${title}</title>
<link rel="stylesheet" type="text/css" href="github-markdown.css"/>
<style type="text/css">
.markdown-body {
box-sizing: border-box;
min-width: 200px;
max-width: 980px;
margin: 0 auto;
padding: 45px;
}
@media (max-width: 767px) {
.markdown-body {
padding: 15px;
}
}
</style>
</head>
<body class="markdown-body">
${body}
</body>
</html>
`;
}
/**
* Convert .md file to .html
*
* @param {string} file - Markdown file
*/
function compileMarkdown(file) {
const htmlFile = file.replace('.md', '.html');
const md = fs.readFileSync(docs + '/' + file, { encoding: 'utf8' });
const htmlFragment = marked(localize(md), { renderer });
const html = htmlDocument(capitalize(file.replace('.md', '')), htmlFragment);
fs.writeFileSync(out + '/' + htmlFile, html);
}
/**
* Process all markdown files into html files
*/
async function compileDocs() {
return new Promise((resolve, reject) => {
if (!fs.existsSync(out)) {
fs.mkdirSync(out, { recursive: true });
}
fs.readdir(docs, (err, files) => {
let count = 0;
files.forEach(file => {
if (file.endsWith('.md')) {
compileMarkdown(file);
count++;
}
});
resolve(count);
});
});
}
module.exports = {
compileDocs,
};
if (require.main === module) {
compileDocs();
}
|
'use strict';
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _sourceMapFixtures = require('source-map-fixtures');
var _ = require('../../');
var _2 = _interopRequireDefault(_);
var fixture = (0, _sourceMapFixtures.mapFile)('throws').require();
(0, _2['default'])('throw an uncaught exception', function (t) {
setImmediate(run);
});
var run = function run() {
return fixture.run();
};
//# sourceMappingURL=./source-map-initial.js.map
// Generated using node test/fixtures/_generate-source-map-initial.js
|
'use strict';
angular.module('app')
.constant('MINERAL_TAGS_SET', [
'Bauxite',
'Copper',
'Diamond',
'Gold',
'Iron ore',
'Nickel',
'Phosphate -Precious stones (Jade)',
'Uranium'
]);
|
/**
* @hack 替换pixi的_renderWebGL用来支持 softClip
*/
/**
* Renders the object using the WebGL renderer
*
* @method _renderWebGL
* @param renderSession {RenderSession}
* @private
*/
PIXI.DisplayObjectContainer.prototype._renderWebGL = function(renderSession)
{
if (!this.visible || this.alpha <= 0) return;
if (this._cacheAsBitmap)
{
this._renderCachedSprite(renderSession);
return;
}
var i;
if (this.softClip) {
SoftClipManager.getManager(renderSession).pushPolygon(this.softClip);
}
var skipRenderChildren = false;
if (this._graphicsFilter || this._mask || this._filters)
{
if (this._graphicsFilter) {
renderSession.spriteBatch.flush();
renderSession.filterManager.pushFilter(this._graphicsFilter);
}
// push filter first as we need to ensure the stencil buffer is correct for any masking
if (this._filters && !this.filterSelf)
{
renderSession.spriteBatch.flush();
renderSession.filterManager.pushFilter(this._filterBlock);
}
if (this._mask)
{
renderSession.spriteBatch.stop();
renderSession.maskManager.pushMask(this.mask, renderSession);
renderSession.spriteBatch.start();
}
if (this._renderSelfWebGL) {
skipRenderChildren = this._renderSelfWebGL(renderSession);
}
// simple render children!
if (!skipRenderChildren) {
for (i = 0; i < this.children.length; i++)
{
this.children[i]._renderWebGL(renderSession);
}
}
renderSession.spriteBatch.stop();
if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession);
if (this._filters && !this.filterSelf) renderSession.filterManager.popFilter();
if (this._graphicsFilter) renderSession.filterManager.popFilter();
renderSession.spriteBatch.start();
}
else
{
if (this._renderSelfWebGL) {
skipRenderChildren = this._renderSelfWebGL(renderSession);
}
// simple render children!
if (!skipRenderChildren) {
for (i = 0; i < this.children.length; i++)
{
this.children[i]._renderWebGL(renderSession);
}
}
}
if (this.softClip) {
SoftClipManager.getManager(renderSession).popPolygon();
}
};
/**
* Renders the object using the Canvas renderer
*
* @method _renderCanvas
* @param renderSession {RenderSession}
* @private
*/
PIXI.DisplayObjectContainer.prototype._renderCanvas = function(renderSession)
{
if (this.visible === false || this.alpha === 0) return;
if (this._cacheAsBitmap)
{
this._renderCachedSprite(renderSession);
return;
}
var skipRenderChildren = false;
if (this._mask)
{
renderSession.maskManager.pushMask(this._mask, renderSession);
}
if (this._renderSelfCanvas) {
skipRenderChildren = this._renderSelfCanvas(renderSession);
}
if (!skipRenderChildren) {
for (var i = 0; i < this.children.length; i++)
{
this.children[i]._renderCanvas(renderSession);
}
}
if (this._mask)
{
renderSession.maskManager.popMask(renderSession);
}
};
PIXI.DisplayObjectContainer.prototype.addChildAt = function(child, index)
{
if(index >= 0 && index <= this.children.length)
{
if(child.parent)
{
child.parent.removeChild(child);
}
child.parent = this;
this.children.splice(index, 0, child);
this._qc && this._qc._dispatchChildrenChanged('add', [child._qc]);
if(this.stage)child.setStageReference(this.stage);
return child;
}
else
{
throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length);
}
};
/**
* Swaps the position of 2 Display Objects within this container.
*
* @method swapChildren
* @param child {DisplayObject}
* @param child2 {DisplayObject}
*/
PIXI.DisplayObjectContainer.prototype.swapChildren = function(child, child2)
{
if(child === child2) {
return;
}
var index1 = this.getChildIndex(child);
var index2 = this.getChildIndex(child2);
if(index1 < 0 || index2 < 0) {
throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.');
}
this.children[index1] = child2;
this.children[index2] = child;
this._qc && this._qc._dispatchChildrenChanged('order', [child._qc, child2._qc]);
child.displayChanged(qc.DisplayChangeStatus.ORDER);
child2.displayChanged(qc.DisplayChangeStatus.ORDER);
};
/**
* Changes the position of an existing child in the display object container
*
* @method setChildIndex
* @param child {DisplayObject} The child DisplayObject instance for which you want to change the index number
* @param index {Number} The resulting index number for the child display object
*/
PIXI.DisplayObjectContainer.prototype.setChildIndex = function(child, index)
{
if (index < 0 || index >= this.children.length)
{
throw new Error('The supplied index is out of bounds');
}
var currentIndex = this.getChildIndex(child);
this.children.splice(currentIndex, 1); //remove from old position
this.children.splice(index, 0, child); //add at new position
this._qc && this._qc._dispatchChildrenChanged('order', [child._qc]);
child.displayChanged(qc.DisplayChangeStatus.ORDER);
};
/**
* Removes a child from the specified index position.
*
* @method removeChildAt
* @param index {Number} The index to get the child from
* @return {DisplayObject} The child that was removed.
*/
PIXI.DisplayObjectContainer.prototype.removeChildAt = function(index)
{
var child = this.getChildAt( index );
child.maybeOutWorld();
if(this.stage)
child.removeStageReference();
child.parent = undefined;
this.children.splice( index, 1 );
this._qc && this._qc._dispatchChildrenChanged('remove', [child._qc]);
return child;
};
/**
* 提供 remove 方法,这样节点移除的时候就不需要判断 if remove then remove else removeChild
*/
PIXI.DisplayObjectContainer.prototype.remove = function(child)
{
return this.removeChild(child);
};
/**
* Removes all children from this container that are within the begin and end indexes.
*
* @method removeChildren
* @param beginIndex {Number} The beginning position. Default value is 0.
* @param endIndex {Number} The ending position. Default value is size of the container.
*/
PIXI.DisplayObjectContainer.prototype.removeChildren = function(beginIndex, endIndex)
{
var begin = beginIndex || 0;
var end = typeof endIndex === 'number' ? endIndex : this.children.length;
var range = end - begin;
if (range > 0 && range <= end)
{
var removed = this.children.splice(begin, range);
var removedQCNode = [];
for (var i = 0; i < removed.length; i++) {
var child = removed[i];
child.maybeOutWorld();
if(this.stage)
child.removeStageReference();
child.parent = undefined;
if (child._qc) {
removedQCNode.push(child._qc);
}
}
this._qc && this._qc._dispatchChildrenChanged('remove', removedQCNode);
return removed;
}
else if (range === 0 && this.children.length === 0)
{
this._qc && this._qc._dispatchChildrenChanged('remove', []);
return [];
}
else
{
throw new Error( 'removeChildren: Range Error, numeric values are outside the acceptable range' );
}
};
/**
* 获取本地节点范围
* @returns {Rectangle}
*/
PIXI.DisplayObjectContainer.prototype.getLocalBounds = function()
{
var matrixCache = this.worldTransform;
this._isSubNeedCalcTransform = true;
this.worldTransform = PIXI.identityMatrix;
for(var i=0,j=this.children.length; i<j; i++)
{
this.children[i].updateTransform();
}
var bounds = this.getBounds();
this.worldTransform = matrixCache;
this._isSubNeedCalcTransform = true;
this._isNotNeedCalcTransform = false;
return bounds;
};
PIXI.DisplayObjectContainer.prototype.displayMaybeOutWorld = PIXI.DisplayObject.prototype.maybeOutWorld;
/**
* 可能被移出世界,并不在进入世界显示时
*/
PIXI.DisplayObjectContainer.prototype.maybeOutWorld = function() {
this.displayMaybeOutWorld();
var children = this.children;
for(var i=0,j=children.length; i<j; i++)
{
children[i].maybeOutWorld();
}
};
|
const fs = require('fs')
const test = require('tape')
const GraphemeSplitter = require('../index')
function ucs2encode(array) {
return array.map( value => {
let output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += String.fromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += String.fromCharCode(value);
return output;
}).join('');
}
function testDataFromLine(line) {
const codePoints = line.split(/\s*[×÷]\s*/).map(c => parseInt(c, 16));
const input = ucs2encode(codePoints);
const expected = line.split(/\s*÷\s*/) .map(sequence => {
const codePoints = sequence.split(/\s*×\s*/).map(c => parseInt(c, 16))
return ucs2encode(codePoints)
});
return { input, expected };
}
const testData = fs.readFileSync('tests/GraphemeBreakTest.txt', 'utf-8')
.split('\n')
.filter(line =>
line != null && line.length > 0 && !line.startsWith('#'))
.map(line => line.split('#')[0])
.map(testDataFromLine);
// ---------------------------------------------------------------------------
// Test cases
// ---------------------------------------------------------------------------
test('splitGraphemes returns properly split list from string', t => {
const splitter = new GraphemeSplitter();
t.plan(testData.length);
testData.forEach( ({ input, expected }) => {
const result = splitter.splitGraphemes(input);
t.deepLooseEqual(result, expected);
});
t.end();
});
test('iterateGraphemes returns properly split iterator from string', t => {
const splitter = new GraphemeSplitter();
t.plan(testData.length);
testData.forEach( ({ input, expected }) => {
const result = splitter.iterateGraphemes(input);
t.deepLooseEqual([...result], expected);
});
t.end();
});
test('countGraphemes returns the correct number of graphemes in string', t => {
const splitter = new GraphemeSplitter();
t.plan(testData.length);
testData.forEach( ({ input, expected }) => {
const result = splitter.countGraphemes(input);
t.equal(result, expected.length);
});
t.end();
});
|
// Common modules
import '../../../common'
// Page modules
var ko = require('knockout')
var Model = require('../../../models/accommodation/listing')
ko.applyBindings(new Model())
|
//First View Stuff!!!!!
//VIEW//////////////////////////////////
//displayPlayerHand+
//displayDealerHand+
//winScreen+
//quitGame+
//displayNewScore+
window.onload = addListeners;
function addListeners(){
document.getElementById('play-btn').addEventListener("click", playBtn, false);
document.getElementById('deal-btn').addEventListener("click", dealBtn, false);
document.getElementById('hit-btn').addEventListener("click", hitBtn, false);
document.getElementById('stay-btn').addEventListener("click", stayBtn, false);
document.getElementById('toggle-ace-btn').addEventListener("click", toggleAceBtn, false);
document.getElementById('play-again-btn').addEventListener("click", playAgainBtn, false);
totalScore = new overallScore();
}
function displayPlayerHand(player){
//PLAYER////////////////////////////////
//hand, hasAce, scoreHigh, scoreLow, aceLowOrHigh
//dealTo(card), getScore()
//getHand
var i = 0;
var playerHand = player.hand;
console.log("-------------");
console.log("Player hand: ")
for(i = 0; i < playerHand.length; i++){
console.log(playerHand[i].name() + ", ");
}
if(player.hasAce){
if(player.aceLowOrHigh == 1){
console.log("Hand Score: " + player.scoreLow);
}else{
console.log("Hand Score: " + player.scoreHigh);
}
}else{
console.log("Hand score: " + player.scoreHigh);
}
console.log("-------------");
}
function displayDealerHand(dealer){
//displays the dealers hand. if it's the first turn, it only displays the first card.
//else, it displays the entire hand up until that point.
var i = 0;
var dealerHand = dealer.hand;
console.log("-------------");
console.log("Dealer hand: ");
if(dealer.turn == 1){
console.log(dealerHand[0].name() + ", -FACEDOWN CARD-");
}else{
for(i = 0; i < dealerHand.length; i++){
console.log(dealerHand[i].name() + ", ")
displayDealerScore(dealer);
}
}
console.log("-------------");
}
function displayDealerScore(dealer){
if(dealer.aceLowOrHigh == 1){
console.log("Dealer score:" + dealer.scoreLow);
}else if(dealer.aceLowOrHigh == 11){
console.log("Dealer score: " + dealer.scoreHigh);
}
}
////DOM MANIPULATION
function showNewTotalScore(){
var scoreDiv = document.getElementById('overall-score');
scoreDiv.innerHTML = '';
scoreDiv.innerHTML = totalScore.total;
}
function showDeal(){
var playButton = document.getElementById('play-button');
var dealButton = document.getElementById('deal-button');
//when this is called, the play button is showing, nothing else is showing
//only need to move to 'deal' button, and maybe add stuff to player and dealer
playButton.style.display = 'none';
dealButton.style.display = 'inline-block';
}
function showHitStay(){
var dealButton = document.getElementById('deal-button');
var hitButton = document.getElementById('hit-button');
var stayButton = document.getElementById('stay-button');
//when this is called player will have a hand, dealer will have a hand
//hit old buttons, make sure hit and stay are visible
//this will probably only fire when 'deal' is pressed
dealButton.style.display = 'none';
hitButton.style.display = 'inline-block';
stayButton.style.display = 'inline-block';
displayPlayerHand(player);
displayDealerHand(dealer);
}
function showWinner(winner){
//when this is fired, someone will have won. you can't hit or stay, so this is changing to play again or quit
//final score will have been shown already, just update the dom so that the hands are empty and the winner is show
//in one of the dom elements as well as the two buttons needed
var dealButton = document.getElementById('deal-button');
var hitButton = document.getElementById('hit-button');
var stayButton = document.getElementById('stay-button');
var playAgainButton = document.getElementById('play-again-button');
dealButton.style.display = 'none';
hitButton.style.display = 'none';
stayButton.style.display = 'none';
playAgainButton.style.display = 'inline-block';
showNewTotalScore();
displayDealerHand(dealer);
displayPlayerHand(player);
console.log("############################");
console.log("The winner is: " + winner.name);
console.log("############################");
}
function showTie(){
//when this is fired, tie
var hitButton = document.getElementById('hit-button');
var stayButton = document.getElementById('stay-button');
var playAgainButton = document.getElementById('play-again-button');
hitButton.style.display = 'none';
stayButton.style.display = 'none';
playAgainButton.style.display = 'inline-block';
showNewTotalScore();
displayDealerHand(dealer);
displayPlayerHand(player);
console.log("############################");
console.log("Tie game!");
console.log("############################");
}
function showRestart(){
//this function is called when the view needs to be reset, aka after Quit is pressed
var playAgainButton = document.getElementById('play-again-button');
var playButton = document.getElementById('play-button');
showNewTotalScore();
playAgainButton.style.display = 'none';
playButton.style.display = 'inline-block';
}
|
/* Allow namespace commentia to be defined elsewhere (mainly for passing config vars) */
window.commentia = window.commentia || {};
/* If no APIURL provided, default to root api.php */
window.commentia.APIURL = window.commentia.APIURL || "/api.php";
function ajax(url, callback, data, x) {
try {
x = new(this.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
x.open(data ? 'POST' : 'GET', url, 1);
x.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
x.onreadystatechange = function () {
x.readyState > 3 && callback && callback(x.responseText, x);
};
x.send(data)
} catch (e) {
window.console && console.log(e);
}
};
function httpRequest() {
var http_request;
try {
http_request = new XMLHttpRequest();
return http_request;
} catch (ignore) {
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
return http_request;
} catch (ignore) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
return http_request;
} catch (ignore) {
alert("Your browser broke!");
return false;
}
}
}
}
function refreshComments() {
var comments_section = document.getElementById("comments-container");
var url = window.commentia.APIURL + "?action=display";
console.log("GET request to: " + url);
ajax(window.commentia.APIURL + "?action=display", function (response) {
comments_section.innerHTML = response;
});
}
function showReplyArea(caller) {
var comment = findCommentRoot(caller);
var ucid = comment.getAttribute('data-ucid');
var reply_area_id = 'reply-area-' + ucid;
var reply_box_id = 'reply-box-' + ucid;
var reply_button_id = 'reply-button-' + ucid;
var cancel_button_id = 'edit-cancel-button-' + ucid;
if (!document.getElementById(reply_area_id)) {
var reply_area = document.createElement('div');
reply_area.setAttribute('id', reply_area_id);
var reply_box = document.createElement('textarea');
reply_box.setAttribute('id', reply_box_id);
reply_box.setAttribute('oninput', "autoGrow(this);");
reply_area.appendChild(reply_box);
var reply_button = document.createElement('button');
reply_button.innerHTML = 'reply';
reply_button.setAttribute('id', reply_button_id);
reply_button.setAttribute('onclick', 'postReply(this);');
reply_area.appendChild(reply_button);
var cancel_button = document.createElement('button');
cancel_button.innerHTML = 'cancel';
cancel_button.setAttribute('id', cancel_button_id);
cancel_button.setAttribute('onclick', 'hideReplyArea(this);');
reply_area.appendChild(cancel_button);
comment.getElementsByClassName('commentia-comment__reply-area')[0].appendChild(reply_area);
}
document.getElementById(reply_area_id).style.display = "block";
}
function hideReplyArea(caller) {
var comment = findCommentRoot(caller);
var ucid = comment.getAttribute('data-ucid');
var reply_area_id = 'reply-area-' + ucid;
document.getElementById(reply_area_id).style.display = "none";
}
function findCommentRoot(el) {
while ((el = el.parentNode) && !el.hasAttribute('data-ucid'));
return el;
}
function postReply(caller) {
var comment = findCommentRoot(caller);
var ucid = comment.getAttribute('data-ucid');
var reply_path = comment.getAttribute('data-reply-path');
var reply_box_id = 'reply-box-' + ucid;
var comments_section = document.getElementById("comments-container");
var content = encodeURI(document.getElementById(reply_box_id).value);
var params = "action=reply&content=" + content + "&reply_path=" + reply_path;
console.log("POST request to: " + window.commentia.APIURL + " with params: " + params);
ajax(window.commentia.APIURL, function () {
refreshComments();
}, params);
}
function postNewComment(caller) {
var comment_box_id = 'comment-box';
var comments_section = document.getElementById("comments-container");
var content = encodeURI(document.getElementById(comment_box_id).value);
var params = "action=postNewComment&content=" + content + "&username=user0";
console.log("POST request to: " + window.commentia.APIURL + " with params: " + params);
ajax(window.commentia.APIURL, function () {
refreshComments();
}, params);
http_request.open("POST", window.commentia.APIURL, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.send(params);
}
function deleteComment(caller) {
var url = window.commentia.APIURL + "?action=getPhrase&phrase=DIALOGS_DELETE_COMMENT";
var http_request = httpRequest();
var dialog_msg;
console.log("GET request to: " + url);
http_request.onreadystatechange = function() {
if (http_request.readyState === 4) {
dialog_msg = http_request.responseText;
http_request = null;
}
}
http_request.open("GET", url, false);
http_request.send();
if (confirm(dialog_msg)) {
var comments_section = document.getElementById("comments-container");
var comment = findCommentRoot(caller);
var ucid = comment.getAttribute('data-ucid');
var reply_path = comment.getAttribute('data-reply-path');
var params = "action=delete&ucid=" + ucid + "&reply_path=" + reply_path;
console.log("POST request to: " + window.commentia.APIURL + " with params: " + params);
var http_request = httpRequest();
http_request.onreadystatechange = function() {
if (http_request.readyState === 4) {
refreshComments();
http_request = null;
}
}
http_request.open("POST", window.commentia.APIURL, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.send(params);
}
}
function showEditArea(caller) {
var comment = findCommentRoot(caller);
var ucid = comment.getAttribute('data-ucid');
var reply_path = comment.getAttribute('data-reply-path');
var edit_area_id = 'edit-area-' + ucid;
var edit_box_id = 'edit-box-' + ucid;
var edit_button_id = 'edit-button-' + ucid;
var cancel_button_id = 'edit-cancel-button-' + ucid;
if (!document.getElementById(edit_area_id)) {
var edit_area = document.createElement('div');
edit_area.setAttribute('id', edit_area_id);
var edit_box = document.createElement('textarea');
edit_box.setAttribute('id', edit_box_id);
edit_box.setAttribute('oninput', "autoGrow(this);");
var url = window.commentia.APIURL + "?action=getCommentMarkdown&ucid=" + ucid + "&reply_path=" + reply_path;
var http_request = httpRequest();
console.log("GET request to: " + url);
http_request.onreadystatechange = function() {
if (http_request.readyState === 4) {
comment.getElementsByClassName('commentia-comment__content')[0].style.display = "none";
comment.getElementsByClassName('commentia-comment__edit-area')[0].appendChild(edit_area);
comment.getElementsByClassName('commentia-comment__edit-area')[0].style.display = "block";
edit_box.innerHTML = http_request.responseText;
document.getElementById(edit_box_id).style.height = document.getElementById(edit_box_id).scrollHeight + 'px';
http_request = null;
}
}
http_request.open("GET", url, true);
http_request.send();
edit_area.appendChild(edit_box);
var edit_button = document.createElement('button');
edit_button.innerHTML = 'edit';
edit_button.setAttribute('id', edit_button_id);
edit_button.setAttribute('onclick', 'editComment(this);');
edit_area.appendChild(edit_button);
var cancel_button = document.createElement('button');
cancel_button.innerHTML = 'cancel';
cancel_button.setAttribute('id', cancel_button_id);
cancel_button.setAttribute('onclick', 'hideEditArea(this);');
edit_area.appendChild(cancel_button);
} else {
comment.getElementsByClassName('commentia-comment__content')[0].style.display = "none";
comment.getElementsByClassName('commentia-comment__edit-area')[0].style.display = "block";
}
}
function hideEditArea(caller) {
var comment = findCommentRoot(caller);
comment.getElementsByClassName('commentia-comment__edit-area')[0].style.display = "none";
comment.getElementsByClassName('commentia-comment__content')[0].style.display = "block";
}
function editComment(caller) {
var comment = findCommentRoot(caller);
var ucid = comment.getAttribute('data-ucid');
var edit_box = document.getElementById('edit-box-' + ucid);
var reply_path = comment.getAttribute('data-reply-path');
var params = "action=edit&content=" + encodeURI(edit_box.value) + "&ucid=" + ucid + "&reply_path=" + reply_path;
var http_request = httpRequest();
console.log("POST request to: " + window.commentia.APIURL + " with params: " + params);
http_request.onreadystatechange = function() {
if (http_request.readyState === 4) {
refreshComments();
http_request = null;
}
}
http_request.open("POST", window.commentia.APIURL, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.send(params);
}
function autoGrow(caller) {
caller.style.height = "auto";
caller.style.height = (caller.scrollHeight + 5) + "px";
}
|
jQuery(document).ready(function() {
//VARIABLES
themeID = 0; //ONLY NEEDED IF WORKING ON THEME AND WANT TO RENDER LINKS w/THEME ID
brandCount = 0;
displayLimit = 10;
totalCount = 0;
searchTerm = $('#search-term').html(); //LOADS SEARCH TERM
systemLanguageDesk = $('#system_language').html(); //LOADS SYSTEM LANGUAGE
readArticle = $('#read-article').html(); //LOADS READ ARTICLE SNIPPET
//FOR EACH BRAND FUNCTION
$('#site-brands > div').each( function(i,e) {
//LOOP VARIABLES
brandID = e.id;
brandCount ++;
totalBrands = $('#site-brands > div').length;
brandName = e.textContent;
//ADDING TAB ELEMENTS FOR BRANDS AND ALL RESULTS
if (brandCount == 1) {
$('#siteResults ul.nav-tabs').append('<li role="presentation" class="active"><a href="#' + brandID + 'Results" aria-controls="' + brandID + 'Results" role="tab" data-toggle="tab">' + brandName + '</a></li>');
$('#siteResults div.tab-content').append('<div id="' + brandID + 'Results" role="tabpanel" class="tab-pane brand active"><div class="articles"></div><div class="footer col-md-12"></div></div>');
} else {
$('#siteResults ul.nav-tabs').append('<li role="presentation"><a href="#' + brandID + 'Results" aria-controls="' + brandID + 'Results" role="tab" data-toggle="tab">' + brandName + '</a></li>');
$('#siteResults div.tab-content').append('<div id="' + brandID + 'Results" role="tabpanel" class="tab-pane brand"><div class="articles"></div><div class="footer col-md-12"></div></div>');
}
MultiSearch = function(data) {
brandID = e.id;
resultsCount = 0;
auto_suggest_content = "";
auto_suggest_articles = "";
auto_suggest_questions = "";
$.each(data, function() {
var html = $(this.label);
article_title = html.find(".article-autocomplete-subject").html();
article_body = html.find(".article-autocomplete-body").html();
auto_suggest_articles += '<article class="row nomarg result article"><div class="col-md-12"><h3><a href="' + this.id + '&t=' + themeID + '">' + article_title + '</a></h3><p>' + article_body + '</p><a class="btn btn-pill" href="' + this.id + '">' + readArticle + '</a></div></article>';
resultsCount++;
});
totalCount = totalCount + resultsCount ;
if (resultsCount > 0) {
$('#siteResults div.tab-content div#' + brandID + 'Results .articles').append(auto_suggest_articles);
}
if (resultsCount >= 10) {
$('#siteResults div.tab-content div#' + brandID + 'Results .footer').append('<button class="next-page btn btn-primary" data-page="2" data-brand="'+brandID+'">Load More Results<i class="fa fa-spinner fa-spin hidden"></i></button>');
}
};
//NO RESULTS
MultiFail = function(data) {
brandID = e.id;
//DISPLAY NO RESULTS FOR BRAND
$('#' + brandID + ' > h3').removeClass('hidden');
};
//AJAX REQUEST
brandID = e.id;
$.ajax({
url: '//' + document.domain.toString() + '/customer/' + systemLanguageDesk + '/portal/articles/autocomplete?term=' + searchTerm + '&b_id=' + brandID,
dataType: 'json'
}).done(MultiSearch).fail(MultiFail);
}); //END OF EACH BRAND FUNCTION
//CHECK URL PARAMETER
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
displayMode = getParameterByName('displayMode');
//DISPLAY SITE WIDE RESULTS OR BRAND ONLY RESULTS
if (displayMode == "BrandOnly") {
$('#brandResults').removeClass('hidden');
$('#siteResults').addClass('hidden');
} else {
$('#brandResults').addClass('hidden');
$('#siteResults').removeClass('hidden');
}
$('body').on('click', 'button.next-page', function () {
brandID = $(this).attr('data-brand');
pageNumber = parseInt($(this).attr('data-page'));
searchTerm = $('#search-term').html(); //LOADS SEARCH TERM
systemLanguageDesk = $('#system_language').html(); //LOADS SYSTEM LANGUAGE
searchBrandURL = 'https://'+document.domain.toString()+'/customer/'+systemLanguageDesk+'/portal/articles/search?q='+searchTerm+'&page='+pageNumber+'&b_id='+brandID+'&displayMode=BrandOnly'
//AJAX REQUEST(S)
$.ajax({
async: true,
type: 'GET',
url: searchBrandURL,
beforeSend: function() {
$('#siteResults div.tab-content div#' + brandID + 'Results .footer .next-page i').removeClass('hidden');
},
complete: function() {
$('#siteResults div.tab-content div#' + brandID + 'Results .footer .next-page i').addClass('hidden');
++pageNumber
$('#siteResults div.tab-content div#' + brandID + 'Results .footer .next-page').attr('data-page', pageNumber );
},
success: function(data) {
var searchbrandResults = $(data).find('#brandResults .result');
var resultsCount = $(data).find('#results-count').html();
var nextUrl = $(data).find('#paginate_block a.next_page').attr('href');
if(! nextUrl) {
$('#siteResults div.tab-content div#' + brandID + 'Results button.next-page').hide();
$('#siteResults div.tab-content div#' + brandID + 'Results .footer').append('<h5> All ' + resultsCount + ' Results Loaded</h5>')
} else {
}
$('#siteResults div.tab-content div#' + brandID + 'Results .articles').append(searchbrandResults);
if(pageNumber == 2) {
$('a[href$="#' + brandID + 'Results"]').append('<span data-count="' + resultsCount + '"> (' + resultsCount + ')</span>');
}
},
fail: function(){
alert('no results');
}
});
});
}); |
angular.module("scripty11")
.factory("Item", function(filterFilter) {
var items = [
{id: 1, name: "Item 1", color: "red"},
{id: 2, name: "Item 2", color: "blue"},
{id: 3, name: "Item 3", color: "red"},
{id: 4, name: "Item 4", color: "white"}
];
return {
query: function(params) {
return filterFilter(items, params);
},
get: function(params) {
return this.query(params)[0];
}
};
});
|
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const path = require('path');
const pkg = require('../../../package.json');
const Helper_1 = __importDefault(require("../Helper"));
const MyError_1 = __importDefault(require("../MyError"));
const Result_1 = __importDefault(require("../Result"));
// post actions
const ACTIONS = [
'page',
'select',
'insert',
'update',
'_delete',
'rpc',
'logout',
'test',
];
class ViewerModule {
constructor(hostApp) {
this.hostApp = hostApp;
}
async init() {
this.css = (await Helper_1.default.getFilePaths(path.join(this.hostApp.getFrontendDirPath(), 'viewer'), 'css')).map(path => `/viewer/${path}`);
this.js = (await Helper_1.default.getFilePaths(path.join(this.hostApp.getFrontendDirPath(), 'viewer'), 'js')).map(path => `/viewer/${path}`);
// console.log('viewer.css:', this.css);
// console.log('viewer.js:' , this.js);
}
getLinks() {
return [
...(this.hostApp.commonModule.css),
...(this.css)
];
}
getScripts() {
return [
// '/lib/react/react.development.js',
// '/lib/react/react-dom.development.js',
'/lib/react/react.production.min.js',
'/lib/react/react-dom.production.min.js',
...(this.hostApp.commonModule.js),
...(this.js)
];
}
async handleViewerGet(context, application) {
console.log('ViewerModule.handleViewerGet', context.query /*, Object.keys(context.query).map(name => typeof context.query[name])*/);
if (application.isAuthentication() && !(context.getReq().session.user && context.getReq().session.user[context.getRoute()])) {
await this.loginGet(context, application);
}
else {
await application.connect(context);
try {
await application.initContext(context);
const response = await application.fill(context);
context.getRes().render('viewer/index', {
version: pkg.version,
application: application,
context: context,
response: response,
links: [
...this.getLinks(),
...application.links
],
scripts: [
...this.getScripts(),
...application.scripts
]
});
}
finally {
application.release(context);
}
}
}
async loginGet(context, application) {
console.log('ViewerModule.loginGet');
// const application = this.getApplication(context);
// const users = await application.getUsers(context);
context.getRes().render('viewer/login', {
version: pkg.version,
context: context,
application: application,
links: [
...this.getLinks(),
...application.links
],
scripts: [
...this.getScripts(),
...application.scripts
],
data: {
name: application.getName(),
text: application.getText(),
title: application.getTitle(context),
errMsg: null,
}
});
}
async handleViewerPost(context, application) {
// console.log('ViewerModule.handleViewerPost');
if (context.getReq().body.action === 'login') {
await this.loginPost(context, application);
}
else {
if (application.isAuthentication() && !(context.getReq().session.user && context.getReq().session.user[context.getRoute()])) {
throw new MyError_1.default({ message: 'Unauthorized', status: 401, context });
}
if (ACTIONS.indexOf(context.getReq().body.action) === -1) {
throw new Error(`unknown action: ${context.getReq().body.action}`);
}
return await this[context.getReq().body.action](context, application);
}
}
async loginPost(context, application) {
console.log('ViewerModule.loginPost');
const req = context.getReq();
const res = context.getRes();
if (req.body.tzOffset === undefined)
throw new Error('no tzOffset');
if (req.body.username === undefined)
throw new Error('no username');
if (req.body.password === undefined)
throw new Error('no password');
// const application = this.getApplication(context);
await application.connect(context);
try {
const user = await application.authenticate(context, req.body.username, req.body.password);
if (user) {
if (!user.id)
throw new Error('no user id');
if (!user.name)
throw new Error('no user name');
if (req.session.user === undefined) {
req.session.user = {};
}
req.session.ip = context.getIp();
req.session.tzOffset = JSON.parse(req.body.tzOffset);
req.session.user[context.getRoute()] = user;
res.redirect(req.url);
this.getHostApp().logEvent(context, `login ${application.getName()}/${context.getDomain()} ${user.name}`);
}
else {
// const users = await application.getUsers(context);
res.render('viewer/login', {
version: pkg.version,
context: context,
application: application,
links: [
...this.getLinks(),
...application.links
],
scripts: [
...this.getScripts(),
...application.scripts
],
data: {
name: application.getName(),
text: application.getText(),
title: application.getTitle(context),
errMsg: application.getText().login.WrongUsernameOrPassword,
username: req.body.username,
password: req.body.password,
}
});
}
}
finally {
application.release(context);
}
}
// action (fill page)
async page(context, application) {
console.log('ViewerModule.page', context.getReq().body.page);
const req = context.getReq();
const res = context.getRes();
await application.connect(context);
try {
await application.initContext(context);
const page = await application.getPage(context, req.body.page);
const response = await page.fill(context);
if (response === undefined)
throw new Error('page action: response is undefined');
await res.json({ page: response });
}
finally {
application.release(context);
}
}
// action
async select(context, application) {
console.log('ViewerModule.select', context.getReq().body.page);
const req = context.getReq();
const res = context.getRes();
const start = Date.now();
let dataSource;
if (req.body.page) {
const page = await application.getPage(context, req.body.page);
if (req.body.form) {
dataSource = page.getForm(req.body.form).getDataSource(req.body.ds);
}
else {
dataSource = page.getDataSource(req.body.ds);
}
}
else {
dataSource = application.getDataSource(req.body.ds);
}
await dataSource.getDatabase().connect(context);
try {
await application.initContext(context);
const [rows, count] = await dataSource.select(context);
const time = Date.now() - start;
console.log('select time:', time);
await res.json({ rows, count, time });
return time;
}
finally {
await dataSource.getDatabase().release(context);
}
}
// action
async insert(context, application) {
console.log('ViewerModule.insert', context.getReq().body.page);
const req = context.getReq();
const res = context.getRes();
// const application = this.getApplication(context);
const page = await application.getPage(context, req.body.page);
const form = page.getForm(req.body.form);
const dataSource = form.getDataSource('default');
const database = dataSource.getDatabase();
await database.connect(context);
try {
await application.initContext(context);
await database.begin(context);
try {
const result = await dataSource.insert(context);
if (result === undefined)
throw new Error('insert action: result is undefined');
await database.commit(context);
await res.json(result);
this.hostApp.broadcastResult(application, context, result);
}
catch (err) {
await database.rollback(context, err);
throw err;
}
}
finally {
database.release(context);
}
}
// action
async update(context, application) {
console.log('ViewerModule.update', context.getReq().body.page);
const req = context.getReq();
const res = context.getRes();
// const application = this.getApplication(context);
const page = await application.getPage(context, req.body.page);
const form = page.getForm(req.body.form);
const dataSource = form.getDataSource('default');
const database = dataSource.getDatabase();
await database.connect(context);
try {
await application.initContext(context);
await database.begin(context);
try {
const result = await dataSource.update(context);
if (result === undefined)
throw new Error('action update: result is undefined');
await database.commit(context);
await res.json(result);
this.hostApp.broadcastResult(application, context, result);
}
catch (err) {
await database.rollback(context, err);
throw err;
}
}
finally {
database.release(context);
}
}
// action
async _delete(context, application) {
console.log('ViewerModule._delete', context.getReq().body.page);
const req = context.getReq();
const res = context.getRes();
// const application = this.getApplication(context);
const page = await application.getPage(context, req.body.page);
const form = page.getForm(req.body.form);
const dataSource = form.getDataSource('default');
const database = dataSource.getDatabase();
await database.connect(context);
try {
await application.initContext(context);
await database.begin(context);
try {
const result = await dataSource.delete(context);
if (result === undefined)
throw new Error('delete result is undefined');
await database.commit(context);
await res.json(result);
this.hostApp.broadcastResult(application, context, result);
}
catch (err) {
await database.rollback(context, err);
throw err;
}
}
finally {
database.release(context);
}
}
// action
async rpc(context, application) {
console.log('ViewerModule.rpc', context.getReq().body);
const req = context.getReq();
const res = context.getRes();
// const application = this.getApplication(context);
// await application.initContext(context);
let model;
if (req.body.page) {
if (req.body.form) {
const page = await application.getPage(context, req.body.page);
model = page.getForm(req.body.form);
}
else {
model = await application.getPage(context, req.body.page);
}
}
else {
model = application;
}
try {
const result = await model.rpc(req.body.name, context);
if (result === undefined)
throw new Error('rpc action: result is undefined');
if (Array.isArray(result)) {
const [response, _result] = result;
await res.json(response);
if (!(_result instanceof Result_1.default)) {
throw new Error('_result is not Result');
}
this.hostApp.broadcastResult(application, context, _result);
}
else {
await res.json(result);
if (result instanceof Result_1.default) {
this.hostApp.broadcastResult(application, context, result);
}
}
}
catch (err) {
const errorMessage = err.message;
err.message = `rpc error ${req.body.name}: ${err.message}`;
err.context = context;
await this.hostApp.logError(err, req);
await res.json({ errorMessage });
}
}
// action
async logout(context, application) {
console.log('ViewerModule.logout');
const req = context.getReq();
const res = context.getRes();
if (!req.session.user || !req.session.user[context.getRoute()]) {
throw new Error(`no user for route ${context.getRoute()}`);
}
delete req.session.user[context.getRoute()];
await Helper_1.default.Session_save(req.session);
await res.json(null);
}
// action
async test(context, application) {
console.log('ViewerModule.test', context.getReq().body);
const req = context.getReq();
const res = context.getRes();
// const result = await Test[req.body.name](req, res, context, application);
// if (result === undefined) throw new Error('test action: result is undefined');
await res.json(null);
}
async handleViewerGetFile(context, application, next) {
await application.handleGetFile(context, next);
}
getHostApp() {
return this.hostApp;
}
}
module.exports = ViewerModule;
|
var oc = {};
oc.instances = {};
oc.cloneObject = function(obj){
var result = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) result[key] = obj[key];
}
return result;
}
if(oc.std == null){
oc.std = {};
}
oc.std.ff = (function(){
function print(x){ console.log(x); }
function addAny(x,y){ return x + y; }
function mulAny(x,y){ return x * y; }
function subAny(x,y){ return x - y; }
function eqAny(x,y){ return x === y; }
function showAny(x){ return x + ""; }
var unit = {}
var emptyObject = {}
var eqInt = eqAny;
var eqDouble = eqAny;
var eqString = eqAny;
var eqChar = eqAny;
var eqBool = eqAny;
var showInt = showAny;
var showDouble = showAny;
var showString = showAny;
var showChar = showAny;
var showBool = showAny;
var addInt = addAny
var mulInt = mulAny
var subInt = subAny
var divInt = function(x,y){return x / y | 0;}
var addDouble = addAny
var mulDouble = mulAny
var subDouble = subAny
var divDouble = function(x,y){return x / y;}
var addBool = function(x,y){return x || y}
var mulBool = function(x,y){return x && y}
var not = function(x){return !x}
var orBool = function(x,y){return x || y}
var andBool = function(x,y){return x && y}
var appendString = addAny
return {
unit : unit,
showInt : showInt,
showDouble : showDouble,
showString : showString,
showChar : showChar,
showBool : showBool,
eqAny : eqAny,
eqInt : eqInt,
eqDouble : eqDouble,
eqString : eqString,
eqChar : eqChar,
eqBool : eqBool,
not : not,
andBool : andBool,
orBool : orBool,
addInt : addInt,
mulInt : mulInt,
subInt : subInt,
divInt : divInt,
addDouble : addDouble,
mulDouble : mulDouble,
subDouble : subDouble,
divDouble : divDouble,
appendString : appendString,
print : print
}
})();
if(oc.std == null){
oc.std = {};
}
oc.std.numbers = (function(){
oc.instances.add = {};
var add = function(x,p1,p2){
return x(p1,p2);
};
oc.instances.zero = {};
var zero = function(x){
return x;
};
oc.instances.mul = {};
var mul = function(x,p1,p2){
return x(p1,p2);
};
oc.instances.one = {};
var one = function(x){
return x;
};
oc.instances.sub = {};
var sub = function(x,p1,p2){
return x(p1,p2);
};
oc.instances.div = {};
var div = function(x,p1,p2){
return x(p1,p2);
};
oc.instances.add.Int = oc.std.ff.addInt;
oc.instances.mul.Int = oc.std.ff.mulInt;
oc.instances.zero.Int = 0;
oc.instances.one.Int = 1;
oc.instances.sub.Int = oc.std.ff.subInt;
oc.instances.div.Int = oc.std.ff.divInt;
oc.instances.add.Double = oc.std.ff.addDouble;
oc.instances.mul.Double = oc.std.ff.mulDouble;
oc.instances.zero.Double = 0.0;
oc.instances.one.Double = 1.0;
oc.instances.sub.Double = oc.std.ff.subDouble;
oc.instances.div.Double = oc.std.ff.divDouble;
var negate = function(_nzero,_nsub,x){
return _nsub(zero(_nzero),x);
};
return {
add : add,
zero : zero,
mul : mul,
one : one,
sub : sub,
div : div,
negate : negate
}
})();
oc.testModule = (function(){
oc.instances.zero = {};
var zero = function(x){
return x;
};
var x = 1;
return {
zero : zero,
x : x
}
})();
oc.test_import = (function(){
oc.instances.zero.Int = 0;
return {}
})();
|
import React from 'react';
export default class PilotTripCard extends React.Component { //eslint-disable-line
render() {
const { detailedInfo, pilotStatus, totalTask, completedTask, pilotDistance } = this.props;
return (
<a onClick={detailedInfo} style={{ textDecoration: 'none', color: 'inherit' }}>
<div className="trip-card pilot-boxShadow block-background marginBottom" style={{ fontSize: '0.7rem', padding: '1em' }}>
<div className="first-row ink-flex" style={{ paddingBottom: '0.3em' }}>
<div className="all-100 ink-flex push-left">
<div className="trip-info ink-flex vertical" style={{ marginLeft: '0.7em', fontSize: '1.2em' }}>
<div>{pilotStatus}</div>
</div>
</div>
</div>
<div className="second-row ink-flex">
<div className="all-50 ink-flex push-left">
<div className="trip-info ink-flex vertical">
<div className="sub-title">Tasks Completed</div>
<div>{completedTask} of {totalTask}</div>
</div>
</div>
<div className="all-50 ink-flex push-right">
<div className="trip-info ink-flex vertical" style={{ textAlign: 'right' }}>
<div className="sub-title">Travelled so far</div>
<div>{pilotDistance} Km</div>
</div>
</div>
</div>
</div>
</a>
);
}
}
|
// Manage imports of user emails from external providers
export const createMailImport = (data) => ({
url: 'mail/v4/importers',
method: 'post',
data,
});
export const getMailImports = () => ({
url: 'mail/v4/importers',
method: 'get',
});
export const getMailImport = (importID, params) => ({
url: `mail/v4/importers/${importID}`,
method: 'get',
params,
});
export const updateMailImport = (importID, data) => ({
url: `mail/v4/importers/${importID}`,
method: 'put',
data,
});
export const deleteMailImport = (importID) => ({
url: `mail/v4/importers/${importID}`,
method: 'delete',
});
export const startMailImportJob = (importID, data) => ({
url: `mail/v4/importers/${importID}`,
method: 'post',
data,
});
export const resumeMailImportJob = (importID) => ({
url: `mail/v4/importers/${importID}/resume`,
method: 'put',
});
export const cancelMailImportJob = (importID) => ({
url: `mail/v4/importers/${importID}/cancel`,
method: 'put',
});
export const getMailImportFolders = (importID, params) => ({
url: `mail/v4/importers/${importID}/folders`,
method: 'get',
params,
});
export const getMailImportReports = () => ({
url: 'mail/v4/importers/reports',
method: 'get',
});
export const deleteMailImportReport = (reportID) => ({
url: `mail/v4/importers/reports/${reportID}`,
method: 'delete',
});
export const getAuthenticationMethod = (params) => ({
url: 'mail/v4/importers/authinfo',
method: 'get',
params,
});
export const deleteSource = (importID) => ({
url: `mail/v4/importers/reports/${importID}/deletesource`,
method: 'put',
});
|
Template.toimenpiteetIndex.helpers({
kouvola: function () {
return Kunnat.find({kunta: "Kouvola"});
}
});
Template.toimenpiteetIndex.events = {
'click #btnRemove': function(e) {
e.preventDefault();
if (confirm("Haluatko varmasti poistaa tavoitteen?"))
Router.current().remove(this._id);
},
/* sorting by parameter */
'click #btnSortkunta': function(e) {
MeteorisGridView.sort('kunta');
},
/* sorting by parameter */
'click #btnSorttoimiala': function(e) {
MeteorisGridView.sort('toimiala');
},
/* sorting by parameter */
'click #btnSorttoimenpide': function(e) {
MeteorisGridView.sort('toimenpide');
},
/* sorting by parameter */
'click #btnSorttilanne': function(e) {
MeteorisGridView.sort('tilanne');
},
/* sorting by parameter */
'click #btnSortsuunnitelma': function(e) {
MeteorisGridView.sort('suunnitelma');
},
/* sorting by parameter */
'click #btnSortpaivitetty': function(e) {
MeteorisGridView.sort('paivitetty');
},
/* sorting by parameter */
'click #btnSortyhteys': function(e) {
MeteorisGridView.sort('yhteys');
},
'keyup #search': function(e, t) {
e.preventDefault();
Router.current().search(t);
},
/* check all checkbox */
'change #checkAll': function(e) {
e.preventDefault();
var checkboxes = $('.checkAll');
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = e.target.checked;
}
},
/* remove all selected item */
'click #btnRemoveAll': function(e) {
e.preventDefault();
var checkboxes = $('.checkAll');
var checkedLength = 0;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
checkedLength++;
}
}
if (checkedLength > 0) {
if (confirm("Haluatko varmasti poistaa tavoitteen (Yhteensä " + checkedLength + " tavoitetta poistetaan)")) {
// loop over them all
for (var i = 0; i < checkboxes.length; i++) {
// And stick the checked ones onto an array...
if (checkboxes[i].checked) {
Router.current().remove($(checkboxes[i]).val());
}
}
}
} else {
MeteorisFlash.set('danger', 'Valitse poistettava kohde');
}
//set checkAll header to uncheck
$('#checkAll').attr("checked", false);
},
}; |
$(function () {
$(".animsition").animsition({
inClass: 'zoom-in-sm',
outClass: 'zoom-out-sm',
inDuration: 1500,
outDuration: 800,
linkElement: '.animsition-link',
// e.g. linkElement : 'a:not([target="_blank"]):not([href^=#])'
loading: true,
loadingParentElement: 'body', //animsition wrapper element
loadingClass: 'animsition-loading',
unSupportCss: ['animation-duration',
'-webkit-animation-duration',
'-o-animation-duration'
],
overlay: false,
overlayClass: 'animsition-overlay-slide',
overlayParentElement: 'body'
});
});
$(function () {
//Show event modal from clicking event on calendar
$('tbody.event-calendar').on('click', '.event', function () {
var monthEvent = $(this).attr('data-month');
var dayEvent = $(this).text();
var eventContent = $('.day-event[data-month="' + monthEvent + '"][data-day="' + dayEvent + '"]').children('.event-content').clone();
var targetModal = $('#showEventModal');
targetModal.find('.modal-body').append(eventContent);
targetModal.modal('show');
});
$('#showEventModal').on('hidden.bs.modal', function (e) {
$(this).find('.modal-body').html('');
});
});
// category and sub-category page script START Here
$(document).ready(function () {
$('.edit-category').on('click', function () {
var categoryid=$(this).attr("id");
var categoryname=$(this).attr("data-category");
var categorystatus=$(this).attr("data-status");
$('#editcategoryid').val(categoryid);
$('#editcategoryname').val(categoryname);
$('#editcategorystatus').val(categorystatus);
$('.editCategory').show();
});
$('.edit-toggle').on('click', function () {
$('.editCategory').hide();
});
$('.delete-category').on('click', function () {
var categoryid=$(this).attr("id");
$('#deletecategoryid').val(categoryid);
$('#deleteModal').modal('show');
});
$('.addsubcategory').on('click', function () {
var categoryid= $(this).attr('id');
$('#addcategoryid').val(categoryid);
$('#addModal').modal('show');
});
$('.edit-subcategory').on('click', function () {
var categoryid=$(this).attr("data-category-id");
var subcategoryid=$(this).attr("id");
var subcategoryname=$(this).attr("data-subcategory");
var subcategorystatus=$(this).attr("data-substatus");
$('#editcategoryid').val(categoryid);
$('#editsubcategoryid').val(subcategoryid);
$('#editsubcategoryname').val(subcategoryname);
$('#editsubcategorystatus').val(subcategorystatus);
$('.editSubCategory').show();
});
$('.edit-subtoggle').on('click', function () {
$('.editSubCategory').hide();
});
$('.delete-subcategory').on('click', function () {
var subcategoryid=$(this).attr("id");
var categoryid=$(this).attr("data-category-id");
$('#deletesubcategoryid').val(subcategoryid);
$('#deletecategoryid').val(categoryid);
$('#deleteModal').modal('show');
});
$('.updatemap').on('click', function () {
console.log("change")
});
});
// END Here |
angular.module('chatty')
.directive('embedContent', function($sce) {
return {
restrict: 'E',
templateUrl: 'embedContent/embedContent.html',
scope: {
url: '@',
type: '@'
},
controller: function($scope) {
$scope.toggleVisibility = function() {
$scope.visible = !$scope.visible
}
$scope.fixUrl = function(regex, fixed) {
var rex = new RegExp(regex)
var url = $scope.url.replace(rex, fixed)
return $sce.trustAsResourceUrl(url)
}
$scope.testFixUrl = function(tests) {
var result = _.find(tests, function(test) {
var rex = new RegExp(test.test)
return rex.test($scope.url)
})
if (result) {
return $scope.fixUrl(result.regex, result.replace)
} else {
return $scope.url
}
}
}
}
})
|
(function(ns, App) {
ns.Commands.RemoveNoteCommand = function(event) {
App.remove(event.get('data'));
}
})(this.ns, this.App); //dependencies |
(function() {
'use strict';
var _ = require('lodash');
var hooks = require('./hooks');
var plumber = require('gulp-plumber');
var Promise = require('bluebird');
var runner = require('./runner');
var vfs = require('vinyl-fs');
var write = process.stdout.write;
/**
* Promisify the execution of an orchestrator task. Listens to orchestrator events to fulfill/reject the promise.
*
* @name start
* @param {string} name - The name of the task to run.
* @param {object} [options] - Options passed to the task runner. Uses options.verbose and options.quiet
* @param {boolean} [runHooks=true] - Whether or not to execute the hooks for the task. defaults to true.
* @return {promise} - Resolves if the task completes successfuly, rejects with the error object if the task fails.
* @see https://github.com/robrich/orchestrator#event
*/
function start(name, options, runHooks) {
options = options || {};
runHooks = runHooks !== false; // default to true if not explicitly set to false
if (runHooks) {
hooks.run(name, '__pre', options);
hooks.run(name, 'before', options);
}
return new Promise(function(resolve, reject) {
if (!options.verbose && options.quiet) {
process.stdout.write = _.noop;
}
runner.start(name, function(err) {
process.stdout.write = write;
if (err) {
reject(err);
} else {
if (runHooks) {
hooks.run(name, 'done', options);
hooks.run(name, '__post', options);
}
resolve();
}
});
});
}
module.exports = start;
})(); |
var mongoose = require('mongoose'),
// slug = require('slug'),
// ub = App.require('/helpers/ub'),
InquiriesSchema = new mongoose.Schema({
created: {type:Number, default: Date.now()},
givenName: String,
familyName: String,
email: String,
phone: String,
message: String,
age: String,
gender: String,
address: String,
city: String,
state: String,
zip: String
});
module.exports = mongoose.model('Inquiry', InquiriesSchema);
|
'use strict';
var assert = require('assert'),
path = require('path'),
helpers = require('yeoman-generator').test;
describe('HTML5 Boilerplate generator', function () {
before(function (done) {
helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
if (err) {
return done(err);
}
this.app = helpers.createGenerator('chaplin:app', [
'../../app'
]);
done();
}.bind(this));
});
it('creates expected files', function (done) {
var expected = [
'bower.json',
'config.json',
'package.json',
'Gruntfile.coffee',
'app/application.coffee',
'app/initialize.coffee',
'app/mediator.coffee',
'app/routes.coffee',
'app/lib/utils.coffee',
'app/lib/view-helper.coffee',
'app/styles/application.styl',
'app/templates/home.hbs',
'app/templates/site.hbs',
//'app/controllers/home.coffee', Need to figure this one out
'app/controllers/base/controller.coffee',
'app/assets/apple-touch-icon-114x114-precomposed.png',
'app/assets/apple-touch-icon-144x144-precomposed.png',
'app/assets/apple-touch-icon-57x57-precomposed.png',
'app/assets/apple-touch-icon-72x72-precomposed.png',
'app/assets/apple-touch-icon-precomposed.png',
'app/assets/apple-touch-icon.png',
'app/assets/favicon.ico',
'app/assets/index.hbs',
'app/models/base/collection.coffee',
'app/models/base/model.coffee',
'app/views/base/collection-view.coffee',
'app/views/base/view.coffee',
'app/views/home/home-page.coffee',
'app/views/site-view.coffee',
'vendor/main.css',
'vendor/normalize.css',
'.jshintrc',
'.editorconfig'
];
helpers.mockPrompt(this.app, {
'appName': 'html5bptest',
'controllerSuffix': '',
'skeleton': '1'
});
this.app.options['skip-install'] = true;
this.app.run({}, function () {
helpers.assertFiles(expected);
done();
});
});
it('can be imported without blowing up', function () {
var app = require('../app');
assert(app !== undefined);
});
});
|
/* GET users listing. */
exports.list = function(req, res) {
res.send('Maka Paka');
}; |
window.pdfMake = window.pdfMake || {}; window.pdfMake.fonts = {"Suravaram":{"normal":"Suravaram-Regular.ttf","bold":"Suravaram-Regular.ttf","italics":"Suravaram-Regular.ttf","bolditalics":"Suravaram-Regular.ttf"}}; |
/**
* Represents a class that loads UserInterface objects from some source for the authentication system.
*
* In a typical authentication configuration, a username (i.e. some unique
* user identifier) credential enters the system (via form login, or any
* method). The user provider that is configured with that authentication
* method is asked to load the UserInterface object for the given username
* (via loadUserByUsername) so that the rest of the process can continue.
*
* Internally, a user provider can load users from any source (databases,
* configuration, web service). This is totally independent of how the authentication
* information is submitted or what the UserInterface object looks like.
*
* @see {Jymfony.Component.Security.User.UserInterface}
*
* @memberOf Jymfony.Component.Security.User
*/
class UserProviderInterface {
/**
* Loads the user for the given username.
*
* This method must throw UsernameNotFoundException if the user is not
* found.
*
* @param {string} username The username
*
* @returns {Promise<Jymfony.Component.Security.User.UserInterface>}
*
* @throws {Jymfony.Component.Security.Exception.UsernameNotFoundException} if the user is not found
*/
async loadUserByUsername(username) { }
/**
* Refreshes the user.
*
* It is up to the implementation to decide if the user data should be
* totally reloaded (e.g. from the database), or if the UserInterface
* object can just be merged into some internal array of users / identity
* map.
*
* @return {Promise<Jymfony.Component.Security.User.UserInterface>}
*
* @throws {Jymfony.Component.Security.Exception.UnsupportedUserException} if the user is not supported
* @throws {Jymfony.Component.Security.Exception.UsernameNotFoundException} if the user is not found
*/
async refreshUser(user) { }
/**
* Whether this provider supports the given user class.
*
* @param {string} class_
*
* @return {boolean}
*/
supportsClass(class_) { }
}
export default getInterface(UserProviderInterface);
|
//~ name c499
alert(c499);
//~ component c500.js
|
import _ from 'lodash' // eslint-disable-line
import React, {PropTypes} from 'react'
import warning from 'warning'
import {Link} from 'react-router'
import {Grid, Row, Col, Glyphicon} from 'react-bootstrap'
import createModelDetailForm from '../components/create/ModelDetailForm'
export default function ModelDetail(props) {
const {modelAdmin, modelStore, id, config, handleSaveFn, handleDeleteFn} = props
const modelIm = modelStore.get('models').get(id)
const model = modelIm ? modelIm.toJSON() : {}
warning(model, `[fl-admin] ModelDetail: Model ${modelAdmin.name} not loaded with id ${id}`)
const ModelDetailForm = createModelDetailForm(model)
return (
<section className="fla-model-detail">
<Grid fluid>
<Row>
<Col xs={12}>
<p className="fla-back"><Link to={modelAdmin.link()}><Glyphicon glyph="chevron-left" />{modelAdmin.plural}</Link></p>
</Col>
</Row>
<Row>
<Col xs={12}>
<h1>{modelAdmin.display(model)}</h1>
</Col>
</Row>
<ModelDetailForm
formKey={model.id}
model={model}
modelAdmin={modelAdmin}
config={config}
onSubmit={handleSaveFn(model)}
onDelete={handleDeleteFn(model)}
/>
</Grid>
</section>
)
}
ModelDetail.propTypes = {
id: PropTypes.string,
modelStore: PropTypes.object,
modelAdmin: PropTypes.object,
// config: PropTypes.object,
handleSaveFn: PropTypes.func,
handleDeleteFn: PropTypes.func,
}
|
import test from 'ava';
import path from 'path';
import { transcludeString } from '../../src/hercule';
test.cb('should transclude with only required arguments', t => {
const input = 'The quick brown fox jumps over the lazy dog.';
const expected = 'The quick brown fox jumps over the lazy dog.';
transcludeString(input, (err, output) => {
t.deepEqual(err, null);
t.deepEqual(output, expected);
t.end();
});
});
test.cb('should transclude with optional source argument', t => {
const input = 'The quick brown fox jumps over the lazy dog.';
const expected = 'The quick brown fox jumps over the lazy dog.';
transcludeString(input, { source: 'test' }, (err, output) => {
t.deepEqual(err, null);
t.deepEqual(output, expected);
t.end();
});
});
test.cb('returns sourcemap', t => {
const input = 'Jackdaws love my :[size link](size.md) sphinx of quartz.';
const options = {
source: path.join(__dirname, '../fixtures/local-link/index.md'),
};
const expected = 'Jackdaws love my big sphinx of quartz.';
transcludeString(input, options, (err, output, sourcemap) => {
t.deepEqual(err, null);
t.deepEqual(output, expected);
t.deepEqual(sourcemap.sources.length, 2);
t.end();
});
});
test.cb('returns error for invalid links', t => {
const input =
'Jackdaws love my :[missing](i-dont-exist.md) sphinx of :[missing](mineral.md)';
const options = {
source: path.join(__dirname, '../fixtures/invalid-link/index.md'),
};
transcludeString(input, options, err => {
t.regex(err.message, /ENOENT/);
t.regex(err.path, /fixtures\/invalid-link\/i-dont-exist.md/);
t.end();
});
});
|
/*! Hammer.JS - v2.0.4 - 2014-09-28
* http://hammerjs.github.io/
*
* Copyright (c) 2014 Jorik Tangelder;
* Licensed under the MIT license */
(function(window, document, exportName, undefined) {
'use strict';
var VENDOR_PREFIXES = ['', 'webkit', 'moz', 'MS', 'ms', 'o'];
var TEST_ELEMENT = document.createElement('div');
var TYPE_FUNCTION = 'function';
var round = Math.round;
var abs = Math.abs;
var now = Date.now;
/**
* set a timeout with a given scope
* @param {Function} fn
* @param {Number} timeout
* @param {Object} context
* @returns {number}
*/
function setTimeoutContext(fn, timeout, context) {
return setTimeout(bindFn(fn, context), timeout);
}
/**
* if the argument is an array, we want to execute the fn on each entry
* if it aint an array we don't want to do a thing.
* this is used by all the methods that accept a single and array argument.
* @param {*|Array} arg
* @param {String} fn
* @param {Object} [context]
* @returns {Boolean}
*/
function invokeArrayArg(arg, fn, context) {
if (Array.isArray(arg)) {
each(arg, context[fn], context);
return true;
}
return false;
}
/**
* walk objects and arrays
* @param {Object} obj
* @param {Function} iterator
* @param {Object} context
*/
function each(obj, iterator, context) {
var i;
if (!obj) {
return;
}
if (obj.forEach) {
obj.forEach(iterator, context);
} else if (obj.length !== undefined) {
i = 0;
while (i < obj.length) {
iterator.call(context, obj[i], i, obj);
i++;
}
} else {
for (i in obj) {
obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);
}
}
}
/**
* extend object.
* means that properties in dest will be overwritten by the ones in src.
* @param {Object} dest
* @param {Object} src
* @param {Boolean} [merge]
* @returns {Object} dest
*/
function extend(dest, src, merge) {
var keys = Object.keys(src);
var i = 0;
while (i < keys.length) {
if (!merge || (merge && dest[keys[i]] === undefined)) {
dest[keys[i]] = src[keys[i]];
}
i++;
}
return dest;
}
/**
* merge the values from src in the dest.
* means that properties that exist in dest will not be overwritten by src
* @param {Object} dest
* @param {Object} src
* @returns {Object} dest
*/
function merge(dest, src) {
return extend(dest, src, true);
}
/**
* simple class inheritance
* @param {Function} child
* @param {Function} base
* @param {Object} [properties]
*/
function inherit(child, base, properties) {
var baseP = base.prototype,
childP;
childP = child.prototype = Object.create(baseP);
childP.constructor = child;
childP._super = baseP;
if (properties) {
extend(childP, properties);
}
}
/**
* simple function bind
* @param {Function} fn
* @param {Object} context
* @returns {Function}
*/
function bindFn(fn, context) {
return function boundFn() {
return fn.apply(context, arguments);
};
}
/**
* let a boolean value also be a function that must return a boolean
* this first item in args will be used as the context
* @param {Boolean|Function} val
* @param {Array} [args]
* @returns {Boolean}
*/
function boolOrFn(val, args) {
if (typeof val == TYPE_FUNCTION) {
return val.apply(args ? args[0] || undefined : undefined, args);
}
return val;
}
/**
* use the val2 when val1 is undefined
* @param {*} val1
* @param {*} val2
* @returns {*}
*/
function ifUndefined(val1, val2) {
return (val1 === undefined) ? val2 : val1;
}
/**
* addEventListener with multiple events at once
* @param {EventTarget} target
* @param {String} types
* @param {Function} handler
*/
function addEventListeners(target, types, handler) {
each(splitStr(types), function(type) {
target.addEventListener(type, handler, false);
});
}
/**
* removeEventListener with multiple events at once
* @param {EventTarget} target
* @param {String} types
* @param {Function} handler
*/
function removeEventListeners(target, types, handler) {
each(splitStr(types), function(type) {
target.removeEventListener(type, handler, false);
});
}
/**
* find if a node is in the given parent
* @method hasParent
* @param {HTMLElement} node
* @param {HTMLElement} parent
* @return {Boolean} found
*/
function hasParent(node, parent) {
while (node) {
if (node == parent) {
return true;
}
node = node.parentNode;
}
return false;
}
/**
* small indexOf wrapper
* @param {String} str
* @param {String} find
* @returns {Boolean} found
*/
function inStr(str, find) {
return str.indexOf(find) > -1;
}
/**
* split string on whitespace
* @param {String} str
* @returns {Array} words
*/
function splitStr(str) {
return str.trim().split(/\s+/g);
}
/**
* find if a array contains the object using indexOf or a simple polyFill
* @param {Array} src
* @param {String} find
* @param {String} [findByKey]
* @return {Boolean|Number} false when not found, or the index
*/
function inArray(src, find, findByKey) {
if (src.indexOf && !findByKey) {
return src.indexOf(find);
} else {
var i = 0;
while (i < src.length) {
if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) {
return i;
}
i++;
}
return -1;
}
}
/**
* convert array-like objects to real arrays
* @param {Object} obj
* @returns {Array}
*/
function toArray(obj) {
return Array.prototype.slice.call(obj, 0);
}
/**
* unique array with objects based on a key (like 'id') or just by the array's value
* @param {Array} src [{id:1},{id:2},{id:1}]
* @param {String} [key]
* @param {Boolean} [sort=False]
* @returns {Array} [{id:1},{id:2}]
*/
function uniqueArray(src, key, sort) {
var results = [];
var values = [];
var i = 0;
while (i < src.length) {
var val = key ? src[i][key] : src[i];
if (inArray(values, val) < 0) {
results.push(src[i]);
}
values[i] = val;
i++;
}
if (sort) {
if (!key) {
results = results.sort();
} else {
results = results.sort(function sortUniqueArray(a, b) {
return a[key] > b[key];
});
}
}
return results;
}
/**
* get the prefixed property
* @param {Object} obj
* @param {String} property
* @returns {String|Undefined} prefixed
*/
function prefixed(obj, property) {
var prefix, prop;
var camelProp = property[0].toUpperCase() + property.slice(1);
var i = 0;
while (i < VENDOR_PREFIXES.length) {
prefix = VENDOR_PREFIXES[i];
prop = (prefix) ? prefix + camelProp : property;
if (prop in obj) {
return prop;
}
i++;
}
return undefined;
}
/**
* get a unique id
* @returns {number} uniqueId
*/
var _uniqueId = 1;
function uniqueId() {
return _uniqueId++;
}
/**
* get the window object of an element
* @param {HTMLElement} element
* @returns {DocumentView|Window}
*/
function getWindowForElement(element) {
var doc = element.ownerDocument;
return (doc.defaultView || doc.parentWindow);
}
var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
var SUPPORT_TOUCH = ('ontouchstart' in window);
var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined;
var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent);
var INPUT_TYPE_TOUCH = 'touch';
var INPUT_TYPE_PEN = 'pen';
var INPUT_TYPE_MOUSE = 'mouse';
var INPUT_TYPE_KINECT = 'kinect';
var COMPUTE_INTERVAL = 25;
var INPUT_START = 1;
var INPUT_MOVE = 2;
var INPUT_END = 4;
var INPUT_CANCEL = 8;
var DIRECTION_NONE = 1;
var DIRECTION_LEFT = 2;
var DIRECTION_RIGHT = 4;
var DIRECTION_UP = 8;
var DIRECTION_DOWN = 16;
var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT;
var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN;
var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;
var PROPS_XY = ['x', 'y'];
var PROPS_CLIENT_XY = ['clientX', 'clientY'];
/**
* create new input type manager
* @param {Manager} manager
* @param {Function} callback
* @returns {Input}
* @constructor
*/
function Input(manager, callback) {
var self = this;
this.manager = manager;
this.callback = callback;
this.element = manager.element;
this.target = manager.options.inputTarget;
// smaller wrapper around the handler, for the scope and the enabled state of the manager,
// so when disabled the input events are completely bypassed.
this.domHandler = function(ev) {
if (boolOrFn(manager.options.enable, [manager])) {
self.handler(ev);
}
};
this.init();
}
Input.prototype = {
/**
* should handle the inputEvent data and trigger the callback
* @virtual
*/
handler: function() { },
/**
* bind the events
*/
init: function() {
this.evEl && addEventListeners(this.element, this.evEl, this.domHandler);
this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler);
this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
},
/**
* unbind the events
*/
destroy: function() {
this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler);
this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler);
this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
}
};
/**
* create new input type manager
* called by the Manager constructor
* @param {Hammer} manager
* @returns {Input}
*/
function createInputInstance(manager) {
var Type;
var inputClass = manager.options.inputClass;
if (inputClass) {
Type = inputClass;
} else if (SUPPORT_POINTER_EVENTS) {
Type = PointerEventInput;
} else if (SUPPORT_ONLY_TOUCH) {
Type = TouchInput;
} else if (!SUPPORT_TOUCH) {
Type = MouseInput;
} else {
Type = TouchMouseInput;
}
return new (Type)(manager, inputHandler);
}
/**
* handle input events
* @param {Manager} manager
* @param {String} eventType
* @param {Object} input
*/
function inputHandler(manager, eventType, input) {
var pointersLen = input.pointers.length;
var changedPointersLen = input.changedPointers.length;
var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0));
var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0));
input.isFirst = !!isFirst;
input.isFinal = !!isFinal;
if (isFirst) {
manager.session = {};
}
// source event is the normalized value of the domEvents
// like 'touchstart, mouseup, pointerdown'
input.eventType = eventType;
// compute scale, rotation etc
computeInputData(manager, input);
// emit secret event
manager.emit('hammer.input', input);
manager.recognize(input);
manager.session.prevInput = input;
}
/**
* extend the data with some usable properties like scale, rotate, velocity etc
* @param {Object} manager
* @param {Object} input
*/
function computeInputData(manager, input) {
var session = manager.session;
var pointers = input.pointers;
var pointersLength = pointers.length;
// store the first input to calculate the distance and direction
if (!session.firstInput) {
session.firstInput = simpleCloneInputData(input);
}
// to compute scale and rotation we need to store the multiple touches
if (pointersLength > 1 && !session.firstMultiple) {
session.firstMultiple = simpleCloneInputData(input);
} else if (pointersLength === 1) {
session.firstMultiple = false;
}
var firstInput = session.firstInput;
var firstMultiple = session.firstMultiple;
var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;
var center = input.center = getCenter(pointers);
input.timeStamp = now();
input.deltaTime = input.timeStamp - firstInput.timeStamp;
input.angle = getAngle(offsetCenter, center);
input.distance = getDistance(offsetCenter, center);
computeDeltaXY(session, input);
input.offsetDirection = getDirection(input.deltaX, input.deltaY);
input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;
input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;
computeIntervalInputData(session, input);
// find the correct target
var target = manager.element;
if (hasParent(input.srcEvent.target, target)) {
target = input.srcEvent.target;
}
input.target = target;
}
function computeDeltaXY(session, input) {
var center = input.center;
var offset = session.offsetDelta || {};
var prevDelta = session.prevDelta || {};
var prevInput = session.prevInput || {};
if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) {
prevDelta = session.prevDelta = {
x: prevInput.deltaX || 0,
y: prevInput.deltaY || 0
};
offset = session.offsetDelta = {
x: center.x,
y: center.y
};
}
input.deltaX = prevDelta.x + (center.x - offset.x);
input.deltaY = prevDelta.y + (center.y - offset.y);
}
/**
* velocity is calculated every x ms
* @param {Object} session
* @param {Object} input
*/
function computeIntervalInputData(session, input) {
var last = session.lastInterval || input,
deltaTime = input.timeStamp - last.timeStamp,
velocity, velocityX, velocityY, direction;
if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) {
var deltaX = last.deltaX - input.deltaX;
var deltaY = last.deltaY - input.deltaY;
var v = getVelocity(deltaTime, deltaX, deltaY);
velocityX = v.x;
velocityY = v.y;
velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y;
direction = getDirection(deltaX, deltaY);
session.lastInterval = input;
} else {
// use latest velocity info if it doesn't overtake a minimum period
velocity = last.velocity;
velocityX = last.velocityX;
velocityY = last.velocityY;
direction = last.direction;
}
input.velocity = velocity;
input.velocityX = velocityX;
input.velocityY = velocityY;
input.direction = direction;
}
/**
* create a simple clone from the input used for storage of firstInput and firstMultiple
* @param {Object} input
* @returns {Object} clonedInputData
*/
function simpleCloneInputData(input) {
// make a simple copy of the pointers because we will get a reference if we don't
// we only need clientXY for the calculations
var pointers = [];
var i = 0;
while (i < input.pointers.length) {
pointers[i] = {
clientX: round(input.pointers[i].clientX),
clientY: round(input.pointers[i].clientY)
};
i++;
}
return {
timeStamp: now(),
pointers: pointers,
center: getCenter(pointers),
deltaX: input.deltaX,
deltaY: input.deltaY
};
}
/**
* get the center of all the pointers
* @param {Array} pointers
* @return {Object} center contains `x` and `y` properties
*/
function getCenter(pointers) {
var pointersLength = pointers.length;
// no need to loop when only one touch
if (pointersLength === 1) {
return {
x: round(pointers[0].clientX),
y: round(pointers[0].clientY)
};
}
var x = 0, y = 0, i = 0;
while (i < pointersLength) {
x += pointers[i].clientX;
y += pointers[i].clientY;
i++;
}
return {
x: round(x / pointersLength),
y: round(y / pointersLength)
};
}
/**
* calculate the velocity between two points. unit is in px per ms.
* @param {Number} deltaTime
* @param {Number} x
* @param {Number} y
* @return {Object} velocity `x` and `y`
*/
function getVelocity(deltaTime, x, y) {
return {
x: x / deltaTime || 0,
y: y / deltaTime || 0
};
}
/**
* get the direction between two points
* @param {Number} x
* @param {Number} y
* @return {Number} direction
*/
function getDirection(x, y) {
if (x === y) {
return DIRECTION_NONE;
}
if (abs(x) >= abs(y)) {
return x > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
}
return y > 0 ? DIRECTION_UP : DIRECTION_DOWN;
}
/**
* calculate the absolute distance between two points
* @param {Object} p1 {x, y}
* @param {Object} p2 {x, y}
* @param {Array} [props] containing x and y keys
* @return {Number} distance
*/
function getDistance(p1, p2, props) {
if (!props) {
props = PROPS_XY;
}
var x = p2[props[0]] - p1[props[0]],
y = p2[props[1]] - p1[props[1]];
return Math.sqrt((x * x) + (y * y));
}
/**
* calculate the angle between two coordinates
* @param {Object} p1
* @param {Object} p2
* @param {Array} [props] containing x and y keys
* @return {Number} angle
*/
function getAngle(p1, p2, props) {
if (!props) {
props = PROPS_XY;
}
var x = p2[props[0]] - p1[props[0]],
y = p2[props[1]] - p1[props[1]];
return Math.atan2(y, x) * 180 / Math.PI;
}
/**
* calculate the rotation degrees between two pointersets
* @param {Array} start array of pointers
* @param {Array} end array of pointers
* @return {Number} rotation
*/
function getRotation(start, end) {
return getAngle(end[1], end[0], PROPS_CLIENT_XY) - getAngle(start[1], start[0], PROPS_CLIENT_XY);
}
/**
* calculate the scale factor between two pointersets
* no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
* @param {Array} start array of pointers
* @param {Array} end array of pointers
* @return {Number} scale
*/
function getScale(start, end) {
return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);
}
var MOUSE_INPUT_MAP = {
mousedown: INPUT_START,
mousemove: INPUT_MOVE,
mouseup: INPUT_END
};
var MOUSE_ELEMENT_EVENTS = 'mousedown';
var MOUSE_WINDOW_EVENTS = 'mousemove mouseup';
/**
* Mouse events input
* @constructor
* @extends Input
*/
function MouseInput() {
this.evEl = MOUSE_ELEMENT_EVENTS;
this.evWin = MOUSE_WINDOW_EVENTS;
this.allow = true; // used by Input.TouchMouse to disable mouse events
this.pressed = false; // mousedown state
Input.apply(this, arguments);
}
inherit(MouseInput, Input, {
/**
* handle mouse events
* @param {Object} ev
*/
handler: function MEhandler(ev) {
var eventType = MOUSE_INPUT_MAP[ev.type];
// on start we want to have the left mouse button down
if (eventType & INPUT_START && ev.button === 0) {
this.pressed = true;
}
if (eventType & INPUT_MOVE && ev.which !== 1) {
eventType = INPUT_END;
}
// mouse must be down, and mouse events are allowed (see the TouchMouse input)
if (!this.pressed || !this.allow) {
return;
}
if (eventType & INPUT_END) {
this.pressed = false;
}
this.callback(this.manager, eventType, {
pointers: [ev],
changedPointers: [ev],
pointerType: INPUT_TYPE_MOUSE,
srcEvent: ev
});
}
});
var POINTER_INPUT_MAP = {
pointerdown: INPUT_START,
pointermove: INPUT_MOVE,
pointerup: INPUT_END,
pointercancel: INPUT_CANCEL,
pointerout: INPUT_CANCEL
};
// in IE10 the pointer types is defined as an enum
var IE10_POINTER_TYPE_ENUM = {
2: INPUT_TYPE_TOUCH,
3: INPUT_TYPE_PEN,
4: INPUT_TYPE_MOUSE,
5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816
};
var POINTER_ELEMENT_EVENTS = 'pointerdown';
var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel';
// IE10 has prefixed support, and case-sensitive
if (window.MSPointerEvent) {
POINTER_ELEMENT_EVENTS = 'MSPointerDown';
POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel';
}
/**
* Pointer events input
* @constructor
* @extends Input
*/
function PointerEventInput() {
this.evEl = POINTER_ELEMENT_EVENTS;
this.evWin = POINTER_WINDOW_EVENTS;
Input.apply(this, arguments);
this.store = (this.manager.session.pointerEvents = []);
}
inherit(PointerEventInput, Input, {
/**
* handle mouse events
* @param {Object} ev
*/
handler: function PEhandler(ev) {
var store = this.store;
var removePointer = false;
var eventTypeNormalized = ev.type.toLowerCase().replace('ms', '');
var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;
var isTouch = (pointerType == INPUT_TYPE_TOUCH);
// get index of the event in the store
var storeIndex = inArray(store, ev.pointerId, 'pointerId');
// start and mouse must be down
if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
if (storeIndex < 0) {
store.push(ev);
storeIndex = store.length - 1;
}
} else if (eventType & (INPUT_END | INPUT_CANCEL)) {
removePointer = true;
}
// it not found, so the pointer hasn't been down (so it's probably a hover)
if (storeIndex < 0) {
return;
}
// update the event in the store
store[storeIndex] = ev;
this.callback(this.manager, eventType, {
pointers: store,
changedPointers: [ev],
pointerType: pointerType,
srcEvent: ev
});
if (removePointer) {
// remove from the store
store.splice(storeIndex, 1);
}
}
});
var SINGLE_TOUCH_INPUT_MAP = {
touchstart: INPUT_START,
touchmove: INPUT_MOVE,
touchend: INPUT_END,
touchcancel: INPUT_CANCEL
};
var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart';
var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel';
/**
* Touch events input
* @constructor
* @extends Input
*/
function SingleTouchInput() {
this.evTarget = SINGLE_TOUCH_TARGET_EVENTS;
this.evWin = SINGLE_TOUCH_WINDOW_EVENTS;
this.started = false;
Input.apply(this, arguments);
}
inherit(SingleTouchInput, Input, {
handler: function TEhandler(ev) {
var type = SINGLE_TOUCH_INPUT_MAP[ev.type];
// should we handle the touch events?
if (type === INPUT_START) {
this.started = true;
}
if (!this.started) {
return;
}
var touches = normalizeSingleTouches.call(this, ev, type);
// when done, reset the started state
if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) {
this.started = false;
}
this.callback(this.manager, type, {
pointers: touches[0],
changedPointers: touches[1],
pointerType: INPUT_TYPE_TOUCH,
srcEvent: ev
});
}
});
/**
* @this {TouchInput}
* @param {Object} ev
* @param {Number} type flag
* @returns {undefined|Array} [all, changed]
*/
function normalizeSingleTouches(ev, type) {
var all = toArray(ev.touches);
var changed = toArray(ev.changedTouches);
if (type & (INPUT_END | INPUT_CANCEL)) {
all = uniqueArray(all.concat(changed), 'identifier', true);
}
return [all, changed];
}
var TOUCH_INPUT_MAP = {
touchstart: INPUT_START,
touchmove: INPUT_MOVE,
touchend: INPUT_END,
touchcancel: INPUT_CANCEL
};
var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel';
/**
* Multi-user touch events input
* @constructor
* @extends Input
*/
function TouchInput() {
this.evTarget = TOUCH_TARGET_EVENTS;
this.targetIds = {};
Input.apply(this, arguments);
}
inherit(TouchInput, Input, {
handler: function MTEhandler(ev) {
var type = TOUCH_INPUT_MAP[ev.type];
var touches = getTouches.call(this, ev, type);
if (!touches) {
return;
}
this.callback(this.manager, type, {
pointers: touches[0],
changedPointers: touches[1],
pointerType: INPUT_TYPE_TOUCH,
srcEvent: ev
});
}
});
/**
* @this {TouchInput}
* @param {Object} ev
* @param {Number} type flag
* @returns {undefined|Array} [all, changed]
*/
function getTouches(ev, type) {
var allTouches = toArray(ev.touches);
var targetIds = this.targetIds;
// when there is only one touch, the process can be simplified
if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) {
targetIds[allTouches[0].identifier] = true;
return [allTouches, allTouches];
}
var i,
targetTouches,
changedTouches = toArray(ev.changedTouches),
changedTargetTouches = [],
target = this.target;
// get target touches from touches
targetTouches = allTouches.filter(function(touch) {
return hasParent(touch.target, target);
});
// collect touches
if (type === INPUT_START) {
i = 0;
while (i < targetTouches.length) {
targetIds[targetTouches[i].identifier] = true;
i++;
}
}
// filter changed touches to only contain touches that exist in the collected target ids
i = 0;
while (i < changedTouches.length) {
if (targetIds[changedTouches[i].identifier]) {
changedTargetTouches.push(changedTouches[i]);
}
// cleanup removed touches
if (type & (INPUT_END | INPUT_CANCEL)) {
delete targetIds[changedTouches[i].identifier];
}
i++;
}
if (!changedTargetTouches.length) {
return;
}
return [
// merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'
uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true),
changedTargetTouches
];
}
/**
* Combined touch and mouse input
*
* Touch has a higher priority then mouse, and while touching no mouse events are allowed.
* This because touch devices also emit mouse events while doing a touch.
*
* @constructor
* @extends Input
*/
function TouchMouseInput() {
Input.apply(this, arguments);
var handler = bindFn(this.handler, this);
this.touch = new TouchInput(this.manager, handler);
this.mouse = new MouseInput(this.manager, handler);
}
inherit(TouchMouseInput, Input, {
/**
* handle mouse and touch events
* @param {Hammer} manager
* @param {String} inputEvent
* @param {Object} inputData
*/
handler: function TMEhandler(manager, inputEvent, inputData) {
var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH),
isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE);
// when we're in a touch event, so block all upcoming mouse events
// most mobile browser also emit mouseevents, right after touchstart
if (isTouch) {
this.mouse.allow = false;
} else if (isMouse && !this.mouse.allow) {
return;
}
// reset the allowMouse when we're done
if (inputEvent & (INPUT_END | INPUT_CANCEL)) {
this.mouse.allow = true;
}
this.callback(manager, inputEvent, inputData);
},
/**
* remove the event listeners
*/
destroy: function destroy() {
this.touch.destroy();
this.mouse.destroy();
}
});
var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction');
var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined;
// magical touchAction value
var TOUCH_ACTION_COMPUTE = 'compute';
var TOUCH_ACTION_AUTO = 'auto';
var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented
var TOUCH_ACTION_NONE = 'none';
var TOUCH_ACTION_PAN_X = 'pan-x';
var TOUCH_ACTION_PAN_Y = 'pan-y';
/**
* Touch Action
* sets the touchAction property or uses the js alternative
* @param {Manager} manager
* @param {String} value
* @constructor
*/
function TouchAction(manager, value) {
this.manager = manager;
this.set(value);
}
TouchAction.prototype = {
/**
* set the touchAction value on the element or enable the polyfill
* @param {String} value
*/
set: function(value) {
// find out the touch-action by the event handlers
if (value == TOUCH_ACTION_COMPUTE) {
value = this.compute();
}
if (NATIVE_TOUCH_ACTION) {
this.manager.element.style[PREFIXED_TOUCH_ACTION] = value;
}
this.actions = value.toLowerCase().trim();
},
/**
* just re-set the touchAction value
*/
update: function() {
this.set(this.manager.options.touchAction);
},
/**
* compute the value for the touchAction property based on the recognizer's settings
* @returns {String} value
*/
compute: function() {
var actions = [];
each(this.manager.recognizers, function(recognizer) {
if (boolOrFn(recognizer.options.enable, [recognizer])) {
actions = actions.concat(recognizer.getTouchAction());
}
});
return cleanTouchActions(actions.join(' '));
},
/**
* this method is called on each input cycle and provides the preventing of the browser behavior
* @param {Object} input
*/
preventDefaults: function(input) {
// not needed with native support for the touchAction property
if (NATIVE_TOUCH_ACTION) {
return;
}
var srcEvent = input.srcEvent;
var direction = input.offsetDirection;
// if the touch action did prevented once this session
if (this.manager.session.prevented) {
srcEvent.preventDefault();
return;
}
var actions = this.actions;
var hasNone = inStr(actions, TOUCH_ACTION_NONE);
var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);
var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
if (hasNone ||
(hasPanY && direction & DIRECTION_HORIZONTAL) ||
(hasPanX && direction & DIRECTION_VERTICAL)) {
return this.preventSrc(srcEvent);
}
},
/**
* call preventDefault to prevent the browser's default behavior (scrolling in most cases)
* @param {Object} srcEvent
*/
preventSrc: function(srcEvent) {
this.manager.session.prevented = true;
srcEvent.preventDefault();
}
};
/**
* when the touchActions are collected they are not a valid value, so we need to clean things up. *
* @param {String} actions
* @returns {*}
*/
function cleanTouchActions(actions) {
// none
if (inStr(actions, TOUCH_ACTION_NONE)) {
return TOUCH_ACTION_NONE;
}
var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);
// pan-x and pan-y can be combined
if (hasPanX && hasPanY) {
return TOUCH_ACTION_PAN_X + ' ' + TOUCH_ACTION_PAN_Y;
}
// pan-x OR pan-y
if (hasPanX || hasPanY) {
return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;
}
// manipulation
if (inStr(actions, TOUCH_ACTION_MANIPULATION)) {
return TOUCH_ACTION_MANIPULATION;
}
return TOUCH_ACTION_AUTO;
}
/**
* Recognizer flow explained; *
* All recognizers have the initial state of POSSIBLE when a input session starts.
* The definition of a input session is from the first input until the last input, with all it's movement in it. *
* Example session for mouse-input: mousedown -> mousemove -> mouseup
*
* On each recognizing cycle (see Manager.recognize) the .recognize() method is executed
* which determines with state it should be.
*
* If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to
* POSSIBLE to give it another change on the next cycle.
*
* Possible
* |
* +-----+---------------+
* | |
* +-----+-----+ |
* | | |
* Failed Cancelled |
* +-------+------+
* | |
* Recognized Began
* |
* Changed
* |
* Ended/Recognized
*/
var STATE_POSSIBLE = 1;
var STATE_BEGAN = 2;
var STATE_CHANGED = 4;
var STATE_ENDED = 8;
var STATE_RECOGNIZED = STATE_ENDED;
var STATE_CANCELLED = 16;
var STATE_FAILED = 32;
/**
* Recognizer
* Every recognizer needs to extend from this class.
* @constructor
* @param {Object} options
*/
function Recognizer(options) {
this.id = uniqueId();
this.manager = null;
this.options = merge(options || {}, this.defaults);
// default is enable true
this.options.enable = ifUndefined(this.options.enable, true);
this.state = STATE_POSSIBLE;
this.simultaneous = {};
this.requireFail = [];
}
Recognizer.prototype = {
/**
* @virtual
* @type {Object}
*/
defaults: {},
/**
* set options
* @param {Object} options
* @return {Recognizer}
*/
set: function(options) {
extend(this.options, options);
// also update the touchAction, in case something changed about the directions/enabled state
this.manager && this.manager.touchAction.update();
return this;
},
/**
* recognize simultaneous with an other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
recognizeWith: function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {
return this;
}
var simultaneous = this.simultaneous;
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
if (!simultaneous[otherRecognizer.id]) {
simultaneous[otherRecognizer.id] = otherRecognizer;
otherRecognizer.recognizeWith(this);
}
return this;
},
/**
* drop the simultaneous link. it doesnt remove the link on the other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
dropRecognizeWith: function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) {
return this;
}
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
delete this.simultaneous[otherRecognizer.id];
return this;
},
/**
* recognizer can only run when an other is failing
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
requireFailure: function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) {
return this;
}
var requireFail = this.requireFail;
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
if (inArray(requireFail, otherRecognizer) === -1) {
requireFail.push(otherRecognizer);
otherRecognizer.requireFailure(this);
}
return this;
},
/**
* drop the requireFailure link. it does not remove the link on the other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
dropRequireFailure: function(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) {
return this;
}
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
var index = inArray(this.requireFail, otherRecognizer);
if (index > -1) {
this.requireFail.splice(index, 1);
}
return this;
},
/**
* has require failures boolean
* @returns {boolean}
*/
hasRequireFailures: function() {
return this.requireFail.length > 0;
},
/**
* if the recognizer can recognize simultaneous with an other recognizer
* @param {Recognizer} otherRecognizer
* @returns {Boolean}
*/
canRecognizeWith: function(otherRecognizer) {
return !!this.simultaneous[otherRecognizer.id];
},
/**
* You should use `tryEmit` instead of `emit` directly to check
* that all the needed recognizers has failed before emitting.
* @param {Object} input
*/
emit: function(input) {
var self = this;
var state = this.state;
function emit(withState) {
self.manager.emit(self.options.event + (withState ? stateStr(state) : ''), input);
}
// 'panstart' and 'panmove'
if (state < STATE_ENDED) {
emit(true);
}
emit(); // simple 'eventName' events
// panend and pancancel
if (state >= STATE_ENDED) {
emit(true);
}
},
/**
* Check that all the require failure recognizers has failed,
* if true, it emits a gesture event,
* otherwise, setup the state to FAILED.
* @param {Object} input
*/
tryEmit: function(input) {
if (this.canEmit()) {
return this.emit(input);
}
// it's failing anyway
this.state = STATE_FAILED;
},
/**
* can we emit?
* @returns {boolean}
*/
canEmit: function() {
var i = 0;
while (i < this.requireFail.length) {
if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {
return false;
}
i++;
}
return true;
},
/**
* update the recognizer
* @param {Object} inputData
*/
recognize: function(inputData) {
// make a new copy of the inputData
// so we can change the inputData without messing up the other recognizers
var inputDataClone = extend({}, inputData);
// is is enabled and allow recognizing?
if (!boolOrFn(this.options.enable, [this, inputDataClone])) {
this.reset();
this.state = STATE_FAILED;
return;
}
// reset when we've reached the end
if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {
this.state = STATE_POSSIBLE;
}
this.state = this.process(inputDataClone);
// the recognizer has recognized a gesture
// so trigger an event
if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {
this.tryEmit(inputDataClone);
}
},
/**
* return the state of the recognizer
* the actual recognizing happens in this method
* @virtual
* @param {Object} inputData
* @returns {Const} STATE
*/
process: function(inputData) { }, // jshint ignore:line
/**
* return the preferred touch-action
* @virtual
* @returns {Array}
*/
getTouchAction: function() { },
/**
* called when the gesture isn't allowed to recognize
* like when another is being recognized or it is disabled
* @virtual
*/
reset: function() { }
};
/**
* get a usable string, used as event postfix
* @param {Const} state
* @returns {String} state
*/
function stateStr(state) {
if (state & STATE_CANCELLED) {
return 'cancel';
} else if (state & STATE_ENDED) {
return 'end';
} else if (state & STATE_CHANGED) {
return 'move';
} else if (state & STATE_BEGAN) {
return 'start';
}
return '';
}
/**
* direction cons to string
* @param {Const} direction
* @returns {String}
*/
function directionStr(direction) {
if (direction == DIRECTION_DOWN) {
return 'down';
} else if (direction == DIRECTION_UP) {
return 'up';
} else if (direction == DIRECTION_LEFT) {
return 'left';
} else if (direction == DIRECTION_RIGHT) {
return 'right';
}
return '';
}
/**
* get a recognizer by name if it is bound to a manager
* @param {Recognizer|String} otherRecognizer
* @param {Recognizer} recognizer
* @returns {Recognizer}
*/
function getRecognizerByNameIfManager(otherRecognizer, recognizer) {
var manager = recognizer.manager;
if (manager) {
return manager.get(otherRecognizer);
}
return otherRecognizer;
}
/**
* This recognizer is just used as a base for the simple attribute recognizers.
* @constructor
* @extends Recognizer
*/
function AttrRecognizer() {
Recognizer.apply(this, arguments);
}
inherit(AttrRecognizer, Recognizer, {
/**
* @namespace
* @memberof AttrRecognizer
*/
defaults: {
/**
* @type {Number}
* @default 1
*/
pointers: 1
},
/**
* Used to check if it the recognizer receives valid input, like input.distance > 10.
* @memberof AttrRecognizer
* @param {Object} input
* @returns {Boolean} recognized
*/
attrTest: function(input) {
var optionPointers = this.options.pointers;
return optionPointers === 0 || input.pointers.length === optionPointers;
},
/**
* Process the input and return the state for the recognizer
* @memberof AttrRecognizer
* @param {Object} input
* @returns {*} State
*/
process: function(input) {
var state = this.state;
var eventType = input.eventType;
var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);
var isValid = this.attrTest(input);
// on cancel input and we've recognized before, return STATE_CANCELLED
if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) {
return state | STATE_CANCELLED;
} else if (isRecognized || isValid) {
if (eventType & INPUT_END) {
return state | STATE_ENDED;
} else if (!(state & STATE_BEGAN)) {
return STATE_BEGAN;
}
return state | STATE_CHANGED;
}
return STATE_FAILED;
}
});
/**
* Pan
* Recognized when the pointer is down and moved in the allowed direction.
* @constructor
* @extends AttrRecognizer
*/
function PanRecognizer() {
AttrRecognizer.apply(this, arguments);
this.pX = null;
this.pY = null;
}
inherit(PanRecognizer, AttrRecognizer, {
/**
* @namespace
* @memberof PanRecognizer
*/
defaults: {
event: 'pan',
threshold: 10,
pointers: 1,
direction: DIRECTION_ALL
},
getTouchAction: function() {
var direction = this.options.direction;
var actions = [];
if (direction & DIRECTION_HORIZONTAL) {
actions.push(TOUCH_ACTION_PAN_Y);
}
if (direction & DIRECTION_VERTICAL) {
actions.push(TOUCH_ACTION_PAN_X);
}
return actions;
},
directionTest: function(input) {
var options = this.options;
var hasMoved = true;
var distance = input.distance;
var direction = input.direction;
var x = input.deltaX;
var y = input.deltaY;
// lock to axis?
if (!(direction & options.direction)) {
if (options.direction & DIRECTION_HORIZONTAL) {
direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT;
hasMoved = x != this.pX;
distance = Math.abs(input.deltaX);
} else {
direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN;
hasMoved = y != this.pY;
distance = Math.abs(input.deltaY);
}
}
input.direction = direction;
return hasMoved && distance > options.threshold && direction & options.direction;
},
attrTest: function(input) {
return AttrRecognizer.prototype.attrTest.call(this, input) &&
(this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input)));
},
emit: function(input) {
this.pX = input.deltaX;
this.pY = input.deltaY;
var direction = directionStr(input.direction);
if (direction) {
this.manager.emit(this.options.event + direction, input);
}
this._super.emit.call(this, input);
}
});
/**
* Pinch
* Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).
* @constructor
* @extends AttrRecognizer
*/
function PinchRecognizer() {
AttrRecognizer.apply(this, arguments);
}
inherit(PinchRecognizer, AttrRecognizer, {
/**
* @namespace
* @memberof PinchRecognizer
*/
defaults: {
event: 'pinch',
threshold: 0,
pointers: 2
},
getTouchAction: function() {
return [TOUCH_ACTION_NONE];
},
attrTest: function(input) {
return this._super.attrTest.call(this, input) &&
(Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN);
},
emit: function(input) {
this._super.emit.call(this, input);
if (input.scale !== 1) {
var inOut = input.scale < 1 ? 'in' : 'out';
this.manager.emit(this.options.event + inOut, input);
}
}
});
/**
* Press
* Recognized when the pointer is down for x ms without any movement.
* @constructor
* @extends Recognizer
*/
function PressRecognizer() {
Recognizer.apply(this, arguments);
this._timer = null;
this._input = null;
}
inherit(PressRecognizer, Recognizer, {
/**
* @namespace
* @memberof PressRecognizer
*/
defaults: {
event: 'press',
pointers: 1,
time: 500, // minimal time of the pointer to be pressed
threshold: 5 // a minimal movement is ok, but keep it low
},
getTouchAction: function() {
return [TOUCH_ACTION_AUTO];
},
process: function(input) {
var options = this.options;
var validPointers = input.pointers.length === options.pointers;
var validMovement = input.distance < options.threshold;
var validTime = input.deltaTime > options.time;
this._input = input;
// we only allow little movement
// and we've reached an end event, so a tap is possible
if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) {
this.reset();
} else if (input.eventType & INPUT_START) {
this.reset();
this._timer = setTimeoutContext(function() {
this.state = STATE_RECOGNIZED;
this.tryEmit();
}, options.time, this);
} else if (input.eventType & INPUT_END) {
return STATE_RECOGNIZED;
}
return STATE_FAILED;
},
reset: function() {
clearTimeout(this._timer);
},
emit: function(input) {
if (this.state !== STATE_RECOGNIZED) {
return;
}
if (input && (input.eventType & INPUT_END)) {
this.manager.emit(this.options.event + 'up', input);
} else {
this._input.timeStamp = now();
this.manager.emit(this.options.event, this._input);
}
}
});
/**
* Rotate
* Recognized when two or more pointer are moving in a circular motion.
* @constructor
* @extends AttrRecognizer
*/
function RotateRecognizer() {
AttrRecognizer.apply(this, arguments);
}
inherit(RotateRecognizer, AttrRecognizer, {
/**
* @namespace
* @memberof RotateRecognizer
*/
defaults: {
event: 'rotate',
threshold: 0,
pointers: 2
},
getTouchAction: function() {
return [TOUCH_ACTION_NONE];
},
attrTest: function(input) {
return this._super.attrTest.call(this, input) &&
(Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN);
}
});
/**
* Swipe
* Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.
* @constructor
* @extends AttrRecognizer
*/
function SwipeRecognizer() {
AttrRecognizer.apply(this, arguments);
}
inherit(SwipeRecognizer, AttrRecognizer, {
/**
* @namespace
* @memberof SwipeRecognizer
*/
defaults: {
event: 'swipe',
threshold: 10,
velocity: 0.65,
direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL,
pointers: 1
},
getTouchAction: function() {
return PanRecognizer.prototype.getTouchAction.call(this);
},
attrTest: function(input) {
var direction = this.options.direction;
var velocity;
if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) {
velocity = input.velocity;
} else if (direction & DIRECTION_HORIZONTAL) {
velocity = input.velocityX;
} else if (direction & DIRECTION_VERTICAL) {
velocity = input.velocityY;
}
return this._super.attrTest.call(this, input) &&
direction & input.direction &&
input.distance > this.options.threshold &&
abs(velocity) > this.options.velocity && input.eventType & INPUT_END;
},
emit: function(input) {
var direction = directionStr(input.direction);
if (direction) {
this.manager.emit(this.options.event + direction, input);
}
this.manager.emit(this.options.event, input);
}
});
/**
* A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur
* between the given interval and position. The delay option can be used to recognize multi-taps without firing
* a single tap.
*
* The eventData from the emitted event contains the property `tapCount`, which contains the amount of
* multi-taps being recognized.
* @constructor
* @extends Recognizer
*/
function TapRecognizer() {
Recognizer.apply(this, arguments);
// previous time and center,
// used for tap counting
this.pTime = false;
this.pCenter = false;
this._timer = null;
this._input = null;
this.count = 0;
}
inherit(TapRecognizer, Recognizer, {
/**
* @namespace
* @memberof PinchRecognizer
*/
defaults: {
event: 'tap',
pointers: 1,
taps: 1,
interval: 300, // max time between the multi-tap taps
time: 250, // max time of the pointer to be down (like finger on the screen)
threshold: 2, // a minimal movement is ok, but keep it low
posThreshold: 10 // a multi-tap can be a bit off the initial position
},
getTouchAction: function() {
return [TOUCH_ACTION_MANIPULATION];
},
process: function(input) {
var options = this.options;
var validPointers = input.pointers.length === options.pointers;
var validMovement = input.distance < options.threshold;
var validTouchTime = input.deltaTime < options.time;
this.reset();
if ((input.eventType & INPUT_START) && (this.count === 0)) {
return this.failTimeout();
}
// we only allow little movement
// and we've reached an end event, so a tap is possible
if (validMovement && validTouchTime && validPointers) {
if (input.eventType != INPUT_END) {
return this.failTimeout();
}
var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true;
var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold;
this.pTime = input.timeStamp;
this.pCenter = input.center;
if (!validMultiTap || !validInterval) {
this.count = 1;
} else {
this.count += 1;
}
this._input = input;
// if tap count matches we have recognized it,
// else it has began recognizing...
var tapCount = this.count % options.taps;
if (tapCount === 0) {
// no failing requirements, immediately trigger the tap event
// or wait as long as the multitap interval to trigger
if (!this.hasRequireFailures()) {
return STATE_RECOGNIZED;
} else {
this._timer = setTimeoutContext(function() {
this.state = STATE_RECOGNIZED;
this.tryEmit();
}, options.interval, this);
return STATE_BEGAN;
}
}
}
return STATE_FAILED;
},
failTimeout: function() {
this._timer = setTimeoutContext(function() {
this.state = STATE_FAILED;
}, this.options.interval, this);
return STATE_FAILED;
},
reset: function() {
clearTimeout(this._timer);
},
emit: function() {
if (this.state == STATE_RECOGNIZED ) {
this._input.tapCount = this.count;
this.manager.emit(this.options.event, this._input);
}
}
});
/**
* Simple way to create an manager with a default set of recognizers.
* @param {HTMLElement} element
* @param {Object} [options]
* @constructor
*/
function Hammer(element, options) {
options = options || {};
options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset);
return new Manager(element, options);
}
/**
* @const {string}
*/
Hammer.VERSION = '2.0.4';
/**
* default settings
* @namespace
*/
Hammer.defaults = {
/**
* set if DOM events are being triggered.
* But this is slower and unused by simple implementations, so disabled by default.
* @type {Boolean}
* @default false
*/
domEvents: false,
/**
* The value for the touchAction property/fallback.
* When set to `compute` it will magically set the correct value based on the added recognizers.
* @type {String}
* @default compute
*/
touchAction: TOUCH_ACTION_COMPUTE,
/**
* @type {Boolean}
* @default true
*/
enable: true,
/**
* EXPERIMENTAL FEATURE -- can be removed/changed
* Change the parent input target element.
* If Null, then it is being set the to main element.
* @type {Null|EventTarget}
* @default null
*/
inputTarget: null,
/**
* force an input class
* @type {Null|Function}
* @default null
*/
inputClass: null,
/**
* Default recognizer setup when calling `Hammer()`
* When creating a new Manager these will be skipped.
* @type {Array}
*/
preset: [
// RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...]
[RotateRecognizer, { enable: false }],
[PinchRecognizer, { enable: false }, ['rotate']],
[SwipeRecognizer,{ direction: DIRECTION_HORIZONTAL }],
[PanRecognizer, { direction: DIRECTION_HORIZONTAL }, ['swipe']],
[TapRecognizer],
[TapRecognizer, { event: 'doubletap', taps: 2 }, ['tap']],
[PressRecognizer]
],
/**
* Some CSS properties can be used to improve the working of Hammer.
* Add them to this method and they will be set when creating a new Manager.
* @namespace
*/
cssProps: {
/**
* Disables text selection to improve the dragging gesture. Mainly for desktop browsers.
* @type {String}
* @default 'none'
*/
userSelect: 'none',
/**
* Disable the Windows Phone grippers when pressing an element.
* @type {String}
* @default 'none'
*/
touchSelect: 'none',
/**
* Disables the default callout shown when you touch and hold a touch target.
* On iOS, when you touch and hold a touch target such as a link, Safari displays
* a callout containing information about the link. This property allows you to disable that callout.
* @type {String}
* @default 'none'
*/
touchCallout: 'none',
/**
* Specifies whether zooming is enabled. Used by IE10>
* @type {String}
* @default 'none'
*/
contentZooming: 'none',
/**
* Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.
* @type {String}
* @default 'none'
*/
userDrag: 'none',
/**
* Overrides the highlight color shown when the user taps a link or a JavaScript
* clickable element in iOS. This property obeys the alpha value, if specified.
* @type {String}
* @default 'rgba(0,0,0,0)'
*/
tapHighlightColor: 'rgba(0,0,0,0)'
}
};
var STOP = 1;
var FORCED_STOP = 2;
/**
* Manager
* @param {HTMLElement} element
* @param {Object} [options]
* @constructor
*/
function Manager(element, options) {
options = options || {};
this.options = merge(options, Hammer.defaults);
this.options.inputTarget = this.options.inputTarget || element;
this.handlers = {};
this.session = {};
this.recognizers = [];
this.element = element;
this.input = createInputInstance(this);
this.touchAction = new TouchAction(this, this.options.touchAction);
toggleCssProps(this, true);
each(options.recognizers, function(item) {
var recognizer = this.add(new (item[0])(item[1]));
item[2] && recognizer.recognizeWith(item[2]);
item[3] && recognizer.requireFailure(item[3]);
}, this);
}
Manager.prototype = {
/**
* set options
* @param {Object} options
* @returns {Manager}
*/
set: function(options) {
extend(this.options, options);
// Options that need a little more setup
if (options.touchAction) {
this.touchAction.update();
}
if (options.inputTarget) {
// Clean up existing event listeners and reinitialize
this.input.destroy();
this.input.target = options.inputTarget;
this.input.init();
}
return this;
},
/**
* stop recognizing for this session.
* This session will be discarded, when a new [input]start event is fired.
* When forced, the recognizer cycle is stopped immediately.
* @param {Boolean} [force]
*/
stop: function(force) {
this.session.stopped = force ? FORCED_STOP : STOP;
},
/**
* run the recognizers!
* called by the inputHandler function on every movement of the pointers (touches)
* it walks through all the recognizers and tries to detect the gesture that is being made
* @param {Object} inputData
*/
recognize: function(inputData) {
var session = this.session;
if (session.stopped) {
return;
}
// run the touch-action polyfill
this.touchAction.preventDefaults(inputData);
var recognizer;
var recognizers = this.recognizers;
// this holds the recognizer that is being recognized.
// so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED
// if no recognizer is detecting a thing, it is set to `null`
var curRecognizer = session.curRecognizer;
// reset when the last recognizer is recognized
// or when we're in a new session
if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) {
curRecognizer = session.curRecognizer = null;
}
var i = 0;
while (i < recognizers.length) {
recognizer = recognizers[i];
// find out if we are allowed try to recognize the input for this one.
// 1. allow if the session is NOT forced stopped (see the .stop() method)
// 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one
// that is being recognized.
// 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.
// this can be setup with the `recognizeWith()` method on the recognizer.
if (session.stopped !== FORCED_STOP && ( // 1
!curRecognizer || recognizer == curRecognizer || // 2
recognizer.canRecognizeWith(curRecognizer))) { // 3
recognizer.recognize(inputData);
} else {
recognizer.reset();
}
// if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the
// current active recognizer. but only if we don't already have an active recognizer
if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) {
curRecognizer = session.curRecognizer = recognizer;
}
i++;
}
},
/**
* get a recognizer by its event name.
* @param {Recognizer|String} recognizer
* @returns {Recognizer|Null}
*/
get: function(recognizer) {
if (recognizer instanceof Recognizer) {
return recognizer;
}
var recognizers = this.recognizers;
for (var i = 0; i < recognizers.length; i++) {
if (recognizers[i].options.event == recognizer) {
return recognizers[i];
}
}
return null;
},
/**
* add a recognizer to the manager
* existing recognizers with the same event name will be removed
* @param {Recognizer} recognizer
* @returns {Recognizer|Manager}
*/
add: function(recognizer) {
if (invokeArrayArg(recognizer, 'add', this)) {
return this;
}
// remove existing
var existing = this.get(recognizer.options.event);
if (existing) {
this.remove(existing);
}
this.recognizers.push(recognizer);
recognizer.manager = this;
this.touchAction.update();
return recognizer;
},
/**
* remove a recognizer by name or instance
* @param {Recognizer|String} recognizer
* @returns {Manager}
*/
remove: function(recognizer) {
if (invokeArrayArg(recognizer, 'remove', this)) {
return this;
}
var recognizers = this.recognizers;
recognizer = this.get(recognizer);
recognizers.splice(inArray(recognizers, recognizer), 1);
this.touchAction.update();
return this;
},
/**
* bind event
* @param {String} events
* @param {Function} handler
* @returns {EventEmitter} this
*/
on: function(events, handler) {
var handlers = this.handlers;
each(splitStr(events), function(event) {
handlers[event] = handlers[event] || [];
handlers[event].push(handler);
});
return this;
},
/**
* unbind event, leave emit blank to remove all handlers
* @param {String} events
* @param {Function} [handler]
* @returns {EventEmitter} this
*/
off: function(events, handler) {
var handlers = this.handlers;
each(splitStr(events), function(event) {
if (!handler) {
delete handlers[event];
} else {
handlers[event].splice(inArray(handlers[event], handler), 1);
}
});
return this;
},
/**
* emit event to the listeners
* @param {String} event
* @param {Object} data
*/
emit: function(event, data) {
// we also want to trigger dom events
if (this.options.domEvents) {
triggerDomEvent(event, data);
}
// no handlers, so skip it all
var handlers = this.handlers[event] && this.handlers[event].slice();
if (!handlers || !handlers.length) {
return;
}
data.type = event;
data.preventDefault = function() {
data.srcEvent.preventDefault();
};
data.stopPropagation = function() {
data.srcEvent.stopPropagation();
};
var i = 0;
while (i < handlers.length) {
handlers[i](data);
i++;
}
},
/**
* destroy the manager and unbinds all events
* it doesn't unbind dom events, that is the user own responsibility
*/
destroy: function() {
this.element && toggleCssProps(this, false);
this.handlers = {};
this.session = {};
this.input.destroy();
this.element = null;
}
};
/**
* add/remove the css properties as defined in manager.options.cssProps
* @param {Manager} manager
* @param {Boolean} add
*/
function toggleCssProps(manager, add) {
var element = manager.element;
each(manager.options.cssProps, function(value, name) {
element.style[prefixed(element.style, name)] = add ? value : '';
});
}
/**
* trigger dom event
* @param {String} event
* @param {Object} data
*/
function triggerDomEvent(event, data) {
var gestureEvent = document.createEvent('Event');
gestureEvent.initEvent(event, true, true);
gestureEvent.gesture = data;
data.target.dispatchEvent(gestureEvent);
}
extend(Hammer, {
INPUT_START: INPUT_START,
INPUT_MOVE: INPUT_MOVE,
INPUT_END: INPUT_END,
INPUT_CANCEL: INPUT_CANCEL,
STATE_POSSIBLE: STATE_POSSIBLE,
STATE_BEGAN: STATE_BEGAN,
STATE_CHANGED: STATE_CHANGED,
STATE_ENDED: STATE_ENDED,
STATE_RECOGNIZED: STATE_RECOGNIZED,
STATE_CANCELLED: STATE_CANCELLED,
STATE_FAILED: STATE_FAILED,
DIRECTION_NONE: DIRECTION_NONE,
DIRECTION_LEFT: DIRECTION_LEFT,
DIRECTION_RIGHT: DIRECTION_RIGHT,
DIRECTION_UP: DIRECTION_UP,
DIRECTION_DOWN: DIRECTION_DOWN,
DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL,
DIRECTION_VERTICAL: DIRECTION_VERTICAL,
DIRECTION_ALL: DIRECTION_ALL,
Manager: Manager,
Input: Input,
TouchAction: TouchAction,
TouchInput: TouchInput,
MouseInput: MouseInput,
PointerEventInput: PointerEventInput,
TouchMouseInput: TouchMouseInput,
SingleTouchInput: SingleTouchInput,
Recognizer: Recognizer,
AttrRecognizer: AttrRecognizer,
Tap: TapRecognizer,
Pan: PanRecognizer,
Swipe: SwipeRecognizer,
Pinch: PinchRecognizer,
Rotate: RotateRecognizer,
Press: PressRecognizer,
on: addEventListeners,
off: removeEventListeners,
each: each,
merge: merge,
extend: extend,
inherit: inherit,
bindFn: bindFn,
prefixed: prefixed
});
if (typeof define == TYPE_FUNCTION && define.amd) {
define(function() {
return Hammer;
});
} else if (typeof module != 'undefined' && module.exports) {
module.exports = Hammer;
} else {
window[exportName] = Hammer;
}
})(window, document, 'Hammer');
|
/*!
* Bootstrap v3.2.0 (http://getbootstrap.com)
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
if (typeof jQuery === 'undefined') { throw new Error('Bootstrap\'s JavaScript requires jQuery') }
/* ========================================================================
* Bootstrap: transition.js v3.2.0
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition : 'webkitTransitionEnd',
MozTransition : 'transitionend',
OTransition : 'oTransitionEnd otransitionend',
transition : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function (e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
/* ========================================================================
* Bootstrap: modal.js v3.2.0
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function (element, options) {
this.options = options
this.$body = $(document.body)
this.$element = $(element)
this.$backdrop =
this.isShown = null
this.scrollbarWidth = 0
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.VERSION = '3.2.0'
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function (_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.checkScrollbar()
this.$body.addClass('modal-open')
this.setScrollbar()
this.escape()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(that.$body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element
.addClass('in')
.attr('aria-hidden', false)
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$element.find('.modal-dialog') // wait for modal to slide in
.one('bsTransitionEnd', function () {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(300) :
that.$element.trigger('focus').trigger(e)
})
}
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.$body.removeClass('modal-open')
this.resetScrollbar()
this.escape()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.attr('aria-hidden', true)
.off('click.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one('bsTransitionEnd', $.proxy(this.hideModal, this))
.emulateTransitionEnd(300) :
this.hideModal()
}
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) {
this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keyup.dismiss.bs.modal')
}
}
Modal.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function (callback) {
var that = this
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
.appendTo(this.$body)
this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus.call(this.$element[0])
: this.hide.call(this)
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one('bsTransitionEnd', callback)
.emulateTransitionEnd(150) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
var callbackRemove = function () {
that.removeBackdrop()
callback && callback()
}
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one('bsTransitionEnd', callbackRemove)
.emulateTransitionEnd(150) :
callbackRemove()
} else if (callback) {
callback()
}
}
Modal.prototype.checkScrollbar = function () {
if (document.body.clientWidth >= window.innerWidth) return
this.scrollbarWidth = this.scrollbarWidth || this.measureScrollbar()
}
Modal.prototype.setScrollbar = function () {
var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
if (this.scrollbarWidth) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
}
Modal.prototype.resetScrollbar = function () {
this.$body.css('padding-right', '')
}
Modal.prototype.measureScrollbar = function () { // thx walsh
var scrollDiv = document.createElement('div')
scrollDiv.className = 'modal-scrollbar-measure'
this.$body.append(scrollDiv)
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
this.$body[0].removeChild(scrollDiv)
return scrollbarWidth
}
// MODAL PLUGIN DEFINITION
// =======================
function Plugin(option, _relatedTarget) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
var old = $.fn.modal
$.fn.modal = Plugin
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target.one('show.bs.modal', function (showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
})
})
Plugin.call($target, option, this)
})
}(jQuery);
|
/**
* Created by grest on 9/10/14.
*/
angular.module('ruchJow.user.removeAccountHandler', ['ruchJow.homepageActions', 'ipCookie', 'ruchJow.user.translations'])
.factory('ruchJowRemoveAccountHandler', ['$modal', '$http', 'ruchJowSecurity', function ($modal, $http, ruchJowSecurity) {
return {
handleRemoveAccountToken: function (token) {
var modalInstance = $modal.open({
templateUrl: 'removeAccountConfirmationModal.html',
controller: ['$scope', '$modalInstance', 'ruchJowSecurity', 'token', function ($scope, $modalInstance, ruchJowSecurity, token) {
$scope.status = 'pending';
$scope.message = 'user.remove_account.msg.pending';
ruchJowSecurity.confirmRemoveAccount(token)
.then(function () {
$scope.status = 'confirmed';
$scope.message = 'user.remove_account.msg.confirmed';
}, function (status) {
switch (status) {
case 'token_not_exists':
$scope.status = status;
$scope.message = 'user.remove_account.msg.token_not_exists';
break;
default:
$scope.status = 'internal_error';
$scope.message = 'user.remove_account.msg.internal_error';
}
});
$scope.ok = function () {
$modalInstance.close();
};
}],
resolve: {
token: function () {
return token;
}
}
});
return modalInstance.result;
}
};
}])
.config(['ruchJowHomepageActionsProvider', function (homepageActionsProvider) {
homepageActionsProvider.register('remove_account', 'ruchJowRemoveAccountHandler.handleRemoveAccountToken');
}]); |
#!/usr/bin/env node
var argv = require('minimist')(process.argv.slice(2));
if(argv.h || argv.help){
console.log("USE: ");
console.log(" -n number of messages to send. (optional) default 1000");
console.log(" -c number of concurrent messages to send. (optional) default 1");
process.exit();
}
var cp = require('child_process');
var client = cp.spawn(__dirname+"/perfclient.js",argv)
client.stdout.pipe(process.stdout);
client.stderr.pipe(process.stderr);
var exit;
var killed = false;
client.on('exit',function(code){
if(killed) return;
if(code) {
process.stderr.write("client exited with code ",code);
exit = code;
}
killed = true;
server.kill();
})
// todo. more than one server.
var server = cp.spawn("node",[__dirname+"/server.js"]);
server.on('exit',function(code){
if(killed) return;
if(code){
process.stderr.write("client exited with code ",code);
exit = code;
}
client.kill();
})
|
/*jshint maxlen: 1000*/
/*global FileReader*/
(function (window) {
var EventEmitter = require('events').EventEmitter;
var PeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var SessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription || window.webkitRTCSessionDescription;
var RTCIceCandidate = window.RTCIceCandidate || window.mozRTCIceCandidate || window.webkitRTCIceCandidate;
var requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem || window.mozRequestFileSystem;
var MAX_CHUNK_SIZE = 152400,
RETRY_INTERVAL = 300,
STATUS_NEW = 'new',
STATUS_START = 'started',
STATUS_END = 'finished';
var peerServer = {
iceServers: [
{url: 'stun:23.21.150.121'},
{url: 'stun:stun.l.google.com:19302'},
{url: 'turn:numb.viagenie.ca', credential: 'webrtcdemo', username: 'louis%40mozilla.com'}
]
};
var peerOptions = {
optional: [
{DtlsSrtpKeyAgreement: true}
]
};
var channelOptions = {
reliable: true
};
var constraints = {
optional: [],
mandatory: {
OfferToReceiveAudio: true,
OfferToReceiveVideo: true
}
};
/**
* Creating empty file that can be filled with chunks
*
* @constructor
* @param {Object} options
* @param {Number} options.size
* @param {String} options.name
* @param {String} options.type
*/
function FileStream(options) {
this._loaded = 0;
this._chunks = [];
this._size = options.size;
this._type = options.type;
this.name = options.name;
EventEmitter.call(this);
}
FileStream.prototype = Object.create(EventEmitter.prototype);
FileStream.prototype.constructor = FileStream;
/**
* Adding chunk to buffer
*
* @param {ArrayBuffer} buff
*/
FileStream.prototype.append = function (buff) {
this._chunks.push(buff);
this._loaded += buff.byteLength || buff.size;
this.emit('progress', this._loaded / this._size);
if (this._loaded >= this._size) {
this._createUrl();
}
return this;
};
/**
* Starting load file
*/
FileStream.prototype.load = function () {
return this.emit('start');
};
Object.defineProperty(FileStream.prototype, 'url', {
get: function () {
if (!this._url) {
throw new Error('.url is not avaliable until file loads');
}
return this._url;
}
});
FileStream.prototype._createUrl = function () {
var blob = this.getBlob(),
onError = this.emit.bind(this, 'error'),
_this = this;
if (!requestFileSystem) {
this._url = URL.createObjectURL(blob);
_this.emit('url', this._url);
_this.emit('load');
return;
}
requestFileSystem(window.TEMPORARY, blob.size, function (fs) {
fs.root.getFile(_this.name, {create: true}, function (fileEntry) {
_this._url = fileEntry.toURL();
_this.emit('url', _this._url);
fileEntry.createWriter(function (writer) {
writer.onerror = onError;
writer.onwriteend = function () {
_this.emit('load');
};
writer.write(blob);
}, onError);
}, onError);
}, onError);
};
/**
* Getting blob from stream
*
* @return {Blob} file
*/
FileStream.prototype.getBlob = function () {
return new Blob(this._chunks, {type: this._type});
};
/**
* WebRTC peer connection wrapper
* @constructor
*/
function Peer() {
this._messagePull = [];
this._iceCandidate = null;
this._files = {
received: {},
sent: {}
};
this._createConnection();
this.messages = new EventEmitter();
EventEmitter.call(this);
}
Peer.prototype = Object.create(EventEmitter.prototype);
Peer.prototype.constructor = Peer;
Peer.prototype._createConnection = function () {
var _this = this,
pc;
try {
pc = new PeerConnection(peerServer, peerOptions);
} catch(e) {
return this.emit('error', e);
}
this._pc = pc;
this._channel = null;
pc.onicecandidate = function (e) {
if (e.candidate === null) {
return;
}
pc.onicecandidate = null;
_this.emit('sync', {candidate: e.candidate});
};
pc.onaddstream = function (data) {
if (data.stream.id !== 'default') {
_this.emit('stream', data.stream);
}
};
pc.ondatachannel = function (e) {
var channel = e.channel;
_this._channel = channel;
channel.onmessage = _this._onChannelMessage.bind(_this);
};
pc.oniceconnectionstatechange = function (e) {
if (pc.iceConnectionState == 'disconnected') {
_this.emit('disconnect');
_this._createConnection();
}
};
};
/**
* Create offer with current state of connection
*/
Peer.prototype._createOffer = function () {
var _this = this;
this._pc.createOffer(
function (offer) {
_this._pc.setLocalDescription(offer);
_this.emit('sync', {offer: offer});
},
this.emit.bind(this, 'error'),
constraints
);
return this;
};
/**
* Reopen connection
* @param {Object} settings same to .sync()
*/
Peer.prototype._renew = function (settings) {
var streams = this._pc.getLocalStreams();
this._pc.close();
this._createConnection();
streams.forEach(function (stream) {
this._pc.addStream(stream);
}, this);
this.sync(settings);
this._pc.addIceCandidate(new RTCIceCandidate(this._iceCandidate));
this.emit('reconnect');
};
/**
* Sync with another peer
*
* @param {String|Object} opts
* @param {Object} [opts.offer] of another peer
* @param {Object} [opts.candidate] new ice candidate
* @param {Object} [opts.answer] of answer peer
*/
Peer.prototype.sync = function (opts) {
var settings = 'object' === typeof opts ? opts : JSON.parse(opts),
pc = this._pc,
_this = this;
if (settings.offer) {
pc.setRemoteDescription(new SessionDescription(settings.offer), function () {
pc.createAnswer(
function (answer) {
pc.setLocalDescription(answer);
_this.emit('sync', {answer: answer});
},
_this.emit.bind(_this, 'error'),
constraints
);
}, function () {
_this._renew(settings);
});
}
if (settings.candidate) {
this._iceCandidate = settings.candidate;
this._pc.addIceCandidate(new RTCIceCandidate(settings.candidate));
}
if (settings.answer) {
this._pc.setRemoteDescription(new SessionDescription(settings.answer));
}
};
/**
* Create data channel
*/
Peer.prototype._createChannel = function () {
var _this = this,
channel = this._pc.createDataChannel('myLabel', channelOptions);
channel.onopen = function () {
channel.binaryType = 'arraybuffer';
_this._tryToSendMessages();
};
channel.onerror = this.emit.bind(this, 'error');
channel.onmessage = this._onChannelMessage.bind(this);
this._channel = channel;
this._createOffer();
};
function readFileAsStream(file, onProgress, onDone) {
var reader = new FileReader(),
loaddedBefore = 0;
reader.readAsArrayBuffer(file);
reader.onprogress = function (e) {
if (!reader.result) {
return;
}
var loaded = e.loaded,
chunk, index;
for (index = loaddedBefore; index < loaded; index += MAX_CHUNK_SIZE) {
chunk = reader.result.slice(index, index + MAX_CHUNK_SIZE);
onProgress(chunk);
}
loaddedBefore = e.loaded;
};
reader.onloadend = function () {
var loaded = reader.result.byteLength,
index, chunk;
for (index = loaddedBefore; index < loaded; index += MAX_CHUNK_SIZE) {
chunk = reader.result.slice(index, index + MAX_CHUNK_SIZE);
onProgress(chunk);
}
onDone();
};
}
Peer.prototype._sendFile = function (id) {
var file = this._files.sent[id],
_this = this;
readFileAsStream(
file,
this._send.bind(this),
function () {
_this._send({
file: id,
status: STATUS_END
});
}
);
};
/**
* Data channel message handler
*/
Peer.prototype._onChannelMessage = function (e) {
var data = e.data,
_this = this,
file;
if (data instanceof ArrayBuffer || data instanceof Blob) {
return this._lastFile.append(data);
}
data = JSON.parse(data);
if (data.message) {
return this.messages.emit(data.message, data.data);
}
if (data.file) {
switch (data.status) {
case STATUS_NEW:
file = new FileStream(data);
file.on('start', function () {
_this._send({
file: data.file,
status: STATUS_START
});
});
this.emit('file', file);
this._lastFile = this._files.received[data.file] = file;
break;
case STATUS_START:
this._sendFile(data.file);
break;
case STATUS_END:
this.emit('file load', this._lastFile.getBlob());
break;
}
}
};
/**
* Add media stream
*
* @param {MediaStream} stream
*/
Peer.prototype.addStream = function (stream) {
this._pc.addStream(stream);
this._createOffer();
};
/**
* Sending json or ArrayBuffer to peer
* @private
*
* @param {ArrayBuffer|Object} message
*/
Peer.prototype._send = function (message) {
if (!this._channel) {
this._createChannel();
}
message = message instanceof ArrayBuffer ? message : JSON.stringify(message);
this._messagePull.push(message);
if ('open' === this._channel.readyState) {
this._tryToSendMessages();
}
};
/**
* Send data to peer
* @param {String} name
* @param {Mixed} data
*/
Peer.prototype.send = function (name, data) {
this._send({
message: name,
data: data
});
return this;
};
Peer.prototype._tryToSendMessages = function (isRetry) {
var pull = this._messagePull,
message;
if (!isRetry && this._messageRetryTimer) {
return;
}
if (this._messageRetryTimer) {
clearTimeout(this._messageRetryTimer);
this._messageRetryTimer = null;
}
while((message = pull.shift())) {
try {
this._channel.send(message);
} catch(e) {
message.id = Math.random();
pull.unshift(message);
this._messageRetryTimer = setTimeout(this._tryToSendMessages.bind(this, true), RETRY_INTERVAL);
this.emit('error', e);
break;
}
}
};
/**
* Send file to peer
*
* @param {File} file
*/
Peer.prototype.sendFile = function (file) {
var id = Date.now() + Math.random();
this._files.sent[id] = file;
this._send({
file: id,
name: file.name,
size: file.size,
type: file.type,
status: STATUS_NEW
});
};
/**
* Close connection
*/
Peer.prototype.close = function () {
this._pc.close();
this.emit('close');
this.removeAllListeners();
};
/*global define*/
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = Peer;
} else if (typeof define === 'function' && define.amd) {
define(Peer);
} else {
window.Peer = Peer;
}
}(window));
|
"use strict";
angular.
module( "mwl.calendar" ).
directive( "mwlEventDisplay", [ "$compile", function ( $compile ) {
return {
restrict: "A",
scope: true,
link: function linkFunction ( scope, element, attrs ) {
var linkedDirective = attrs.mwlEventDisplay;
if( linkedDirective ) {
//we remove our directive so as not to loop
element.removeAttr( "mwl-event-display" );
//in link, ng-repeat will have already $compiled and provided
//us with all of our repeats. so we remove that too
element.removeAttr( "ng-repeat" );
if( !element.attr( linkedDirective ) ) {
element.attr( linkedDirective, true );
element.attr( "event", "event" );
element.attr( "event-click", "eventClick()" );
element.attr( "event-edit-click", "eventEditClick()" );
element.attr( "event-delete-click", "eventDeleteClick()" );
element.attr( "edit-event-html", "editEventHtml" );
element.attr( "delete-event-html", "deleteEventHtml" );
$compile( element )( scope );
}
}
}
};
} ] );
|
module.exports = require('graphology-traversal');
|
'use strict';
var express = require('express');
var controller = require('./game.controller');
var config = require('../../config/environment');
var auth = require('../../auth/auth.service');
//var game_engine = require('./../../components/game_engine');
var router = express.Router();
//
router.post('/', auth.hasRole('admin'), controller.create);
router.delete('/:id', auth.hasRole('admin'), controller.destroy);
//
router.get('/', auth.isAuthenticated(), controller.index);
router.get('/:id', auth.isAuthenticated(), controller.show);
router.put('/:id', auth.isAuthenticated(), controller.update);
module.exports = router;
|
var fs = require('fs');
var checksPath = __dirname+'/../checks/';
fs.readdirSync(checksPath).forEach(function(file){
if(file.substr(-3) === '.js'){
var type = file.substr(0, file.length-3);
exports[type] = require(checksPath + type);
}
}); |
// This service connects to our REST API
angular.module('RDash').factory("Data", function ($http) {
var serviceBase = '/';
var obj = {};
obj.get = function (q, external) {
var path = external ? q : serviceBase + q;
return $http.get(path).then(function (results) {
return results.data;
});
};
obj.post = function (q, object) {
return $http.post(serviceBase + q, object).then(function (results) {
return results.data;
});
};
obj.put = function (q, object) {
return $http.put(serviceBase + q, object).then(function (results) {
return results.data;
});
};
obj.delete = function (q) {
return $http.delete(serviceBase + q).then(function (results) {
return results.data;
});
};
return obj;
}); |
'use strict';
module.exports = {
up: function (queryInterface, Sequelize) {
return queryInterface.createTable('Consultations', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
eventId: {
type: Sequelize.INTEGER,
references: {
model: 'Events',
key: 'id',
},
onUpdate: 'CASCADE',
onDelete: 'CASCADE'
},
patientId: {
type: Sequelize.INTEGER,
allowNull: false,
references: {
model: 'Patients',
key: 'id',
},
onUpdate: 'CASCADE',
onDelete: 'CASCADE'
},
start: {
type: Sequelize.DATE,
},
end: {
type: Sequelize.DATE
},
description: {
type: Sequelize.TEXT
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
}
});
},
down: function (queryInterface, Sequelize) {
return queryInterface.dropTable('Consultations');
}
}; |
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');
var ngAnnotate = require('gulp-ng-annotate');
var uglify = require('gulp-uglify');
var path = require('path');
var wrap = require('../lib/gulp-wrap-src.js');
var config = require('../../build-config.js');
var rename = require('../lib/gulp-rename-filename.js');
var filter = require('../lib/gulp-mini-filter.js');
module.exports = function (gulp, module) {
module.task('scripts', ['clean', 'templates'], function () {
// At the moment of writing, generating and consuming source maps isn't optimal. Compile tools merge previous
// maps incorrectly, browsers aren't 100% certain about breakpoint locations and are unable to unmangle
// argument names. The most stable seems to be to uglify and map in two stages:
// 1. concat all js in one file and persist to the filesystem
// 2. uglify the previous file and point point the content of the source map to the original file.
var jsGlob = [
path.join(module.folders.src, module.name + '.js'),
path.join(module.folders.src, '**/*.js'),
path.join(module.folders.dest, module.name + '-templates.js'),
'!**/*.test.js',
'!**/*.ignore.js'
];
return gulp.src(jsGlob)
.pipe(module.touch())
.pipe(wrap({
header: {
path: module.name + '-header.js',
contents: config.header + '(function(angular) {\n'
},
footer: {
path: module.name + '-footer.js',
contents: '})(angular);'
}
}))
.pipe(sourcemaps.init())
.pipe(concat(module.name + '.js'))
.pipe(ngAnnotate())
.pipe(sourcemaps.write('.', { sourceRoot: '../src/' + module.name }))
.pipe(gulp.dest(module.folders.dest))
// Create the minified version
.pipe(sourcemaps.init())
.pipe(filter(function(file) {
// Filter out the previous map file.
return path.extname(file.path) != '.map';
}))
.pipe(rename(module.name + '.min.js'))
.pipe(uglify({ preserveComments: 'some' }))
.pipe(sourcemaps.write('.', { includeContent: false, sourceRoot: './' }))
.pipe(gulp.dest(module.folders.dest));
}
);
};
|
import assert from 'assert';
import '../src/prototypes';
import Combo from '../src/PricingRules/Combo';
const mockServices = {
priceList: {
p1: {
productName: 'P1',
price: 100
},
p2: {
productName: 'P2',
price: 200
},
p3: {
productName: 'P3',
price: 300
}
}
}
const p1Buy2Get1Free = {
productCode: 'p1',
buy: 2,
free: 1
};
describe('Combo', function () {
describe('Constructor', function () {
it('throws exception if definition is wrong - empty JSON object', function () {
try {
new Combo({});
assert.fail('Error expected');
} catch (ex) {
// do nothing
}
});
it('throws exception if definition is wrong - missing product code', function () {
try {
new Combo({
product_Code: 'xxx',
buy: 2,
free: 1
});
assert.fail('Error expected');
} catch (ex) {
// do nothing
}
});
it('throws exception if definition is wrong - missing buy', function () {
try {
new Combo({
productCode: 'xxx',
bu_y: 2,
free: 1
});
assert.fail('Error expected');
} catch (ex) {
// do nothing
}
});
it('throws exception if definition is wrong - missing free', function () {
try {
new Combo({
productCode: 'xxx',
buy: 2,
fr_ee: 1
});
assert.fail('Error expected');
} catch (ex) {
// do nothing
}
});
it('create Combo if definition is correct', function () {
try {
new Combo(p1Buy2Get1Free);
} catch (ex) {
assert.fail(ex);
}
});
});
describe('apply', function () {
it('Combo - buy 2 p1 with $200', function () {
let combo = new Combo(p1Buy2Get1Free, mockServices);
let cartItems = {
'p1': {
qty: 2,
subTotal: 200
}
}
let newItems = combo.applyRule(cartItems);
assert.equal(cartItems.p1.subTotal, 200); // after apply
});
it('Combo - buy 3 p1 with $200', function () {
let combo = new Combo(p1Buy2Get1Free, mockServices);
let cartItems = {
'p1': {
qty: 3,
subTotal: 300
}
}
let newItems = combo.applyRule(cartItems);
assert.equal(cartItems.p1.subTotal, 200); // after apply
});
it('Combo - buy 6 p1 with $400', function () {
let combo = new Combo(p1Buy2Get1Free, mockServices);
let cartItems = {
'p1': {
qty: 6,
subTotal: 600
}
}
let newItems = combo.applyRule(cartItems);
assert.equal(cartItems.p1.subTotal, 400); // after apply
});
it('Combo - buy 7 p1 with $500', function () {
let combo = new Combo(p1Buy2Get1Free, mockServices);
let cartItems = {
'p1': {
qty: 7,
subTotal: 700
}
}
let newItems = combo.applyRule(cartItems);
assert.equal(cartItems.p1.subTotal, 500); // after apply
});
});
})
|
require(['src/web/blend','src/web/dialog/alert','src/web/Slider','src/web/Layer.js','src/web/LayerGroup.js'], function (blend, alert,slider,layer,layergroup) {
"use strict";
blend = blend||{};
//dialogs
blend.dialog = {};
blend.dialog.alert = alert;
//components
blend.component = {};
// blend.component.slider = slider;
blend.Slider = slider;
//layer
blend.Layer = layer;
blend.LayerGroup = layergroup;
// window.Blend = blend;
window.Blend = window.Blend || {};//初始化window的blend 对象 , 将 blend 作为模块 绑定到 Blend.ui 上
window.Blend.ui = blend;
//等到dom ready之后回调
var e;
if (typeof CustomEvent !== 'undefined') {
e = new CustomEvent('blendready', {
// detail: { slideNumber: Math.abs(slideNumber) },
bubbles: false,
cancelable: true
});
}else{
e = document.createEvent("Event");
e.initEvent("blendready",false,false);
}
if (/complete|loaded|interactive/.test(document.readyState)) {
document.dispatchEvent(e);
} else {
document.addEventListener('DOMContentLoaded', function() {
document.dispatchEvent(e);
}, false);
}
},null,true);
|
"format register";
(function(global) {
var defined = {};
// indexOf polyfill for IE8
var indexOf = Array.prototype.indexOf || function(item) {
for (var i = 0, l = this.length; i < l; i++)
if (this[i] === item)
return i;
return -1;
}
function dedupe(deps) {
var newDeps = [];
for (var i = 0, l = deps.length; i < l; i++)
if (indexOf.call(newDeps, deps[i]) == -1)
newDeps.push(deps[i])
return newDeps;
}
function register(name, deps, declare, execute) {
if (typeof name != 'string')
throw "System.register provided no module name";
var entry;
// dynamic
if (typeof declare == 'boolean') {
entry = {
declarative: false,
deps: deps,
execute: execute,
executingRequire: declare
};
}
else {
// ES6 declarative
entry = {
declarative: true,
deps: deps,
declare: declare
};
}
entry.name = name;
// we never overwrite an existing define
if (!defined[name])
defined[name] = entry;
entry.deps = dedupe(entry.deps);
// we have to normalize dependencies
// (assume dependencies are normalized for now)
// entry.normalizedDeps = entry.deps.map(normalize);
entry.normalizedDeps = entry.deps;
}
function buildGroups(entry, groups) {
groups[entry.groupIndex] = groups[entry.groupIndex] || [];
if (indexOf.call(groups[entry.groupIndex], entry) != -1)
return;
groups[entry.groupIndex].push(entry);
for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) {
var depName = entry.normalizedDeps[i];
var depEntry = defined[depName];
// not in the registry means already linked / ES6
if (!depEntry || depEntry.evaluated)
continue;
// now we know the entry is in our unlinked linkage group
var depGroupIndex = entry.groupIndex + (depEntry.declarative != entry.declarative);
// the group index of an entry is always the maximum
if (depEntry.groupIndex === undefined || depEntry.groupIndex < depGroupIndex) {
// if already in a group, remove from the old group
if (depEntry.groupIndex !== undefined) {
groups[depEntry.groupIndex].splice(indexOf.call(groups[depEntry.groupIndex], depEntry), 1);
// if the old group is empty, then we have a mixed depndency cycle
if (groups[depEntry.groupIndex].length == 0)
throw new TypeError("Mixed dependency cycle detected");
}
depEntry.groupIndex = depGroupIndex;
}
buildGroups(depEntry, groups);
}
}
function link(name) {
var startEntry = defined[name];
startEntry.groupIndex = 0;
var groups = [];
buildGroups(startEntry, groups);
var curGroupDeclarative = !!startEntry.declarative == groups.length % 2;
for (var i = groups.length - 1; i >= 0; i--) {
var group = groups[i];
for (var j = 0; j < group.length; j++) {
var entry = group[j];
// link each group
if (curGroupDeclarative)
linkDeclarativeModule(entry);
else
linkDynamicModule(entry);
}
curGroupDeclarative = !curGroupDeclarative;
}
}
// module binding records
var moduleRecords = {};
function getOrCreateModuleRecord(name) {
return moduleRecords[name] || (moduleRecords[name] = {
name: name,
dependencies: [],
exports: {}, // start from an empty module and extend
importers: []
})
}
function linkDeclarativeModule(entry) {
// only link if already not already started linking (stops at circular)
if (entry.module)
return;
var module = entry.module = getOrCreateModuleRecord(entry.name);
var exports = entry.module.exports;
var declaration = entry.declare.call(global, function(name, value) {
module.locked = true;
exports[name] = value;
for (var i = 0, l = module.importers.length; i < l; i++) {
var importerModule = module.importers[i];
if (!importerModule.locked) {
var importerIndex = indexOf.call(importerModule.dependencies, module);
importerModule.setters[importerIndex](exports);
}
}
module.locked = false;
return value;
});
module.setters = declaration.setters;
module.execute = declaration.execute;
if (!module.setters || !module.execute)
throw new TypeError("Invalid System.register form for " + entry.name);
// now link all the module dependencies
for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) {
var depName = entry.normalizedDeps[i];
var depEntry = defined[depName];
var depModule = moduleRecords[depName];
// work out how to set depExports based on scenarios...
var depExports;
if (depModule) {
depExports = depModule.exports;
}
else if (depEntry && !depEntry.declarative) {
depExports = { 'default': depEntry.module.exports, __useDefault: true };
}
// in the module registry
else if (!depEntry) {
depExports = load(depName);
}
// we have an entry -> link
else {
linkDeclarativeModule(depEntry);
depModule = depEntry.module;
depExports = depModule.exports;
}
// only declarative modules have dynamic bindings
if (depModule && depModule.importers) {
depModule.importers.push(module);
module.dependencies.push(depModule);
}
else
module.dependencies.push(null);
// run the setter for this dependency
if (module.setters[i])
module.setters[i](depExports);
}
}
// An analog to loader.get covering execution of all three layers (real declarative, simulated declarative, simulated dynamic)
function getModule(name) {
var exports;
var entry = defined[name];
if (!entry) {
exports = load(name);
if (!exports)
throw new Error("Unable to load dependency " + name + ".");
}
else {
if (entry.declarative)
ensureEvaluated(name, []);
else if (!entry.evaluated)
linkDynamicModule(entry);
exports = entry.module.exports;
}
if ((!entry || entry.declarative) && exports && exports.__useDefault)
return exports['default'];
return exports;
}
function linkDynamicModule(entry) {
if (entry.module)
return;
var exports = {};
var module = entry.module = { exports: exports, id: entry.name };
// AMD requires execute the tree first
if (!entry.executingRequire) {
for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) {
var depName = entry.normalizedDeps[i];
var depEntry = defined[depName];
if (depEntry)
linkDynamicModule(depEntry);
}
}
// now execute
entry.evaluated = true;
var output = entry.execute.call(global, function(name) {
for (var i = 0, l = entry.deps.length; i < l; i++) {
if (entry.deps[i] != name)
continue;
return getModule(entry.normalizedDeps[i]);
}
throw new TypeError('Module ' + name + ' not declared as a dependency.');
}, exports, module);
if (output)
module.exports = output;
}
/*
* Given a module, and the list of modules for this current branch,
* ensure that each of the dependencies of this module is evaluated
* (unless one is a circular dependency already in the list of seen
* modules, in which case we execute it)
*
* Then we evaluate the module itself depth-first left to right
* execution to match ES6 modules
*/
function ensureEvaluated(moduleName, seen) {
var entry = defined[moduleName];
// if already seen, that means it's an already-evaluated non circular dependency
if (entry.evaluated || !entry.declarative)
return;
// this only applies to declarative modules which late-execute
seen.push(moduleName);
for (var i = 0, l = entry.normalizedDeps.length; i < l; i++) {
var depName = entry.normalizedDeps[i];
if (indexOf.call(seen, depName) == -1) {
if (!defined[depName])
load(depName);
else
ensureEvaluated(depName, seen);
}
}
if (entry.evaluated)
return;
entry.evaluated = true;
entry.module.execute.call(global);
}
// magical execution function
var modules = {};
function load(name) {
if (modules[name])
return modules[name];
var entry = defined[name];
// first we check if this module has already been defined in the registry
if (!entry)
throw "Module " + name + " not present.";
// recursively ensure that the module and all its
// dependencies are linked (with dependency group handling)
link(name);
// now handle dependency execution in correct order
ensureEvaluated(name, []);
// remove from the registry
defined[name] = undefined;
var module = entry.declarative ? entry.module.exports : { 'default': entry.module.exports, '__useDefault': true };
// return the defined module object
return modules[name] = module;
};
return function(main, declare) {
var System;
// if there's a system loader, define onto it
if (typeof System != 'undefined' && System.register) {
declare(System);
System['import'](main);
}
// otherwise, self execute
else {
declare(System = {
register: register,
get: load,
set: function(name, module) {
modules[name] = module;
},
newModule: function(module) {
return module;
},
global: global
});
System.set('@empty', System.newModule({}));
load(main);
}
};
})(typeof window != 'undefined' ? window : global)
/* ('mainModule', function(System) {
System.register(...);
}); */
('app', function(System) {
System.register("github:LeaVerou/prism@gh-pages/themes/prism-okaidia.css!github:systemjs/plugin-css@0.1.0", [], false, function() { console.log("SystemJS Builder - Plugin for github:LeaVerou/prism@gh-pages/themes/prism-okaidia.css!github:systemjs/plugin-css@0.1.0 does not support sfx builds"); });
(function() {
function define(){}; define.amd = {};
var Showdown = {extensions: {}};
var forEach = Showdown.forEach = function(obj, callback) {
if (typeof obj.forEach === 'function') {
obj.forEach(callback);
} else {
var i,
len = obj.length;
for (i = 0; i < len; i++) {
callback(obj[i], i, obj);
}
}
};
var stdExtName = function(s) {
return s.replace(/[_-]||\s/g, '').toLowerCase();
};
Showdown.converter = function(converter_options) {
var g_urls;
var g_titles;
var g_html_blocks;
var g_list_level = 0;
var g_lang_extensions = [];
var g_output_modifiers = [];
if (typeof module !== 'undefined' && typeof exports !== 'undefined' && typeof require !== 'undefined') {
var fs = require('fs');
if (fs) {
var extensions = fs.readdirSync((__dirname || '.') + '/extensions').filter(function(file) {
return ~file.indexOf('.js');
}).map(function(file) {
return file.replace(/\.js$/, '');
});
Showdown.forEach(extensions, function(ext) {
var name = stdExtName(ext);
Showdown.extensions[name] = require('./extensions/' + ext);
});
}
}
this.makeHtml = function(text) {
g_urls = {};
g_titles = {};
g_html_blocks = [];
text = text.replace(/~/g, "~T");
text = text.replace(/\$/g, "~D");
text = text.replace(/\r\n/g, "\n");
text = text.replace(/\r/g, "\n");
text = "\n\n" + text + "\n\n";
text = _Detab(text);
text = text.replace(/^[ \t]+$/mg, "");
Showdown.forEach(g_lang_extensions, function(x) {
text = _ExecuteExtension(x, text);
});
text = _DoGithubCodeBlocks(text);
text = _HashHTMLBlocks(text);
text = _StripLinkDefinitions(text);
text = _RunBlockGamut(text);
text = _UnescapeSpecialChars(text);
text = text.replace(/~D/g, "$$");
text = text.replace(/~T/g, "~");
Showdown.forEach(g_output_modifiers, function(x) {
text = _ExecuteExtension(x, text);
});
return text;
};
if (converter_options && converter_options.extensions) {
var self = this;
Showdown.forEach(converter_options.extensions, function(plugin) {
if (typeof plugin === 'string') {
plugin = Showdown.extensions[stdExtName(plugin)];
}
if (typeof plugin === 'function') {
Showdown.forEach(plugin(self), function(ext) {
if (ext.type) {
if (ext.type === 'language' || ext.type === 'lang') {
g_lang_extensions.push(ext);
} else if (ext.type === 'output' || ext.type === 'html') {
g_output_modifiers.push(ext);
}
} else {
g_output_modifiers.push(ext);
}
});
} else {
throw "Extension '" + plugin + "' could not be loaded. It was either not found or is not a valid extension.";
}
});
}
var _ExecuteExtension = function(ext, text) {
if (ext.regex) {
var re = new RegExp(ext.regex, 'g');
return text.replace(re, ext.replace);
} else if (ext.filter) {
return ext.filter(text);
}
};
var _StripLinkDefinitions = function(text) {
text += "~0";
text = text.replace(/^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|(?=~0))/gm, function(wholeMatch, m1, m2, m3, m4) {
m1 = m1.toLowerCase();
g_urls[m1] = _EncodeAmpsAndAngles(m2);
if (m3) {
return m3 + m4;
} else if (m4) {
g_titles[m1] = m4.replace(/"/g, """);
}
return "";
});
text = text.replace(/~0/, "");
return text;
};
var _HashHTMLBlocks = function(text) {
text = text.replace(/\n/g, "\n\n");
var block_tags_a = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del|style|section|header|footer|nav|article|aside";
var block_tags_b = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|style|section|header|footer|nav|article|aside";
text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)\b[^\r]*?\n<\/\2>[ \t]*(?=\n+))/gm, hashElement);
text = text.replace(/^(<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|style|section|header|footer|nav|article|aside)\b[^\r]*?<\/\2>[ \t]*(?=\n+)\n)/gm, hashElement);
text = text.replace(/(\n[ ]{0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g, hashElement);
text = text.replace(/(\n\n[ ]{0,3}<!(--[^\r]*?--\s*)+>[ \t]*(?=\n{2,}))/g, hashElement);
text = text.replace(/(?:\n\n)([ ]{0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g, hashElement);
text = text.replace(/\n\n/g, "\n");
return text;
};
var hashElement = function(wholeMatch, m1) {
var blockText = m1;
blockText = blockText.replace(/\n\n/g, "\n");
blockText = blockText.replace(/^\n/, "");
blockText = blockText.replace(/\n+$/g, "");
blockText = "\n\n~K" + (g_html_blocks.push(blockText) - 1) + "K\n\n";
return blockText;
};
var _RunBlockGamut = function(text) {
text = _DoHeaders(text);
var key = hashBlock("<hr />");
text = text.replace(/^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$/gm, key);
text = text.replace(/^[ ]{0,2}([ ]?\-[ ]?){3,}[ \t]*$/gm, key);
text = text.replace(/^[ ]{0,2}([ ]?\_[ ]?){3,}[ \t]*$/gm, key);
text = _DoLists(text);
text = _DoCodeBlocks(text);
text = _DoBlockQuotes(text);
text = _HashHTMLBlocks(text);
text = _FormParagraphs(text);
return text;
};
var _RunSpanGamut = function(text) {
text = _DoCodeSpans(text);
text = _EscapeSpecialCharsWithinTagAttributes(text);
text = _EncodeBackslashEscapes(text);
text = _DoImages(text);
text = _DoAnchors(text);
text = _DoAutoLinks(text);
text = _EncodeAmpsAndAngles(text);
text = _DoItalicsAndBold(text);
text = text.replace(/ +\n/g, " <br />\n");
return text;
};
var _EscapeSpecialCharsWithinTagAttributes = function(text) {
var regex = /(<[a-z\/!$]("[^"]*"|'[^']*'|[^'">])*>|<!(--.*?--\s*)+>)/gi;
text = text.replace(regex, function(wholeMatch) {
var tag = wholeMatch.replace(/(.)<\/?code>(?=.)/g, "$1`");
tag = escapeCharacters(tag, "\\`*_");
return tag;
});
return text;
};
var _DoAnchors = function(text) {
text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writeAnchorTag);
text = text.replace(/(\[((?:\[[^\]]*\]|[^\[\]])*)\]\([ \t]*()<?(.*?(?:\(.*?\).*?)?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g, writeAnchorTag);
text = text.replace(/(\[([^\[\]]+)\])()()()()()/g, writeAnchorTag);
return text;
};
var writeAnchorTag = function(wholeMatch, m1, m2, m3, m4, m5, m6, m7) {
if (m7 == undefined)
m7 = "";
var whole_match = m1;
var link_text = m2;
var link_id = m3.toLowerCase();
var url = m4;
var title = m7;
if (url == "") {
if (link_id == "") {
link_id = link_text.toLowerCase().replace(/ ?\n/g, " ");
}
url = "#" + link_id;
if (g_urls[link_id] != undefined) {
url = g_urls[link_id];
if (g_titles[link_id] != undefined) {
title = g_titles[link_id];
}
} else {
if (whole_match.search(/\(\s*\)$/m) > -1) {
url = "";
} else {
return whole_match;
}
}
}
url = escapeCharacters(url, "*_");
var result = "<a href=\"" + url + "\"";
if (title != "") {
title = title.replace(/"/g, """);
title = escapeCharacters(title, "*_");
result += " title=\"" + title + "\"";
}
result += ">" + link_text + "</a>";
return result;
};
var _DoImages = function(text) {
text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writeImageTag);
text = text.replace(/(!\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g, writeImageTag);
return text;
};
var writeImageTag = function(wholeMatch, m1, m2, m3, m4, m5, m6, m7) {
var whole_match = m1;
var alt_text = m2;
var link_id = m3.toLowerCase();
var url = m4;
var title = m7;
if (!title)
title = "";
if (url == "") {
if (link_id == "") {
link_id = alt_text.toLowerCase().replace(/ ?\n/g, " ");
}
url = "#" + link_id;
if (g_urls[link_id] != undefined) {
url = g_urls[link_id];
if (g_titles[link_id] != undefined) {
title = g_titles[link_id];
}
} else {
return whole_match;
}
}
alt_text = alt_text.replace(/"/g, """);
url = escapeCharacters(url, "*_");
var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\"";
title = title.replace(/"/g, """);
title = escapeCharacters(title, "*_");
result += " title=\"" + title + "\"";
result += " />";
return result;
};
var _DoHeaders = function(text) {
text = text.replace(/^(.+)[ \t]*\n=+[ \t]*\n+/gm, function(wholeMatch, m1) {
return hashBlock('<h1 id="' + headerId(m1) + '">' + _RunSpanGamut(m1) + "</h1>");
});
text = text.replace(/^(.+)[ \t]*\n-+[ \t]*\n+/gm, function(matchFound, m1) {
return hashBlock('<h2 id="' + headerId(m1) + '">' + _RunSpanGamut(m1) + "</h2>");
});
text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm, function(wholeMatch, m1, m2) {
var h_level = m1.length;
return hashBlock("<h" + h_level + ' id="' + headerId(m2) + '">' + _RunSpanGamut(m2) + "</h" + h_level + ">");
});
function headerId(m) {
return m.replace(/[^\w]/g, '').toLowerCase();
}
return text;
};
var _ProcessListItems;
var _DoLists = function(text) {
text += "~0";
var whole_list = /^(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm;
if (g_list_level) {
text = text.replace(whole_list, function(wholeMatch, m1, m2) {
var list = m1;
var list_type = (m2.search(/[*+-]/g) > -1) ? "ul" : "ol";
list = list.replace(/\n{2,}/g, "\n\n\n");
;
var result = _ProcessListItems(list);
result = result.replace(/\s+$/, "");
result = "<" + list_type + ">" + result + "</" + list_type + ">\n";
return result;
});
} else {
whole_list = /(\n\n|^\n?)(([ ]{0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(~0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/g;
text = text.replace(whole_list, function(wholeMatch, m1, m2, m3) {
var runup = m1;
var list = m2;
var list_type = (m3.search(/[*+-]/g) > -1) ? "ul" : "ol";
var list = list.replace(/\n{2,}/g, "\n\n\n");
;
var result = _ProcessListItems(list);
result = runup + "<" + list_type + ">\n" + result + "</" + list_type + ">\n";
return result;
});
}
text = text.replace(/~0/, "");
return text;
};
_ProcessListItems = function(list_str) {
g_list_level++;
list_str = list_str.replace(/\n{2,}$/, "\n");
list_str += "~0";
list_str = list_str.replace(/(\n)?(^[ \t]*)([*+-]|\d+[.])[ \t]+([^\r]+?(\n{1,2}))(?=\n*(~0|\2([*+-]|\d+[.])[ \t]+))/gm, function(wholeMatch, m1, m2, m3, m4) {
var item = m4;
var leading_line = m1;
var leading_space = m2;
if (leading_line || (item.search(/\n{2,}/) > -1)) {
item = _RunBlockGamut(_Outdent(item));
} else {
item = _DoLists(_Outdent(item));
item = item.replace(/\n$/, "");
item = _RunSpanGamut(item);
}
return "<li>" + item + "</li>\n";
});
list_str = list_str.replace(/~0/g, "");
g_list_level--;
return list_str;
};
var _DoCodeBlocks = function(text) {
text += "~0";
text = text.replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=~0))/g, function(wholeMatch, m1, m2) {
var codeblock = m1;
var nextChar = m2;
codeblock = _EncodeCode(_Outdent(codeblock));
codeblock = _Detab(codeblock);
codeblock = codeblock.replace(/^\n+/g, "");
codeblock = codeblock.replace(/\n+$/g, "");
codeblock = "<pre><code>" + codeblock + "\n</code></pre>";
return hashBlock(codeblock) + nextChar;
});
text = text.replace(/~0/, "");
return text;
};
var _DoGithubCodeBlocks = function(text) {
text += "~0";
text = text.replace(/(?:^|\n)```(.*)\n([\s\S]*?)\n```/g, function(wholeMatch, m1, m2) {
var language = m1;
var codeblock = m2;
codeblock = _EncodeCode(codeblock);
codeblock = _Detab(codeblock);
codeblock = codeblock.replace(/^\n+/g, "");
codeblock = codeblock.replace(/\n+$/g, "");
codeblock = "<pre><code" + (language ? " class=\"" + language + '"' : "") + ">" + codeblock + "\n</code></pre>";
return hashBlock(codeblock);
});
text = text.replace(/~0/, "");
return text;
};
var hashBlock = function(text) {
text = text.replace(/(^\n+|\n+$)/g, "");
return "\n\n~K" + (g_html_blocks.push(text) - 1) + "K\n\n";
};
var _DoCodeSpans = function(text) {
text = text.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm, function(wholeMatch, m1, m2, m3, m4) {
var c = m3;
c = c.replace(/^([ \t]*)/g, "");
c = c.replace(/[ \t]*$/g, "");
c = _EncodeCode(c);
return m1 + "<code>" + c + "</code>";
});
return text;
};
var _EncodeCode = function(text) {
text = text.replace(/&/g, "&");
text = text.replace(/</g, "<");
text = text.replace(/>/g, ">");
text = escapeCharacters(text, "\*_{}[]\\", false);
return text;
};
var _DoItalicsAndBold = function(text) {
text = text.replace(/(\*\*|__)(?=\S)([^\r]*?\S[*_]*)\1/g, "<strong>$2</strong>");
text = text.replace(/(\*|_)(?=\S)([^\r]*?\S)\1/g, "<em>$2</em>");
return text;
};
var _DoBlockQuotes = function(text) {
text = text.replace(/((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)/gm, function(wholeMatch, m1) {
var bq = m1;
bq = bq.replace(/^[ \t]*>[ \t]?/gm, "~0");
bq = bq.replace(/~0/g, "");
bq = bq.replace(/^[ \t]+$/gm, "");
bq = _RunBlockGamut(bq);
bq = bq.replace(/(^|\n)/g, "$1 ");
bq = bq.replace(/(\s*<pre>[^\r]+?<\/pre>)/gm, function(wholeMatch, m1) {
var pre = m1;
pre = pre.replace(/^ /mg, "~0");
pre = pre.replace(/~0/g, "");
return pre;
});
return hashBlock("<blockquote>\n" + bq + "\n</blockquote>");
});
return text;
};
var _FormParagraphs = function(text) {
text = text.replace(/^\n+/g, "");
text = text.replace(/\n+$/g, "");
var grafs = text.split(/\n{2,}/g);
var grafsOut = [];
var end = grafs.length;
for (var i = 0; i < end; i++) {
var str = grafs[i];
if (str.search(/~K(\d+)K/g) >= 0) {
grafsOut.push(str);
} else if (str.search(/\S/) >= 0) {
str = _RunSpanGamut(str);
str = str.replace(/^([ \t]*)/g, "<p>");
str += "</p>";
grafsOut.push(str);
}
}
end = grafsOut.length;
for (var i = 0; i < end; i++) {
while (grafsOut[i].search(/~K(\d+)K/) >= 0) {
var blockText = g_html_blocks[RegExp.$1];
blockText = blockText.replace(/\$/g, "$$$$");
grafsOut[i] = grafsOut[i].replace(/~K\d+K/, blockText);
}
}
return grafsOut.join("\n\n");
};
var _EncodeAmpsAndAngles = function(text) {
text = text.replace(/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/g, "&");
text = text.replace(/<(?![a-z\/?\$!])/gi, "<");
return text;
};
var _EncodeBackslashEscapes = function(text) {
text = text.replace(/\\(\\)/g, escapeCharacters_callback);
text = text.replace(/\\([`*_{}\[\]()>#+-.!])/g, escapeCharacters_callback);
return text;
};
var _DoAutoLinks = function(text) {
text = text.replace(/<((https?|ftp|dict):[^'">\s]+)>/gi, "<a href=\"$1\">$1</a>");
text = text.replace(/<(?:mailto:)?([-.\w]+\@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi, function(wholeMatch, m1) {
return _EncodeEmailAddress(_UnescapeSpecialChars(m1));
});
return text;
};
var _EncodeEmailAddress = function(addr) {
var encode = [function(ch) {
return "&#" + ch.charCodeAt(0) + ";";
}, function(ch) {
return "&#x" + ch.charCodeAt(0).toString(16) + ";";
}, function(ch) {
return ch;
}];
addr = "mailto:" + addr;
addr = addr.replace(/./g, function(ch) {
if (ch == "@") {
ch = encode[Math.floor(Math.random() * 2)](ch);
} else if (ch != ":") {
var r = Math.random();
ch = (r > .9 ? encode[2](ch) : r > .45 ? encode[1](ch) : encode[0](ch));
}
return ch;
});
addr = "<a href=\"" + addr + "\">" + addr + "</a>";
addr = addr.replace(/">.+:/g, "\">");
return addr;
};
var _UnescapeSpecialChars = function(text) {
text = text.replace(/~E(\d+)E/g, function(wholeMatch, m1) {
var charCodeToReplace = parseInt(m1);
return String.fromCharCode(charCodeToReplace);
});
return text;
};
var _Outdent = function(text) {
text = text.replace(/^(\t|[ ]{1,4})/gm, "~0");
text = text.replace(/~0/g, "");
return text;
};
var _Detab = function(text) {
text = text.replace(/\t(?=\t)/g, " ");
text = text.replace(/\t/g, "~A~B");
text = text.replace(/~B(.+?)~A/g, function(wholeMatch, m1, m2) {
var leadingText = m1;
var numSpaces = 4 - leadingText.length % 4;
for (var i = 0; i < numSpaces; i++)
leadingText += " ";
return leadingText;
});
text = text.replace(/~A/g, " ");
text = text.replace(/~B/g, "");
return text;
};
var escapeCharacters = function(text, charsToEscape, afterBackslash) {
var regexString = "([" + charsToEscape.replace(/([\[\]\\])/g, "\\$1") + "])";
if (afterBackslash) {
regexString = "\\\\" + regexString;
}
var regex = new RegExp(regexString, "g");
text = text.replace(regex, escapeCharacters_callback);
return text;
};
var escapeCharacters_callback = function(wholeMatch, m1) {
var charCodeToEscape = m1.charCodeAt(0);
return "~E" + charCodeToEscape + "E";
};
};
if (typeof module !== 'undefined')
module.exports = Showdown;
if (typeof define === 'function' && define.amd) {
System.register("github:showdownjs/showdown@0.3.4/src/showdown", [], false, function() {
return Showdown;
});
}
})();
System.register("github:LeaVerou/prism@gh-pages/prism", [], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
self = (typeof window !== 'undefined') ? window : ((typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) ? self : {});
var Prism = (function() {
var lang = /\blang(?:uage)?-(?!\*)(\w+)\b/i;
var _ = self.Prism = {
util: {
encode: function(tokens) {
if (tokens instanceof Token) {
return new Token(tokens.type, _.util.encode(tokens.content), tokens.alias);
} else if (_.util.type(tokens) === 'Array') {
return tokens.map(_.util.encode);
} else {
return tokens.replace(/&/g, '&').replace(/</g, '<').replace(/\u00a0/g, ' ');
}
},
type: function(o) {
return Object.prototype.toString.call(o).match(/\[object (\w+)\]/)[1];
},
clone: function(o) {
var type = _.util.type(o);
switch (type) {
case 'Object':
var clone = {};
for (var key in o) {
if (o.hasOwnProperty(key)) {
clone[key] = _.util.clone(o[key]);
}
}
return clone;
case 'Array':
return o.map(function(v) {
return _.util.clone(v);
});
}
return o;
}
},
languages: {
extend: function(id, redef) {
var lang = _.util.clone(_.languages[id]);
for (var key in redef) {
lang[key] = redef[key];
}
return lang;
},
insertBefore: function(inside, before, insert, root) {
root = root || _.languages;
var grammar = root[inside];
if (arguments.length == 2) {
insert = arguments[1];
for (var newToken in insert) {
if (insert.hasOwnProperty(newToken)) {
grammar[newToken] = insert[newToken];
}
}
return grammar;
}
var ret = {};
for (var token in grammar) {
if (grammar.hasOwnProperty(token)) {
if (token == before) {
for (var newToken in insert) {
if (insert.hasOwnProperty(newToken)) {
ret[newToken] = insert[newToken];
}
}
}
ret[token] = grammar[token];
}
}
_.languages.DFS(_.languages, function(key, value) {
if (value === root[inside] && key != inside) {
this[key] = ret;
}
});
return root[inside] = ret;
},
DFS: function(o, callback, type) {
for (var i in o) {
if (o.hasOwnProperty(i)) {
callback.call(o, i, o[i], type || i);
if (_.util.type(o[i]) === 'Object') {
_.languages.DFS(o[i], callback);
} else if (_.util.type(o[i]) === 'Array') {
_.languages.DFS(o[i], callback, i);
}
}
}
}
},
highlightAll: function(async, callback) {
var elements = document.querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code');
for (var i = 0,
element; element = elements[i++]; ) {
_.highlightElement(element, async === true, callback);
}
},
highlightElement: function(element, async, callback) {
var language,
grammar,
parent = element;
while (parent && !lang.test(parent.className)) {
parent = parent.parentNode;
}
if (parent) {
language = (parent.className.match(lang) || [, ''])[1];
grammar = _.languages[language];
}
if (!grammar) {
return ;
}
element.className = element.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;
parent = element.parentNode;
if (/pre/i.test(parent.nodeName)) {
parent.className = parent.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;
}
var code = element.textContent;
if (!code) {
return ;
}
code = code.replace(/^(?:\r?\n|\r)/, '');
var env = {
element: element,
language: language,
grammar: grammar,
code: code
};
_.hooks.run('before-highlight', env);
if (async && self.Worker) {
var worker = new Worker(_.filename);
worker.onmessage = function(evt) {
env.highlightedCode = Token.stringify(JSON.parse(evt.data), language);
_.hooks.run('before-insert', env);
env.element.innerHTML = env.highlightedCode;
callback && callback.call(env.element);
_.hooks.run('after-highlight', env);
};
worker.postMessage(JSON.stringify({
language: env.language,
code: env.code
}));
} else {
env.highlightedCode = _.highlight(env.code, env.grammar, env.language);
_.hooks.run('before-insert', env);
env.element.innerHTML = env.highlightedCode;
callback && callback.call(element);
_.hooks.run('after-highlight', env);
}
},
highlight: function(text, grammar, language) {
var tokens = _.tokenize(text, grammar);
return Token.stringify(_.util.encode(tokens), language);
},
tokenize: function(text, grammar, language) {
var Token = _.Token;
var strarr = [text];
var rest = grammar.rest;
if (rest) {
for (var token in rest) {
grammar[token] = rest[token];
}
delete grammar.rest;
}
tokenloop: for (var token in grammar) {
if (!grammar.hasOwnProperty(token) || !grammar[token]) {
continue;
}
var patterns = grammar[token];
patterns = (_.util.type(patterns) === "Array") ? patterns : [patterns];
for (var j = 0; j < patterns.length; ++j) {
var pattern = patterns[j],
inside = pattern.inside,
lookbehind = !!pattern.lookbehind,
lookbehindLength = 0,
alias = pattern.alias;
pattern = pattern.pattern || pattern;
for (var i = 0; i < strarr.length; i++) {
var str = strarr[i];
if (strarr.length > text.length) {
break tokenloop;
}
if (str instanceof Token) {
continue;
}
pattern.lastIndex = 0;
var match = pattern.exec(str);
if (match) {
if (lookbehind) {
lookbehindLength = match[1].length;
}
var from = match.index - 1 + lookbehindLength,
match = match[0].slice(lookbehindLength),
len = match.length,
to = from + len,
before = str.slice(0, from + 1),
after = str.slice(to + 1);
var args = [i, 1];
if (before) {
args.push(before);
}
var wrapped = new Token(token, inside ? _.tokenize(match, inside) : match, alias);
args.push(wrapped);
if (after) {
args.push(after);
}
Array.prototype.splice.apply(strarr, args);
}
}
}
}
return strarr;
},
hooks: {
all: {},
add: function(name, callback) {
var hooks = _.hooks.all;
hooks[name] = hooks[name] || [];
hooks[name].push(callback);
},
run: function(name, env) {
var callbacks = _.hooks.all[name];
if (!callbacks || !callbacks.length) {
return ;
}
for (var i = 0,
callback; callback = callbacks[i++]; ) {
callback(env);
}
}
}
};
var Token = _.Token = function(type, content, alias) {
this.type = type;
this.content = content;
this.alias = alias;
};
Token.stringify = function(o, language, parent) {
if (typeof o == 'string') {
return o;
}
if (Object.prototype.toString.call(o) == '[object Array]') {
return o.map(function(element) {
return Token.stringify(element, language, o);
}).join('');
}
var env = {
type: o.type,
content: Token.stringify(o.content, language, parent),
tag: 'span',
classes: ['token', o.type],
attributes: {},
language: language,
parent: parent
};
if (env.type == 'comment') {
env.attributes['spellcheck'] = 'true';
}
if (o.alias) {
var aliases = _.util.type(o.alias) === 'Array' ? o.alias : [o.alias];
Array.prototype.push.apply(env.classes, aliases);
}
_.hooks.run('wrap', env);
var attributes = '';
for (var name in env.attributes) {
attributes += name + '="' + (env.attributes[name] || '') + '"';
}
return '<' + env.tag + ' class="' + env.classes.join(' ') + '" ' + attributes + '>' + env.content + '</' + env.tag + '>';
};
if (!self.document) {
if (!self.addEventListener) {
return self.Prism;
}
self.addEventListener('message', function(evt) {
var message = JSON.parse(evt.data),
lang = message.language,
code = message.code;
self.postMessage(JSON.stringify(_.util.encode(_.tokenize(code, _.languages[lang]))));
self.close();
}, false);
return self.Prism;
}
var script = document.getElementsByTagName('script');
script = script[script.length - 1];
if (script) {
_.filename = script.src;
if (document.addEventListener && !script.hasAttribute('data-manual')) {
document.addEventListener('DOMContentLoaded', _.highlightAll);
}
}
return self.Prism;
})();
if (typeof module !== 'undefined' && module.exports) {
module.exports = Prism;
}
Prism.languages.markup = {
'comment': /<!--[\w\W]*?-->/g,
'prolog': /<\?.+?\?>/,
'doctype': /<!DOCTYPE.+?>/,
'cdata': /<!\[CDATA\[[\w\W]*?]]>/i,
'tag': {
pattern: /<\/?[\w:-]+\s*(?:\s+[\w:-]+(?:=(?:("|')(\\?[\w\W])*?\1|[^\s'">=]+))?\s*)*\/?>/gi,
inside: {
'tag': {
pattern: /^<\/?[\w:-]+/i,
inside: {
'punctuation': /^<\/?/,
'namespace': /^[\w-]+?:/
}
},
'attr-value': {
pattern: /=(?:('|")[\w\W]*?(\1)|[^\s>]+)/gi,
inside: {'punctuation': /=|>|"/g}
},
'punctuation': /\/?>/g,
'attr-name': {
pattern: /[\w:-]+/g,
inside: {'namespace': /^[\w-]+?:/}
}
}
},
'entity': /&#?[\da-z]{1,8};/gi
};
Prism.hooks.add('wrap', function(env) {
if (env.type === 'entity') {
env.attributes['title'] = env.content.replace(/&/, '&');
}
});
Prism.languages.css = {
'comment': /\/\*[\w\W]*?\*\//g,
'atrule': {
pattern: /@[\w-]+?.*?(;|(?=\s*\{))/gi,
inside: {'punctuation': /[;:]/g}
},
'url': /url\((?:(["'])(\\\n|\\?.)*?\1|.*?)\)/gi,
'selector': /[^\{\}\s][^\{\};]*(?=\s*\{)/g,
'string': /("|')(\\\n|\\?.)*?\1/g,
'property': /(\b|\B)[\w-]+(?=\s*:)/ig,
'important': /\B!important\b/gi,
'punctuation': /[\{\};:]/g,
'function': /[-a-z0-9]+(?=\()/ig
};
if (Prism.languages.markup) {
Prism.languages.insertBefore('markup', 'tag', {'style': {
pattern: /<style[\w\W]*?>[\w\W]*?<\/style>/ig,
inside: {
'tag': {
pattern: /<style[\w\W]*?>|<\/style>/ig,
inside: Prism.languages.markup.tag.inside
},
rest: Prism.languages.css
},
alias: 'language-css'
}});
Prism.languages.insertBefore('inside', 'attr-value', {'style-attr': {
pattern: /\s*style=("|').+?\1/ig,
inside: {
'attr-name': {
pattern: /^\s*style/ig,
inside: Prism.languages.markup.tag.inside
},
'punctuation': /^\s*=\s*['"]|['"]\s*$/,
'attr-value': {
pattern: /.+/gi,
inside: Prism.languages.css
}
},
alias: 'language-css'
}}, Prism.languages.markup.tag);
}
Prism.languages.clike = {
'comment': [{
pattern: /(^|[^\\])\/\*[\w\W]*?\*\//g,
lookbehind: true
}, {
pattern: /(^|[^\\:])\/\/.*?(\r?\n|$)/g,
lookbehind: true
}],
'string': /("|')(\\\n|\\?.)*?\1/g,
'class-name': {
pattern: /((?:(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/ig,
lookbehind: true,
inside: {punctuation: /(\.|\\)/}
},
'keyword': /\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/g,
'boolean': /\b(true|false)\b/g,
'function': {
pattern: /[a-z0-9_]+\(/ig,
inside: {punctuation: /\(/}
},
'number': /\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?)\b/g,
'operator': /[-+]{1,2}|!|<=?|>=?|={1,3}|&{1,2}|\|?\||\?|\*|\/|~|\^|%/g,
'ignore': /&(lt|gt|amp);/gi,
'punctuation': /[{}[\];(),.:]/g
};
Prism.languages.javascript = Prism.languages.extend('clike', {
'keyword': /\b(break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|get|if|implements|import|in|instanceof|interface|let|new|null|package|private|protected|public|return|set|static|super|switch|this|throw|true|try|typeof|var|void|while|with|yield)\b/g,
'number': /\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee][+-]?\d+)?|NaN|-?Infinity)\b/g,
'function': /(?!\d)[a-z0-9_$]+(?=\()/ig
});
Prism.languages.insertBefore('javascript', 'keyword', {'regex': {
pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/g,
lookbehind: true
}});
if (Prism.languages.markup) {
Prism.languages.insertBefore('markup', 'tag', {'script': {
pattern: /<script[\w\W]*?>[\w\W]*?<\/script>/ig,
inside: {
'tag': {
pattern: /<script[\w\W]*?>|<\/script>/ig,
inside: Prism.languages.markup.tag.inside
},
rest: Prism.languages.javascript
},
alias: 'language-javascript'
}});
}
(function() {
if (!self.Prism || !self.document || !document.querySelector) {
return ;
}
var Extensions = {
'js': 'javascript',
'html': 'markup',
'svg': 'markup',
'xml': 'markup',
'py': 'python',
'rb': 'ruby',
'ps1': 'powershell',
'psm1': 'powershell'
};
Array.prototype.slice.call(document.querySelectorAll('pre[data-src]')).forEach(function(pre) {
var src = pre.getAttribute('data-src');
var extension = (src.match(/\.(\w+)$/) || [, ''])[1];
var language = Extensions[extension] || extension;
var code = document.createElement('code');
code.className = 'language-' + language;
pre.textContent = '';
code.textContent = 'Loading…';
pre.appendChild(code);
var xhr = new XMLHttpRequest();
xhr.open('GET', src, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status < 400 && xhr.responseText) {
code.textContent = xhr.responseText;
Prism.highlightElement(code);
} else if (xhr.status >= 400) {
code.textContent = '✖ Error ' + xhr.status + ' while fetching file: ' + xhr.statusText;
} else {
code.textContent = '✖ Error: File does not exist or is empty';
}
}
};
xhr.send(null);
});
})();
global.define = __define;
return module.exports;
});
System.register("github:systemjs/plugin-css@0.1.0/css", [], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
if (typeof window !== 'undefined') {
var waitSeconds = 100;
var head = document.getElementsByTagName('head')[0];
var links = document.getElementsByTagName('link');
var linkHrefs = [];
for (var i = 0; i < links.length; i++) {
linkHrefs.push(links[i].href);
}
var isWebkit = !!window.navigator.userAgent.match(/AppleWebKit\/([^ ;]*)/);
var webkitLoadCheck = function(link, callback) {
setTimeout(function() {
for (var i = 0; i < document.styleSheets.length; i++) {
var sheet = document.styleSheets[i];
if (sheet.href == link.href)
return callback();
}
webkitLoadCheck(link, callback);
}, 10);
};
var noop = function() {};
var loadCSS = function(url) {
return new Promise(function(resolve, reject) {
var timeout = setTimeout(function() {
reject('Unable to load CSS');
}, waitSeconds * 1000);
var _callback = function() {
clearTimeout(timeout);
link.onload = noop;
setTimeout(function() {
resolve('');
}, 7);
};
var link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = url;
if (!isWebkit)
link.onload = _callback;
else
webkitLoadCheck(link, _callback);
head.appendChild(link);
});
};
exports.fetch = function(load) {
for (var i = 0; i < linkHrefs.length; i++)
if (load.address == linkHrefs[i])
return '';
return loadCSS(load.address);
};
} else {
exports.build = false;
}
global.define = __define;
return module.exports;
});
(function() {
function define(){}; define.amd = {};
System.register("github:showdownjs/showdown@0.3.4", ["github:showdownjs/showdown@0.3.4/src/showdown"], false, function(__require, __exports, __module) {
return (function(main) {
return main;
}).call(this, __require('github:showdownjs/showdown@0.3.4/src/showdown'));
});
})();
System.register("github:LeaVerou/prism@gh-pages", ["github:LeaVerou/prism@gh-pages/prism"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
module.exports = require("github:LeaVerou/prism@gh-pages/prism");
global.define = __define;
return module.exports;
});
System.register("github:systemjs/plugin-css@0.1.0", ["github:systemjs/plugin-css@0.1.0/css"], true, function(require, exports, module) {
var global = System.global,
__define = global.define;
global.define = undefined;
module.exports = require("github:systemjs/plugin-css@0.1.0/css");
global.define = __define;
return module.exports;
});
System.register("github:guybedford/markdown-component@0.1.0/markdown-component", ["github:showdownjs/showdown@0.3.4", "github:LeaVerou/prism@gh-pages", "github:LeaVerou/prism@gh-pages/themes/prism-okaidia.css!github:systemjs/plugin-css@0.1.0"], function (_export) {
"use strict";
var showdown, prism, _prototypeProperties, _inherits, _classCallCheck, converter, XMarkdownComponent;
return {
setters: [function (_githubShowdownjsShowdown034) {
showdown = _githubShowdownjsShowdown034["default"];
}, function (_githubLeaVerouPrismGhPages) {
prism = _githubLeaVerouPrismGhPages["default"];
}, function (_githubLeaVerouPrismGhPagesThemesPrismOkaidiaCssGithubSystemjsPluginCss010) {}],
execute: function () {
_prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); };
_inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
_classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
converter = new showdown.converter();
XMarkdownComponent = (function (HTMLElement) {
function XMarkdownComponent() {
_classCallCheck(this, XMarkdownComponent);
if (Object.getPrototypeOf(XMarkdownComponent) !== null) {
Object.getPrototypeOf(XMarkdownComponent).apply(this, arguments);
}
}
_inherits(XMarkdownComponent, HTMLElement);
_prototypeProperties(XMarkdownComponent, null, {
createdCallback: {
value: function createdCallback() {
this.innerHTML = converter.makeHtml(this.innerHTML.split("\n").map(function (line) {
return line.trim();
}).join("\n"));
prism.highlightAll(this.querySelectorAll("code"));
},
writable: true,
configurable: true
}
});
return XMarkdownComponent;
})(HTMLElement);
document.registerElement("x-markdown-component", XMarkdownComponent);
}
};
});
System.register("github:guybedford/markdown-component@0.1", ["github:guybedford/markdown-component@0.1.0/markdown-component"], function (_export) {
"use strict";
return {
setters: [function (_githubGuybedfordMarkdownComponent010MarkdownComponent) {
for (var _key in _githubGuybedfordMarkdownComponent010MarkdownComponent) {
_export(_key, _githubGuybedfordMarkdownComponent010MarkdownComponent[_key]);
}
}],
execute: function () {}
};
});
System.register("app", ["github:guybedford/markdown-component@0.1.0"], function (_export) {
"use strict";
var log;
return {
setters: [function (_githubGuybedfordMarkdownComponent010) {}],
execute: function () {
log = function (msg) {
return console.log(msg);
};
log("test");
}
};
});
});
//# sourceMappingURL=bundle-sfx.js.map |
var package,
urlVars = getUrlVars(),
ship, canvas, camera;
var killmail = new Killmail(urlVars["id"], function (k) {
try {
package = k.getKillmail();
console.log(k.getEFT())
console.log(package)
$(document).ready(function () {
getShip(package);
populateModules(package)
getAttackers(package);
getTypes(package);
getVictimInformation(package.killmail.victim);
getSystemInfo(package.systemInfo);
new ClipboardJS('.clipboardCopy', {
text: function (trigger) {
showAlert("copied to clipboard", "success");
return k.getEFT();
}
});
});
} catch (e) {
showAlert("Failed to read killmail: " + e, "danger")
}
});
function setResonancePercentage(resonance, value) {
if (!value) {
value = 1;
}
value = 1 - value;
if (value < 0) { value = 0 }
value = (value * 100).toFixed(0);
$('#' + resonance).css('width', value + '%').attr('aria-valuenow', value);
$('#' + resonance).text(value + "%");
}
function setModuleSlot(type, slot, i) {
typeNames = package.attributes.types;
$("#" + type + slot).prepend('<img class="ttp" src="//imageserver.eveonline.com/Type/' + i.typeID + '_32.png" title="' + typeNames[i.typeID] + '" style="height: 32px; width: 32px; z-index:3000">')
$("#" + type + slot + " .ttp").tooltipster({
contentAsHTML: true,
position: 'bottom',
side: 'bottom',
viewportAware: false,
functionInit: function (ins) {
ins.content(moduleToolTip(i, typeNames));
},
});
if (i.chargeTypeID > 0) $("#" + type + slot + "l").prepend('<img src="//imageserver.eveonline.com/Type/' + i.chargeTypeID + '_32.png" style="height: 32px; width: 32px;">')
}
function moduleToolTip(i, t) {
var pm = package.priceMap;
var attr = "";
if (pm[i.typeID] != undefined) {
attr += `<div style="font-size: 10px;">Value: ${simpleVal(pm[i.typeID], 2)} ISK</div>`
}
$.each(i, function (k, v) {
if (!k.includes("chargeRate") && !k.includes("chargeSize") &&
!k.includes("HeatAbsorb") && !k.includes("Group") &&
k != "optimalSigRadius" && k != "mass" && k != "hp") {
icon = attributeNameIconMap[k];
if (icon != undefined) {
attr += `
<div><img src="/i/icons/${icon}" style="height: 23px; width: 23px"> ${k}: ${v}</div>
`
}
}
});
return `
<div style="font-weight: bolder;">${t[i.typeID]}</div>
${attr}
`;
}
function rc() {
return (Math.random() >= 0.5 ? 1 : -1) * Math.random() * 1000000;
}
function cycleModule(slot) {
var vec4 = ccpwgl_int.math.vec4,
quat = ccpwgl_int.math.quat,
mat4 = ccpwgl_int.math.mat4;
var viewProjInv = ship.getTransform();
var pt = quat.fromValues(rc(), rc(), 4000000, 1);
ship.setTurretTargetPosition(slot, pt);
ship.setTurretState(slot, ccpwgl.TurretState.FIRING);
setTimeout(cycleModule, Math.random() * 3000, slot);
}
function setModule(slot, type) {
if (graphicsMap[type] && ship != undefined) {
ship.mountTurret(slot, graphicsMap[type]);
setTimeout(cycleModule, 100, slot);
}
}
function populateModules(package) {
if (!package.attributes)
return;
typeNames = package.attributes.types;
$.each(package.attributes.modules, function (k, i) {
switch (i.location) {
case 27: // hiSlots
setModuleSlot("high", "1", i);
setModule(1, i.typeID)
break;
case 28: // hiSlots
setModuleSlot("high", "2", i);
setModule(2, i.typeID)
break;
case 29: // hiSlots
setModuleSlot("high", "3", i);
setModule(3, i.typeID)
break;
case 30: // hiSlots
setModuleSlot("high", "4", i);
setModule(4, i.typeID)
break;
case 31: // hiSlots
setModuleSlot("high", "5", i);
setModule(5, i.typeID)
break;
case 32: // hiSlots
setModuleSlot("high", "6", i);
setModule(6, i.typeID)
break;
case 33: // hiSlots
setModuleSlot("high", "7", i);
setModule(7, i.typeID)
break;
case 34: // hiSlots
setModuleSlot("high", "8", i);
setModule(8, i.typeID)
break;
case 19:
setModuleSlot("mid", "1", i);
break;
case 20:
setModuleSlot("mid", "2", i);
break;
case 21:
setModuleSlot("mid", "3", i);
break;
case 22:
setModuleSlot("mid", "4", i);
break;
case 23:
setModuleSlot("mid", "5", i);
break;
case 24:
setModuleSlot("mid", "6", i);
break;
case 25:
setModuleSlot("mid", "7", i);
break;
case 26:
setModuleSlot("mid", "8", i);
break;
case 11:
setModuleSlot("low", "1", i);
break;
case 12:
setModuleSlot("low", "2", i);
break;
case 13:
setModuleSlot("low", "3", i);
break;
case 14:
setModuleSlot("low", "4", i);
break;
case 15:
setModuleSlot("low", "5", i);
break;
case 16:
setModuleSlot("low", "6", i);
break;
case 17:
setModuleSlot("low", "7", i);
break;
case 18:
setModuleSlot("low", "8", i);
break;
case 92:
setModuleSlot("rig", "1", i);
break;
case 93:
setModuleSlot("rig", "2", i);
break;
case 94:
setModuleSlot("rig", "3", i);
break;
case 164:
setModuleSlot("sub", "1", i);
break;
case 165:
setModuleSlot("sub", "2", i);
break;
case 166:
setModuleSlot("sub", "3", i);
break;
case 167:
setModuleSlot("sub", "4", i);
break;
case 168:
setModuleSlot("sub", "5", i);
break;
}
});
}
function getCorporationImage(a) {
if (a.corporation_id != undefined) {
return "Corporation/" + a.corporation_id + "_32.png";
} else {
return "Corporation/" + a.faction_id + "_32.png";
}
}
function getAllianceImage(a) {
if (a.alliance_id != undefined) {
return "Alliance/" + a.alliance_id + "_64.png";
} else if (a.faction_id != undefined) {
return "Corporation/" + a.faction_id + "_64.png";
} else {
return "Corporation/" + a.corporation_id + "_64.png";
}
}
function getPortrait(a) {
if (a.character_id != undefined) {
return "Character/" + a.character_id + "_64.jpg";
} else if (a.corporation_id != undefined) {
return "Corporation/" + a.corporation_id + "_64.png";
} else {
return "Corporation/" + a.faction_id + "_64.png";
}
}
function getTypeImage(typeID) {
return "Type/" + typeID + "_64.png";
}
function getShipImage(a) {
return a.ship_type_id + "_32.png";
}
function getWeaponImage(a) {
return a.weapon_type_id == undefined ?
a.ship_type_id + "_32.png" :
a.weapon_type_id + "_32.png";
}
function getSystemInfo(a) {
if (a.security == undefined) a.security = 0;
var theStuff = "";
theStuff += `Location: ${a.solarSystemName} (${a.security.toFixed(1)}) ${a.regionName}<br>`;
if (a.celestialID != undefined) theStuff += "Near: " + a.celestialName + "<br>";
$("#sysInfo").html(`${theStuff}`);
}
function getVictimInformation(a) {
$("#victimImage").attr('src', `//imageserver.eveonline.com/${getPortrait(a)}`)
$("#victimCorporationImage").attr('src', `//imageserver.eveonline.com/${getCorporationImage(a)}`)
$("#victimAllianceImage").attr('src', `//imageserver.eveonline.com/${getAllianceImage(a)}`)
$("#victim").html(getCharacterInformation(a));
}
function getLink(id, type) {
return `<a href="/${type}?id=${id}">${package.nameMap[id]}</a>`;
}
function getCharacterInformation(a) {
var theStuff = "";
if (a.character_id != undefined) theStuff += getLink(a.character_id, "character") + "<br>";
if (a.corporation_id != undefined) theStuff += getLink(a.corporation_id, "corporation") + "<br>"
if (a.alliance_id != undefined) theStuff += getLink(a.alliance_id, "alliance") + "<br>"
if (a.faction_id != undefined) theStuff += "<small>" + package.nameMap[a.faction_id] + "</small>"
return theStuff;
}
function getAttackers(package) {
$("#numInvolved").text(simpleVal(package.killmail.attackers.length) + " Involved");
var stripe = false,
totalDamaged = 0;
$.each(package.killmail.attackers, function (k, a) {
if (a.damage_done != undefined)
totalDamaged += a.damage_done;
var row = `
<div class="row killmail" style="background-color: ${stripe ? "#06100a;" : "#16201a;"} padding: 0px;">
<div style="float: left; width: 64px">
<img src="//imageserver.eveonline.com/${getPortrait(a)}" style="width:64px; height: 64px">
</div>
<div style="float: left; width: 32px">
<img src="//imageserver.eveonline.com/Type/${getShipImage(a)}" style="width:32px; height: 32px">
<img src="//imageserver.eveonline.com/Type/${getWeaponImage(a)}" style="width:32px; height: 32px">
</div>
<div style="width: 230px; float: left; ">
${getCharacterInformation(a)}
</div>
<div style="width: 66px; float: left; text-align: right">
${simpleVal(a.damage_done)}
</div>
</div>`;
$("#attackers").append(row);
stripe = !stripe;
});
$("#totalDamaged").html(simpleVal(totalDamaged) + " Damage");
}
function addTypeRow(typeID, dropped, quantity, value, stripe) {
if (value == undefined)
value = 0;
var row = `
<div class="row killmail" style="background-color: ${stripe ? "#06100a;" : "#16201a;"} padding: 0px;">
<div style="float: left; width: 32px">
<img src="//imageserver.eveonline.com/${getTypeImage(typeID)}" style="width: 32px; height: 32px">
</div>
<div style="float: left; width: 182px;">
${package.nameMap[typeID]}
</div>
<div style="width: 64px; float: left; text-align: right">
${simpleVal(quantity)}
</div>
<div style="width: 114px; float: left; text-align: right">
${simpleVal(value)}
</div>
</div>`;
$("#types").append(row);
}
function getTypes(package) {
var stripe = true,
pm = package.priceMap,
droppedValue = 0,
totalValue = 0;
if (pm[package.killmail.victim.ship_type_id]) {
totalValue = pm[package.killmail.victim.ship_type_id];
}
addTypeRow(package.killmail.victim.ship_type_id, false, 1, totalValue, !stripe);
$.each(package.killmail.victim.items, function (k, a) {
if (pm[a.item_type_id] != undefined) {
package.killmail.victim.items[k].value = pm[a.item_type_id] *
(a.quantity_destroyed != undefined ? a.quantity_destroyed : a.quantity_dropped);
} else {
package.killmail.victim.items[k].value = 0;
}
});
$.each(package.killmail.victim.items, function (k, a) {
if (a.quantity_destroyed) {
addTypeRow(a.item_type_id, false, a.quantity_destroyed, a.value, stripe);
totalValue += a.value;
} else if (a.quantity_dropped) {
addTypeRow(a.item_type_id, true, a.quantity_dropped, a.value, stripe);
totalValue += a.value;
droppedValue += a.value;
}
stripe = !stripe;
});
$("#totalValue").html(simpleVal(totalValue) + " Total");
$("#droppedValue").html(simpleVal(droppedValue) + " Dropped");
}
function resizeCanvasToDisplaySize(canvas, mult) {
var width = Math.round(256),
height = Math.round(256);
if (window.innerHeight == screen.height) {
width = screen.width;
height = screen.height;
}
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
}
}
function getShipwebGL(package) {
$("#shipImage").attr("src", "//imageserver.eveonline.com/Render/" + package.attributes.typeID + "_256.png")
try {
var mat4 = ccpwgl_int.math.mat4,
rotation = 0.0,
direction = 0.001,
canvas = document.getElementById('shipCanvas'),
gl = canvas.getContext("webgl"),
effect;
ccpwgl.initialize(canvas, {});
ccpwgl_int.store.RegisterPath('local', 'https://www.evedata.org/')
camera = ccpwgl.createCamera(canvas, {}, true);
scene = ccpwgl.loadScene(sceneList[Math.floor(Math.random() * sceneList.length)]);
ship = scene.loadShip(package.dna/*, function () {
ship.addArmorEffects('local:/i/shaders/fxarmorimpactv5.sm_hi',
(eff) => {
effect = eff;
},
(err) => { console.log(err); throw err });
}*/);
scene.loadSun(sunList[Math.floor(Math.random() * sunList.length)]);
ccpwgl.onPreRender = function (dt) {
resizeCanvasToDisplaySize(canvas, window.devicePixelRatio);
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
if (window.innerHeight != screen.height) {
camera.rotationX += 0.01;
camera.rotationY += direction;
if (camera.rotationY > 1.57 & direction > 0) {
direction = -0.001;
} else if (camera.rotationY < -1.57 & direction < 0) {
direction = 0.001;
}
if (ship.isLoaded() == true) {
$("#shipImage").addClass("hidden");
}
camera.focus(ship, 5, 1);
}
}
} catch (err) {
getShipFallback(package.attributes.typeID);
}
}
function fullscreen() {
var canvas = document.getElementById('shipCanvas');
if (canvas.webkitRequestFullScreen) {
canvas.webkitRequestFullScreen();
}
else {
canvas.mozRequestFullScreen();
}
}
function getShipFallback(typeID) {
var canvas = document.getElementById('shipCanvas');
canvas.parentNode.removeChild(canvas);
}
function getShip(package) {
if (!package.attributes) {
return;
}
var a = package.attributes.ship;
getShipwebGL(package);
setResonancePercentage("shieldEm", a.shieldEmDamageResonance)
setResonancePercentage("shieldTherm", a.shieldThermalDamageResonance)
setResonancePercentage("shieldKin", a.shieldKineticDamageResonance)
setResonancePercentage("shieldExp", a.shieldExplosiveDamageResonance)
setResonancePercentage("armorEm", a.armorEmDamageResonance)
setResonancePercentage("armorTherm", a.armorThermalDamageResonance)
setResonancePercentage("armorKin", a.armorKineticDamageResonance)
setResonancePercentage("armorExp", a.armorExplosiveDamageResonance)
setResonancePercentage("hullEm", a.emDamageResonance)
setResonancePercentage("hullTherm", a.thermalDamageResonance)
setResonancePercentage("hullKin", a.kineticDamageResonance)
setResonancePercentage("hullExp", a.explosiveDamageResonance)
$("#ehp").text(simpleVal(a.avgEHP) + " EHP");
$("#hullHP").text(simpleVal(a.hp) + " HP");
$("#armorHP").text(simpleVal(a.armorHP) + " HP");
$("#shieldHP").text(simpleVal(a.shieldCapacity) + " HP");
$("#rps").text(simpleVal(a.avgRPS) + " EHP/s");
$("#warpStrength").text(simpleVal(a.totalWarpScrambleStrength));
$("#webStrength").text(simpleVal(a.stasisWebifierStrength) + "%");
$("#targets").text(simpleVal(a.maxLockedTargets));
$("#scanRes").text(simpleVal(a.scanResolution));
$("#cargo").text(simpleVal(a.capacity) + " m³");
$("#lockRange").text(simpleVal(a.maxTargetRange / 1000) + " km");
$("#warpSpeed").text(simpleVal(a.warpSpeedMultiplier, 1) + " AU/s");
$("#speed").text(simpleVal(a.maxVelocity) + " km/s");
$("#mwdSpeed").text(simpleVal(a.maxVelocityMWD) + " km/s");
$("#sigRadius").text(simpleVal(a.signatureRadius));
$("#mwdSigRadius").text(simpleVal(a.signatureRadiusMWD));
$.each(a, function (k, v) {
switch (k) {
case "hiSlots": // hiSlots
$("#hiSlots").attr('src', '/i/fw/' + v + 'h.png');
break;
case "medSlots": // medSlots
$("#medSlots").attr('src', '/i/fw/' + v + 'm.png');
break;
case "lowSlots": // lowSlots
$("#lowSlots").attr('src', '/i/fw/' + v + 'l.png');
break;
case "rigSlots": // rigSlots
$("#rigSlots").attr('src', '/i/fw/' + v + 'r.png');
break;
case "maxSubsystems": // SubSystems
$("#subSlots").attr('src', '/i/fw/' + v + 's.png');
break;
case "serviceSlots": // structure services
$("#subSlots").attr('src', '/i/fw/' + att + 's.png');
break;
case "capacitorCapacity":
if (a.capacitorStable == 1.0) {
$("#capacitorDuration").text((100 * a.capacitorFraction).toFixed(0) + "% Stable");
} else {
$("#capacitorDuration").text(convertMS(a.capacitorDuration));
}
$("#capacitorDetails").text(simpleVal(v) + " GJ")
break;
case "totalDPS":
$("#totalDamage").html(simpleVal(v) + " DPS")
if (a.moduleDPS) $("#offenseModule").html(simpleVal(a.moduleDPS) + " DPS<br>" + simpleVal(a.moduleAlphaDamage) + " Alpha")
if (a.droneDPS) $("#offenseDrone").html(simpleVal(a.droneDPS) + " DPS<br>" + simpleVal(a.droneAlphaDamage) + " Alpha")
break;
case "scanRadarStrength":
$("#sensorStrength").text(simpleVal(v));
break;
case "scanLadarStrength":
$("#sensorStrength").text(simpleVal(v));
break;
case "scanMagnetometricStrength":
$("#sensorStrength").text(simpleVal(v));
break;
case "scanGravimetricStrength":
$("#sensorStrength").text(simpleVal(v));
break;
case "remoteArmorDamageAmountPerSecond":
$("#remoteArmor").text(simpleVal(v) + " hp/s");
$(".remoteRepair").removeClass('hidden');
break;
case "remoteStructureDamageAmountPerSecond":
$("#remoteHull").text(simpleVal(v) + " hp/s");
$(".remoteRepair").removeClass('hidden');
break;
case "remoteShieldBonusAmountPerSecond":
$("#remoteShield").text(simpleVal(v) + " hp/s");
$(".remoteRepair").removeClass('hidden');
break;
case "remotePowerTransferAmountPerSecond":
$("#remotePower").text(simpleVal(v) + " GJ/s");
$(".remoteRepair").removeClass('hidden');
break;
}
});
}
|
import { h, Component } from 'preact';
import { Link } from 'preact-router/match';
import { shortDateFormatter } from '../../utils/formatting';
import { getVideoUrl, getPlaylistUrl, createReferrerUrl } from '../../utils/routing';
import MediaQuery from '../media-query';
import StreamingList, { StaticList } from '../streaming-list';
import RichText from '../rich-text';
import styles from './style.css';
const getItemUrl = (playlist, video) => createReferrerUrl(getVideoUrl(video), getPlaylistUrl(playlist));
export const PlaylistItem = ({ video, playlist, mobile }) => (
<div class={styles.item} mobile={mobile ? '' : null} component='video'>
<div class={styles.details}>
<Link class={styles.title} part='title' href={getItemUrl(playlist, video)}>{video.snippet.title}</Link>
<div class={styles.published} part='published'>Published on {shortDateFormatter.format(video.snippet.publishedAt)}</div>
<RichText class={styles.description} part='description' text={video.snippet.description} />
</div>
<Link class={styles.thumbnail}
part='thumbnail'
title={video.snippet.title}
href={getItemUrl(playlist, video)}
src={video.snippet.thumbnails ? video.snippet.thumbnails.medium.url : undefined}
style={video.snippet.thumbnails ? `background-image: url(${video.snippet.thumbnails.medium.url})` : undefined}
/>
</div>
);
class Playlist extends Component {
update({ playlist, matches }) {
const itemTemplate = video => <PlaylistItem video={video} playlist={playlist} mobile={matches} />;
const itemHeight = matches ? 300 : 198;
this.setState({ itemTemplate, itemHeight });
}
componentWillMount() {
this.update(this.props);
}
componentWillReceiveProps(nextProps) {
if (nextProps.playlist === this.props.playlist && nextProps.matches === this.props.matches) return;
this.update(nextProps);
}
shouldComponentUpdate({ position }, { itemTemplate, itemHeight }) {
const shouldUpdate =
this.props.position !== position ||
this.state.itemTemplate !== itemTemplate ||
this.state.itemHeight !== itemHeight;
return shouldUpdate;
}
render({ playlist, position, onPositionChange }, { itemTemplate, itemHeight }) {
const isSync = Array.isArray(playlist.items);
const List = isSync ? StaticList : StreamingList;
return (
<div class={styles.playlist} component='playlist'>
<List
part='items'
source={playlist.items}
total={playlist.total}
position={position}
itemTemplate={itemTemplate}
itemHeight={itemHeight}
itemGutter={20}
onPositionChange={onPositionChange}
/>
</div>
);
}
}
export default props => (
<MediaQuery query='(max-device-width: 480px)'>
<Playlist {...props} />
</MediaQuery>
);
|
var getUrls = require('get-urls')
var concat = require('concat-stream')
var Menu = require('terminal-menu')
var ttys = require('ttys')
var opn = require('opn')
module.exports = function () {
function setupMenu (items, width) {
var title = 'BEEP. SELECT URL, HUMAN.\n'
width = Math.max(width, title.length)
var menu = Menu({x: 1, y: 1, width: width})
menu.reset()
menu.write(title)
menu.write('------------------------\n')
for (var i in items) {
menu.add(items[i])
}
menu.on('select', function (url) {
console.dir(url)
menu.close()
opn(url)
})
menu.on('close', function () {
ttys.stdin.setRawMode(false)
ttys.stdin.end()
})
ttys.stdin.setRawMode(true)
ttys.stdin.pipe(menu.createStream()).pipe(process.stdout)
}
(function () {
var items = []
var longestLine = 0
process.stdin.pipe(concat(function (text) {
var urls = getUrls(text.toString())
for (var i in urls) {
var url = urls[i]
items.push(url)
longestLine = Math.max(longestLine, url.length)
}
setupMenu(items, longestLine)
}))
})()
}
|
function VerifyCtrl($http, $rootScope, $location) {
'ngInject';
// ViewModel
const vm = this;
var verificationData = $location.search().key;
vm.verifySent = false;
$http.get($rootScope.apiUrl + 'users/verificate?key=' + verificationData).success((data) => {
vm.verifySent = true;
if (data.result === 0) {
vm.verified = false;
} else {
vm.verified = true;
}
}).error((err, status) => {
vm.verifySent = true;
vm.verified = false;
});
}
export default {
name: 'VerifyCtrl',
fn: VerifyCtrl
};
|
"use strict";
// Generated, unfortunately. Edit original template in browser/templates/serverville_messages.ts.tmpl
var sv;
(function (sv) {
var JsonDataType;
(function (JsonDataType) {
JsonDataType.NULL = "null";
JsonDataType.BOOLEAN = "boolean";
JsonDataType.NUMBER = "number";
JsonDataType.STRING = "string";
JsonDataType.JSON = "json";
JsonDataType.XML = "xml";
JsonDataType.DATETIME = "datetime";
JsonDataType.BYTES = "bytes";
JsonDataType.OBJECT = "object";
})(JsonDataType = sv.JsonDataType || (sv.JsonDataType = {}));
})(sv || (sv = {}));
var sv;
(function (sv) {
function makeClientError(code, details) {
if (details === void 0) { details = null; }
var msg = "Unknown network error";
switch (code) {
case -1:
msg = "Connection closed";
break;
case -2:
msg = "Network error";
break;
}
return { errorCode: code, errorMessage: msg, errorDetails: details };
}
sv.makeClientError = makeClientError;
})(sv || (sv = {}));
/// <reference path="serverville_types.ts" />
var sv;
(function (sv_1) {
var HttpTransport = (function () {
function HttpTransport(sv) {
this.SV = sv;
}
HttpTransport.prototype.init = function (onConnected) {
this.callApi("GetTime", {}, function (reply) {
if (onConnected != null)
onConnected(null);
}, onConnected);
};
HttpTransport.prototype.callApi = function (api, request, onSuccess, onError) {
this.doPost(this.SV.ServerURL + "/api/" + api, request, onSuccess, onError);
};
HttpTransport.prototype.doPost = function (url, request, onSuccess, onError) {
var req = new XMLHttpRequest();
req.open("POST", url);
if (this.SV.SessionId)
req.setRequestHeader("Authorization", this.SV.SessionId);
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
var body = JSON.stringify(request);
if (this.SV.LogMessagesToConsole)
console.log("HTTP<- " + body);
var self = this;
req.onload = function (ev) {
if (self.SV.LogMessagesToConsole)
console.log("HTTP-> " + req.response);
if (req.status >= 200 && req.status < 400) {
var message = JSON.parse(req.response);
if (onSuccess) {
onSuccess(message);
}
}
else {
var error = JSON.parse(req.response);
if (onError)
onError(error);
else
self.SV._onServerError(error);
}
if (req.getResponseHeader("X-Notifications")) {
// Pending notifications from the server!
self.getNotifications();
}
};
req.onerror = function (ev) {
var err = sv_1.makeClientError(-2);
if (onError)
onError(err);
else
self.SV._onServerError(err);
};
req.send(body);
};
HttpTransport.prototype.close = function () {
};
HttpTransport.prototype.getNotifications = function () {
var url = this.SV.ServerURL + "/notifications";
var self = this;
var onSuccess = function (reply) {
if (!reply.notifications)
return;
for (var i = 0; i < reply.notifications.length; i++) {
var note = reply.notifications[i];
self.SV._onServerNotification(note.notification_type, note.body);
}
};
var onError = function (err) {
console.log("Error retreiving notifications: " + err.errorMessage);
};
this.doPost(url, {}, onSuccess, onError);
};
HttpTransport.unauthedRequest = function (url, request, onSuccess, onError) {
var req = new XMLHttpRequest();
req.open("POST", url);
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
var body = JSON.stringify(request);
req.onload = function (ev) {
if (req.status >= 200 && req.status < 400) {
var message = JSON.parse(req.response);
if (onSuccess) {
onSuccess(message);
}
}
else {
var error = JSON.parse(req.response);
if (onError)
onError(error);
}
};
req.onerror = function (ev) {
var err = sv_1.makeClientError(-2);
if (onError)
onError(err);
};
req.send(body);
};
return HttpTransport;
}());
sv_1.HttpTransport = HttpTransport;
})(sv || (sv = {}));
/// <reference path="serverville_types.ts" />
var sv;
(function (sv_2) {
var WebSocketTransport = (function () {
function WebSocketTransport(sv) {
this.MessageSequence = 0;
this.ReplyCallbacks = {};
this.SV = sv;
}
WebSocketTransport.prototype.init = function (onConnected) {
var url = this.SV.ServerURL + "/websocket";
this.ServerSocket = new WebSocket(url);
this.Connected = false;
var self = this;
this.ServerSocket.onopen = function (evt) {
self.Connected = true;
onConnected(null);
};
this.ServerSocket.onclose = function (evt) {
self.onWSClosed(evt);
self.Connected = false;
};
this.ServerSocket.onmessage = function (evt) {
self.onWSMessage(evt);
};
this.ServerSocket.onerror = function (evt) {
if (onConnected != null) {
onConnected(sv_2.makeClientError(-2, evt.message));
}
};
};
WebSocketTransport.prototype.callApi = function (api, request, onSuccess, onError) {
var self = this;
if (this.Connected) {
sendMessage();
}
else {
this.init(function (err) {
if (err) {
if (onError)
onError(err);
}
else {
sendMessage();
}
});
}
function sendMessage() {
var messageNum = (self.MessageSequence++).toString();
var message = api + ":" + messageNum + ":" + JSON.stringify(request);
if (self.SV.LogMessagesToConsole)
console.log("WS<- " + message);
var callback = function (isError, reply) {
if (isError) {
if (onError)
onError(reply);
else
self.SV._onServerError(reply);
}
else {
if (onSuccess)
onSuccess(reply);
}
};
self.ReplyCallbacks[messageNum] = callback;
self.ServerSocket.send(message);
}
};
WebSocketTransport.prototype.close = function () {
this.Connected = false;
if (this.ServerSocket) {
this.ServerSocket.close();
this.ServerSocket = null;
}
};
WebSocketTransport.prototype.onWSClosed = function (evt) {
if (this.Connected == false) {
// Ignore close when we never actually got open first
return;
}
console.log("Web socket closed");
this.Connected = false;
this.SV._onTransportClosed();
};
WebSocketTransport.prototype.onWSMessage = function (evt) {
var messageStr = evt.data;
if (this.SV.LogMessagesToConsole)
console.log("WS-> " + messageStr);
var split1 = messageStr.indexOf(":");
if (split1 < 1) {
console.log("Incorrectly formatted message");
return;
}
var messageType = messageStr.substring(0, split1);
if (messageType == "N") {
// Server push message
var split2_1 = messageStr.indexOf(":", split1 + 1);
if (split2_1 < 0) {
console.log("Incorrectly formatted message");
return;
}
var notificationType = messageStr.substring(split1 + 1, split2_1);
var notificationJson = messageStr.substring(split2_1 + 1);
this.SV._onServerNotification(notificationType, notificationJson);
}
else if (messageType == "E" || messageType == "R") {
// Reply
var split2 = messageStr.indexOf(":", split1 + 1);
if (split2 < 0) {
console.log("Incorrectly formatted message");
return;
}
var messageNum = messageStr.substring(split1 + 1, split2);
var messageJson = messageStr.substring(split2 + 1);
var messageData = JSON.parse(messageJson);
var isError = false;
if (messageType == "E")
isError = true;
var callback = this.ReplyCallbacks[messageNum];
delete this.ReplyCallbacks[messageNum];
callback(isError, messageData);
}
else {
console.log("Unknown server message: " + messageStr);
}
};
return WebSocketTransport;
}());
sv_2.WebSocketTransport = WebSocketTransport;
})(sv || (sv = {}));
/// <reference path="serverville_messages.ts" />
/// <reference path="serverville_http.ts" />
/// <reference path="serverville_ws.ts" />
// Generated, unfortunately. Edit original template in browser/templates/serverville.ts.tmpl
var sv;
(function (sv) {
var Serverville = (function () {
function Serverville(url) {
this.LogMessagesToConsole = false;
this.PingPeriod = 60000;
this.UserMessageTypeHandlers = {};
this.LastSend = 0;
this.PingTimer = 0;
this.LastServerTime = 0;
this.LastServerTimeAt = 0;
this.SessionId = localStorage.getItem("SessionId");
this.initServerUrl(url);
}
Serverville.prototype.initServerUrl = function (url) {
this.ServerURL = url;
var protocolLen = this.ServerURL.indexOf("://");
if (protocolLen < 2)
throw "Malformed url: " + url;
this.ServerHost = this.ServerURL.substring(protocolLen + 3);
this.ServerProtocol = this.ServerURL.substring(0, protocolLen);
if (this.ServerProtocol == "ws" || this.ServerProtocol == "wss") {
this.Transport = new sv.WebSocketTransport(this);
}
else if (this.ServerProtocol == "http" || this.ServerProtocol == "https") {
this.Transport = new sv.HttpTransport(this);
}
else {
throw "Unknown server protocol: " + url;
}
};
Serverville.prototype.init = function (onComplete) {
var self = this;
function onTransportInitted(err) {
if (err != null) {
if (self.SessionId && err.errorCode == 2) {
self.signOut();
// Try again
self.Transport.init(onTransportInitted);
return;
}
onComplete(null, err);
return;
}
if (self.SessionId) {
self.validateSession(self.SessionId, function (reply) {
onComplete(reply, null);
self.startPingHeartbeat();
}, function (err) {
if (self.SessionId && err.errorCode == 2) {
self.signOut();
// Try again
self.Transport.init(onTransportInitted);
return;
}
onComplete(null, err);
});
}
else {
onComplete(null, null);
}
}
;
this.Transport.init(onTransportInitted);
};
Serverville.prototype.initWithResidentId = function (resId, onComplete) {
if (!resId) {
this.init(onComplete);
return;
}
var serverUrl = this.ServerURL;
if (this.ServerProtocol == "ws")
serverUrl = "http://" + this.ServerHost;
else if (this.ServerProtocol == "wss")
serverUrl = "https://" + this.ServerHost;
serverUrl += "/api/GetHostWithResident";
var req = {
resident_id: resId
};
var self = this;
sv.HttpTransport.unauthedRequest(serverUrl, req, function (reply) {
var url = self.fixupServerURL(reply.host);
self.initServerUrl(url);
self.init(onComplete);
}, function (err) {
onComplete(null, err);
});
};
Serverville.prototype.fixupServerURL = function (host) {
var url = host;
if (host.indexOf("://") < 0) {
url = this.ServerProtocol + "://" + host;
}
return url;
};
Serverville.prototype.switchHosts = function (host, onComplete) {
var url = this.fixupServerURL(host);
if (this.ServerURL == url) {
onComplete(null);
return;
}
this.shutdown();
this.initServerUrl(url);
this.init(function (user, err) {
onComplete(err);
});
};
Serverville.prototype.startPingHeartbeat = function () {
if (this.PingPeriod == 0 || this.PingTimer != 0)
return;
var self = this;
this.PingTimer = window.setInterval(function () {
self.ping();
}, this.PingPeriod);
};
Serverville.prototype.stopPingHeartbeat = function () {
if (this.PingTimer != 0) {
window.clearInterval(this.PingTimer);
}
this.PingTimer = 0;
};
Serverville.prototype.setUserInfo = function (userInfo) {
if (userInfo == null) {
this.UserInfo = null;
this.SessionId = null;
localStorage.removeItem("SessionId");
}
else {
this.UserInfo = userInfo;
this.SessionId = userInfo.session_id;
localStorage.setItem("SessionId", this.SessionId);
this.setServerTime(userInfo.time);
}
};
Serverville.prototype.setUserSession = function (sessionId) {
this.SessionId = sessionId;
localStorage.setItem("SessionId", this.SessionId);
};
Serverville.prototype.userInfo = function () {
return this.UserInfo;
};
Serverville.prototype._onServerError = function (err) {
if (err.errorCode < 0) {
// Network error
this.shutdown();
}
if (err.errorCode == 2) {
this.setUserInfo(null);
this.shutdown();
}
else if (err.errorCode == 19) {
this.shutdown();
}
if (this.GlobalErrorHandler != null)
this.GlobalErrorHandler(err);
};
Serverville.prototype._onServerNotification = function (notificationType, notificationJson) {
var notification = JSON.parse(notificationJson);
switch (notificationType) {
case "error":
// Pushed error
this._onServerError(notification);
return;
case "msg":
// User message
this._onUserMessage(notification);
return;
case "resJoined":
if (this.ResidentJoinedHandler)
this.ResidentJoinedHandler(notification);
return;
case "resLeft":
if (this.ResidentLeftHandler)
this.ResidentLeftHandler(notification);
return;
case "resEvent":
if (this.ResidentEventHandler)
this.ResidentEventHandler(notification);
return;
case "resUpdate":
if (this.ResidentStateUpdateHandler)
this.ResidentStateUpdateHandler(notification);
return;
default:
console.log("Unknown type of server notification: " + notificationType);
return;
}
};
Serverville.prototype._onUserMessage = function (message) {
var typeHandler = this.UserMessageTypeHandlers[message.message_type];
if (typeHandler != null) {
typeHandler(message);
}
else if (this.UserMessageHandler != null) {
this.UserMessageHandler(message);
}
else {
console.log("No handler for message " + message.message_type);
}
};
Serverville.prototype._onTransportClosed = function () {
this.stopPingHeartbeat();
this._onServerError(sv.makeClientError(-1));
};
Serverville.prototype.ping = function () {
if (performance.now() - this.LastSend < 4000)
return;
var self = this;
this.getTime(function (reply) {
self.setServerTime(reply.time);
}, function (err) {
if (err.errorCode <= 0) {
// Network error, stop pinging until we make another real request
self.shutdown();
}
});
};
Serverville.prototype.setServerTime = function (time) {
this.LastServerTime = time;
this.LastServerTimeAt = performance.now();
};
Serverville.prototype.getServerTime = function () {
if (this.LastServerTime == 0)
return 0;
return (performance.now() - this.LastServerTimeAt) + this.LastServerTime;
};
Serverville.prototype.getLastSendTime = function () {
return this.LastSend;
};
Serverville.prototype.loadUserKeyData = function (onDone) {
if (!this.UserInfo)
throw "No user loaded";
var data = new sv.KeyData(this, this.UserInfo.user_id);
data.loadAll(onDone);
return data;
};
Serverville.prototype.loadKeyData = function (id, onDone) {
var data = new sv.KeyData(this, id);
data.loadAll(onDone);
return data;
};
Serverville.prototype.isSignedIn = function () {
return this.SessionId != null;
};
Serverville.prototype.signOut = function () {
this.setUserInfo(null);
};
Serverville.prototype.shutdown = function () {
this.stopPingHeartbeat();
if (this.Transport) {
this.Transport.close();
}
};
Serverville.prototype.apiByName = function (api, request, onSuccess, onError) {
var self = this;
this.Transport.callApi(api, request, function (reply) {
self.startPingHeartbeat();
if (onSuccess)
onSuccess(reply);
}, onError);
this.LastSend = performance.now();
};
// Start generated code -----------------------------------------------------------------------------------
Serverville.prototype.signInReq = function (request, onSuccess, onError) {
var self = this;
this.apiByName("SignIn", request, function (reply) { self.setUserInfo(reply); if (onSuccess) {
onSuccess(reply);
} }, onError);
};
Serverville.prototype.signIn = function (username, email, password, onSuccess, onError) {
this.signInReq({
"username": username,
"email": email,
"password": password
}, onSuccess, onError);
};
Serverville.prototype.validateSessionReq = function (request, onSuccess, onError) {
var self = this;
this.apiByName("ValidateSession", request, function (reply) { self.setUserInfo(reply); if (onSuccess) {
onSuccess(reply);
} }, onError);
};
Serverville.prototype.validateSession = function (session_id, onSuccess, onError) {
this.validateSessionReq({
"session_id": session_id
}, onSuccess, onError);
};
Serverville.prototype.createAnonymousAccountReq = function (request, onSuccess, onError) {
var self = this;
this.apiByName("CreateAnonymousAccount", request, function (reply) { self.setUserInfo(reply); if (onSuccess) {
onSuccess(reply);
} }, onError);
};
Serverville.prototype.createAnonymousAccount = function (invite_code, language, country, onSuccess, onError) {
this.createAnonymousAccountReq({
"invite_code": invite_code,
"language": language,
"country": country
}, onSuccess, onError);
};
Serverville.prototype.createAccountReq = function (request, onSuccess, onError) {
var self = this;
this.apiByName("CreateAccount", request, function (reply) { self.setUserInfo(reply); if (onSuccess) {
onSuccess(reply);
} }, onError);
};
Serverville.prototype.createAccount = function (username, email, password, invite_code, language, country, onSuccess, onError) {
this.createAccountReq({
"username": username,
"email": email,
"password": password,
"invite_code": invite_code,
"language": language,
"country": country
}, onSuccess, onError);
};
Serverville.prototype.convertToFullAccountReq = function (request, onSuccess, onError) {
var self = this;
this.apiByName("ConvertToFullAccount", request, function (reply) { self.setUserInfo(reply); if (onSuccess) {
onSuccess(reply);
} }, onError);
};
Serverville.prototype.convertToFullAccount = function (username, email, password, invite_code, language, country, onSuccess, onError) {
this.convertToFullAccountReq({
"username": username,
"email": email,
"password": password,
"invite_code": invite_code,
"language": language,
"country": country
}, onSuccess, onError);
};
Serverville.prototype.changePasswordReq = function (request, onSuccess, onError) {
var self = this;
this.apiByName("ChangePassword", request, function (reply) { self.setUserSession(reply.session_id); if (onSuccess) {
onSuccess(reply);
} }, onError);
};
Serverville.prototype.changePassword = function (old_password, new_password, onSuccess, onError) {
this.changePasswordReq({
"old_password": old_password,
"new_password": new_password
}, onSuccess, onError);
};
Serverville.prototype.getTimeReq = function (request, onSuccess, onError) {
this.apiByName("GetTime", request, onSuccess, onError);
};
Serverville.prototype.getTime = function (onSuccess, onError) {
this.getTimeReq({}, onSuccess, onError);
};
Serverville.prototype.getUserInfoReq = function (request, onSuccess, onError) {
this.apiByName("GetUserInfo", request, onSuccess, onError);
};
Serverville.prototype.getUserInfo = function (onSuccess, onError) {
this.getUserInfoReq({}, onSuccess, onError);
};
Serverville.prototype.setLocaleReq = function (request, onSuccess, onError) {
this.apiByName("SetLocale", request, onSuccess, onError);
};
Serverville.prototype.setLocale = function (country, language, onSuccess, onError) {
this.setLocaleReq({
"country": country,
"language": language
}, onSuccess, onError);
};
Serverville.prototype.getUserDataComboReq = function (request, onSuccess, onError) {
this.apiByName("GetUserDataCombo", request, onSuccess, onError);
};
Serverville.prototype.getUserDataCombo = function (since, onSuccess, onError) {
this.getUserDataComboReq({
"since": since
}, onSuccess, onError);
};
Serverville.prototype.setUserKeyReq = function (request, onSuccess, onError) {
this.apiByName("SetUserKey", request, onSuccess, onError);
};
Serverville.prototype.setUserKey = function (key, value, data_type, onSuccess, onError) {
this.setUserKeyReq({
"key": key,
"value": value,
"data_type": data_type
}, onSuccess, onError);
};
Serverville.prototype.setUserKeysReq = function (request, onSuccess, onError) {
this.apiByName("SetUserKeys", request, onSuccess, onError);
};
Serverville.prototype.setUserKeys = function (values, onSuccess, onError) {
this.setUserKeysReq({
"values": values
}, onSuccess, onError);
};
Serverville.prototype.setAndDeleteUserKeysReq = function (request, onSuccess, onError) {
this.apiByName("SetAndDeleteUserKeys", request, onSuccess, onError);
};
Serverville.prototype.setAndDeleteUserKeys = function (values, delete_keys, onSuccess, onError) {
this.setAndDeleteUserKeysReq({
"values": values,
"delete_keys": delete_keys
}, onSuccess, onError);
};
Serverville.prototype.getUserKeyReq = function (request, onSuccess, onError) {
this.apiByName("GetUserKey", request, onSuccess, onError);
};
Serverville.prototype.getUserKey = function (key, onSuccess, onError) {
this.getUserKeyReq({
"key": key
}, onSuccess, onError);
};
Serverville.prototype.getUserKeysReq = function (request, onSuccess, onError) {
this.apiByName("GetUserKeys", request, onSuccess, onError);
};
Serverville.prototype.getUserKeys = function (keys, since, onSuccess, onError) {
this.getUserKeysReq({
"keys": keys,
"since": since
}, onSuccess, onError);
};
Serverville.prototype.getAllUserKeysReq = function (request, onSuccess, onError) {
this.apiByName("GetAllUserKeys", request, onSuccess, onError);
};
Serverville.prototype.getAllUserKeys = function (since, onSuccess, onError) {
this.getAllUserKeysReq({
"since": since
}, onSuccess, onError);
};
Serverville.prototype.deleteUserKeyReq = function (request, onSuccess, onError) {
this.apiByName("DeleteUserKey", request, onSuccess, onError);
};
Serverville.prototype.deleteUserKey = function (key, onSuccess, onError) {
this.deleteUserKeyReq({
"key": key
}, onSuccess, onError);
};
Serverville.prototype.deleteUserKeysReq = function (request, onSuccess, onError) {
this.apiByName("DeleteUserKeys", request, onSuccess, onError);
};
Serverville.prototype.deleteUserKeys = function (keys, onSuccess, onError) {
this.deleteUserKeysReq({
"keys": keys
}, onSuccess, onError);
};
Serverville.prototype.getDataKeyReq = function (request, onSuccess, onError) {
this.apiByName("GetDataKey", request, onSuccess, onError);
};
Serverville.prototype.getDataKey = function (id, key, onSuccess, onError) {
this.getDataKeyReq({
"id": id,
"key": key
}, onSuccess, onError);
};
Serverville.prototype.getDataKeysReq = function (request, onSuccess, onError) {
this.apiByName("GetDataKeys", request, onSuccess, onError);
};
Serverville.prototype.getDataKeys = function (id, keys, since, include_deleted, onSuccess, onError) {
this.getDataKeysReq({
"id": id,
"keys": keys,
"since": since,
"include_deleted": include_deleted
}, onSuccess, onError);
};
Serverville.prototype.getDataKeysStartingWithReq = function (request, onSuccess, onError) {
this.apiByName("GetDataKeysStartingWith", request, onSuccess, onError);
};
Serverville.prototype.getDataKeysStartingWith = function (id, prefix, since, include_deleted, onSuccess, onError) {
this.getDataKeysStartingWithReq({
"id": id,
"prefix": prefix,
"since": since,
"include_deleted": include_deleted
}, onSuccess, onError);
};
Serverville.prototype.getAllDataKeysReq = function (request, onSuccess, onError) {
this.apiByName("GetAllDataKeys", request, onSuccess, onError);
};
Serverville.prototype.getAllDataKeys = function (id, since, include_deleted, onSuccess, onError) {
this.getAllDataKeysReq({
"id": id,
"since": since,
"include_deleted": include_deleted
}, onSuccess, onError);
};
Serverville.prototype.pageAllDataKeysReq = function (request, onSuccess, onError) {
this.apiByName("PageAllDataKeys", request, onSuccess, onError);
};
Serverville.prototype.pageAllDataKeys = function (id, page_size, start_after, descending, onSuccess, onError) {
this.pageAllDataKeysReq({
"id": id,
"page_size": page_size,
"start_after": start_after,
"descending": descending
}, onSuccess, onError);
};
Serverville.prototype.getKeyDataRecordReq = function (request, onSuccess, onError) {
this.apiByName("GetKeyDataRecord", request, onSuccess, onError);
};
Serverville.prototype.getKeyDataRecord = function (id, onSuccess, onError) {
this.getKeyDataRecordReq({
"id": id
}, onSuccess, onError);
};
Serverville.prototype.getKeyDataRecordsReq = function (request, onSuccess, onError) {
this.apiByName("GetKeyDataRecords", request, onSuccess, onError);
};
Serverville.prototype.getKeyDataRecords = function (record_type, parent, onSuccess, onError) {
this.getKeyDataRecordsReq({
"record_type": record_type,
"parent": parent
}, onSuccess, onError);
};
Serverville.prototype.setDataKeysReq = function (request, onSuccess, onError) {
this.apiByName("SetDataKeys", request, onSuccess, onError);
};
Serverville.prototype.setDataKeys = function (id, values, onSuccess, onError) {
this.setDataKeysReq({
"id": id,
"values": values
}, onSuccess, onError);
};
Serverville.prototype.getHostWithResidentReq = function (request, onSuccess, onError) {
this.apiByName("GetHostWithResident", request, onSuccess, onError);
};
Serverville.prototype.getHostWithResident = function (resident_id, onSuccess, onError) {
this.getHostWithResidentReq({
"resident_id": resident_id
}, onSuccess, onError);
};
Serverville.prototype.createResidentReq = function (request, onSuccess, onError) {
this.apiByName("CreateResident", request, onSuccess, onError);
};
Serverville.prototype.createResident = function (resident_type, values, onSuccess, onError) {
this.createResidentReq({
"resident_type": resident_type,
"values": values
}, onSuccess, onError);
};
Serverville.prototype.deleteResidentReq = function (request, onSuccess, onError) {
this.apiByName("DeleteResident", request, onSuccess, onError);
};
Serverville.prototype.deleteResident = function (resident_id, final_values, onSuccess, onError) {
this.deleteResidentReq({
"resident_id": resident_id,
"final_values": final_values
}, onSuccess, onError);
};
Serverville.prototype.removeResidentFromAllChannelsReq = function (request, onSuccess, onError) {
this.apiByName("RemoveResidentFromAllChannels", request, onSuccess, onError);
};
Serverville.prototype.removeResidentFromAllChannels = function (resident_id, final_values, onSuccess, onError) {
this.removeResidentFromAllChannelsReq({
"resident_id": resident_id,
"final_values": final_values
}, onSuccess, onError);
};
Serverville.prototype.setTransientValueReq = function (request, onSuccess, onError) {
this.apiByName("SetTransientValue", request, onSuccess, onError);
};
Serverville.prototype.setTransientValue = function (resident_id, key, value, onSuccess, onError) {
this.setTransientValueReq({
"resident_id": resident_id,
"key": key,
"value": value
}, onSuccess, onError);
};
Serverville.prototype.setTransientValuesReq = function (request, onSuccess, onError) {
this.apiByName("SetTransientValues", request, onSuccess, onError);
};
Serverville.prototype.setTransientValues = function (resident_id, values, onSuccess, onError) {
this.setTransientValuesReq({
"resident_id": resident_id,
"values": values
}, onSuccess, onError);
};
Serverville.prototype.deleteTransientValueReq = function (request, onSuccess, onError) {
this.apiByName("DeleteTransientValue", request, onSuccess, onError);
};
Serverville.prototype.deleteTransientValue = function (resident_id, key, onSuccess, onError) {
this.deleteTransientValueReq({
"resident_id": resident_id,
"key": key
}, onSuccess, onError);
};
Serverville.prototype.deleteTransientValuesReq = function (request, onSuccess, onError) {
this.apiByName("DeleteTransientValues", request, onSuccess, onError);
};
Serverville.prototype.deleteTransientValues = function (resident_id, values, onSuccess, onError) {
this.deleteTransientValuesReq({
"resident_id": resident_id,
"values": values
}, onSuccess, onError);
};
Serverville.prototype.getTransientValueReq = function (request, onSuccess, onError) {
this.apiByName("GetTransientValue", request, onSuccess, onError);
};
Serverville.prototype.getTransientValue = function (resident_id, key, onSuccess, onError) {
this.getTransientValueReq({
"resident_id": resident_id,
"key": key
}, onSuccess, onError);
};
Serverville.prototype.getTransientValuesReq = function (request, onSuccess, onError) {
this.apiByName("GetTransientValues", request, onSuccess, onError);
};
Serverville.prototype.getTransientValues = function (resident_id, keys, onSuccess, onError) {
this.getTransientValuesReq({
"resident_id": resident_id,
"keys": keys
}, onSuccess, onError);
};
Serverville.prototype.getAllTransientValuesReq = function (request, onSuccess, onError) {
this.apiByName("GetAllTransientValues", request, onSuccess, onError);
};
Serverville.prototype.getAllTransientValues = function (resident_id, onSuccess, onError) {
this.getAllTransientValuesReq({
"resident_id": resident_id
}, onSuccess, onError);
};
Serverville.prototype.joinChannelReq = function (request, onSuccess, onError) {
this.apiByName("JoinChannel", request, onSuccess, onError);
};
Serverville.prototype.joinChannel = function (channel_id, resident_id, values, onSuccess, onError) {
this.joinChannelReq({
"channel_id": channel_id,
"resident_id": resident_id,
"values": values
}, onSuccess, onError);
};
Serverville.prototype.leaveChannelReq = function (request, onSuccess, onError) {
this.apiByName("LeaveChannel", request, onSuccess, onError);
};
Serverville.prototype.leaveChannel = function (channel_id, resident_id, final_values, onSuccess, onError) {
this.leaveChannelReq({
"channel_id": channel_id,
"resident_id": resident_id,
"final_values": final_values
}, onSuccess, onError);
};
Serverville.prototype.addResidentToChannelReq = function (request, onSuccess, onError) {
this.apiByName("AddResidentToChannel", request, onSuccess, onError);
};
Serverville.prototype.addResidentToChannel = function (channel_id, resident_id, values, onSuccess, onError) {
this.addResidentToChannelReq({
"channel_id": channel_id,
"resident_id": resident_id,
"values": values
}, onSuccess, onError);
};
Serverville.prototype.removeResidentFromChannelReq = function (request, onSuccess, onError) {
this.apiByName("RemoveResidentFromChannel", request, onSuccess, onError);
};
Serverville.prototype.removeResidentFromChannel = function (channel_id, resident_id, final_values, onSuccess, onError) {
this.removeResidentFromChannelReq({
"channel_id": channel_id,
"resident_id": resident_id,
"final_values": final_values
}, onSuccess, onError);
};
Serverville.prototype.listenToChannelReq = function (request, onSuccess, onError) {
this.apiByName("ListenToChannel", request, onSuccess, onError);
};
Serverville.prototype.listenToChannel = function (channel_id, onSuccess, onError) {
this.listenToChannelReq({
"channel_id": channel_id
}, onSuccess, onError);
};
Serverville.prototype.stopListenToChannelReq = function (request, onSuccess, onError) {
this.apiByName("StopListenToChannel", request, onSuccess, onError);
};
Serverville.prototype.stopListenToChannel = function (channel_id, onSuccess, onError) {
this.stopListenToChannelReq({
"channel_id": channel_id
}, onSuccess, onError);
};
Serverville.prototype.updateWorldListeningZonesReq = function (request, onSuccess, onError) {
this.apiByName("UpdateWorldListeningZones", request, onSuccess, onError);
};
Serverville.prototype.updateWorldListeningZones = function (world_id, listen_to, stop_listen_to, onSuccess, onError) {
this.updateWorldListeningZonesReq({
"world_id": world_id,
"listen_to": listen_to,
"stop_listen_to": stop_listen_to
}, onSuccess, onError);
};
Serverville.prototype.triggerResidentEventReq = function (request, onSuccess, onError) {
this.apiByName("TriggerResidentEvent", request, onSuccess, onError);
};
Serverville.prototype.triggerResidentEvent = function (resident_id, event_type, event_data, onSuccess, onError) {
this.triggerResidentEventReq({
"resident_id": resident_id,
"event_type": event_type,
"event_data": event_data
}, onSuccess, onError);
};
Serverville.prototype.sendUserMessageReq = function (request, onSuccess, onError) {
this.apiByName("SendUserMessage", request, onSuccess, onError);
};
Serverville.prototype.sendUserMessage = function (to, message_type, message, guaranteed, onSuccess, onError) {
this.sendUserMessageReq({
"to": to,
"message_type": message_type,
"message": message,
"guaranteed": guaranteed
}, onSuccess, onError);
};
Serverville.prototype.getPendingMessagesReq = function (request, onSuccess, onError) {
this.apiByName("GetPendingMessages", request, onSuccess, onError);
};
Serverville.prototype.getPendingMessages = function (onSuccess, onError) {
this.getPendingMessagesReq({}, onSuccess, onError);
};
Serverville.prototype.clearPendingMessageReq = function (request, onSuccess, onError) {
this.apiByName("ClearPendingMessage", request, onSuccess, onError);
};
Serverville.prototype.clearPendingMessage = function (id, onSuccess, onError) {
this.clearPendingMessageReq({
"id": id
}, onSuccess, onError);
};
Serverville.prototype.getCurrencyBalanceReq = function (request, onSuccess, onError) {
this.apiByName("GetCurrencyBalance", request, onSuccess, onError);
};
Serverville.prototype.getCurrencyBalance = function (currency_id, onSuccess, onError) {
this.getCurrencyBalanceReq({
"currency_id": currency_id
}, onSuccess, onError);
};
Serverville.prototype.getCurrencyBalancesReq = function (request, onSuccess, onError) {
this.apiByName("GetCurrencyBalances", request, onSuccess, onError);
};
Serverville.prototype.getCurrencyBalances = function (onSuccess, onError) {
this.getCurrencyBalancesReq({}, onSuccess, onError);
};
Serverville.prototype.getProductsReq = function (request, onSuccess, onError) {
this.apiByName("GetProducts", request, onSuccess, onError);
};
Serverville.prototype.getProducts = function (onSuccess, onError) {
this.getProductsReq({}, onSuccess, onError);
};
Serverville.prototype.getProductReq = function (request, onSuccess, onError) {
this.apiByName("GetProduct", request, onSuccess, onError);
};
Serverville.prototype.getProduct = function (product_id, onSuccess, onError) {
this.getProductReq({
"product_id": product_id
}, onSuccess, onError);
};
Serverville.prototype.stripeCheckoutReq = function (request, onSuccess, onError) {
this.apiByName("StripeCheckout", request, onSuccess, onError);
};
Serverville.prototype.stripeCheckout = function (stripe_token, product_id, onSuccess, onError) {
this.stripeCheckoutReq({
"stripe_token": stripe_token,
"product_id": product_id
}, onSuccess, onError);
};
Serverville.prototype.batchRequestReq = function (request, onSuccess, onError) {
this.apiByName("batchRequest", request, onSuccess, onError);
};
Serverville.prototype.batchRequest = function (requests, onSuccess, onError) {
this.batchRequestReq({
"requests": requests
}, onSuccess, onError);
};
Serverville.prototype.getBraintreeClientTokenReq = function (request, onSuccess, onError) {
this.apiByName("getBraintreeClientToken", request, onSuccess, onError);
};
Serverville.prototype.getBraintreeClientToken = function (api_version, onSuccess, onError) {
this.getBraintreeClientTokenReq({
"api_version": api_version
}, onSuccess, onError);
};
Serverville.prototype.braintreePurchaseReq = function (request, onSuccess, onError) {
this.apiByName("BraintreePurchase", request, onSuccess, onError);
};
Serverville.prototype.braintreePurchase = function (nonce, product_id, onSuccess, onError) {
this.braintreePurchaseReq({
"nonce": nonce,
"product_id": product_id
}, onSuccess, onError);
};
return Serverville;
}());
sv.Serverville = Serverville;
})(sv || (sv = {}));
var sv;
(function (sv) {
var KeyData = (function () {
function KeyData(server, id) {
if (server == null)
throw "Must supply a serverville server";
if (id == null)
throw "Data must have an id";
this.id = id;
this.server = server;
this.data = {};
this.data_info = {};
this.local_dirty = {};
this.local_deletes = {};
this.most_recent = 0;
}
KeyData.prototype.mostRecentModifiedTime = function () { return this.most_recent; };
KeyData.prototype.loadKeys = function (keys, onDone) {
var self = this;
this.server.getDataKeys(this.id, keys, 0, false, function (reply) {
for (var key in reply.values) {
var dataInfo = reply.values[key];
self.data_info[dataInfo.key] = dataInfo;
self.data[key] = dataInfo.value;
}
if (onDone)
onDone();
}, function (reply) {
if (onDone)
onDone();
});
};
KeyData.prototype.loadAll = function (onDone) {
this.data = {};
this.local_dirty = {};
this.local_deletes = {};
var self = this;
this.server.getAllDataKeys(this.id, 0, false, function (reply) {
self.data_info = reply.values;
for (var key in self.data_info) {
var dataInfo = self.data_info[key];
self.data[key] = dataInfo.value;
if (dataInfo.modified > self.most_recent)
self.most_recent = dataInfo.modified;
}
if (onDone)
onDone();
}, function (reply) {
if (onDone)
onDone();
});
};
KeyData.prototype.refresh = function (onDone) {
var self = this;
this.server.getAllDataKeys(this.id, this.most_recent, true, function (reply) {
for (var key in reply.values) {
var dataInfo = reply.values[key];
if (dataInfo.deleted) {
delete self.data[key];
delete self.data_info[key];
}
else {
self.data[key] = dataInfo.value;
self.data_info[key] = dataInfo;
}
if (dataInfo.modified > self.most_recent)
self.most_recent = dataInfo.modified;
}
if (onDone)
onDone();
}, function (reply) {
if (onDone)
onDone();
});
};
KeyData.prototype.set = function (key, val, data_type) {
if (data_type === void 0) { data_type = null; }
var user = this.server.userInfo();
if (user == null || user.user_id != this.id)
throw "Read-only data!";
this.data[key] = val;
var info = this.data_info[key];
if (info) {
info.value = val;
if (data_type)
info.data_type = data_type;
}
else {
info = {
"id": this.id,
"key": key,
"value": val,
"data_type": data_type,
"created": 0,
"modified": 0,
"deleted": false
};
this.data_info[key] = info;
}
this.local_dirty[key] = true;
delete this.local_deletes[key];
};
KeyData.prototype.delete = function (key) {
var user = this.server.userInfo();
if (user == null || user.user_id != this.id)
throw "Read-only data!";
var info = this.data_info[key];
if (!info)
return;
delete this.data[key];
delete this.data_info[key];
this.local_deletes[key] = true;
};
KeyData.prototype.save = function (onDone) {
var user = this.server.userInfo();
if (user == null || user.user_id != this.id)
throw "Read-only data!";
var saveSet = null;
var deleteSet = null;
for (var key in this.local_dirty) {
var info = this.data_info[key];
if (saveSet == null)
saveSet = [];
saveSet.push({
"key": info.key,
"value": info.value,
"data_type": info.data_type
});
}
for (var key in this.local_deletes) {
if (deleteSet == null)
deleteSet = [];
deleteSet.push(key);
}
var self = this;
this.server.setAndDeleteUserKeys(saveSet, deleteSet, function (reply) {
self.local_dirty = {};
self.local_deletes = {};
if (onDone)
onDone(null);
}, function (reply) {
if (onDone)
onDone(reply);
});
};
KeyData.prototype.stringify = function () {
var temp = {
id: this.id,
data: this.data_info,
dirty: this.local_dirty,
deleted: this.local_deletes
};
return JSON.stringify(temp);
};
KeyData.fromJson = function (json, server) {
var temp = JSON.parse(json);
var keydata = new KeyData(server, temp.id);
keydata.data_info = temp.data;
keydata.local_dirty = temp.dirty;
keydata.local_deletes = temp.deleted;
for (var key in keydata.data_info) {
var dataInfo = keydata.data_info[key];
keydata.data[key] = dataInfo.value;
if (dataInfo.modified > keydata.most_recent)
keydata.most_recent = dataInfo.modified;
}
return keydata;
};
return KeyData;
}());
sv.KeyData = KeyData;
})(sv || (sv = {}));
var sv;
(function (sv) {
function makeStripeButton(server, apiKey, product, successUrl, failUrl) {
var form = document.createElement("form");
form.method = "POST";
form.action = "https://" + server.ServerHost + "/form/stripeCheckout";
var sessionToken = document.createElement("input");
sessionToken.type = "hidden";
sessionToken.name = "session_id";
sessionToken.value = server.SessionId;
form.appendChild(sessionToken);
var productInput = document.createElement("input");
productInput.type = "hidden";
productInput.name = "product_id";
productInput.value = product.id;
form.appendChild(productInput);
var successUrlInput = document.createElement("input");
successUrlInput.type = "hidden";
successUrlInput.name = "success_redirect_url";
successUrlInput.value = successUrl;
form.appendChild(successUrlInput);
var failUrlInput = document.createElement("input");
failUrlInput.type = "hidden";
failUrlInput.name = "fail_redirect_url";
failUrlInput.value = failUrl;
form.appendChild(failUrlInput);
var script = document.createElement("script");
script.classList.add("stripe-button");
script.setAttribute("data-key", apiKey);
script.setAttribute("data-amount", String(product.price));
script.setAttribute("data-name", product.name);
script.setAttribute("data-description", product.description);
script.setAttribute("data-image", product.image_url);
script.setAttribute("data-locale", "auto");
script.setAttribute("data-zip-code", "true");
script.setAttribute("data-billing-address", "true");
script.src = "https://checkout.stripe.com/checkout.js";
form.appendChild(script);
return form;
}
sv.makeStripeButton = makeStripeButton;
})(sv || (sv = {}));
//# sourceMappingURL=serverville.js.map |
/**
* User: kgoulding
* Date: 4/3/12
* Time: 11:12 PM
*/
(function () { // self-invoking function
SAS.Main = function () {
var _self = this;
//region private fields and methods
var _map;
/** @type SAS.PriorityList */
var _priorityList;
var _bubbleChart;
var _mechanismList;
var _pages;
var _layout;
/** @type SAS.DataManager */
var _dataManager;
var _filename = 'test1';
var _detectSVG = function () {
return document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1");
};
var _reportIncompatibleBrowser = function () {
window.location = "oldbrowser.html";
};
var _preventAccidentalLeaving = function () {
window.onbeforeunload = function () {
if (!_dataManager.getIsSaved()) {
return "You have not submitted your response yet.";
}
};
};
var _setupClicksForActiveMech = function (activeMech) {
$("#moreInfo").html("");
if (activeMech != null) {
var $link = $("<a href='#'>See all explanations for </a>").appendTo("#moreInfo").click(function () {
new SAS.InfoWindow().createMechanismWindow(activeMech, _priorityList.getPriorities());
});
var $boldSpan = $('<span>').appendTo($link);
SAS.localizr.live(activeMech.data.progressive, function(str) {
$boldSpan.html(str.toLowerCase());
});
_bubbleChart.colorForMechanism(activeMech);
}
};
var _addLangBtn = function ($holder) {
var $langSel = $("<select></select>").appendTo($holder);
SAS.controlUtilsInstance.populateSelectList($langSel, null, ['en', 'af'], 'en');
$langSel.change(function() {
SAS.localizr.setActiveLang($(this).val());
});
};
var _initialize = function () {
if (!_detectSVG()) {
_reportIncompatibleBrowser();
return;
}
_dataManager = new SAS.DataManager();
_layout = new SAS.Layout();
// _map = new SAS.MapFrame();
_priorityList = new SAS.PriorityList();
_bubbleChart = new SAS.BubbleChart(_priorityList);
_mechanismList = new SAS.MechanismList(_filename, _bubbleChart);
_pages = new SAS.Pages(_layout, _priorityList, _mechanismList, _bubbleChart, _map, _dataManager);
_addLangBtn($('#langSel'));
_priorityList.onLoad(function () {
_bubbleChart.createBubbles();
_layout.positionElements();
});
_mechanismList.onLoad(function () {
_layout.positionElements();
});
_priorityList.onRatingChange(function () {
_bubbleChart.resizeBubbles();
});
_mechanismList.onActiveMechanismChange(function () {
_setupClicksForActiveMech(_mechanismList.getActiveMechanism());
});
_layout.onLayout(function () {
_bubbleChart.updateLayout();
});
};
//endregion
//region public API
this.getCacheVersion = function () {
//TODO - the cacheVersion should update each time any data changes on the server...
return 13;
};
this.getPages = function () {
return _pages;
};
/** @return {SAS.BubbleChart} */
this.getBubbleChart = function() {
return _bubbleChart;
};
/** @return {SAS.DataManager} */
this.getDataManager = function () {
return _dataManager;
};
/**
* @param {String} pId
* @return {SAS.PriorityDef}
*/
this.getPriorityDef = function (pId) {
return _priorityList.getPriorityDef(pId);
};
this.initialize = function () {
_initialize();
};
this.preventAccidentalLeaving = function () {
//TEMP _preventAccidentalLeaving();
};
//endregion
};
/**
@type SAS.Main
@const
*/
SAS.mainInstance = new SAS.Main();
SAS.mainInstance.initialize();
})(); |
(function() {
/**
* App Actions
**/
function userActions(context) {
var dispatch = context.dispatch;
var getState = context.getState;
var notifyError = context.utils.notifyError;
var post = context.utils.post;
var get = context.utils.get;
var url = context.utils.url;
function loginWithEmail(email, password) {
post(url.login, {
email: email,
password: password
}).then(function(response) {
dispatch('USER__LOGIN_SUCCESS', {email: email, token: response.token});
}).catch(function(e) {
dispatch('USER__LOGIN_FAILED', {email: email, cause: e});
notifyError({message: 'Login Failed', error: e});
});
}
function logout() {
dispatch('USER__LOGOUT');
}
function list() {
get(url.list, {
page: 1
}).then(function(response) {
dispatch('USERS__LIST', {users: response.data});
})
}
function load(id) {
var users = getState().users;
if (users.usersById[id])
return;
list();
}
return {
loginWithEmail: loginWithEmail,
logout: logout,
list: list,
load: load
}
}
/**
* App Reducer
**/
function userReducer(state, action) {
if (!state) state = {logged: false};
if (action.type === 'USER__LOGIN_SUCCESS') {
return {logged: true, email: action.payload.email, token: action.payload.token};
} else if (action.type === 'USER__LOGOUT' || action.type === 'USER__LOGIN_FAILED') {
return {logged: false};
}
return state;
}
function usersReducer(state, action) {
if (!state) state = {users: [], usersById: {}};
switch (action.type) {
case 'USERS__LIST':
return {
users: action.payload.users,
usersById: _.keyBy(action.payload.users, 'id')
};
}
return state;
}
var notificationId = 0;
function notificationsReducer(state, action) {
if (!state) state = [];
if (action.type === 'NOTIFICATION__ADD') {
var notification = action.payload;
notification.id = ++notificationId;
return [notification].concat(state);
} else if (action.type === 'NOTIFICATION__DISMISS') {
var id = action.payload.id || action.payload;
return state.filter(function(p) {
return !(id === p.id || action.payload === p);
});
}
return state;
}
function loadingReducer(state, action) {
state = state || {count: 0};
var count = state.count;
switch (action.type) {
case 'LOADING__BEGIN':
count++;
return {active: count > 0, count: count};
case 'LOADING__END':
count = Math.max(--count, 0);
return {active: count > 0, count: count};
}
return state;
}
function routerReducer(state, action) {
state = state || {url: null};
if (action.type === 'ROUTER__URL') {
state = {url: action.payload.url};
}
return state;
}
/**
* App Configuration
**/
window.app = CreateSimpleApp({
state: function(context) {
return {
user: JSON.parse(localStorage.getItem('user') || '{}')
}
},
reducers: function(context) {
return {
user: userReducer,
users: usersReducer,
loading: loadingReducer,
notifications: notificationsReducer,
router: routerReducer
}
},
actions: function(context) {
return {
user: userActions(context)
}
},
routes: function(context) {
var Route = riot.router.Route,
RedirectRoute = riot.router.RedirectRoute,
DefaultRoute = riot.router.DefaultRoute;
return [
new Route({tag: 'app'}).routes([
new Route({tag: 'users'}),
new Route({tag: 'user', path:'user/:userId'}),
new DefaultRoute({tag: 'home'})
]),
new RedirectRoute({from: '', to: 'app'})
];
},
utils: function(context) {
function appFetch(method, url, data) {
context.dispatch('LOADING__BEGIN', {url: url});
var req = {
method: method,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
};
// add custom backend auth token here...
if (method === 'POST') req.body = JSON.stringify(data);
if (method === 'GET' && data) url = url + (url.indexOf('?') > -1 ? '&' : '?') + $.param(data);
return window.fetch(url, req).then(function(response) {
return response.json().then(function(data) {
context.dispatch('LOADING__END', {url: url});
if (response.status === 200) {
return data;
} else {
var error = new Error(response.statusText);
error.response = response;
error.data = data;
throw error;
}
});
});
}
function appNotify(type, notification) {
notification.type = type;
return context.dispatch('NOTIFICATION__ADD', notification);
}
return {
// ajax
url: {
login: 'http://reqres.in/api/login',
list: 'http://reqres.in/api/users'
},
post: appFetch.bind(null, 'POST'),
get: appFetch.bind(null, 'GET'),
// notifications
notifyError: appNotify.bind(null, 'danger'),
notifySuccess: appNotify.bind(null, 'success'),
notifyAlert: appNotify.bind(null, 'warning'),
notifyInfo: appNotify.bind(null, 'info'),
dismiss: function(notification) {
context.dispatch('NOTIFICATION__DISMISS', notification);
}
};
}
});
/**
* Custom Listeners
**/
app.on('USER__LOGIN_SUCCESS USER__LOGOUT', function() {
var state = app.getState();
if (state.user.logged) {
localStorage.setItem('user', JSON.stringify(state.user));
} else {
localStorage.removeItem('user');
}
riot.route('#/app');
});
riot.router.on('route:updated', function() {
app.dispatch('ROUTER__URL', {url: riot.router.current.uri});
});
app.store.subscribe(function() {
var state = app.getState();
if (state.router.url !== null
&& state.router.url !== riot.router.current.uri) {
riot.route(state.router.url);
}
});
})();
|
'use strict';
var mql = require('./mql.js');
module.exports = {
mql: mql
};
|
import React from "react"
import { logsIcon } from "../icons"
const FeedbackTooltipContent = ({ url, onOpened }) => {
const openFeedbackPage = () => {
if (onOpened) {
onOpened()
}
window.open(url, `blank`, `noreferrer`)
}
return (
<>
<span style={{ marginRight: `5px` }}>How are we doing?</span>
<div
data-gatsby-preview-indicator="tooltip-link-text"
onClick={openFeedbackPage}
>
Share feedback
<span data-gatsby-preview-indicator="tooltip-svg">{logsIcon}</span>
</div>
</>
)
}
export default FeedbackTooltipContent
|
import { PostTime } from "../PostTime/PostTime"
import { SharePost } from "../SharePost/SharePost"
import { Container, Title, About, PostDetails, AuthorImage } from "./styles"
const PostHeader = ({ post }) => {
return (
<Container>
<Title>{post.title}</Title>
<About>
<PostDetails>
<AuthorImage>
<img src="/nicolas_thiry.png" alt="Nicolas Thiry" />
</AuthorImage>
<div>
Nicolas Thiry
<PostTime post={post} />
</div>
</PostDetails>
<SharePost />
</About>
</Container>
)
}
export { PostHeader }
|
var
path = require('path'),
chai = require('chai'),
chaiAsPromised = require('chai-as-promised'),
Process = require('./../../../../../../lib/core/process').Process,
utils = require('./../../../utils')
chai.use(chaiAsPromised)
var
expect = chai.expect,
should = chai.should()
describe('browser.js', function() {
this.timeout(0)
it('should fail if an unsupported command line option is provided', function() {
var proc = new Process(), out = ''
return proc.create('node',
utils.nodeProcCoverageArgs('bin/hooks/testem/crossbrowsertesting/browser.js', [
'--unknown'
]), {
onstderr: function(stderr) {
out += stderr
}
})
.then(() => {
expect(out).to.contain('Unknown option: --unknown')
return true
})
.catch(err => {
utils.log.error('error: ', err)
throw err
})
.should.be.fulfilled
})
it('should print help if "--help" command line option is provided', function() {
var proc = new Process(), out = ''
return proc.create('node',
utils.nodeProcCoverageArgs('bin/hooks/testem/crossbrowsertesting/browser.js', [
'--help'
]), {
onstdout: function(stdout) {
out += stdout
}
})
.then(() => {
expect(out).to.contain("browser.js [--help|-h] [--config <config-file>] [--os <os>] [--osVersion <os-version>] [--browser <browser>] [--browserVersion <browser-version>] [--device <device> ] [--orientation <orientation>] [--size <size>] [--local] [--localIdentifier <identifier>] [--video] [--screenshots] [--timeout <timeout-in-sec>] [--framework <test-framework>] [--project <project>] [--test <test>] [--build <build>]")
return true
})
.catch(err => {
utils.log.error('error: ', err)
throw err
})
.should.be.fulfilled
})
it('should fail if no command line options are provided', function() {
var proc = new Process(), out = ''
return proc.create('node',
utils.nodeProcCoverageArgs('bin/hooks/testem/crossbrowsertesting/browser.js'), {
onstderr: function(stderr) {
out += stderr
}
})
.then(() => {
expect(out).to.contain('failed to create test - StatusCodeError: 400')
expect(out).to.contain('required option browser missing')
return true
})
.catch(err => {
utils.log.error('error: ', err)
throw err
})
.should.be.fulfilled
})
it('should fail if invalid browser details command line arguments are provided', function() {
var proc = new Process(), out = ''
return proc.create('node',
utils.nodeProcCoverageArgs('bin/hooks/testem/crossbrowsertesting/browser.js', [
"--os", "Windows", "--osVersion", "None", "--browser", "Firefox", "--browserVersion", "43.0"
]), {
onstderr: function(stderr) {
out += stderr
}
})
.then(() => {
expect(out).to.contain('failed to create test - StatusCodeError: 400')
expect(out).to.contain('invalid osVersion \\"None\\" for os \\"Windows\\"')
return true
})
.catch(err => {
utils.log.error('error: ', err)
throw err
})
.should.be.fulfilled
})
it('should create a test for valid command line options and then stop run and cleanly exit when killed', function() {
var proc = new Process(), tried = false, build = utils.buildDetails()
return proc.create('node',
utils.nodeProcCoverageArgs('bin/hooks/testem/crossbrowsertesting/browser.js', [
"--os", "Windows", "--osVersion", "7 64-bit", "--browser", "Chrome", "--browserVersion", "33.0", "--build", build.build, "--test", build.test, "--project", build.project, "http://build.cross-browser-tests-runner.org:3000/tests/pages/tests.html"
]), {
onstdout: function(stdout) {
if(!tried && stdout.match(/created test/)) {
tried = true
proc.stop()
}
}
})
.catch(err => {
utils.log.error('error: ', err)
throw err
})
.should.be.fulfilled
})
})
|
"use strict";
/**
* Created by Junaid Anwar on 5/28/15.
*/
var winston = require('winston');
var logger = new(winston.Logger)();
logger.add(winston.transports.Console, {
level: 'verbose',
prettyPrint: true,
colorize: true,
silent: false,
timestamp: false
});
logger.stream = {
write: function(message, encoding) {
logger.info(message);
}
};
module.exports = logger;
|
var irc = require('irc');
var server = require('./server/server');
var pouch = require('pouchdb');
var config = require('./config')
var dbLocation = (process.env.COUCHLOCATION || 'http://localhost:5984/irclog');
var db = new pouch(dbLocation);
var bot = new irc.Client(config.server, config.botName, {
channels: config.channels
});
var app = server.start();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bots = {};
var names = [];
var logout = function (id) {
bots[id].bot.disconnect();
delete bots[id];
};
io.on('connection', function (socket) {
console.log('user connected', socket.id);
socket.on('login', function (msg) {
console.log(msg)
var name = msg.name.match(/(\w+)/)[0]
var newBot = new irc.Client(config.server, name, {
channels: config.channels
});
bots[socket.id] = {
bot: newBot
};
newBot.addListener('registered', function (ircMessage) {
// show it in client
socket.emit('joined', {
name: msg.name,
newNick: ircMessage.args[0],
names: names
});
});
});
socket.on('send message', function (msg) {
bots[socket.id].bot.say(config.channels[0], msg.message);
});
socket.on('logout', function (msg) {
if (bots.hasOwnProperty(socket.id)) {
logout(socket.id);
}
});
socket.on('disconnect', function () {
if (bots.hasOwnProperty(socket.id)) {
logout(socket.id);
}
console.log('user diconnected');
});
});
http.listen(3000, function () {
console.log('listening on :3000');
});
bot.addListener('message', function (from, to, text, message) {
db.put({
text: text,
_id: new Date() - 0 + from,
timestamp: new Date(),
sentfrom: from,
sentto: to
}).then(function(resp) {
io.emit('new message',
{
text: text,
name: from,
timestamp: new Date(),
names: names
});
}).catch(function(error){
console.error(error);
});
});
bot.addListener('join', function (channels, nick, message) {
// show it in client
console.log('irc bot joined: '+ nick);
});
bot.addListener('names', function (channel, nicks) {
names = nicks;
});
|
/*
* Template name: Kertas - Responsive Bootstrap 3 Admin Template
* Version: 1.0.0
* Author: VergoLabs
*/
function initValidation() {
$("#commentForm").validate();
// validate signup form on keyup and submit
$("#signupForm").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
},
topic: {
required: "#newsletter:checked",
minlength: 2
},
agree: "required"
},
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address",
agree: "Please accept our policy"
}
});
// propose username by combining first- and lastname
$("#username").focus(function() {
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
if(firstname && lastname && !this.value) {
this.value = firstname + "." + lastname;
}
});
}
$(function() {
"use strict";
initValidation();
}); |
'use strict';
/**
* Dependencies
*/
const gulp = require('gulp');
const copyAssets = require('./copy-assets');
const updateRedirects = require('./update-redirects');
const build = require('../build');
/**
* Export task
*/
module.exports = function watchAssets() {
gulp.watch(build.SRC_ASSETS, gulp.series(copyAssets, updateRedirects));
};
|
{
expect(request.requestHeaders).toEqual(
utils.merge(defaults.headers.common, defaults.headers.get, {
"X-COMMON-HEADER": "commonHeaderValue",
"X-GET-HEADER": "getHeaderValue",
"X-FOO-HEADER": "fooHeaderValue",
"X-BAR-HEADER": "barHeaderValue"
})
);
done();
}
|
const gulp = require("gulp");
const source = require("vinyl-source-stream"); // Used to stream bundle for further handling
const buffer = require("vinyl-buffer");
const babelify = require("babelify");
const browserify = require("browserify");
const watchify = require("watchify");
const gutil = require("gulp-util");
const cssmin = require("gulp-cssmin");
const less = require("gulp-less");
const uglify = require("gulp-uglify");
const header = require("gulp-header");
const config = require("../config");
const _error_ = "error"
// Build without watch:
gulp.task("js-build", () => {
config.esToJs.forEach(o => {
var filename = o.filename + ".js";
browserify(o.entry, { debug: true })
.transform(babelify, {
sourceMaps: true
})
.bundle()
.on(_error_, err => console.log(err))
.pipe(source(filename))
.pipe(gulp.dest(o.destfolder));
});
});
gulp.task("dist", () => {
config.esToJs.forEach(o => {
var filename = o.filename + ".js";
browserify(o.entry, { debug: false })
.transform(babelify, {
sourceMaps: false
})
.bundle()
.on(_error_, err => console.log(err))
.pipe(source(filename))
.pipe(buffer())
.pipe(uglify())
.pipe(header(config.license, {
version: config.version,
build: (new Date()).toUTCString()
}))
.pipe(gulp.dest(config.distFolder));
});
var allLess = config.lessToCss.concat(config.lessToCssExtras);
allLess.forEach(o => {
if (o.nodist) return;
var source = o.src, dest = o.dest;
gulp.src(source) // path to your files
.pipe(less().on(_error_, err => console.log(err)))
.pipe(cssmin().on(_error_, err => console.log(err))) // always minify CSS, remove temptation of editing css directly
.pipe(gulp.dest(config.cssDistFolder));
});
});
// Build for distribution (with uglify)
gulp.task("js-min", () => {
//NB: the following lines are working examples of source mapping generation and js minification
//they are commented on purpose, to keep the build process fast during development
config.esToJs.forEach(o => {
var filename = o.filename + ".min.js";
browserify(o.entry, { debug: false })
.transform(babelify, {
sourceMaps: false
})
.bundle()
.on(_error_, err => console.log(err))
.pipe(source(filename))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest(o.destfolder));
});
});
gulp.task("css-min", () => {
config.lessToCss.forEach(o => {
var source = o.src, dest = o.dest;
gulp.src(source) // path to your files
.pipe(less().on(_error_, err => console.log(err)))
.pipe(cssmin().on(_error_, err => console.log(err))) // always minify CSS, remove temptation of editing css directly
.pipe(gulp.dest(dest));
});
});
// Copies static files to the output folder
gulp.task("copy-static", () => {
config.toBeCopied.forEach(o => {
gulp.src([o.src])
.pipe(gulp.dest(o.dest));
});
});
// watches less files for changes; compiles the files upon change
gulp.task("watch-less", () => {
gulp.watch(config.lessRoot, ["css-build"]);
});
// Build using watchify, and watch
gulp.task("watch-es", watch => {
if (watch === undefined) watch = true;
config.esToJs.forEach(o => {
var filename = o.filename + ".built.js";
var bundler = browserify(o.entry, {
debug: true, // gives us sourcemapping
cache: {}, // required for watchify
packageCache: {}, // required for watchify
fullPaths: true // required for watchify
});
bundler.transform(babelify, {});
if (watch) {
bundler = watchify(bundler);
}
function rebundle() {
var stream = bundler.bundle();
stream.on(_error_, err => console.log(err));
stream = stream.pipe(source(filename));
return stream.pipe(gulp.dest(o.destfolder));
}
bundler.on("update", () => {
console.log(`[*] Rebuilding ${o.destfolder}${filename}`);
rebundle();
});
return rebundle();
});
});
gulp.task("dev-init", ["js-build", "css-min", "copy-static"]);
gulp.task("env-init", ["js-dist", "css-min", "copy-static"]);
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M12 19c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zM6 1c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12-8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm-6 8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0-6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0-6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z" />
, 'DialpadOutlined');
|
import React from "react";
import SeresTwoGrande from "../../utils/catalog/seres-2-grande";
import PatternPage from "../../components/pattern-page";
const SeresTwoGrandePage = () => (
<PatternPage pattern={SeresTwoGrande} />
);
export default SeresTwoGrandePage;
|
var chai = require('chai'),
should = chai.should(),
X = require('../build/x.test');
describe("X", function() {
it("Should be an Object", function() {
X.should.be.an('object');
});
it("Should be restful by default", function() {
X.restful.should.be.ok;
});
it("Should have a Version number", function() {
X.Version.should.exist;
});
}); |
const lab = require("lab").script();
const code = require("code");
exports.lab = lab;
let Execute = require("../src/index");
lab.experiment("Loop array Test", () => {
lab.test("should return an array contain the result for all items of input array", () => {
let execute = new Execute();
let executionTree = Execute.prepareExecutionTree([
{
title: "step 1",
actionType: "map",
action:{
array: (data) => data.array,
reducer: (data) => {return data + 1;}
},
output: {
addToResult: true,
accessibleToNextSteps: true,
map: {
destination: "different-node"
}
}
}
]);
let executionData = {
array :[1,2,3]
};
return execute.run(executionTree, executionData).then( (result)=> {
code.expect(result["different-node"]).to.equal([2,3,4]);
});
});
lab.test("should return an array contain the result for all items of input array (with concurrency)", () => {
let execute = new Execute();
let executionTree = Execute.prepareExecutionTree([
{
title: "step 1",
actionType: "map",
action:{
array: (data) => data.array,
reducer: (data) => {return data + 1;},
concurrency: 22,
},
output: {
addToResult: true,
accessibleToNextSteps: true,
map: {
destination: "different-node"
}
}
}
]);
let executionData = {
array :[1,2,3]
};
return execute.run(executionTree, executionData).then( (result)=> {
code.expect(result["different-node"]).to.equal([2,3,4]);
});
});
lab.test("map middleware should accept child execution tree", () => {
let execute = new Execute();
let childExecutionTree = [
{
title: "step c1",
action: (data) => ({a:data.i})
},
{
title: "step c2",
action: (data) => ({b:data.i + 1})
}
];
let executionTree = Execute.prepareExecutionTree([
{
title: "step 1",
actionType: "map",
action:{
array: (data) => data.array,
executionTree: childExecutionTree
}
}
]);
let executionData = {
array :[{i:1},{i:2},{i:3}]
};
return execute.run(executionTree, executionData).then( (result)=> {
code.expect(result.length).to.equal(3);
});
});
lab.test("map middleware should accept child execution tree and custom execution data", () => {
let execute = new Execute();
let childExecutionTree = Execute.prepareExecutionTree([
{
title: "step c1",
action: (data) => ({a:data.item.i})
},
{
title: "step c2",
action: (data) => ({b:data.item.i + 1})
}
]);
let executionTree = Execute.prepareExecutionTree([
{
title: "step 1",
actionType: "map",
action:{
array: (data) => data.array,
executionData: (data, item) => {
return {
data: data,
item: item
};
},
executionTree: childExecutionTree
}
}
]);
let executionData = {
array :[{i:1},{i:2},{i:3}]
};
return execute.run(executionTree, executionData).then( (result)=> {
code.expect(result.length).to.equal(3);
code.expect(result[0].a).to.equal(1);
});
});
}); |
/**
* Minim mathematics library for JavaScript.
*
* @link http://www.minimmaths.org/
* @copyright Copyright 2013 © MrAnchovy http://www.mranchovy.com/
* @license MIT http://opensource.org/licenses/MIT
* @namespace Minim
* @version 0.1.1-dev
**/
var Minim = {
/** Current version. */
VERSION: '0.1.1-dev'
};
(function (M) {
"use strict";
/**
* Copy properties to an object.
*
* This is a shallow copy so use with care with properties that are objects or arrays.
**/
M.extend = function (target) {
var source;
var length = arguments.length;
for (var i = 1; i < length; i++) {
source = arguments[i];
for (var name in source) {
target[name] = source[name];
}
}
return target;
};
// important constants
M.extend(M, {
/** Convert degrees to radians. */
DEG2RAD: Math.PI / 180,
/** Convert radians to degrees. */
RAD2DEG: 180 / Math.PI,
/** The value of π/2. */
PIOVER2: Math.PI / 2,
/** The maximum integer value in IEEE 754 (2^53 - 1). */
MAXINT: 9007199254740992,
/** The error in a single operation in IEEE 754. */
EPSILON: 1 / 9007199254740991,
/** Acceptable relative difference in almost equal floats. */
ALMOSTEQUAL: 1e-12,
/** Acceptable absolute difference in almost equal floats near zero. */
ALMOSTZERO: 1e-305,
});
/**
* Caution: almostEqual is not transitive (almostEqual(a, b) && almostEqual(b, c)
* does not imply almostEqual(a, c))
**/
M.almostEqual = function (a, b) {
var diff = Math.abs(a - b);
return (
// test the absolute difference, this is needed for numbers near zero
diff < Minim.ALMOSTZERO ||
// test the relative difference
diff < Math.max(Math.abs(a), Math.abs(b)) * Minim.ALMOSTEQUAL);
};
/**
* Test for a valid integer
*
* see http://phpjs.org/functions/is_int/
*
* @param mixed x the candidate to test
* @returns boolean true iff x is a valid integer
**/
M.isInteger = function (x) {
return (
x === +x && // numerical strings etc.
isFinite(x) && // +/- infinity and NaN
// j shint doesn't like !(x % 1) && // non-integers
x % 1 === 0 && // non-integers
Math.abs(x) <= M.MAXINT // cannot be held exactly
);
};
/** Modules should extend this property with any (public) classes. */
M.classes = {};
})(Minim);
|
/**
* Meow speech bubble object.
*/
game.Meow = me.ObjectEntity.extend({
init: function(x, y, level) {
var settings = {};
settings.image = me.loader.getImage("meowyell");
settings.spritewidth = 24;
settings.spriteheight = 24;
this.parent(x, y, settings);
this.renderable.addAnimation("0", [0]);
this.renderable.addAnimation("1", [1]);
this.renderable.addAnimation("2", [2]);
this.renderable.setCurrentAnimation(
Math.floor(3 * Math.random()).toString());
this.anchorPoint.set(0.5, 0.5);
this.gravity = 0;
this.alwaysUpdate = true;
this.collidable = false;
this.level = level;
this.innerRadius = 1;
this.startX = x;
this.startY = y;
this.ctrX = 144;
this.ctrY = 108;
this.leftBound = -136;
this.rightBound = 136 - 24;
this.topBound = -100;
this.bottomBound = 100 - 24;
this.counter = 30 + 20*Math.random();
if (game.settings.soundOn) {
var ind = Math.floor(3*Math.random());
me.audio.play("meow" + ind.toString());
}
},
update: function() {
this.counter--;
if (this.counter <= 0) {
me.game.remove(this);
}
if (this.level.player != null) {
this.pos.set(this.startX, this.startY);
var v = me.game.viewport.pos;
var p = new me.Vector2d(v.x + this.ctrX, v.y + this.ctrY);
this.boundOnLeft(p);
this.boundOnTop(p);
this.boundOnRight(p);
this.boundOnBottom(p);
}
},
boundOnLeft: function(playerPos) {
if (this.pos.x < playerPos.x + this.leftBound) {
var newX = playerPos.x + this.leftBound;
var newY = playerPos.y + ((this.pos.y - playerPos.y)
/ (this.pos.x - playerPos.x) * this.leftBound);
this.pos.set(newX, newY);
}
},
boundOnRight: function(playerPos) {
if (this.pos.x > playerPos.x + this.rightBound) {
var newX = playerPos.x + this.rightBound;
var newY = playerPos.y + ((this.pos.y - playerPos.y)
/ (this.pos.x - playerPos.x) * this.rightBound);
this.pos.set(newX, newY);
}
},
boundOnTop: function(playerPos) {
if (this.pos.y < playerPos.y + this.topBound) {
var newX = playerPos.x + ((this.pos.x - playerPos.x)
/ (this.pos.y - playerPos.y) * this.topBound);
var newY = playerPos.y + this.topBound;
this.pos.set(newX, newY);
}
},
boundOnBottom: function(playerPos) {
if (this.pos.y > playerPos.y + this.bottomBound) {
var newX = playerPos.x + ((this.pos.x - playerPos.x)
/ (this.pos.y - playerPos.y) * this.bottomBound);
var newY = playerPos.y + this.bottomBound;
this.pos.set(newX, newY);
}
}
});
|
/*
Slimbox v2.04 - The ultimate lightweight Lightbox clone for jQuery
(c) 2007-2010 Christophe Beyls <http://www.digitalia.be>
MIT-style license.
*/
/* Modified by Charly Le Prof (30 may 2012) charlyleprof2@gmail.com
- if vc == 0 vertical center for image
- if vc == 1 vertical center for image + caption
- if ir == 0 image source
- if ir == 1 image resize with wm = width max, hm = height max;
- Read file with parenthesis e.g.: totolitoto (1).jpg
- Right click for "save as"
- Hide focus border line on click with ie7
- Remove l=document.documentElement from function (w)
*/
/* Modified by Dric (14 oct 2012) cedric@driczone.net
- wm and hm are now 90% of screen size instead of a fixed size.
*/
(function (w) {
var E = w(window),
u, f, F = -1,
n, x, D, v, y, L, r, m = !window.XMLHttpRequest,
s = [],
k = {},
t = new Image(),
J = new Image(),
vc = 1,
ir = 1,
H, a, g, p, I, d, G, c, A, K;
w(function () {
w("body").append(w([H = w('<div id="lbOverlay" />')[0], a = w('<div id="lbCenter" />')[0], G = w('<div id="lbBottomContainer" />')[0]]).css("display", "none"));
g = w('<div id="lbImage" />').appendTo(a).append(p = w('<div style="position: relative;" />').append([I = w('<a id="lbPrevLink" href="#" />').click(B)[0], d = w('<a id="lbNextLink" href="#" />').click(e)[0]])[0])[0];
c = w('<div id="lbBottom" />').appendTo(G).append([w('<a id="lbCloseLink" href="#" />').add(H).click(C)[0], A = w('<div id="lbCaption" />')[0], K = w('<div id="lbNumber" />')[0], w('<div style="clear: both;" />')[0]])[0]
// Ajout Charly (image resize)
im = w('<img />').appendTo(g).css({position:"absolute",width:"100%",height:"100%",top:0,left:0,backgroundRepeat:"no-repeat"});
});
w.slimbox = function (O, N, M) {
u = w.extend({
loop: false,
overlayOpacity: 0.8,
overlayFadeDuration: 400,
resizeDuration: 400,
resizeEasing: "swing",
initialWidth: 250,
initialHeight: 250,
imageFadeDuration: 400,
captionAnimationDuration: 400,
counterText: "{x}/{y}",
closeKeys: [27, 88, 67],
previousKeys: [37, 80],
nextKeys: [39, 78]
}, M);
if (typeof O == "string") {
O = [
[O, N]
];
N = 0
}
// Ajout Charly
hm = E.height() * 0.90;
wm = E.width() * 0.90; // image resize
var zIndexNumber = 9999; // redefine z-order
$('div').each(function() {
$(this).css('zIndex', zIndexNumber);
zIndexNumber += 10;
});
I.hideFocus = true; // hide focus border line on click with ie7
d.hideFocus = true;
// Fin ajout Charly
y = E.scrollTop() + (E.height() / 2);
L = u.initialWidth;
r = u.initialHeight;
w(a).css({
top: Math.max(0, y - (r / 2)),
width: L,
height: r,
marginLeft: -L / 2
}).show();
v = m || (H.currentStyle && (H.currentStyle.position != "fixed"));
if (v) {
H.style.position = "absolute"
}
w(H).css("opacity", u.overlayOpacity).fadeIn(u.overlayFadeDuration);
z();
j(1);
f = O;
u.loop = u.loop && (f.length > 1);
return b(N)
};
w.fn.slimbox = function (M, P, O) {
P = P ||
function (Q) {
return [Q.href, Q.getAttribute('tiptitle')]
};
O = O ||
function () {
return true
};
var N = this;
return N.unbind("click").click(function () {
var S = this,
U = 0,
T, Q = 0,
R;
T = w.grep(N, function (W, V) {
return O.call(S, W, V)
});
for (R = T.length; Q < R; ++Q) {
if (T[Q] == S) {
U = Q
}
T[Q] = P(T[Q], Q)
}
return w.slimbox(T, U, M)
})
};
function z() {
var N = E.scrollLeft(),
M = E.width();
w([a, G]).css("left", N + (M / 2));
if (v) {
w(H).css({
left: N,
top: E.scrollTop(),
width: M,
height: E.height()
})
}
}
function j(M) {
if (M) {
w("object").add(m ? "select" : "embed").each(function (O, P) {
s[O] = [P, P.style.visibility];
P.style.visibility = "hidden"
})
} else {
w.each(s, function (O, P) {
P[0].style.visibility = P[1]
});
s = []
}
var N = M ? "bind" : "unbind";
E[N]("scroll resize", z);
w(document)[N]("keydown", o)
}
function o(O) {
var N = O.keyCode,
M = w.inArray;
return (M(N, u.closeKeys) >= 0) ? C() : (M(N, u.nextKeys) >= 0) ? e() : (M(N, u.previousKeys) >= 0) ? B() : false
}
function B() {
return b(x)
}
function e() {
return b(D)
}
function b(M) {
if (M >= 0) {
F = M;
n = f[F][0];
x = (F || (u.loop ? f.length : 0)) - 1;
D = ((F + 1) % f.length) || (u.loop ? 0 : -1);
q();
a.className = "lbLoading";
k = new Image();
k.onload = i;
k.src = n
}
return false
}
function i() {
// Ajout Charly (image resize)
nW = k.width;
nH = k.height;
if(ir==1){
if(k.width > wm || k.height > hm) {
nH = k.width / k.height < wm / hm ? hm : wm * (k.height / k.width);
nW = k.width / k.height < wm / hm ? hm * (k.width / k.height) : wm;
}
}
w(im).attr("src", n);
// Fin ajout Charly
a.className = "";
w(g).css({
visibility: "hidden",
display: ""
});
w(p).width(nW); // replace k.width by nW (image resize)
w([p, I, d]).height(nH);// replace k.height by nH (image resize)
w(A).html(f[F][1] || "");
w(K).html((((f.length > 1) && u.counterText) || "").replace(/{x}/, F + 1).replace(/{y}/, f.length));
if (x >= 0) {
t.src = f[x][0]
}
if (D >= 0) {
J.src = f[D][0]
}
L = g.offsetWidth;
r = g.offsetHeight;
var M = Math.max(0, y - (r / 2));
// Ajout Charly (vertical center for image and caption)
if(vc==1) w(G).css({display: "", visibility: "hidden", width: L});
M = M - (G.offsetHeight/2) + 1;
// Fin ajout Charly
if (a.offsetHeight != r) {
w(a).animate({
height: r,
top: M
}, u.resizeDuration, u.resizeEasing)
}
// Ajout Charly (vertical center for image and caption) top: M
if (a.offsetWidth != L) {
w(a).animate({
width: L,
marginLeft: -L / 2,
top: M
}, u.resizeDuration, u.resizeEasing)
}
w(a).queue(function () {
w(G).css({
width: L,
top: M + r,
marginLeft: -L / 2,
visibility: "hidden",
display: ""
});
w(g).css({
display: "none",
visibility: "",
opacity: ""
}).fadeIn(u.imageFadeDuration, h)
})
}
function h() {
if (x >= 0) {
w(I).show()
}
if (D >= 0) {
w(d).show()
}
w(c).css("marginTop", -c.offsetHeight).animate({
marginTop: 0
}, u.captionAnimationDuration);
G.style.visibility = ""
}
function q() {
k.onload = null;
k.src = t.src = J.src = n;
w([a, g, c]).stop(true);
w([I, d, g, G]).hide()
}
function C() {
if (F >= 0) {
q();
F = x = D = -1;
w(a).hide();
w(H).stop().fadeOut(u.overlayFadeDuration, j)
}
return false
}
})(jQuery);
// AUTOLOAD CODE BLOCK (MAY BE CHANGED OR REMOVED)
if (!/android|iphone|ipod|series60|symbian|windows ce|blackberry/i.test(navigator.userAgent)) {
jQuery(function ($) {
$("a[rel^='lightbox']").slimbox({ /* Put custom options here */
}, null, function (el) {
return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
});
});
} |
/**
* @file Revoke a permission from a user to read data from another one
*/
'use strict'
let commander = require('commander'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
green = require('chalk').bold.green,
red = require('chalk').bold.red
commander
.command('revoke-permission <user> <permission>')
.description('revoke a permission from a user to read data from another one')
.action((user, permission) => {
User.findOneAndUpdate({
name: user
}, {
$pull: {
canRead: permission
}
}, {
new: true
}, (err, dbUser) => {
if (err || !dbUser) {
console.log(red('Failed to add permission'))
console.log('Error: %s', err || 'User ' + user + ' not found')
process.exit(1)
}
let permissions = [user].concat(dbUser.canRead).join(', ')
console.log(green('User updated'))
console.log('User: %s\nPermissions: %s', user, permissions)
process.exit(0)
})
}) |
/**
* An example with a custom session store in mongoDB : mongoose-session
*/
// Load library
import sockpress from 'sockpress'
import mongoose from 'mongoose'
import mongooseSession from 'mongoose-session'
// Create new engine using mongoose session controller
const store = mongooseSession(mongoose)
const app = sockpress({
secret: 'key',
resave: false,
store
})
// Routes
app.post('/login', (req, res) => {
if (!req.session.authenticated) {
req.session.authenticated = true
// save is automatically called in express routes
}
res.send({
error: null
})
})
app.io.route('action', (socket, data) => {
if (socket.session.authenticated) {
socket.session.foo = 'bar'
socket.session.save()
}
})
// Start the engine
app.listen(3000)
|
_gaq.push(['_trackPageview']);
// If awaiting activation
var waiting = true;
// If trusted exit, for exit confirmation
var trustedExit = false;
// Used to fade out subtitles after calculated duration
var subtitleTimer = false;
var subtitleVanishBaseMillis;
var subtitleVanishExtraMillisPerChar;
var subtitleHourlyTimer = false;
var subtitleHourlyShip = 0;
// Holder object for audio files to test mp3 duration
var subtitleMp3;
// If auto-focus on window to capture key events or not
var autoFocus = 0;
// Critical Animation
var critAnim = false;
var taihaStatus = false;
// Screenshot status
var isTakingScreenshot = false;
var suspendedTaiha = false;
// Overlay avoids cursor
var subtitlePosition = "bottom";
// Overlay for map markers
var markersOverlayTimer = false;
// Idle time check
/*
variables explanation:
longestIdleTime - high score of idle time
idleTimer - timer ID for interval function of idleFunction
idleTimeout - timer ID for unsafe idle time marker
idleFunction - function that indicates the way of the idle counter
*/
localStorage.longestIdleTime = Math.max(localStorage.longestIdleTime || 0,1800000);
var
lastRequestMark = Date.now(),
idleTimer,
idleTimeout,
idleFunction;
// Show game screens
function ActivateGame(){
waiting = false;
var scale = (ConfigManager.api_gameScale || 100) / 100;
$(".box-wrap").css("background", "#fff");
$(".box-wait").hide();
$(".game-swf").remove();
$(".box-game")
.prepend("<iframe class=game-swf frameborder=0></iframe>")
.find(".game-swf")
.attr("src", "http://www.dmm.com/netgame/social/-/gadgets/=/app_id=854854/")
.end()
.show();
$(".box-wrap").css({
"background": "#fff",
"width": 1200,
"zoom": scale,
"margin-top": ConfigManager.api_margin
});
idleTimer = setInterval(idleFunction,1000);
if(ConfigManager.alert_idle_counter) {
$(".game-idle-timer").trigger("refresh-tick");
}
}
$(document).on("ready", function(){
// Initialize data managers
ConfigManager.load();
KC3Master.init();
RemodelDb.init();
KC3Meta.init("../../../../data/");
KC3Meta.loadQuotes();
KC3QuestManager.load();
KC3Database.init();
KC3Translation.execute();
// User css customizations
if(ConfigManager.dmm_custom_css !== ""){
var customCSS = document.createElement("style");
customCSS.type = "text/css";
customCSS.id = "dmm_custom_css";
customCSS.innerHTML = ConfigManager.dmm_custom_css;
$("head").append(customCSS);
}
// Apply interface configs
if(ConfigManager.api_bg_image === ""){
$("body").css("background", ConfigManager.api_bg_color);
}else{
$("body").css("background-image", "url("+ConfigManager.api_bg_image+")");
$("body").css("background-color", ConfigManager.api_bg_color);
$("body").css("background-size", ConfigManager.api_bg_size);
$("body").css("background-position", ConfigManager.api_bg_position);
$("body").css("background-repeat", "no-repeat");
}
if(ConfigManager.api_subtitles){
$(".overlay_subtitles").css("font-family", ConfigManager.subtitle_font);
$(".overlay_subtitles").css("font-size", ConfigManager.subtitle_size);
if(ConfigManager.subtitle_bold){
$(".overlay_subtitles").css("font-weight", "bold");
}
const scale = (ConfigManager.api_gameScale || 100) / 100;
switch (ConfigManager.subtitle_display) {
case "bottom":
$(".overlay_subtitles span").css("pointer-events", "none");
break;
case "below":
$(".overlay_subtitles").prependTo(".out-of-box");
$(".overlay_subtitles").css({
position: "relative",
margin: "5px auto 0px",
left: "auto",
top: "auto",
bottom: "auto",
right: "auto",
width: $(".box-game").width(),
zoom: scale
});
break;
case "stick":
$(".overlay_subtitles").prependTo(".out-of-box");
$(".overlay_subtitles").css({
position: "fixed",
left: "50%",
top: "auto",
bottom: ConfigManager.alert_idle_counter > 1 ? "40px" : "3px",
right: "auto",
margin: "0px 0px 0px "+(-($(".box-game").width()/2))+"px",
width: $(".box-game").width(),
zoom: scale
});
break;
default: break;
}
}
$(".box-wait").show();
// Quick Play
$(".play_btn").on('click', function(){
ActivateGame();
});
// Disable Quick Play (must panel)
if(ConfigManager.api_mustPanel) {
$(".play_btn")
.off('click')
.attr("disabled", "disabled")
.text(KC3Meta.term("APIWaitToggle"))
.css("color", "#777")
.css('width', "40%");
}
// Configure Refresh Toggle (using $(".game-refresh").trigger("click") is possible)
$(".game-refresh").on("click",function(){
switch($(this).text()) {
case("01"):
$(".game-swf").attr("src","about:blank").attr("src",localStorage.absoluteswf);
$(this).text("05");
break;
default:
$(this).text(($(this).text()-1).toDigits(2));
break;
}
});
// Listen ConfigManager changed
window.addEventListener("storage", function({key, timeStamp, url}){
if(key === ConfigManager.keyName()) {
ConfigManager.load();
if($("#dmm_custom_css").html() !== ConfigManager.dmm_custom_css){
$("#dmm_custom_css").html(ConfigManager.dmm_custom_css);
}
}
});
// Untranslated quest copy-able text form
$(".overlay_quests").on("click", ".no_tl", function(){
chrome.tabs.create({
url: "https://translate.google.com/#ja/"+ConfigManager.language+"/"
+encodeURIComponent($(this).data("qtitle"))
+"%0A%0A"
+encodeURIComponent($(this).data("qdesc"))
});
});
// Overlay avoids cursor
$(".overlay_subtitles span").on("mouseover", function(){
switch (ConfigManager.subtitle_display) {
case "evade":
if (subtitlePosition == "bottom") {
$(".overlay_subtitles").css("bottom", "");
$(".overlay_subtitles").css("top", "5px");
subtitlePosition = "top";
} else {
$(".overlay_subtitles").css("top", "");
$(".overlay_subtitles").css("bottom", "5px");
subtitlePosition = "bottom";
}
break;
case "ghost":
$(".overlay_subtitles").addClass("ghost");
break;
default: break;
}
});
// Configure Idle Timer
/*
unsafe-tick : remove the safe marker of API idle time
refresh-tick : reset the timer and set the idle time as safe zone
*/
$(".game-idle-timer").on("unsafe-tick",function(){
$(".game-idle-timer").removeClass("safe-timer");
}).on("refresh-tick",function(){
clearTimeout(idleTimeout);
$(".game-idle-timer").addClass("safe-timer");
idleTimeout = setTimeout(function(){
$(".game-idle-timer").trigger("unsafe-tick");
},localStorage.longestIdleTime);
});
idleFunction = function(){
if(ConfigManager.alert_idle_counter) {
$(".game-idle-timer").text(String(Math.floor((Date.now() - lastRequestMark) / 1000)).toHHMMSS());
// Show Idle Counter
if(ConfigManager.alert_idle_counter > 1) {
$(".game-idle-timer").show();
} else {
$(".game-idle-timer").hide();
}
} else {
$(".game-idle-timer").text(String(NaN).toHHMMSS());
$(".game-idle-timer").hide();
clearInterval(idleTimer);
}
};
// Enable Refresh Toggle
if(ConfigManager.api_directRefresh) {
$(".game-refresh").css("display","flex");
}
// Exit confirmation
window.onbeforeunload = function(){
// added waiting condition should be ignored
if(ConfigManager.api_askExit==1 && !trustedExit && !waiting){
trustedExit = true;
setTimeout(function(){ trustedExit = false; }, 100);
// Not support custom message any more, see:
// https://bugs.chromium.org/p/chromium/issues/detail?id=587940
return KC3Meta.term("UnwantedExitDMM");
}
};
setInterval(function(){
if(autoFocus===0){
window.focus();
$(".focus_regain").hide();
}else{
$(".focus_regain").show();
$(".focus_val").css("width", (800*(autoFocus/20))+"px");
autoFocus--;
}
}, 1000);
});
$(document).on("keydown", function(event){
switch(event.keyCode) {
// F7: Toggle keyboard focus
case(118):
autoFocus = 20;
return false;
// F9: Screenshot
case(120):
if (isTakingScreenshot) return;
isTakingScreenshot = true;
(new KCScreenshot())
.setCallback(function(){
isTakingScreenshot = false;
})
.start("Auto", $(".box-wrap"));
return false;
// F10: Clear overlays
case(121):
interactions.clearOverlays({}, {}, function(){});
return false;
// Other else
default:
break;
}
});
/* Invoke-able actions
-----------------------------------*/
var interactions = {
// Panel is opened, activate the game
activateGame :function(request, sender, response){
if(waiting){
ActivateGame();
response({success:true});
}else{
response({success:false});
}
},
// Cat Bomb Detection -> Enforced
catBomb :function(request, sender, response){
try{
switch(ConfigManager.api_directRefresh) {
case 0:
throw new Error("");
case 1:
$(".game-refresh").text((0).toDigits(2)).css('right','0px');
break;
default:
// TODO : Forced API Link Refresh
$(".game-refresh").text((0).toDigits(2)).trigger('bomb-exploded');
break;
}
response({success:true});
}catch(e){
console.error("CatBomb exception", e);
}finally{
response({success:false});
}
},
// Request OK Marker
goodResponses :function(request, sender, response){
if(request.tcp_status === 200 && request.api_status === 1) {
localStorage.longestIdleTime = Math.max(localStorage.longestIdleTime,Date.now() - lastRequestMark);
lastRequestMark = Date.now();
$(".game-idle-timer").trigger("refresh-tick");
clearInterval(idleTimer);
idleTimer = setInterval(idleFunction,1000);
idleFunction();
} else {
clearInterval(idleTimer);
clearTimeout(idleTimeout);
$(".game-idle-timer").trigger("unsafe-tick");
console.error("API Link cease to functioning anymore after",String(Math.floor((Date.now() - lastRequestMark)/1000)).toHHMMSS(),"idle time");
}
},
// Quest page is opened, show overlays
questOverlay :function(request, sender, response){
//Only skip overlay generation if neither of the overlay features is enabled.
if(!ConfigManager.api_translation && !ConfigManager.api_tracking){ response({success:false}); return true; }
KC3QuestManager.load();
$.each(request.questlist, function( index, QuestRaw ){
// console.log("showing quest",QuestRaw);
if( QuestRaw !=- 1 && index < 5 ){
var QuestBox = $("#factory .ol_quest_exist").clone().appendTo(".overlay_quests");
// Get quest data
var QuestData = KC3QuestManager.get( QuestRaw.api_no );
// Show meta, title and description
if( typeof QuestData.meta().available != "undefined" ){
if (ConfigManager.api_translation){
$(".name", QuestBox).text( QuestData.meta().name );
$(".desc", QuestBox).text( QuestData.meta().desc );
}else{
$(".content", QuestBox).css({opacity: 0});
}
if(ConfigManager.api_tracking){
$(".tracking", QuestBox).html( QuestData.outputHtml() );
if(QuestData.tracking && QuestData.tracking.length > 1){
$(".tracking", QuestBox).addClass("small");
}
}else{
$(".tracking", QuestBox).hide();
}
}else{
if(ConfigManager.google_translate) {
$(".with_tl", QuestBox).css({ visibility: "hidden" });
$(".no_tl", QuestBox).data("qid", QuestRaw.api_no);
$(".no_tl", QuestBox).data("qtitle", QuestRaw.api_title);
$(".no_tl", QuestBox).data("qdesc", QuestRaw.api_detail);
$(".no_tl", QuestBox).show();
} else {
QuestBox.css({ visibility: "hidden" });
}
}
}
});
response({success:true});
},
// Quest Progress Notification
questProgress :function(request, sender, response){
response({success:true});
},
// In-game record screen translation
recordOverlay :function(request, sender, response){
// app.Dom.applyRecordOverlay(request.record);
response({success:true});
},
// Show map markers for old worlds (node letters & icons)
markersOverlay :function(request, sender, response){
if(!ConfigManager.map_markers && !ConfigManager.map_letters){
response({success:false}); return true;
}
var sortieStartDelayMillis = 2800;
var markersShowMillis = 5000;
var compassLeastShowMillis = 3500;
if(markersOverlayTimer){
// Keep showing if last ones not disappear yet
clearTimeout(markersOverlayTimer);
$(".overlay_markers").show();
} else {
var letters = KC3Meta.nodeLetters(request.worldId, request.mapId);
var lettersFound = (!!letters && Object.keys(letters).length > 0);
var icons = KC3Meta.nodeMarkers(request.worldId, request.mapId);
var iconsFound = (!!icons.length && icons.length > 0);
$(".overlay_markers").hide().empty();
if(lettersFound && ConfigManager.map_letters){
// Show node letters
for(let l in letters){
var letterDiv = $('<div class="letter"></div>').text(l)
.css("left", letters[l][0] + "px")
.css("top", letters[l][1] + "px");
if(l.length > 1) letterDiv.css("font-size", 34 - 6 * l.length);
$(".overlay_markers").append(letterDiv);
}
}
if(iconsFound && ConfigManager.map_markers){
// Show some icon style markers
for(let i in icons){
var obj = icons[i];
var iconImg = $('<img />')
.attr("src", chrome.runtime.getURL("assets/img/" + obj.img))
.attr("width", obj.size[0])
.attr("height", obj.size[1]);
var iconDiv = $('<div class="icon"></div>')
.css("left", obj.pos[0] + "px")
.css("top", obj.pos[1] + "px")
.append(iconImg);
$(".overlay_markers").append(iconDiv);
}
}
if(request.needsDelay){
// Delay to show on start of sortie
setTimeout(function(){
$(".overlay_markers").fadeIn(1000);
}, sortieStartDelayMillis);
} else {
$(".overlay_markers").fadeIn(1000);
}
markersOverlayTimer = true;
}
if(markersOverlayTimer){
markersOverlayTimer = setTimeout(function(){
$(".overlay_markers").fadeOut(2000);
markersOverlayTimer = false;
}, markersShowMillis
+ (request.compassShow ? compassLeastShowMillis : 0)
+ (request.needsDelay ? sortieStartDelayMillis : 0)
);
}
response({success:true});
},
// Remove HTML overlays
clearOverlays :function(request, sender, response){
// console.log("clearing overlays");
// app.Dom.clearOverlays();
$(".overlay_quests").empty();
$(".overlay_markers").empty();
$(".overlay_record").hide();
response({success:true});
},
// Screenshot triggered, capture the visible tab
screenshot :function(request, sender, response){
if (isTakingScreenshot) return;
isTakingScreenshot = true;
// ~Please rewrite the screenshot script
(new KCScreenshot())
.setCallback(function(){
response({success:true});
isTakingScreenshot = false;
})
.start(request.playerName, $(".box-wrap"));
return true;
},
// Fit screen
fitScreen :function(request, sender, response){
var gameScale = (ConfigManager.api_gameScale || 100) / 100;
var topMargin = Math.ceil((ConfigManager.api_margin || 0) * gameScale);
// Get browser zoon level for the page
chrome.tabs.getZoom(null, function(zoomFactor){
// Resize the window
chrome.windows.getCurrent(function(wind){
chrome.windows.update(wind.id, {
width: Math.ceil(1200 * gameScale * zoomFactor) + (wind.width - Math.ceil($(window).width() * zoomFactor)),
height: Math.ceil(720 * gameScale * zoomFactor) + (wind.height - Math.ceil($(window).height() * zoomFactor)) + topMargin
});
});
});
},
// Taiha Alert Start
taihaAlertStart :function(request, sender, response, callback){
taihaStatus = true;
if(ConfigManager.alert_taiha_blur) {
$(".box-wrap").addClass("critical");
}
if(ConfigManager.alert_taiha_blood) {
if(critAnim){ clearInterval(critAnim); }
if(!ConfigManager.alert_taiha_noanim){
critAnim = setInterval(function() {
$(".taiha_red").toggleClass("anim2");
}, 500);
}
$(".taiha_blood").show(0, function(){
$(".taiha_red").show(0, function(){
(callback || function(){})();
});
});
}
},
// Taiha Alert Stop
taihaAlertStop :function(request, sender, response, callback){
taihaStatus = false;
$(".box-wrap").removeClass("critical");
if(critAnim){ clearInterval(critAnim); }
$(".taiha_blood").hide(0, function(){
$(".taiha_red").hide(0, function(){
(callback || function(){})();
});
});
},
// Suspend Taiha Alert for taking screenshot
suspendTaiha :function(callback){
var self = this;
if (!taihaStatus && !suspendedTaiha) {
(callback || function(){})();
return false;
}
if (suspendedTaiha) {
clearTimeout(suspendedTaiha);
(callback || function(){})();
} else {
this.taihaAlertStop({}, {}, {}, function(){
setTimeout(function(){
(callback || function(){})();
}, 10);
});
}
suspendedTaiha = setTimeout(function(){
self.taihaAlertStart({}, {}, {});
suspendedTaiha = false;
}, 2000);
},
// Show subtitles
subtitle :function(request, sender, response){
if(!ConfigManager.api_subtitles) return true;
//console.debug("subtitle", request);
// Get subtitle text
var subtitleText = false;
var quoteIdentifier = "";
var quoteVoiceNum = request.voiceNum;
var quoteVoiceSize = request.voiceSize;
var quoteVoiceDuration = request.duration;
var quoteSpeaker = "";
switch(request.voicetype){
case "titlecall":
quoteIdentifier = "titlecall_"+request.filename;
break;
case "npc":
quoteIdentifier = "npc";
break;
case "event":
quoteIdentifier = "event";
break;
case "abyssal":
quoteIdentifier = "abyssal";
if(ConfigManager.subtitle_speaker){
const abyssalId = KC3Meta.getAbyssalIdByFilename(quoteVoiceNum);
quoteSpeaker = KC3Meta.abyssShipName(abyssalId);
}
break;
default:
quoteIdentifier = request.shipID;
if(ConfigManager.subtitle_speaker){
quoteSpeaker = KC3Meta.shipName(KC3Master.ship(quoteIdentifier).api_name);
}
break;
}
subtitleText = KC3Meta.quote( quoteIdentifier, quoteVoiceNum, quoteVoiceSize );
// Lazy init timing parameters
if(!subtitleVanishBaseMillis){
subtitleVanishBaseMillis = Number(KC3Meta.quote("timing", "baseMillisVoiceLine")) || 2000;
}
if(!subtitleVanishExtraMillisPerChar){
subtitleVanishExtraMillisPerChar = Number(KC3Meta.quote("timing", "extraMillisPerChar")) || 50;
}
const hideSubtitle = () => {
// hide first to fading will stop
$(".overlay_subtitles").stop(true, true);
$(".overlay_subtitles").hide();
// If subtitle removal timer is ongoing, reset
if(subtitleTimer){
if(Array.isArray(subtitleTimer))
subtitleTimer.forEach(clearTimeout);
else
clearTimeout(subtitleTimer);
}
};
// Display subtitle and set its removal timer
const showSubtitle = (subtitleText, quoteIdentifier) => {
if($.type(subtitleText) === "string") {
showSubtitleLine(subtitleText, quoteIdentifier);
const millis = quoteVoiceDuration || (subtitleVanishBaseMillis +
subtitleVanishExtraMillisPerChar * $(".overlay_subtitles").text().length);
subtitleTimer = setTimeout(fadeSubtitlesOut, millis);
return;
}
subtitleTimer = [];
let lastLineOutMillis = 0;
$.each(subtitleText, (delay, text) => {
const delays = String(delay).split(',');
const millis = Number(delays[0]);
lastLineOutMillis = delays.length > 1 ? Number(delays[1]) :
(millis + subtitleVanishBaseMillis + subtitleVanishExtraMillisPerChar * text.length);
subtitleTimer.push(setTimeout(() => {
showSubtitleLine(text, quoteIdentifier);
}, millis));
});
subtitleTimer.push(setTimeout(fadeSubtitlesOut, lastLineOutMillis));
};
const fadeSubtitlesOut = () => {
subtitleTimer = false;
$(".overlay_subtitles").fadeOut(1000, function(){
switch (ConfigManager.subtitle_display) {
case "evade":
$(".overlay_subtitles").css("top", "");
$(".overlay_subtitles").css("bottom", "5px");
subtitlePosition = "bottom";
break;
case "ghost":
$(".overlay_subtitles").removeClass("ghost");
break;
default: break;
}
});
};
const showSubtitleLine = (subtitleText, quoteIdentifier) => {
$(".overlay_subtitles span").html(subtitleText);
if(!!quoteSpeaker){
$(".overlay_subtitles span").html("{0}: {1}".format(quoteSpeaker, subtitleText));
}
$(".overlay_subtitles").toggleClass("abyssal", quoteIdentifier === "abyssal");
$(".overlay_subtitles").show();
};
const cancelHourlyLine = () => {
if(subtitleHourlyTimer) clearTimeout(subtitleHourlyTimer);
subtitleHourlyTimer = false;
subtitleHourlyShip = 0;
};
const bookHourlyLine = (text, shipId) => {
cancelHourlyLine();
const nextHour = new Date().shiftHour(1).resetTime(["Minutes", "Seconds", "Milliseconds"]).getTime();
const diffMillis = nextHour - Date.now();
// Do not book on unexpected diff time: passed or > 59 minutes
if(diffMillis <= 0 || diffMillis > 59 * 60000) {
showSubtitle(text, shipId);
} else {
subtitleHourlyShip = shipId;
subtitleHourlyTimer = setTimeout(function(){
// Should cancel booked hourly line for some conditions
if(subtitleHourlyShip == shipId
// if Chrome delays timer execution > 3 seconds
&& Math.abs(Date.now() - nextHour) < 3000
){
hideSubtitle();
showSubtitle(text, shipId);
}
cancelHourlyLine();
}, diffMillis);
}
};
// If subtitles available for the voice
if(subtitleText){
hideSubtitle();
// Book for a future display if it's a ship's hourly voice,
// because game preload voice file in advance (about > 5 mins).
if(!isNaN(Number(quoteIdentifier)) && KC3Meta.isHourlyVoiceNum(quoteVoiceNum)){
if(ConfigManager.subtitle_hourly){
bookHourlyLine(subtitleText, quoteIdentifier);
}
} else {
showSubtitle(subtitleText, quoteIdentifier);
}
}
},
// Live reloading meta data
reloadMeta :function(request, sender, response){
if(request.metaType === "Quotes") {
KC3Meta.loadQuotes();
} else if(request.metaType === "Quests") {
KC3Meta.reloadQuests();
}
console.info(request.metaType, "reloaded");
},
// Dummy action
dummy :function(request, sender, response){
}
};
/* Listen to messaging triggers
-----------------------------------*/
chrome.runtime.onMessage.addListener(function(request, sender, response){
// If request is for this script
if((request.identifier||"") == "kc3_gamescreen"){
// If action requested is supported
if(typeof interactions[request.action] !== "undefined"){
// Execute the action
interactions[request.action](request, sender, response);
return true;
}
}
}); |
/**
* @class ForceDirectedNetwork
*
* Implements a force-directed network widget
*
* And here's an example:
*
* @example
* $("#div-id").ForceDirectedNetwork({
* minHeight : "300px",
* workspaceID : "workspace.1",
* token : "user-token-53"
* });
*
* @extends KBWidget
* @chainable
*
* @param {Object} options
* The options
*
* @param {String} options.workspaceID
* The workspace ID of the network to look up
*
* @param {String} options.token
* The authorization token used for workspace lookup
*
* @param {String|Number} options.minHeight
* A minimum height for the widget
*/define (
[
'kbwidget',
'bootstrap',
'jquery',
'kbwidget'
], function(
KBWidget,
bootstrap,
$,
KBWidget
) {
var URL_ROOT = "http://140.221.84.142/objects/coexpr_test/Networks";
var WS_URL = "http://kbase.us/services/workspace_service/";
var GO_URL_TEMPLATE = "http://www.ebi.ac.uk/QuickGO/GTerm?id=<%= id %>";
return KBWidget({
name: "ForceDirectedNetwork",
version: "0.1.0",
options: {
minHeight: "300px",
minStrength: 0.7
},
init: function (options) {
this._super(options);
this.render();
return this;
},
render: function () {
var self = this;
var fetchAjax = function () {
return 1;
};
if (self.options.minHeight) {
self.$elem.css("min-height", self.options.minHeight);
}
if (self.options.workspaceID === undefined) {
fetchAjax = self.exampleData();
} else if (self.options.token) {
$.ajaxSetup({ cache: true });
var wsRegex = /^(\w+)\.(.+)/;
var wsid = wsRegex.exec(self.options.workspaceID);
if (wsid !== null && wsid[1] && wsid[2]) {
var kbws = new workspaceService(WS_URL);
fetchAjax = kbws.get_object({
auth: self.options.token,
workspace: wsid[1],
id: wsid[2],
type: 'Networks'
});
} else {
self.trigger("error", ["Cannot parse workspace ID " +
self.options.workspaceID
]);
return self;
}
} else {
fetchAjax = $.ajax({
dataType: "json",
url: URL_ROOT + "/" + encodeURIComponent(self.options.workspaceID) + ".json"
});
}
KBVis.require(["jquery", "underscore", "renderers/network",
"util/viewport", "text!sample-data/network1.json",
"transformers/netindex", "util/slider", "util/progress",
"text!templates/checkbox.html",
"text!templates/error-alert.html",
"jquery-ui"
],
function (
JQ, _, Network, Viewport, Example, NetIndex, Slider,
Progress, CheckboxTemplate, ErrorTemplate
) {
Example = JSON.parse(Example);
var minStrength = 0.7;
var viewport = new Viewport({
parent: self.$elem,
title: "Network",
maximize: true
});
viewport.css("min-height", "600px");
var datasetFilter = function () {
return true;
};
var goLink = _.template(GO_URL_TEMPLATE);
var network = new Network({
element: viewport,
dock: false,
infoOn: "hover",
edgeFilter: function (edge) {
return edge.source != edge.target &&
(edge.strength >= minStrength ||
edge.source.type === "CLUSTER" ||
edge.target.type === "CLUSTER") &&
datasetFilter(edge);
},
nodeInfo: function (node, makeRow) {
makeRow("Type", node.type);
makeRow("KBase ID", link(node.entityId, "#"));
if (node.type === "GENE" && node.userAnnotations !== undefined) {
var annotations = node.userAnnotations;
if (annotations["external_id"] !== undefined)
makeRow("External ID",
link(annotations["external_id"], "#"));
if (annotations["functions"] !== undefined)
makeRow("Function", annotations["functions"]);
if (annotations.ontologies !== undefined) {
var goList = JQ("<ul/>");
_.each(_.keys(annotations.ontologies), function (item) {
goList.append(JQ("<li/>")
.append(link(item, goLink({
id: item
}))));
});
makeRow("GO terms", goList);
}
}
},
searchTerms: function (node, indexMe) {
indexMe(node.entityId);
indexMe(node.kbid);
if (node.userAnnotations !== undefined) {
var annotations = node.userAnnotations;
if (annotations["functions"] !== undefined)
indexMe(annotations["functions"]);
}
}
});
viewport.renderer(network);
forceSlider(viewport, "charge", "Node charge",
JQ("<i>", { class: "icon-magnet" }), 5);
forceSlider(viewport, "distance", "Edge distance",
JQ("<i>", { class: "icon-resize-horizontal" }));
forceSlider(viewport, "strength", "Edge strength",
JQ("<span>", { class: "glyphicon glyphicon-link" }),
0.015);
forceSlider(viewport, "gravity", "Gravity", "G", 0.012);
var toolbox = viewport.toolbox();
addSlider(toolbox);
addSearch(toolbox);
var progress = new Progress({
type: Progress.SPIN,
element: viewport
});
progress.show();
JQ.when(fetchAjax).done(function (result) {
var maxGenes = 300;
var geneCounter = 0;
var data = NetIndex(result.data, {
maxEdges: 100000
});
progress.dismiss();
try {
network.setData(data);
} catch (error) {
JQ(self.$elem)
.prepend(_.template(ErrorTemplate, error));
return;
}
network.render();
addDatasetDropdown(toolbox, data);
addClusterDropdown(toolbox, data);
});
function forceSlider(
viewport, property, title, label, factor) {
if (factor === undefined)
factor = 1;
viewport.addTool((new Slider({
title: title,
label: label,
value: 0,
min: -10,
max: 10,
step: 1,
slide: function (value) {
network.forceDelta(property, value * factor);
network.update();
}
})).element());
}
function addSlider($container) {
var slider = new Slider({
label: JQ("<i>", {
class: "icon-adjust"
}),
title: "Minimum edge strength",
min: 0,
max: 1,
step: 0.01,
value: 0.8,
slide: function (value) {
minStrength = value;
network.update();
}
});
$container.prepend(JQ("<div>", {
class: "btn btn-default tool"
})
.append(JQ("<div>", {
class: "btn-pad"
})
.append(slider.element())
));
}
function addSearch($container) {
var wrapper = JQ("<div>", {
class: "btn btn-default tool"
});
wrapper
.append(JQ("<div>", { class: "btn-pad" })
.append(JQ("<input/>", {
id: "network-search",
type: "text",
class: "input-xs"
}))
).append(JQ("<div/>", { class: "btn-pad" })
.append(JQ("<i/>", { class: "icon-search" })));
$container.prepend(wrapper);
JQ("#network-search").keyup(function () {
network.updateSearch(JQ(this).val());
});
}
function addClusterDropdown($container, data) {
var list = JQ("<fieldset>");
var menu = JQ("<ul>", {
class: "dropdown-menu",
role: "menu"
})
.append(JQ("<li>").append(list));
var allClusters = dropdownCheckbox("all", "All clusters", true);
var allCheckbox = allClusters.find("input");
allClusters.css("background-color", "#666").css("color", "#fff");
list.append(allClusters);
var clusters = [];
// A bit of a Schwartzian Transform to sort by neighbors
_.map(
_.filter(data.nodes, function (n) {
return n.type === "CLUSTER";
}),
function (node) {
clusters.push({
node: node,
neighbors: network.neighbors(node).length
});
}
);
_.each(_.sortBy(clusters,
function (entry) {
return -entry.neighbors;
}),
function (entry) {
var box = dropdownCheckbox(entry.node.id, "", true);
var labelDiv = JQ("<div>", {
style: "min-width:120px"
})
.append(
JQ("<span>", {
style: "float: left"
})
.html(entry.node.entityId)
).append(
JQ("<span>", {
style: "float:right;color:#aaa"
})
.html("N:" + entry.neighbors)
);
box.children("label").first().append(labelDiv);
list.append(box);
}
);
list.find("label").click(function (event) {
event.preventDefault();
});
list.find("input[type='checkbox']").click(function (event) {
// Prevent menu from closing on checkbox
event.stopPropagation();
var box = JQ(this);
var id = box.val();
var checked = box.prop("checked");
var clSelect = "input[type='checkbox'][value!='all']";
if (id === "all") {
list.find(clSelect)
.prop("checked", checked)
.trigger("change");
} else {
if (list.find(clSelect + ":not(:checked)").length === 0)
allCheckbox.prop("checked", true);
else
allCheckbox.prop("checked", false);
}
}).change(function (event) {
var id = JQ(this).val();
var checked = JQ(this).prop("checked");
if (id === "all")
return;
var node = network.findNode(id);
if (node === null) {
self.$elem.prepend(_.template(ErrorTemplate, {
message: "Could not find node " + id
}));
return;
}
network.pause();
if (checked) {
unhideCluster(node);
} else {
hideCluster(node);
}
network.resume();
});
var button = JQ("<div>", {
class: "btn btn-default btn-sm dropdown-toggle",
"data-toggle": "dropdown"
}).text("Clusters ").append(JQ("<span/>", {
class: "caret"
}))
.dropdown();
$container.prepend(JQ("<div>", {
class: "btn-group tool"
})
.append(button)
.append(menu)
);
}
function unhideCluster(cluster) {
network.unhideNode(cluster);
var neighbors = network.neighbors(cluster, null);
_.each(neighbors, function (nPair) {
var node = nPair[0];
if (node.type === 'GENE')
network.unhideNode(node);
});
}
function hideCluster(cluster) {
var neighbors = network.neighbors(cluster);
_.each(neighbors, function (nPair) {
var node = nPair[0];
if (node.type === 'GENE')
network.hideNode(node);
})
network.hideNode(cluster);
}
function addDatasetDropdown($container, data) {
var wrapper = JQ("<div>", {
class: "btn-group tool"
});
var list = JQ("<ul>", {
class: "dropdown-menu",
role: "menu"
});
list.append(dropdownLink("All data sets", "", "all"));
_.each(data.datasets, function (ds) {
var dsStr = ds.id.replace(/^kb.*\.ws\/\//, "");
list.append(dropdownLink(dsStr, ds.description, ds.id));
});
list.find("a").on("click", function (event) {
var id = JQ(this).data("value");
list.find("li").removeClass("active");
JQ(this).parent().addClass("active");
if (id == "all")
datasetFilter = function () {
return true;
};
else
datasetFilter = function (edge) {
return edge.datasetId == id;
};
network.update();
});
var button = JQ("<div/>", {
class: "btn btn-default btn-sm dropdown-toggle",
"data-toggle": "dropdown"
}).text("Data Set ").append(JQ("<span/>", {
class: "caret"
}))
.dropdown();
wrapper
.append(button)
.append(list);
$container.prepend(wrapper);
}
function dropdownLink(linkText, title, value) {
return JQ("<li>")
.append(JQ("<a>", {
href: "#",
"data-toggle": "tooltip",
"data-container": "body",
"title": title,
"data-original-title": title,
"data-value": value
}).append(linkText));
}
function dropdownCheckbox(value, label, checked) {
return JQ("<div>", {
class: "dropdown-menu-item"
})
.append(_.template(CheckboxTemplate, {
label: label,
value: value,
checked: checked
}));
}
function link(content, href, attrs) {
return JQ("<a>", _.extend({
href: href
}, attrs)).html(content);
}
});
return self;
},
exampleData: function () {
return {
data: {
nodes: [{
type: "GENE",
id: "kb|netnode.0",
userAnnotations: {
external_id: "Athaliana.TAIR10:AT2G15410",
functions: "transposable element gene.[Source:TAIR;Acc:AT2G15410]"
},
entityId: "kb|g.3899.locus.10011"
}, {
type: "GENE",
id: "kb|netnode.1",
userAnnotations: {
ontologies: {
"GO:0006468": [{
ec: "IEA",
desc: "protein phosphorylation",
domain: "biological_process"
}]
},
external_id: "Athaliana.TAIR10:AT1G32320",
functions: "MAP kinase kinase 10 [Source:EMBL;Acc:AEE31463.1]"
},
entityId: "kb|g.3899.locus.3560"
}, {
type: "GENE",
id: "kb|netnode.2",
userAnnotations: {
external_id: "Athaliana.TAIR10:AT2G21600",
functions: "protein RER1B [Source:EMBL;Acc:AEC07201.1]"
},
entityId: "kb|g.3899.locus.10793"
}, {
type: "CLUSTER",
id: "kb|netnode.3",
userAnnotations: {},
entityId: "cluster.1\n"
}, {
type: "CLUSTER",
id: "kb|netnode.4",
userAnnotations: {},
entityId: "cluster.2\n"
}],
edges: [{
nodeId2: "kb|netnode.0",
nodeId1: "kb|netnode.3",
id: "kb|netedge.0",
name: "interacting gene pair",
strength: "0.7",
datasetId: "kb|netdataset.ws//DataSet1",
directed: "false",
userAnnotations: {},
}, {
nodeId2: "kb|netnode.0",
nodeId1: "kb|netnode.4",
id: "kb|netedge.0",
name: "interacting gene pair",
strength: "1",
datasetId: "kb|netdataset.ws//DataSet1",
directed: "false",
userAnnotations: {},
}, {
nodeId2: "kb|netnode.1",
nodeId1: "kb|netnode.4",
id: "kb|netedge.0",
name: "interacting gene pair",
strength: "0.9",
datasetId: "kb|netdataset.ws//DataSet1",
directed: "false",
userAnnotations: {},
}, {
nodeId2: "kb|netnode.2",
nodeId1: "kb|netnode.4",
id: "kb|netedge.0",
name: "interacting gene pair",
strength: "0.85",
datasetId: "kb|netdataset.ws//DataSet1",
directed: "false",
userAnnotations: {},
}, {
nodeId2: "kb|netnode.1",
nodeId1: "kb|netnode.3",
id: "kb|netedge.0",
name: "interacting gene pair",
strength: "0.65",
datasetId: "kb|netdataset.ws//DataSet1",
directed: "false",
userAnnotations: {},
}],
datasets: [{
properties: {
original_data_type: "workspace",
coex_net_args: "-i datafiltered.csv -o edge_list.csv -c 0.75 ",
original_data_id: "ws://DataSet1",
coex_filter_args: "-i data.csv -s sample.csv -o datafiltered.csv -m anova -n 100"
},
description: "Data Set description",
id: "kb|netdataset.ws//DataSet1",
name: "First Data Set",
taxons: ["kb|g.3899"],
sourceReference: "WORKSPACE",
networkType: "FUNCTIONAL_ASSOCIATION"
}, ]
}
};
}
});
});
|
//js todo/scripts/build.js
load("steal/rhino/rhino.js");
steal('steal/build').then('steal/build/scripts','steal/build/styles',function(){
steal.build('todo/scripts/build.html',{to: 'todo'});
});
|
import $ from "jquery"
import "bootstrap-sass"
$("#modal-result-form").on("show.bs.modal", function (event) {
const $button = $(event.relatedTarget)
const participantNames = $button.data("participant-names")
const appearanceIds = $button.data("appearance-ids")
const currentPoints = $button.data("current-points")
const $modal = $(this)
$modal.find("#participant-names").text(participantNames)
$modal.find("#appearance-ids").val(appearanceIds)
$modal.find("#results_points").val(currentPoints)
})
$("#modal-result-form").on("shown.bs.modal", function () {
$(this).find("#results_points").focus()
})
|
const assert = require('assert');
const setup = require('../setup.js');
module.exports = () => {
describe('observeMany', () => {
it('fires once per set, however many properties change', () => {
const { component, target } = setup(`{foo} {bar}`, { foo: 1, bar: 2 });
const observed = [];
component.observeMany(['foo', 'bar'], (n, o) => {
observed.push([o, n, target.innerHTML]);
});
component.set({ foo: 3, bar: 4 });
component.set({ foo: 5 });
component.set({ bar: 6 });
assert.deepEqual(observed, [
[[undefined, undefined], [1, 2], '1 2'],
[[1, 2], [3, 4], '1 2'],
[[3, 4], [5, 4], '3 4'],
[[5, 4], [5, 6], '5 4']
]);
});
it('respects init: false', () => {
const { component, target } = setup(`{foo} {bar}`, { foo: 1, bar: 2 });
const observed = [];
component.observeMany(['foo', 'bar'], (n, o) => {
observed.push([o, n, target.innerHTML]);
}, {
init: false
});
component.set({ foo: 3, bar: 4 });
assert.deepEqual(observed, [
[[1, 2], [3, 4], '1 2']
]);
});
it('respects defer: true', () => {
const { component, target } = setup(`{foo} {bar}`, { foo: 1, bar: 2 });
const observed = [];
component.observeMany(['foo', 'bar'], (n, o) => {
observed.push([o, n, target.innerHTML]);
}, {
defer: true
});
component.set({ foo: 3, bar: 4 });
assert.deepEqual(observed, [
[[undefined, undefined], [1, 2], '1 2'],
[[1, 2], [3, 4], '3 4']
]);
});
});
}; |
var uri=location.protocol+"//"+location.hostname+"/users/userMemesJSON?username="+$(".user-profile-userpage h2").text()+"&order=";var correctHash=["top","comments","date"];var fillTable=function(a){var b="";$.each(a,function(c,d){b+='<tr><td><a href="'+location.protocol+"//"+location.hostname+"/meme/"+d.Id+'">'+d.Title+"</a></td><td>"+profile_spicelevel+": "+d.Points+"</td><td> "+profile_comments+': <a href="'+location.protocol+"//"+location.hostname+"/meme/"+d.Id+'"><span class="badge">'+d.comments+"</span></a></td><td>"+profile_addedon+": "+d.Date+"</td></tr>"});$(".uploads-userpage table tbody").html(b)};var getUserMemeData=function(a){$.ajax({type:"GET",dataType:"json",url:uri+a,success:function(b){location.hash=a;fillTable(b)}})};$(document).ready(function(){var a=location.hash.slice(1);if($.inArray(a,correctHash)>-1){getUserMemeData(a)}$(".sort").click(function(b){b.preventDefault();getUserMemeData($(this).attr("data-sortby"))})}); |
(function () {
"use strict";
/**
* Keep track of all pointers and keys.
* @namespace HYPER.Input
*/
HYPER.Input = {};
/**
* Keep track of all pointers.
* @namespace HYPER.Input.Pointer
*/
HYPER.Input.Pointer = {
/**
* @property {array} point - Array for all ten pointer objects.
*/
point: [],
/**
* Returns a pointer object, leave blank for a basic mouse.
* @method HYPER.Input.Pointer.getPointer
* @param {number} ID - The ID of the pointer you want.
*/
getPointer: function (ID) {
ID = ID || 0;
return this.point[ID];
},
/**
* Returns if a pointer is being clicked.
* @method HYPER.Input.Pointer.getClick
* @param {number} ID - The ID of the pointer you want.
*/
getClick: function (ID) {
ID = ID || 0;
return this.point[ID].click;
},
/**
* Returns if a pointer is being held.
* @method HYPER.Input.Pointer.getHold
* @param {number} ID - The ID of the pointer you want.
*/
getHold: function (ID) {
ID = ID || 0;
return this.point[ID].held;
},
/**
* Returns if a pointer is clicked Up.
* @method HYPER.Input.Pointer.getUp
* @param {number} ID - The ID of the pointer you want.
*/
getUp: function (ID) {
ID = ID || 0;
return this.point[ID].up;
},
/**
* Returns if a pointer is clicked Down.
* @method HYPER.Input.Pointer.getDown
* @param {number} ID - The ID of the pointer you want.
*/
getDown: function (ID) {
ID = ID || 0;
return this.point[ID].down;
},
/**
* Returns the position of the pointer on the page.
* @method HYPER.Input.Pointer.getPosition
* @param {number} ID - The ID of the pointer you want.
*/
getPosition: function (ID) {
ID = ID || 0;
return this.point[ID]
},
/**
* @property {object} _listeners - The event listeners for pointers.
*/
_listeners: {
/**
* Function to be called on the mouse move event.
* @method HYPER.Input.Pointer._listeners.mousemove
* @param {object} e - The info to be passed from the event.
*/
mousemove: function (e) {
// Prevent the default action from occurring.
e.preventDefault();
// Set the X coordinate of the click
HYPER.Input.Pointer.point[0]._x = e.pageX;
// Set the Y coordinate of the click
HYPER.Input.Pointer.point[0]._y = e.pageY;
},
/**
* Function to be called on the mouse down event.
* @method HYPER.Input.Pointer._listeners.mousedown
* @param {object} e - The info to be passed from the event.
*/
mousedown: function (e) {
// Prevent the default action from occurring.
e.preventDefault();
// Set the X coordinate of the click
HYPER.Input.Pointer.point[0]._x = e.pageX;
// Set the Y coordinate of the click
HYPER.Input.Pointer.point[0]._y = e.pageY;
// record that the click is being pressed down
HYPER.Input.Pointer.point[0]._down = true;
// record that the click is being held down
HYPER.Input.Pointer.point[0]._hold = true;
},
/**
* Function to be called on the mouse up event.
* @method HYPER.Input.Pointer._listeners.mouseup
* @param {object} e - The info to be passed from the event.
*/
mouseup: function (e) {
// Prevent the default action from occurring.
e.preventDefault();
// Set the X coordinate of the click
HYPER.Input.Pointer.point[0]._x = e.pageX;
// Set the Y coordinate of the click
HYPER.Input.Pointer.point[0]._y = e.pageY;
// record that the click is being pressed up
HYPER.Input.Pointer.point[0]._up = true;
// record that the click is no longer being pressed down
HYPER.Input.Pointer.point[0]._hold = false;
},
/**
* Function to be called on the touchmove event.
* @method HYPER.Input.Pointer._listeners.touchmove
* @param {object} e - The info to be passed from the event.
*/
touchmove: function (e) {
// Prevent the default action from occurring.
e.preventDefault();
// Set the X coordinate of the touchpoint
HYPER.Input.Pointer.point[e.which]._x = e.changedTouches[e.which].pageX;
// Set the Y coordinate of the touchpoint
HYPER.Input.Pointer.point[e.which]._y = e.changedTouches[e.which].pageY;
},
/**
* Function to be called on the touch start event.
* @method HYPER.Input.Pointer._listeners.touchstart
* @param {object} e - The info to be passed from the event.
*/
touchstart: function (e) {
// Prevent the default action from occurring.
e.preventDefault();
// Set the X coordinate of the touchpoint
HYPER.Input.Pointer.point[e.which]._x = e.changedTouches[e.which].pageX;
// Set the Y coordinate of the touchpoint
HYPER.Input.Pointer.point[e.which]._y = e.changedTouches[e.which].pageY;
// record that the touchpoint is being pressed down
HYPER.Input.Pointer.point[e.which]._down = true;
// record that the touchpoint is being held down
HYPER.Input.Pointer.point[e.which]._hold = true;
},
/**
* Function to be called on the touch end event.
* @method HYPER.Input.Pointer._listeners.touchend
* @param {object} e - The info to be passed from the event.
*/
touchend: function (e) {
// Prevent the default action from occurring.
e.preventDefault();
// Set the X coordinate of the touchpoint
HYPER.Input.Pointer.point[e.which]._x = e.changedTouches[e.which].pageX;
// Set the Y coordinate of the touchpoint
HYPER.Input.Pointer.point[e.which]._y = e.changedTouches[e.which].pageY;
// record that the touchpoint is being pressed up
HYPER.Input.Pointer.point[e.which]._up = true;
// record that the touchpoint is no longer being held down
HYPER.Input.Pointer.point[e.which]._hold = false;
},
/**
* Function to be called on any listerners you dont want to do anything.
* @method HYPER.Input.Pointer._listeners.preventDefault
* @param {object} e - The info to be passed from the event.
*/
preventDefault: function (e) {
e.preventDefault();
},
},
};
/**
* Keep track of all keys.
* @namespace HYPER.Input.Keys
*/
HYPER.Input.Keys = {
/**
* @property {array} key - Array of all key according to JavaScript Key Codes.
*/
key: [],
/**
* Returns a key object.
* @method HYPER.Input.Keys.getKey
* @param {string} letter - The key you are checking for.
*/
getKey: function (letter) {
letter = letter.toLocaleLowerCase();
if (letter === "backspace") {
return HYPER.Input.Keys.key[8];
}
if (letter === "tab") {
return HYPER.Input.Keys.key[9];
}
if (letter === "enter") {
return HYPER.Input.Keys.key[13];
}
if (letter === "shift") {
return HYPER.Input.Keys.key[16];
}
if (letter === "ctrl") {
return HYPER.Input.Keys.key[17];
}
if (letter === "alt") {
return HYPER.Input.Keys.key[18];
}
if (letter === "pause/break") {
return HYPER.Input.Keys.key[19];
}
if (letter === "caps lock") {
return HYPER.Input.Keys.key[20];
}
if (letter === "escape") {
return HYPER.Input.Keys.key[27];
}
if (letter === "page up") {
return HYPER.Input.Keys.key[33];
}
if (letter === "page down") {
return HYPER.Input.Keys.key[34];
}
if (letter === "end") {
return HYPER.Input.Keys.key[35];
}
if (letter === "home") {
return HYPER.Input.Keys.key[36];
}
if (letter === "left arrow") {
return HYPER.Input.Keys.key[37];
}
if (letter === "up arrow") {
return HYPER.Input.Keys.key[38];
}
if (letter === "right arrow") {
return HYPER.Input.Keys.key[39];
}
if (letter === "down arrow") {
return HYPER.Input.Keys.key[40];
}
if (letter === "space") {
return HYPER.Input.Keys.key[32];
}
if (letter === "insert") {
return HYPER.Input.Keys.key[45];
}
if (letter === "delete") {
return HYPER.Input.Keys.key[46];
}
if (letter === "0") {
return HYPER.Input.Keys.key[48];
}
if (letter === "1") {
return HYPER.Input.Keys.key[49];
}
if (letter === "2") {
return HYPER.Input.Keys.key[50];
}
if (letter === "3") {
return HYPER.Input.Keys.key[51];
}
if (letter === "4") {
return HYPER.Input.Keys.key[52];
}
if (letter === "5") {
return HYPER.Input.Keys.key[53];
}
if (letter === "6") {
return HYPER.Input.Keys.key[54];
}
if (letter === "7") {
return HYPER.Input.Keys.key[55];
}
if (letter === "8") {
return HYPER.Input.Keys.key[56];
}
if (letter === "9") {
return HYPER.Input.Keys.key[57];
}
if (letter === "a") {
return HYPER.Input.Keys.key[65];
}
if (letter === "b") {
return HYPER.Input.Keys.key[66];
}
if (letter === "c") {
return HYPER.Input.Keys.key[67];
}
if (letter === "d") {
return HYPER.Input.Keys.key[68];
}
if (letter === "e") {
return HYPER.Input.Keys.key[69];
}
if (letter === "f") {
return HYPER.Input.Keys.key[70];
}
if (letter === "g") {
return HYPER.Input.Keys.key[71];
}
if (letter === "h") {
return HYPER.Input.Keys.key[72];
}
if (letter === "i") {
return HYPER.Input.Keys.key[73];
}
if (letter === "j") {
return HYPER.Input.Keys.key[74];
}
if (letter === "k") {
return HYPER.Input.Keys.key[75];
}
if (letter === "l") {
return HYPER.Input.Keys.key[76];
}
if (letter === "m") {
return HYPER.Input.Keys.key[77];
}
if (letter === "n") {
return HYPER.Input.Keys.key[78];
}
if (letter === "o") {
return HYPER.Input.Keys.key[79];
}
if (letter === "p") {
return HYPER.Input.Keys.key[80];
}
if (letter === "q") {
return HYPER.Input.Keys.key[81];
}
if (letter === "r") {
return HYPER.Input.Keys.key[82];
}
if (letter === "s") {
return HYPER.Input.Keys.key[83];
}
if (letter === "t") {
return HYPER.Input.Keys.key[84];
}
if (letter === "u") {
return HYPER.Input.Keys.key[85];
}
if (letter === "v") {
return HYPER.Input.Keys.key[86];
}
if (letter === "w") {
return HYPER.Input.Keys.key[87];
}
if (letter === "x") {
return HYPER.Input.Keys.key[88];
}
if (letter === "y") {
return HYPER.Input.Keys.key[89];
}
if (letter === "z") {
return HYPER.Input.Keys.key[90];
}
if (letter === "left window key") {
return HYPER.Input.Keys.key[91];
}
if (letter === "right window key") {
return HYPER.Input.Keys.key[92];
}
if (letter === "select key") {
return HYPER.Input.Keys.key[93];
}
if (letter === "numpad 0") {
return HYPER.Input.Keys.key[96];
}
if (letter === "numpad 1") {
return HYPER.Input.Keys.key[97];
}
if (letter === "numpad 2") {
return HYPER.Input.Keys.key[98];
}
if (letter === "numpad 3") {
return HYPER.Input.Keys.key[99];
}
if (letter === "numpad 4") {
return HYPER.Input.Keys.key[100];
}
if (letter === "numpad 5") {
return HYPER.Input.Keys.key[101];
}
if (letter === "numpad 6") {
return HYPER.Input.Keys.key[102];
}
if (letter === "numpad 7") {
return HYPER.Input.Keys.key[103];
}
if (letter === "numpad 8") {
return HYPER.Input.Keys.key[104];
}
if (letter === "numpad 9") {
return HYPER.Input.Keys.key[105];
}
if (letter === "multiply") {
return HYPER.Input.Keys.key[106];
}
if (letter === "add") {
return HYPER.Input.Keys.key[107];
}
if (letter === "subtract") {
return HYPER.Input.Keys.key[109];
}
if (letter === "decimal point") {
return HYPER.Input.Keys.key[110];
}
if (letter === "divide") {
return HYPER.Input.Keys.key[111];
}
if (letter === "f1") {
return HYPER.Input.Keys.key[112];
}
if (letter === "f2") {
return HYPER.Input.Keys.key[113];
}
if (letter === "f3") {
return HYPER.Input.Keys.key[114];
}
if (letter === "f4") {
return HYPER.Input.Keys.key[115];
}
if (letter === "f5") {
return HYPER.Input.Keys.key[116];
}
if (letter === "f6") {
return HYPER.Input.Keys.key[117];
}
if (letter === "f7") {
return HYPER.Input.Keys.key[118];
}
if (letter === "f8") {
return HYPER.Input.Keys.key[119];
}
if (letter === "f9") {
return HYPER.Input.Keys.key[120];
}
if (letter === "f10") {
return HYPER.Input.Keys.key[121];
}
if (letter === "f11") {
return HYPER.Input.Keys.key[122];
}
if (letter === "f12") {
return HYPER.Input.Keys.key[123];
}
if (letter === "num lock") {
return HYPER.Input.Keys.key[144];
}
if (letter === "scroll lock") {
return HYPER.Input.Keys.key[145];
}
if (letter === "semi-colon") {
return HYPER.Input.Keys.key[186];
}
if (letter === "equal sign") {
return HYPER.Input.Keys.key[187];
}
if (letter === "comma") {
return HYPER.Input.Keys.key[188];
}
if (letter === "dash") {
return HYPER.Input.Keys.key[189];
}
if (letter === "period") {
return HYPER.Input.Keys.key[190];
}
if (letter === "forward slash") {
return HYPER.Input.Keys.key[191];
}
if (letter === "grave accent") {
return HYPER.Input.Keys.key[192];
}
if (letter === "open bracket") {
return HYPER.Input.Keys.key[219];
}
if (letter === "back slash") {
return HYPER.Input.Keys.key[220];
}
if (letter === "close braket") {
return HYPER.Input.Keys.key[221];
}
if (letter === "single quote") {
return HYPER.Input.Keys.key[222];
}
},
getKeyFromID: function (ID) {
if (ID === 8) {
return "backspace";
}
if (ID === 9) {
return "tab";
}
if (ID === 13) {
return "enter";
}
if (ID === 16) {
return "shift";
}
if (ID === 17) {
return "ctrl";
}
if (ID === 18) {
return "alt";
}
if (ID === 19) {
return "pause/break";
}
if (ID === 20) {
return "caps lock";
}
if (ID === 27) {
return "escape";
}
if (ID === 33) {
return "page up";
}
if (ID === 34) {
return "page down";
}
if (ID === 35) {
return "end";
}
if (ID === 36) {
return "home";
}
if (ID === 37) {
return "left arrow";
}
if (ID === 38) {
return "up arrow";
}
if (ID === 39) {
return "right arrow";
}
if (ID === 40) {
return "down arrow";
}
if (ID === 32) {
return "space";
}
if (ID === 45) {
return "insert";
}
if (ID === 46) {
return "delete";
}
if (ID === 48) {
return "0";
}
if (ID === 49) {
return "1";
}
if (ID === 50) {
return "2";
}
if (ID === 51) {
return "3";
}
if (ID === 52) {
return "4";
}
if (ID === 53) {
return "5";
}
if (ID === 54) {
return "6";
}
if (ID === 55) {
return "7";
}
if (ID === 56) {
return "8";
}
if (ID === 57) {
return "9";
}
if (ID === 65) {
return "a";
}
if (ID === 66) {
return "b";
}
if (ID === 67) {
return "c";
}
if (ID === 68) {
return "d";
}
if (ID === 69) {
return "e";
}
if (ID === 70) {
return "f";
}
if (ID === 71) {
return "g";
}
if (ID === 72) {
return "h";
}
if (ID === 73) {
return "i";
}
if (ID === 74) {
return "j";
}
if (ID === 75) {
return "k";
}
if (ID === 76) {
return "l";
}
if (ID === 77) {
return "m";
}
if (ID === 78) {
return "n";
}
if (ID === 79) {
return "o";
}
if (ID === 80) {
return "p";
}
if (ID === 81) {
return "q";
}
if (ID === 82) {
return "r";
}
if (ID === 83) {
return "s";
}
if (ID === 84) {
return "t";
}
if (ID === 85) {
return "u";
}
if (ID === 86) {
return "v";
}
if (ID === 87) {
return "w";
}
if (ID === 88) {
return "x";
}
if (ID === 89) {
return "y";
}
if (ID === 90) {
return "z";
}
if (ID === 91) {
return "left window key";
}
if (ID === 92) {
return "right window key";
}
if (ID === 93) {
return "select key";
}
if (ID === 96) {
return "numpad 0";
}
if (ID === 97) {
return "numpad 1";
}
if (ID === 98) {
return "numpad 2";
}
if (ID === 99) {
return "numpad 3";
}
if (ID === 100) {
return "numpad 4";
}
if (ID === 101) {
return "numpad 5";
}
if (ID === 102) {
return "numpad 6";
}
if (ID === 103) {
return "numpad 7";
}
if (ID === 104) {
return "numpad 8";
}
if (ID === 105) {
return "numpad 9";
}
if (ID === 106) {
return "multiply";
}
if (ID === 107) {
return "add";
}
if (ID === 109) {
return "subtract";
}
if (ID === 110) {
return "decimal point";
}
if (ID === 111) {
return "divide";
}
if (ID === 112) {
return "f1";
}
if (ID === 113) {
return "f2";
}
if (ID === 114) {
return "f3";
}
if (ID === 115) {
return "f4";
}
if (ID === 116) {
return "f5";
}
if (ID === 117) {
return "f6";
}
if (ID === 118) {
return "f7";
}
if (ID === 119) {
return "f8";
}
if (ID === 120) {
return "f9";
}
if (ID === 121) {
return "f10";
}
if (ID === 122) {
return "f11";
}
if (ID === 123) {
return "f12";
}
if (ID === 144) {
return "num lock";
}
if (ID === 145) {
return "scroll lock";
}
if (ID === 186) {
return "semi-colon";
}
if (ID === 187) {
return "equal sign";
}
if (ID === 188) {
return "comma";
}
if (ID === 189) {
return "dash";
}
if (ID === 190) {
return "period";
}
if (ID === 191) {
return "forward slash";
}
if (ID === 192) {
return "grave accent";
}
if (ID === 219) {
return "open bracket";
}
if (ID === 220) {
return "back slash";
}
if (ID === 221) {
return "close braket";
}
if (ID === 222) {
return "single quote";
}
},
/**
* @private
* @property {object} _listeners - The event listeners for keys.
*/
_listeners: {
/**
* Event listener function that fires when a key is lifted.
* @method HYPER.Input.Keys._listeners.onkeyup
* @param {number}data - pointer data of the click.
*/
onkeyup: function (e) {
// record that you are lifting up.
HYPER.Input.Keys.key[e.which]._up = true;
// sets the hold value to false
HYPER.Input.Keys.key[e.which]._hold = false;
},
/**
* Event listener function that fires when a key is pushed.
* @method HYPER.Input.Keys._listeners.onkeydown
* @param {number}data - pointer data of the click.
*/
onkeydown: function (e) {
// record that you are pressing down
HYPER.Input.Keys.key[e.which]._down = true;
// sets the hold value to true
HYPER.Input.Keys.key[e.which]._hold = true;
},
},
};
/**
Initilize all the event listeners that will be used
*/
HYPER.Input._addEventListeners = function () {
// check to see if mobile.
if (mobileAndTabletcheck()) {
// Init the touchmove listener
document.addEventListener("touchmove", HYPER.Input.Pointer._listeners.touchmove);
// Init the touchstart listener
document.addEventListener("touchstart", HYPER.Input.Pointer._listeners.touchstart);
// Init the touchend listener
document.addEventListener("touchend", HYPER.Input.Pointer._listeners.touchend);
// Init the touchcancel listener
document.addEventListener("touchcancel", HYPER.Input.Pointer._listeners.touchend);
} else {
// Init the mousemove listener
document.addEventListener("mousemove", HYPER.Input.Pointer._listeners.mousemove);
// Init the mousedown listener
document.addEventListener("mousedown", HYPER.Input.Pointer._listeners.mousedown);
// Init the mouseup listener
document.addEventListener("mouseup", HYPER.Input.Pointer._listeners.mouseup);
}
// Init the keydown listener
window.addEventListener("keydown", HYPER.Input.Keys._listeners.onkeydown);
// Init the keyup listener
window.addEventListener("keyup", HYPER.Input.Keys._listeners.onkeyup);
// set drag to prevent default to smooth out game.
window.addEventListener("drag", HYPER.Input.Pointer._listeners.preventDefault);
};
HYPER.Input.screens = [];
HYPER.Input.addScreen = function (screen) {
HYPER.Input.screens.push(screen);
};
HYPER.Input.updateInput = function () {
for (var i = 0; i < 1; i++) {
HYPER.Input.Pointer.point[i].x = HYPER.Input.Pointer.point[i]._x;
HYPER.Input.Pointer.point[i].y = HYPER.Input.Pointer.point[i]._y;
HYPER.Input.Pointer.point[i].up = HYPER.Input.Pointer.point[i]._up;
HYPER.Input.Pointer.point[i].down = HYPER.Input.Pointer.point[i]._down;
HYPER.Input.Pointer.point[i].hold = HYPER.Input.Pointer.point[i]._hold;
HYPER.Input.Pointer.point[i].dblclick = HYPER.Input.Pointer.point[i]._dblclick;
HYPER.Input.Pointer.point[i].click = HYPER.Input.Pointer.point[i]._up;
HYPER.Input.Pointer.point[i]._up = false;
HYPER.Input.Pointer.point[i]._down = false;
HYPER.Input.Pointer.point[i]._dblclick = false;
for (var s = 0; s < HYPER.Input.screens.length; s++) {
if (HYPER.Input.Pointer.point[i].x > HYPER.Input.screens[s].canvas.offsetLeft &&
HYPER.Input.Pointer.point[i].y > HYPER.Input.screens[s].canvas.offsetTop &&
HYPER.Input.Pointer.point[i].x < HYPER.Input.screens[s].canvas.offsetLeft + HYPER.Input.screens[s].view.width &&
HYPER.Input.Pointer.point[i].y < HYPER.Input.screens[s].canvas.offsetTop + HYPER.Input.screens[s].view.height) {
HYPER.Input.screens[s]._onHover(i);
if (HYPER.Input.Pointer.point[i].click) {
HYPER.Input.screens[s]._onClick(i);
}
if (HYPER.Input.Pointer.point[i].up) {
HYPER.Input.screens[s]._onUp(i);
}
if (HYPER.Input.Pointer.point[i].down) {
HYPER.Input.screens[s]._onDown(i);
}
if (HYPER.Input.Pointer.point[i].hold) {
HYPER.Input.screens[s]._onHold(i);
}
if (HYPER.Input.Pointer.point[i].dblclick) {
HYPER.Input.screens[s]._onDblClick(i);
}
}
}
};
for (var i = 0; i < 222; i++) {
HYPER.Input.Keys.key[i].up = HYPER.Input.Keys.key[i]._up;
HYPER.Input.Keys.key[i].down = HYPER.Input.Keys.key[i]._down;
HYPER.Input.Keys.key[i].hold = HYPER.Input.Keys.key[i]._hold;
HYPER.Input.Keys.key[i]._up = false;
HYPER.Input.Keys.key[i]._down = false;
for (var s = 0; s < HYPER.Input.screens.length; s++) {
if (HYPER.Input.Keys.key[i].up) {
HYPER.Input.screens[s]._onKeyUp(HYPER.Input.Keys.getKeyFromID(i));
}
if (HYPER.Input.Keys.key[i].down) {
HYPER.Input.screens[s]._onKeyDown(HYPER.Input.Keys.getKeyFromID(i));
}
if (HYPER.Input.Keys.key[i].hold) {
HYPER.Input.screens[s]._onKeyHeld(HYPER.Input.Keys.getKeyFromID(i));
}
}
};
};
/**
Initilize the Input module.
*/
HYPER.Input.init = function () {
for (var i = 0; i < 10; i++) {
HYPER.Input.Pointer.point[i] = {
x: 0,
y: 0,
up: false,
down: false,
hold: false,
dblclick: false,
_x: 0,
_y: 0,
_up: false,
_down: false,
_hold: false,
_dblclick: false,
};
};
for (var i = 0; i < 300; i++) {
if (!HYPER.Input.Keys.key[i]) {
HYPER.Input.Keys.key[i] = {
_up: false,
_down: false,
_hold: false,
up: false,
down: false,
hold: false,
_ID: i,
};
}
HYPER.Input.Keys.key[i].up = HYPER.Input.Keys.key[i]._up;
HYPER.Input.Keys.key[i].down = HYPER.Input.Keys.key[i]._down;
HYPER.Input.Keys.key[i].hold = HYPER.Input.Keys.key[i]._hold;
HYPER.Input.Keys.key[i]._up = false;
HYPER.Input.Keys.key[i]._down = false;
};
HYPER.Input._addEventListeners();
HYPER.Timer.addOnTick(HYPER.Input.updateInput);
};
})(); |
import Vue from 'vue';
import SidebarMediator from '~/sidebar/sidebar_mediator';
import SidebarStore from '~/sidebar/stores/sidebar_store';
import SidebarService from '~/sidebar/services/sidebar_service';
import Mock from './mock_data';
describe('Sidebar mediator', () => {
beforeEach(() => {
Vue.http.interceptors.push(Mock.sidebarMockInterceptor);
this.mediator = new SidebarMediator(Mock.mediator);
});
afterEach(() => {
SidebarService.singleton = null;
SidebarStore.singleton = null;
SidebarMediator.singleton = null;
});
it('assigns yourself ', () => {
this.mediator.assignYourself();
expect(this.mediator.store.currentUser).toEqual(Mock.mediator.currentUser);
expect(this.mediator.store.assignees[0]).toEqual(Mock.mediator.currentUser);
});
it('saves assignees', (done) => {
this.mediator.saveAssignees('issue[assignee_ids]')
.then((resp) => {
expect(resp.status).toEqual(200);
done();
})
.catch(() => {});
});
it('fetches the data', () => {
spyOn(this.mediator.service, 'get').and.callThrough();
this.mediator.fetch();
expect(this.mediator.service.get).toHaveBeenCalled();
});
});
|
define({
"addTaskTip": "Adicione um ou mais filtros no widget e configure parâmetros para cada um deles.",
"enableMapFilter": "Remover filtro de camada pré-configurado do mapa.",
"newFilter": "Novo Filtro",
"filterExpression": "Expressão de filtro",
"layerDefaultSymbolTip": "Utilizar símbolo padrão da camada",
"uploadImage": "Carregar uma Imagem",
"selectLayerTip": "Selecione uma camada.",
"setTitleTip": "Configure um título."
}); |
'use strict';
/**
* Module dependencies
*/
var fbMarketingsPolicy = require('../policies/fb-marketings.server.policy'),
fbMarketings = require('../controllers/fb-marketings.server.controller');
module.exports = function(app) {
// Fb marketings Routes
app.route('/api/fb-marketings').all(fbMarketingsPolicy.isAllowed)
.get(fbMarketings.list)
.post(fbMarketings.create);
app.route('/api/fb-marketings/:fbMarketingId').all(fbMarketingsPolicy.isAllowed)
.get(fbMarketings.read)
.put(fbMarketings.update)
.delete(fbMarketings.delete);
// Finish by binding the Fb marketing middleware
app.param('fbMarketingId', fbMarketings.fbMarketingByID);
};
|
export const notify = (msg, style) => {
const $callout = $(`
<div class="callout ${style || ''}">
<p>${msg}</p>
</div>
`);
$('#notifications').append($callout);
window.setTimeout(() => $callout.remove(), 3000);
};
export const success = (msg) => notify(msg, "success");
export const info = (msg) => notify(msg, "info");
export const warning = (msg) => notify(msg, "alert");
|
/**
* @file Structure Builder
* @author Alexander Rose <alexander.rose@weirdbyte.de>
* @private
*/
function StructureBuilder (structure) {
let currentModelindex = null
let currentChainid = null
let currentResname = null
let currentResno = null
let currentInscode = null
let currentHetero = null
let previousResname
let previousHetero
const atomStore = structure.atomStore
const residueStore = structure.residueStore
const chainStore = structure.chainStore
const modelStore = structure.modelStore
const residueMap = structure.residueMap
let ai = -1
let ri = -1
let ci = -1
let mi = -1
function addResidueType (ri) {
const count = residueStore.atomCount[ ri ]
const offset = residueStore.atomOffset[ ri ]
const atomTypeIdList = new Array(count)
for (let i = 0; i < count; ++i) {
atomTypeIdList[ i ] = atomStore.atomTypeId[ offset + i ]
}
residueStore.residueTypeId[ ri ] = residueMap.add(
previousResname, atomTypeIdList, previousHetero
)
}
this.addAtom = function (modelindex, chainname, chainid, resname, resno, hetero, sstruc, inscode) {
let addModel = false
let addChain = false
let addResidue = false
if (currentModelindex !== modelindex) {
addModel = true
addChain = true
addResidue = true
mi += 1
ci += 1
ri += 1
} else if (currentChainid !== chainid) {
addChain = true
addResidue = true
ci += 1
ri += 1
} else if (currentResno !== resno || currentResname !== resname || currentInscode !== inscode) {
addResidue = true
ri += 1
}
ai += 1
if (addModel) {
modelStore.growIfFull()
modelStore.chainOffset[ mi ] = ci
modelStore.chainCount[ mi ] = 0
modelStore.count += 1
chainStore.modelIndex[ ci ] = mi
}
if (addChain) {
chainStore.growIfFull()
chainStore.setChainname(ci, chainname)
chainStore.setChainid(ci, chainid)
chainStore.residueOffset[ ci ] = ri
chainStore.residueCount[ ci ] = 0
chainStore.count += 1
chainStore.modelIndex[ ci ] = mi
modelStore.chainCount[ mi ] += 1
residueStore.chainIndex[ ri ] = ci
}
if (addResidue) {
previousResname = currentResname
previousHetero = currentHetero
if (ri > 0) addResidueType(ri - 1)
residueStore.growIfFull()
residueStore.resno[ ri ] = resno
if (sstruc !== undefined) {
residueStore.sstruc[ ri ] = sstruc.charCodeAt(0)
}
if (inscode !== undefined) {
residueStore.inscode[ ri ] = inscode.charCodeAt(0)
}
residueStore.atomOffset[ ri ] = ai
residueStore.atomCount[ ri ] = 0
residueStore.count += 1
residueStore.chainIndex[ ri ] = ci
chainStore.residueCount[ ci ] += 1
}
atomStore.count += 1
atomStore.residueIndex[ ai ] = ri
residueStore.atomCount[ ri ] += 1
currentModelindex = modelindex
currentChainid = chainid
currentResname = resname
currentResno = resno
currentInscode = inscode
currentHetero = hetero
}
this.finalize = function () {
previousResname = currentResname
previousHetero = currentHetero
if (ri > -1) addResidueType(ri)
}
}
export default StructureBuilder
|
'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var pkg = require('../package.json');
var argv = require('yargs').argv;
var browserSync = require('browser-sync');
var browserSyncSpa = require('browser-sync-spa');
var util = require('util');
var proxyMiddleware = require('http-proxy-middleware');
function browserSyncInit (baseDir, browser) {
browser = browser === undefined ? 'default' : browser;
var routes = null;
if (baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
routes = {
'/bower_components': 'bower_components'
};
}
var server = {
baseDir: baseDir,
routes: routes
};
var proxyOptions = {
target: pkg.config.API_PROXY[(argv.proxy) ? argv.proxy : 'local'],
changeOrigin: true,
// logLevel: 'debug',
// onProxyReq: function (proxyReq, req, res) {
// console.log(proxyReq);
// }
};
server.middleware = proxyMiddleware('/api', proxyOptions);
browserSync.instance = browserSync.init({
startPath: '/',
server: server,
browser: browser
});
}
browserSync.use(browserSyncSpa({
selector: '[ng-app]'// Only needed for angular apps
}));
gulp.task('serve', ['watch'], function () {
browserSyncInit([path.join(conf.paths.tmp, '/serve'), conf.paths.favicons, conf.paths.src]);
});
gulp.task('serve:dist', ['build'], function () {
browserSyncInit(conf.paths.dist);
}); |
const _delete = require('../delete'); // eslint-disable-line no-underscore-dangle
const AWS = require('aws-sdk-mock');
/* global describe it expect sinon before after */
describe('delete.handler', () => {
before(() => {
AWS.mock('DynamoDB.DocumentClient', 'delete', (params, callback) => {
callback(null);
});
});
after(() => {
AWS.restore('DynamoDB.DocumentClient', 'delete');
});
it('should throw an exception on missing id', (done) => {
const callback = (error) => {
expect(error).to.be.instanceOf(Error);
done();
};
const pathParameters = { };
_delete.handler({ pathParameters }, null, callback);
});
it('should delete an object when keys are given', (done) => {
const callback = (error) => {
expect(error).to.be.null();
done();
};
const pathParameters = { id: 'key-a', timestamp: 1111 };
_delete.handler({ pathParameters }, null, callback);
});
});
|
var expect = require('chai').expect
, Server = require('../../../../..')
, setup = require('../../../../setup')
, teardown = require('../../../../teardown')
, Constants = require('jsr-constants')
, OK = Constants.OK.toString()
, create = require('jsr-client')
, client
, sender;
describe('jsr-server (tcp):', function() {
before(function(done) {
setup(function() {
client = create();
client.once('connect', function() {
sender = create();
sender.once('connect', done);
});
})
});
after(teardown);
it('should reply with error on bad args length (client pause)',
function(done) {
client.client.pause(5000, 'oops', function onReply(err, reply) {
function fn() {
throw err;
}
expect(fn).throws(Error);
expect(fn).throws(/unknown subcommand/i);
expect(fn).throws(/wrong number of arguments/i);
done();
});
}
);
it('should reply with error on bad timeout (client pause)',
function(done) {
client.client.pause('NaN', function onReply(err, reply) {
function fn() {
throw err;
}
expect(fn).throws(Error);
expect(fn).throws(/not an integer/i);
expect(fn).throws(/out of range/i);
done();
});
}
);
it('should ok on pause (client pause)',
function(done) {
var start = Date.now()
// don't want to slow the tests down too much
, timeout = 50;
client.client.pause(timeout, function onReply(err, reply) {
expect(err).to.eql(null);
expect(reply).to.eql(OK);
sender.ping(function onReply(err, reply) {
var diff = Date.now() - start;
expect(err).to.eql(null);
expect(reply).to.eql(Constants.PONG.toString());
expect(diff).to.be.gte(timeout);
done();
});
});
}
);
});
|
/*jshint newcap:false*/
import Ember from "ember-metal/core"; // Ember.lookup
import jQuery from "ember-views/system/jquery";
// import {expectAssertion} from "ember-metal/tests/debug_helpers";
import { forEach } from "ember-metal/enumerable_utils";
import run from "ember-metal/run_loop";
import Namespace from "ember-runtime/system/namespace";
import EmberView from "ember-views/views/view";
import _MetamorphView from "ember-views/views/metamorph_view";
import EmberHandlebars from "ember-handlebars";
import EmberObject from "ember-runtime/system/object";
import ObjectController from "ember-runtime/controllers/object_controller";
import { A } from "ember-runtime/system/native_array";
import { computed } from "ember-metal/computed";
import { fmt } from "ember-runtime/system/string";
import { typeOf } from "ember-metal/utils";
import ContainerView from "ember-views/views/container_view";
import { Binding } from "ember-metal/binding";
import { observersFor } from "ember-metal/observer";
import TextField from "ember-views/views/text_field";
import Container from "ember-runtime/system/container";
import { create as o_create } from "ember-metal/platform";
var trim = jQuery.trim;
import { get } from "ember-metal/property_get";
import { set } from "ember-metal/property_set";
function firstGrandchild(view) {
return get(get(view, 'childViews').objectAt(0), 'childViews').objectAt(0);
}
function nthChild(view, nth) {
return get(view, 'childViews').objectAt(nth || 0);
}
var firstChild = nthChild;
var originalLog, logCalls;
var caretPosition = function (element) {
var ctrl = element[0];
var caretPos = 0;
// IE Support
if (document.selection) {
ctrl.focus();
var selection = document.selection.createRange();
selection.moveStart('character', -ctrl.value.length);
caretPos = selection.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart === '0') {
caretPos = ctrl.selectionStart;
}
return caretPos;
};
var setCaretPosition = function (element, pos) {
var ctrl = element[0];
if (ctrl.setSelectionRange) {
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
} else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
};
var view;
var appendView = function() {
run(function() { view.appendTo('#qunit-fixture'); });
};
var originalLookup = Ember.lookup;
var TemplateTests, container, lookup;
/**
This module specifically tests integration with Handlebars and Ember-specific
Handlebars extensions.
If you add additional template support to View, you should create a new
file in which to test.
*/
QUnit.module("View - handlebars integration", {
setup: function() {
Ember.lookup = lookup = {};
lookup.TemplateTests = TemplateTests = Namespace.create();
container = new Container();
container.optionsForType('template', { instantiate: false });
container.register('view:default', _MetamorphView);
container.register('view:toplevel', EmberView.extend());
},
teardown: function() {
run(function() {
if (container) {
container.destroy();
}
if (view) {
view.destroy();
}
container = view = null;
});
Ember.lookup = lookup = originalLookup;
TemplateTests = null;
}
});
test("template view should call the function of the associated template", function() {
container.register('template:testTemplate', EmberHandlebars.compile("<h1 id='twas-called'>template was called</h1>"));
view = EmberView.create({
container: container,
templateName: 'testTemplate'
});
appendView();
ok(view.$('#twas-called').length, "the named template was called");
});
test("{{view}} should not override class bindings defined on a child view", function() {
var LabelView = EmberView.extend({
container: container,
templateName: 'nested',
classNameBindings: ['something'],
something: 'visible'
});
container.register('controller:label', ObjectController, { instantiate: true });
container.register('view:label', LabelView);
container.register('template:label', EmberHandlebars.compile('<div id="child-view"></div>'));
container.register('template:nester', EmberHandlebars.compile('{{render "label"}}'));
view = EmberView.create({
container: container,
templateName: 'nester',
controller: ObjectController.create({
container: container
})
});
appendView();
ok(view.$('.visible').length > 0, 'class bindings are not overriden');
});
test("template view should call the function of the associated template with itself as the context", function() {
container.register('template:testTemplate', EmberHandlebars.compile("<h1 id='twas-called'>template was called for {{view.personName}}. Yea {{view.personName}}</h1>"));
view = EmberView.createWithMixins({
container: container,
templateName: 'testTemplate',
_personName: "Tom DAAAALE",
_i: 0,
personName: computed(function() {
this._i++;
return this._personName + this._i;
})
});
appendView();
equal("template was called for Tom DAAAALE1. Yea Tom DAAAALE1", view.$('#twas-called').text(), "the named template was called with the view as the data source");
});
test("should allow values from normal JavaScript hash objects to be used", function() {
view = EmberView.create({
template: EmberHandlebars.compile('{{#with view.person as person}}{{person.firstName}} {{person.lastName}} (and {{person.pet.name}}){{/with}}'),
person: {
firstName: 'Señor',
lastName: 'CFC',
pet: {
name: 'Fido'
}
}
});
appendView();
equal(view.$().text(), "Señor CFC (and Fido)", "prints out values from a hash");
});
test("should read from globals (DEPRECATED)", function() {
Ember.lookup.Global = 'Klarg';
view = EmberView.create({
template: EmberHandlebars.compile('{{Global}}')
});
expectDeprecation(function(){
appendView();
}, "Global lookup of Global from a Handlebars template is deprecated.");
equal(view.$().text(), Ember.lookup.Global);
});
test("should read from globals with a path (DEPRECATED)", function() {
Ember.lookup.Global = { Space: 'Klarg' };
view = EmberView.create({
template: EmberHandlebars.compile('{{Global.Space}}')
});
expectDeprecation(function(){
appendView();
}, "Global lookup of Global.Space from a Handlebars template is deprecated.");
equal(view.$().text(), Ember.lookup.Global.Space);
});
test("with context, should read from globals (DEPRECATED)", function() {
Ember.lookup.Global = 'Klarg';
view = EmberView.create({
context: {},
template: EmberHandlebars.compile('{{Global}}')
});
expectDeprecation(function(){
appendView();
}, "Global lookup of Global from a Handlebars template is deprecated.");
equal(view.$().text(), Ember.lookup.Global);
});
test("with context, should read from globals with a path (DEPRECATED)", function() {
Ember.lookup.Global = { Space: 'Klarg' };
view = EmberView.create({
context: {},
template: EmberHandlebars.compile('{{Global.Space}}')
});
expectDeprecation(function(){
appendView();
}, "Global lookup of Global.Space from a Handlebars template is deprecated.");
equal(view.$().text(), Ember.lookup.Global.Space);
});
test("should read from a global-ish simple local path without deprecation", function() {
view = EmberView.create({
context: { NotGlobal: 'Gwar' },
template: EmberHandlebars.compile('{{NotGlobal}}')
});
expectNoDeprecation();
appendView();
equal(view.$().text(), 'Gwar');
});
test("should read a number value", function() {
var context = { aNumber: 1 };
view = EmberView.create({
context: context,
template: EmberHandlebars.compile('{{aNumber}}')
});
appendView();
equal(view.$().text(), '1');
Ember.run(function(){
Ember.set(context, 'aNumber', 2);
});
equal(view.$().text(), '2');
});
test("should read an escaped number value", function() {
var context = { aNumber: 1 };
view = EmberView.create({
context: context,
template: EmberHandlebars.compile('{{{aNumber}}}')
});
appendView();
equal(view.$().text(), '1');
Ember.run(function(){
Ember.set(context, 'aNumber', 2);
});
equal(view.$().text(), '2');
});
test("should read from an Object.create(null)", function() {
// Use ember's polyfill for Object.create
var nullObject = o_create(null);
nullObject['foo'] = 'bar';
view = EmberView.create({
context: { nullObject: nullObject },
template: EmberHandlebars.compile('{{nullObject.foo}}')
});
appendView();
equal(view.$().text(), 'bar');
Ember.run(function(){
Ember.set(nullObject, 'foo', 'baz');
});
equal(view.$().text(), 'baz');
});
test("should escape HTML in normal mustaches", function() {
view = EmberView.create({
template: EmberHandlebars.compile('{{view.output}}'),
output: "you need to be more <b>bold</b>"
});
appendView();
equal(view.$('b').length, 0, "does not create an element");
equal(view.$().text(), 'you need to be more <b>bold</b>', "inserts entities, not elements");
run(function() { set(view, 'output', "you are so <i>super</i>"); });
equal(view.$().text(), 'you are so <i>super</i>', "updates with entities, not elements");
equal(view.$('i').length, 0, "does not create an element when value is updated");
});
test("should not escape HTML in triple mustaches", function() {
view = EmberView.create({
template: EmberHandlebars.compile('{{{view.output}}}'),
output: "you need to be more <b>bold</b>"
});
appendView();
equal(view.$('b').length, 1, "creates an element");
run(function() {
set(view, 'output', "you are so <i>super</i>");
});
equal(view.$('i').length, 1, "creates an element when value is updated");
});
test("should not escape HTML if string is a Handlebars.SafeString", function() {
view = EmberView.create({
template: EmberHandlebars.compile('{{view.output}}'),
output: new Handlebars.SafeString("you need to be more <b>bold</b>")
});
appendView();
equal(view.$('b').length, 1, "creates an element");
run(function() {
set(view, 'output', new Handlebars.SafeString("you are so <i>super</i>"));
});
equal(view.$('i').length, 1, "creates an element when value is updated");
});
test("child views can be inserted using the {{view}} Handlebars helper", function() {
container.register('template:nester', EmberHandlebars.compile("<h1 id='hello-world'>Hello {{world}}</h1>{{view view.labelView}}"));
container.register('template:nested', EmberHandlebars.compile("<div id='child-view'>Goodbye {{cruel}} {{world}}</div>"));
var context = {
world: "world!"
};
var LabelView = EmberView.extend({
container: container,
tagName: "aside",
templateName: 'nested'
});
view = EmberView.create({
labelView: LabelView,
container: container,
templateName: 'nester',
context: context
});
set(context, 'cruel', "cruel");
appendView();
ok(view.$("#hello-world:contains('Hello world!')").length, "The parent view renders its contents");
ok(view.$("#child-view:contains('Goodbye cruel world!')").length === 1, "The child view renders its content once");
ok(view.$().text().match(/Hello world!.*Goodbye cruel world\!/), "parent view should appear before the child view");
});
test("child views can be inserted inside a bind block", function() {
container.register('template:nester', EmberHandlebars.compile("<h1 id='hello-world'>Hello {{world}}</h1>{{view view.bqView}}"));
container.register('template:nested', EmberHandlebars.compile("<div id='child-view'>Goodbye {{#with content as thing}}{{thing.blah}} {{view view.otherView}}{{/with}} {{world}}</div>"));
container.register('template:other', EmberHandlebars.compile("cruel"));
var context = {
world: "world!"
};
var OtherView = EmberView.extend({
container: container,
templateName: 'other'
});
var BQView = EmberView.extend({
container: container,
otherView: OtherView,
tagName: "blockquote",
templateName: 'nested'
});
view = EmberView.create({
container: container,
bqView: BQView,
context: context,
templateName: 'nester'
});
set(context, 'content', EmberObject.create({ blah: "wot" }));
appendView();
ok(view.$("#hello-world:contains('Hello world!')").length, "The parent view renders its contents");
ok(view.$("blockquote").text().match(/Goodbye.*wot.*cruel.*world\!/), "The child view renders its content once");
ok(view.$().text().match(/Hello world!.*Goodbye.*wot.*cruel.*world\!/), "parent view should appear before the child view");
});
test("using Handlebars helper that doesn't exist should result in an error", function() {
var names = [{ name: 'Alex' }, { name: 'Stef' }];
var context = { content: A(names) };
throws(function() {
view = EmberView.create({
context: context,
template: EmberHandlebars.compile('{{#group}}{{#each name in content}}{{name}}{{/each}}{{/group}}')
});
appendView();
}, "Missing helper: 'group'");
});
test("View should update when a property changes and the bind helper is used", function() {
container.register('template:foo', EmberHandlebars.compile('<h1 id="first">{{#with view.content as thing}}{{bind "thing.wham"}}{{/with}}</h1>'));
view = EmberView.create({
container: container,
templateName: 'foo',
content: EmberObject.create({
wham: 'bam',
thankYou: "ma'am"
})
});
appendView();
equal(view.$('#first').text(), "bam", "precond - view renders Handlebars template");
run(function() { set(get(view, 'content'), 'wham', 'bazam'); });
equal(view.$('#first').text(), "bazam", "view updates when a bound property changes");
});
test("View should not use keyword incorrectly - Issue #1315", function() {
container.register('template:foo', EmberHandlebars.compile('{{#each value in view.content}}{{value}}-{{#each option in view.options}}{{option.value}}:{{option.label}} {{/each}}{{/each}}'));
view = EmberView.create({
container: container,
templateName: 'foo',
content: A(['X', 'Y']),
options: A([
{ label: 'One', value: 1 },
{ label: 'Two', value: 2 }
])
});
appendView();
equal(view.$().text(), 'X-1:One 2:Two Y-1:One 2:Two ');
});
test("View should update when a property changes and no bind helper is used", function() {
container.register('template:foo', EmberHandlebars.compile('<h1 id="first">{{#with view.content as thing}}{{thing.wham}}{{/with}}</h1>'));
view = EmberView.create({
container: container,
templateName: 'foo',
content: EmberObject.create({
wham: 'bam',
thankYou: "ma'am"
})
});
appendView();
equal(view.$('#first').text(), "bam", "precond - view renders Handlebars template");
run(function() { set(get(view, 'content'), 'wham', 'bazam'); });
equal(view.$('#first').text(), "bazam", "view updates when a bound property changes");
});
test("View should update when the property used with the #with helper changes [DEPRECATED]", function() {
container.register('template:foo', EmberHandlebars.compile('<h1 id="first">{{#with view.content}}{{wham}}{{/with}}</h1>'));
view = EmberView.create({
container: container,
templateName: 'foo',
content: EmberObject.create({
wham: 'bam',
thankYou: "ma'am"
})
});
expectDeprecation(function() {
appendView();
}, 'Using the context switching form of `{{with}}` is deprecated. Please use the keyword form (`{{with foo as bar}}`) instead. See http://emberjs.com/guides/deprecations/#toc_more-consistent-handlebars-scope for more details.');
equal(view.$('#first').text(), "bam", "precond - view renders Handlebars template");
run(function() {
set(view, 'content', EmberObject.create({
wham: 'bazam'
}));
});
equal(view.$('#first').text(), "bazam", "view updates when a bound property changes");
});
test("should not update when a property is removed from the view", function() {
container.register('template:foo', EmberHandlebars.compile('<h1 id="first">{{#bind "view.content"}}{{#bind "foo"}}{{bind "baz"}}{{/bind}}{{/bind}}</h1>'));
view = EmberView.create({
container: container,
templateName: 'foo',
content: EmberObject.create({
foo: EmberObject.create({
baz: "unicorns"
})
})
});
appendView();
equal(view.$('#first').text(), "unicorns", "precond - renders the bound value");
var oldContent = get(view, 'content');
run(function() {
set(view, 'content', EmberObject.create({
foo: EmberObject.create({
baz: "ninjas"
})
}));
});
equal(view.$('#first').text(), 'ninjas', "updates to new content value");
run(function() {
set(oldContent, 'foo.baz', 'rockstars');
});
run(function() {
set(oldContent, 'foo.baz', 'ewoks');
});
equal(view.$('#first').text(), "ninjas", "does not update removed object");
});
test("Handlebars templates update properties if a content object changes", function() {
container.register('template:menu', EmberHandlebars.compile('<h1>Today\'s Menu</h1>{{#bind "view.coffee"}}<h2>{{color}} coffee</h2><span id="price">{{bind "price"}}</span>{{/bind}}'));
run(function() {
view = EmberView.create({
container: container,
templateName: 'menu',
coffee: EmberObject.create({
color: 'brown',
price: '$4'
})
});
});
appendView();
equal(view.$('h2').text(), "brown coffee", "precond - renders color correctly");
equal(view.$('#price').text(), '$4', "precond - renders price correctly");
run(function() {
set(view, 'coffee', EmberObject.create({
color: "mauve",
price: "$4.50"
}));
});
equal(view.$('h2').text(), "mauve coffee", "should update name field when content changes");
equal(view.$('#price').text(), "$4.50", "should update price field when content changes");
run(function() {
set(view, 'coffee', EmberObject.create({
color: "mauve",
price: "$5.50"
}));
});
equal(view.$('h2').text(), "mauve coffee", "should update name field when content changes");
equal(view.$('#price').text(), "$5.50", "should update price field when content changes");
run(function() {
set(view, 'coffee.price', "$5");
});
equal(view.$('#price').text(), "$5", "should update price field when price property is changed");
run(function() {
view.destroy();
});
});
test("Template updates correctly if a path is passed to the bind helper", function() {
container.register('template:menu', EmberHandlebars.compile('<h1>{{bind "view.coffee.price"}}</h1>'));
view = EmberView.create({
container: container,
templateName: 'menu',
coffee: EmberObject.create({
price: '$4'
})
});
appendView();
equal(view.$('h1').text(), "$4", "precond - renders price");
run(function() {
set(view, 'coffee.price', "$5");
});
equal(view.$('h1').text(), "$5", "updates when property changes");
run(function() {
set(view, 'coffee', { price: "$6" });
});
equal(view.$('h1').text(), "$6", "updates when parent property changes");
});
test("Template updates correctly if a path is passed to the bind helper and the context object is an ObjectController", function() {
container.register('template:menu', EmberHandlebars.compile('<h1>{{bind "view.coffee.price"}}</h1>'));
var controller = ObjectController.create();
var realObject = EmberObject.create({
price: "$4"
});
set(controller, 'model', realObject);
view = EmberView.create({
container: container,
templateName: 'menu',
coffee: controller
});
appendView();
equal(view.$('h1').text(), "$4", "precond - renders price");
run(function() {
set(realObject, 'price', "$5");
});
equal(view.$('h1').text(), "$5", "updates when property is set on real object");
run(function() {
set(controller, 'price', "$6" );
});
equal(view.$('h1').text(), "$6", "updates when property is set on object controller");
});
test("should update the block when object passed to #if helper changes", function() {
container.register('template:menu', EmberHandlebars.compile('<h1>{{#if view.inception}}{{view.INCEPTION}}{{/if}}</h1>'));
view = EmberView.create({
container: container,
templateName: 'menu',
INCEPTION: "BOOOOOOOONG doodoodoodoodooodoodoodoo",
inception: 'OOOOoooooOOOOOOooooooo'
});
appendView();
equal(view.$('h1').text(), "BOOOOOOOONG doodoodoodoodooodoodoodoo", "renders block if a string");
var tests = [false, null, undefined, [], '', 0];
forEach(tests, function(val) {
run(function() {
set(view, 'inception', val);
});
equal(view.$('h1').text(), '', fmt("hides block when conditional is '%@'", [String(val)]));
run(function() {
set(view, 'inception', true);
});
equal(view.$('h1').text(), "BOOOOOOOONG doodoodoodoodooodoodoodoo", "precond - renders block when conditional is true");
});
});
test("should update the block when object passed to #unless helper changes", function() {
container.register('template:advice', EmberHandlebars.compile('<h1>{{#unless view.onDrugs}}{{view.doWellInSchool}}{{/unless}}</h1>'));
view = EmberView.create({
container: container,
templateName: 'advice',
onDrugs: true,
doWellInSchool: "Eat your vegetables"
});
appendView();
equal(view.$('h1').text(), "", "hides block if true");
var tests = [false, null, undefined, [], '', 0];
forEach(tests, function(val) {
run(function() {
set(view, 'onDrugs', val);
});
equal(view.$('h1').text(), 'Eat your vegetables', fmt("renders block when conditional is '%@'; %@", [String(val), typeOf(val)]));
run(function() {
set(view, 'onDrugs', true);
});
equal(view.$('h1').text(), "", "precond - hides block when conditional is true");
});
});
test("should update the block when object passed to #if helper changes and an inverse is supplied", function() {
container.register('template:menu', EmberHandlebars.compile('<h1>{{#if view.inception}}{{view.INCEPTION}}{{else}}{{view.SAD}}{{/if}}</h1>'));
view = EmberView.create({
container: container,
templateName: 'menu',
INCEPTION: "BOOOOOOOONG doodoodoodoodooodoodoodoo",
inception: false,
SAD: 'BOONG?'
});
appendView();
equal(view.$('h1').text(), "BOONG?", "renders alternate if false");
run(function() { set(view, 'inception', true); });
var tests = [false, null, undefined, [], '', 0];
forEach(tests, function(val) {
run(function() {
set(view, 'inception', val);
});
equal(view.$('h1').text(), 'BOONG?', fmt("renders alternate if %@", [String(val)]));
run(function() {
set(view, 'inception', true);
});
equal(view.$('h1').text(), "BOOOOOOOONG doodoodoodoodooodoodoodoo", "precond - renders block when conditional is true");
});
});
test("edge case: child conditional should not render children if parent conditional becomes false", function() {
var childCreated = false;
var child = null;
view = EmberView.create({
cond1: true,
cond2: false,
viewClass: EmberView.extend({
init: function() {
this._super();
childCreated = true;
child = this;
}
}),
template: EmberHandlebars.compile('{{#if view.cond1}}{{#if view.cond2}}{{#view view.viewClass}}test{{/view}}{{/if}}{{/if}}')
});
appendView();
ok(!childCreated, 'precondition');
run(function() {
// The order of these sets is important for the test
view.set('cond2', true);
view.set('cond1', false);
});
// TODO: Priority Queue, for now ensure correct result.
//ok(!childCreated, 'child should not be created');
ok(child.isDestroyed, 'child should be gone');
equal(view.$().text(), '');
});
test("Template views return throw if their template cannot be found", function() {
view = EmberView.create({
templateName: 'cantBeFound',
container: { lookup: function() { }}
});
expectAssertion(function() {
get(view, 'template');
}, /cantBeFound/);
});
test("Layout views return throw if their layout cannot be found", function() {
view = EmberView.create({
layoutName: 'cantBeFound',
container: { lookup: function() { }}
});
expectAssertion(function() {
get(view, 'layout');
}, /cantBeFound/);
});
test("Template views add an elementId to child views created using the view helper", function() {
container.register('template:parent', EmberHandlebars.compile('<div>{{view view.childView}}</div>'));
container.register('template:child', EmberHandlebars.compile("I can't believe it's not butter."));
var ChildView = EmberView.extend({
container: container,
templateName: 'child'
});
view = EmberView.create({
container: container,
childView: ChildView,
templateName: 'parent'
});
appendView();
var childView = get(view, 'childViews.firstObject');
equal(view.$().children().first().children().first().attr('id'), get(childView, 'elementId'));
});
test("views set the template of their children to a passed block", function() {
container.register('template:parent', EmberHandlebars.compile('<h1>{{#view}}<span>It worked!</span>{{/view}}</h1>'));
view = EmberView.create({
container: container,
templateName: 'parent'
});
appendView();
ok(view.$('h1:has(span)').length === 1, "renders the passed template inside the parent template");
});
test("views render their template in the context of the parent view's context", function() {
container.register('template:parent', EmberHandlebars.compile('<h1>{{#with content as person}}{{#view}}{{person.firstName}} {{person.lastName}}{{/view}}{{/with}}</h1>'));
var context = {
content: {
firstName: "Lana",
lastName: "del Heeeyyyyyy"
}
};
view = EmberView.create({
container: container,
templateName: 'parent',
context: context
});
appendView();
equal(view.$('h1').text(), "Lana del Heeeyyyyyy", "renders properties from parent context");
});
test("views make a view keyword available that allows template to reference view context", function() {
container.register('template:parent', EmberHandlebars.compile('<h1>{{#with view.content as person}}{{#view person.subview}}{{view.firstName}} {{person.lastName}}{{/view}}{{/with}}</h1>'));
view = EmberView.create({
container: container,
templateName: 'parent',
content: {
subview: EmberView.extend({
firstName: "Brodele"
}),
firstName: "Lana",
lastName: "del Heeeyyyyyy"
}
});
appendView();
equal(view.$('h1').text(), "Brodele del Heeeyyyyyy", "renders properties from parent context");
});
test("a view helper's bindings are to the parent context", function() {
var Subview = EmberView.extend({
classNameBindings: ['color'],
controller: EmberObject.create({
color: 'green',
name: "bar"
}),
template: EmberHandlebars.compile('{{view.someController.name}} {{name}}')
});
var View = EmberView.extend({
controller: EmberObject.create({
color: "mauve",
name: 'foo'
}),
Subview: Subview,
template: EmberHandlebars.compile('<h1>{{view view.Subview colorBinding="color" someControllerBinding="this"}}</h1>')
});
view = View.create();
appendView();
equal(view.$('h1 .mauve').length, 1, "renders property on helper declaration from parent context");
equal(view.$('h1 .mauve').text(), "foo bar", "renders property bound in template from subview context");
});
// test("should warn if setting a template on a view with a templateName already specified", function() {
// view = EmberView.create({
// childView: EmberView.extend({
// templateName: 'foo'
// }),
// template: EmberHandlebars.compile('{{#view childView}}test{{/view}}')
// });
// expectAssertion(function() {
// appendView();
// }, "Unable to find view at path 'childView'");
// run(function() {
// view.destroy();
// });
// view = EmberView.create({
// childView: EmberView.extend(),
// template: EmberHandlebars.compile('{{#view childView templateName="foo"}}test{{/view}}')
// });
// expectAssertion(function() {
// appendView();
// }, "Unable to find view at path 'childView'");
// });
test("Child views created using the view helper should have their parent view set properly", function() {
var template = '{{#view}}{{#view}}{{view}}{{/view}}{{/view}}';
view = EmberView.create({
template: EmberHandlebars.compile(template)
});
appendView();
var childView = firstGrandchild(view);
equal(childView, get(firstChild(childView), 'parentView'), 'parent view is correct');
});
test("Child views created using the view helper should have their IDs registered for events", function() {
var template = '{{view}}{{view id="templateViewTest"}}';
view = EmberView.create({
template: EmberHandlebars.compile(template)
});
appendView();
var childView = firstChild(view);
var id = childView.$()[0].id;
equal(EmberView.views[id], childView, 'childView without passed ID is registered with View.views so that it can properly receive events from EventDispatcher');
childView = nthChild(view, 1);
id = childView.$()[0].id;
equal(id, 'templateViewTest', 'precond -- id of childView should be set correctly');
equal(EmberView.views[id], childView, 'childView with passed ID is registered with View.views so that it can properly receive events from EventDispatcher');
});
test("Child views created using the view helper and that have a viewName should be registered as properties on their parentView", function() {
var template = '{{#view}}{{view viewName="ohai"}}{{/view}}';
view = EmberView.create({
template: EmberHandlebars.compile(template)
});
appendView();
var parentView = firstChild(view);
var childView = firstGrandchild(view);
equal(get(parentView, 'ohai'), childView);
});
test("should update boundIf blocks if the conditional changes", function() {
container.register('template:foo', EmberHandlebars.compile('<h1 id="first">{{#boundIf "view.content.myApp.isEnabled"}}{{view.content.wham}}{{/boundIf}}</h1>'));
view = EmberView.create({
container: container,
templateName: 'foo',
content: EmberObject.create({
wham: 'bam',
thankYou: "ma'am",
myApp: EmberObject.create({
isEnabled: true
})
})
});
appendView();
equal(view.$('#first').text(), "bam", "renders block when condition is true");
run(function() {
set(get(view, 'content'), 'myApp.isEnabled', false);
});
equal(view.$('#first').text(), "", "re-renders without block when condition is false");
run(function() {
set(get(view, 'content'), 'myApp.isEnabled', true);
});
equal(view.$('#first').text(), "bam", "re-renders block when condition changes to true");
});
test("should not update boundIf if truthiness does not change", function() {
var renderCount = 0;
view = EmberView.create({
template: EmberHandlebars.compile('<h1 id="first">{{#boundIf "view.shouldDisplay"}}{{view view.InnerViewClass}}{{/boundIf}}</h1>'),
shouldDisplay: true,
InnerViewClass: EmberView.extend({
template: EmberHandlebars.compile("bam"),
render: function() {
renderCount++;
return this._super.apply(this, arguments);
}
})
});
appendView();
equal(renderCount, 1, "precond - should have rendered once");
equal(view.$('#first').text(), "bam", "renders block when condition is true");
run(function() {
set(view, 'shouldDisplay', 1);
});
equal(renderCount, 1, "should not have rerendered");
equal(view.$('#first').text(), "bam", "renders block when condition is true");
});
test("{{view}} id attribute should set id on layer", function() {
container.register('template:foo', EmberHandlebars.compile('{{#view view.idView id="bar"}}baz{{/view}}'));
var IdView = EmberView;
view = EmberView.create({
idView: IdView,
container: container,
templateName: 'foo'
});
appendView();
equal(view.$('#bar').length, 1, "adds id attribute to layer");
equal(view.$('#bar').text(), 'baz', "emits content");
});
test("{{view}} tag attribute should set tagName of the view", function() {
container.register('template:foo', EmberHandlebars.compile('{{#view view.tagView tag="span"}}baz{{/view}}'));
var TagView = EmberView;
view = EmberView.create({
tagView: TagView,
container: container,
templateName: 'foo'
});
appendView();
equal(view.$('span').length, 1, "renders with tag name");
equal(view.$('span').text(), 'baz', "emits content");
});
test("{{view}} class attribute should set class on layer", function() {
container.register('template:foo', EmberHandlebars.compile('{{#view view.idView class="bar"}}baz{{/view}}'));
var IdView = EmberView;
view = EmberView.create({
idView: IdView,
container: container,
templateName: 'foo'
});
appendView();
equal(view.$('.bar').length, 1, "adds class attribute to layer");
equal(view.$('.bar').text(), 'baz', "emits content");
});
test("{{view}} should not allow attributeBindings to be set", function() {
expectAssertion(function() {
view = EmberView.create({
template: EmberHandlebars.compile('{{view attributeBindings="one two"}}')
});
appendView();
}, /Setting 'attributeBindings' via Handlebars is not allowed/);
});
test("{{view}} should be able to point to a local view", function() {
view = EmberView.create({
template: EmberHandlebars.compile("{{view view.common}}"),
common: EmberView.extend({
template: EmberHandlebars.compile("common")
})
});
appendView();
equal(view.$().text(), "common", "tries to look up view name locally");
});
test("{{view}} should evaluate class bindings set to global paths DEPRECATED", function() {
var App;
run(function() {
lookup.App = App = Namespace.create({
isApp: true,
isGreat: true,
directClass: "app-direct",
isEnabled: true
});
});
view = EmberView.create({
textField: TextField,
template: EmberHandlebars.compile('{{view view.textField class="unbound" classBinding="App.isGreat:great App.directClass App.isApp App.isEnabled:enabled:disabled"}}')
});
expectDeprecation(function() {
appendView();
});
ok(view.$('input').hasClass('unbound'), "sets unbound classes directly");
ok(view.$('input').hasClass('great'), "evaluates classes bound to global paths");
ok(view.$('input').hasClass('app-direct'), "evaluates classes bound directly to global paths");
ok(view.$('input').hasClass('is-app'), "evaluates classes bound directly to booleans in global paths - dasherizes and sets class when true");
ok(view.$('input').hasClass('enabled'), "evaluates ternary operator in classBindings");
ok(!view.$('input').hasClass('disabled'), "evaluates ternary operator in classBindings");
run(function() {
App.set('isApp', false);
App.set('isEnabled', false);
});
ok(!view.$('input').hasClass('is-app'), "evaluates classes bound directly to booleans in global paths - removes class when false");
ok(!view.$('input').hasClass('enabled'), "evaluates ternary operator in classBindings");
ok(view.$('input').hasClass('disabled'), "evaluates ternary operator in classBindings");
run(function() {
lookup.App.destroy();
});
});
test("{{view}} should evaluate class bindings set in the current context", function() {
view = EmberView.create({
isView: true,
isEditable: true,
directClass: "view-direct",
isEnabled: true,
textField: TextField,
template: EmberHandlebars.compile('{{view view.textField class="unbound" classBinding="view.isEditable:editable view.directClass view.isView view.isEnabled:enabled:disabled"}}')
});
appendView();
ok(view.$('input').hasClass('unbound'), "sets unbound classes directly");
ok(view.$('input').hasClass('editable'), "evaluates classes bound in the current context");
ok(view.$('input').hasClass('view-direct'), "evaluates classes bound directly in the current context");
ok(view.$('input').hasClass('is-view'), "evaluates classes bound directly to booleans in the current context - dasherizes and sets class when true");
ok(view.$('input').hasClass('enabled'), "evaluates ternary operator in classBindings");
ok(!view.$('input').hasClass('disabled'), "evaluates ternary operator in classBindings");
run(function() {
view.set('isView', false);
view.set('isEnabled', false);
});
ok(!view.$('input').hasClass('is-view'), "evaluates classes bound directly to booleans in the current context - removes class when false");
ok(!view.$('input').hasClass('enabled'), "evaluates ternary operator in classBindings");
ok(view.$('input').hasClass('disabled'), "evaluates ternary operator in classBindings");
});
test("{{view}} should evaluate class bindings set with either classBinding or classNameBindings from globals DEPRECATED", function() {
var App;
run(function() {
lookup.App = App = Namespace.create({
isGreat: true,
isEnabled: true
});
});
view = EmberView.create({
textField: TextField,
template: EmberHandlebars.compile('{{view view.textField class="unbound" classBinding="App.isGreat:great App.isEnabled:enabled:disabled" classNameBindings="App.isGreat:really-great App.isEnabled:really-enabled:really-disabled"}}')
});
expectDeprecation(function() {
appendView();
});
ok(view.$('input').hasClass('unbound'), "sets unbound classes directly");
ok(view.$('input').hasClass('great'), "evaluates classBinding");
ok(view.$('input').hasClass('really-great'), "evaluates classNameBinding");
ok(view.$('input').hasClass('enabled'), "evaluates ternary operator in classBindings");
ok(view.$('input').hasClass('really-enabled'), "evaluates ternary operator in classBindings");
ok(!view.$('input').hasClass('disabled'), "evaluates ternary operator in classBindings");
ok(!view.$('input').hasClass('really-disabled'), "evaluates ternary operator in classBindings");
run(function() {
App.set('isEnabled', false);
});
ok(!view.$('input').hasClass('enabled'), "evaluates ternary operator in classBindings");
ok(!view.$('input').hasClass('really-enabled'), "evaluates ternary operator in classBindings");
ok(view.$('input').hasClass('disabled'), "evaluates ternary operator in classBindings");
ok(view.$('input').hasClass('really-disabled'), "evaluates ternary operator in classBindings");
run(function() {
lookup.App.destroy();
});
});
test("{{view}} should evaluate other attribute bindings set to global paths", function() {
run(function() {
lookup.App = Namespace.create({
name: "myApp"
});
});
view = EmberView.create({
textField: TextField,
template: EmberHandlebars.compile('{{view view.textField valueBinding="App.name"}}')
});
expectDeprecation(function() {
appendView();
}, 'Global lookup of App.name from a Handlebars template is deprecated.');
equal(view.$('input').val(), "myApp", "evaluates attributes bound to global paths");
run(function() {
lookup.App.destroy();
});
});
test("{{view}} should evaluate other attributes bindings set in the current context", function() {
view = EmberView.create({
name: "myView",
textField: TextField,
template: EmberHandlebars.compile('{{view view.textField valueBinding="view.name"}}')
});
appendView();
equal(view.$('input').val(), "myView", "evaluates attributes bound in the current context");
});
test("{{view}} should be able to bind class names to truthy properties", function() {
container.register('template:template', EmberHandlebars.compile('{{#view view.classBindingView classBinding="view.number:is-truthy"}}foo{{/view}}'));
var ClassBindingView = EmberView.extend();
view = EmberView.create({
classBindingView: ClassBindingView,
container: container,
number: 5,
templateName: 'template'
});
appendView();
equal(view.$('.is-truthy').length, 1, "sets class name");
run(function() {
set(view, 'number', 0);
});
equal(view.$('.is-truthy').length, 0, "removes class name if bound property is set to falsey");
});
test("{{view}} should be able to bind class names to truthy or falsy properties", function() {
container.register('template:template', EmberHandlebars.compile('{{#view view.classBindingView classBinding="view.number:is-truthy:is-falsy"}}foo{{/view}}'));
var ClassBindingView = EmberView.extend();
view = EmberView.create({
classBindingView: ClassBindingView,
container: container,
number: 5,
templateName: 'template'
});
appendView();
equal(view.$('.is-truthy').length, 1, "sets class name to truthy value");
equal(view.$('.is-falsy').length, 0, "doesn't set class name to falsy value");
run(function() {
set(view, 'number', 0);
});
equal(view.$('.is-truthy').length, 0, "doesn't set class name to truthy value");
equal(view.$('.is-falsy').length, 1, "sets class name to falsy value");
});
test("should not reset cursor position when text field receives keyUp event", function() {
view = TextField.create({
value: "Broseidon, King of the Brocean"
});
run(function() {
view.append();
});
view.$().val('Brosiedoon, King of the Brocean');
setCaretPosition(view.$(), 5);
run(function() {
view.trigger('keyUp', {});
});
equal(caretPosition(view.$()), 5, "The keyUp event should not result in the cursor being reset due to the bind-attr observers");
run(function() {
view.destroy();
});
});
test("should be able to output a property without binding", function() {
var context = {
content: EmberObject.create({
anUnboundString: "No spans here, son."
})
};
view = EmberView.create({
context: context,
template: EmberHandlebars.compile(
'<div id="first">{{unbound content.anUnboundString}}</div>'
)
});
appendView();
equal(view.$('#first').html(), "No spans here, son.");
});
test("should allow standard Handlebars template usage", function() {
view = EmberView.create({
context: { name: "Erik" },
template: Handlebars.compile("Hello, {{name}}")
});
appendView();
equal(view.$().text(), "Hello, Erik");
});
test("should be able to use standard Handlebars #each helper", function() {
view = EmberView.create({
context: { items: ['a', 'b', 'c'] },
template: Handlebars.compile("{{#each items}}{{this}}{{/each}}")
});
appendView();
equal(view.$().html(), "abc");
});
test("should be able to use unbound helper in #each helper", function() {
view = EmberView.create({
items: A(['a', 'b', 'c', 1, 2, 3]),
template: EmberHandlebars.compile(
"<ul>{{#each item in view.items}}<li>{{unbound item}}</li>{{/each}}</ul>")
});
appendView();
equal(view.$().text(), "abc123");
equal(view.$('li').children().length, 0, "No markers");
});
test("should be able to use unbound helper in #each helper (with objects)", function() {
view = EmberView.create({
items: A([{wham: 'bam'}, {wham: 1}]),
template: EmberHandlebars.compile(
"<ul>{{#each item in view.items}}<li>{{unbound item.wham}}</li>{{/each}}</ul>")
});
appendView();
equal(view.$().text(), "bam1");
equal(view.$('li').children().length, 0, "No markers");
});
test("should work with precompiled templates", function() {
var templateString = EmberHandlebars.precompile("{{view.value}}");
var compiledTemplate = EmberHandlebars.template(eval(templateString));
view = EmberView.create({
value: "rendered",
template: compiledTemplate
});
appendView();
equal(view.$().text(), "rendered", "the precompiled template was rendered");
run(function() { view.set('value', 'updated'); });
equal(view.$().text(), "updated", "the precompiled template was updated");
});
test("should expose a controller keyword when present on the view", function() {
var templateString = "{{controller.foo}}{{#view}}{{controller.baz}}{{/view}}";
view = EmberView.create({
container: container,
controller: EmberObject.create({
foo: "bar",
baz: "bang"
}),
template: EmberHandlebars.compile(templateString)
});
appendView();
equal(view.$().text(), "barbang", "renders values from controller and parent controller");
var controller = get(view, 'controller');
run(function() {
controller.set('foo', "BAR");
controller.set('baz', "BLARGH");
});
equal(view.$().text(), "BARBLARGH", "updates the DOM when a bound value is updated");
run(function() {
view.destroy();
});
view = EmberView.create({
controller: "aString",
template: EmberHandlebars.compile("{{controller}}")
});
appendView();
equal(view.$().text(), "aString", "renders the controller itself if no additional path is specified");
});
test("should expose a controller keyword that can be used in conditionals", function() {
var templateString = "{{#view}}{{#if controller}}{{controller.foo}}{{/if}}{{/view}}";
view = EmberView.create({
container: container,
controller: EmberObject.create({
foo: "bar"
}),
template: EmberHandlebars.compile(templateString)
});
appendView();
equal(view.$().text(), "bar", "renders values from controller and parent controller");
run(function() {
view.set('controller', null);
});
equal(view.$().text(), "", "updates the DOM when the controller is changed");
});
test("should expose a controller keyword that persists through Ember.ContainerView", function() {
var templateString = "{{view view.containerView}}";
view = EmberView.create({
containerView: ContainerView,
container: container,
controller: EmberObject.create({
foo: "bar"
}),
template: EmberHandlebars.compile(templateString)
});
appendView();
var containerView = get(view, 'childViews.firstObject');
var viewInstanceToBeInserted = EmberView.create({
template: EmberHandlebars.compile('{{controller.foo}}')
});
run(function() {
containerView.pushObject(viewInstanceToBeInserted);
});
equal(trim(viewInstanceToBeInserted.$().text()), "bar", "renders value from parent's controller");
});
test("should expose a view keyword [DEPRECATED]", function() {
var templateString = '{{#with view.differentContent}}{{view.foo}}{{#view baz="bang"}}{{view.baz}}{{/view}}{{/with}}';
view = EmberView.create({
container: container,
differentContent: {
view: {
foo: "WRONG",
baz: "WRONG"
}
},
foo: "bar",
template: EmberHandlebars.compile(templateString)
});
expectDeprecation(function() {
appendView();
}, 'Using the context switching form of `{{with}}` is deprecated. Please use the keyword form (`{{with foo as bar}}`) instead. See http://emberjs.com/guides/deprecations/#toc_more-consistent-handlebars-scope for more details.');
equal(view.$().text(), "barbang", "renders values from view and child view");
});
test("should be able to explicitly set a view's context", function() {
var context = EmberObject.create({
test: 'test'
});
var CustomContextView = EmberView.extend({
context: context,
template: EmberHandlebars.compile("{{test}}")
});
view = EmberView.create({
customContextView: CustomContextView,
template: EmberHandlebars.compile("{{view view.customContextView}}")
});
appendView();
equal(view.$().text(), "test");
});
test("should escape HTML in primitive value contexts when using normal mustaches", function() {
view = EmberView.create({
context: '<b>Max</b><b>James</b>',
template: EmberHandlebars.compile('{{this}}'),
});
appendView();
equal(view.$('b').length, 0, "does not create an element");
equal(view.$().text(), '<b>Max</b><b>James</b>', "inserts entities, not elements");
run(function() { set(view, 'context', '<i>Max</i><i>James</i>'); });
equal(view.$().text(), '<i>Max</i><i>James</i>', "updates with entities, not elements");
equal(view.$('i').length, 0, "does not create an element when value is updated");
});
test("should not escape HTML in primitive value contexts when using triple mustaches", function() {
view = EmberView.create({
context: '<b>Max</b><b>James</b>',
template: EmberHandlebars.compile('{{{this}}}'),
});
appendView();
equal(view.$('b').length, 2, "creates an element");
run(function() { set(view, 'context', '<i>Max</i><i>James</i>'); });
equal(view.$('i').length, 2, "creates an element when value is updated");
});
QUnit.module("Ember.View - handlebars integration", {
setup: function() {
Ember.lookup = lookup = { Ember: Ember };
originalLog = Ember.Logger.log;
logCalls = [];
Ember.Logger.log = function(arg) { logCalls.push(arg); };
},
teardown: function() {
if (view) {
run(function() {
view.destroy();
});
view = null;
}
Ember.Logger.log = originalLog;
Ember.lookup = originalLookup;
}
});
test("should be able to log a property", function() {
var context = {
value: 'one'
};
view = EmberView.create({
context: context,
template: EmberHandlebars.compile('{{log value}}')
});
appendView();
equal(view.$().text(), "", "shouldn't render any text");
equal(logCalls[0], 'one', "should call log with value");
});
test("should be able to log a view property", function() {
view = EmberView.create({
template: EmberHandlebars.compile('{{log view.value}}'),
value: 'one'
});
appendView();
equal(view.$().text(), "", "shouldn't render any text");
equal(logCalls[0], 'one', "should call log with value");
});
test("should be able to log `this`", function() {
view = EmberView.create({
context: 'one',
template: EmberHandlebars.compile('{{log this}}'),
});
appendView();
equal(view.$().text(), "", "shouldn't render any text");
equal(logCalls[0], 'one', "should call log with item one");
});
var MyApp;
QUnit.module("Templates redrawing and bindings", {
setup: function() {
Ember.lookup = lookup = { Ember: Ember };
MyApp = lookup.MyApp = EmberObject.create({});
},
teardown: function() {
run(function() {
if (view) view.destroy();
});
Ember.lookup = originalLookup;
}
});
test("should be able to update when bound property updates", function() {
MyApp.set('controller', EmberObject.create({name: 'first'}));
var View = EmberView.extend({
template: EmberHandlebars.compile('<i>{{view.value.name}}, {{view.computed}}</i>'),
valueBinding: 'MyApp.controller',
computed: computed(function() {
return this.get('value.name') + ' - computed';
}).property('value')
});
run(function() {
view = View.create();
});
appendView();
run(function() {
MyApp.set('controller', EmberObject.create({
name: 'second'
}));
});
equal(view.get('computed'), "second - computed", "view computed properties correctly update");
equal(view.$('i').text(), 'second, second - computed', "view rerenders when bound properties change");
});
test("properties within an if statement should not fail on re-render", function() {
view = EmberView.create({
template: EmberHandlebars.compile('{{#if view.value}}{{view.value}}{{/if}}'),
value: null
});
appendView();
equal(view.$().text(), '');
run(function() {
view.set('value', 'test');
});
equal(view.$().text(), 'test');
run(function() {
view.set('value', null);
});
equal(view.$().text(), '');
});
test('should cleanup bound properties on rerender', function() {
view = EmberView.create({
controller: EmberObject.create({name: 'wycats'}),
template: EmberHandlebars.compile('{{name}}')
});
appendView();
equal(view.$().text(), 'wycats', 'rendered binding');
run(view, 'rerender');
equal(view._childViews.length, 1);
});
test("views within an if statement should be sane on re-render", function() {
view = EmberView.create({
template: EmberHandlebars.compile('{{#if view.display}}{{input}}{{/if}}'),
display: false
});
appendView();
equal(view.$('input').length, 0);
run(function() {
// Setting twice will trigger the observer twice, this is intentional
view.set('display', true);
view.set('display', 'yes');
});
var textfield = view.$('input');
equal(textfield.length, 1);
// Make sure the view is still registered in View.views
ok(EmberView.views[textfield.attr('id')]);
});
test("the {{this}} helper should not fail on removal", function() {
view = EmberView.create({
context: 'abc',
template: EmberHandlebars.compile('{{#if view.show}}{{this}}{{/if}}'),
show: true
});
appendView();
equal(view.$().text(), 'abc', "should start property - precond");
run(function() {
view.set('show', false);
});
equal(view.$().text(), '');
});
test("bindings should be relative to the current context", function() {
view = EmberView.create({
museumOpen: true,
museumDetails: EmberObject.create({
name: "SFMoMA",
price: 20
}),
museumView: EmberView.extend({
template: EmberHandlebars.compile('Name: {{view.name}} Price: ${{view.dollars}}')
}),
template: EmberHandlebars.compile('{{#if view.museumOpen}} {{view view.museumView nameBinding="view.museumDetails.name" dollarsBinding="view.museumDetails.price"}} {{/if}}')
});
appendView();
equal(trim(view.$().text()), "Name: SFMoMA Price: $20", "should print baz twice");
});
test("bindings should respect keywords", function() {
view = EmberView.create({
museumOpen: true,
controller: {
museumOpen: true,
museumDetails: EmberObject.create({
name: "SFMoMA",
price: 20
})
},
museumView: EmberView.extend({
template: EmberHandlebars.compile('Name: {{view.name}} Price: ${{view.dollars}}')
}),
template: EmberHandlebars.compile('{{#if view.museumOpen}}{{view view.museumView nameBinding="controller.museumDetails.name" dollarsBinding="controller.museumDetails.price"}}{{/if}}')
});
appendView();
equal(trim(view.$().text()), "Name: SFMoMA Price: $20", "should print baz twice");
});
test("bindings can be 'this', in which case they *are* the current context [DEPRECATED]", function() {
view = EmberView.create({
museumOpen: true,
museumDetails: EmberObject.create({
name: "SFMoMA",
price: 20,
museumView: EmberView.extend({
template: EmberHandlebars.compile('Name: {{view.museum.name}} Price: ${{view.museum.price}}')
})
}),
template: EmberHandlebars.compile('{{#if view.museumOpen}} {{#with view.museumDetails}}{{view museumView museum=this}} {{/with}}{{/if}}')
});
expectDeprecation(function() {
appendView();
}, 'Using the context switching form of `{{with}}` is deprecated. Please use the keyword form (`{{with foo as bar}}`) instead. See http://emberjs.com/guides/deprecations/#toc_more-consistent-handlebars-scope for more details.');
equal(trim(view.$().text()), "Name: SFMoMA Price: $20", "should print baz twice");
});
// https://github.com/emberjs/ember.js/issues/120
test("should not enter an infinite loop when binding an attribute in Handlebars", function() {
var LinkView = EmberView.extend({
classNames: ['app-link'],
tagName: 'a',
attributeBindings: ['href'],
href: '#none',
click: function() {
return false;
}
});
var parentView = EmberView.create({
linkView: LinkView,
test: EmberObject.create({ href: 'test' }),
template: EmberHandlebars.compile('{{#view view.linkView hrefBinding="view.test.href"}} Test {{/view}}')
});
run(function() {
parentView.appendTo('#qunit-fixture');
});
// Use match, since old IE appends the whole URL
var href = parentView.$('a').attr('href');
ok(href.match(/(^|\/)test$/), "Expected href to be 'test' but got '"+href+"'");
run(function() {
parentView.destroy();
});
});
test("should update bound values after the view is removed and then re-appended", function() {
view = EmberView.create({
template: EmberHandlebars.compile("{{#if view.showStuff}}{{view.boundValue}}{{else}}Not true.{{/if}}"),
showStuff: true,
boundValue: "foo"
});
appendView();
equal(trim(view.$().text()), "foo");
run(function() {
set(view, 'showStuff', false);
});
equal(trim(view.$().text()), "Not true.");
run(function() {
set(view, 'showStuff', true);
});
equal(trim(view.$().text()), "foo");
run(function() {
view.remove();
set(view, 'showStuff', false);
});
run(function() {
set(view, 'showStuff', true);
});
appendView();
run(function() {
set(view, 'boundValue', "bar");
});
equal(trim(view.$().text()), "bar");
});
test("should update bound values after view's parent is removed and then re-appended", function() {
expectDeprecation("Setting `childViews` on a Container is deprecated.");
var controller = EmberObject.create();
var parentView = ContainerView.create({
childViews: ['testView'],
controller: controller,
testView: EmberView.create({
template: EmberHandlebars.compile("{{#if showStuff}}{{boundValue}}{{else}}Not true.{{/if}}")
})
});
controller.setProperties({
showStuff: true,
boundValue: "foo"
});
run(function() {
parentView.appendTo('#qunit-fixture');
});
view = parentView.get('testView');
equal(trim(view.$().text()), "foo");
run(function() {
set(controller, 'showStuff', false);
});
equal(trim(view.$().text()), "Not true.");
run(function() {
set(controller, 'showStuff', true);
});
equal(trim(view.$().text()), "foo");
run(function() {
parentView.remove();
set(controller, 'showStuff', false);
});
run(function() {
set(controller, 'showStuff', true);
});
run(function() {
parentView.appendTo('#qunit-fixture');
});
run(function() {
set(controller, 'boundValue', "bar");
});
equal(trim(view.$().text()), "bar");
run(function() {
parentView.destroy();
});
});
test("should call a registered helper for mustache without parameters", function() {
EmberHandlebars.registerHelper('foobar', function() {
return 'foobar';
});
view = EmberView.create({
template: EmberHandlebars.compile("{{foobar}}")
});
appendView();
ok(view.$().text() === 'foobar', "Regular helper was invoked correctly");
});
test("should bind to the property if no registered helper found for a mustache without parameters", function() {
view = EmberView.createWithMixins({
template: EmberHandlebars.compile("{{view.foobarProperty}}"),
foobarProperty: computed(function() {
return 'foobarProperty';
})
});
appendView();
ok(view.$().text() === 'foobarProperty', "Property was bound to correctly");
});
test("should accept bindings as a string or an Ember.Binding", function() {
var viewClass = EmberView.extend({
template: EmberHandlebars.compile("binding: {{view.bindingTest}}, string: {{view.stringTest}}")
});
EmberHandlebars.registerHelper('boogie', function(id, options) {
options.hash = options.hash || {};
options.hash.bindingTestBinding = Binding.oneWay('context.' + id);
options.hash.stringTestBinding = id;
return EmberHandlebars.ViewHelper.helper(this, viewClass, options);
});
view = EmberView.create({
context: EmberObject.create({
direction: 'down'
}),
template: EmberHandlebars.compile("{{boogie direction}}")
});
appendView();
equal(trim(view.$().text()), "binding: down, string: down");
});
test("should teardown observers from bound properties on rerender", function() {
view = EmberView.create({
template: EmberHandlebars.compile("{{view.foo}}"),
foo: 'bar'
});
appendView();
equal(observersFor(view, 'foo').length, 1);
run(function() {
view.rerender();
});
equal(observersFor(view, 'foo').length, 1);
});
test("should provide a helpful assertion for bindings within HTML comments", function() {
view = EmberView.create({
template: EmberHandlebars.compile('<!-- {{view.someThing}} -->'),
someThing: 'foo',
_debugTemplateName: 'blahzorz'
});
expectAssertion(function() {
appendView();
}, 'An error occured while setting up template bindings. Please check "blahzorz" template for invalid markup or bindings within HTML comments.');
});
|
/*!
* angular-loading-bar-fork v0.8.0
* https://chieffancypants.github.io/angular-loading-bar
* Copyright (c) 2015 Wes Cruver
* License: MIT
*/
/*
* angular-loading-bar
*
* intercepts XHR requests and creates a loading bar.
* Based on the excellent nprogress work by rstacruz (more info in readme)
*
* (c) 2013 Wes Cruver
* License: MIT
*/
(function() {
'use strict';
// Alias the loading bar for various backwards compatibilities since the project has matured:
angular.module('angular-loading-bar', ['cfp.loadingBarInterceptor']);
angular.module('chieffancypants.loadingBar', ['cfp.loadingBarInterceptor']);
/**
* loadingBarInterceptor service
*
* Registers itself as an Angular interceptor and listens for XHR requests.
*/
angular.module('cfp.loadingBarInterceptor', ['cfp.loadingBar'])
.config(['$httpProvider', function ($httpProvider) {
var interceptor = ['$q', '$cacheFactory', '$timeout', '$rootScope', '$log', 'cfpLoadingBar', function ($q, $cacheFactory, $timeout, $rootScope, $log, cfpLoadingBar) {
/**
* The total number of requests made
*/
var reqsTotal = 0;
/**
* The number of requests completed (either successfully or not)
*/
var reqsCompleted = 0;
/**
* The amount of time spent fetching before showing the loading bar
*/
var latencyThreshold = cfpLoadingBar.latencyThreshold;
/**
* $timeout handle for latencyThreshold
*/
var startTimeout;
/**
* calls cfpLoadingBar.complete() which removes the
* loading bar from the DOM.
*/
function setComplete() {
$timeout.cancel(startTimeout);
cfpLoadingBar.complete();
reqsCompleted = 0;
reqsTotal = 0;
}
/**
* Determine if the response has already been cached
* @param {Object} config the config option from the request
* @return {Boolean} retrns true if cached, otherwise false
*/
function isCached(config) {
var cache;
var defaultCache = $cacheFactory.get('$http');
var defaults = $httpProvider.defaults;
// Choose the proper cache source. Borrowed from angular: $http service
if ((config.cache || defaults.cache) && config.cache !== false &&
(config.method === 'GET' || config.method === 'JSONP')) {
cache = angular.isObject(config.cache) ? config.cache
: angular.isObject(defaults.cache) ? defaults.cache
: defaultCache;
}
var cached = cache !== undefined ?
cache.get(config.url) !== undefined : false;
if (config.cached !== undefined && cached !== config.cached) {
return config.cached;
}
config.cached = cached;
return cached;
}
return {
'request': function(config) {
// Check to make sure this request hasn't already been cached and that
// the requester didn't explicitly ask us to ignore this request:
if (!config.ignoreLoadingBar && !isCached(config)) {
$rootScope.$broadcast('cfpLoadingBar:loading', {url: config.url});
if (reqsTotal === 0) {
startTimeout = $timeout(function() {
cfpLoadingBar.start();
}, latencyThreshold);
}
reqsTotal++;
cfpLoadingBar.set(reqsCompleted / reqsTotal);
}
return config;
},
'response': function(response) {
if (!response || !response.config) {
$log.error('Broken interceptor detected: Config object not supplied in response:\n https://github.com/chieffancypants/angular-loading-bar/pull/50');
return response;
}
if (!response.config.ignoreLoadingBar && !isCached(response.config)) {
reqsCompleted++;
$rootScope.$broadcast('cfpLoadingBar:loaded', {url: response.config.url, result: response});
if (reqsCompleted >= reqsTotal) {
setComplete();
} else {
cfpLoadingBar.set(reqsCompleted / reqsTotal);
}
}
return response;
},
'responseError': function(rejection) {
if (!rejection || !rejection.config) {
$log.error('Broken interceptor detected: Config object not supplied in rejection:\n https://github.com/chieffancypants/angular-loading-bar/pull/50');
return $q.reject(rejection);
}
if (!rejection.config.ignoreLoadingBar && !isCached(rejection.config)) {
reqsCompleted++;
$rootScope.$broadcast('cfpLoadingBar:loaded', {url: rejection.config.url, result: rejection});
if (reqsCompleted >= reqsTotal) {
setComplete();
} else {
cfpLoadingBar.set(reqsCompleted / reqsTotal);
}
}
return $q.reject(rejection);
}
};
}];
$httpProvider.interceptors.push(interceptor);
}]);
/**
* Loading Bar
*
* This service handles adding and removing the actual element in the DOM.
* Generally, best practices for DOM manipulation is to take place in a
* directive, but because the element itself is injected in the DOM only upon
* XHR requests, and it's likely needed on every view, the best option is to
* use a service.
*/
angular.module('cfp.loadingBar', [])
.provider('cfpLoadingBar', function() {
this.autoIncrement = true;
this.includeSpinner = true;
this.includeBar = true;
this.latencyThreshold = 100;
this.startSize = 0.02;
this.parentSelector = 'body';
this.spinnerTemplate = '<div id="loading-bar-spinner"><div class="spinner-icon"></div></div>';
this.loadingBarTemplate = '<div id="loading-bar"><div class="bar"><div class="peg"></div></div></div>';
this.dotted = true;
this.dottedTemplate = [
'<div class="loader-dotted">',
'<div class="dot"></div>',
'<div class="dot"></div>',
'<div class="dot"></div>',
'</div>'
].join('');
this.$get = ['$injector', '$document', '$timeout', '$rootScope', function ($injector, $document, $timeout, $rootScope) {
var $animate;
var $parentSelector = this.parentSelector,
loadingBarContainer = angular.element(this.loadingBarTemplate),
loadingBar = loadingBarContainer.find('div').eq(0),
spinner = this.dotted ? angular.element(this.dottedTemplate, this.spinnerTemplate) :
angular.element(this.spinnerTemplate);
var incTimeout,
completeTimeout,
started = false,
status = 0;
var autoIncrement = this.autoIncrement;
var includeSpinner = this.includeSpinner;
var includeBar = this.includeBar;
var startSize = this.startSize;
/**
* Inserts the loading bar element into the dom, and sets it to 2%
*/
function _start() {
if (!$animate) {
$animate = $injector.get('$animate');
}
var $parent = $document.find($parentSelector).eq(0);
$timeout.cancel(completeTimeout);
// do not continually broadcast the started event:
if (started) {
return;
}
$rootScope.$broadcast('cfpLoadingBar:started');
started = true;
if (includeBar) {
$animate.enter(loadingBarContainer, $parent, angular.element($parent[0].lastChild));
}
if (includeSpinner) {
$animate.enter(spinner, $parent, angular.element($parent[0].lastChild));
}
_set(startSize);
}
/**
* Set the loading bar's width to a certain percent.
*
* @param n any value between 0 and 1
*/
function _set(n) {
if (!started) {
return;
}
var pct = (n * 100) + '%';
loadingBar.css('width', pct);
status = n;
// increment loadingbar to give the illusion that there is always
// progress but make sure to cancel the previous timeouts so we don't
// have multiple incs running at the same time.
if (autoIncrement) {
$timeout.cancel(incTimeout);
incTimeout = $timeout(function() {
_inc();
}, 250);
}
}
/**
* Increments the loading bar by a random amount
* but slows down as it progresses
*/
function _inc() {
if (_status() >= 1) {
return;
}
var rnd = 0;
// TODO: do this mathmatically instead of through conditions
var stat = _status();
if (stat >= 0 && stat < 0.25) {
// Start out between 3 - 6% increments
rnd = (Math.random() * (5 - 3 + 1) + 3) / 100;
} else if (stat >= 0.25 && stat < 0.65) {
// increment between 0 - 3%
rnd = (Math.random() * 3) / 100;
} else if (stat >= 0.65 && stat < 0.9) {
// increment between 0 - 2%
rnd = (Math.random() * 2) / 100;
} else if (stat >= 0.9 && stat < 0.99) {
// finally, increment it .5 %
rnd = 0.005;
} else {
// after 99%, don't increment:
rnd = 0;
}
var pct = _status() + rnd;
_set(pct);
}
function _status() {
return status;
}
function _completeAnimation() {
status = 0;
started = false;
}
function _complete() {
if (!$animate) {
$animate = $injector.get('$animate');
}
$rootScope.$broadcast('cfpLoadingBar:completed');
_set(1);
$timeout.cancel(completeTimeout);
// Attempt to aggregate any start/complete calls within 500ms:
completeTimeout = $timeout(function() {
var promise = $animate.leave(loadingBarContainer, _completeAnimation);
if (promise && promise.then) {
promise.then(_completeAnimation);
}
$animate.leave(spinner);
}, 500);
}
return {
start : _start,
set : _set,
status : _status,
inc : _inc,
complete : _complete,
autoIncrement : this.autoIncrement,
includeSpinner : this.includeSpinner,
latencyThreshold : this.latencyThreshold,
parentSelector : this.parentSelector,
startSize : this.startSize
};
}]; //
}); // wtf javascript. srsly
})(); //
|
exports.buildUAString = function buildUAString() {
var conf = require('../package.json');
return conf.name + ' / ' + conf.version;
};
|
var classstd_1_1net_1_1ip__address__base =
[
[ "ip_address_base", "dd/d9c/classstd_1_1net_1_1ip__address__base.html#acc822b61826c2365cfd77f103ba659e0", null ],
[ "ip_address_base", "dd/d9c/classstd_1_1net_1_1ip__address__base.html#a0b2564a1f6e2016bf1a6de8c41d88dc2", null ],
[ "getFamily", "dd/d9c/classstd_1_1net_1_1ip__address__base.html#ae1d6838d9be19034286f6891d127d270", null ],
[ "m_addr", "dd/d9c/classstd_1_1net_1_1ip__address__base.html#ae5c42bf0a2684877760d4738d7c5ef63", null ]
]; |
// Post schema
class Post {
comments: ?Array<Comment>;
content: string;
date: Date;
id: string;
image: ?string;
link: ?Object;
user: ?Object;
likes: number;
categories: Array<string>;
}
|
/**
* @license AngularJS v1.4.2-build.4069+sha.ad7200e
* (c) 2010-2015 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {'use strict';
/**
* @ngdoc module
* @name ngRoute
* @description
*
* # ngRoute
*
* The `ngRoute` module provides routing and deeplinking services and directives for angular apps.
*
* ## Example
* See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`.
*
*
* <div doc-module-components="ngRoute"></div>
*/
/* global -ngRouteModule */
var ngRouteModule = angular.module('ngRoute', ['ng']).
provider('$route', $RouteProvider),
$routeMinErr = angular.$$minErr('ngRoute');
/**
* @ngdoc provider
* @name $routeProvider
*
* @description
*
* Used for configuring routes.
*
* ## Example
* See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`.
*
* ## Dependencies
* Requires the {@link ngRoute `ngRoute`} module to be installed.
*/
function $RouteProvider() {
function inherit(parent, extra) {
return angular.extend(Object.create(parent), extra);
}
var routes = {};
/**
* @ngdoc method
* @name $routeProvider#when
*
* @param {string} path Route path (matched against `$location.path`). If `$location.path`
* contains redundant trailing slash or is missing one, the route will still match and the
* `$location.path` will be updated to add or drop the trailing slash to exactly match the
* route definition.
*
* * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up
* to the next slash are matched and stored in `$routeParams` under the given `name`
* when the route matches.
* * `path` can contain named groups starting with a colon and ending with a star:
* e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name`
* when the route matches.
* * `path` can contain optional named groups with a question mark: e.g.`:name?`.
*
* For example, routes like `/color/:color/largecode/:largecode*\/edit` will match
* `/color/brown/largecode/code/with/slashes/edit` and extract:
*
* * `color: brown`
* * `largecode: code/with/slashes`.
*
*
* @param {Object} route Mapping information to be assigned to `$route.current` on route
* match.
*
* Object properties:
*
* - `controller` – `{(string|function()=}` – Controller fn that should be associated with
* newly created scope or the name of a {@link angular.Module#controller registered
* controller} if passed as a string.
* - `controllerAs` – `{string=}` – An identifier name for a reference to the controller.
* If present, the controller will be published to scope under the `controllerAs` name.
* - `template` – `{string=|function()=}` – html template as a string or a function that
* returns an html template as a string which should be used by {@link
* ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives.
* This property takes precedence over `templateUrl`.
*
* If `template` is a function, it will be called with the following parameters:
*
* - `{Array.<Object>}` - route parameters extracted from the current
* `$location.path()` by applying the current route
*
* - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
* template that should be used by {@link ngRoute.directive:ngView ngView}.
*
* If `templateUrl` is a function, it will be called with the following parameters:
*
* - `{Array.<Object>}` - route parameters extracted from the current
* `$location.path()` by applying the current route
*
* - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should
* be injected into the controller. If any of these dependencies are promises, the router
* will wait for them all to be resolved or one to be rejected before the controller is
* instantiated.
* If all the promises are resolved successfully, the values of the resolved promises are
* injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is
* fired. If any of the promises are rejected the
* {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. The map object
* is:
*
* - `key` – `{string}`: a name of a dependency to be injected into the controller.
* - `factory` - `{string|function}`: If `string` then it is an alias for a service.
* Otherwise if function, then it is {@link auto.$injector#invoke injected}
* and the return value is treated as the dependency. If the result is a promise, it is
* resolved before its value is injected into the controller. Be aware that
* `ngRoute.$routeParams` will still refer to the previous route within these resolve
* functions. Use `$route.current.params` to access the new route parameters, instead.
*
* - `redirectTo` – {(string|function())=} – value to update
* {@link ng.$location $location} path with and trigger route redirection.
*
* If `redirectTo` is a function, it will be called with the following parameters:
*
* - `{Object.<string>}` - route parameters extracted from the current
* `$location.path()` by applying the current route templateUrl.
* - `{string}` - current `$location.path()`
* - `{Object}` - current `$location.search()`
*
* The custom `redirectTo` function is expected to return a string which will be used
* to update `$location.path()` and `$location.search()`.
*
* - `[reloadOnSearch=true]` - {boolean=} - reload route when only `$location.search()`
* or `$location.hash()` changes.
*
* If the option is set to `false` and url in the browser changes, then
* `$routeUpdate` event is broadcasted on the root scope.
*
* - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive
*
* If the option is set to `true`, then the particular route can be matched without being
* case sensitive
*
* @returns {Object} self
*
* @description
* Adds a new route definition to the `$route` service.
*/
this.when = function(path, route) {
//copy original route object to preserve params inherited from proto chain
var routeCopy = angular.copy(route);
if (angular.isUndefined(routeCopy.reloadOnSearch)) {
routeCopy.reloadOnSearch = true;
}
if (angular.isUndefined(routeCopy.caseInsensitiveMatch)) {
routeCopy.caseInsensitiveMatch = this.caseInsensitiveMatch;
}
routes[path] = angular.extend(
routeCopy,
path && pathRegExp(path, routeCopy)
);
// create redirection for trailing slashes
if (path) {
var redirectPath = (path[path.length - 1] == '/')
? path.substr(0, path.length - 1)
: path + '/';
routes[redirectPath] = angular.extend(
{redirectTo: path},
pathRegExp(redirectPath, routeCopy)
);
}
return this;
};
/**
* @ngdoc property
* @name $routeProvider#caseInsensitiveMatch
* @description
*
* A boolean property indicating if routes defined
* using this provider should be matched using a case insensitive
* algorithm. Defaults to `false`.
*/
this.caseInsensitiveMatch = false;
/**
* @param path {string} path
* @param opts {Object} options
* @return {?Object}
*
* @description
* Normalizes the given path, returning a regular expression
* and the original path.
*
* Inspired by pathRexp in visionmedia/express/lib/utils.js.
*/
function pathRegExp(path, opts) {
var insensitive = opts.caseInsensitiveMatch,
ret = {
originalPath: path,
regexp: path
},
keys = ret.keys = [];
path = path
.replace(/([().])/g, '\\$1')
.replace(/(\/)?:(\w+)([\?\*])?/g, function(_, slash, key, option) {
var optional = option === '?' ? option : null;
var star = option === '*' ? option : null;
keys.push({ name: key, optional: !!optional });
slash = slash || '';
return ''
+ (optional ? '' : slash)
+ '(?:'
+ (optional ? slash : '')
+ (star && '(.+?)' || '([^/]+)')
+ (optional || '')
+ ')'
+ (optional || '');
})
.replace(/([\/$\*])/g, '\\$1');
ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : '');
return ret;
}
/**
* @ngdoc method
* @name $routeProvider#otherwise
*
* @description
* Sets route definition that will be used on route change when no other route definition
* is matched.
*
* @param {Object|string} params Mapping information to be assigned to `$route.current`.
* If called with a string, the value maps to `redirectTo`.
* @returns {Object} self
*/
this.otherwise = function(params) {
if (typeof params === 'string') {
params = {redirectTo: params};
}
this.when(null, params);
return this;
};
this.$get = ['$rootScope',
'$location',
'$routeParams',
'$q',
'$injector',
'$templateRequest',
'$sce',
function($rootScope, $location, $routeParams, $q, $injector, $templateRequest, $sce) {
/**
* @ngdoc service
* @name $route
* @requires $location
* @requires $routeParams
*
* @property {Object} current Reference to the current route definition.
* The route definition contains:
*
* - `controller`: The controller constructor as define in route definition.
* - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for
* controller instantiation. The `locals` contain
* the resolved values of the `resolve` map. Additionally the `locals` also contain:
*
* - `$scope` - The current route scope.
* - `$template` - The current route template HTML.
*
* @property {Object} routes Object with all route configuration Objects as its properties.
*
* @description
* `$route` is used for deep-linking URLs to controllers and views (HTML partials).
* It watches `$location.url()` and tries to map the path to an existing route definition.
*
* Requires the {@link ngRoute `ngRoute`} module to be installed.
*
* You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API.
*
* The `$route` service is typically used in conjunction with the
* {@link ngRoute.directive:ngView `ngView`} directive and the
* {@link ngRoute.$routeParams `$routeParams`} service.
*
* @example
* This example shows how changing the URL hash causes the `$route` to match a route against the
* URL, and the `ngView` pulls in the partial.
*
* <example name="$route-service" module="ngRouteExample"
* deps="angular-route.js" fixBase="true">
* <file name="index.html">
* <div ng-controller="MainController">
* Choose:
* <a href="Book/Moby">Moby</a> |
* <a href="Book/Moby/ch/1">Moby: Ch1</a> |
* <a href="Book/Gatsby">Gatsby</a> |
* <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
* <a href="Book/Scarlet">Scarlet Letter</a><br/>
*
* <div ng-view></div>
*
* <hr />
*
* <pre>$location.path() = {{$location.path()}}</pre>
* <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
* <pre>$route.current.params = {{$route.current.params}}</pre>
* <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
* <pre>$routeParams = {{$routeParams}}</pre>
* </div>
* </file>
*
* <file name="book.html">
* controller: {{name}}<br />
* Book Id: {{params.bookId}}<br />
* </file>
*
* <file name="chapter.html">
* controller: {{name}}<br />
* Book Id: {{params.bookId}}<br />
* Chapter Id: {{params.chapterId}}
* </file>
*
* <file name="script.js">
* angular.module('ngRouteExample', ['ngRoute'])
*
* .controller('MainController', function($scope, $route, $routeParams, $location) {
* $scope.$route = $route;
* $scope.$location = $location;
* $scope.$routeParams = $routeParams;
* })
*
* .controller('BookController', function($scope, $routeParams) {
* $scope.name = "BookController";
* $scope.params = $routeParams;
* })
*
* .controller('ChapterController', function($scope, $routeParams) {
* $scope.name = "ChapterController";
* $scope.params = $routeParams;
* })
*
* .config(function($routeProvider, $locationProvider) {
* $routeProvider
* .when('/Book/:bookId', {
* templateUrl: 'book.html',
* controller: 'BookController',
* resolve: {
* // I will cause a 1 second delay
* delay: function($q, $timeout) {
* var delay = $q.defer();
* $timeout(delay.resolve, 1000);
* return delay.promise;
* }
* }
* })
* .when('/Book/:bookId/ch/:chapterId', {
* templateUrl: 'chapter.html',
* controller: 'ChapterController'
* });
*
* // configure html5 to get links working on jsfiddle
* $locationProvider.html5Mode(true);
* });
*
* </file>
*
* <file name="protractor.js" type="protractor">
* it('should load and compile correct template', function() {
* element(by.linkText('Moby: Ch1')).click();
* var content = element(by.css('[ng-view]')).getText();
* expect(content).toMatch(/controller\: ChapterController/);
* expect(content).toMatch(/Book Id\: Moby/);
* expect(content).toMatch(/Chapter Id\: 1/);
*
* element(by.partialLinkText('Scarlet')).click();
*
* content = element(by.css('[ng-view]')).getText();
* expect(content).toMatch(/controller\: BookController/);
* expect(content).toMatch(/Book Id\: Scarlet/);
* });
* </file>
* </example>
*/
/**
* @ngdoc event
* @name $route#$routeChangeStart
* @eventType broadcast on root scope
* @description
* Broadcasted before a route change. At this point the route services starts
* resolving all of the dependencies needed for the route change to occur.
* Typically this involves fetching the view template as well as any dependencies
* defined in `resolve` route property. Once all of the dependencies are resolved
* `$routeChangeSuccess` is fired.
*
* The route change (and the `$location` change that triggered it) can be prevented
* by calling `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on}
* for more details about event object.
*
* @param {Object} angularEvent Synthetic event object.
* @param {Route} next Future route information.
* @param {Route} current Current route information.
*/
/**
* @ngdoc event
* @name $route#$routeChangeSuccess
* @eventType broadcast on root scope
* @description
* Broadcasted after a route dependencies are resolved.
* {@link ngRoute.directive:ngView ngView} listens for the directive
* to instantiate the controller and render the view.
*
* @param {Object} angularEvent Synthetic event object.
* @param {Route} current Current route information.
* @param {Route|Undefined} previous Previous route information, or undefined if current is
* first route entered.
*/
/**
* @ngdoc event
* @name $route#$routeChangeError
* @eventType broadcast on root scope
* @description
* Broadcasted if any of the resolve promises are rejected.
*
* @param {Object} angularEvent Synthetic event object
* @param {Route} current Current route information.
* @param {Route} previous Previous route information.
* @param {Route} rejection Rejection of the promise. Usually the error of the failed promise.
*/
/**
* @ngdoc event
* @name $route#$routeUpdate
* @eventType broadcast on root scope
* @description
* The `reloadOnSearch` property has been set to false, and we are reusing the same
* instance of the Controller.
*
* @param {Object} angularEvent Synthetic event object
* @param {Route} current Current/previous route information.
*/
var forceReload = false,
preparedRoute,
preparedRouteIsUpdateOnly,
$route = {
routes: routes,
/**
* @ngdoc method
* @name $route#reload
*
* @description
* Causes `$route` service to reload the current route even if
* {@link ng.$location $location} hasn't changed.
*
* As a result of that, {@link ngRoute.directive:ngView ngView}
* creates new scope and reinstantiates the controller.
*/
reload: function() {
forceReload = true;
$rootScope.$evalAsync(function() {
// Don't support cancellation of a reload for now...
prepareRoute();
commitRoute();
});
},
/**
* @ngdoc method
* @name $route#updateParams
*
* @description
* Causes `$route` service to update the current URL, replacing
* current route parameters with those specified in `newParams`.
* Provided property names that match the route's path segment
* definitions will be interpolated into the location's path, while
* remaining properties will be treated as query params.
*
* @param {!Object<string, string>} newParams mapping of URL parameter names to values
*/
updateParams: function(newParams) {
if (this.current && this.current.$$route) {
newParams = angular.extend({}, this.current.params, newParams);
$location.path(interpolate(this.current.$$route.originalPath, newParams));
// interpolate modifies newParams, only query params are left
$location.search(newParams);
} else {
throw $routeMinErr('norout', 'Tried updating route when with no current route');
}
}
};
$rootScope.$on('$locationChangeStart', prepareRoute);
$rootScope.$on('$locationChangeSuccess', commitRoute);
return $route;
/////////////////////////////////////////////////////
/**
* @param on {string} current url
* @param route {Object} route regexp to match the url against
* @return {?Object}
*
* @description
* Check if the route matches the current url.
*
* Inspired by match in
* visionmedia/express/lib/router/router.js.
*/
function switchRouteMatcher(on, route) {
var keys = route.keys,
params = {};
if (!route.regexp) return null;
var m = route.regexp.exec(on);
if (!m) return null;
for (var i = 1, len = m.length; i < len; ++i) {
var key = keys[i - 1];
var val = m[i];
if (key && val) {
params[key.name] = val;
}
}
return params;
}
function prepareRoute($locationEvent) {
var lastRoute = $route.current;
preparedRoute = parseRoute();
preparedRouteIsUpdateOnly = preparedRoute && lastRoute && preparedRoute.$$route === lastRoute.$$route
&& angular.equals(preparedRoute.pathParams, lastRoute.pathParams)
&& !preparedRoute.reloadOnSearch && !forceReload;
if (!preparedRouteIsUpdateOnly && (lastRoute || preparedRoute)) {
if ($rootScope.$broadcast('$routeChangeStart', preparedRoute, lastRoute).defaultPrevented) {
if ($locationEvent) {
$locationEvent.preventDefault();
}
}
}
}
function commitRoute() {
var lastRoute = $route.current;
var nextRoute = preparedRoute;
if (preparedRouteIsUpdateOnly) {
lastRoute.params = nextRoute.params;
angular.copy(lastRoute.params, $routeParams);
$rootScope.$broadcast('$routeUpdate', lastRoute);
} else if (nextRoute || lastRoute) {
forceReload = false;
$route.current = nextRoute;
if (nextRoute) {
if (nextRoute.redirectTo) {
if (angular.isString(nextRoute.redirectTo)) {
$location.path(interpolate(nextRoute.redirectTo, nextRoute.params)).search(nextRoute.params)
.replace();
} else {
$location.url(nextRoute.redirectTo(nextRoute.pathParams, $location.path(), $location.search()))
.replace();
}
}
}
$q.when(nextRoute).
then(function() {
if (nextRoute) {
var locals = angular.extend({}, nextRoute.resolve),
template, templateUrl;
angular.forEach(locals, function(value, key) {
locals[key] = angular.isString(value) ?
$injector.get(value) : $injector.invoke(value, null, null, key);
});
if (angular.isDefined(template = nextRoute.template)) {
if (angular.isFunction(template)) {
template = template(nextRoute.params);
}
} else if (angular.isDefined(templateUrl = nextRoute.templateUrl)) {
if (angular.isFunction(templateUrl)) {
templateUrl = templateUrl(nextRoute.params);
}
templateUrl = $sce.getTrustedResourceUrl(templateUrl);
if (angular.isDefined(templateUrl)) {
nextRoute.loadedTemplateUrl = templateUrl;
template = $templateRequest(templateUrl);
}
}
if (angular.isDefined(template)) {
locals['$template'] = template;
}
return $q.all(locals);
}
}).
then(function(locals) {
// after route change
if (nextRoute == $route.current) {
if (nextRoute) {
nextRoute.locals = locals;
angular.copy(nextRoute.params, $routeParams);
}
$rootScope.$broadcast('$routeChangeSuccess', nextRoute, lastRoute);
}
}, function(error) {
if (nextRoute == $route.current) {
$rootScope.$broadcast('$routeChangeError', nextRoute, lastRoute, error);
}
});
}
}
/**
* @returns {Object} the current active route, by matching it against the URL
*/
function parseRoute() {
// Match a route
var params, match;
angular.forEach(routes, function(route, path) {
if (!match && (params = switchRouteMatcher($location.path(), route))) {
match = inherit(route, {
params: angular.extend({}, $location.search(), params),
pathParams: params});
match.$$route = route;
}
});
// No route matched; fallback to "otherwise" route
return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
}
/**
* @returns {string} interpolation of the redirect path with the parameters
*/
function interpolate(string, params) {
var result = [];
angular.forEach((string || '').split(':'), function(segment, i) {
if (i === 0) {
result.push(segment);
} else {
var segmentMatch = segment.match(/(\w+)(?:[?*])?(.*)/);
var key = segmentMatch[1];
result.push(params[key]);
result.push(segmentMatch[2] || '');
delete params[key];
}
});
return result.join('');
}
}];
}
ngRouteModule.provider('$routeParams', $RouteParamsProvider);
/**
* @ngdoc service
* @name $routeParams
* @requires $route
*
* @description
* The `$routeParams` service allows you to retrieve the current set of route parameters.
*
* Requires the {@link ngRoute `ngRoute`} module to be installed.
*
* The route parameters are a combination of {@link ng.$location `$location`}'s
* {@link ng.$location#search `search()`} and {@link ng.$location#path `path()`}.
* The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched.
*
* In case of parameter name collision, `path` params take precedence over `search` params.
*
* The service guarantees that the identity of the `$routeParams` object will remain unchanged
* (but its properties will likely change) even when a route change occurs.
*
* Note that the `$routeParams` are only updated *after* a route change completes successfully.
* This means that you cannot rely on `$routeParams` being correct in route resolve functions.
* Instead you can use `$route.current.params` to access the new route's parameters.
*
* @example
* ```js
* // Given:
* // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
* // Route: /Chapter/:chapterId/Section/:sectionId
* //
* // Then
* $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
* ```
*/
function $RouteParamsProvider() {
this.$get = function() { return {}; };
}
ngRouteModule.directive('ngView', ngViewFactory);
ngRouteModule.directive('ngView', ngViewFillContentFactory);
/**
* @ngdoc directive
* @name ngView
* @restrict ECA
*
* @description
* # Overview
* `ngView` is a directive that complements the {@link ngRoute.$route $route} service by
* including the rendered template of the current route into the main layout (`index.html`) file.
* Every time the current route changes, the included view changes with it according to the
* configuration of the `$route` service.
*
* Requires the {@link ngRoute `ngRoute`} module to be installed.
*
* @animations
* enter - animation is used to bring new content into the browser.
* leave - animation is used to animate existing content away.
*
* The enter and leave animation occur concurrently.
*
* @scope
* @priority 400
* @param {string=} onload Expression to evaluate whenever the view updates.
*
* @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll
* $anchorScroll} to scroll the viewport after the view is updated.
*
* - If the attribute is not set, disable scrolling.
* - If the attribute is set without value, enable scrolling.
* - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated
* as an expression yields a truthy value.
* @example
<example name="ngView-directive" module="ngViewExample"
deps="angular-route.js;angular-animate.js"
animations="true" fixBase="true">
<file name="index.html">
<div ng-controller="MainCtrl as main">
Choose:
<a href="Book/Moby">Moby</a> |
<a href="Book/Moby/ch/1">Moby: Ch1</a> |
<a href="Book/Gatsby">Gatsby</a> |
<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
<a href="Book/Scarlet">Scarlet Letter</a><br/>
<div class="view-animate-container">
<div ng-view class="view-animate"></div>
</div>
<hr />
<pre>$location.path() = {{main.$location.path()}}</pre>
<pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre>
<pre>$route.current.params = {{main.$route.current.params}}</pre>
<pre>$routeParams = {{main.$routeParams}}</pre>
</div>
</file>
<file name="book.html">
<div>
controller: {{book.name}}<br />
Book Id: {{book.params.bookId}}<br />
</div>
</file>
<file name="chapter.html">
<div>
controller: {{chapter.name}}<br />
Book Id: {{chapter.params.bookId}}<br />
Chapter Id: {{chapter.params.chapterId}}
</div>
</file>
<file name="animations.css">
.view-animate-container {
position:relative;
height:100px!important;
background:white;
border:1px solid black;
height:40px;
overflow:hidden;
}
.view-animate {
padding:10px;
}
.view-animate.ng-enter, .view-animate.ng-leave {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
display:block;
width:100%;
border-left:1px solid black;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
padding:10px;
}
.view-animate.ng-enter {
left:100%;
}
.view-animate.ng-enter.ng-enter-active {
left:0;
}
.view-animate.ng-leave.ng-leave-active {
left:-100%;
}
</file>
<file name="script.js">
angular.module('ngViewExample', ['ngRoute', 'ngAnimate'])
.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider
.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: 'BookCtrl',
controllerAs: 'book'
})
.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: 'ChapterCtrl',
controllerAs: 'chapter'
});
$locationProvider.html5Mode(true);
}])
.controller('MainCtrl', ['$route', '$routeParams', '$location',
function($route, $routeParams, $location) {
this.$route = $route;
this.$location = $location;
this.$routeParams = $routeParams;
}])
.controller('BookCtrl', ['$routeParams', function($routeParams) {
this.name = "BookCtrl";
this.params = $routeParams;
}])
.controller('ChapterCtrl', ['$routeParams', function($routeParams) {
this.name = "ChapterCtrl";
this.params = $routeParams;
}]);
</file>
<file name="protractor.js" type="protractor">
it('should load and compile correct template', function() {
element(by.linkText('Moby: Ch1')).click();
var content = element(by.css('[ng-view]')).getText();
expect(content).toMatch(/controller\: ChapterCtrl/);
expect(content).toMatch(/Book Id\: Moby/);
expect(content).toMatch(/Chapter Id\: 1/);
element(by.partialLinkText('Scarlet')).click();
content = element(by.css('[ng-view]')).getText();
expect(content).toMatch(/controller\: BookCtrl/);
expect(content).toMatch(/Book Id\: Scarlet/);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ngView#$viewContentLoaded
* @eventType emit on the current ngView scope
* @description
* Emitted every time the ngView content is reloaded.
*/
ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate'];
function ngViewFactory($route, $anchorScroll, $animate) {
return {
restrict: 'ECA',
terminal: true,
priority: 400,
transclude: 'element',
link: function(scope, $element, attr, ctrl, $transclude) {
var currentScope,
currentElement,
previousLeaveAnimation,
autoScrollExp = attr.autoscroll,
onloadExp = attr.onload || '';
scope.$on('$routeChangeSuccess', update);
update();
function cleanupLastView() {
if (previousLeaveAnimation) {
$animate.cancel(previousLeaveAnimation);
previousLeaveAnimation = null;
}
if (currentScope) {
currentScope.$destroy();
currentScope = null;
}
if (currentElement) {
previousLeaveAnimation = $animate.leave(currentElement);
previousLeaveAnimation.then(function() {
previousLeaveAnimation = null;
});
currentElement = null;
}
}
function update() {
var locals = $route.current && $route.current.locals,
template = locals && locals.$template;
if (angular.isDefined(template)) {
var newScope = scope.$new();
var current = $route.current;
// Note: This will also link all children of ng-view that were contained in the original
// html. If that content contains controllers, ... they could pollute/change the scope.
// However, using ng-view on an element with additional content does not make sense...
// Note: We can't remove them in the cloneAttchFn of $transclude as that
// function is called before linking the content, which would apply child
// directives to non existing elements.
var clone = $transclude(newScope, function(clone) {
$animate.enter(clone, null, currentElement || $element).then(function onNgViewEnter() {
if (angular.isDefined(autoScrollExp)
&& (!autoScrollExp || scope.$eval(autoScrollExp))) {
$anchorScroll();
}
});
cleanupLastView();
});
currentElement = clone;
currentScope = current.scope = newScope;
currentScope.$emit('$viewContentLoaded');
currentScope.$eval(onloadExp);
} else {
cleanupLastView();
}
}
}
};
}
// This directive is called during the $transclude call of the first `ngView` directive.
// It will replace and compile the content of the element with the loaded template.
// We need this directive so that the element content is already filled when
// the link function of another directive on the same element as ngView
// is called.
ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route'];
function ngViewFillContentFactory($compile, $controller, $route) {
return {
restrict: 'ECA',
priority: -400,
link: function(scope, $element) {
var current = $route.current,
locals = current.locals;
$element.html(locals.$template);
var link = $compile($element.contents());
if (current.controller) {
locals.$scope = scope;
var controller = $controller(current.controller, locals);
if (current.controllerAs) {
scope[current.controllerAs] = controller;
}
$element.data('$ngControllerController', controller);
$element.children().data('$ngControllerController', controller);
}
link(scope);
}
};
}
})(window, window.angular);
|
/**
*
* ChatLoadMore
*
*/
import React, { PropTypes } from 'react';
import { FormattedMessage } from 'react-intl';
import styled from 'styled-components';
import pallete from 'styles/colors';
import messages from './messages';
const Wrapper = styled.div`
display: flex;
justify-content: center;
align-items: center;
color: ${pallete.theme};
&:hover {
cursor: pointer;
text-decoration: underline;
}
`;
class ChatLoadMore extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
const { visible } = this.props;
return (
<Wrapper>
{visible ?
(<section onTouchTap={() => { this.props.onLoad(); }}>
<FormattedMessage {...messages.header} />
</section>) : null}
</Wrapper>
);
}
}
ChatLoadMore.propTypes = {
onLoad: PropTypes.func,
visible: PropTypes.bool,
};
export default ChatLoadMore;
|
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {'default': obj};
}
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _utilsTransitionEvents = require('./utils/TransitionEvents');
var _utilsTransitionEvents2 = _interopRequireDefault(_utilsTransitionEvents);
var CarouselItem = _react2['default'].createClass({
displayName: 'CarouselItem',
propTypes: {
direction: _react2['default'].PropTypes.oneOf(['prev', 'next']),
onAnimateOutEnd: _react2['default'].PropTypes.func,
active: _react2['default'].PropTypes.bool,
animateIn: _react2['default'].PropTypes.bool,
animateOut: _react2['default'].PropTypes.bool,
caption: _react2['default'].PropTypes.node,
index: _react2['default'].PropTypes.number
},
getInitialState: function getInitialState() {
return {
direction: null
};
},
getDefaultProps: function getDefaultProps() {
return {
animation: true
};
},
handleAnimateOutEnd: function handleAnimateOutEnd() {
if (this.props.onAnimateOutEnd && this.isMounted()) {
this.props.onAnimateOutEnd(this.props.index);
}
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
if (this.props.active !== nextProps.active) {
this.setState({
direction: null
});
}
},
componentDidUpdate: function componentDidUpdate(prevProps) {
if (!this.props.active && prevProps.active) {
_utilsTransitionEvents2['default'].addEndEventListener(_react2['default'].findDOMNode(this), this.handleAnimateOutEnd);
}
if (this.props.active !== prevProps.active) {
setTimeout(this.startAnimation, 20);
}
},
startAnimation: function startAnimation() {
if (!this.isMounted()) {
return;
}
this.setState({
direction: this.props.direction === 'prev' ? 'right' : 'left'
});
},
render: function render() {
var classes = {
item: true,
active: this.props.active && !this.props.animateIn || this.props.animateOut,
next: this.props.active && this.props.animateIn && this.props.direction === 'next',
prev: this.props.active && this.props.animateIn && this.props.direction === 'prev'
};
if (this.state.direction && (this.props.animateIn || this.props.animateOut)) {
classes[this.state.direction] = true;
}
return _react2['default'].createElement(
'div',
_extends({}, this.props, {className: (0, _classnames2['default'])(this.props.className, classes)}),
this.props.children,
this.props.caption ? this.renderCaption() : null
);
},
renderCaption: function renderCaption() {
return _react2['default'].createElement(
'div',
{className: 'carousel-caption'},
this.props.caption
);
}
});
exports['default'] = CarouselItem;
module.exports = exports['default']; |
import React, { PropTypes } from "react";
import Dialog from "rc-dialog";
import ErrorList from "../ErrorList";
import { connect } from "react-redux";
class BaseModal extends React.Component {
static propTypes = {
show: PropTypes.bool,
errorAddr: PropTypes.array,
closeBtnLabel: PropTypes.string,
closeAction: PropTypes.func
};
static defaultProps = {
show: false,
errorAddr: null,
closeBtnLabel: "Ok"
};
close () {
this.props.dispatch(this.props.closeAction());
}
getEndpoint () {
return (
this.props.endpoint ||
this.props.auth.getIn(["configure", "currentEndpointKey"]) ||
this.props.auth.getIn(["configure", "defaultEndpointKey"])
);
}
getErrorList () {
let [base, ...rest] = this.props.errorAddr;
return <ErrorList errors={this.props.auth.getIn([
base, this.getEndpoint(), ...rest
])} />
}
render () {
let body = (this.props.errorAddr)
? this.getErrorList()
: this.props.children;
return (this.props.show)
? (
<Dialog
visible={this.props.show}
className={`redux-auth-modal ${this.props.containerClass}`}
title={this.props.title}
onClose={this.close.bind(this)}>
<div>
<div className="redux-auth-modal-body">
{body}
</div>
<div className="redux-auth-modal-footer">
<button
onClick={this.close.bind(this)}
className={`${this.props.containerClass}-close`}>
{this.props.closeBtnLabel}
</button>
</div>
</div>
</Dialog>
)
: <span />;
}
}
export default connect(({auth}) => ({auth}))(BaseModal);
|
/* globals module */
/**
* @module baasicApiHttp
* @description `baasicApiHttp` service is a core Baasic service that facilitates communication with the Baasic API. `baasicApiHttp` service is based on Angular '$http' service. For more information please visit online angular [documentation](https://docs.angularjs.org/api/ng/service/$http). This service handles:
- authentication tokens and
- HAL parsing.
*/
(function (angular, module, undefined) {
'use strict';
var extend = angular.extend;
function tail(array) {
return Array.prototype.slice.call(array, 1);
}
function createShortMethods(proxy) {
angular.forEach(tail(arguments, 1), function (name) {
proxy[name] = function (url, config) {
return proxy(extend(config || {}, {
method: name,
url: url
}));
};
});
}
function createShortMethodsWithData(proxy) {
angular.forEach(tail(arguments, 1), function (name) {
proxy[name] = function (url, data, config) {
return proxy(extend(config || {}, {
method: name,
url: url,
data: data
}));
};
});
}
var proxyFactory = function proxyFactory(app) {
var proxyMethod = function (config) {
var request = {};
if (config) {
request.url = config.url;
request.method = config.method;
if (config.headers) request.headers = config.headers;
if (config.data) request.data = config.data;
}
return app.apiClient.request(request);
};
createShortMethods(proxyMethod, 'get', 'delete', 'head', 'jsonp');
createShortMethodsWithData(proxyMethod, 'post', 'put', 'patch');
return proxyMethod;
};
module.service('baasicApiHttp', ['$q', 'baasicApp', function baasicApiHttp($q, baasicApp) {
var proxy = proxyFactory(baasicApp.get());
proxy.createNew = function (app) {
return proxyFactory(app);
};
return proxy;
}]);
})(angular, module); |
// foucs時のerr処理
$('.form-group input').focus(function() {
if($(this).val() != '') {
$(this).parent().removeClass('has-error');
$(this).next('.text-danger').hide();
}
}).blur(function() {
if($(this).val() == '') {
$(this).parent().addClass('has-error');
$(this).next('.text-danger').show();
}
if($(this).val() != '') {
$(this).parent().removeClass('has-error');
$(this).next('.text-danger').hide();
}
});
// パスワードの再確認
$('#password2').blur(function() {
if($('#password').val() != $('#password2').val()) {
$('.passwordErr').show();
$(this).parent().addClass('has-error');
}
else {
$('.passwordErr').hide();
$(this).parent().removeClass('has-error');
}
});
$('#send').on('click', function() {
var postFlag = true;
var data = {};
data['lastName'] = $('#lastName').val();
data['firstName'] = $('#firstName').val();
data['rubyLastName'] = $('#rubyLastName').val();
data['rubyFirstName'] = $('#rubyFirstName').val();
data['email'] = $('#email').val();
data['birth'] = $('#birth').val();
data['sex'] = $('#sex').val();
if($('#password').val() == $('#password2').val()) {
data['password'] = $('#password').val();
$('.passwordErr').hide();
}
else {
data['password'] = $('#password').val();
$('#password2').parent().addClass('has-error');
postFlag = false;
}
console.log(data);
// 入力漏れが存在するか確認
Object.keys(data).forEach(function(key) {
if(data[key] == '') {
$('.' + key).parent().addClass('has-error');
$('.' + key).next('.text-danger').show();
postFlag = false;
}
});
console.log(postFlag);
if(postFlag) {
$.ajax({
url: '/app/createAccount',
type: 'POST',
dataType: 'json',
data: data,
success: function(data, textStatus) {
console.log(data);
if(data.results == true) {
alert('アカウント作成に成功しました。');
location.href = '/personal';
}
else if(data.results == false) {
var code = '';
code += '<div class="alert alert-danger alert-dismissible" role="alert">'
code += '<a href="#" type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></a>';
code += data.err;
code += '</div>';
$('.errArea').html(code).hide().fadeIn(600);
}
else {
var code = '';
code += '<div class="alert alert-danger alert-dismissible" role="alert">'
code += '<a href="#" type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></a>';
code += '接続に失敗しました。通信状況を確認してもう一度お試しください';
code += '</div>';
$('.errArea').html(code).hide().fadeIn(600);
}
},
error: function(err) {
alert('接続に失敗しました。通信状況を確認してもう一度お試しください。');
}
});
}
});
|
function draw_red(region) {
var geo = region.geometries[1].coordinates;
var array = [];
for (var j=0; j<geo.length; j++) {
var coords = geo[j];
if (coords.length > 1) {
var polygonCoords = [];
for(var i=0; i<coords.length; i++) {
polygonCoords.push([coords[i][1], coords[i][0]]);
}
array.push(L.polygon(polygonCoords, {color: '#B71B15'}));
} else {
for (var k=0; k< coords.length; k++) {
coords2 = coords[k];
var polygonCoords = [];
for(var i=0; i<coords2.length; i++) {
polygonCoords.push([coords2[i][1], coords2[i][0]]);
}
array.push(L.polygon(polygonCoords, {color: '#B71B15'}));
}
}
}
return array;
}
function draw_green(region, map) {
var geo = region.geometries[1].coordinates;
var array = [];
for (var j=0; j<geo.length; j++) {
var coords = geo[j];
if (coords.length > 1) {
var polygonCoords = [];
for(var i=0; i<coords.length; i++) {
polygonCoords.push([coords[i][1], coords[i][0]]);
}
array.push(L.polygon(polygonCoords, {color: '#58B03B'}));
} else {
for (var k=0; k< coords.length; k++) {
coords2 = coords[k];
var polygonCoords = [];
for(var i=0; i<coords2.length; i++) {
polygonCoords.push([coords2[i][1], coords2[i][0]]);
}
array.push(L.polygon(polygonCoords, {color: '#58B03B'}));
}
}
}
return array;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.