code
stringlengths 2
1.05M
|
---|
var
_ = require('underscore'),
clone = require('clone'),
Promise = require('bluebird'),
ruleDao = require('../persistence/ruleDao'),
actionService = require('./actionService'),
elasticSearchService = require('../../lib/ioc').create('elasticSearchService'),
timeService = require('./timeService'),
ruleConverter = require('../converters/ruleConverter'),
ruleEngineConverter = require('../converters/ruleEngineConverter');
/**
* The rules are the entities stored in the database
*/
var rules;
/**
* Entities cache
*/
var cache = null;
/**
* Rule Engine service.
*
* This service will manage the rules and evaluations of the rules.
*/
module.exports = {
/**
* Populate the rules for the evaluation. This will act as a caching
* mechanism to avoid retrieving the rules for each event received.
*/
populate: function() {
cache = createEmptyCache();
rules = {};
return ruleDao
.findAllEnabled()
.each(function(ruleRetrieved) {
return ruleConverter
.convertForEvaluation(ruleRetrieved, cache)
.then(function(ruleConverted) {
rules[ruleConverted.id] = clone(ruleConverted);
});
})
.then(function() {
console.log('Rules reloaded');
})
.catch(function(err) {
console.log('Unable to populate the rules.');
console.log(err);
})
//.then(function() {
// console.log(cache);
// console.log(rules);
// _.each(rules, console.log);
//})
;
},
/**
* Match the events and send actions if necessary
*
* @param events The events to evaluate
*/
match: function(events) {
var promise = Promise.resolve();
if (_.isUndefined(rules) || _.isNull(rules) || _.isEmpty(rules)) {
promise = promise.then(this.populate());
}
return promise
.then(function() {
return evaluate(cache, rules, events);
})
.then(function(data) {
// Save the matched results to ElasticSearch
_.each(data.matched, function(matched) {
elasticSearchService.saveMatch(matched);
});
// Finally process the actions
if (!_.isEmpty(data.actions)) {
actionService.processActions(data.actions);
}
});
},
/**
* Validate a single rule
*
* @param rule The rule to validate
* @param event The event to validate
* @returns {Object} The result of the validation
*/
validate: function(rule, event) {
var validationCache = createEmptyCache();
var validationRules = {};
return Promise.resolve()
.then(function() {
return ruleConverter
.convertForEvaluation(rule, validationCache)
.then(function(ruleConverted) {
validationRules[ruleConverted.id] = clone(ruleConverted);
})
.then(function() {
return evaluate(validationCache, validationRules, [ event ]);
});
})
.catch(function(err) {
console.log('Unable to validate rule %s.', rule.get('id'));
console.log(err);
});
}
};
/**
* Create an empty cache
*
* @returns {Object} The empty cache
*/
function createEmptyCache() {
return {
actionTargets: {},
actionTargetTemplates: {},
actionTypes: {},
eventSources: {},
eventTypes: {},
rules: {}
};
}
/**
* Evaluate a list of events against the rules with the cache of models
*
* @param cache The cache that contains the different models associated with the rules (action types, ...)
* @param rules The rules that must be evaluated
* @param events The events to evaluate
* @returns {{actions: Array, matched: Array}} The result of matching
*/
function evaluate(cache, rules, events) {
var data = {
actions: [],
matched: []
};
// Analyze each received events
_.each(_.isArray(events) ? events : [events], function (event) {
if (_.isUndefined(event) || _.isNull(event)) {
console.log('The event is null for a strange reason');
return;
}
var eventMatchingResults = {};
// Analyze each active rule
_.each(rules, function (rule) {
// Analyze each condition in the rule
_.each(rule.conditions, function (condition, conditionIndex) {
// Define the fields that can be evaluated
var matchingBy = {
conditionIndex: conditionIndex,
source: isEventSourceDefined(condition),
type: isEventTypeDefined(condition),
function: !_.isUndefined(condition.fn)
};
// Retrieve the evaluator function
var evaluationFn = eventMatchEngine[(matchingBy.source ? 's' : '') + (matchingBy.type ? 't' : '') + (matchingBy.function ? 'f' : '')];
// Evaluate the condition
if (evaluationFn(cache, condition, event)) {
// First match
if (!eventMatchingResults[rule.id]) {
event.matchedAt = timeService.timestamp();
eventMatchingResults[rule.id] = {
rule: clone(rule),
event: clone(event),
matchedConditions: [],
matchedActions: []
};
}
// Store match
eventMatchingResults[rule.id].matchedConditions.push({
matchingBy: matchingBy
});
}
}, this);
}, this);
// Evaluate the matches
_.each(eventMatchingResults, function (eventMatchingResult) {
// Evaluate the transformations
_.each(eventMatchingResult.rule.transformations, function (transformation, transformationIndex) {
// Define the fields that can be evaluated
var matchingBy = {
transformationIndex: transformationIndex,
targetAndType: true // Mandatory evaluation
};
// Evaluate the transformation
var actionTarget = cache.actionTargets[transformation.actionTarget.generatedIdentifier];
var actionTargetTemplate = cache.actionTargetTemplates[actionTarget.get('action_target_template_id')];
var actionType = cache.actionTypes[transformation.actionType.type];
// Process the transformation of the event to the target format
var action;
// Only apply transformation if an expression is available
if (transformation.fn) {
action = transformation.fn.compiled(
event,
ruleEngineConverter.convertActionTarget(actionTarget),
ruleEngineConverter.convertActionType(actionType),
ruleEngineConverter.convertEventSource(event.source ? cache.eventSources[event.source] : null),
ruleEngineConverter.convertEventType(event.type ? cache.eventTypes[event.type] : null),
{ json: JSON, console: console }
);
}
else {
action = _.pick(event, 'timestamp', 'source', 'type', 'properties');
}
// Store transformation
eventMatchingResult.matchedActions.push({
matchingBy: matchingBy,
actionBody: action
});
data.actions.push({
targetUrl: actionTargetTemplate.get('targetUrl'),
targetToken: actionTargetTemplate.get('targetToken'),
target: actionTarget.get('generatedIdentifier'),
type: actionType.get('type'),
properties: action
});
}, this);
// Save in elastic search the event matching result
data.matched.push(eventMatchingResult);
}, this);
}, this);
return data;
}
/**
* Check if an event source is defined on a condition.
*
* @param condition The condition to check
* @returns {boolean} True if the event source is defined
*/
function isEventSourceDefined(condition) {
return !_.isUndefined(condition.eventSource) && !_.isUndefined(condition.eventSource.generatedIdentifier);
}
/**
* Check if an event type is defined on a condition.
*
* @param condition The condition to check
* @returns {boolean} True if the event type is defined
*/
function isEventTypeDefined(condition) {
return !_.isUndefined(condition.eventType) && !_.isUndefined(condition.eventType.type);
}
/**
* Matching array functions to evaluate the different conditions
* regarding of the data that are present in the condition.
*/
var eventMatchEngine = {
f: function(cache, condition, event) { return matchConditionFunction(cache, condition, event); },
t: function(cache, condition, event) { return matchConditionEventType(condition, event); },
s: function(cache, condition, event) { return matchConditionEventSource(condition, event); },
sf: function(cache, condition, event) { return matchConditionEventSource(condition, event) && matchConditionFunction(cache, condition, event); },
tf: function(cache, condition, event) { return matchConditionEventType(condition, event) && matchConditionFunction(cache, condition, event); },
st: function(cache, condition, event) { return matchConditionEventSource(condition, event) && matchConditionEventType(condition, event); },
stf: function(cache, condition, event) { return matchConditionEventSource(condition, event) && matchConditionEventType(condition, event) && matchConditionFunction(cache, condition, event); },
'': function(cache, condition, event) { return false; }
};
/**
* Match an event with the condition based on the event source.
*
* @param condition The condition to evaluate
* @param event The event to evaluate
* @returns {boolean} True if the event source match with the event
*/
function matchConditionEventSource(condition, event) {
return condition.eventSource.generatedIdentifier === event.source;
}
/**
* Match an event with the condition based on the event type.
*
* @param condition The condition to evaluate
* @param event The event to evaluate
* @returns {boolean} True if the event type match with the event
*/
function matchConditionEventType(condition, event) {
return condition.eventType.type === event.type;
}
/**
* Match an event with the condition based on the expression function.
*
* @parma cache Cache that contains retrieved models
* @param condition The condition to evaluate
* @param event The event to evaluate
* @returns {boolean} True if the function is correctly evaluated and return true.
*/
function matchConditionFunction(cache, condition, event) {
return condition.fn.compiled(
event,
ruleEngineConverter.convertEventSource(cache.eventSources[event.source]),
ruleEngineConverter.convertEventType(cache.eventTypes[event.type]),
{ json: JSON, console: console }
);
} |
"use strict";
app.ports.requestDeucePopupPanelInfo.subscribe(function (_) {
// Enough delay so that the menu will actually appear and have height
window.setTimeout(function() {
var deucePopupPanel = document.getElementsByClassName("deuce-popup-panel")[0];
if (deucePopupPanel) {
var info =
{ "height":
deucePopupPanel.offsetHeight
}
app.ports.receiveDeucePopupPanelInfo.send(info);
}
}, 10);
});
|
function euler571() {
// Good luck!
return true
}
euler571()
|
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.AutosizeInput = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var _assign = require('object-assign');
var emptyObject = require('fbjs/lib/emptyObject');
var _invariant = require('fbjs/lib/invariant');
if ("production" !== 'production') {
var warning = require('fbjs/lib/warning');
}
var MIXINS_KEY = 'mixins';
// Helper function to allow the creation of anonymous functions which do not
// have .name set to the name of the variable being assigned to.
function identity(fn) {
return fn;
}
var ReactPropTypeLocationNames;
if ("production" !== 'production') {
ReactPropTypeLocationNames = {
prop: 'prop',
context: 'context',
childContext: 'child context'
};
} else {
ReactPropTypeLocationNames = {};
}
function factory(ReactComponent, isValidElement, ReactNoopUpdateQueue) {
/**
* Policies that describe methods in `ReactClassInterface`.
*/
var injectedMixins = [];
/**
* Composite components are higher-level components that compose other composite
* or host components.
*
* To create a new type of `ReactClass`, pass a specification of
* your new class to `React.createClass`. The only requirement of your class
* specification is that you implement a `render` method.
*
* var MyComponent = React.createClass({
* render: function() {
* return <div>Hello World</div>;
* }
* });
*
* The class specification supports a specific protocol of methods that have
* special meaning (e.g. `render`). See `ReactClassInterface` for
* more the comprehensive protocol. Any other properties and methods in the
* class specification will be available on the prototype.
*
* @interface ReactClassInterface
* @internal
*/
var ReactClassInterface = {
/**
* An array of Mixin objects to include when defining your component.
*
* @type {array}
* @optional
*/
mixins: 'DEFINE_MANY',
/**
* An object containing properties and methods that should be defined on
* the component's constructor instead of its prototype (static methods).
*
* @type {object}
* @optional
*/
statics: 'DEFINE_MANY',
/**
* Definition of prop types for this component.
*
* @type {object}
* @optional
*/
propTypes: 'DEFINE_MANY',
/**
* Definition of context types for this component.
*
* @type {object}
* @optional
*/
contextTypes: 'DEFINE_MANY',
/**
* Definition of context types this component sets for its children.
*
* @type {object}
* @optional
*/
childContextTypes: 'DEFINE_MANY',
// ==== Definition methods ====
/**
* Invoked when the component is mounted. Values in the mapping will be set on
* `this.props` if that prop is not specified (i.e. using an `in` check).
*
* This method is invoked before `getInitialState` and therefore cannot rely
* on `this.state` or use `this.setState`.
*
* @return {object}
* @optional
*/
getDefaultProps: 'DEFINE_MANY_MERGED',
/**
* Invoked once before the component is mounted. The return value will be used
* as the initial value of `this.state`.
*
* getInitialState: function() {
* return {
* isOn: false,
* fooBaz: new BazFoo()
* }
* }
*
* @return {object}
* @optional
*/
getInitialState: 'DEFINE_MANY_MERGED',
/**
* @return {object}
* @optional
*/
getChildContext: 'DEFINE_MANY_MERGED',
/**
* Uses props from `this.props` and state from `this.state` to render the
* structure of the component.
*
* No guarantees are made about when or how often this method is invoked, so
* it must not have side effects.
*
* render: function() {
* var name = this.props.name;
* return <div>Hello, {name}!</div>;
* }
*
* @return {ReactComponent}
* @required
*/
render: 'DEFINE_ONCE',
// ==== Delegate methods ====
/**
* Invoked when the component is initially created and about to be mounted.
* This may have side effects, but any external subscriptions or data created
* by this method must be cleaned up in `componentWillUnmount`.
*
* @optional
*/
componentWillMount: 'DEFINE_MANY',
/**
* Invoked when the component has been mounted and has a DOM representation.
* However, there is no guarantee that the DOM node is in the document.
*
* Use this as an opportunity to operate on the DOM when the component has
* been mounted (initialized and rendered) for the first time.
*
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidMount: 'DEFINE_MANY',
/**
* Invoked before the component receives new props.
*
* Use this as an opportunity to react to a prop transition by updating the
* state using `this.setState`. Current props are accessed via `this.props`.
*
* componentWillReceiveProps: function(nextProps, nextContext) {
* this.setState({
* likesIncreasing: nextProps.likeCount > this.props.likeCount
* });
* }
*
* NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop
* transition may cause a state change, but the opposite is not true. If you
* need it, you are probably looking for `componentWillUpdate`.
*
* @param {object} nextProps
* @optional
*/
componentWillReceiveProps: 'DEFINE_MANY',
/**
* Invoked while deciding if the component should be updated as a result of
* receiving new props, state and/or context.
*
* Use this as an opportunity to `return false` when you're certain that the
* transition to the new props/state/context will not require a component
* update.
*
* shouldComponentUpdate: function(nextProps, nextState, nextContext) {
* return !equal(nextProps, this.props) ||
* !equal(nextState, this.state) ||
* !equal(nextContext, this.context);
* }
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @return {boolean} True if the component should update.
* @optional
*/
shouldComponentUpdate: 'DEFINE_ONCE',
/**
* Invoked when the component is about to update due to a transition from
* `this.props`, `this.state` and `this.context` to `nextProps`, `nextState`
* and `nextContext`.
*
* Use this as an opportunity to perform preparation before an update occurs.
*
* NOTE: You **cannot** use `this.setState()` in this method.
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @param {ReactReconcileTransaction} transaction
* @optional
*/
componentWillUpdate: 'DEFINE_MANY',
/**
* Invoked when the component's DOM representation has been updated.
*
* Use this as an opportunity to operate on the DOM when the component has
* been updated.
*
* @param {object} prevProps
* @param {?object} prevState
* @param {?object} prevContext
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidUpdate: 'DEFINE_MANY',
/**
* Invoked when the component is about to be removed from its parent and have
* its DOM representation destroyed.
*
* Use this as an opportunity to deallocate any external resources.
*
* NOTE: There is no `componentDidUnmount` since your component will have been
* destroyed by that point.
*
* @optional
*/
componentWillUnmount: 'DEFINE_MANY',
// ==== Advanced methods ====
/**
* Updates the component's currently mounted DOM representation.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @internal
* @overridable
*/
updateComponent: 'OVERRIDE_BASE'
};
/**
* Mapping from class specification keys to special processing functions.
*
* Although these are declared like instance properties in the specification
* when defining classes using `React.createClass`, they are actually static
* and are accessible on the constructor instead of the prototype. Despite
* being static, they must be defined outside of the "statics" key under
* which all other static methods are defined.
*/
var RESERVED_SPEC_KEYS = {
displayName: function(Constructor, displayName) {
Constructor.displayName = displayName;
},
mixins: function(Constructor, mixins) {
if (mixins) {
for (var i = 0; i < mixins.length; i++) {
mixSpecIntoComponent(Constructor, mixins[i]);
}
}
},
childContextTypes: function(Constructor, childContextTypes) {
if ("production" !== 'production') {
validateTypeDef(Constructor, childContextTypes, 'childContext');
}
Constructor.childContextTypes = _assign(
{},
Constructor.childContextTypes,
childContextTypes
);
},
contextTypes: function(Constructor, contextTypes) {
if ("production" !== 'production') {
validateTypeDef(Constructor, contextTypes, 'context');
}
Constructor.contextTypes = _assign(
{},
Constructor.contextTypes,
contextTypes
);
},
/**
* Special case getDefaultProps which should move into statics but requires
* automatic merging.
*/
getDefaultProps: function(Constructor, getDefaultProps) {
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps = createMergedResultFunction(
Constructor.getDefaultProps,
getDefaultProps
);
} else {
Constructor.getDefaultProps = getDefaultProps;
}
},
propTypes: function(Constructor, propTypes) {
if ("production" !== 'production') {
validateTypeDef(Constructor, propTypes, 'prop');
}
Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes);
},
statics: function(Constructor, statics) {
mixStaticSpecIntoComponent(Constructor, statics);
},
autobind: function() {}
};
function validateTypeDef(Constructor, typeDef, location) {
for (var propName in typeDef) {
if (typeDef.hasOwnProperty(propName)) {
// use a warning instead of an _invariant so components
// don't show up in prod but only in __DEV__
if ("production" !== 'production') {
warning(
typeof typeDef[propName] === 'function',
'%s: %s type `%s` is invalid; it must be a function, usually from ' +
'React.PropTypes.',
Constructor.displayName || 'ReactClass',
ReactPropTypeLocationNames[location],
propName
);
}
}
}
}
function validateMethodOverride(isAlreadyDefined, name) {
var specPolicy = ReactClassInterface.hasOwnProperty(name)
? ReactClassInterface[name]
: null;
// Disallow overriding of base class methods unless explicitly allowed.
if (ReactClassMixin.hasOwnProperty(name)) {
_invariant(
specPolicy === 'OVERRIDE_BASE',
'ReactClassInterface: You are attempting to override ' +
'`%s` from your class specification. Ensure that your method names ' +
'do not overlap with React methods.',
name
);
}
// Disallow defining methods more than once unless explicitly allowed.
if (isAlreadyDefined) {
_invariant(
specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED',
'ReactClassInterface: You are attempting to define ' +
'`%s` on your component more than once. This conflict may be due ' +
'to a mixin.',
name
);
}
}
/**
* Mixin helper which handles policy validation and reserved
* specification keys when building React classes.
*/
function mixSpecIntoComponent(Constructor, spec) {
if (!spec) {
if ("production" !== 'production') {
var typeofSpec = typeof spec;
var isMixinValid = typeofSpec === 'object' && spec !== null;
if ("production" !== 'production') {
warning(
isMixinValid,
"%s: You're attempting to include a mixin that is either null " +
'or not an object. Check the mixins included by the component, ' +
'as well as any mixins they include themselves. ' +
'Expected object but got %s.',
Constructor.displayName || 'ReactClass',
spec === null ? null : typeofSpec
);
}
}
return;
}
_invariant(
typeof spec !== 'function',
"ReactClass: You're attempting to " +
'use a component class or function as a mixin. Instead, just use a ' +
'regular object.'
);
_invariant(
!isValidElement(spec),
"ReactClass: You're attempting to " +
'use a component as a mixin. Instead, just use a regular object.'
);
var proto = Constructor.prototype;
var autoBindPairs = proto.__reactAutoBindPairs;
// By handling mixins before any other properties, we ensure the same
// chaining order is applied to methods with DEFINE_MANY policy, whether
// mixins are listed before or after these methods in the spec.
if (spec.hasOwnProperty(MIXINS_KEY)) {
RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins);
}
for (var name in spec) {
if (!spec.hasOwnProperty(name)) {
continue;
}
if (name === MIXINS_KEY) {
// We have already handled mixins in a special case above.
continue;
}
var property = spec[name];
var isAlreadyDefined = proto.hasOwnProperty(name);
validateMethodOverride(isAlreadyDefined, name);
if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
RESERVED_SPEC_KEYS[name](Constructor, property);
} else {
// Setup methods on prototype:
// The following member methods should not be automatically bound:
// 1. Expected ReactClass methods (in the "interface").
// 2. Overridden methods (that were mixed in).
var isReactClassMethod = ReactClassInterface.hasOwnProperty(name);
var isFunction = typeof property === 'function';
var shouldAutoBind =
isFunction &&
!isReactClassMethod &&
!isAlreadyDefined &&
spec.autobind !== false;
if (shouldAutoBind) {
autoBindPairs.push(name, property);
proto[name] = property;
} else {
if (isAlreadyDefined) {
var specPolicy = ReactClassInterface[name];
// These cases should already be caught by validateMethodOverride.
_invariant(
isReactClassMethod &&
(specPolicy === 'DEFINE_MANY_MERGED' ||
specPolicy === 'DEFINE_MANY'),
'ReactClass: Unexpected spec policy %s for key %s ' +
'when mixing in component specs.',
specPolicy,
name
);
// For methods which are defined more than once, call the existing
// methods before calling the new property, merging if appropriate.
if (specPolicy === 'DEFINE_MANY_MERGED') {
proto[name] = createMergedResultFunction(proto[name], property);
} else if (specPolicy === 'DEFINE_MANY') {
proto[name] = createChainedFunction(proto[name], property);
}
} else {
proto[name] = property;
if ("production" !== 'production') {
// Add verbose displayName to the function, which helps when looking
// at profiling tools.
if (typeof property === 'function' && spec.displayName) {
proto[name].displayName = spec.displayName + '_' + name;
}
}
}
}
}
}
}
function mixStaticSpecIntoComponent(Constructor, statics) {
if (!statics) {
return;
}
for (var name in statics) {
var property = statics[name];
if (!statics.hasOwnProperty(name)) {
continue;
}
var isReserved = name in RESERVED_SPEC_KEYS;
_invariant(
!isReserved,
'ReactClass: You are attempting to define a reserved ' +
'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' +
'as an instance property instead; it will still be accessible on the ' +
'constructor.',
name
);
var isInherited = name in Constructor;
_invariant(
!isInherited,
'ReactClass: You are attempting to define ' +
'`%s` on your component more than once. This conflict may be ' +
'due to a mixin.',
name
);
Constructor[name] = property;
}
}
/**
* Merge two objects, but throw if both contain the same key.
*
* @param {object} one The first object, which is mutated.
* @param {object} two The second object
* @return {object} one after it has been mutated to contain everything in two.
*/
function mergeIntoWithNoDuplicateKeys(one, two) {
_invariant(
one && two && typeof one === 'object' && typeof two === 'object',
'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.'
);
for (var key in two) {
if (two.hasOwnProperty(key)) {
_invariant(
one[key] === undefined,
'mergeIntoWithNoDuplicateKeys(): ' +
'Tried to merge two objects with the same key: `%s`. This conflict ' +
'may be due to a mixin; in particular, this may be caused by two ' +
'getInitialState() or getDefaultProps() methods returning objects ' +
'with clashing keys.',
key
);
one[key] = two[key];
}
}
return one;
}
/**
* Creates a function that invokes two functions and merges their return values.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createMergedResultFunction(one, two) {
return function mergedResult() {
var a = one.apply(this, arguments);
var b = two.apply(this, arguments);
if (a == null) {
return b;
} else if (b == null) {
return a;
}
var c = {};
mergeIntoWithNoDuplicateKeys(c, a);
mergeIntoWithNoDuplicateKeys(c, b);
return c;
};
}
/**
* Creates a function that invokes two functions and ignores their return vales.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createChainedFunction(one, two) {
return function chainedFunction() {
one.apply(this, arguments);
two.apply(this, arguments);
};
}
/**
* Binds a method to the component.
*
* @param {object} component Component whose method is going to be bound.
* @param {function} method Method to be bound.
* @return {function} The bound method.
*/
function bindAutoBindMethod(component, method) {
var boundMethod = method.bind(component);
if ("production" !== 'production') {
boundMethod.__reactBoundContext = component;
boundMethod.__reactBoundMethod = method;
boundMethod.__reactBoundArguments = null;
var componentName = component.constructor.displayName;
var _bind = boundMethod.bind;
boundMethod.bind = function(newThis) {
for (
var _len = arguments.length,
args = Array(_len > 1 ? _len - 1 : 0),
_key = 1;
_key < _len;
_key++
) {
args[_key - 1] = arguments[_key];
}
// User is trying to bind() an autobound method; we effectively will
// ignore the value of "this" that the user is trying to use, so
// let's warn.
if (newThis !== component && newThis !== null) {
if ("production" !== 'production') {
warning(
false,
'bind(): React component methods may only be bound to the ' +
'component instance. See %s',
componentName
);
}
} else if (!args.length) {
if ("production" !== 'production') {
warning(
false,
'bind(): You are binding a component method to the component. ' +
'React does this for you automatically in a high-performance ' +
'way, so you can safely remove this call. See %s',
componentName
);
}
return boundMethod;
}
var reboundMethod = _bind.apply(boundMethod, arguments);
reboundMethod.__reactBoundContext = component;
reboundMethod.__reactBoundMethod = method;
reboundMethod.__reactBoundArguments = args;
return reboundMethod;
};
}
return boundMethod;
}
/**
* Binds all auto-bound methods in a component.
*
* @param {object} component Component whose method is going to be bound.
*/
function bindAutoBindMethods(component) {
var pairs = component.__reactAutoBindPairs;
for (var i = 0; i < pairs.length; i += 2) {
var autoBindKey = pairs[i];
var method = pairs[i + 1];
component[autoBindKey] = bindAutoBindMethod(component, method);
}
}
var IsMountedPreMixin = {
componentDidMount: function() {
this.__isMounted = true;
}
};
var IsMountedPostMixin = {
componentWillUnmount: function() {
this.__isMounted = false;
}
};
/**
* Add more to the ReactClass base class. These are all legacy features and
* therefore not already part of the modern ReactComponent.
*/
var ReactClassMixin = {
/**
* TODO: This will be deprecated because state should always keep a consistent
* type signature and the only use case for this, is to avoid that.
*/
replaceState: function(newState, callback) {
this.updater.enqueueReplaceState(this, newState, callback);
},
/**
* Checks whether or not this composite component is mounted.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function() {
if ("production" !== 'production') {
warning(
this.__didWarnIsMounted,
'%s: isMounted is deprecated. Instead, make sure to clean up ' +
'subscriptions and pending requests in componentWillUnmount to ' +
'prevent memory leaks.',
(this.constructor && this.constructor.displayName) ||
this.name ||
'Component'
);
this.__didWarnIsMounted = true;
}
return !!this.__isMounted;
}
};
var ReactClassComponent = function() {};
_assign(
ReactClassComponent.prototype,
ReactComponent.prototype,
ReactClassMixin
);
/**
* Creates a composite component class given a class specification.
* See https://facebook.github.io/react/docs/top-level-api.html#react.createclass
*
* @param {object} spec Class specification (which must define `render`).
* @return {function} Component constructor function.
* @public
*/
function createClass(spec) {
// To keep our warnings more understandable, we'll use a little hack here to
// ensure that Constructor.name !== 'Constructor'. This makes sure we don't
// unnecessarily identify a class without displayName as 'Constructor'.
var Constructor = identity(function(props, context, updater) {
// This constructor gets overridden by mocks. The argument is used
// by mocks to assert on what gets mounted.
if ("production" !== 'production') {
warning(
this instanceof Constructor,
'Something is calling a React component directly. Use a factory or ' +
'JSX instead. See: https://fb.me/react-legacyfactory'
);
}
// Wire up auto-binding
if (this.__reactAutoBindPairs.length) {
bindAutoBindMethods(this);
}
this.props = props;
this.context = context;
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
this.state = null;
// ReactClasses doesn't have constructors. Instead, they use the
// getInitialState and componentWillMount methods for initialization.
var initialState = this.getInitialState ? this.getInitialState() : null;
if ("production" !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (
initialState === undefined &&
this.getInitialState._isMockFunction
) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
initialState = null;
}
}
_invariant(
typeof initialState === 'object' && !Array.isArray(initialState),
'%s.getInitialState(): must return an object or null',
Constructor.displayName || 'ReactCompositeComponent'
);
this.state = initialState;
});
Constructor.prototype = new ReactClassComponent();
Constructor.prototype.constructor = Constructor;
Constructor.prototype.__reactAutoBindPairs = [];
injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor));
mixSpecIntoComponent(Constructor, IsMountedPreMixin);
mixSpecIntoComponent(Constructor, spec);
mixSpecIntoComponent(Constructor, IsMountedPostMixin);
// Initialize the defaultProps property after all mixins have been merged.
if (Constructor.getDefaultProps) {
Constructor.defaultProps = Constructor.getDefaultProps();
}
if ("production" !== 'production') {
// This is a tag to indicate that the use of these method names is ok,
// since it's used with createClass. If it's not, then it's likely a
// mistake so we'll warn you to use the static property, property
// initializer or constructor respectively.
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps.isReactClassApproved = {};
}
if (Constructor.prototype.getInitialState) {
Constructor.prototype.getInitialState.isReactClassApproved = {};
}
}
_invariant(
Constructor.prototype.render,
'createClass(...): Class specification must implement a `render` method.'
);
if ("production" !== 'production') {
warning(
!Constructor.prototype.componentShouldUpdate,
'%s has a method called ' +
'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
'The name is phrased as a question because the function is ' +
'expected to return a value.',
spec.displayName || 'A component'
);
warning(
!Constructor.prototype.componentWillRecieveProps,
'%s has a method called ' +
'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?',
spec.displayName || 'A component'
);
}
// Reduce time spent doing lookups by setting these on the prototype.
for (var methodName in ReactClassInterface) {
if (!Constructor.prototype[methodName]) {
Constructor.prototype[methodName] = null;
}
}
return Constructor;
}
return createClass;
}
module.exports = factory;
},{"fbjs/lib/emptyObject":4,"fbjs/lib/invariant":5,"fbjs/lib/warning":6,"object-assign":7}],2:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var React = require('react');
var factory = require('./factory');
if (typeof React === 'undefined') {
throw Error(
'create-react-class could not find the React object. If you are using script tags, ' +
'make sure that React is being loaded before create-react-class.'
);
}
// Hack to grab NoopUpdateQueue from isomorphic React
var ReactNoopUpdateQueue = new React.Component().updater;
module.exports = factory(
React.Component,
React.isValidElement,
ReactNoopUpdateQueue
);
},{"./factory":1,"react":undefined}],3:[function(require,module,exports){
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function emptyFunction() {};
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
module.exports = emptyFunction;
},{}],4:[function(require,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var emptyObject = {};
if ("production" !== 'production') {
Object.freeze(emptyObject);
}
module.exports = emptyObject;
},{}],5:[function(require,module,exports){
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var validateFormat = function validateFormat(format) {};
if ("production" !== 'production') {
validateFormat = function validateFormat(format) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
};
}
function invariant(condition, format, a, b, c, d, e, f) {
validateFormat(format);
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
},{}],6:[function(require,module,exports){
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var emptyFunction = require('./emptyFunction');
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction;
if ("production" !== 'production') {
var printWarning = function printWarning(format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
warning = function warning(condition, format) {
if (format === undefined) {
throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (format.indexOf('Failed Composite propType: ') === 0) {
return; // Ignore CompositeComponent proptype check.
}
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(undefined, [format].concat(args));
}
};
}
module.exports = warning;
},{"./emptyFunction":3}],7:[function(require,module,exports){
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
'use strict';
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
module.exports = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
},{}],8:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
if ("production" !== 'production') {
var invariant = require('fbjs/lib/invariant');
var warning = require('fbjs/lib/warning');
var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');
var loggedTypeFailures = {};
}
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?Function} getStack Returns the component stack.
* @private
*/
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
if ("production" !== 'production') {
for (var typeSpecName in typeSpecs) {
if (typeSpecs.hasOwnProperty(typeSpecName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', location, typeSpecName);
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
} catch (ex) {
error = ex;
}
warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error);
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var stack = getStack ? getStack() : '';
warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : '');
}
}
}
}
}
module.exports = checkPropTypes;
},{"./lib/ReactPropTypesSecret":12,"fbjs/lib/invariant":5,"fbjs/lib/warning":6}],9:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var emptyFunction = require('fbjs/lib/emptyFunction');
var invariant = require('fbjs/lib/invariant');
var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');
module.exports = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret) {
// It is still safe when called from React.
return;
}
invariant(
false,
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use PropTypes.checkPropTypes() to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
};
shim.isRequired = shim;
function getShim() {
return shim;
};
// Important!
// Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
var ReactPropTypes = {
array: shim,
bool: shim,
func: shim,
number: shim,
object: shim,
string: shim,
symbol: shim,
any: shim,
arrayOf: getShim,
element: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim
};
ReactPropTypes.checkPropTypes = emptyFunction;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
},{"./lib/ReactPropTypesSecret":12,"fbjs/lib/emptyFunction":3,"fbjs/lib/invariant":5}],10:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var emptyFunction = require('fbjs/lib/emptyFunction');
var invariant = require('fbjs/lib/invariant');
var warning = require('fbjs/lib/warning');
var ReactPropTypesSecret = require('./lib/ReactPropTypesSecret');
var checkPropTypes = require('./checkPropTypes');
module.exports = function(isValidElement, throwOnDirectAccess) {
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/
var ANONYMOUS = '<<anonymous>>';
// Important!
// Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
symbol: createPrimitiveTypeChecker('symbol'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker
};
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
/*eslint-disable no-self-compare*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/*eslint-enable no-self-compare*/
/**
* We use an Error-like object for backward compatibility as people may call
* PropTypes directly and inspect their output. However, we don't use real
* Errors anymore. We don't inspect their stack anyway, and creating them
* is prohibitively expensive if they are created too often, such as what
* happens in oneOfType() for any type before the one that matched.
*/
function PropTypeError(message) {
this.message = message;
this.stack = '';
}
// Make `instanceof Error` still work for returned errors.
PropTypeError.prototype = Error.prototype;
function createChainableTypeChecker(validate) {
if ("production" !== 'production') {
var manualPropTypeCallCache = {};
var manualPropTypeWarningCount = 0;
}
function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (secret !== ReactPropTypesSecret) {
if (throwOnDirectAccess) {
// New behavior only for users of `prop-types` package
invariant(
false,
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use `PropTypes.checkPropTypes()` to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
} else if ("production" !== 'production' && typeof console !== 'undefined') {
// Old behavior for people using React.PropTypes
var cacheKey = componentName + ':' + propName;
if (
!manualPropTypeCallCache[cacheKey] &&
// Avoid spamming the console because they are often not actionable except for lib authors
manualPropTypeWarningCount < 3
) {
warning(
false,
'You are manually calling a React.PropTypes validation ' +
'function for the `%s` prop on `%s`. This is deprecated ' +
'and will throw in the standalone `prop-types` package. ' +
'You may be seeing this warning due to a third-party PropTypes ' +
'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.',
propFullName,
componentName
);
manualPropTypeCallCache[cacheKey] = true;
manualPropTypeWarningCount++;
}
}
}
if (props[propName] == null) {
if (isRequired) {
if (props[propName] === null) {
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
}
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName, secret) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType = getPreciseType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunction.thatReturnsNull);
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
}
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!isValidElement(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
"production" !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0;
return emptyFunction.thatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (is(propValue, expectedValues[i])) {
return null;
}
}
var valuesString = JSON.stringify(expectedValues);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
}
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
}
for (var key in propValue) {
if (propValue.hasOwnProperty(key)) {
var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
"production" !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0;
return emptyFunction.thatReturnsNull;
}
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (typeof checker !== 'function') {
warning(
false,
'Invalid argument supplid to oneOfType. Expected an array of check functions, but ' +
'received %s at index %s.',
getPostfixForTypeWarning(checker),
i
);
return emptyFunction.thatReturnsNull;
}
}
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) {
return null;
}
}
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (!checker) {
continue;
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
function isSymbol(propType, propValue) {
// Native Symbol.
if (propType === 'symbol') {
return true;
}
// 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
if (propValue['@@toStringTag'] === 'Symbol') {
return true;
}
// Fallback for non-spec compliant Symbols which are polyfilled.
if (typeof Symbol === 'function' && propValue instanceof Symbol) {
return true;
}
return false;
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';
}
if (isSymbol(propType, propValue)) {
return 'symbol';
}
return propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
if (typeof propValue === 'undefined' || propValue === null) {
return '' + propValue;
}
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
// Returns a string that is postfixed to a warning about an invalid type.
// For example, "undefined" or "of type array"
function getPostfixForTypeWarning(value) {
var type = getPreciseType(value);
switch (type) {
case 'array':
case 'object':
return 'an ' + type;
case 'boolean':
case 'date':
case 'regexp':
return 'a ' + type;
default:
return type;
}
}
// Returns class name of the object, if any.
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
ReactPropTypes.checkPropTypes = checkPropTypes;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
},{"./checkPropTypes":8,"./lib/ReactPropTypesSecret":12,"fbjs/lib/emptyFunction":3,"fbjs/lib/invariant":5,"fbjs/lib/warning":6}],11:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
if ("production" !== 'production') {
var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' &&
Symbol.for &&
Symbol.for('react.element')) ||
0xeac7;
var isValidElement = function(object) {
return typeof object === 'object' &&
object !== null &&
object.$$typeof === REACT_ELEMENT_TYPE;
};
// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess = true;
module.exports = require('./factoryWithTypeCheckers')(isValidElement, throwOnDirectAccess);
} else {
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
module.exports = require('./factoryWithThrowingShims')();
}
},{"./factoryWithThrowingShims":9,"./factoryWithTypeCheckers":10}],12:[function(require,module,exports){
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
module.exports = ReactPropTypesSecret;
},{}],13:[function(require,module,exports){
(function (global){
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = (typeof window !== "undefined" ? window['React'] : typeof global !== "undefined" ? global['React'] : null);
var PropTypes = require('prop-types');
var createClass = require('create-react-class');
var sizerStyle = {
position: 'absolute',
top: 0,
left: 0,
visibility: 'hidden',
height: 0,
overflow: 'scroll',
whiteSpace: 'pre'
};
var AutosizeInput = createClass({
propTypes: {
className: PropTypes.string, // className for the outer element
defaultValue: PropTypes.any, // default field value
inputClassName: PropTypes.string, // className for the input element
inputRef: PropTypes.func, // ref callback for the input element
inputStyle: PropTypes.object, // css styles for the input element
minWidth: PropTypes.oneOfType([// minimum width for input element
PropTypes.number, PropTypes.string]),
onAutosize: PropTypes.func, // onAutosize handler: function(newWidth) {}
onChange: PropTypes.func, // onChange handler: function(newValue) {}
placeholder: PropTypes.string, // placeholder text
placeholderIsMinWidth: PropTypes.bool, // don't collapse size to less than the placeholder
style: PropTypes.object, // css styles for the outer element
value: PropTypes.any },
// field value
getDefaultProps: function getDefaultProps() {
return {
minWidth: 1
};
},
getInitialState: function getInitialState() {
return {
inputWidth: this.props.minWidth,
inputId: '_' + Math.random().toString(36).substr(2, 12)
};
},
componentDidMount: function componentDidMount() {
this.mounted = true;
this.copyInputStyles();
this.updateInputWidth();
},
componentDidUpdate: function componentDidUpdate(prevProps, prevState) {
if (prevState.inputWidth !== this.state.inputWidth) {
if (typeof this.props.onAutosize === 'function') {
this.props.onAutosize(this.state.inputWidth);
}
}
this.updateInputWidth();
},
componentWillUnmount: function componentWillUnmount() {
this.mounted = false;
},
inputRef: function inputRef(el) {
this.input = el;
if (typeof this.props.inputRef === 'function') {
this.props.inputRef(el);
}
},
placeHolderSizerRef: function placeHolderSizerRef(el) {
this.placeHolderSizer = el;
},
sizerRef: function sizerRef(el) {
this.sizer = el;
},
copyInputStyles: function copyInputStyles() {
if (!this.mounted || !window.getComputedStyle) {
return;
}
var inputStyle = this.input && window.getComputedStyle(this.input);
if (!inputStyle) {
return;
}
var widthNode = this.sizer;
widthNode.style.fontSize = inputStyle.fontSize;
widthNode.style.fontFamily = inputStyle.fontFamily;
widthNode.style.fontWeight = inputStyle.fontWeight;
widthNode.style.fontStyle = inputStyle.fontStyle;
widthNode.style.letterSpacing = inputStyle.letterSpacing;
widthNode.style.textTransform = inputStyle.textTransform;
if (this.props.placeholder) {
var placeholderNode = this.placeHolderSizer;
placeholderNode.style.fontSize = inputStyle.fontSize;
placeholderNode.style.fontFamily = inputStyle.fontFamily;
placeholderNode.style.fontWeight = inputStyle.fontWeight;
placeholderNode.style.fontStyle = inputStyle.fontStyle;
placeholderNode.style.letterSpacing = inputStyle.letterSpacing;
placeholderNode.style.textTransform = inputStyle.textTransform;
}
},
updateInputWidth: function updateInputWidth() {
if (!this.mounted || !this.sizer || typeof this.sizer.scrollWidth === 'undefined') {
return;
}
var newInputWidth = undefined;
if (this.props.placeholder && (!this.props.value || this.props.value && this.props.placeholderIsMinWidth)) {
newInputWidth = Math.max(this.sizer.scrollWidth, this.placeHolderSizer.scrollWidth) + 2;
} else {
newInputWidth = this.sizer.scrollWidth + 2;
}
if (newInputWidth < this.props.minWidth) {
newInputWidth = this.props.minWidth;
}
if (newInputWidth !== this.state.inputWidth) {
this.setState({
inputWidth: newInputWidth
});
}
},
getInput: function getInput() {
return this.input;
},
focus: function focus() {
this.input.focus();
},
blur: function blur() {
this.input.blur();
},
select: function select() {
this.input.select();
},
render: function render() {
var sizerValue = [this.props.defaultValue, this.props.value, ''].reduce(function (previousValue, currentValue) {
if (previousValue !== null && previousValue !== undefined) {
return previousValue;
}
return currentValue;
});
var wrapperStyle = this.props.style || {};
if (!wrapperStyle.display) wrapperStyle.display = 'inline-block';
var inputStyle = _extends({}, this.props.inputStyle);
inputStyle.width = this.state.inputWidth + 'px';
inputStyle.boxSizing = 'content-box';
var inputProps = _extends({}, this.props);
inputProps.className = this.props.inputClassName;
inputProps.style = inputStyle;
// ensure props meant for `AutosizeInput` don't end up on the `input`
delete inputProps.inputClassName;
delete inputProps.inputStyle;
delete inputProps.minWidth;
delete inputProps.onAutosize;
delete inputProps.placeholderIsMinWidth;
delete inputProps.inputRef;
return React.createElement(
'div',
{ className: this.props.className, style: wrapperStyle },
React.createElement('style', { dangerouslySetInnerHTML: {
__html: ['input#' + this.state.id + '::-ms-clear {display: none;}'].join('\n')
} }),
React.createElement('input', _extends({ id: this.state.id }, inputProps, { ref: this.inputRef })),
React.createElement(
'div',
{ ref: this.sizerRef, style: sizerStyle },
sizerValue
),
this.props.placeholder ? React.createElement(
'div',
{ ref: this.placeHolderSizerRef, style: sizerStyle },
this.props.placeholder
) : null
);
}
});
module.exports = AutosizeInput;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"create-react-class":2,"prop-types":11}]},{},[13])(13)
}); |
import React from 'react'
import { findDOMNode } from 'react-dom'
import { render } from '../TestUtils'
import WindowScroller from './WindowScroller'
function ChildComponent ({ scrollTop, height }) {
return (
<div>{`scrollTop:${scrollTop}, height:${height}`}</div>
)
}
describe('WindowScroller', () => {
function simulateWindowScroll ({
scrollY = 0
}) {
document.body.style.height = '10000px'
window.scrollY = scrollY
document.dispatchEvent(new window.Event('scroll', { bubbles: true }))
document.body.style.height = ''
}
function simulateWindowResize ({
height = 0
}) {
window.innerHeight = height
document.dispatchEvent(new window.Event('resize', { bubbles: true }))
}
function getMarkup ({
onScroll,
onResize
} = {}) {
return (
<WindowScroller
onScroll={onScroll}
onResize={onResize}
>
{({ height, scrollTop }) => (
<ChildComponent
height={height}
scrollTop={scrollTop}
/>
)}
</WindowScroller>
)
}
// Starts updating scrollTop only when the top position is reached
it('should have correct top property to be defined on :_positionFromTop', () => {
const component = render(getMarkup())
const rendered = findDOMNode(component)
const top = rendered.getBoundingClientRect().top
expect(component._positionFromTop).toEqual(top)
})
it('inherits the window height and passes it to child component', () => {
// Set default window height
window.innerHeight = 500
const component = render(getMarkup())
const rendered = findDOMNode(component)
expect(component.state.height).toEqual(window.innerHeight)
expect(component.state.height).toEqual(500)
expect(rendered.textContent).toContain('height:500')
})
describe('onScroll', () => {
it('should trigger callback when window scrolls', async done => {
const onScrollCalls = []
render(getMarkup({
onScroll: params => onScrollCalls.push(params)
}))
simulateWindowScroll({ scrollY: 5000 })
// Allow scrolling timeout to complete so that the component computes state
await new Promise(resolve => setTimeout(resolve, 150))
expect(onScrollCalls.length).toEqual(1)
expect(onScrollCalls[0]).toEqual({
scrollTop: 4992 // 5000 - 8 (position from top)
})
done()
})
it('should update :scrollTop when window is scrolled', async done => {
const component = render(getMarkup())
const rendered = findDOMNode(component)
// Initial load of the component should have 0 scrollTop
expect(rendered.textContent).toContain('scrollTop:0')
simulateWindowScroll({ scrollY: 5000 })
// Allow scrolling timeout to complete so that the component computes state
await new Promise(resolve => setTimeout(resolve, 150))
const componentScrollTop = window.scrollY - component._positionFromTop
expect(component.state.scrollTop).toEqual(componentScrollTop)
expect(rendered.textContent).toContain(`scrollTop:${componentScrollTop}`)
done()
})
})
describe('onResize', () => {
it('should trigger callback when window resizes', () => {
const onResizeCalls = []
render(getMarkup({
onResize: params => onResizeCalls.push(params)
}))
simulateWindowResize({ height: 1000 })
expect(onResizeCalls.length).toEqual(1)
expect(onResizeCalls[0]).toEqual({
height: 1000
})
// Set default window height
window.innerHeight = 500
})
it('should update height when window resizes', () => {
const component = render(getMarkup())
const rendered = findDOMNode(component)
// Initial load of the component should have the same window height = 500
expect(component.state.height).toEqual(window.innerHeight)
expect(component.state.height).toEqual(500)
expect(rendered.textContent).toContain('height:500')
simulateWindowResize({ height: 1000 })
expect(component.state.height).toEqual(window.innerHeight)
expect(component.state.height).toEqual(1000)
expect(rendered.textContent).toContain('height:1000')
// Set default window height
window.innerHeight = 500
})
})
})
|
"use strict";
var should = require('should')
, app = require('../../fixtures/app').app
, DockerAPI = require('../../../lib/docker-api')
, DockerContainer = require('../../../lib/docker-container')
require('should-promised');
describe('docker-api', function () {
var api
it('should return a DockerAPI instance', function () {
api = new DockerAPI(app)
should(api).be.instanceOf(DockerAPI)
})
describe(".listContainers()", function () {
it('should return a Promise and then() should return DockerContainer[]', function (done) {
var promise
promise = api.listContainers()
promise.should.be.Promise()
promise
.then(function (cnts) {
should(cnts).be.Array().and.matchEach(function (value) {
should(value).be.instanceOf(DockerContainer)
})
done()
})
.catch(function (err) {
done(err)
})
})
})
}) |
Space.ui.BlazeComponent.extend('Todos.TodoList', {
dependencies: {
store: 'Todos.TodosStore',
meteor: 'Meteor'
},
todos() {
return this.store.filteredTodos();
},
hasAnyTodos() {
return this.store.filteredTodos().length > 0;
},
allTodosCompleted() {
return this.store.activeTodos().lenght === 0;
},
isToggleChecked() {
if (this.hasAnyTodos() && this.allTodosCompleted()) {
return 'checked';
} else {
return false;
}
},
events() {
return [{
'click .toggle-all': this.toggleAllTodos
}];
},
toggleAllTodos() {
switch (this.store.activeFilter()) {
case this.store.FILTERS.ALL:
if (this.store.activeTodos().length > 0) {
return this._completeOpenTodos();
} else {
return this._reopenCompleteTodos();
}
case this.store.FILTERS.ACTIVE:
return this._completeOpenTodos();
case this.store.FILTERS.COMPLETED:
return this._reopenCompleteTodos();
}
},
_completeOpenTodos() {
for (let todo of this.store.activeTodos()) {
this.publish(new Todos.TodoCompleted({
todoId: todo.id
}));
}
},
_reopenCompleteTodos() {
for (let todo of this.store.completedTodos()) {
this.publish(new Todos.TodoReopened({
todoId: todo.id
}));
}
}
})
// Register blaze-component for template
.register('todo_list');
|
// Karma configuration
// Generated on Fri Nov 15 2013 00:26:38 GMT-0700 (MST)
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// frameworks to use
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'src/**/*.js',
'test/**/*Spec.js'
],
// list of files to exclude
exclude: [
],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera (has to be installed with `npm install karma-opera-launcher`)
// - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
// - PhantomJS
// - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
browsers: ['Chrome'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
|
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = Reference;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose"));
var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var React = _interopRequireWildcard(require("react"));
var _warning = _interopRequireDefault(require("warning"));
var _Manager = require("./Manager");
var _utils = require("./utils");
var InnerReference =
/*#__PURE__*/
function (_React$Component) {
(0, _inheritsLoose2.default)(InnerReference, _React$Component);
function InnerReference() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
(0, _defineProperty2.default)((0, _assertThisInitialized2.default)((0, _assertThisInitialized2.default)(_this)), "refHandler", function (node) {
(0, _utils.safeInvoke)(_this.props.innerRef, node);
(0, _utils.safeInvoke)(_this.props.setReferenceNode, node);
});
return _this;
}
var _proto = InnerReference.prototype;
_proto.render = function render() {
(0, _warning.default)(Boolean(this.props.setReferenceNode), '`Reference` should not be used outside of a `Manager` component.');
return (0, _utils.unwrapArray)(this.props.children)({
ref: this.refHandler
});
};
return InnerReference;
}(React.Component);
function Reference(props) {
return React.createElement(_Manager.ManagerContext.Consumer, null, function (_ref) {
var setReferenceNode = _ref.setReferenceNode;
return React.createElement(InnerReference, (0, _extends2.default)({
setReferenceNode: setReferenceNode
}, props));
});
} |
function string(str, l) {
str = str ? str : '';
return str.length <= l ? true : false;
}
function imageHW(file, h, w) {
// TODO: create validation image
return true;
}
function arrayString(str, l) {
str = str ? str : '';
var strArr = str.split(',');
var flag = true;
strArr.forEach(function(e, i) {
if (e.length > l) {
flag = false;
return flag;
}
});
return flag;
}
module.exports = {
string: string,
image: imageHW,
arrayString: arrayString
};
|
"use strict";
var gulp = require('gulp'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
rename = require('gulp-rename'),
sass = require('gulp-sass'),
maps = require('gulp-sourcemaps'),
del = require('del');
gulp.task("concatScripts", function() {
return gulp.src([
'js/jquery.js',
'js/sticky/jquery.sticky.js',
'js/main.js'
])
.pipe(maps.init())
.pipe(concat('app.js'))
.pipe(maps.write('./'))
.pipe(gulp.dest('js'));
});
gulp.task("minifyScripts", ["concatScripts"], function() {
return gulp.src("js/app.js")
.pipe(uglify())
.pipe(rename('app.min.js'))
.pipe(gulp.dest('js'));
});
gulp.task('compileSass', function() {
return gulp.src("scss/application.scss")
.pipe(maps.init())
.pipe(sass())
.pipe(maps.write('./'))
.pipe(gulp.dest('css'));
})
gulp.task('watchFiles', function(){
gulp.watch('scss/**/*.scss', ['compileSass']);
gulp.watch('js/main.js', ['concatScripts']);
})
gulp.task('clean', function(){
del(['dist', 'css/application.css*', 'js/app*.js*']);
})
gulp.task("build", ['minifyScripts', 'compileSass'], function(){
return gulp.src(["css/application.js", "js/app.min.js", "index.html", "img/**", "fonts/**"], {base: './'})
.pipe(gulp.dest('dist'));
});
gulp.task('serve', ['watchFiles']);
gulp.task("default", ["clean"], function(){
gulp.start('build');
});
|
/**
* @Author: will
* @Date: 2017-08-09T23:33:32+08:00
* @Filename: ToastView.js
* @Last modified by: will
* @Last modified time: 2017-08-12T17:12:02+08:00
*/
// ToastView.js
'use strict';
import React, {Component} from "react";
import PropTypes from 'prop-types';
import {View, Image, Text} from 'react-native';
import Theme from '../themes/Theme';
import Overlay from '../Overlay/Overlay';
export default class ToastView extends Overlay.View {
static propTypes = {
...Overlay.View.propTypes,
text: PropTypes.oneOfType([PropTypes.element, PropTypes.string, PropTypes.number]),
icon: PropTypes.oneOfType([
PropTypes.element,
PropTypes.shape({uri: PropTypes.string}), //{uri: 'http://...'}
PropTypes.number, //require('path/to/image')
PropTypes.oneOf(['none', 'success', 'fail', 'smile', 'sad', 'info', 'stop']),
]),
position: PropTypes.oneOf(['top', 'bottom', 'center']),
};
static defaultProps = {
...Overlay.View.defaultProps,
overlayOpacity: 0,
overlayPointerEvents: 'none',
position: 'center',
};
buildProps() {
super.buildProps();
let {style, text, icon, position, ...others} = this.props;
style = [{
paddingLeft: Theme.toastScreenPaddingLeft,
paddingRight: Theme.toastScreenPaddingRight,
paddingTop: Theme.toastScreenPaddingTop,
paddingBottom: Theme.toastScreenPaddingBottom,
justifyContent: position === 'top' ? 'flex-start' : (position === 'bottom' ? 'flex-end' : 'center'),
alignItems: 'center',
}].concat(style);
let contentStyle = {
backgroundColor: Theme.toastColor,
paddingLeft: Theme.toastPaddingLeft,
paddingRight: Theme.toastPaddingRight,
paddingTop: Theme.toastPaddingTop,
paddingBottom: Theme.toastPaddingBottom,
borderRadius: Theme.toastBorderRadius,
alignItems: 'center',
};
if (typeof text === 'string' || typeof text === 'number') {
text = (
<Text style={{color: Theme.toastTextColor, fontSize: Theme.toastFontSize}}>{text}</Text>
);
}
if (icon || icon === 0) {
let image;
if (!React.isValidElement(icon)) {
let imageSource;
if (typeof icon === 'string') {
switch (icon) {
case 'success': imageSource = require('../icons/success.png'); break;
case 'fail': imageSource = require('../icons/fail.png'); break;
case 'smile': imageSource = require('../icons/smile.png'); break;
case 'sad': imageSource = require('../icons/sad.png'); break;
case 'info': imageSource = require('../icons/info.png'); break;
case 'stop': imageSource = require('../icons/stop.png'); break;
default: imageSource = null; break;
}
} else {
imageSource = icon;
}
image = (
<Image
style={{width: Theme.toastIconWidth, height: Theme.toastIconHeight, tintColor: Theme.toastIconTintColor}}
source={imageSource}
/>
);
} else {
image = icon;
}
icon = (
<View style={{paddingTop: Theme.toastIconPaddingTop, paddingBottom: Theme.toastIconPaddingBottom}}>
{image}
</View>
);
}
this.props = {style, contentStyle, text, icon, position, ...others};
}
renderContent() {
let {contentStyle, text, icon} = this.props;
return (
<View style={contentStyle}>
{icon}
{text}
</View>
);
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:3b45ceba2068a1a065c2a51775b112b84c605f3d246ce7e0e29ff5517788dcb0
size 521
|
var path = require('path')
, testutil = global.testutil = require('../lib/index.js')
, testGroup = createTestGroup()
global.requireUnit = function(testFilename) {
return testutil.requireUnit(testFilename, undefined, testGroup)
}
testutil.includeTests(path.dirname(module.filename), module.exports, testGroup)
/**
* Normally wouldn't have to create this from scratch if you are just changing the srcFolder
* however this was done to preserve the original data in basicTestGroups
*/
function createTestGroup() {
var TestGroup = testutil.TestGroup
return new TestGroup( "test"
, "lib")
} |
angular.module( 'multiLanguage' )
.provider( '$multiLanguageConfig', function() {
var supportedLanguages = 'en,es,de,fr,ru'.split( ',' );
var map = {
en: 'us',
es: 'es',
de: 'de',
fr: 'fr',
ru: 'ru',
};
var tabTemplate = [
'<ul class="nav nav-tabs" role="tablist">',
'<li role="presentation" ng-class="{\'active\':$index ==0}" ng-repeat="l in supportedLanguages">',
'<a data-target="#lang{{random}}-{{l}}" role="tab" data-toggle="tab"> <span class="flag-icon flag-icon-{{map[l]}}"></span> {{l}} </a>',
'</li>',
'<li role="presentation">',
'<a ng-click="translate()"><span class="fa fa-language fa-2"></span> Translate </a>',
'</li>',
'</ul>',
].join( '\n' );
var tabPanelTemplate = [
'<div class="tab-content">',
'<div role="tabpanel" ng-class="{\'active\':$index ==0}" class="tab-pane" id="lang{{random}}-{{lt}}" ng-repeat="lt in supportedLanguages"></div>',
'</div>',
].join( '\n' );
this.$get = function() {
return {
supportedLanguages: supportedLanguages,
map : map,
tabTemplate : tabTemplate,
tabPanelTemplate : tabPanelTemplate,
};
};
} ); |
import React from 'react';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
// Helpers
import { rewriteMediaLink } from 'utils/rewrite';
// Styles
import './common.css';
// Polyfill
require('es6-promise').polyfill();
require('isomorphic-fetch');
// Components
import Post from 'components/Utils/Post';
import DetailAvatar from 'components/Popup/Action/Detail/DetailAvatar';
import DetailActions from 'components/Popup/Action/Detail/DetailActions';
import DetailIcon from 'components/Popup/Action/Detail/DetailIcon';
const DetailContainerWrapper = ({ provider, post, viewCount, sharers, children }) => (
<div className={`detail__container provider--${provider}`}>
<DetailActions>
<DetailIcon
name="share"
text={{ type: 'count', content: sharers.length }}
/>
<DetailIcon
name="detail"
text={{ type: 'count', content: viewCount }}
/>
<DetailIcon
name="like"
text={{ type: 'count', content: post.like_count }}
active={false}
/>
{children}
</DetailActions>
<DetailAvatar type="share" provider={provider} list={sharers} />
</div>
);
const DetailContainer = props => {
const { provider, post } = props;
let DetailComponents;
switch (provider) {
case 'twitter':
case 'weibo':
DetailComponents = (
<DetailContainerWrapper {...props}>
<DetailIcon
name="retweet"
text={{ type: 'count', content: post.retweet_count }}
active={false}
/>
</DetailContainerWrapper>
);
break;
case 'unsplash':
DetailComponents = (
<DetailContainerWrapper {...props}>
<DetailIcon
name="download"
text={{ type: 'count', content: post.download_count }}
/>
</DetailContainerWrapper>
);
break;
default:
break;
}
return DetailComponents;
};
class Share extends React.Component {
constructor(props) {
super(props);
this.state = ({ center: true });
this.checkDetailHeight = this.checkDetailHeight.bind(this);
}
componentDidMount() {
this.POST_WITH_MEDIA = (() => {
const { data } = window.__share_data__;
return data.media || (data.quote && data.quote.media);
})();
this.checkDetailHeight();
setInterval(() => {
this.checkDetailHeight();
}, 1000);
// Auto Pause All Video
window.addEventListener('blur', () => {
const videos = document.getElementsByTagName('video');
[].forEach.call(videos, video => {
video.pause();
});
});
}
shouldComponentUpdate(nextProps, nextState) {
return this.state.center !== nextState.center;
}
checkDetailHeight() {
if (this.refs.detail.offsetHeight < window.innerHeight && !this.POST_WITH_MEDIA) {
this.setState({ center: true });
} else {
this.setState({ center: false });
}
}
render() {
const { data, sharers, viewCount } = window.__share_data__;
const { provider } = data;
const wrapperClass = classNames({
popup__wrapper: true,
center: this.state.center,
});
return (
<div className="oneline oneline--timeline animate--general">
<div className="popup overflow--y">
<div className={wrapperClass}>
<div className="detail overflow--y animate--enter" ref="detail">
<Post
className="detail__post"
post={rewriteMediaLink({
type: 'post',
provider,
data,
})}
/>
<DetailContainer
provider={provider}
post={data}
viewCount={viewCount}
sharers={rewriteMediaLink({
type: 'sharers',
provider,
data: sharers,
})}
/>
</div>
</div>
</div>
</div>
);
}
}
// Render
ReactDOM.render(
<Share />,
document.querySelector('.root')
);
|
'use strict'
const {INTEGER, STRING, FLOAT} = require('sequelize')
module.exports = db => db.define('movies_genres', {
movie_id: {
type: INTEGER,
defaultValue: null,
primaryKey: true,
},
genre: {
type: STRING,
defaultValue: null,
},
})
module.exports.associations = (Movie_genre, {Movie}) => {
Movie_genre.belongsTo(Movie)
} |
// ==UserScript==
// @name BuyHightech
// @namespace https://github.com/MyRequiem/comfortablePlayingInGW
// @description В HighTech магазине добавляет ссылки "Продать" и "Купить" для каждого предмета. При клике открывается страница с формой подачи объявления для данного предмета.
// @id comfortablePlayingInGW@MyRequiem
// @updateURL https://raw.githubusercontent.com/MyRequiem/comfortablePlayingInGW/master/separatedScripts/BuyHightech/buyHightech.meta.js
// @downloadURL https://raw.githubusercontent.com/MyRequiem/comfortablePlayingInGW/master/separatedScripts/BuyHightech/buyHightech.user.js
// @include https://*gwars.ru/shopc.php*
// @include https://*gwars.ru/market-p.php?stage=2&item_id=*
// @grant none
// @license MIT
// @version 2.09-130820
// @author MyRequiem [https://www.gwars.ru/info.php?id=2095458]
// ==/UserScript==
/*global unsafeWindow */
/*jslint browser: true, maxlen: 80, vars: true, plusplus: true, regexp: true */
/*eslint-env browser */
/*eslint no-useless-escape: 'warn', linebreak-style: ['error', 'unix'],
quotes: ['error', 'single'], semi: ['error', 'always'],
eqeqeq: 'error', curly: 'error'
*/
/*jscs:disable requireMultipleVarDecl, requireVarDeclFirst */
/*jscs:disable disallowKeywords, disallowDanglingUnderscores */
/*jscs:disable validateIndentation */
(function () {
'use strict';
/**
* @class General
* @constructor
*/
var General = function () {
/**
* @property root
* @type {Object}
*/
this.root = this.getRoot();
/**
* @property doc
* @type {Object}
*/
this.doc = this.root.document;
/**
* @property loc
* @type {String}
*/
this.loc = this.root.location.href;
};
/**
* @lends General.prototype
*/
General.prototype = {
/**
* @method getRoot
* @return {Object}
*/
getRoot: function () {
var rt = typeof unsafeWindow;
return rt !== 'undefined' ? unsafeWindow : window;
}
};
var general = new General();
/**
* @class BuyHightech
* @constructor
*/
var BuyHightech = function () {
/**
* @method init
*/
this.init = function () {
if (/\/shopc\.php/.test(general.loc)) {
var descrTd = general.doc.querySelectorAll('td[class$=' +
'"lightbg"][valign="top"][align="left"]' +
'[width="100%"]'),
strength,
price,
id,
i;
for (i = 0; i < descrTd.length; i++) {
id = /id=(.+)$/.exec(descrTd[i].parentNode.
querySelector('a').href)[1];
price = /(\d+) EUN/.exec(descrTd[i].innerHTML)[1];
strength = /Прочность:<\/b> (\d+)/i.
exec(descrTd[i].innerHTML)[1];
descrTd[i].removeChild(descrTd[i].lastElementChild);
descrTd[i].innerHTML += ' <span style="font-weight: ' +
'bold; margin-left: 7px;"> Создать объявление: ' +
'</span><a target="_blank" style="color: #0000FF;" ' +
'href="https://www.gwars.ru/market-p.php?' +
'stage=2&item_id=' + id + '&action_id=2&p=' + price +
'&s=' + strength + '">[Купить]' + '</a> ' +
'<a target="_blank" style="color: #990000;" href=' +
'"https://www.gwars.ru/market-p.php?' +
'stage=2&item_id=' + id + '&action_id=1&p=' + price +
'&s=' + strength + '">[Продать]</a>';
}
return;
}
// на странице подачи объявлений
var param = /&p=(\d+)&s=(\d+)$/.exec(general.loc);
if (param) {
general.doc.querySelector('td[colspan="3"]' +
'[class="greenlightbg"]').innerHTML += ' <span ' +
'style="color: #990000;">[Стоимость в магазине: ' +
param[1] + ' EUN]</span>';
//остров любой
general.doc.querySelector('select[name="island"]').value = '-1';
var dur1 = general.doc.
querySelector('input[name="durability1"]'),
dur2 = general.doc.
querySelector('input[name="durability2"]');
//если продаем, то прочность максимальная,
//если покупаем, то минимальная
if (/action_id=1/.test(general.loc)) {
dur1.value = param[2];
dur2.value = param[2];
} else {
dur1.value = '0';
dur2.value = '1';
}
// срок размещения 7 дней
general.doc.
querySelector('select[name="date_len"]').value = '7';
}
};
};
new BuyHightech().init();
}());
|
define(function() {
var doc = document.documentElement;
return {
getTop: function() {
return (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
},
getLeft: function() {
return (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
}
};
});
|
'use strict';
var _ = require('lodash');
var mongo = require('../../lib/mongo/');
function User(p) {
this.text = p.text;
}
Object.defineProperty(User, 'collection', {
get: function () { // the function returned will be used as the value of the property
return mongo.getDb().collection('user');
}
});
User.dropCollection = function (cb) {
User.collection.drop(cb);
};
module.exports = User;
|
/*
Gradebook from Names and Scores
I worked on this challenge with Gary Wong
This challenge took me 1 hours.
You will work with the following two variables. The first, students, holds the names of four students.
The second, scores, holds groups of test scores. The relative positions of elements within the two
variables match (i.e., 'Joseph' is the first element in students; his scores are the first value in scores.).
Do not alter the students and scores code.
*/
var students = ["Joseph", "Susan", "William", "Elizabeth"]
var scores = [ [80, 70, 70, 100],
[85, 80, 90, 90],
[75, 70, 80, 75],
[100, 90, 95, 85] ]
// __________________________________________
// Write your code below.
var gradebook = {};
for (var student in students){
gradebook[students[student]] = {
testScores: scores[student]
};
}
// console.log(gradebook);
gradebook.addScore = function(name, score) {
gradebook[name]['testScores'].push(score);
}
gradebook.getAverage = function(){}
function average(array) {
var sum = 0;
for (var num in array) {
sum += array[num];
}
return sum/array.length;
}
gradebook.getAverage = function(name){
return average(gradebook[name]['testScores']);
}
// console.log(gradebook.getAverage("William"));
// console.log(average([80, 70, 70, 100]));
// console.log(gradebook);
// __________________________________________
// Refactored Solution
var gradebook = {};
for (var student in students){
gradebook[students[student]] = {testScores: scores[student]};
}
// console.log(gradebook);
gradebook.addScore = function(name, score) {
gradebook[name]['testScores'].push(score);
}
function average(array) {
var sum = 0;
for (var i = 0, j = array.length; i < j; i++) {sum += array[i];}
return sum/array.length;
}
gradebook.getAverage = function(name){
return average(gradebook[name]['testScores']);
}
// __________________________________________
// Reflect
// What did you learn about adding functions to objects?
// I learned that you can just add an empty function to an object by using object.functionName = function() {},
// and go back and fill out the function later.
// How did you iterate over nested arrays in JavaScript?
// We used students[student] as a key, so gradebook[students[student]] = {etc}. And since (for num in array) produces
// the indices 0, 1, 2, 3 etc as num, we could reuse the index in the line
// gradebook[students[student]] = {testScores: scores[student]}.
// We used for.. in loops in the initial solution, though I think using a normal loop -
// for (var i = 0; i < etc; i++) is better practice in many situations in JavaScript.
// Were there any new methods you were able to incorporate? If so, what were they and how did they work?
// We did not use any new methods. The syntax was pretty simple. We used push to add a value, and for/for..in loops.
// __________________________________________
// Test Code: Do not alter code below this line.
function assert(test, message, test_number) {
if (!test) {
console.log(test_number + "false");
throw "ERROR: " + message;
}
console.log(test_number + "true");
return true;
}
assert(
(gradebook instanceof Object),
"The value of gradebook should be an Object.\n",
"1. "
)
assert(
(gradebook["Elizabeth"] instanceof Object),
"gradebook's Elizabeth property should be an object.",
"2. "
)
assert(
(gradebook.William.testScores === scores[2]),
"William's testScores should equal the third element in scores.",
"3. "
)
assert(
(gradebook.addScore instanceof Function),
"The value of gradebook's addScore property should be a Function.",
"4. "
)
gradebook.addScore("Susan", 80)
assert(
(gradebook.Susan.testScores.length === 5
&& gradebook.Susan.testScores[4] === 80),
"Susan's testScores should have a new score of 80 added to the end.",
"5. "
)
assert(
(gradebook.getAverage instanceof Function),
"The value of gradebook's getAverage property should be a Function.",
"6. "
)
assert(
(average instanceof Function),
"The value of average should be a Function.\n",
"7. "
)
assert(
average([1, 2, 3]) === 2,
"average should return the average of the elements in the array argument.\n",
"8. "
)
assert(
(gradebook.getAverage("Joseph") === 80),
"gradebook's getAverage should return 80 if passed 'Joseph'.",
"9. "
) |
var audio = new Audio();
function playAudio(string, lang) {
if (typeof(lang) === 'undefined') lang='ru';
audio.src = 'api/tts/' + lang + '?s=' + encodeURIComponent(string);
audio.play();
}
var recognizing = false;
var onEndUser;
var transcript = '';
try {
var recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.lang = 'ru-RU';
recognition.interimResults = false;
recognition.onstart = function() {
recognizing = true;
};
recognition.onerror = function(event) {
if (event.error === 'no-speech') {
}
if (event.error === 'audio-capture') {
console.log("onerror " + event.error);
ignore_onend = true;
}
if (event.error === 'not-allowed') {
console.log("onerror " + event.error);
ignore_onend = true;
}
};
recognition.onresult = function(event) {
if ( typeof (event.results) === 'undefined') {
recognition.onend = null;
recognition.stop();
return;
}
for (var i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
transcript += event.results[i][0].transcript;
recognition.stop();
}
}
};
recognition.onend = function() {
if (ignore_onend) {
return;
}
recognizing = false;
onEndUser(transcript);
};
}
catch(error) {
console.error(error);
// expected output: SyntaxError: unterminated string literal
// Note - error messages will vary depending on browser
}
function sendCommand(command) {
$.ajax({
url : "/speech/command",
type : "POST",
data : {
transcript : command
},
success : function(resp) {
}
});
}
function startRecognizing(onEnd) {
onEndUser = onEnd;
if (recognizing) {
recognizing = false;
recognition.stop();
return;
}
transcript = '';
recognition.start();
ignore_onend = false;
start_timestamp = event.timeStamp;
}
|
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
all: ['*.js'],
options: {
node: true,
'-W030': true, // to allow mocha expects syntax
globals: {
before: false,
after: false,
beforeEach: false,
afterEach: false,
describe: false,
it: false
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.registerTask('default', ['jshint']);
};
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schoolSchema = new Schema({
type: { type: String, enum: ['Grammar School', 'Middle School', 'High School'], default: 'High School' },
name: { type: String, trim: true },
address: String,
imageUrl: String,
description: String,
website: String,
scheduleAvailable: { type: Boolean, default: false },
links: [{
iconName: { type: String, default: 'link' },
title: String,
url: String
}]
});
module.exports = { name: 'School', schema: schoolSchema }; |
/*MIT License
Copyright (c) 2017 MTA SZTAKI
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
var config = require('./config.json');
var fs = require('fs');
exports.configType = '';
exports.sourcePath = config.source.apePath + config.source.jsApiPath;
exports.pluginPath = this.sourcePath + 'plugins/';
exports.nodeModulesPath = config.build.binPath + this.configType + config.build.nodeModulesPath;
exports.apertusModulePath = this.nodeModulesPath + config.build.apertusModulePath;
exports.httpServer = {
host: "",
port: 0,
address: ""
};
exports.requireNodeModule = function(moduleName) {
if (!fs.existsSync(this.nodeModulesPath + moduleName)) {
console.log('error: required module does not exist: "' + this.nodeModulesPath + moduleName + '"');
console.log('config.source.apePath: "' + config.source.apePath + '"');
console.log('config.build.binPath: "' + config.build.binPath + '"');
console.log('configuration:');
console.log(config);
process.exit(1);
}
return require(this.nodeModulesPath + moduleName);
}
exports.setConfigType = function(configStr) {
exports.configType = configStr + '/';
exports.configurationPath = config.build.binPath + this.configType;
exports.nodeModulesPath = config.build.binPath + this.configType + config.build.nodeModulesPath;
exports.apertusModulePath = this.nodeModulesPath + config.build.apertusModulePath;
}
|
'use strict';
/**
* @ngdoc overview
* @name webApp
* @description
* # webApp
*
* Main module of the application.
*/
var webApp = angular
.module('webApp', [
'ngRoute',
'ngAnimate',
'ui.tree',
'mediaPlayer',
'hmTouchEvents',
'ngImgCrop'
])
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
controller : 'MainCtrl',
templateUrl : 'views/main.html',
title: 'info'
})
.when('/povej', {
controller : 'PovejCtrl',
template : '<povej>',
title: 'webapp'
})
.when('/mobile', {
controller : 'MobileCtrl',
templateUrl : 'views/mobile.html',
title: 'mobilna aplikacija'
})
.when('/login', {
controller : 'LoginCtrl',
templateUrl : 'views/login.html',
title: 'prijavi se'
})
.when('/logout', {
controller : 'LoginCtrl',
})
.when('/uredi', {
controller: 'UrediCtrl',
templateUrl: 'views/uredi.html',
title: 'urejevalnik'
})
.otherwise({
redirectTo : '/'
})
;
// @todo check cordova routing, apps
$locationProvider.html5Mode(true);
}])
.run(['CONFIG', '$rootScope', '$location', 'Authentication', 'Content', function(config, $rootScope, $location, Authentication, Content) {
var path = function() {
return $location.path();
};
$rootScope.$watch(path, function(newVal, oldVal) {
$rootScope.activetab = newVal;
});
$rootScope.fullScreen = false;
$rootScope.$on('ui::toggleFullscreen', function(event) {
$rootScope.fullScreen = !$rootScope.fullScreen;
});
$rootScope.$on('content::load', function(event, scope, sync) {
var credentials = Authentication.GetCredentials();
var setupScope = function(data) {
if (!angular.isObject(data)) {
data = JSON.parse(data);
}
Content.saveLocalStructure(data, credentials).finally(function() {
scope.content = Content.fetchRemotes(data.content, credentials);
scope.favorites = Content.fetchRemotes(data.favorites, credentials);
$rootScope.$broadcast('content::loaded', data);
});
};
Content.isLocalStructure(credentials).then(
function() {
if (sync) {
Content.get(credentials).then(setupScope);
} else {
Content.getLocalStructure(credentials).then(setupScope);
}
},
function() {
Content.get(credentials).then(setupScope);
}
);
});
$rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
$rootScope.title = current.$$route.title;
});
Authentication.CheckCredentials();
$rootScope.logout = function() {
Authentication.ClearCredentials();
Content.resetPromise();
$location.path('/');
};
}])
; |
/**
* Created by lex on 07.03.17.
*/
import $ from 'jquery'
/*
* @class
* Basic class for components that need $(document).ready
* */
export default class AbstractComponent {
/*@constructor
* */
constructor() {
this.render = this.render.bind(this);
this._processComponent();
}
/*
*
* @this {AbstractComponent}
* @private
* Method wraps render() method
* */
_processComponent(){
let obj = this;
$(document).ready(function () {
obj.render();
});
}
/*
*
* @this {AbstractComponent}
* Main method what need to be overwritten. Put your logic here.
* */
render() {
}
} |
module("background_geolocation");
// In this test we call the example showAlert API method with an example string
//asyncTest("Attempt to show an alert with no text", 1, function() {
// forge.background_geolocation.showAlert("Hello, testing world!", function () {
// askQuestion("Did you see an alert with the message 'Hello, testing world!'?", {
// Yes: function () {
// ok(true, "User claims success");
// start();
// },
// No: function () {
// ok(false, "User claims failure");
// start();
// }
// });
// }, function () {
// ok(false, "API method returned failure");
// start();
// });
//});
|
version https://git-lfs.github.com/spec/v1
oid sha256:ba63a34e99110ad2d72ae1e3b7d35c3590752bc20dcd1a1a056ecea88aa2df57
size 255693
|
'use strict';
var _regenerator = require('babel-runtime/regenerator');
var _regenerator2 = _interopRequireDefault(_regenerator);
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var JSDOM = require('jsdom/lib/old-api.js').jsdom;
var serializeDocument = require('jsdom/lib/old-api.js').serializeDocument;
var promiseLimit = require('promise-limit');
var shim = function shim(window) {
window.SVGElement = window.HTMLElement;
window.localStorage = window.sessionStorage = {
getItem: function getItem(key) {
return this[key];
},
setItem: function setItem(key, value) {
this[key] = value;
}
};
};
var getPageContents = function getPageContents(window, options, originalRoute) {
options = options || {};
return new Promise(function (resolve, reject) {
var int = void 0;
function captureDocument() {
var result = {
originalRoute: originalRoute,
route: originalRoute,
html: serializeDocument(window.document)
};
if (int != null) {
clearInterval(int);
}
window.close();
return result;
}
// CAPTURE WHEN AN EVENT FIRES ON THE DOCUMENT
if (options.renderAfterDocumentEvent) {
window.document.addEventListener(options.renderAfterDocumentEvent, function () {
return resolve(captureDocument());
});
// CAPTURE ONCE A SPECIFC ELEMENT EXISTS
} else if (options.renderAfterElementExists) {
var doc = window.document;
int = setInterval(function () {
if (doc.querySelector(options.renderAfterElementExists)) resolve(captureDocument());
}, 100);
// CAPTURE AFTER A NUMBER OF MILLISECONDS
} else if (options.renderAfterTime) {
setTimeout(function () {
return resolve(captureDocument());
}, options.renderAfterTime);
// DEFAULT: RUN IMMEDIATELY
} else {
resolve(captureDocument());
}
});
};
var JSDOMRenderer = function () {
function JSDOMRenderer(rendererOptions) {
_classCallCheck(this, JSDOMRenderer);
this._rendererOptions = rendererOptions || {};
if (this._rendererOptions.maxConcurrentRoutes == null) this._rendererOptions.maxConcurrentRoutes = 0;
if (this._rendererOptions.inject && !this._rendererOptions.injectProperty) {
this._rendererOptions.injectProperty = '__PRERENDER_INJECTED';
}
}
_createClass(JSDOMRenderer, [{
key: 'initialize',
value: function () {
var _ref = _asyncToGenerator( /*#__PURE__*/_regenerator2.default.mark(function _callee() {
return _regenerator2.default.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt('return', Promise.resolve());
case 1:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function initialize() {
return _ref.apply(this, arguments);
}
return initialize;
}()
}, {
key: 'renderRoutes',
value: function () {
var _ref2 = _asyncToGenerator( /*#__PURE__*/_regenerator2.default.mark(function _callee2(routes, Prerenderer) {
var _this = this;
var rootOptions, limiter, results;
return _regenerator2.default.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
rootOptions = Prerenderer.getOptions();
limiter = promiseLimit(this._rendererOptions.maxConcurrentRoutes);
results = Promise.all(routes.map(function (route) {
return limiter(function () {
return new Promise(function (resolve, reject) {
JSDOM.env({
url: `http://127.0.0.1:${rootOptions.server.port}${route}`,
features: {
FetchExternalResources: ['script'],
ProcessExternalResources: ['script'],
SkipExternalResources: false
},
created: function created(err, window) {
if (err) return reject(err);
// Injection / shimming must happen before we resolve with the window,
// otherwise the page will finish loading before the injection happens.
if (_this._rendererOptions.inject) {
window[_this._rendererOptions.injectProperty] = _this._rendererOptions.inject;
}
window.addEventListener('error', function (event) {
console.error(event.error);
});
shim(window);
resolve(window);
}
});
}).then(function (window) {
return getPageContents(window, _this._rendererOptions, route);
});
});
})).catch(function (e) {
console.error(e);
return Promise.reject(e);
});
return _context2.abrupt('return', results);
case 4:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
function renderRoutes(_x, _x2) {
return _ref2.apply(this, arguments);
}
return renderRoutes;
}()
}, {
key: 'destroy',
value: function destroy() {
// NOOP
}
}]);
return JSDOMRenderer;
}();
module.exports = JSDOMRenderer; |
var keypress = require('keypress');
var columns = require('../main').create({
margin: {
top: 5,
bottom: 2,
right: 5,
left: 5
},
column_separator: ' | ',
header_separator: '-_-_',
flow_mode: 'reset',
overflow: 3,
maximum_buffer: 300,
tab_size: 2,
// mode: 'debug'
});
var a = columns.addColumn({
wrap: true
});
columns.addColumn("A2", {
width: "50%",
wrap: true
});
columns.addColumn("A3", {
width: 40,
wrap: true,
header: "CUSTOM HEADER"
});
columns.addColumn("A4");
columns.addColumn("A5");
// random writes
count = 0;
var color;
setInterval(function() {
a.write("A" + count + "한 글\tB한 글한 글한 글한글한글한글한 글" + "\n");
}, 220);
// columns.column("A2").write('\033[43m');
setInterval(function() {
if (count % 1 === 0) {
color = Math.round(Math.random() * 255);
}
columns.column("A2").write("B" + '' + count + (count % 1 === 0 ? "\033[38;5;" + (color) + 'm' : '') + randomTruncate("BB BBBBBBBBBBBBBBBBBB BBBBBBB BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB") + "\n");
count++;
}, 210);
setInterval(function() {
columns.column("A3").write(randomTruncate("C" + count + "0 1 \t2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 ") + "\n");
}, 1000);
setInterval(function() {
columns.column("A4").write(randomTruncate("D" + count + "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD") + "\n");
}, 500);
setInterval(function() {
columns.column("A5").write(randomTruncate("E" + count + "EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE") + "\n");
}, 200);
function randomTruncate(line) {
return line.substring(0, 6 + Math.random() * (line.length - 6));
}
// exit properly so we can restore state correctly
if (process.stdin.isTTY) {
keypress(process.stdin);
process.stdin.setRawMode(true);
process.stdin.on('keypress', function(ch, key) {
if (key && ((key.ctrl && key.name == 'c') || key.name == 'q')) {
process.stdin.pause();
process.exit(0);
}
});
}
|
$(document).ready(function(){
var socket = io.connect( 'http://127.0.0.1:3000' );
$( "#messageForm" ).submit( function() {
var nameVal = $( "#nameInput" ).val();
var msg = $( "#messageInput" ).val();
var receiver = $("#receiver").val();
//var reciever = 'sdklfjsdklfjsdl';
var roomname = nameVal + receiver;
$.ajax({
type: "POST",
url: "/Chat",
data: dataString,
dataType: "json",
cache : false,
success: function(data){
var socket = io.connect( 'http://127.0.0.1:3000' );
socket.emit('message', {
name: nameVal,
message: msg,
receive : receiver
});
socket.emit('receiver_messages', {
name: nameVal,
message: msg,
receiver : receiver
});
} ,error: function(xhr, status, error) {
alert(error);
},
});
/*
socket.join(roomname);
socket.set('room', roomname);
socket.set('nickname', nameVal);
*/
//socket.emit('message', {name: nameVal, message: msg, receive : receiver} );
/*// Ajax call for saving datas
$.ajax({
url: "./ajax/insertNewMessage.php",
type: "POST",
data: { name: nameVal, message: msg },
success: function(data) {
}
});*/
return false;
});
var socket = io.connect( 'http://127.0.0.1:3000' );
socket.on( 'message', function( data ) {
var actualContent = $( "#messages" ).html();
var newMsgContent = '<li> <strong>' + data.name + '</strong> : ' + data.message + '</li>';
var content = newMsgContent + actualContent;
$( "#messages" ).html( content );
});
});
socket.on( 'receiver_messages', function( data ) {
console.log('xxx');
});
|
var express = require('express');
var app = express();
var result = {namn:'demas'}
app.get('/', function (req, res) {
res.send(result);
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
}); |
import { version } from '../../package.json';
import { Router } from 'express';
import receipt from './receipt';
export default ({ config, db }) => {
let api = Router();
// mount the facets resource
api.use('/receipt', receipt({ config, db }));
api.get('/', (req, res) => {
res.json({ version });
});
return api;
} |
var ellipse = require('./')
var test = require('tape').test
var context = document.createElement('canvas').getContext('2d')
test("draws an ellipse with quadratic curves", function(t) {
context.beginPath()
ellipse(context, [25, 25], [10, 5])
t.equal(context.isPointInPath(25, 25), true, 'in path')
t.equal(context.isPointInPath(40, 25), false, 'not in path')
t.equal(context.isPointInPath(25, 35), false, 'not in path')
t.end()
}) |
var Scope = (function(){
var events = (function(){
var topics = {};
var hOP = topics.hasOwnProperty;
return {
subscribe: function(topic, listener) {
if(!hOP.call(topics, topic)) topics[topic] = [];
var index = topics[topic].push(listener) -1;
return {
remove: function() {
delete topics[topic][index];
}
};
},
publish: function(topic, info) {
if(!hOP.call(topics, topic)) return;
topics[topic].forEach(function(item) {
item(info != undefined ? info : {});
});
}
};
})();
var Input = (function(){
var isValid = function(state, validation){
var validated = validation(state.input.val());
var message = { state: state};
if(validated === true){
state.isValid = true;
} else {
state.isValid = false;
message.error = validated;
}
events.publish('update', message);
};
return function(input){
var state = {
input: input
};
var component = {
isValid: isValid(state, component.validate)
};
return component;
};
}());
var Form = (function(){
var isValid = function(state){
return function(){
var valid = true;
_.forOwn(state.inputs, function(input){
if(input.valid() === false){
valid = false;
return false
}
});
return valid;
};
};
return function(form){
var state = {
inputs: {}
};
var component = {
isValid: isValid(state)
};
events.subscribe('update', function(message){
});
return component;
};
}());
}());
|
'use strict';
angular
.module('myCashManager.cycles', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/cycles', {
templateUrl: $apiRoot() + 'cycles/cycles.html',
controller: 'CyclesCtrl',
auth: true
});
}]).controller('CyclesCtrl', function ($scope, $uibModal, $log, appService, accountService) {
$scope.cycles = [];
$scope.sortKey = 'date_next';
$scope.reverse = false;
$scope.sort = function (keyname) {
$scope.sortKey = keyname; //set the sortKey to the param passed
$scope.reverse = !$scope.reverse; //if true make it false and vice versa
};
$scope.getCycles = function () {
accountService.getCycles()
.then(function (result) {
$scope.cycles = result.data.response;
});
};
$scope.deleteCycle = function (id) {
accountService.deleteCycle(id)
.then(function (result) {
$scope.getCycles();
});
};
$scope.openEditCycle = function (item) {
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: appService.apiRoot() + 'cycles/add_cycle_content.html',
controller: 'ModalAddCycleCtrl',
resolve: {
selected: function () {
console.log(item);
return item;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
accountService.postCycle($scope.selected)
.then(function () {
$scope.getCycles();
});
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
$scope.open = function (size) {
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: appService.apiRoot() + 'cycles/add_cycle_content.html',
controller: 'ModalAddCycleCtrl',
size: size,
resolve: {
selected: function () {
return {
date_start: Date.now(),
repeat_every: 1
};
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
accountService.putCycle($scope.selected)
.then(function () {
$scope.getCycles();
});
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
$scope.openAddTransactionContent = function (cycle) {
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: appService.apiRoot() + 'cycles/add_transaction_content.html',
controller: 'ModalAddCycleTransactionCtrl',
//size: size,
resolve: {
cycle: function () {
return cycle;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
accountService.putCycleTransaction($scope.selected)
.then(function () {
$scope.getCycles();
});
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
}); |
'use strict'
const _ = require('lodash')
const oki = require('oki')
const createError = require('midwest/util/create-error')
const resolver = require('deep-equal-resolver')({
moduleName: 'midwest-membership/strategies/local',
validate: oki({
'errors.wrongPassword': _.isPlainObject,
'errors.noUserFound': _.isPlainObject,
'errors.notLocal': _.isPlainObject,
'getAuthenticationDetails': _.isFunction,
'checkPassword': _.isFunction,
}),
})
module.exports = _.memoize((state) => {
return (req, res, next) => {
const { email, password } = req.body
return state.getAuthenticationDetails(email.toLowerCase()).then((user) => {
if (!user) {
throw createError(state.errors.noUserFound)
} else if (!user.password) {
throw createError(state.errors.notLocal)
}
return state.checkPassword(password, user.password).then((result) => {
if (!result) {
console.log('about to throw error')
throw createError(state.errors.wrongPassword)
}
return user
})
})
}
}, resolver)
|
/**
* configuration for grunt tasks
* @module Gruntfile
*/
module.exports = function(grunt) {
/** load tasks */
require('load-grunt-tasks')(grunt);
/** paths to file on server */
var files = {
/** meta / non-script files */
meta: [
'README.md',
'TODO.md',
'package.json',
'.gitignore',
'*.sublime-project',
'*.sublime-workspace',
'*.iml',
'.idea',
'dump.rdb',
],
/** server scripts */
server: [
'*.*',
'lib/*.*',
],
/** array of all paths */
all: []
};
/** add meta files to `files.all` */
files.meta.forEach(function(file) {
files.all.push(file);
});
/** add server files to `files.all` */
files.server.forEach(function(file) {
files.all.push(file);
});
/** ignore meta files on server */
files.meta.forEach(function(file) {
files.server.push('!' + file);
});
/** all grunt tasks */
var tasks = {
/** metadata inside `package.json` file */
pkg: grunt.file.readJSON('package.json'),
/** lint javascript tool */
jshint: {
/** paths to files */
files: files.server,
/** options for jshint task */
options: {
/** options here to override JSHint defaults */
globals: {
console: true,
module: true
}
}
},
/** build TODO.md from inline comments */
todos: {
src: {
/** options for plugin */
options: {
priorities: {
low: /TODO/,
med: /FIXME/,
high: null
},
reporter: {
/** put at the top of the generated file */
header: function() {
return '-- BEGIN TASK LIST --\n\n';
},
/** flow for each file */
fileTasks: function(file, tasks, options) {
/** skip if no tasks or checking Gruntfile */
if (!tasks.length || file && file === 'Gruntfile.js') {
return '';
}
var result = '* ' + file + ' (' + tasks.length + ')\n\n';
/** iterate over tasks, add data */
tasks.forEach(function(task) {
result += ' [' + task.lineNumber + ' - ' +
task.priority + '] ' + task.line.trim() + '\n';
result += '\n';
});
return result;
},
/** put at the bottom of the generated file */
footer: function() {
return '-- END TASK LIST --\n';
}
}
},
files: {
'TODO.md': files.server
}
}
},
/** testing framework */
jasmine_node: {
options: {
forceExit: true,
match: 'spec',
matchall: false,
extensions: 'js',
specNameMatcher: 'spec',
},
match: []
},
};
/** merge files and task config, initialize grunt config */
grunt.initConfig(grunt.util._.extend(tasks, files));
/** default grunt task, ran with `grunt` */
grunt.registerTask('default', [
// ...
]);
/** parses command, starts server or runs either model, api, or single test(s) */
grunt.registerTask('test', 'Used to run tests.', function(path) {
var args = Array.prototype.slice.call(arguments);
if (args.length) {
grunt.config('jasmine_node.match', args[0] + '.');
}
grunt.task.run('jasmine_node');
});
}; |
/* eslint-env jest*/
jest.unmock('../Divider');
import React from 'react';
import { findDOMNode } from 'react-dom';
import { renderIntoDocument, Simulate } from 'react-dom/test-utils';
import Divider from '../Divider';
describe('Divider', () => {
it('updates the className with inset or vertical', () => {
let divider = renderIntoDocument(<Divider />);
let dividerNode = findDOMNode(divider);
expect(dividerNode.className).toBe('md-divider');
divider = renderIntoDocument(<Divider inset />);
dividerNode = findDOMNode(divider);
expect(dividerNode.className).toContain('--inset');
expect(dividerNode.className).not.toContain('--vertical');
divider = renderIntoDocument(<Divider inset vertical />);
dividerNode = findDOMNode(divider);
expect(dividerNode.className).toContain('--inset');
expect(dividerNode.className).toContain('--vertical');
divider = renderIntoDocument(<Divider vertical />);
dividerNode = findDOMNode(divider);
expect(dividerNode.className).not.toContain('--inset');
expect(dividerNode.className).toContain('--vertical');
});
it('passes all remaining props to the divider', () => {
const onClick = jest.fn();
const onFocus = jest.fn();
const onBlur = jest.fn();
const onMouseDown = jest.fn();
const onMouseUp = jest.fn();
const onMouseOver = jest.fn();
const onMouseLeave = jest.fn();
const onTouchStart = jest.fn();
const onTouchEnd = jest.fn();
const onTouchCancel = jest.fn();
const style = { display: 'block' };
const divider = renderIntoDocument(
<Divider
style={style}
onClick={onClick}
onFocus={onFocus}
onBlur={onBlur}
onMouseDown={onMouseDown}
onMouseUp={onMouseUp}
onMouseOver={onMouseOver}
onMouseLeave={onMouseLeave}
onTouchStart={onTouchStart}
onTouchEnd={onTouchEnd}
onTouchCancel={onTouchCancel}
/>
);
const dividerNode = findDOMNode(divider);
expect(dividerNode.style.display).toBe(style.display);
Simulate.click(dividerNode);
expect(onClick).toBeCalled();
Simulate.focus(dividerNode);
expect(onFocus).toBeCalled();
Simulate.blur(dividerNode);
expect(onBlur).toBeCalled();
Simulate.mouseOver(dividerNode);
expect(onMouseOver).toBeCalled();
Simulate.mouseLeave(dividerNode);
expect(onMouseLeave).toBeCalled();
Simulate.mouseDown(dividerNode);
expect(onMouseDown).toBeCalled();
Simulate.mouseUp(dividerNode);
expect(onMouseUp).toBeCalled();
Simulate.touchStart(dividerNode);
expect(onTouchStart).toBeCalled();
Simulate.touchEnd(dividerNode);
expect(onTouchEnd).toBeCalled();
Simulate.touchCancel(dividerNode);
expect(onTouchCancel).toBeCalled();
});
});
|
/**
* Brands mock on server side
*
* @author Eric Fehr ([email protected], github: ricofehr)
* @class Brand
* @namespace mock
* @module nextdeploy
*/
module.exports = function(app) {
var express = require('express');
var brandsRouter = express.Router();
/**
* Mock brands list request
*
* @method get:/
*/
brandsRouter.get('/', function(req, res) {
res.send({
'brands':[
{"id":1,"name":"Test Company","logo":null,"projects":[1,5]},
{"id":2,"name":"YourCompany","logo":null,"projects":[2,6]},
{"id":3,"name":"HisCompany","logo":null,"projects":[3,4]}
]
});
});
/**
* Mock new brand request
*
* @method post:/
*/
brandsRouter.post('/', function(req, res) {
var brand = req.body.brand;
res.status(200).send({
"brand":{
"id": Math.floor((Math.random() * 1000) + 4),
"name": brand.name,
"logo": null,
"projects": []
}
});
});
/**
* Mock show brand request
*
* @method get:/$id
*/
brandsRouter.get('/:id', function(req, res) {
res.send({
'brand':{
id: req.params.id
}
});
});
/**
* Mock change brand request
*
* @method put:/$id
*/
brandsRouter.put('/:id', function(req, res) {
var brand = req.body.brand;
res.status(200).send({
"brand":{
"id": req.params.id,
"name": brand.name,
"logo":null,
"projects":brand.projects
}
});
});
/**
* Mock delete brand request
*
* @method delete:/$id
*/
brandsRouter.delete('/:id', function(req, res) {
res.status(204).end();
});
app.use('/api/v1/brands', require('body-parser').json(), brandsRouter);
};
|
// Generated by CoffeeScript 1.7.1
(function() {
"use strict";
var LIVERELOAD_PORT, lrSnippet, mountFolder;
LIVERELOAD_PORT = 35728;
lrSnippet = require("connect-livereload")({
port: LIVERELOAD_PORT
});
mountFolder = function(connect, dir) {
return connect["static"](require("path").resolve(dir));
};
module.exports = function(grunt) {
var yeomanConfig;
require("load-grunt-tasks")(grunt);
require("time-grunt")(grunt);
yeomanConfig = {
app: "app",
dist: "dist"
};
try {
yeomanConfig.app = require("./bower.json").appPath || yeomanConfig.app;
} catch (_error) {}
grunt.initConfig({
yeoman: yeomanConfig,
watch: {
coffee: {
files: ["<%= yeoman.app %>/scripts/**/*.coffee"],
tasks: ["coffee:dist"]
},
compass: {
files: ["<%= yeoman.app %>/styles/**/*.{scss,sass}"],
tasks: ["compass:server"]
},
livereload: {
options: {
livereload: LIVERELOAD_PORT
},
files: ["<%= yeoman.app %>/index.html", "<%= yeoman.app %>/views/**/*.html", "<%= yeoman.app %>/styles/**/*.scss", ".tmp/styles/**/*.css", "{.tmp,<%= yeoman.app %>}/scripts/**/*.js", "<%= yeoman.app %>/images/**/*.{png,jpg,jpeg,gif,webp,svg}"]
}
},
connect: {
options: {
port: 8080,
hostname: "localhost"
},
livereload: {
options: {
middleware: function(connect) {
return [lrSnippet, mountFolder(connect, ".tmp"), mountFolder(connect, yeomanConfig.app)];
}
}
},
test: {
options: {
middleware: function(connect) {
return [mountFolder(connect, ".tmp"), mountFolder(connect, "test")];
}
}
},
dist: {
options: {
middleware: function(connect) {
return [mountFolder(connect, yeomanConfig.dist)];
}
}
}
},
open: {
server: {
url: "http://localhost:<%= connect.options.port %>",
app: 'firefox'
}
},
clean: {
dist: {
files: [
{
dot: true,
src: [".tmp", "<%= yeoman.dist %>/*", "!<%= yeoman.dist %>/.git*"]
}
]
},
server: ".tmp"
},
jshint: {
options: {
jshintrc: ".jshintrc"
},
all: ["Gruntfile.js", "<%= yeoman.app %>/scripts/**/*.js"]
},
compass: {
options: {
sassDir: "<%= yeoman.app %>/styles",
cssDir: ".tmp/styles",
generatedImagesDir: ".tmp/styles/ui/images/",
imagesDir: "<%= yeoman.app %>/styles/ui/images/",
javascriptsDir: "<%= yeoman.app %>/scripts",
fontsDir: "<%= yeoman.app %>/fonts",
importPath: "<%= yeoman.app %>/bower_components",
httpImagesPath: "styles/ui/images/",
httpGeneratedImagesPath: "styles/ui/images/",
httpFontsPath: "fonts",
relativeAssets: true
},
dist: {
options: {
debugInfo: false,
noLineComments: true
}
},
server: {
options: {
debugInfo: true
}
},
forvalidation: {
options: {
debugInfo: false,
noLineComments: false
}
}
},
coffee: {
server: {
options: {
sourceMap: true,
sourceRoot: ""
},
files: [
{
expand: true,
cwd: "<%= yeoman.app %>/scripts",
src: "**/*.coffee",
dest: ".tmp/scripts",
ext: ".js"
}
]
},
dist: {
options: {
sourceMap: false,
sourceRoot: ""
},
files: [
{
expand: true,
cwd: "<%= yeoman.app %>/scripts",
src: "**/*.coffee",
dest: ".tmp/scripts",
ext: ".js"
}
]
}
},
useminPrepare: {
html: "<%= yeoman.app %>/index.html",
options: {
dest: "<%= yeoman.dist %>",
flow: {
steps: {
js: ["concat"],
css: ["concat"]
},
post: []
}
}
},
usemin: {
html: ["<%= yeoman.dist %>/**/*.html", "!<%= yeoman.dist %>/bower_components/**"],
css: ["<%= yeoman.dist %>/styles/**/*.css"],
options: {
dirs: ["<%= yeoman.dist %>"]
}
},
htmlmin: {
dist: {
options: {},
files: [
{
expand: true,
cwd: "<%= yeoman.app %>",
src: ["*.html", "views/*.html"],
dest: "<%= yeoman.dist %>"
}
]
}
},
copy: {
dist: {
files: [
{
expand: true,
dot: true,
cwd: "<%= yeoman.app %>",
dest: "<%= yeoman.dist %>",
src: ["favicon.ico", "bower_components/font-awesome/css/*", "bower_components/font-awesome/fonts/*", "bower_components/weather-icons/css/*", "bower_components/weather-icons/font/*", "fonts/**/*", "i18n/**/*", "images/**/*", "styles/bootstrap/**/*", "styles/fonts/**/*", "styles/img/**/*", "styles/ui/images/**/*", "views/**/*"]
}, {
expand: true,
cwd: ".tmp",
dest: "<%= yeoman.dist %>",
src: ["styles/**", "assets/**"]
}, {
expand: true,
cwd: ".tmp/images",
dest: "<%= yeoman.dist %>/images",
src: ["generated/*"]
}
]
},
styles: {
expand: true,
cwd: "<%= yeoman.app %>/styles",
dest: ".tmp/styles/",
src: "**/*.css"
}
},
concurrent: {
server: ["coffee:server", "compass:server", "copy:styles"],
dist: ["coffee:dist", "compass:dist", "copy:styles", "htmlmin"]
},
concat: {
options: {
separator: grunt.util.linefeed + ';' + grunt.util.linefeed
},
dist: {
src: ["<%= yeoman.dist %>/bower_components/angular/angular.min.js"],
dest: "<%= yeoman.dist %>/scripts/vendor.js"
}
},
uglify: {
options: {
mangle: false
},
dist: {
files: {
"<%= yeoman.dist %>/scripts/app.js": [".tmp/**/*.js"]
}
}
}
});
grunt.registerTask("server", function(target) {
if (target === "dist") {
return grunt.task.run(["build", "open", "connect:dist:keepalive"]);
}
return grunt.task.run(["clean:server", "concurrent:server", "connect:livereload", "open", "watch"]);
});
grunt.registerTask("build", ["clean:dist", "useminPrepare", "concurrent:dist", "copy:dist", "concat", "uglify", "usemin"]);
return grunt.registerTask("default", ["server"]);
};
}).call(this);
|
'use strict';
module.exports = function (value, sanitizer) {
var patt = new RegExp(sanitizer.regexp, sanitizer.regexpmod);
return value.replace(patt, sanitizer.replace);
}; |
function plot() {
var width = window.innerWidth ;
var height = window.innerHeight;
var graph = d3.select("body")
.append("div")
.style("width", width + "px")
.style("height", height + "px")
.attr("id", "graph");
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
var fdg = d3.forceSimulation()
.force("link", d3.forceLink().distance(40).strength(.5))
.force("center", d3.forceCenter(width/2, height/2+ 20))
.force("charge", d3.forceManyBody().strength(-(height/20)))
.force("y", d3.forceY(1))
.force("x", d3.forceX(1));
d3.json("https://raw.githubusercontent.com/DealPete/forceDirected/master/countries.json", function(error, data) {
if(error) throw error;
var div = d3.select(".tooltip");
var node = graph
.attr("class", "nodes")
.selectAll("img")
.data(data.nodes)
.enter().append("img")
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended))
.on("mouseover", function(d){
div.transition()
.duration(100)
.style("opacity", 1);
div.html('<span>'+d.country+'<span>');
div.style("left", (d3.event.pageX > (width - 200)) ? (d3.event.pageX - 130)+ "px":(d3.event.pageX + 30) + "px")
.style("top", (d3.event.pageX > (width - 200)) ? (d3.event.pageY - 44) + "px":(d3.event.pageY - 30) + "px");
})
.on("mouseout", function(){
div.transition()
.duration(100)
.style("opacity", 0)
div
.style("left", "-999px")
.style("top", "-999px");
})
.attr("class", function(d){ return "node flag flag-" + d.code} );
var link = svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(data.links)
.enter().append("line")
.attr("class", "link");
fdg
.nodes(data.nodes)
.on('tick', tick);
fdg.force("link")
.links(data.links);
function tick() {
node
.style("top", function(d) { return d.y + "px"; } )
.style("left", function(d) { return d.x + "px"; });
link
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
}
});
function dragstarted(d) {
if (!d3.event.active) fdg.alphaTarget(.5).restart();
if (d3.event.x > 20 && d3.event.x < width -20)
d.fx = d3.event.x;
if (d3.event.y > 60 && d3.event.y < height-20)
d.fy = d3.event.y;
}
function dragged(d) {
if (d3.event.x > 20 && d3.event.x < width -20)
d.fx = d3.event.x;
if (d3.event.y > 60 && d3.event.y < height-20)
d.fy = d3.event.y;
}
function dragended(d) {
if (!d3.event.active) fdg.alphaTarget(0);
d.fx = null;
d.fy = null;
}
addRandomCircles();
}
plot();
function addRandomCircles() {
for(var i = 0; i < 2000; i++) {
var x = Math.random() * window.innerWidth,
y = Math.random() * window.innerHeight;
d3.select("svg")
.append("circle")
.attr("r", .7)
.attr("class", "bkdCircles")
.attr("fill", d3.interpolateWarm(Math.random()/2))
.attr("cx", x)
.attr("cy", y);
}
} |
const { expect } = require('chai');
const KmS3 = require('../lib/s3.js');
const config = {
Bucket: process.env.s3_bucket,
accessKeyId: process.env.s3_access_key,
secretAccessKey: process.env.s3_secret_access_key,
};
describe('KmS3', function () {
const kmS3;
before(function() {
kmS3 = new KmS3(config);
});
describe('listS3Objects', function () {
it('should list all objects in the bucket', function (done) {
this.timeout(10000);
kmS3.listS3Objects().then(function(data) {
expect(typeof data).to.not.equal('undefined');
done();
});
});
});
describe('getS3Object', function () {
it('should get an object', function () {
return kmS3.getS3Object('revisions/118.json').then(function(data) {
// console.log(data.Body.toString('utf-8'));
expect(typeof data).to.not.equal('undefined');
});
});
});
});
|
import React from "react";
import { shallow } from "enzyme";
import Fabric from "./Fabric";
describe("Fabric", () => {
it("matches snapshot", () => {
const aFabric = shallow(<Fabric />);
expect(aFabric).toMatchSnapshot();
});
});
|
const {
login, transport, logout
} = require('./common');
const {Events} = require('../src');
let events;
login()
.then(() => {
// find resources
events = new Events(transport);
return events.create()
.debug()
.facility('daemon')
.msg('hello')
.save();
})
.then(() => {
return events.find()
.exec()
.then(docs => docs[0])
.then((event) => {
console.log(event.toString());
});
})
.then(logout)
.catch(error => console.error(error.message));
|
/**
* svgtoreact
*
* @author Michael Hsu
*/
import React from 'react';
export default function SVGData(props) {
return (
<svg width={42} height={32} viewBox="0 0 42 32" {...props}>
<g fill="none">
<path d="M-9-14h60v60h-60z" />
<path
d="M36.984 10.723l-7.261 7.261c.176.298.277.645.277 1.016 0 1.105-.895 2-2 2s-2-.895-2-2c0-.144.015-.284.044-.419l-6.535-3.268c-.367.421-.907.687-1.508.687-.371 0-.718-.101-1.016-.277l-7.261 7.261c.176.298.277.645.277 1.016 0 1.105-.895 2-2 2s-2-.895-2-2 .895-2 2-2c.371 0 .718.101 1.016.277l7.261-7.261c-.176-.298-.277-.645-.277-1.016 0-1.105.895-2 2-2s2 .895 2 2c0 .144-.015.284-.044.419l6.535 3.268c.367-.421.907-.687 1.508-.687.371 0 .718.101 1.016.277l7.261-7.261c-.176-.298-.277-.645-.277-1.016 0-1.105.895-2 2-2s2 .895 2 2-.895 2-2 2c-.371 0-.718-.101-1.016-.277zm-34.984-9.723v29h39c.552 0 1 .448 1 1s-.448 1-1 1h-41v-31c0-.552.448-1 1-1s1 .448 1 1z"
fill="#fff"
/>
</g>
</svg>
);
}
|
'use strict';
var _get = require('babel-runtime/helpers/get')['default'];
var _inherits = require('babel-runtime/helpers/inherits')['default'];
var _createDecoratedClass = require('babel-runtime/helpers/create-decorated-class')['default'];
var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default'];
var _Object$assign = require('babel-runtime/core-js/object/assign')['default'];
var React = require('react');
var Button = require('react-bootstrap/lib/Button');
var ButtonInput = require('react-bootstrap/lib/ButtonInput');
var Input = require('react-bootstrap/lib/Input');
var Api = require('../application/Api');
var login = require('../application/login');
var OverlayTooltip = require('./OverlayTooltip');
var autobind = require('autobind-decorator');
var LoginPane = (function (_React$Component) {
_inherits(LoginPane, _React$Component);
function LoginPane() {
_classCallCheck(this, LoginPane);
_get(Object.getPrototypeOf(LoginPane.prototype), 'constructor', this).call(this);
this.state = {
loggedInAs: null,
username: null,
password: null
};
global._LoginPane = this;
}
_createDecoratedClass(LoginPane, [{
key: 'render',
value: function render() {
return React.createElement(
'div',
{ style: _Object$assign({}, Styles.pane, {
paddingLeft: 12,
paddingRight: 12,
paddingBottom: 6,
paddingTop: 6
}) },
this.state.loggedInAs ? this._renderLoggedIn() : this._renderLoggedOut(),
this._renderErrors()
);
}
}, {
key: '_renderErrors',
decorators: [autobind],
value: function _renderErrors() {
if (this.state.errorMessage) {
return React.createElement(
'div',
{ style: {
color: 'red',
fontSize: 13,
fontWeight: '600',
fontFamily: 'Helvetica Neue',
textAlign: 'center',
maxWidth: 250
} },
React.createElement(
'small',
null,
this.state.errorMessage
)
);
} else {
return null;
}
}
}, {
key: '_renderLoggedIn',
decorators: [autobind],
value: function _renderLoggedIn() {
return React.createElement(
'div',
null,
React.createElement(
'div',
{ style: { paddingTop: 5 } },
this.state.loggedInAs.username
),
React.createElement(
OverlayTooltip,
{ tooltip: 'Logs out of exp.host' },
React.createElement(
Button,
{ bsSize: 'small', style: {
marginTop: 5,
alignSelf: 'center'
}, onClick: this._logoutClicked
},
'Logout'
)
)
);
}
}, {
key: '_renderLoggedOut',
decorators: [autobind],
value: function _renderLoggedOut() {
var _this = this;
return React.createElement(
'div',
null,
React.createElement(
'form',
{ name: 'login', onSubmit: function (e) {
e.preventDefault();
_this._loginSubmitted();
} },
React.createElement(
'div',
null,
React.createElement(Input, { type: 'text', bsSize: 'small', style: Styles.input, ref: 'username', onChange: function (event) {
_this.setState({ username: event.target.value });
}, placeholder: 'username' })
),
React.createElement(
'div',
null,
React.createElement(Input, { type: 'password', bsSize: 'small', style: Styles.input, ref: 'password', onChange: function (event) {
_this.setState({ password: event.target.value });
}, placeholder: 'password' })
),
React.createElement(Input, { type: 'submit', bsSize: 'small', value: 'Login or Create Account' })
)
);
}
}, {
key: '_logoutClicked',
decorators: [autobind],
value: function _logoutClicked() {
var _this2 = this;
console.log("logout clicked");
login.logoutAsync().then(function () {
console.log("logout successful");
_this2.setState({ loggedInAs: null, errorMessage: null });
if (_this2.props.onLogout) {
_this2.props.onLogout();
}
}, function (err) {
console.error("logout error:", err);
_this2.setState({ errorMessage: err.message });
});
}
}, {
key: '_loginSubmitted',
decorators: [autobind],
value: function _loginSubmitted() {
var _this3 = this;
console.log("login clicked");
login.loginOrAddUserAsync({
username: this.state.username,
password: this.state.password
}).then(function (result) {
console.log("login successful");
_this3.setState({
errorMessage: null,
loggedInAs: result.user
});
if (_this3.props.onLogin) {
_this3.props.onLogin(result.user);
}
}, function (err) {
console.error("login error:", err);
_this3.setState({ errorMessage: err.message });
console.error(err);
});
// console.log("username=", this.state.username, "password=", this.state.password);
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var _this4 = this;
Api.callMethodAsync('whoami', []).then(function (result) {
_this4.setState({ loggedInAs: result.user });
if (result.user && _this4.props.onLogin) {
_this4.props.onLogin(result.user);
}
}, function (err) {
_this4.setState({ errorMessage: err.message });
});
}
}]);
return LoginPane;
})(React.Component);
var Styles = {
pane: {
backgroundColor: '#eeeeee',
boxShadow: '0 0 10px 0 rgba(0, 0, 0, 0.3)'
},
input: {
// borderRadius: 3,
// width: 200,
// fontFamily: ['Verdana', 'Helvetica Neue', 'Verdana', 'Helvetica', 'Arial', 'Sans-serif'],
// fontSize: 11,
// fontWeight: '200',
},
submit: {
// borderRadius: 3,
// width: 200,
}
};
module.exports = LoginPane;
//# sourceMappingURL=../sourcemaps/web/LoginPane.js.map |
'use strict';
// Use applicaion configuration module to register a new module
ApplicationConfiguration.registerModule('funds'); |
var React = require('react/addons'),
classnames = require('classnames');
module.exports = React.createClass({
displayName: 'ItemNote',
propTypes: {
className: React.PropTypes.string,
type: React.PropTypes.string,
label: React.PropTypes.string,
icon: React.PropTypes.string
},
getDefaultProps: function() {
return {
type: 'default'
};
},
render: function() {
var className = classnames({
'item-note': true
}, this.props.type, this.props.className);
// elements
var label = this.props.label ? (
<div className="item-note-label">{this.props.label}</div>
) : null;
var icon = this.props.icon ? (
<div className={'item-note-icon ' + this.props.icon} />
) : null;
return (
<div className={className}>
{label}
{icon}
</div>
);
}
}); |
module.exports.id = '1';
module.exports.title = '1 ()';
module.exports.time = 1;
module.exports.flokVersion = '2';
module.exports.up = function up(mig, flok, done) {
global.__flokfirst = 1;
setTimeout(done, 10);
};
module.exports.down = function down(mig, flok, done) {
global.__flokfirst = 0;
setTimeout(done, 10);
};
|
{
expect(isAbsoluteURL("/foo")).toBe(false);
expect(isAbsoluteURL("foo")).toBe(false);
}
|
import {Section, Text, Button} from 'cx/widgets';
import { expr } from 'cx/ui';
import Controller from './Controller';
export default () => <cx>
<h2 putInto="header">Sign in</h2>
<div class="center" controller={Controller} >
<Section title="Sign In" visible={expr("!{user.uid}")}>
<p>
Ulogujte se za pristup administrativnom panelu.
</p>
<p>
<a href="#" onClick="signInWithGoogle">
<img src="~/assets/sign-in/google/btn_google_signin_dark_normal_web.png" />
</a>
</p>
</Section>
<Section title="User Info" visible={expr("!!{user.uid}")} ws>
<p ws>
Ulogovani ste kao <Text tpl="{user.displayName}{user.email:wrap; (;)}" />.
</p>
<Button onClick="signOut" mod="hollow">
Sign Out
</Button>
</Section>
</div>
</cx>
|
'use strict';
var patchOperationsHelper = require('../patch-operations-helper');
var validator = require('../util/validator');
var schema = require('../json-schemas/api-base-path-mapping-schema');
var pub = {};
pub.getParameters = function getParameters(event) {
return validator.validate(event, schema);
};
var allowedModifications = {
add: [],
replace: ['basePath', 'restapiId', 'stage'],
remove: []
};
pub.getPatchOperations = function (eventParams) {
// Work around due to faulty, or inconsistent, AWS validation where it requires restapiId rather than restApiId (casing)
eventParams.params.restapiId = eventParams.params.restApiId;
eventParams.old.restapiId = eventParams.old.restApiId;
var modifications = patchOperationsHelper.getAllowedModifications(eventParams.params, eventParams.old, allowedModifications);
return patchOperationsHelper.getOperations(eventParams.params, modifications);
};
module.exports = pub;
|
var gulp = require('gulp');
var mini = require('gulp-imagemin');
var plugins = require('gulp-load-plugins')({
pattern: 'imagemin-*', // the glob to search for
//config: 'package.json', // where to find the plugins, by default searched up from process.cwd()
//scope: ['dependencies', 'devDependencies'], // which keys in the config to look within
replaceString: 'imagemin-', // what to remove from the name of the module when adding it to the context
camelize: true, // if true, transforms hyphenated plugins names to camel case
lazy: true, // whether the plugins should be lazy loaded on demand
});
var input = './input';
var output = './output';
gulp.task('default', function () {
return gulp.src(input + '/*')
// 配置详情见 https://www.npmjs.org/package/gulp-imagemin
.pipe(mini({
progressive: true, // 针对 jpg,是否无损,默认假
//optimizationLevel: 3, // 针对 png,0-7,迭代压缩尝试等级,越高次数越多,默认 3
interlaced: true, // 针对 gif,是否交错呈现,默认假
// 针对 svg,压缩所使用的插件列表,默认为 []
// 所有的插件详情见 https://github.com/svg/svgo/tree/master/plugins
// 通过看每个 exports.active 的真值确定默认是否启动
svgoPlugins: [
{ removeViewBox: false },
{ removeComments: true }
],
// imagemin 插件,默认为 null
// 所有插件见 https://www.npmjs.org/browse/keyword/imageminplugin
use: [
plugins.optipng(),
plugins.pngquant(),
plugins.advpng(),
plugins.pngcrush(),
plugins.pngout(),
plugins.jpegtran(),
plugins.jpegRecompress(),
plugins.mozjpeg(),
plugins.gifsicle(),
plugins.svgo(),
plugins.zopfli()
]
}))
.pipe(gulp.dest(output));
}); |
'use strict';
const Command = require('../../../..');
class ErrorCommand extends Command {
* run() {
throw new Error('something wrong');
}
get description() { return 'throw error'; }
}
module.exports = ErrorCommand;
|
var connectionProvider = require('../mysqlConnectionStringProvider.js');
var vehicleModel = {
getAllVehicle : function (callback) {
var connection = connectionProvider.mysqlConnectionStringProvider.getMySqlConnection();
var queryStatement = "SELECT * FROM vehicles_list ORDER BY year DESC";
if (connection) {
connection.query(queryStatement, function (err, rows, fields) {
if (err) { throw err; }
console.log(rows);
callback(rows);
});
connectionProvider.mysqlConnectionStringProvider.closeMySqlConnection(connection);
}
}
,
getAllMakesByYear : function (year, callback) {
var connection = connectionProvider.mysqlConnectionStringProvider.getMySqlConnection();
var queryStatement = "SELECT DISTINCT make FROM vehicles_list WHERE year = ? ORDER BY make ASC";
if (connection) {
connection.query(queryStatement, [year] , function (err, rows, fields) {
if (err) { throw err; }
console.log(rows);
callback(rows);
});
connectionProvider.mysqlConnectionStringProvider.closeMySqlConnection(connection);
}
}
,
getAllModelsByYearAndMake : function (year, make, callback) {
var connection = connectionProvider.mysqlConnectionStringProvider.getMySqlConnection();
var queryStatement = "SELECT DISTINCT model FROM vehicles_list WHERE year = ? and make = ? ORDER BY model ASC";
if (connection) {
connection.query(queryStatement, [year,make] , function (err, rows, fields) {
if (err) { throw err; }
console.log(rows);
callback(rows);
});
connectionProvider.mysqlConnectionStringProvider.closeMySqlConnection(connection);
}
}
,
getYears : function (callback) {
var connection = connectionProvider.mysqlConnectionStringProvider.getMySqlConnection();
var queryStatement = "SELECT DISTINCT year FROM vehicles_list ORDER BY year DESC";
if (connection) {
connection.query(queryStatement, function (err, rows, fields) {
if (err) { throw err; }
console.log(rows);
callback(rows);
});
connectionProvider.mysqlConnectionStringProvider.closeMySqlConnection(connection);
}
}
,
getAvailableServices : function (callback) {
var connection = connectionProvider.mysqlConnectionStringProvider.getMySqlConnection();
var queryStatement = "SELECT id, name, description FROM services ORDER BY name ASC";
if (connection) {
connection.query(queryStatement, function (err, rows, fields) {
if (err) { throw err; }
console.log(rows);
callback(rows);
});
connectionProvider.mysqlConnectionStringProvider.closeMySqlConnection(connection);
}
}
,
getUserVehiclesByUserId : function (userId, callback) {
var connection = connectionProvider.mysqlConnectionStringProvider.getMySqlConnection();
var queryStatement = "SELECT uv.*, v.year, v.make,v.model, v.year, v.vin, v.mileage_read FROM users_vehicles uv INNER JOIN serviced_vehicles v ON v.id = uv.vehicle_id WHERE uv.user_id = ?";
if (connection) {
connection.query(queryStatement, [userId] , function (err, rows, fields) {
if (err) { throw err; }
console.log(rows);
callback(rows);
});
connectionProvider.mysqlConnectionStringProvider.closeMySqlConnection(connection);
}
}
,
getAllVehicles : function (callback) {
var connection = connectionProvider.mysqlConnectionStringProvider.getMySqlConnection();
var queryStatement = "SELECT * FROM vehicles_list";
if (connection) {
connection.query(queryStatement, function (err, rows, fields) {
callback(err,rows);
});
connectionProvider.mysqlConnectionStringProvider.closeMySqlConnection(connection);
}
}
,
updateVehicleById: function (vehicle, vehicleId, callback) {
var connection = connectionProvider.mysqlConnectionStringProvider.getMySqlConnection();
var queryStatement = "UPDATE vehicles_list SET ? WHERE id = ?";
if (connection) {
connection.query(queryStatement, [vehicle, vehicleId], function (err, rows, fields) {
if (err) { throw err; }
console.log(rows);
if (rows)
callback({status : 'success'});
});
connectionProvider.mysqlConnectionStringProvider.closeMySqlConnection(connection);
}
}
,
createVehicle: function (vehicle, callback) {
var connection = connectionProvider.mysqlConnectionStringProvider.getMySqlConnection();
var queryStatement = "INSERT INTO vehicles_list SET ?";
if (connection) {
connection.query(queryStatement, vehicle, function (err, result) {
if (err) {
callback({error: err.code});
}
console.log(result);
if (result) {
callback({status : 'success'});
}
});
connectionProvider.mysqlConnectionStringProvider.closeMySqlConnection(connection);
}
}
,
getVehicleById: function (id, callback) {
var connection = connectionProvider.mysqlConnectionStringProvider.getMySqlConnection();
var queryStatement = "SELECT * FROM vehicles_list WHERE id = ?";
if (connection) {
connection.query(queryStatement, [id], function (err, rows, fields) {
if (err) { throw err; }
console.log(rows[0]);
callback(rows[0]);
});
connectionProvider.mysqlConnectionStringProvider.closeMySqlConnection(connection);
}
}
,
markDeleted : function(id, callback) {
var connection = connectionProvider.mysqlConnectionStringProvider.getMySqlConnection();
var queryStatement = "DELETE FROM vehicles_list WHERE id = ?";
if (connection) {
connection.query(queryStatement, [id], function (err, result) {
callback(err, result);
});
connectionProvider.mysqlConnectionStringProvider.closeMySqlConnection(connection);
}
}
}
module.exports.vehicleModel = vehicleModel; |
export const questionCategory = {
radio: 0,
checkbox: 1,
textfield: 2,
date: 3,
dropdown: 4,
upload: 5,
number: 6,
country: 7,
plus: 8,
infoText: 9,
textArea: 10
};
|
var EventManager = ring.create({
constructor: function(gamemanager)
{
this.gamemanager = gamemanager;
this.events = [];
},
trigger: function(event)
{
if (!this.events[event]) return;
var args = [].slice.apply(arguments).slice(1);
if (event !== 'update' && event !== 'draw')
{
//console.log(event, args);
}
for (var name in this.events[event])
{
var callback = this.events[event][name][0];
var context = this.events[event][name][1];
callback.apply(context, args);
}
},
add: function(event, name, callback, context)
{
if (!this.events[event]) this.events[event] = {};
this.events[event][name] = [ callback, context ];
},
remove: function(event, name)
{
if (!this.events[event]) return;
delete this.events[event][name];
}
}); |
define(
[
'marionette',
'tpl!templates/VersionChooser.tpl',
'views/VersionInfo'
],
function(
Marionette,
template,
VersionInfoView
) {
return Marionette.ItemView.extend({
template: template,
dialog: null,
versionView : null,
lastVersionId: null,
events: {
'click .j-create-version-btn' : 'onClickCreateVersion',
'click .j-save-version-btn' : 'onClickSaveVersion',
'click .j-switch-version-btn' : 'onClickSwitchVersion',
'click .j-remove-version-btn' : 'onClickRemoveVersion',
'change .j-version-select' : 'onSelectVersion'
},
initialize: function() {
this.lastVersionId = null;
},
serializeData: function() {
return {
document : this.model,
lastVersionId: this.lastVersionId
};
},
setDialog: function(dialog) {
this.dialog = dialog;
},
getDialog: function() {
return this.dialog;
},
onRender: function() {
var selectedVersionId = !_.isNull(this.lastVersionId) ? this.lastVersionId : this.model.getCurrentVersionId();
this.showVersionInfo(this.model.getVersion(selectedVersionId));
},
showVersionInfo: function(version) {
this.versionView = new VersionInfoView({
el : this.$el.find('.j-version-data'),
model : version
}).render();
this.versionView.on('version:change', function() {
this.setSaveDisabled(false);
}, this);
this.versionView.on('version:select', function(versionId) {
this.$el.find('.j-version-select')
.val(versionId)
.change();
}, this);
this.setSaveDisabled(true);
var isCurrentVersion = this.model.getVersion(this.getSelectedVersionId()).isCurrentDocumentVersion();
this.setChangeDisabled(isCurrentVersion);
this.setDeleteDispabed(isCurrentVersion)
},
setSaveDisabled: function(disabled) {
this.setButtonDisabled('.j-save-version-btn', disabled);
},
setChangeDisabled: function(disabled) {
this.setButtonDisabled('.j-switch-version-btn', disabled);
},
setDeleteDispabed: function(disabled) {
this.setButtonDisabled('.j-remove-version-btn', disabled);
},
setButtonDisabled: function(selector, disabled) {
this.$el.find(selector).attr('disabled', disabled ? 'disabled': null);
},
onClickCreateVersion: function() {
var _this = this;
var dialog = this.getDialog();
dialog.showInfo('Saving...');
dialog.disableClosing();
var childVersion = this.model.createChildVersion(this.model.getVersion(this.getSelectedVersionId()));
childVersion
.save()
.success(function(updatedDocument){
_this.model
.clearVersions()
.set(updatedDocument);
_this.render();
dialog.showSuccess('Version succesfully saved');
dialog.enableClosing();
})
.error(function(){
dialog.showError('Version was not saved');
dialog.enableClosing();
})
},
onClickSaveVersion: function() {
var _this = this;
var dialog = this.getDialog();
dialog.showInfo('Saving...');
dialog.disableClosing();
this.lastVersionId = this.getSelectedVersionId();
this.model.getVersion(this.getSelectedVersionId())
.save()
.success(function(updatedDocument){
_this.model
.clearVersions()
.set(updatedDocument);
_this.render();
dialog.showSuccess('Version succesfully saved');
dialog.enableClosing();
})
.error(function(){
dialog.showError('Version was not saved');
dialog.enableClosing();
})
},
onClickSwitchVersion: function() {
var _this = this;
this.model
.requestChangeVersion(this.getSelectedVersionId())
.success(function(){
_this.getDialog().hide();
})
.error(function(){
_this.getDialog().showError('Version was not changed');
})
},
onClickRemoveVersion: function() {
var _this = this;
var dialog = this.getDialog();
dialog.showInfo('Remove version...');
dialog.disableClosing();
this.model.getVersion(this.getSelectedVersionId())
.destroy()
.success(function(updatedDocument){
_this.model
.clearVersions()
.set(updatedDocument);
_this.render();
dialog.showSuccess('Version succesfully removed');
dialog.enableClosing();
})
.error(function(){
dialog.showError('Version was not removed');
dialog.enableClosing();
})
},
onSelectVersion: function() {
this.showVersionInfo(this.model.getVersion(this.getSelectedVersionId()));
},
getSelectedVersionId: function() {
return this.$el.find('.j-version-select').find(':selected').val();
}
});
}) |
module.exports = function(config) {
config.set({
basePath: './',
frameworks: ['systemjs', 'jasmine'],
systemjs: {
configFile: 'config.js',
config: {
paths: {
"*": "*",
"src/*": "src/*",
"typescript": "node_modules/typescript/lib/typescript.js",
"systemjs": "node_modules/systemjs/dist/system.js",
'system-polyfills': 'node_modules/systemjs/dist/system-polyfills.js',
'es6-module-loader': 'node_modules/es6-module-loader/dist/es6-module-loader.js'
},
packages: {
'test/unit': {
defaultExtension: 'ts'
},
'src': {
defaultExtension: 'ts'
}
},
transpiler: 'typescript',
typescriptOptions : {
"module": "amd",
"emitDecoratorMetadata": true,
"experimentalDecorators": true
}
},
serveFiles: [
'src/**/*.*',
'jspm_packages/**/*.js',
'jspm_packages/**/*.json'
]
},
files: [
'test/unit/setup.ts',
'test/unit/*.ts'
],
exclude: [],
preprocessors: { },
reporters: ['spec'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
|
$(function () {
var effectDelayms = 200;
var d = new Date();
var h = d.getHours() > 12 ? d.getHours() - 12 : d.getHours();
var m = d.getMinutes() < 10 ? "0" + d.getMinutes() : d.getMinutes();
var a = d.getHours() >= 12 ? "pm" : "am";
// Default meeting date to current date
$('.default-date-now').val(d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear() + " " + h + ":" + m + a);
// auto-grow a textarea element based on content size
function autoGrowTextArea(textarea) {
textarea.style.height = 'auto';
textarea.style.height = textarea.scrollHeight + 'px';
}
// auto-grow textareas on key up
$('.textarea').keyup(function (e) {
autoGrowTextArea(e.target);
});
// Detect when a group of elements is empty
var allEmpty = function (elements) {
for (var i = 0; i < elements.length; i++) {
// a yes/no questions with a 'no' answer is considered 'empty'
if ($('.btn-yes.selected', elements[i]).length > 0) {
return false;
}
if ($(elements[i]).val() !== '') {
return false;
}
}
return true;
};
var yesNoButtonBehaviour = function() {
$('.yesno button').click(function (e) {
$('button', e.target.parentElement).removeClass('selected');
$(this).addClass('selected');
});
} ();
// Setup dependent fields that are shown only when reqd.
var dependsOn = function (elementToHide, textElements) {
//console.log('dependsOn(' + elementToHide.attr('id') + ', ' + textElements.attr('id') + ')')
// set initial visibility of elements
if (allEmpty(textElements)) {
$(elementToHide).hide();
} else {
$(elementToHide).show();
}
// check visibility on key events
//$('textarea, input', textElements).keyup(function (e) {
$(textElements).keyup(function (e) {
if (allEmpty(textElements)) {
$(elementToHide).hide(effectDelayms);
} else {
$(elementToHide).show(effectDelayms);
}
});
$('button', textElements).click(function (e) {
if (allEmpty(textElements)) {
$(elementToHide).hide(effectDelayms);
} else {
$(elementToHide).show(effectDelayms);
}
});
};
// Create a new agenda item, append it to the #agenda-items, and return it
function addAgendaItem() {
var numAgendaItems = $('#agenda-items > *').length;
var thisAgendaItemNum = numAgendaItems + 1;
// clone based on the template
var agendaItem = $('#agenda-item-template').clone(true);
$(agendaItem[0]).attr('id', 'agenda-item-' + thisAgendaItemNum);
$('.agenda-item-number', agendaItem).text('Agenda item no. ' + thisAgendaItemNum);
// assign id's to elements
$('.agenda-item-title', agendaItem).attr('id', 'agenda-item-title-' + thisAgendaItemNum);
$('.agenda-item-description', agendaItem).attr('id', 'agenda-item-description-' + thisAgendaItemNum);
$('.agenda-item-discussion', agendaItem).attr('id', 'agenda-item-discussion-' + thisAgendaItemNum);
$('.agenda-item-discussion-text', agendaItem).attr('id', 'agenda-item-discussion-text-' + thisAgendaItemNum);
$('.agenda-item-decision', agendaItem).attr('id', 'agenda-item-decision-' + thisAgendaItemNum);
$('.agenda-item-decision-reached', agendaItem).attr('id', 'agenda-item-decision-reached-' + thisAgendaItemNum);
$('.agenda-item-decision-reached-dependency', agendaItem).attr('id', 'agenda-item-decision-reached-dependency-' + thisAgendaItemNum);
$('.agenda-item-motion', agendaItem).attr('id', 'agenda-item-motion-' + thisAgendaItemNum);
$('.agenda-item-motion-notes', agendaItem).attr('id', 'agenda-item-motion-notes-' + thisAgendaItemNum);
$('.agenda-item-motion-notes-text', agendaItem).attr('id', 'agenda-item-motion-notes-text-' + thisAgendaItemNum);
agendaItem.hide(); // hide so it can be shown with transition effect
agendaItem.appendTo('#agenda-items');
return agendaItem;
}
var setupAgendaItemDependencies = function (idx, agendaItem) {
var thisAgendaItemNum = idx + 1;
//dependsOn($('#agenda-item-discussion-' + thisAgendaItemNum, agendaItem), $('#agenda-item-discussed-text-' + thisAgendaItemNum, agendaItem));
//dependsOn($('#agenda-item-motion-' + thisAgendaItemNum, agendaItem), $('#agenda-item-discussion-text-' + thisAgendaItemNum));// + ', #agenda-item-discussed-text-' + thisAgendaItemNum, agendaItem));
dependsOn($('#agenda-item-decision-reached-dependency-' + thisAgendaItemNum, agendaItem), $('#agenda-item-decision-reached-' + thisAgendaItemNum));
//dependsOn($('#agenda-item-motion-' + thisAgendaItemNum, agendaItem), $('#agenda-item-discussed-text-' + thisAgendaItemNum));
};
// Dynamically add agenda items
$('.btn-add-agenda-item').click(function (e) {
var agendaItem = addAgendaItem(); // create agenda item elements
agendaItem.show(effectDelayms); // show them
var numAgendaItems = $('#agenda-items > *').length;
setupAgendaItemDependencies(numAgendaItems-1, agendaItem);
$('.input', agendaItem)[0].focus(); // focus on first input (Title)
});
var firstAgendaItem = addAgendaItem(); // add initial agenda item
firstAgendaItem.show();
setupAgendaItemDependencies(0, firstAgendaItem);
// setup other dependencies
dependsOn($('#correspondence-motion'), $('#correspondence-text'));
//dependsOn($('#financial-report-dependency'), $('#financial-report-presenter'));
dependsOn($('#expenses-dependency'), $('#expenses-yes-no'));
dependsOn($('#other-report-dependency'), $('#other-report-text'));
dependsOn($('#other-discussion-dependency'), $('#other-discussion'));
dependsOn($('#other-decision-dependency'), $('#other-decision'));
//$('#help-content .help-group-get-started').show();
// Adds a record to the expenses table
function addExpenseRecord() {
var templateRow = $('#expenses-table-template tbody tr').clone(true);
templateRow.appendTo($('#expenses-table tbody'));
// Attach keyup event to last Description item only
// remove keyup event from all desc
$('#expenses-table .expense-desc .input').off('keyup');
//attach keyup event to last desc
$('#expenses-table .expense-desc .input').last().on('keyup', function (e) {
if (e.keyCode == 13) {
addExpenseRecord();
// focus on new record's date input
$('#expenses-table .expense-date .input').last().focus();
}
});
}
// Add the first expenses record
addExpenseRecord();
var motionFailedText = "This motion did not pass because ";
$('.motion .btn-no').click(function (e) {
// Insert the failed motion default text
var motionDesc = $('.textarea', $(e.target).parent().parent());
if (motionDesc.val() == "") {
motionDesc.val(motionFailedText);
}
});
$('.motion .btn-yes').click(function (e) {
// Clear the failed motion default text
var motionDesc = $('.textarea', $(e.target).parent().parent());
if (motionDesc.val() == motionFailedText) {
motionDesc.val('');
}
});
// Setup context-sensitive help by showing the relevant help sections
// based on focus.
$('#organisation *').focus(function (e) {
$('#help-content .article').hide();
$('#help-content .help-group-get-started').show();
$('#help-content .help-group-organisation').show();
});
$('#meeting-date-article *').focus(function (e) {
$('#help-content .article').hide();
$('#help-content .help-group-organisation').show();
});
$('#meeting-date-and-location *').focus(function (e) {
$('#help-content .article').hide();
$('#help-content .help-group-meeting-date').show();
$('#help-content .help-group-meeting-location').show();
});
$('#attendees *').focus(function (e) {
$('#help-content .article').hide();
$('#help-content .help-group-attendees').show();
});
$('#apologies *').focus(function (e) {
$('#help-content .article').hide();
$('#help-content .help-group-apologies').show();
});
$('#previous-meeting *').focus(function (e) {
$('#help-content .article').hide();
$('#help-content .help-group-previous-meeting').show();
});
$('#previous-meeting-true-and-correct *').focus(function (e) {
$('#help-content .article').hide();
$('#help-content .help-group-previous-meeting-true-and-correct').show();
$('#help-content .help-group-motion').show();
});
$('#previous-minutes-matters-arising *').focus(function (e) {
$('#help-content .article').hide();
$('#help-content .help-group-matters-arising-from-previous-meeting').show();
});
$('#correspondence *').focus(function (e) {
$('#help-content .article').hide();
$('#help-content .help-group-correspondence').show();
$('#help-content .help-group-motion').show();
});
$('#financial-report *').focus(function (e) {
$('#help-content .article').hide();
$('#help-content .help-group-financial-report').show();
$('#help-content .help-group-motion').show();
});
$('#expenses *').focus(function (e) {
$('#help-content .article').hide();
$('#help-content .help-group-expenses').show();
$('#help-content .help-group-motion').show();
});
$('#other-reports *').focus(function (e) {
$('#help-content .article').hide();
$('#help-content .help-group-other-reports').show();
$('#help-content .help-group-motion').show();
});
//$('.motion *').on('focus', function (e) {
// //$('#help-content .article').hide(); // hide all help articles
// $('#help-content .help-group-motion').show();
//});
$('.agenda-item *').focus(function (e) {
$('#help-content .article').hide();
$('#help-content .help-group-agenda-item').show();
$('#help-content .help-group-motion').show();
});
// "Let's get started" button
$('#start-btn').click(function () {
window.location = '#page';
$('#orgnanisation-name').focus();
return false;
});
$('body').addClass('loaded');
//$('#help-close-btn-container').click(function () {
// // expand/collapse help sidebar
// var help = $('#help-sidebar');
// if (help.hasClass('collapsed')) {
// help.removeClass('collapsed');
// help.addClass('expanded');
// $('#help-close-btn-container').attr('title', 'close help sidebar')
// } else {
// help.removeClass('expanded');
// help.addClass('collapsed');
// $('#help-close-btn-container').attr('title', 'show help sidebar')
// }
//});
// move carret to end when focussing on a textarea so user can start typing
// http://stackoverflow.com/questions/6003300/how-to-place-cursor-at-end-of-text-in-textarea-when-tabbed-into
function moveCaretToEnd(el) {
if (typeof el.selectionStart == "number") {
el.selectionStart = el.selectionEnd = el.value.length;
} else if (typeof el.createTextRange != "undefined") {
el.focus();
var range = el.createTextRange();
range.collapse(false);
range.select();
}
}
$(".textarea").focus(function (e) {
moveCaretToEnd(e.target);
// Work around Chrome's little problem
window.setTimeout(function () {
moveCaretToEnd(e.target);
}, 1);
});
// Names of all people in the group will be accumulated based on user input.
var allNames = [];
var accumulateNames = function () {
$('input.names').blur(function (b) {
$('input.names').each(function (idx, e) {
var names = $(e).val().split(',');
for (var i = 0; i < names.length; i++) {
var name = $.trim(names[i]);
if ($.inArray(name, allNames) === -1 && name !== '') {
allNames.push(name);
}
}
});
});
}();
var $help = $("#help-content");
var $header = $("header");
var positionHelpFixed = function () {
// on non-touch, we can use fixed positioning to keep the help
// visible, but only when the header has scrolled off screen.
var scrollTop = $(window).scrollTop();
var helpOffsetTop = $help.offset().top;
if (scrollTop > $header.height()) {
if (Math.abs(scrollTop - helpOffsetTop) > 1) {
$help.css('position', 'fixed');
$help.css('top', '0');
} else {
$help.css('position', 'relative');
$help.css('margin-top', '20px');
}
} else {
$help.css('position', 'relative');
$help.css('margin-top', '20px');
}
};
//if (Modernizr.touch) {
// $('*').focus(function () {
// // move help to where user is focussed
// $help.css('margin-top', 20 + $(this).offset().top - $header.height() - 100 + 'px');
// });
//} else {
$(window).scroll(function () {
// move help using css fixed psoitioning
positionHelpFixed();
});
//}
// array of possible header background images (for prototype only)
var headerImg = [
{
'background-image': 'url("../img/keyboard-full.jpg")'
},
{
'background-image': 'url("../img/home-office-336373_1920.jpg")'
},
{
'background-image': 'url("../img/keyboard-622456_1920.jpg")'
},
{
'background-image': 'url("../img/mosaic-913658.jpg")'
},
{
'background-image': 'url("../img/table-629772.jpg")'
},
{
'background-image': 'url("../img/typing-690856.jpg")'
},
];
var headerImgIdx = 1;
$header.click(function (e) {
// swap image
for (var p in headerImg[headerImgIdx]) {
$header.css(p, headerImg[headerImgIdx][p]);
console.log(headerImg[headerImgIdx][p]);
}
headerImgIdx++;
if (headerImgIdx == headerImg.length) {
headerImgIdx = 0;
}
});
});
|
(function() {
window.S3Upload = (function() {
S3Upload.prototype.s3_object_name = 'default_name';
S3Upload.prototype.s3_sign_put_url = '/signS3put';
S3Upload.prototype.file_dom_selector = 'file_upload';
S3Upload.prototype.onFinishS3Put = function(public_url) {
return console.log('base.onFinishS3Put()', public_url);
};
S3Upload.prototype.onProgress = function(percent, status) {
return console.log('base.onProgress()', percent, status);
};
S3Upload.prototype.onError = function(status) {
return console.log('base.onError()', status);
};
function S3Upload(options) {
if (options == null) options = {};
for (option in options) {
this[option] = options[option];
}
// this.handleFileSelect(document.getElementById(this.file_dom_selector));
this.uploadFile(this.blob);
}
S3Upload.prototype.handleFileSelect = function(file_element) {
var f, files, output, _i, _len, _results;
this.onProgress(0, 'Upload started.');
files = file_element.files;
output = [];
_results = [];
for (_i = 0, _len = files.length; _i < _len; _i++) {
f = files[_i];
_results.push(this.uploadFile(f));
}
return _results;
};
S3Upload.prototype.createCORSRequest = function(method, url) {
var xhr;
xhr = new XMLHttpRequest();
if (xhr.withCredentials != null) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest !== "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
};
S3Upload.prototype.executeOnSignedUrl = function(file, callback) {
var this_s3upload, xhr;
this_s3upload = this;
xhr = new XMLHttpRequest();
xhr.open('GET', this.s3_sign_put_url + '?s3_object_type=' + file.type, true);
xhr.overrideMimeType('text/plain; charset=x-user-defined');
xhr.onreadystatechange = function(e) {
var result;
if (this.readyState === 4 && this.status === 200) {
try {
result = JSON.parse(this.responseText);
} catch (error) {
this_s3upload.onError('Signing server returned some ugly/empty JSON: "' + this.responseText + '"');
return false;
}
return callback(result.signed_request, result.url, result.fd);
} else if (this.readyState === 4 && this.status !== 200) {
return this_s3upload.onError('Could not contact request signing server. Status = ' + this.status);
}
};
return xhr.send();
};
S3Upload.prototype.uploadToS3 = function(file, url, public_url, fd) {
var this_s3upload, xhr;
this_s3upload = this;
xhr = this.createCORSRequest('PUT', url);
if (!xhr) {
this.onError('CORS not supported');
} else {
xhr.onload = function() {
if (xhr.status === 200) {
this_s3upload.onProgress(100, 'Upload completed.');
return this_s3upload.onFinishS3Put(public_url, fd);
} else {
return this_s3upload.onError('Upload error: ' + xhr.status);
}
};
xhr.onerror = function() {
return this_s3upload.onError('XHR error.');
};
xhr.upload.onprogress = function(e) {
var percentLoaded;
if (e.lengthComputable) {
percentLoaded = Math.round((e.loaded / e.total) * 100);
return this_s3upload.onProgress(percentLoaded, percentLoaded === 100 ? 'Finalizing.' : 'Uploading.');
}
};
}
xhr.setRequestHeader('Content-Type', file.type);
xhr.setRequestHeader('x-amz-acl', 'public-read');
return xhr.send(file);
};
S3Upload.prototype.uploadFile = function(file) {
var this_s3upload;
this_s3upload = this;
return this.executeOnSignedUrl(file, function(signedURL, publicURL, fd) {
return this_s3upload.uploadToS3(file, signedURL, publicURL, fd);
});
};
return S3Upload;
})();
}).call(this); |
import TestContainer from 'mocha-test-container-support';
import {
act
} from '@testing-library/preact';
import {
query as domQuery
} from 'min-dom';
import coreModule from 'bpmn-js/lib/core';
import modelingModule from 'bpmn-js/lib/features/modeling';
import camundaModdlePackage from 'camunda-bpmn-moddle/resources/camunda';
import {
bootstrapPropertiesPanel,
inject
} from 'test/TestHelper';
import BpmnPropertiesPanel from 'src/render';
import elementTemplatesModule from 'src/provider/element-templates';
import diagramXML from './fixtures/template-props.bpmn';
import templates from './fixtures/template-props.json';
describe('provider/element-templates - TemplateProps', function() {
let container;
beforeEach(function() {
container = TestContainer.get(this);
});
beforeEach(bootstrapPropertiesPanel(diagramXML, {
container,
modules: [
BpmnPropertiesPanel,
coreModule,
elementTemplatesModule,
modelingModule
],
moddleExtensions: {
camunda: camundaModdlePackage
},
debounceInput: false,
elementTemplates: templates
}));
describe('name', function() {
it('should display template name', inject(
async function(elementRegistry, selection, elementTemplates) {
// given
const element = elementRegistry.get('Template_2');
const template = elementTemplates.get(element);
// when
await act(() => {
selection.select(element);
});
// then
const entry = domQuery('[data-group-id="group-ElementTemplates__Template"] [data-entry-id="template-name"]', container);
expect(entry).to.exist;
expect(entry.children[1].textContent).to.eql(template.name);
})
);
it('should display for an outdated template', inject(
async function(elementRegistry, selection, elementTemplates) {
// given
const element = elementRegistry.get('Template_3');
const template = elementTemplates.get(element);
// when
await act(() => {
selection.select(element);
});
// then
const entry = domQuery('[data-group-id="group-ElementTemplates__Template"] [data-entry-id="template-name"]', container);
expect(entry).to.exist;
expect(entry.children[1].textContent).to.eql(template.name);
})
);
it('should NOT display if no template is applied', inject(
async function(elementRegistry, selection) {
// given
const element = elementRegistry.get('Template_1');
// when
await act(() => {
selection.select(element);
});
// then
const entry = domQuery('[data-group-id="group-ElementTemplates__Template"] [data-entry-id="template-name"]', container);
expect(entry).not.to.exist;
})
);
});
describe('version', function() {
it('should display template version according to metadata', inject(
async function(elementRegistry, selection) {
// given
const element = elementRegistry.get('Template_2');
// when
await act(() => {
selection.select(element);
});
// then
const entry = domQuery('[data-group-id="group-ElementTemplates__Template"] [data-entry-id="template-version"]', container);
expect(entry).to.exist;
expect(entry.children[1].textContent).to.eql('02.01.2000');
})
);
it('should display for an outdated template', inject(
async function(elementRegistry, selection) {
// given
const element = elementRegistry.get('Template_3');
// when
await act(() => {
selection.select(element);
});
// then
const entry = domQuery('[data-group-id="group-ElementTemplates__Template"] [data-entry-id="template-version"]', container);
expect(entry).to.exist;
expect(entry.children[1].textContent).to.eql('01.01.2000');
})
);
it('should display template bare version if metadata is missing', inject(
async function(elementRegistry, selection, elementTemplates) {
// given
const element = elementRegistry.get('TemplateWithoutMetadata');
const template = elementTemplates.get(element);
// when
await act(() => {
selection.select(element);
});
// then
const entry = domQuery('[data-group-id="group-ElementTemplates__Template"] [data-entry-id="template-version"]', container);
expect(entry).to.exist;
expect(entry.children[1].textContent).to.eql(String(template.version));
})
);
it('should NOT display if version is missing', inject(
async function(elementRegistry, selection) {
// given
const element = elementRegistry.get('TemplateWithoutVersion');
// when
await act(() => {
selection.select(element);
});
// then
const entry = domQuery('[data-group-id="group-ElementTemplates__Template"] [data-entry-id="template-version"]', container);
expect(entry).not.to.exist;
})
);
it('should NOT display if no template is applied', inject(
async function(elementRegistry, selection) {
// given
const element = elementRegistry.get('Template_1');
// when
await act(() => {
selection.select(element);
});
// then
const entry = domQuery('[data-group-id="group-ElementTemplates__Template"] [data-entry-id="template-version"]', container);
expect(entry).not.to.exist;
})
);
});
describe('description', function() {
it('should display template description', inject(
async function(elementRegistry, selection, elementTemplates) {
// given
const element = elementRegistry.get('Template_2');
const template = elementTemplates.get(element);
// when
await act(() => {
selection.select(element);
});
// then
const entry = domQuery('[data-group-id="group-ElementTemplates__Template"] [data-entry-id="template-description"]', container);
expect(entry).to.exist;
expect(entry.children[1].textContent).to.eql(template.description);
})
);
it('should display for an outdated template', inject(
async function(elementRegistry, selection, elementTemplates) {
// given
const element = elementRegistry.get('Template_3');
const template = elementTemplates.get(element);
// when
await act(() => {
selection.select(element);
});
// then
const entry = domQuery('[data-group-id="group-ElementTemplates__Template"] [data-entry-id="template-description"]', container);
expect(entry).to.exist;
expect(entry.children[1].textContent).to.eql(template.description);
})
);
it('should NOT display if description is missing', inject(
async function(elementRegistry, selection) {
// given
const element = elementRegistry.get('TemplateWithoutDescription');
// when
await act(() => {
selection.select(element);
});
// then
const entry = domQuery('[data-group-id="group-ElementTemplates__Template"] [data-entry-id="template-description"]', container);
expect(entry).not.to.exist;
})
);
it('should NOT display if no template is applied', inject(
async function(elementRegistry, selection) {
// given
const element = elementRegistry.get('Template_1');
// when
await act(() => {
selection.select(element);
});
// then
const entry = domQuery('[data-group-id="group-ElementTemplates__Template"] [data-entry-id="template-description"]', container);
expect(entry).not.to.exist;
})
);
});
});
|
/**
* Created by bhandr1 on 5/13/2016.
*/
(function () {
angular.module('app.tapi').controller('TestCaseController',TestCaseController);
function TestCaseController($scope,TestCaseModel,TestCaseBasicFactory,$sessionStorage,$state){
init();
function init() {
initModels();
$scope.testCasesList = [];
TestCaseBasicFactory.getAllTestCases().then(success,error);
function success(response) {
$scope.testCasesList = response.data;
}
function error(response) {
}
}
function initModels() {
$scope.testCaseModel = TestCaseModel.newTestCaseModel();
}
function reset() {
$scope.name = "";
$scope.testCasesList = "";
}
$scope.createTestCase = function () {
$state.go('createTestCase');
};
$scope.saveTestCase = function () {
$scope.testCaseModel.scenarioName = $scope.name;
$scope.testCaseModel.scenarioDescription = $scope.description;
$scope.testCaseModel.endPointURI = $scope.endPointURI;
$scope.testCaseModel.endPointHost = $scope.endPointHost;
$scope.testCaseModel.endPointPort = $scope.endPointPort;
$scope.testCaseModel.requestMethod = $scope.requestMethod;
$scope.testCaseModel.responseType = $scope.responseType;
TestCaseBasicFactory.createTestCaseData($scope.testCaseModel).then(success, error);
function success(response) {
reset();
$state.go('viewTestCase');
}
function error(response) {
reset();
}
};
$scope.testCaseList = function () {
$scope.testCasesList = [];
TestCaseBasicFactory.getAllTestCases().then(success,error);
function success(response) {
$scope.testCasesList = response.data;
$state.go('viewTestCase');
}
function error(response) {
}
}
}
TestCaseController.$inject = ['$scope','TestCaseModel','TestCaseBasicFactory','$sessionStorage','$state'];
})();
|
/**
* Browser LSC Storage API // storage.spec.js
* coded by Anatol Merezhanyi @e1r0nd_crg
* https://www.youtube.com/c/AnatolMerezhanyi
*/
import StorageClass from '../storage';
import chai from 'chai';
import sinon from 'sinon';
const expect = chai.expect;
describe('# localStorage', () => {
const storageMock = (() => {
const storage = {};
return {
clear: () => {
for (const key in storage) {
if ({}.propertyIsEnumerable.call(storage, key)) {
delete storage[key];
}
}
},
getItem: (key) => (key in storage ? storage[key] : null),
key: (index) => {
const keys = Object.keys(storage);
return keys[index] || null;
},
get length() {
return Object.keys(storage).length;
},
removeItem: (key) => {
delete storage[key];
},
setItem: (key, value) => {
storage[key] = value || '';
},
};
})();
Object.defineProperty(global, 'window', { value: {} });
Object.defineProperty(window, 'localStorage', { value: storageMock });
it('expect an Error if localStorage isn\'t defined', () => {
const stub = sinon.stub(global.window.localStorage, 'getItem');
expect(() => {
const FailLocal = new StorageClass();
FailLocal.isAvailable();
}).to.throw(Error);
expect(() => {
localStorage.getItem = '';
const FailLocal = new StorageClass();
FailLocal.isAvailable();
}).to.throw(Error);
stub.restore();
});
it('check for availability', () => {
const Local = new StorageClass();
expect(Local.isAvailable()).to.be.true;
expect(Local.hasKey()).to.be.false;
});
it('check initial length', () => {
const lengthWithPrefix = 3;
const Local = new StorageClass();
expect(Local.isAvailable()).to.be.true;
expect(Local.key('x-key', 'y-value')).to.be.true;
expect(Local.prefix = 'new').to.equal('new');
expect(Local.key('a-key', 'a-value')).to.be.true;
expect(Local.key('b-key', 'b-value')).to.be.true;
expect(Local.key('c-key', 'c-value')).to.be.true;
expect(Local.length).to.equal(lengthWithPrefix);
});
it('check for a prefix', () => {
const Local = new StorageClass();
Local.prefix = 'qwe';
expect(Local.prefix).to.equal('qwe');
expect(Local.hasKey('a-key')).to.be.false;
});
it('check for a key', () => {
const Local = new StorageClass();
expect(Local.hasKey('a-key')).to.be.false;
expect(Local.hasKey('')).to.be.false;
});
it('write & read a key-value pair', () => {
const Local = new StorageClass();
expect(Local.key('b-key', 'b-value')).to.be.true;
expect(Local.hasKey('b-key')).to.be.true;
expect(Local.key('b-key')).to.equal('b-value');
expect(Local.key()).to.be.false;
});
it('use each method', () => {
const Local = new StorageClass();
expect(Local.prefix = 'test').to.equal('test');
expect(Local.key('a-key', 'a-value')).to.be.true;
expect(Local.key('b-key', 'b-value1')).to.be.true;
expect(Local.key('c-key', 'c-value')).to.be.true;
expect(Local.hasKey('b-key')).to.be.true;
expect(Local.key('b-key')).to.equal('b-value1');
expect(Local.each()).to.be.an('array');
expect(Local.each()).to.include({ 'a-key': 'a-value' });
expect(Local.each()).to.include({ 'b-key': 'b-value1' });
expect(Local.each()).to.include({ 'c-key': 'c-value' });
});
it('delete a key', () => {
const Local = new StorageClass();
expect(Local.removeKey('b-key')).to.be.true;
expect(Local.hasKey('b-key')).to.be.false;
expect(Local.removeKey('')).to.be.false;
});
it('clear Storage', () => {
const Local = new StorageClass();
const zeroLength = 0;
expect(Local.key('x-key', 'x-value')).to.be.true;
expect(Local.prefix = 'asd').to.equal('asd');
expect(Local.key('c-key', 'c')).to.be.true;
expect(Local.key('d-key', 'd')).to.be.true;
expect(Local.hasKey('d-key')).to.be.true;
expect(Local.clear()).to.be.true;
expect(Local.hasKey('c-key')).to.be.false;
expect(Local.hasKey('d-key')).to.be.false;
expect(Local.length).to.equal(zeroLength);
expect(Local.prefix = '').to.equal('');
expect(Local.hasKey('x-key')).to.be.true;
});
});
describe('# sessionStorage', () => {
const storageMock = (() => {
const storage = {};
return {
clear: () => {
for (const key in storage) {
if ({}.propertyIsEnumerable.call(storage, key)) {
delete storage[key];
}
}
},
getItem: (key) => (key in storage ? storage[key] : null),
key: (index) => {
const keys = Object.keys(storage);
return keys[index] || null;
},
get length() {
return Object.keys(storage).length;
},
removeItem: (key) => {
delete storage[key];
},
setItem: (key, value) => {
storage[key] = value || '';
},
};
})();
Object.defineProperty(window, 'sessionStorage', { value: storageMock });
it('expect an Error if sessionStorage isn\'t defined', () => {
const stub = sinon.stub(global.window.sessionStorage, 'getItem');
expect(() => {
const FailSession = new StorageClass('sessionStorage');
FailSession.isAvailable();
}).to.throw(Error);
expect(() => {
sessionStorage.getItem = '';
const FailSession = new StorageClass('sessionStorage');
FailSession.isAvailable();
}).to.throw(Error);
stub.restore();
});
it('check for availability', () => {
const Session = new StorageClass('sessionStorage');
expect(Session.isAvailable()).to.be.true;
});
it('check for a prefix', () => {
const Session = new StorageClass('sessionStorage');
Session.prefix = 'qwe';
expect(Session.prefix).to.equal('qwe');
});
it('check for a key', () => {
const Session = new StorageClass('sessionStorage');
expect(Session.hasKey('a-key')).to.be.false;
expect(Session.hasKey('')).to.be.false;
});
it('write & read a key-value pair', () => {
const Session = new StorageClass('sessionStorage');
expect(Session.key('b-key', 'b-value')).to.be.true;
expect(Session.key('z-key', 'z-value')).to.be.true;
expect(Session.hasKey('b-key')).to.be.true;
expect(Session.hasKey('z-key')).to.be.true;
expect(Session.key('b-key')).to.equal('b-value');
expect(Session.key('z-key')).to.equal('z-value');
expect(Session.key()).to.be.false;
});
it('use each method', () => {
const Session = new StorageClass('sessionStorage');
expect(Session.prefix = 'test').to.equal('test');
expect(Session.key('a-key', 'a-value')).to.be.true;
expect(Session.key('b-key', 'b-value1')).to.be.true;
expect(Session.key('c-key', 'c-value')).to.be.true;
expect(Session.hasKey('b-key')).to.be.true;
expect(Session.key('b-key')).to.equal('b-value1');
expect(Session.each()).to.be.an('array');
expect(Session.each()).to.not.include({ 'z-key': 'z-value' });
expect(Session.each()).to.include({ 'a-key': 'a-value' });
expect(Session.each()).to.include({ 'b-key': 'b-value1' });
expect(Session.each()).to.include({ 'c-key': 'c-value' });
});
it('use forEach method', () => {
const Session = new StorageClass('sessionStorage');
expect(Session.prefix = 'test').to.equal('test');
expect(Session.key('x-key', 'x-value')).to.be.true;
expect(Session.key('y-key', 'y-value')).to.be.true;
expect(Session.key('x-key')).to.equal('x-value');
expect(Session.key('y-key')).to.equal('y-value');
expect(Session.forEach((key, value, index) => {
Session.key(key, value + index);
}));
expect(Session.key('x-key')).to.equal('x-value3');
expect(Session.key('y-key')).to.equal('y-value4');
});
it('delete a key', () => {
const Session = new StorageClass('sessionStorage');
expect(Session.removeKey('b-key')).to.be.true;
expect(Session.hasKey('b-key')).to.be.false;
expect(Session.removeKey('')).to.be.false;
});
it('clear Storage', () => {
const Session = new StorageClass('sessionStorage');
const zeroLength = 0;
expect(Session.key('c-key', 'c')).to.be.true;
expect(Session.key('d-key', 'd')).to.be.true;
expect(Session.hasKey('d-key')).to.be.true;
expect(Session.clear()).to.be.true;
expect(Session.hasKey('c-key')).to.be.false;
expect(Session.hasKey('d-key')).to.be.false;
expect(Session.length).to.equal(zeroLength);
});
});
|
const net = require('net');
let server = new net.Server();
server.on('connection' () => {
let clientAddress = client.remoteAddress;
console.log("A client connected, address: " + clientAddress);
client.on('close', () => {
})
})
server.on('listening', () => {
console.log('Server is now listening.');
});
server.listen(9000);
|
'use strict';
require('es6-promise').polyfill();
var React = require('react');
var assign = require('object-assign');
var LoadMask = require('react-load-mask');
var Region = require('region');
var PaginationToolbar = React.createFactory(require('./PaginationToolbar'));
var Column = require('./models/Column');
var PropTypes = require('./PropTypes');
var Wrapper = require('./Wrapper');
var Header = require('./Header');
var WrapperFactory = React.createFactory(Wrapper);
var HeaderFactory = React.createFactory(Header);
var ResizeProxy = require('./ResizeProxy');
var findIndexByName = require('./utils/findIndexByName');
var group = require('./utils/group');
var slice = require('./render/slice');
var _getTableProps = require('./render/getTableProps');
var getGroupedRows = require('./render/getGroupedRows');
var renderMenu = require('./render/renderMenu');
var preventDefault = require('./utils/preventDefault');
var isArray = Array.isArray;
var SIZING_ID = '___SIZING___';
function clamp(value, min, max) {
return value < min ? min : value > max ? max : value;
}
function signum(x) {
return x < 0 ? -1 : 1;
}
function emptyFn() {}
function getVisibleCount(props, state) {
return getVisibleColumns(props, state).length;
}
function getVisibleColumns(props, state) {
var visibility = state.visibility;
var visibleColumns = props.columns.filter(function (c) {
var name = c.name;
var visible = c.visible;
if (name in visibility) {
visible = !!visibility[name];
}
return visible;
});
return visibleColumns;
}
function findColumn(columns, column) {
var name = typeof column === 'string' ? column : column.name;
var index = findIndexByName(columns, name);
if (~index) {
return columns[index];
}
}
module.exports = React.createClass({
displayName: 'ReactDataGrid',
mixins: [require('./RowSelect'), require('./ColumnFilter')],
propTypes: {
loading: React.PropTypes.bool,
virtualRendering: React.PropTypes.bool,
//specify false if you don't want any column to be resizable
resizableColumns: React.PropTypes.bool,
filterable: React.PropTypes.bool,
//specify false if you don't want column menus to be displayed
withColumnMenu: React.PropTypes.bool,
cellEllipsis: React.PropTypes.bool,
sortable: React.PropTypes.bool,
loadMaskOverHeader: React.PropTypes.bool,
idProperty: React.PropTypes.string.isRequired,
//you can customize the column menu by specifying a factory
columnMenuFactory: React.PropTypes.func,
onDataSourceResponse: React.PropTypes.func,
onDataSourceSuccess: React.PropTypes.func,
onDataSourceError: React.PropTypes.func,
/**
* @cfg {Number/String} columnMinWidth=50
*/
columnMinWidth: PropTypes.numeric,
scrollBy: PropTypes.numeric,
rowHeight: PropTypes.numeric,
sortInfo: PropTypes.sortInfo,
columns: PropTypes.column,
data: function data(props, name) {
var value = props[name];
if (isArray(value)) {
return new Error('We are deprecating the "data" array prop. Use "dataSource" instead! It can either be an array (for local data) or a remote data source (string url, promise or function)');
}
}
},
getDefaultProps: require('./getDefaultProps'),
componentDidMount: function componentDidMount() {
window.addEventListener('click', this.windowClickListener = this.onWindowClick);
},
componentWillUnmount: function componentWillUnmount() {
this.scroller = null;
window.removeEventListener('click', this.windowClickListener);
},
// checkRowHeight: function(props) {
// if (this.isVirtualRendering(props)){
// //if virtual rendering and no rowHeight specifed, we use
// var row = this.findRowById(SIZING_ID)
// var config = {}
// if (row){
// this.setState({
// rowHeight: config.rowHeight = row.offsetHeight
// })
// }
// //this ensures rows are kept in view
// this.updateStartIndex(props, undefined, config)
// }
// },
onWindowClick: function onWindowClick(event) {
if (this.state.menu) {
this.setState({
menuColumn: null,
menu: null
});
}
},
getInitialState: function getInitialState() {
var props = this.props;
var defaultSelected = props.defaultSelected;
return {
startIndex: 0,
scrollLeft: 0,
scrollTop: 0,
menuColumn: null,
defaultSelected: defaultSelected,
visibility: {},
defaultPageSize: props.defaultPageSize,
defaultPage: props.defaultPage
};
},
updateStartIndex: function updateStartIndex() {
this.handleScrollTop();
},
handleScrollLeft: function handleScrollLeft(scrollLeft) {
this.setState({
scrollLeft: scrollLeft,
menuColumn: null
});
},
handleScrollTop: function handleScrollTop(scrollTop) {
var props = this.p;
var state = this.state;
scrollTop = scrollTop === undefined ? this.state.scrollTop : scrollTop;
state.menuColumn = null;
this.scrollTop = scrollTop;
if (props.virtualRendering) {
var prevIndex = this.state.startIndex || 0;
var renderStartIndex = Math.ceil(scrollTop / props.rowHeight);
state.startIndex = renderStartIndex
// var data = this.prepareData(props)
// if (renderStartIndex >= data.length){
// renderStartIndex = 0
// }
// state.renderStartIndex = renderStartIndex
// var endIndex = this.getRenderEndIndex(props, state)
// if (endIndex > data.length){
// renderStartIndex -= data.length - endIndex
// renderStartIndex = Math.max(0, renderStartIndex)
// state.renderStartIndex = renderStartIndex
// }
// // console.log('scroll!');
// var sign = signum(renderStartIndex - prevIndex)
// state.topOffset = -sign * Math.ceil(scrollTop - state.renderStartIndex * this.props.rowHeight)
// console.log(scrollTop, sign);
;
} else {
state.scrollTop = scrollTop;
}
this.setState(state);
},
getRenderEndIndex: function getRenderEndIndex(props, state) {
var startIndex = state.startIndex;
var rowCount = props.rowCountBuffer;
var length = props.data.length;
if (state.groupData) {
length += state.groupData.groupsCount;
}
if (!rowCount) {
var maxHeight;
if (props.style && typeof props.style.height === 'number') {
maxHeight = props.style.height;
} else {
maxHeight = window.screen.height;
}
rowCount = Math.floor(maxHeight / props.rowHeight);
}
var endIndex = startIndex + rowCount;
if (endIndex > length - 1) {
endIndex = length;
}
return endIndex;
},
onDropColumn: function onDropColumn(index, dropIndex) {
;(this.props.onColumnOrderChange || emptyFn)(index, dropIndex);
},
toggleColumn: function toggleColumn(props, column) {
var visible = column.visible;
var visibility = this.state.visibility;
if (column.name in visibility) {
visible = visibility[column.name];
}
column = findColumn(this.props.columns, column);
if (visible && getVisibleCount(props, this.state) === 1) {
return;
}
var onHide = this.props.onColumnHide || emptyFn;
var onShow = this.props.onColumnShow || emptyFn;
visible ? onHide(column) : onShow(column);
var onChange = this.props.onColumnVisibilityChange || emptyFn;
onChange(column, !visible);
if (column.visible == null && column.hidden == null) {
var visibility = this.state.visibility;
visibility[column.name] = !visible;
this.cleanCache();
this.setState({});
}
},
cleanCache: function cleanCache() {
//so grouped rows are re-rendered
delete this.groupedRows;
//clear row cache
this.rowCache = {};
},
showMenu: function showMenu(menu, state) {
state = state || {};
state.menu = menu;
if (this.state.menu) {
this.setState({
menu: null,
menuColumn: null
});
}
setTimeout((function () {
//since menu is hidden on click on window,
//show it in a timeout, after the click event has reached the window
this.setState(state);
}).bind(this), 0);
},
prepareHeader: function prepareHeader(props, state) {
var allColumns = props.columns;
var columns = getVisibleColumns(props, state);
return (props.headerFactory || HeaderFactory)({
scrollLeft: state.scrollLeft,
resizing: state.resizing,
columns: columns,
allColumns: allColumns,
columnVisibility: state.visibility,
cellPadding: props.headerPadding || props.cellPadding,
filterIconColor: props.filterIconColor,
menuIconColor: props.menuIconColor,
menuIcon: props.menuIcon,
filterIcon: props.filterIcon,
scrollbarSize: props.scrollbarSize,
sortInfo: props.sortInfo,
resizableColumns: props.resizableColumns,
reorderColumns: props.reorderColumns,
filterable: props.filterable,
withColumnMenu: props.withColumnMenu,
sortable: props.sortable,
onDropColumn: this.onDropColumn,
onSortChange: props.onSortChange,
onColumnResizeDragStart: this.onColumnResizeDragStart,
onColumnResizeDrag: this.onColumnResizeDrag,
onColumnResizeDrop: this.onColumnResizeDrop,
toggleColumn: this.toggleColumn.bind(this, props),
showMenu: this.showMenu,
filterMenuFactory: this.filterMenuFactory,
menuColumn: state.menuColumn,
columnMenuFactory: props.columnMenuFactory
});
},
prepareFooter: function prepareFooter(props, state) {
return (props.footerFactory || React.DOM.div)({
className: 'z-footer-wrapper'
});
},
prepareRenderProps: function prepareRenderProps(props) {
var result = {};
var list = {
className: true,
style: true
};
Object.keys(props).forEach(function (name) {
// if (list[name] || name.indexOf('data-') == 0 || name.indexOf('on') === 0){
if (list[name]) {
result[name] = props[name];
}
});
return result;
},
render: function render() {
var props = this.prepareProps(this.props, this.state);
this.p = props;
this.data = props.data;
this.dataSource = props.dataSource;
var header = this.prepareHeader(props, this.state);
var wrapper = this.prepareWrapper(props, this.state);
var footer = this.prepareFooter(props, this.state);
var resizeProxy = this.prepareResizeProxy(props, this.state);
var renderProps = this.prepareRenderProps(props);
var menuProps = {
columns: props.columns,
menu: this.state.menu
};
var loadMask;
if (props.loadMaskOverHeader) {
loadMask = React.createElement(LoadMask, { visible: props.loading });
}
var paginationToolbar;
if (props.pagination) {
var page = props.page;
var minPage = props.minPage;
var maxPage = props.maxPage;
var paginationToolbarFactory = props.paginationFactory || PaginationToolbar;
var paginationProps = assign({
dataSourceCount: props.dataSourceCount,
page: page,
pageSize: props.pageSize,
minPage: minPage,
maxPage: maxPage,
reload: this.reload,
onPageChange: this.gotoPage,
onPageSizeChange: this.setPageSize,
border: props.style.border
}, props.paginationToolbarProps);
paginationToolbar = paginationToolbarFactory(paginationProps);
if (paginationToolbar === undefined) {
paginationToolbar = PaginationToolbar(paginationProps);
}
}
var topToolbar;
var bottomToolbar;
if (paginationToolbar) {
if (paginationToolbar.props.position == 'top') {
topToolbar = paginationToolbar;
} else {
bottomToolbar = paginationToolbar;
}
}
var result = React.createElement(
'div',
renderProps,
topToolbar,
React.createElement(
'div',
{ className: 'z-inner' },
header,
wrapper,
footer,
resizeProxy
),
loadMask,
renderMenu(menuProps),
bottomToolbar
);
return result;
},
getTableProps: function getTableProps(props, state) {
var table;
var rows;
if (props.groupBy) {
rows = this.groupedRows = this.groupedRows || getGroupedRows(props, state.groupData);
rows = slice(rows, props);
}
table = _getTableProps.call(this, props, rows);
return table;
},
handleVerticalScrollOverflow: function handleVerticalScrollOverflow(sign, scrollTop) {
var props = this.p;
var page = props.page;
if (this.isValidPage(page + sign, props)) {
this.gotoPage(page + sign);
}
},
fixHorizontalScrollbar: function fixHorizontalScrollbar() {
var scroller = this.scroller;
if (scroller) {
scroller.fixHorizontalScrollbar();
}
},
onWrapperMount: function onWrapperMount(wrapper, scroller) {
this.scroller = scroller;
},
prepareWrapper: function prepareWrapper(props, state) {
var virtualRendering = props.virtualRendering;
var data = props.data;
var scrollTop = state.scrollTop;
var startIndex = state.startIndex;
var endIndex = virtualRendering ? this.getRenderEndIndex(props, state) : 0;
var renderCount = virtualRendering ? endIndex + 1 - startIndex : data.length;
var totalLength = state.groupData ? data.length + state.groupData.groupsCount : data.length;
if (props.virtualRendering) {
scrollTop = startIndex * props.rowHeight;
}
// var topLoader
// var bottomLoader
// var loadersSize = 0
// if (props.virtualPagination){
// if (props.page < props.maxPage){
// loadersSize += 2 * props.rowHeight
// bottomLoader = <div style={{height: 2 * props.rowHeight, position: 'relative', width: props.columnFlexCount? 'calc(100% - ' + props.scrollbarSize + ')': props.minRowWidth - props.scrollbarSize}}>
// <LoadMask visible={true} style={{background: 'rgba(128, 128, 128, 0.17)'}}/>
// </div>
// }
// if (props.page > props.minPage){
// loadersSize += 2 * props.rowHeight
// topLoader = <div style={{height: 2 * props.rowHeight, position: 'relative', width: props.columnFlexCount? 'calc(100% - ' + props.scrollbarSize + ')': props.minRowWidth - props.scrollbarSize}}>
// <LoadMask visible={true} style={{background: 'rgba(128, 128, 128, 0.17)'}}/>
// </div>
// }
// }
var wrapperProps = assign({
ref: 'wrapper',
onMount: this.onWrapperMount,
scrollLeft: state.scrollLeft,
scrollTop: scrollTop,
topOffset: state.topOffset,
startIndex: startIndex,
totalLength: totalLength,
renderCount: renderCount,
endIndex: endIndex,
allColumns: props.columns,
onScrollLeft: this.handleScrollLeft,
onScrollTop: this.handleScrollTop,
// onScrollOverflow: props.virtualPagination? this.handleVerticalScrollOverflow: null,
menu: state.menu,
menuColumn: state.menuColumn,
showMenu: this.showMenu,
// cellFactory : props.cellFactory,
// rowStyle : props.rowStyle,
// rowClassName : props.rowClassName,
// rowContextMenu : props.rowContextMenu,
// topLoader: topLoader,
// bottomLoader: bottomLoader,
// loadersSize: loadersSize,
// onRowClick: this.handleRowClick,
selected: props.selected == null ? state.defaultSelected : props.selected
}, props);
wrapperProps.columns = getVisibleColumns(props, state);
wrapperProps.tableProps = this.getTableProps(wrapperProps, state);
return (props.WrapperFactory || WrapperFactory)(wrapperProps);
},
handleRowClick: function handleRowClick(rowProps, event) {
if (this.props.onRowClick) {
this.props.onRowClick(rowProps.data, rowProps, event);
}
this.handleSelection(rowProps, event);
},
prepareProps: function prepareProps(thisProps, state) {
var props = assign({}, thisProps);
props.loading = this.prepareLoading(props);
props.data = this.prepareData(props);
props.dataSource = this.prepareDataSource(props);
props.empty = !props.data.length;
props.rowHeight = this.prepareRowHeight(props);
props.virtualRendering = this.isVirtualRendering(props);
props.filterable = this.prepareFilterable(props);
props.resizableColumns = this.prepareResizableColumns(props);
props.reorderColumns = this.prepareReorderColumns(props);
this.prepareClassName(props);
props.style = this.prepareStyle(props);
this.preparePaging(props, state);
this.prepareColumns(props, state);
props.minRowWidth = props.totalColumnWidth + props.scrollbarSize;
return props;
},
prepareLoading: function prepareLoading(props) {
var showLoadMask = props.showLoadMask || !this.isMounted(); //ismounted check for initial load
return props.loading == null ? showLoadMask && this.state.defaultLoading : props.loading;
},
preparePaging: function preparePaging(props, state) {
props.pagination = this.preparePagination(props);
if (props.pagination) {
props.pageSize = this.preparePageSize(props);
props.dataSourceCount = this.prepareDataSourceCount(props);
props.minPage = 1;
props.maxPage = Math.ceil((props.dataSourceCount || 1) / props.pageSize);
props.page = clamp(this.preparePage(props), props.minPage, props.maxPage);
}
},
preparePagination: function preparePagination(props) {
return props.pagination === false ? false : !!props.pageSize || !!props.paginationFactory || this.isRemoteDataSource(props);
},
prepareDataSourceCount: function prepareDataSourceCount(props) {
return props.dataSourceCount == null ? this.state.defaultDataSourceCount : props.dataSourceCount;
},
preparePageSize: function preparePageSize(props) {
return props.pageSize == null ? this.state.defaultPageSize : props.pageSize;
},
preparePage: function preparePage(props) {
return props.page == null ? this.state.defaultPage : props.page;
},
/**
* Returns true if in the current configuration,
* the datagrid should load its data remotely.
*
* @param {Object} [props] Optional. If not given, this.props will be used
* @return {Boolean}
*/
isRemoteDataSource: function isRemoteDataSource(props) {
props = props || this.props;
return props.dataSource && !isArray(props.dataSource);
},
prepareDataSource: function prepareDataSource(props) {
var dataSource = props.dataSource;
if (isArray(dataSource)) {
dataSource = null;
}
return dataSource;
},
prepareData: function prepareData(props) {
var data = null;
if (isArray(props.data)) {
data = props.data;
}
if (isArray(props.dataSource)) {
data = props.dataSource;
}
data = data == null ? this.state.defaultData : data;
if (!isArray(data)) {
data = [];
}
return data;
},
prepareFilterable: function prepareFilterable(props) {
if (props.filterable === false) {
return false;
}
return props.filterable || !!props.onFilter;
},
prepareResizableColumns: function prepareResizableColumns(props) {
if (props.resizableColumns === false) {
return false;
}
return props.resizableColumns || !!props.onColumnResize;
},
prepareReorderColumns: function prepareReorderColumns(props) {
if (props.reorderColumns === false) {
return false;
}
return props.reorderColumns || !!props.onColumnOrderChange;
},
isVirtualRendering: function isVirtualRendering(props) {
props = props || this.props;
return props.virtualRendering || props.rowHeight != null;
},
prepareRowHeight: function prepareRowHeight() {
return this.props.rowHeight == null ? this.state.rowHeight : this.props.rowHeight;
},
groupData: function groupData(props) {
if (props.groupBy) {
var data = this.prepareData(props);
this.setState({
groupData: group(data, props.groupBy)
});
delete this.groupedRows;
}
},
isValidPage: function isValidPage(page, props) {
return page >= 1 && page <= this.getMaxPage(props);
},
getMaxPage: function getMaxPage(props) {
props = props || this.props;
var count = this.prepareDataSourceCount(props) || 1;
var pageSize = this.preparePageSize(props);
return Math.ceil(count / pageSize);
},
reload: function reload() {
if (this.dataSource) {
return this.loadDataSource(this.dataSource, this.props);
}
},
clampPage: function clampPage(page) {
return clamp(page, 1, this.getMaxPage(this.props));
},
setPageSize: function setPageSize(pageSize) {
var stateful;
var newPage = this.preparePage(this.props);
var newState = {};
if (typeof this.props.onPageSizeChange == 'function') {
this.props.onPageSizeChange(pageSize, this.p);
}
if (this.props.pageSize == null) {
stateful = true;
this.state.defaultPageSize = pageSize;
newState.defaultPageSize = pageSize;
}
if (!this.isValidPage(newPage, this.props)) {
newPage = this.clampPage(newPage);
if (typeof this.props.onPageChange == 'function') {
this.props.onPageChange(newPage);
}
if (this.props.page == null) {
stateful = true;
this.state.defaultPage = newPage;
newState.defaultPage = newPage;
}
}
if (stateful) {
this.reload();
this.setState(newState);
}
},
gotoPage: function gotoPage(page) {
if (typeof this.props.onPageChange == 'function') {
this.props.onPageChange(page);
} else {
this.state.defaultPage = page;
var result = this.reload();
this.setState({
defaultPage: page
});
return result;
}
},
/**
* Loads remote data
*
* @param {String/Function/Promise} [dataSource]
* @param {Object} [props]
*/
loadDataSource: function loadDataSource(dataSource, props) {
props = props || this.props;
if (!arguments.length) {
dataSource = props.dataSource;
}
var dataSourceQuery = {};
if (props.sortInfo) {
dataSourceQuery.sortInfo = props.sortInfo;
}
var pagination = this.preparePagination(props);
var pageSize;
var page;
if (pagination) {
pageSize = this.preparePageSize(props);
page = this.preparePage(props);
assign(dataSourceQuery, {
pageSize: pageSize,
page: page,
skip: (page - 1) * pageSize
});
}
if (typeof dataSource == 'function') {
dataSource = dataSource(dataSourceQuery, props);
}
if (typeof dataSource == 'string') {
var fetch = this.props.fetch || global.fetch;
var keys = Object.keys(dataSourceQuery);
if (props.appendDataSourceQueryParams && keys.length) {
//dataSource was initially passed as a string
//so we append quey params
dataSource += '?' + keys.map(function (param) {
return param + '=' + JSON.stringify(dataSourceQuery[param]);
}).join('&');
}
dataSource = fetch(dataSource);
}
if (dataSource && dataSource.then) {
if (props.onDataSourceResponse) {
dataSource.then(props.onDataSourceResponse, props.onDataSourceResponse);
} else {
this.setState({
defaultLoading: true
});
var errorFn = (function (err) {
if (props.onDataSourceError) {
props.onDataSourceError(err);
}
this.setState({
defaultLoading: false
});
}).bind(this);
var noCatchFn = dataSource['catch'] ? null : errorFn;
dataSource = dataSource.then(function (response) {
return response && typeof response.json == 'function' ? response.json() : response;
}).then((function (json) {
if (props.onDataSourceSuccess) {
props.onDataSourceSuccess(json);
this.setState({
defaultLoading: false
});
return;
}
var info;
if (typeof props.getDataSourceInfo == 'function') {
info = props.getDataSourceInfo(json);
}
var data = info ? info.data : Array.isArray(json) ? json : json.data;
var count = info ? info.count : json.count != null ? json.count : null;
var newState = {
defaultData: data,
defaultLoading: false
};
if (props.groupBy) {
newState.groupData = group(data, props.groupBy);
delete this.groupedRows;
}
if (count != null) {
newState.defaultDataSourceCount = count;
}
this.setState(newState);
}).bind(this), noCatchFn);
if (dataSource['catch']) {
dataSource['catch'](errorFn);
}
}
if (props.onDataSourceLoaded) {
dataSource.then(props.onDataSourceLoaded);
}
}
return dataSource;
},
componentWillMount: function componentWillMount() {
this.rowCache = {};
this.groupData(this.props);
if (this.isRemoteDataSource(this.props)) {
this.loadDataSource(this.props.dataSource, this.props);
}
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
this.rowCache = {};
this.groupData(nextProps);
if (this.isRemoteDataSource(nextProps)) {
var otherPage = this.props.page != nextProps.page;
var otherPageSize = this.props.pageSize != nextProps.pageSize;
if (nextProps.reload || otherPage || otherPageSize) {
this.loadDataSource(nextProps.dataSource, nextProps);
}
}
},
prepareStyle: function prepareStyle(props) {
var style = {};
assign(style, props.defaultStyle, props.style);
return style;
},
prepareClassName: function prepareClassName(props) {
props.className = props.className || '';
props.className += ' ' + props.defaultClassName;
if (props.cellEllipsis) {
props.className += ' ' + props.cellEllipsisCls;
}
if (props.styleAlternateRows) {
props.className += ' ' + props.styleAlternateRowsCls;
}
if (props.showCellBorders) {
var cellBordersCls = props.showCellBorders === true ? props.showCellBordersCls + '-horizontal ' + props.showCellBordersCls + '-vertical' : props.showCellBordersCls + '-' + props.showCellBorders;
props.className += ' ' + cellBordersCls;
}
if (props.withColumnMenu) {
props.className += ' ' + props.withColumnMenuCls;
}
if (props.empty) {
props.className += ' ' + props.emptyCls;
}
},
///////////////////////////////////////
///
/// Code dealing with preparing columns
///
///////////////////////////////////////
prepareColumns: function prepareColumns(props, state) {
props.columns = props.columns.map(function (col, index) {
col = Column(col, props);
col.index = index;
return col;
}, this);
this.prepareColumnSizes(props, state);
props.columns.forEach(this.prepareColumnStyle.bind(this, props));
},
prepareColumnStyle: function prepareColumnStyle(props, column) {
var style = column.sizeStyle = {};
column.style = assign({}, column.style);
column.textAlign = column.textAlign || column.style.textAlign;
var minWidth = column.minWidth || props.columnMinWidth;
style.minWidth = minWidth;
if (column.flexible) {
style.flex = column.flex || 1;
} else {
style.width = column.width;
style.minWidth = column.width;
}
},
prepareColumnSizes: function prepareColumnSizes(props, state) {
var visibleColumns = getVisibleColumns(props, state);
var totalWidth = 0;
var flexCount = 0;
visibleColumns.forEach(function (column) {
column.minWidth = column.minWidth || props.columnMinWidth;
if (!column.flexible) {
totalWidth += column.width;
return 0;
} else if (column.minWidth) {
totalWidth += column.minWidth;
}
flexCount++;
}, this);
props.columnFlexCount = flexCount;
props.totalColumnWidth = totalWidth;
},
prepareResizeProxy: function prepareResizeProxy(props, state) {
return React.createElement(ResizeProxy, { ref: 'resizeProxy', active: state.resizing });
},
onColumnResizeDragStart: function onColumnResizeDragStart(config) {
var domNode = this.getDOMNode();
var region = Region.from(domNode);
this.resizeProxyLeft = config.resizeProxyLeft - region.left;
this.setState({
resizing: true,
resizeOffset: this.resizeProxyLeft
});
},
onColumnResizeDrag: function onColumnResizeDrag(config) {
this.refs.resizeProxy.setState({
offset: this.resizeProxyLeft + config.resizeProxyDiff
});
},
onColumnResizeDrop: function onColumnResizeDrop(config, resizeInfo) {
var horizScrollbar = this.refs.wrapper.refs.horizScrollbar;
if (horizScrollbar && this.state.scrollLeft) {
setTimeout((function () {
//FF needs this, since it does not trigger scroll event when scrollbar dissapears
//so we might end up with grid content not visible (to the left)
var domNode = React.findDOMNode(horizScrollbar);
if (domNode && !domNode.scrollLeft) {
this.handleScrollLeft(0);
}
}).bind(this), 1);
}
var props = this.props;
var columns = props.columns;
var onColumnResize = props.onColumnResize || emptyFn;
var first = resizeInfo[0];
var firstCol = findColumn(columns, first.name);
var firstSize = first.size;
var second = resizeInfo[1];
var secondCol = second ? findColumn(columns, second.name) : undefined;
var secondSize = second ? second.size : undefined;
//if defaultWidth specified, update it
if (firstCol.width == null && firstCol.defaultWidth) {
firstCol.defaultWidth = firstSize;
}
if (secondCol && secondCol.width == null && secondCol.defaultWidth) {
secondCol.defaultWidth = secondSize;
}
this.setState(config);
onColumnResize(firstCol, firstSize, secondCol, secondSize);
}
});
// this.checkRowHeight(this.props) |
//https://github.com/slimjack/ExtJs-AsyncModel
Ext.define('Ext.ux.data.validator.ValidationContext', {
alternateClassName: 'ValidationContext',
statics: {
getFieldDisplayName: function (modelRecord, validatedFieldName) {
var me = this;
return modelRecord.getMetaValue(validatedFieldName, 'displayName') || validatedFieldName;
},
create: function (modelRecord, validatedFieldName, additionalContext) {
var result = {
fieldName: (modelRecord instanceof Ext.ux.data.AsyncModel) && validatedFieldName
? this.getFieldDisplayName(modelRecord, validatedFieldName)
: validatedFieldName,
};
if (additionalContext) {
Ext.apply(result, additionalContext);
}
return result;
}
}
}); |
var express = require('express');
var router = express.Router();
var User = require('../models/user')
var Device = require('../models/device')
router.get('/', function(req, res, next){
User.find({},function(err, users){
if(err){
next(err)
}
else {
res.payload = users
res.message = 'List of users'
res.status(200)
next();
}
})
})
router.post('/', User.findUser, function(req, res, next){
User.createUser(req, function(err, newUser){
if(err){
next(err)
}
else{
newUser.save(function(err){
if(err){
next(err)
}
else {
res.status(200)
res.message = 'User Created'
res.payload = newUser
next()
}
})
}
})
})
// ---- User endpoints ----
router.get('/:username', User.findUser, function(req, res, next){
if(req.user){
res.status(200)
res.message = 'User Info'
res.payload = req.user
next()
}
else {
res.payload = null
next()
}
})
router.put('/:username', User.findUser, function(req, res, next){
if(req.user){
next()
}
else {
res.payload = null
next()
}
})
router.delete('/:username', User.findUser, function(req, res, next){
if(req.user){
req.user.remove(function(err){
if(err){
next(err);
}
else{
// Delete devices for this owner
for(var i=0; i < req.user.devices.length; i++){
req.user.devices[i].remove()
}
res.status(200)
res.message = 'User deleted'
res.payload = req.user
next();
}
})
}
else{
res.payload = null
next()
}
})
// ---- Devices endpoints ----
router.post('/:username/devices/', User.findUser, function(req, res, next){
Device.createDevice(req, function(err, newDevice){
if(err){
next(err)
}
else{
newDevice.save(function(err){
if(err){
next(err)
}
else{
// Push device to owner
req.user.update({$push: {'devices': newDevice}}, function(err){
if(err){
next(err)
}
else {
res.status(200)
res.message = 'Device Created'
res.payload = newDevice
next()
}
})
}
})
}
})
})
router.get('/:username/devices/', User.findUser, function(req, res, next){
if(req.user){
res.status(200)
res.message = 'List of devices'
res.payload = req.user.devices
next()
}
else {
res.payload = null
next()
}
})
// ---- Especific device endpoints
router.get('/:username/devices/:device', User.findUser, function(req, res, next){
if(req.user){
var device = null
for(var i = 0; i < req.user.devices.length; i ++){
if(req.user.devices[i].name == req.params.device){
device = req.user.devices[i]
}
}
res.payload = device
next()
}
else {
res.payload = null
next()
}
})
router.delete('/:username/devices/:device', User.findUser, function(req, res, next){
if(req.user){
var device = null
for(var i = 0; i < req.user.devices.length; i ++){
if(req.user.devices[i].name == req.params.device){
device = req.user.devices[i]
}
}
device.remove(function(err){
if(err){
next(err)
}
else{
res.status(200)
res.payload = device
next()
}
})
}
else {
res.payload = null
next()
}
})
module.exports = router
|
var util = require('../util');
exports.encode = function encode ( packet, value ) {
var result = new Buffer(value || '');
return result;
}
exports.decode = function decode ( packet, value ) {
return value.toString();
}
exports.TYPE = 0x0007;
exports.NAME = 'password';
|
/**
* @license
* (c) 2009-2010 Michael Leibman
* michael{dot}leibman{at}gmail{dot}com
* http://github.com/mleibman/slickgrid
* Distributed under MIT license.
* All rights reserved.
*
* SlickGrid v2.0 alpha
*
* NOTES:
* Cell/row DOM manipulations are done directly bypassing jQuery's DOM manipulation methods.
* This increases the speed dramatically, but can only be done safely because there are no event handlers
* or data associated with any cell/row DOM nodes. Cell editors must make sure they implement .destroy()
* and do proper cleanup.
*/
// make sure required JavaScript modules are loaded
if (typeof jQuery === "undefined") {
throw "SlickGrid requires jquery module to be loaded";
}
if (!jQuery.fn.drag) {
throw "SlickGrid requires jquery.event.drag module to be loaded";
}
if (typeof Slick === "undefined") {
throw "slick.core.js not loaded";
}
(function($) {
// Slick.Grid
$.extend(true, window, {
Slick: {
Grid: SlickGrid
}
});
var scrollbarDimensions; // shared across all grids on this page
//////////////////////////////////////////////////////////////////////////////////////////////
// SlickGrid class implementation (available as Slick.Grid)
/**
* @param {Node} container Container node to create the grid in.
* @param {Array,Object} data An array of objects for databinding.
* @param {Array} columns An array of column definitions.
* @param {Object} options Grid options.
**/
function SlickGrid(container,data,columns,options) {
/// <summary>
/// Create and manage virtual grid in the specified $container,
/// connecting it to the specified data source. Data is presented
/// as a grid with the specified columns and data.length rows.
/// Options alter behaviour of the grid.
/// </summary>
// settings
var defaults = {
headerHeight: 25,
rowHeight: 25,
defaultColumnWidth: 80,
enableAddRow: false,
leaveSpaceForNewRows: false,
editable: false,
autoEdit: true,
enableCellNavigation: true,
enableCellRangeSelection: false,
enableColumnReorder: true,
asyncEditorLoading: false,
asyncEditorLoadDelay: 100,
forceFitColumns: false,
enableAsyncPostRender: false,
asyncPostRenderDelay: 60,
autoHeight: false,
editorLock: Slick.GlobalEditorLock,
showHeaderRow: false,
headerRowHeight: 25,
showTopPanel: false,
topPanelHeight: 25,
formatterFactory: null,
editorFactory: null,
cellFlashingCssClass: "flashing",
selectedCellCssClass: "selected",
multiSelect: true,
enableTextSelectionOnCells: false
};
var columnDefaults = {
name: "",
resizable: true,
sortable: false,
minWidth: 30,
rerenderOnResize: false,
headerCssClass: null
};
// scroller
var maxSupportedCssHeight; // browser's breaking point
var th; // virtual height
var h; // real scrollable height
var ph; // page height
var n; // number of pages
var cj; // "jumpiness" coefficient
var page = 0; // current page
var offset = 0; // current page offset
var scrollDir = 1;
// private
var $container;
var uid = "slickgrid_" + Math.round(1000000 * Math.random());
var self = this;
var $headerScroller;
var $headers;
var $headerRow, $headerRowScroller;
var $topPanelScroller;
var $topPanel;
var $viewport;
var $canvas;
var $style;
var stylesheet;
var viewportH, viewportW;
var viewportHasHScroll;
var headerColumnWidthDiff, headerColumnHeightDiff, cellWidthDiff, cellHeightDiff; // padding+border
var absoluteColumnMinWidth;
var activePosX;
var activeRow, activeCell;
var activeCellNode = null;
var currentEditor = null;
var serializedEditorValue;
var editController;
var rowsCache = {};
var renderedRows = 0;
var numVisibleRows;
var prevScrollTop = 0;
var scrollTop = 0;
var lastRenderedScrollTop = 0;
var prevScrollLeft = 0;
var avgRowRenderTime = 10;
var selectionModel;
var selectedRows = [];
var plugins = [];
var cellCssClasses = {};
var columnsById = {};
var sortColumnId;
var sortAsc = true;
// async call handles
var h_editorLoader = null;
var h_render = null;
var h_postrender = null;
var postProcessedRows = {};
var postProcessToRow = null;
var postProcessFromRow = null;
// perf counters
var counter_rows_rendered = 0;
var counter_rows_removed = 0;
//////////////////////////////////////////////////////////////////////////////////////////////
// Initialization
function init() {
/// <summary>
/// Initialize 'this' (self) instance of a SlickGrid.
/// This function is called by the constructor.
/// </summary>
$container = $(container);
if($container.length < 1) {
throw new Error("SlickGrid requires a valid container, "+container+" does not exist in the DOM.");
}
maxSupportedCssHeight = getMaxSupportedCssHeight();
scrollbarDimensions = scrollbarDimensions || measureScrollbar(); // skip measurement if already have dimensions
options = $.extend({},defaults,options);
columnDefaults.width = options.defaultColumnWidth;
// validate loaded JavaScript modules against requested options
if (options.enableColumnReorder && !$.fn.sortable) {
throw new Error("SlickGrid's \"enableColumnReorder = true\" option requires jquery-ui.sortable module to be loaded");
}
editController = {
"commitCurrentEdit": commitCurrentEdit,
"cancelCurrentEdit": cancelCurrentEdit
};
$container
.empty()
.attr("tabIndex",0)
.attr("hideFocus",true)
.css("overflow","hidden")
.css("outline",0)
.addClass(uid)
.addClass("ui-widget");
// set up a positioning container if needed
if (!/relative|absolute|fixed/.test($container.css("position")))
$container.css("position","relative");
$headerScroller = $("<div class='slick-header ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($container);
$headers = $("<div class='slick-header-columns' style='width:10000px; left:-1000px' />").appendTo($headerScroller);
$headerRowScroller = $("<div class='slick-headerrow ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($container);
$headerRow = $("<div class='slick-headerrow-columns' style='width:10000px;' />").appendTo($headerRowScroller);
$topPanelScroller = $("<div class='slick-top-panel-scroller ui-state-default' style='overflow:hidden;position:relative;' />").appendTo($container);
$topPanel = $("<div class='slick-top-panel' style='width:10000px' />").appendTo($topPanelScroller);
if (!options.showTopPanel) {
$topPanelScroller.hide();
}
if (!options.showHeaderRow) {
$headerRowScroller.hide();
}
$viewport = $("<div class='slick-viewport' tabIndex='0' hideFocus style='width:100%;overflow-x:auto;outline:0;position:relative;overflow-y:auto;'>").appendTo($container);
$canvas = $("<div class='grid-canvas' tabIndex='0' hideFocus />").appendTo($viewport);
// header columns and cells may have different padding/border skewing width calculations (box-sizing, hello?)
// calculate the diff so we can set consistent sizes
measureCellPaddingAndBorder();
// for usability reasons, all text selection in SlickGrid is disabled
// with the exception of input and textarea elements (selection must
// be enabled there so that editors work as expected); note that
// selection in grid cells (grid body) is already unavailable in
// all browsers except IE
disableSelection($headers); // disable all text selection in header (including input and textarea)
if (!options.enableTextSelectionOnCells) {
// disable text selection in grid cells except in input and textarea elements
// (this is IE-specific, because selectstart event will only fire in IE)
$viewport.bind("selectstart.ui", function (event) {
return $(event.target).is("input,textarea");
});
}
viewportW = parseFloat($.css($container[0], "width", true));
createColumnHeaders();
setupColumnSort();
createCssRules();
resizeAndRender();
bindAncestorScrollEvents();
$viewport.bind("scroll.slickgrid", handleScroll);
$container.bind("resize.slickgrid", resizeAndRender);
$headerScroller
.bind("contextmenu.slickgrid", handleHeaderContextMenu)
.bind("click.slickgrid", handleHeaderClick);
$canvas
.bind("keydown.slickgrid", handleKeyDown)
.bind("click.slickgrid", handleClick)
.bind("dblclick.slickgrid", handleDblClick)
.bind("contextmenu.slickgrid", handleContextMenu)
.bind("draginit", handleDragInit)
.bind("dragstart", handleDragStart)
.bind("drag", handleDrag)
.bind("dragend", handleDragEnd);
$canvas.delegate(".slick-cell", "mouseenter", handleMouseEnter);
$canvas.delegate(".slick-cell", "mouseleave", handleMouseLeave);
}
function registerPlugin(plugin) {
plugins.unshift(plugin);
plugin.init(self);
}
function unregisterPlugin(plugin) {
for (var i = plugins.length; i >= 0; i--) {
if (plugins[i] === plugin) {
if (plugins[i].destroy) {
plugins[i].destroy();
}
plugins.splice(i, 1);
break;
}
}
}
function setSelectionModel(model) {
if (selectionModel) {
selectionModel.onSelectedRangesChanged.unsubscribe(handleSelectedRangesChanged);
if (selectionModel.destroy) {
selectionModel.destroy();
}
}
selectionModel = model;
if (selectionModel) {
selectionModel.init(self);
selectionModel.onSelectedRangesChanged.subscribe(handleSelectedRangesChanged);
}
}
function getSelectionModel() {
return selectionModel;
}
function getCanvasNode() {
return $canvas[0];
}
function measureScrollbar() {
/// <summary>
/// Measure width of a vertical scrollbar
/// and height of a horizontal scrollbar.
/// </summary
/// <returns>
/// { width: pixelWidth, height: pixelHeight }
/// </returns>
var $c = $("<div style='position:absolute; top:-10000px; left:-10000px; width:100px; height:100px; overflow:scroll;'></div>").appendTo("body");
var dim = { width: $c.width() - $c[0].clientWidth, height: $c.height() - $c[0].clientHeight };
$c.remove();
return dim;
}
function getRowWidth() {
var rowWidth = 0;
var i = columns.length;
while (i--) {
rowWidth += (columns[i].width || columnDefaults.width);
}
return rowWidth;
}
function setCanvasWidth(width) {
$canvas.width(width);
viewportHasHScroll = (width > viewportW - scrollbarDimensions.width);
}
function disableSelection($target) {
/// <summary>
/// Disable text selection (using mouse) in
/// the specified target.
/// </summary
if ($target && $target.jquery) {
$target
.attr('unselectable', 'on')
.css('MozUserSelect', 'none')
.bind('selectstart.ui', function() { return false; }); // from jquery:ui.core.js 1.7.2
}
}
function getMaxSupportedCssHeight() {
var increment = 1000000;
var supportedHeight = increment;
// FF reports the height back but still renders blank after ~6M px
var testUpTo = navigator.userAgent.toLowerCase().match(/firefox/) ? 6000000 : 1000000000;
var div = $("<div style='display:none' />").appendTo(document.body);
while (supportedHeight <= testUpTo) {
div.css("height", supportedHeight + increment);
if (div.height() !== supportedHeight + increment)
break;
else
supportedHeight += increment;
}
div.remove();
return supportedHeight;
}
// TODO: this is static. need to handle page mutation.
function bindAncestorScrollEvents() {
var elem = $canvas[0];
while ((elem = elem.parentNode) != document.body) {
// bind to scroll containers only
if (elem == $viewport[0] || elem.scrollWidth != elem.clientWidth || elem.scrollHeight != elem.clientHeight)
$(elem).bind("scroll.slickgrid", handleActiveCellPositionChange);
}
}
function unbindAncestorScrollEvents() {
$canvas.parents().unbind("scroll.slickgrid");
}
function updateColumnHeader(columnId, title, toolTip) {
var idx = getColumnIndex(columnId);
var $header = $headers.children().eq(idx);
if ($header) {
columns[idx].name = title;
columns[idx].toolTip = toolTip;
$header
.attr("title", toolTip || title || "")
.children().eq(0).html(title);
}
}
function getHeaderRow() {
return $headerRow[0];
}
function getHeaderRowColumn(columnId) {
var idx = getColumnIndex(columnId);
var $header = $headerRow.children().eq(idx);
return $header && $header[0];
}
function createColumnHeaders() {
var i;
function hoverBegin() {
$(this).addClass("ui-state-hover");
}
function hoverEnd() {
$(this).removeClass("ui-state-hover");
}
$headers.empty();
$headerRow.empty();
columnsById = {};
for (i = 0; i < columns.length; i++) {
var m = columns[i] = $.extend({},columnDefaults,columns[i]);
columnsById[m.id] = i;
var header = $("<div class='ui-state-default slick-header-column' id='" + uid + m.id + "' />")
.html("<span class='slick-column-name'>" + m.name + "</span>")
.width(m.width - headerColumnWidthDiff)
.attr("title", m.toolTip || m.name || "")
.data("fieldId", m.id)
.addClass(m.headerCssClass || "")
.appendTo($headers);
if (options.enableColumnReorder || m.sortable) {
header.hover(hoverBegin, hoverEnd);
}
if (m.sortable) {
header.append("<span class='slick-sort-indicator' />");
}
if (options.showHeaderRow) {
$("<div class='ui-state-default slick-headerrow-column c" + i + "'></div>").appendTo($headerRow);
}
}
setSortColumn(sortColumnId,sortAsc);
setupColumnResize();
if (options.enableColumnReorder) {
setupColumnReorder();
}
}
function setupColumnSort() {
$headers.click(function(e) {
if ($(e.target).hasClass("slick-resizable-handle")) {
return;
}
var $col = $(e.target).closest(".slick-header-column");
if (!$col.length)
return;
var column = columns[getColumnIndex($col.data("fieldId"))];
if (column.sortable) {
if (!getEditorLock().commitCurrentEdit())
return;
if (column.id === sortColumnId) {
sortAsc = !sortAsc;
}
else {
sortColumnId = column.id;
sortAsc = true;
}
setSortColumn(sortColumnId,sortAsc);
trigger(self.onSort, {sortCol:column,sortAsc:sortAsc});
}
});
}
function setupColumnReorder() {
$headers.sortable({
containment: "parent",
axis: "x",
cursor: "default",
tolerance: "intersection",
helper: "clone",
placeholder: "slick-sortable-placeholder ui-state-default slick-header-column",
forcePlaceholderSize: true,
start: function(e, ui) { $(ui.helper).addClass("slick-header-column-active"); },
beforeStop: function(e, ui) { $(ui.helper).removeClass("slick-header-column-active"); },
stop: function(e) {
if (!getEditorLock().commitCurrentEdit()) {
$(this).sortable("cancel");
return;
}
var reorderedIds = $headers.sortable("toArray");
var reorderedColumns = [];
for (var i=0; i<reorderedIds.length; i++) {
reorderedColumns.push(columns[getColumnIndex(reorderedIds[i].replace(uid,""))]);
}
setColumns(reorderedColumns);
trigger(self.onColumnsReordered, {});
e.stopPropagation();
setupColumnResize();
}
});
}
function setupColumnResize() {
var $col, j, c, pageX, columnElements, minPageX, maxPageX, firstResizable, lastResizable, originalCanvasWidth;
columnElements = $headers.children();
columnElements.find(".slick-resizable-handle").remove();
columnElements.each(function(i,e) {
if (columns[i].resizable) {
if (firstResizable === undefined) { firstResizable = i; }
lastResizable = i;
}
});
if (firstResizable === undefined) {
return;
}
columnElements.each(function(i,e) {
if (i < firstResizable || (options.forceFitColumns && i >= lastResizable)) { return; }
$col = $(e);
$("<div class='slick-resizable-handle' />")
.appendTo(e)
.bind("dragstart", function(e,dd) {
if (!getEditorLock().commitCurrentEdit()) { return false; }
pageX = e.pageX;
$(this).parent().addClass("slick-header-column-active");
var shrinkLeewayOnRight = null, stretchLeewayOnRight = null;
// lock each column's width option to current width
columnElements.each(function(i,e) { columns[i].previousWidth = $(e).outerWidth(); });
if (options.forceFitColumns) {
shrinkLeewayOnRight = 0;
stretchLeewayOnRight = 0;
// colums on right affect maxPageX/minPageX
for (j = i + 1; j < columnElements.length; j++) {
c = columns[j];
if (c.resizable) {
if (stretchLeewayOnRight !== null) {
if (c.maxWidth) {
stretchLeewayOnRight += c.maxWidth - c.previousWidth;
}
else {
stretchLeewayOnRight = null;
}
}
shrinkLeewayOnRight += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth);
}
}
}
var shrinkLeewayOnLeft = 0, stretchLeewayOnLeft = 0;
for (j = 0; j <= i; j++) {
// columns on left only affect minPageX
c = columns[j];
if (c.resizable) {
if (stretchLeewayOnLeft !== null) {
if (c.maxWidth) {
stretchLeewayOnLeft += c.maxWidth - c.previousWidth;
}
else {
stretchLeewayOnLeft = null;
}
}
shrinkLeewayOnLeft += c.previousWidth - Math.max(c.minWidth || 0, absoluteColumnMinWidth);
}
}
if (shrinkLeewayOnRight === null) { shrinkLeewayOnRight = 100000; }
if (shrinkLeewayOnLeft === null) { shrinkLeewayOnLeft = 100000; }
if (stretchLeewayOnRight === null) { stretchLeewayOnRight = 100000; }
if (stretchLeewayOnLeft === null) { stretchLeewayOnLeft = 100000; }
maxPageX = pageX + Math.min(shrinkLeewayOnRight, stretchLeewayOnLeft);
minPageX = pageX - Math.min(shrinkLeewayOnLeft, stretchLeewayOnRight);
originalCanvasWidth = $canvas.width();
})
.bind("drag", function(e,dd) {
var actualMinWidth, d = Math.min(maxPageX, Math.max(minPageX, e.pageX)) - pageX, x, ci;
if (d < 0) { // shrink column
x = d;
for (j = i; j >= 0; j--) {
c = columns[j];
if (c.resizable) {
actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth);
if (x && c.previousWidth + x < actualMinWidth) {
x += c.previousWidth - actualMinWidth;
c.width = actualMinWidth;
} else {
c.width = c.previousWidth + x;
x = 0;
}
}
}
if (options.forceFitColumns) {
x = -d;
for (j = i + 1; j < columnElements.length; j++) {
c = columns[j];
if (c.resizable) {
if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) {
x -= c.maxWidth - c.previousWidth;
c.width = c.maxWidth;
} else {
c.width = c.previousWidth + x;
x = 0;
}
}
}
} else if (options.syncColumnCellResize) {
setCanvasWidth(originalCanvasWidth + d);
}
} else { // stretch column
x = d;
for (j = i; j >= 0; j--) {
c = columns[j];
if (c.resizable) {
if (x && c.maxWidth && (c.maxWidth - c.previousWidth < x)) {
x -= c.maxWidth - c.previousWidth;
c.width = c.maxWidth;
} else {
c.width = c.previousWidth + x;
x = 0;
}
}
}
if (options.forceFitColumns) {
x = -d;
for (j = i + 1; j < columnElements.length; j++) {
c = columns[j];
if (c.resizable) {
actualMinWidth = Math.max(c.minWidth || 0, absoluteColumnMinWidth);
if (x && c.previousWidth + x < actualMinWidth) {
x += c.previousWidth - actualMinWidth;
c.width = actualMinWidth;
} else {
c.width = c.previousWidth + x;
x = 0;
}
}
}
} else if (options.syncColumnCellResize) {
setCanvasWidth(originalCanvasWidth + d);
}
}
applyColumnHeaderWidths();
if (options.syncColumnCellResize) {
applyColumnWidths();
}
})
.bind("dragend", function(e,dd) {
var newWidth;
$(this).parent().removeClass("slick-header-column-active");
for (j = 0; j < columnElements.length; j++) {
c = columns[j];
newWidth = $(columnElements[j]).outerWidth();
if (c.previousWidth !== newWidth && c.rerenderOnResize) {
invalidateAllRows();
}
}
applyColumnWidths();
resizeCanvas();
trigger(self.onColumnsResized, {});
});
});
}
function getVBoxDelta($el) {
var p = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"];
var delta = 0;
$.each(p, function(n,val) { delta += parseFloat($el.css(val)) || 0; });
return delta;
}
function measureCellPaddingAndBorder() {
var el;
var h = ["borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight"];
var v = ["borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom"];
el = $("<div class='ui-state-default slick-header-column' style='visibility:hidden'>-</div>").appendTo($headers);
headerColumnWidthDiff = headerColumnHeightDiff = 0;
$.each(h, function(n,val) { headerColumnWidthDiff += parseFloat(el.css(val)) || 0; });
$.each(v, function(n,val) { headerColumnHeightDiff += parseFloat(el.css(val)) || 0; });
el.remove();
var r = $("<div class='slick-row' />").appendTo($canvas);
el = $("<div class='slick-cell' id='' style='visibility:hidden'>-</div>").appendTo(r);
cellWidthDiff = cellHeightDiff = 0;
$.each(h, function(n,val) { cellWidthDiff += parseFloat(el.css(val)) || 0; });
$.each(v, function(n,val) { cellHeightDiff += parseFloat(el.css(val)) || 0; });
r.remove();
absoluteColumnMinWidth = Math.max(headerColumnWidthDiff,cellWidthDiff);
}
function createCssRules() {
$style = $("<style type='text/css' rel='stylesheet' />").appendTo($("head"));
var rowHeight = (options.rowHeight - cellHeightDiff);
var rules = [
"." + uid + " .slick-header-column { left: 1000px; }",
"." + uid + " .slick-top-panel { height:" + options.topPanelHeight + "px; }",
"." + uid + " .slick-headerrow-columns { height:" + options.headerRowHeight + "px; }",
"." + uid + " .slick-cell { height:" + rowHeight + "px; }",
"." + uid + " .slick-row { width:" + getRowWidth() + "px; height:" + options.rowHeight + "px; }",
"." + uid + " .lr { float:none; position:absolute; }"
];
var rowWidth = getRowWidth();
var x = 0, w;
for (var i=0; i<columns.length; i++) {
w = columns[i].width;
rules.push("." + uid + " .l" + i + " { left: " + x + "px; }");
rules.push("." + uid + " .r" + i + " { right: " + (rowWidth - x - w) + "px; }");
x += columns[i].width;
}
if ($style[0].styleSheet) { // IE
$style[0].styleSheet.cssText = rules.join(" ");
}
else {
$style[0].appendChild(document.createTextNode(rules.join(" ")));
}
var sheets = document.styleSheets;
for (var i=0; i<sheets.length; i++) {
if ((sheets[i].ownerNode || sheets[i].owningElement) == $style[0]) {
stylesheet = sheets[i];
break;
}
}
}
function findCssRule(selector) {
var rules = (stylesheet.cssRules || stylesheet.rules);
for (var i=0; i<rules.length; i++) {
if (rules[i].selectorText == selector)
return rules[i];
}
return null;
}
function removeCssRules() {
$style.remove();
}
function destroy() {
getEditorLock().cancelCurrentEdit();
trigger(self.onBeforeDestroy, {});
for (var i = 0; i < plugins.length; i++) {
unregisterPlugin(plugins[i]);
}
if (options.enableColumnReorder && $headers.sortable)
$headers.sortable("destroy");
unbindAncestorScrollEvents();
$container.unbind(".slickgrid");
removeCssRules();
$canvas.unbind("draginit dragstart dragend drag");
$container.empty().removeClass(uid);
}
//////////////////////////////////////////////////////////////////////////////////////////////
// General
function trigger(evt, args, e) {
e = e || new Slick.EventData();
args = args || {};
args.grid = self;
return evt.notify(args, e, self);
}
function getEditorLock() {
return options.editorLock;
}
function getEditController() {
return editController;
}
function getColumnIndex(id) {
return columnsById[id];
}
function autosizeColumns() {
var i, c,
widths = [],
shrinkLeeway = 0,
availWidth = (options.autoHeight ? viewportW : viewportW - scrollbarDimensions.width), // with AutoHeight, we do not need to accomodate the vertical scroll bar
total = 0,
existingTotal = 0;
for (i = 0; i < columns.length; i++) {
c = columns[i];
widths.push(c.width);
existingTotal += c.width;
shrinkLeeway += c.width - Math.max(c.minWidth || 0, absoluteColumnMinWidth);
}
total = existingTotal;
invalidateAllRows();
// shrink
while (total > availWidth) {
if (!shrinkLeeway) { return; }
var shrinkProportion = (total - availWidth) / shrinkLeeway;
for (i = 0; i < columns.length && total > availWidth; i++) {
c = columns[i];
if (!c.resizable || c.minWidth === c.width || c.width === absoluteColumnMinWidth) { continue; }
var shrinkSize = Math.floor(shrinkProportion * (c.width - Math.max(c.minWidth || 0, absoluteColumnMinWidth))) || 1;
total -= shrinkSize;
widths[i] -= shrinkSize;
}
}
// grow
var previousTotal = total;
while (total < availWidth) {
var growProportion = availWidth / total;
for (i = 0; i < columns.length && total < availWidth; i++) {
c = columns[i];
if (!c.resizable || c.maxWidth <= c.width) { continue; }
var growSize = Math.min(Math.floor(growProportion * c.width) - c.width, (c.maxWidth - c.width) || 1000000) || 1;
total += growSize;
widths[i] += growSize;
}
if (previousTotal == total) break; // if total is not changing, will result in infinite loop
previousTotal = total;
}
for (i=0; i<columns.length; i++) {
columns[i].width = widths[i];
}
applyColumnHeaderWidths();
applyColumnWidths();
resizeCanvas();
}
function applyColumnHeaderWidths() {
var h;
for (var i = 0, headers = $headers.children(), ii = headers.length; i < ii; i++) {
h = $(headers[i]);
if (h.width() !== columns[i].width - headerColumnWidthDiff) {
h.width(columns[i].width - headerColumnWidthDiff);
}
}
}
function applyColumnWidths() {
var rowWidth = getRowWidth();
var x = 0, w, rule;
for (var i = 0; i < columns.length; i++) {
w = columns[i].width;
rule = findCssRule("." + uid + " .l" + i);
rule.style.left = x + "px";
rule = findCssRule("." + uid + " .r" + i);
rule.style.right = (rowWidth - x - w) + "px";
x += columns[i].width;
}
rule = findCssRule("." + uid + " .slick-row");
rule.style.width = rowWidth + "px";
}
function setSortColumn(columnId, ascending) {
sortColumnId = columnId;
sortAsc = ascending;
var columnIndex = getColumnIndex(sortColumnId);
$headers.children().removeClass("slick-header-column-sorted");
$headers.find(".slick-sort-indicator").removeClass("slick-sort-indicator-asc slick-sort-indicator-desc");
if (columnIndex != null) {
$headers.children().eq(columnIndex)
.addClass("slick-header-column-sorted")
.find(".slick-sort-indicator")
.addClass(sortAsc ? "slick-sort-indicator-asc" : "slick-sort-indicator-desc");
}
}
function handleSelectedRangesChanged(e, ranges) {
selectedRows = [];
var hash = {};
for (var i = 0; i < ranges.length; i++) {
for (var j = ranges[i].fromRow; j <= ranges[i].toRow; j++) {
if (!hash[j]) { // prevent duplicates
selectedRows.push(j);
}
hash[j] = {};
for (var k = ranges[i].fromCell; k <= ranges[i].toCell; k++) {
if (canCellBeSelected(j, k)) {
hash[j][columns[k].id] = options.selectedCellCssClass;
}
}
}
}
setCellCssStyles(options.selectedCellCssClass, hash);
trigger(self.onSelectedRowsChanged, {rows:getSelectedRows()}, e);
}
function getColumns() {
return columns;
}
function setColumns(columnDefinitions) {
columns = columnDefinitions;
invalidateAllRows();
createColumnHeaders();
removeCssRules();
createCssRules();
resizeAndRender();
handleScroll();
}
function getOptions() {
return options;
}
function setOptions(args) {
if (!getEditorLock().commitCurrentEdit()) {
return;
}
makeActiveCellNormal();
if (options.enableAddRow !== args.enableAddRow) {
invalidateRow(getDataLength());
}
options = $.extend(options,args);
render();
}
function setData(newData,scrollToTop) {
invalidateAllRows();
data = newData;
if (scrollToTop)
scrollTo(0);
}
function getData() {
return data;
}
function getDataLength() {
if (data.getLength) {
return data.getLength();
}
else {
return data.length;
}
}
function getDataItem(i) {
if (data.getItem) {
return data.getItem(i);
}
else {
return data[i];
}
}
function getTopPanel() {
return $topPanel[0];
}
function showTopPanel() {
options.showTopPanel = true;
$topPanelScroller.slideDown("fast", resizeCanvas);
}
function hideTopPanel() {
options.showTopPanel = false;
$topPanelScroller.slideUp("fast", resizeCanvas);
}
function showHeaderRowColumns() {
options.showHeaderRow = true;
$headerRowScroller.slideDown("fast", resizeCanvas);
}
function hideHeaderRowColumns() {
options.showHeaderRow = false;
$headerRowScroller.slideUp("fast", resizeCanvas);
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Rendering / Scrolling
function scrollTo(y) {
var oldOffset = offset;
page = Math.min(n-1, Math.floor(y / ph));
offset = Math.round(page * cj);
var newScrollTop = y - offset;
if (offset != oldOffset) {
var range = getVisibleRange(newScrollTop);
cleanupRows(range.top,range.bottom);
updateRowPositions();
}
if (prevScrollTop != newScrollTop) {
scrollDir = (prevScrollTop + oldOffset < newScrollTop + offset) ? 1 : -1;
$viewport[0].scrollTop = (lastRenderedScrollTop = scrollTop = prevScrollTop = newScrollTop);
trigger(self.onViewportChanged, {});
}
}
function defaultFormatter(row, cell, value, columnDef, dataContext) {
return (value === null || value === undefined) ? "" : value;
}
function getFormatter(row, column) {
var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
// look up by id, then index
var columnOverrides = rowMetadata &&
rowMetadata.columns &&
(rowMetadata.columns[column.id] || rowMetadata.columns[getColumnIndex(column.id)]);
return (columnOverrides && columnOverrides.formatter) ||
(rowMetadata && rowMetadata.formatter) ||
column.formatter ||
(options.formatterFactory && options.formatterFactory.getFormatter(column)) ||
defaultFormatter;
}
function getEditor(row, cell) {
var column = columns[cell];
var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
var columnMetadata = rowMetadata && rowMetadata.columns;
if (columnMetadata && columnMetadata[column.id] && columnMetadata[column.id].editor !== undefined) {
return columnMetadata[column.id].editor;
}
if (columnMetadata && columnMetadata[cell] && columnMetadata[cell].editor !== undefined) {
return columnMetadata[cell].editor;
}
return column.editor || (options.editorFactory && options.editorFactory.getEditor(column));
}
function appendRowHtml(stringArray, row) {
var d = getDataItem(row);
var dataLoading = row < getDataLength() && !d;
var cellCss;
var rowCss = "slick-row " +
(dataLoading ? " loading" : "") +
(row % 2 == 1 ? ' odd' : ' even');
var metadata = data.getItemMetadata && data.getItemMetadata(row);
if (metadata && metadata.cssClasses) {
rowCss += " " + metadata.cssClasses;
}
stringArray.push("<div class='ui-widget-content " + rowCss + "' row='" + row + "' style='top:" + (options.rowHeight*row-offset) + "px'>");
var colspan;
var rowHasColumnData = metadata && metadata.columns;
for (var i=0, cols=columns.length; i<cols; i++) {
var m = columns[i];
colspan = getColspan(row, i); // TODO: don't calc unless we have to
cellCss = "slick-cell lr l" + i + " r" + Math.min(columns.length -1, i + colspan - 1) + (m.cssClass ? " " + m.cssClass : "");
if (row === activeRow && i === activeCell) {
cellCss += (" active");
}
// TODO: merge them together in the setter
for (var key in cellCssClasses) {
if (cellCssClasses[key][row] && cellCssClasses[key][row][m.id]) {
cellCss += (" " + cellCssClasses[key][row][m.id]);
}
}
stringArray.push("<div class='" + cellCss + "'>");
// if there is a corresponding row (if not, this is the Add New row or this data hasn't been loaded yet)
if (d) {
stringArray.push(getFormatter(row, m)(row, i, d[m.field], m, d));
}
stringArray.push("</div>");
if (colspan)
i += (colspan - 1);
}
stringArray.push("</div>");
}
function cleanupRows(rangeToKeep) {
for (var i in rowsCache) {
if (((i = parseInt(i, 10)) !== activeRow) && (i < rangeToKeep.top || i > rangeToKeep.bottom)) {
removeRowFromCache(i);
}
}
}
function invalidate() {
updateRowCount();
invalidateAllRows();
render();
}
function invalidateAllRows() {
if (currentEditor) {
makeActiveCellNormal();
}
for (var row in rowsCache) {
removeRowFromCache(row);
}
}
function removeRowFromCache(row) {
var node = rowsCache[row];
if (!node) { return; }
$canvas[0].removeChild(node);
delete rowsCache[row];
delete postProcessedRows[row];
renderedRows--;
counter_rows_removed++;
}
function invalidateRows(rows) {
var i, rl;
if (!rows || !rows.length) { return; }
scrollDir = 0;
for (i=0, rl=rows.length; i<rl; i++) {
if (currentEditor && activeRow === i) {
makeActiveCellNormal();
}
if (rowsCache[rows[i]]) {
removeRowFromCache(rows[i]);
}
}
}
function invalidateRow(row) {
invalidateRows([row]);
}
function updateCell(row,cell) {
var cellNode = getCellNode(row,cell);
if (!cellNode) {
return;
}
var m = columns[cell], d = getDataItem(row);
if (currentEditor && activeRow === row && activeCell === cell) {
currentEditor.loadValue(d);
}
else {
cellNode.innerHTML = d ? getFormatter(row, m)(row, cell, d[m.field], m, d) : "";
invalidatePostProcessingResults(row);
}
}
function updateRow(row) {
if (!rowsCache[row]) { return; }
$(rowsCache[row]).children().each(function(i) {
var m = columns[i];
if (row === activeRow && i === activeCell && currentEditor) {
currentEditor.loadValue(getDataItem(activeRow));
}
else if (getDataItem(row)) {
this.innerHTML = getFormatter(row, m)(row, i, getDataItem(row)[m.field], m, getDataItem(row));
}
else {
this.innerHTML = "";
}
});
invalidatePostProcessingResults(row);
}
function getViewportHeight() {
return parseFloat($.css($container[0], "height", true)) -
options.headerHeight -
getVBoxDelta($headers) -
(options.showTopPanel ? options.topPanelHeight + getVBoxDelta($topPanelScroller) : 0) -
(options.showHeaderRow ? options.headerRowHeight + getVBoxDelta($headerRowScroller) : 0);
}
function resizeCanvas() {
if (options.autoHeight) {
viewportH = options.rowHeight * (getDataLength() + (options.enableAddRow ? 1 : 0) + (options.leaveSpaceForNewRows? numVisibleRows - 1 : 0));
}
else {
viewportH = getViewportHeight();
}
numVisibleRows = Math.ceil(viewportH / options.rowHeight);
viewportW = parseFloat($.css($container[0], "width", true));
$viewport.height(viewportH);
var w = 0, i = columns.length;
while (i--) {
w += columns[i].width;
}
setCanvasWidth(w);
updateRowCount();
render();
}
function resizeAndRender() {
if (options.forceFitColumns) {
autosizeColumns();
} else {
resizeCanvas();
}
}
function updateRowCount() {
var newRowCount = getDataLength() + (options.enableAddRow?1:0) + (options.leaveSpaceForNewRows?numVisibleRows-1:0);
var oldH = h;
// remove the rows that are now outside of the data range
// this helps avoid redundant calls to .removeRow() when the size of the data decreased by thousands of rows
var l = options.enableAddRow ? getDataLength() : getDataLength() - 1;
for (var i in rowsCache) {
if (i >= l) {
removeRowFromCache(i);
}
}
th = Math.max(options.rowHeight * newRowCount, viewportH - scrollbarDimensions.height);
if (th < maxSupportedCssHeight) {
// just one page
h = ph = th;
n = 1;
cj = 0;
}
else {
// break into pages
h = maxSupportedCssHeight;
ph = h / 100;
n = Math.floor(th / ph);
cj = (th - h) / (n - 1);
}
if (h !== oldH) {
$canvas.css("height",h);
scrollTop = $viewport[0].scrollTop;
}
var oldScrollTopInRange = (scrollTop + offset <= th - viewportH);
if (th == 0 || scrollTop == 0) {
page = offset = 0;
}
else if (oldScrollTopInRange) {
// maintain virtual position
scrollTo(scrollTop+offset);
}
else {
// scroll to bottom
scrollTo(th-viewportH);
}
if (h != oldH && options.autoHeight) {
resizeCanvas();
}
}
function getVisibleRange(viewportTop) {
if (viewportTop == null)
viewportTop = scrollTop;
return {
top: Math.floor((scrollTop+offset)/options.rowHeight),
bottom: Math.ceil((scrollTop+offset+viewportH)/options.rowHeight)
};
}
function getRenderedRange(viewportTop) {
var range = getVisibleRange(viewportTop);
var buffer = Math.round(viewportH/options.rowHeight);
var minBuffer = 3;
if (scrollDir == -1) {
range.top -= buffer;
range.bottom += minBuffer;
}
else if (scrollDir == 1) {
range.top -= minBuffer;
range.bottom += buffer;
}
else {
range.top -= minBuffer;
range.bottom += minBuffer;
}
range.top = Math.max(0,range.top);
range.bottom = Math.min(options.enableAddRow ? getDataLength() : getDataLength() - 1,range.bottom);
return range;
}
function renderRows(range) {
var i, l,
parentNode = $canvas[0],
rowsBefore = renderedRows,
stringArray = [],
rows = [],
startTimestamp = new Date(),
needToReselectCell = false;
for (i = range.top; i <= range.bottom; i++) {
if (rowsCache[i]) { continue; }
renderedRows++;
rows.push(i);
appendRowHtml(stringArray,i);
if (activeCellNode && activeRow === i) {
needToReselectCell = true;
}
counter_rows_rendered++;
}
var x = document.createElement("div");
x.innerHTML = stringArray.join("");
for (i = 0, l = x.childNodes.length; i < l; i++) {
rowsCache[rows[i]] = parentNode.appendChild(x.firstChild);
}
if (needToReselectCell) {
activeCellNode = getCellNode(activeRow,activeCell);
}
if (renderedRows - rowsBefore > 5) {
avgRowRenderTime = (new Date() - startTimestamp) / (renderedRows - rowsBefore);
}
}
function startPostProcessing() {
if (!options.enableAsyncPostRender) { return; }
clearTimeout(h_postrender);
h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay);
}
function invalidatePostProcessingResults(row) {
delete postProcessedRows[row];
postProcessFromRow = Math.min(postProcessFromRow,row);
postProcessToRow = Math.max(postProcessToRow,row);
startPostProcessing();
}
function updateRowPositions() {
for (var row in rowsCache) {
rowsCache[row].style.top = (row*options.rowHeight-offset) + "px";
}
}
function render() {
var visible = getVisibleRange();
var rendered = getRenderedRange();
// remove rows no longer in the viewport
cleanupRows(rendered);
// add new rows
renderRows(rendered);
postProcessFromRow = visible.top;
postProcessToRow = Math.min(options.enableAddRow ? getDataLength() : getDataLength() - 1, visible.bottom);
startPostProcessing();
lastRenderedScrollTop = scrollTop;
h_render = null;
}
function handleScroll() {
scrollTop = $viewport[0].scrollTop;
var scrollLeft = $viewport[0].scrollLeft;
var scrollDist = Math.abs(scrollTop - prevScrollTop);
if (scrollLeft !== prevScrollLeft) {
prevScrollLeft = scrollLeft;
$headerScroller[0].scrollLeft = scrollLeft;
$topPanelScroller[0].scrollLeft = scrollLeft;
$headerRowScroller[0].scrollLeft = scrollLeft;
}
if (scrollDist) {
scrollDir = prevScrollTop < scrollTop ? 1 : -1;
prevScrollTop = scrollTop;
// switch virtual pages if needed
if (scrollDist < viewportH) {
scrollTo(scrollTop + offset);
}
else {
var oldOffset = offset;
page = Math.min(n - 1, Math.floor(scrollTop * ((th - viewportH) / (h - viewportH)) * (1 / ph)));
offset = Math.round(page * cj);
if (oldOffset != offset)
invalidateAllRows();
}
if (h_render)
clearTimeout(h_render);
if (Math.abs(lastRenderedScrollTop - scrollTop) < viewportH)
render();
else
h_render = setTimeout(render, 50);
trigger(self.onViewportChanged, {});
}
trigger(self.onScroll, {scrollLeft:scrollLeft, scrollTop:scrollTop});
}
function asyncPostProcessRows() {
while (postProcessFromRow <= postProcessToRow) {
var row = (scrollDir >= 0) ? postProcessFromRow++ : postProcessToRow--;
var rowNode = rowsCache[row];
if (!rowNode || postProcessedRows[row] || row>=getDataLength()) { continue; }
var d = getDataItem(row), cellNodes = rowNode.childNodes;
for (var i=0, j=0, l=columns.length; i<l; ++i) {
var m = columns[i];
if (m.asyncPostRender) { m.asyncPostRender(cellNodes[j], postProcessFromRow, d, m); }
++j;
}
postProcessedRows[row] = true;
h_postrender = setTimeout(asyncPostProcessRows, options.asyncPostRenderDelay);
return;
}
}
function addCellCssStyles(key,hash) {
if (cellCssClasses[key]) {
throw "addCellCssStyles: cell CSS hash with key '" + key + "' already exists.";
}
cellCssClasses[key] = hash;
var node;
for (var row in rowsCache) {
if (hash[row]) {
for (var columnId in hash[row]) {
node = getCellNode(row, getColumnIndex(columnId));
if (node) {
$(node).addClass(hash[row][columnId]);
}
}
}
}
}
function removeCellCssStyles(key) {
if (!cellCssClasses[key]) {
return;
}
var node;
for (var row in rowsCache) {
if (cellCssClasses[key][row]) {
for (var columnId in cellCssClasses[key][row]) {
node = getCellNode(row, getColumnIndex(columnId));
if (node) {
$(node).removeClass(cellCssClasses[key][row][columnId]);
}
}
}
}
delete cellCssClasses[key];
}
function setCellCssStyles(key,hash) {
removeCellCssStyles(key);
addCellCssStyles(key,hash);
}
function flashCell(row, cell, speed) {
speed = speed || 100;
if (rowsCache[row]) {
var $cell = $(getCellNode(row,cell));
function toggleCellClass(times) {
if (!times) return;
setTimeout(function() {
$cell.queue(function() {
$cell.toggleClass(options.cellFlashingCssClass).dequeue();
toggleCellClass(times-1);
});
},
speed);
}
toggleCellClass(4);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Interactivity
function handleDragInit(e,dd) {
var cell = getCellFromEvent(e);
if (!cell || !cellExists(cell.row, cell.cell)) {
return false;
}
retval = trigger(self.onDragInit, dd, e);
if (e.isImmediatePropagationStopped()) {
return retval;
}
// if nobody claims to be handling drag'n'drop by stopping immediate propagation,
// cancel out of it
return false;
}
function handleDragStart(e,dd) {
var cell = getCellFromEvent(e);
if (!cell || !cellExists(cell.row, cell.cell)) {
return false;
}
var retval = trigger(self.onDragStart, dd, e);
if (e.isImmediatePropagationStopped()) {
return retval;
}
return false;
}
function handleDrag(e,dd) {
return trigger(self.onDrag, dd, e);
}
function handleDragEnd(e,dd) {
trigger(self.onDragEnd, dd, e);
}
function handleKeyDown(e) {
trigger(self.onKeyDown, {}, e);
var handled = e.isImmediatePropagationStopped();
if (!handled) {
if (!e.shiftKey && !e.altKey && !e.ctrlKey) {
if (e.which == 27) {
if (!getEditorLock().isActive()) {
return; // no editing mode to cancel, allow bubbling and default processing (exit without cancelling the event)
}
cancelEditAndSetFocus();
}
else if (e.which == 37) {
navigateLeft();
}
else if (e.which == 39) {
navigateRight();
}
else if (e.which == 38) {
navigateUp();
}
else if (e.which == 40) {
navigateDown();
}
else if (e.which == 9) {
navigateNext();
}
else if (e.which == 13) {
if (options.editable) {
if (currentEditor) {
// adding new row
if (activeRow === getDataLength()) {
navigateDown();
}
else {
commitEditAndSetFocus();
}
} else {
if (getEditorLock().commitCurrentEdit()) {
makeActiveCellEditable();
}
}
}
}
else
return;
}
else if (e.which == 9 && e.shiftKey && !e.ctrlKey && !e.altKey) {
navigatePrev();
}
else
return;
}
// the event has been handled so don't let parent element (bubbling/propagation) or browser (default) handle it
e.stopPropagation();
e.preventDefault();
try {
e.originalEvent.keyCode = 0; // prevent default behaviour for special keys in IE browsers (F3, F5, etc.)
}
catch (error) {} // ignore exceptions - setting the original event's keycode throws access denied exception for "Ctrl" (hitting control key only, nothing else), "Shift" (maybe others)
}
function handleClick(e) {
var cell = getCellFromEvent(e);
if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) {
return;
}
trigger(self.onClick, {row:cell.row, cell:cell.cell}, e);
if (e.isImmediatePropagationStopped()) {
return;
}
if (canCellBeActive(cell.row, cell.cell)) {
if (!getEditorLock().isActive() || getEditorLock().commitCurrentEdit()) {
scrollRowIntoView(cell.row,false);
setActiveCellInternal(getCellNode(cell.row,cell.cell), (cell.row === getDataLength()) || options.autoEdit);
}
}
}
function handleContextMenu(e) {
var $cell = $(e.target).closest(".slick-cell", $canvas);
if ($cell.length === 0) { return; }
// are we editing this cell?
if (activeCellNode === $cell[0] && currentEditor !== null) { return; }
trigger(self.onContextMenu, {}, e);
}
function handleDblClick(e) {
var cell = getCellFromEvent(e);
if (!cell || (currentEditor !== null && activeRow == cell.row && activeCell == cell.cell)) {
return;
}
trigger(self.onDblClick, {row:cell.row, cell:cell.cell}, e);
if (e.isImmediatePropagationStopped()) {
return;
}
if (options.editable) {
gotoCell(cell.row, cell.cell, true);
}
}
function handleHeaderContextMenu(e) {
var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns");
var column = $header && columns[self.getColumnIndex($header.data("fieldId"))];
trigger(self.onHeaderContextMenu, {column: column}, e);
}
function handleHeaderClick(e) {
var $header = $(e.target).closest(".slick-header-column", ".slick-header-columns");
var column = $header && columns[self.getColumnIndex($header.data("fieldId"))];
trigger(self.onHeaderClick, {column: column}, e);
}
function handleMouseEnter(e) {
trigger(self.onMouseEnter, {}, e);
}
function handleMouseLeave(e) {
trigger(self.onMouseLeave, {}, e);
}
function cellExists(row,cell) {
return !(row < 0 || row >= getDataLength() || cell < 0 || cell >= columns.length);
}
function getCellFromPoint(x,y) {
var row = Math.floor((y+offset)/options.rowHeight);
var cell = 0;
var w = 0;
for (var i=0; i<columns.length && w<x; i++) {
w += columns[i].width;
cell++;
}
if (cell < 0) {
cell = 0;
}
return {row:row,cell:cell-1};
}
function getCellFromNode(node) {
// read column number from .l1 or .c1 CSS classes
var cls = /l\d+/.exec(node.className) || /c\d+/.exec(node.className);
if (!cls)
throw "getCellFromNode: cannot get cell - " + node.className;
return parseInt(cls[0].substr(1, cls[0].length-1), 10);
}
function getCellFromEvent(e) {
var $cell = $(e.target).closest(".slick-cell", $canvas);
if (!$cell.length)
return null;
return {
row: $cell.parent().attr("row") | 0,
cell: getCellFromNode($cell[0])
};
}
function getCellNodeBox(row,cell) {
if (!cellExists(row,cell))
return null;
var y1 = row * options.rowHeight - offset;
var y2 = y1 + options.rowHeight - 1;
var x1 = 0;
for (var i=0; i<cell; i++) {
x1 += columns[i].width;
}
var x2 = x1 + columns[cell].width;
return {
top: y1,
left: x1,
bottom: y2,
right: x2
};
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Cell switching
function resetActiveCell() {
setActiveCellInternal(null,false);
}
function setFocus() {
// IE tries to scroll the viewport so that the item being focused is aligned to the left border
// IE-specific .setActive() sets the focus, but doesn't scroll
if ($.browser.msie) {
$canvas[0].setActive();
}
else {
$canvas[0].focus();
}
}
function scrollActiveCellIntoView() {
if (activeCellNode) {
var left = $(activeCellNode).position().left,
right = left + $(activeCellNode).outerWidth(),
scrollLeft = $viewport.scrollLeft(),
scrollRight = scrollLeft + $viewport.width();
if (left < scrollLeft)
$viewport.scrollLeft(left);
else if (right > scrollRight)
$viewport.scrollLeft(Math.min(left, right - $viewport[0].clientWidth));
}
}
function setActiveCellInternal(newCell, editMode) {
if (activeCellNode !== null) {
makeActiveCellNormal();
$(activeCellNode).removeClass("active");
}
var activeCellChanged = (activeCellNode !== newCell);
activeCellNode = newCell;
if (activeCellNode != null) {
activeRow = parseInt($(activeCellNode).parent().attr("row"));
activeCell = activePosX = getCellFromNode(activeCellNode);
$(activeCellNode).addClass("active");
if (options.editable && editMode && isCellPotentiallyEditable(activeRow,activeCell)) {
clearTimeout(h_editorLoader);
if (options.asyncEditorLoading) {
h_editorLoader = setTimeout(function() { makeActiveCellEditable(); }, options.asyncEditorLoadDelay);
}
else {
makeActiveCellEditable();
}
}
else {
setFocus();
}
}
else {
activeRow = activeCell = null;
}
if (activeCellChanged) {
scrollActiveCellIntoView();
trigger(self.onActiveCellChanged, getActiveCell());
}
}
function clearTextSelection() {
if (document.selection && document.selection.empty) {
document.selection.empty();
}
else if (window.getSelection) {
var sel = window.getSelection();
if (sel && sel.removeAllRanges) {
sel.removeAllRanges();
}
}
}
function isCellPotentiallyEditable(row, cell) {
// is the data for this row loaded?
if (row < getDataLength() && !getDataItem(row)) {
return false;
}
// are we in the Add New row? can we create new from this cell?
if (columns[cell].cannotTriggerInsert && row >= getDataLength()) {
return false;
}
// does this cell have an editor?
if (!getEditor(row, cell)) {
return false;
}
return true;
}
function makeActiveCellNormal() {
if (!currentEditor) { return; }
trigger(self.onBeforeCellEditorDestroy, {editor:currentEditor});
currentEditor.destroy();
currentEditor = null;
if (activeCellNode) {
$(activeCellNode).removeClass("editable invalid");
if (getDataItem(activeRow)) {
var column = columns[activeCell];
activeCellNode.innerHTML = getFormatter(activeRow, column)(activeRow, activeCell, getDataItem(activeRow)[column.field], column, getDataItem(activeRow));
invalidatePostProcessingResults(activeRow);
}
}
// if there previously was text selected on a page (such as selected text in the edit cell just removed),
// IE can't set focus to anything else correctly
if ($.browser.msie) { clearTextSelection(); }
getEditorLock().deactivate(editController);
}
function makeActiveCellEditable(editor) {
if (!activeCellNode) { return; }
if (!options.editable) {
throw "Grid : makeActiveCellEditable : should never get called when options.editable is false";
}
// cancel pending async call if there is one
clearTimeout(h_editorLoader);
if (!isCellPotentiallyEditable(activeRow,activeCell)) {
return;
}
var columnDef = columns[activeCell];
var item = getDataItem(activeRow);
if (trigger(self.onBeforeEditCell, {row:activeRow, cell:activeCell, item:item, column:columnDef}) === false) {
setFocus();
return;
}
getEditorLock().activate(editController);
$(activeCellNode).addClass("editable");
// don't clear the cell if a custom editor is passed through
if (!editor) {
activeCellNode.innerHTML = "";
}
currentEditor = new (editor || getEditor(activeRow, activeCell))({
grid: self,
gridPosition: absBox($container[0]),
position: absBox(activeCellNode),
container: activeCellNode,
column: columnDef,
item: item || {},
commitChanges: commitEditAndSetFocus,
cancelChanges: cancelEditAndSetFocus
});
if (item)
currentEditor.loadValue(item);
serializedEditorValue = currentEditor.serializeValue();
if (currentEditor.position)
handleActiveCellPositionChange();
}
function commitEditAndSetFocus() {
// if the commit fails, it would do so due to a validation error
// if so, do not steal the focus from the editor
if (getEditorLock().commitCurrentEdit()) {
setFocus();
if (options.autoEdit) {
navigateDown();
}
}
}
function cancelEditAndSetFocus() {
if (getEditorLock().cancelCurrentEdit()) {
setFocus();
}
}
function absBox(elem) {
var box = {top:elem.offsetTop, left:elem.offsetLeft, bottom:0, right:0, width:$(elem).outerWidth(), height:$(elem).outerHeight(), visible:true};
box.bottom = box.top + box.height;
box.right = box.left + box.width;
// walk up the tree
var offsetParent = elem.offsetParent;
while ((elem = elem.parentNode) != document.body) {
if (box.visible && elem.scrollHeight != elem.offsetHeight && $(elem).css("overflowY") != "visible")
box.visible = box.bottom > elem.scrollTop && box.top < elem.scrollTop + elem.clientHeight;
if (box.visible && elem.scrollWidth != elem.offsetWidth && $(elem).css("overflowX") != "visible")
box.visible = box.right > elem.scrollLeft && box.left < elem.scrollLeft + elem.clientWidth;
box.left -= elem.scrollLeft;
box.top -= elem.scrollTop;
if (elem === offsetParent) {
box.left += elem.offsetLeft;
box.top += elem.offsetTop;
offsetParent = elem.offsetParent;
}
box.bottom = box.top + box.height;
box.right = box.left + box.width;
}
return box;
}
function getActiveCellPosition(){
return absBox(activeCellNode);
}
function getGridPosition(){
return absBox($container[0])
}
function handleActiveCellPositionChange() {
if (!activeCellNode) return;
var cellBox;
trigger(self.onActiveCellPositionChanged, {});
if (currentEditor) {
cellBox = cellBox || getActiveCellPosition();
if (currentEditor.show && currentEditor.hide) {
if (!cellBox.visible)
currentEditor.hide();
else
currentEditor.show();
}
if (currentEditor.position)
currentEditor.position(cellBox);
}
}
function getCellEditor() {
return currentEditor;
}
function getActiveCell() {
if (!activeCellNode)
return null;
else
return {row: activeRow, cell: activeCell};
}
function getActiveCellNode() {
return activeCellNode;
}
function scrollRowIntoView(row, doPaging) {
var rowAtTop = row * options.rowHeight;
var rowAtBottom = (row + 1) * options.rowHeight - viewportH + (viewportHasHScroll?scrollbarDimensions.height:0);
// need to page down?
if ((row + 1) * options.rowHeight > scrollTop + viewportH + offset) {
scrollTo(doPaging ? rowAtTop : rowAtBottom);
render();
}
// or page up?
else if (row * options.rowHeight < scrollTop + offset) {
scrollTo(doPaging ? rowAtBottom : rowAtTop);
render();
}
}
function getColspan(row, cell) {
var metadata = data.getItemMetadata && data.getItemMetadata(row);
if (!metadata || !metadata.columns) {
return 1;
}
var columnData = metadata.columns[columns[cell].id] || metadata.columns[cell];
var colspan = (columnData && columnData.colspan);
if (colspan === "*") {
colspan = columns.length - cell;
}
return (colspan || 1);
}
function findFirstFocusableCell(row) {
var cell = 0;
while (cell < columns.length) {
if (canCellBeActive(row, cell)) {
return cell;
}
cell += getColspan(row, cell);
}
return null;
}
function findLastFocusableCell(row) {
var cell = 0;
var lastFocusableCell = null;
while (cell < columns.length) {
if (canCellBeActive(row, cell)) {
lastFocusableCell = cell;
}
cell += getColspan(row, cell);
}
return lastFocusableCell;
}
function gotoRight(row, cell, posX) {
if (cell >= columns.length) {
return null;
}
do {
cell += getColspan(row, cell);
}
while (cell < columns.length && !canCellBeActive(row, cell));
if (cell < columns.length) {
return {
"row": row,
"cell": cell,
"posX": cell
};
}
return null;
}
function gotoLeft(row, cell, posX) {
if (cell <= 0) {
return null;
}
var firstFocusableCell = findFirstFocusableCell(row);
if (firstFocusableCell === null || firstFocusableCell >= cell) {
return null;
}
var prev = {
"row": row,
"cell": firstFocusableCell,
"posX": firstFocusableCell
};
var pos;
while (true) {
pos = gotoRight(prev.row, prev.cell, prev.posX);
if (!pos) {
return null;
}
if (pos.cell >= cell) {
return prev;
}
prev = pos;
}
}
function gotoDown(row, cell, posX) {
var prevCell;
while (true) {
if (++row >= getDataLength() + (options.enableAddRow ? 1 : 0)) {
return null;
}
prevCell = cell = 0;
while (cell <= posX) {
prevCell = cell;
cell += getColspan(row, cell);
}
if (canCellBeActive(row, prevCell)) {
return {
"row": row,
"cell": prevCell,
"posX": posX
};
}
}
}
function gotoUp(row, cell, posX) {
var prevCell;
while (true) {
if (--row < 0) {
return null;
}
prevCell = cell = 0;
while (cell <= posX) {
prevCell = cell;
cell += getColspan(row, cell);
}
if (canCellBeActive(row, prevCell)) {
return {
"row": row,
"cell": prevCell,
"posX": posX
};
}
}
}
function gotoNext(row, cell, posX) {
var pos = gotoRight(row, cell, posX);
if (pos) {
return pos;
}
var firstFocusableCell = null;
while (++row < getDataLength() + (options.enableAddRow ? 1 : 0)) {
firstFocusableCell = findFirstFocusableCell(row);
if (firstFocusableCell !== null) {
return {
"row": row,
"cell": firstFocusableCell,
"posX": firstFocusableCell
};
}
}
return null;
}
function gotoPrev(row, cell, posX) {
var pos;
var lastSelectableCell;
while (!pos) {
pos = gotoLeft(row, cell, posX);
if (pos) {
break;
}
if (--row < 0) {
return null;
}
cell = 0;
lastSelectableCell = findLastFocusableCell(row);
if (lastSelectableCell !== null) {
pos = {
"row": row,
"cell": lastSelectableCell,
"posX": lastSelectableCell
};
}
}
return pos;
}
function navigateRight() {
navigate("right");
}
function navigateLeft() {
navigate("left");
}
function navigateDown() {
navigate("down");
}
function navigateUp() {
navigate("up");
}
function navigateNext() {
navigate("next");
}
function navigatePrev() {
navigate("prev");
}
function navigate(dir) {
if (!activeCellNode || !options.enableCellNavigation) { return; }
if (!getEditorLock().commitCurrentEdit()) { return; }
var stepFunctions = {
"up": gotoUp,
"down": gotoDown,
"left": gotoLeft,
"right": gotoRight,
"prev": gotoPrev,
"next": gotoNext
};
var stepFn = stepFunctions[dir];
var pos = stepFn(activeRow, activeCell, activePosX);
if (pos) {
var isAddNewRow = (pos.row == getDataLength());
scrollRowIntoView(pos.row, !isAddNewRow);
setActiveCellInternal(getCellNode(pos.row, pos.cell), isAddNewRow || options.autoEdit);
activePosX = pos.posX;
}
}
function getCellNode(row, cell) {
if (rowsCache[row]) {
var cells = $(rowsCache[row]).children();
var nodeCell;
for (var i = 0; i < cells.length; i++) {
nodeCell = getCellFromNode(cells[i]);
if (nodeCell === cell) {
return cells[i];
}
else if (nodeCell > cell) {
return null;
}
}
}
return null;
}
function setActiveCell(row, cell) {
if (row > getDataLength() || row < 0 || cell >= columns.length || cell < 0) {
return;
}
if (!options.enableCellNavigation) {
return;
}
scrollRowIntoView(row,false);
setActiveCellInternal(getCellNode(row,cell),false);
}
function canCellBeActive(row, cell) {
if (!options.enableCellNavigation || row >= getDataLength() + (options.enableAddRow ? 1 : 0) || row < 0 || cell >= columns.length || cell < 0) {
return false;
}
var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
if (rowMetadata && typeof rowMetadata.focusable === "boolean") {
return rowMetadata.focusable;
}
var columnMetadata = rowMetadata && rowMetadata.columns;
if (columnMetadata && columnMetadata[columns[cell].id] && typeof columnMetadata[columns[cell].id].focusable === "boolean") {
return columnMetadata[columns[cell].id].focusable;
}
if (columnMetadata && columnMetadata[cell] && typeof columnMetadata[cell].focusable === "boolean") {
return columnMetadata[cell].focusable;
}
if (typeof columns[cell].focusable === "boolean") {
return columns[cell].focusable;
}
return true;
}
function canCellBeSelected(row, cell) {
if (row >= getDataLength() || row < 0 || cell >= columns.length || cell < 0) {
return false;
}
var rowMetadata = data.getItemMetadata && data.getItemMetadata(row);
if (rowMetadata && typeof rowMetadata.selectable === "boolean") {
return rowMetadata.selectable;
}
var columnMetadata = rowMetadata && rowMetadata.columns && (rowMetadata.columns[columns[cell].id] || rowMetadata.columns[cell]);
if (columnMetadata && typeof columnMetadata.selectable === "boolean") {
return columnMetadata.selectable;
}
if (typeof columns[cell].selectable === "boolean") {
return columns[cell].selectable;
}
return true;
}
function gotoCell(row, cell, forceEdit) {
if (!canCellBeActive(row, cell)) {
return;
}
if (!getEditorLock().commitCurrentEdit()) { return; }
scrollRowIntoView(row,false);
var newCell = getCellNode(row, cell);
// if selecting the 'add new' row, start editing right away
setActiveCellInternal(newCell, forceEdit || (row === getDataLength()) || options.autoEdit);
// if no editor was created, set the focus back on the grid
if (!currentEditor) {
setFocus();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
// IEditor implementation for the editor lock
function commitCurrentEdit() {
var item = getDataItem(activeRow);
var column = columns[activeCell];
if (currentEditor) {
if (currentEditor.isValueChanged()) {
var validationResults = currentEditor.validate();
if (validationResults.valid) {
if (activeRow < getDataLength()) {
var editCommand = {
row: activeRow,
cell: activeCell,
editor: currentEditor,
serializedValue: currentEditor.serializeValue(),
prevSerializedValue: serializedEditorValue,
execute: function() {
this.editor.applyValue(item,this.serializedValue);
updateRow(this.row);
},
undo: function() {
this.editor.applyValue(item,this.prevSerializedValue);
updateRow(this.row);
}
};
if (options.editCommandHandler) {
makeActiveCellNormal();
options.editCommandHandler(item,column,editCommand);
}
else {
editCommand.execute();
makeActiveCellNormal();
}
trigger(self.onCellChange, {
row: activeRow,
cell: activeCell,
item: item
});
}
else {
var newItem = {};
currentEditor.applyValue(newItem,currentEditor.serializeValue());
makeActiveCellNormal();
trigger(self.onAddNewRow, {item:newItem, column:column});
}
// check whether the lock has been re-acquired by event handlers
return !getEditorLock().isActive();
}
else {
// TODO: remove and put in onValidationError handlers in examples
$(activeCellNode).addClass("invalid");
$(activeCellNode).stop(true,true).effect("highlight", {color:"red"}, 300);
trigger(self.onValidationError, {
editor: currentEditor,
cellNode: activeCellNode,
validationResults: validationResults,
row: activeRow,
cell: activeCell,
column: column
});
currentEditor.focus();
return false;
}
}
makeActiveCellNormal();
}
return true;
}
function cancelCurrentEdit() {
makeActiveCellNormal();
return true;
}
function rowsToRanges(rows) {
var ranges = [];
var lastCell = columns.length - 1;
for (var i = 0; i < rows.length; i++) {
ranges.push(new Slick.Range(rows[i], 0, rows[i], lastCell));
}
return ranges;
}
function getSelectedRows() {
if (!selectionModel) {
throw "Selection model is not set";
}
return selectedRows;
}
function setSelectedRows(rows) {
if (!selectionModel) {
throw "Selection model is not set";
}
selectionModel.setSelectedRanges(rowsToRanges(rows));
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Debug
this.debug = function() {
var s = "";
s += ("\n" + "counter_rows_rendered: " + counter_rows_rendered);
s += ("\n" + "counter_rows_removed: " + counter_rows_removed);
s += ("\n" + "renderedRows: " + renderedRows);
s += ("\n" + "numVisibleRows: " + numVisibleRows);
s += ("\n" + "maxSupportedCssHeight: " + maxSupportedCssHeight);
s += ("\n" + "n(umber of pages): " + n);
s += ("\n" + "(current) page: " + page);
s += ("\n" + "page height (ph): " + ph);
s += ("\n" + "scrollDir: " + scrollDir);
alert(s);
};
// a debug helper to be able to access private members
this.eval = function(expr) {
return eval(expr);
};
//////////////////////////////////////////////////////////////////////////////////////////////
// Public API
$.extend(this, {
"slickGridVersion": "2.0a1",
// Events
"onScroll": new Slick.Event(),
"onSort": new Slick.Event(),
"onHeaderContextMenu": new Slick.Event(),
"onHeaderClick": new Slick.Event(),
"onMouseEnter": new Slick.Event(),
"onMouseLeave": new Slick.Event(),
"onClick": new Slick.Event(),
"onDblClick": new Slick.Event(),
"onContextMenu": new Slick.Event(),
"onKeyDown": new Slick.Event(),
"onAddNewRow": new Slick.Event(),
"onValidationError": new Slick.Event(),
"onViewportChanged": new Slick.Event(),
"onColumnsReordered": new Slick.Event(),
"onColumnsResized": new Slick.Event(),
"onCellChange": new Slick.Event(),
"onBeforeEditCell": new Slick.Event(),
"onBeforeCellEditorDestroy": new Slick.Event(),
"onBeforeDestroy": new Slick.Event(),
"onActiveCellChanged": new Slick.Event(),
"onActiveCellPositionChanged": new Slick.Event(),
"onDragInit": new Slick.Event(),
"onDragStart": new Slick.Event(),
"onDrag": new Slick.Event(),
"onDragEnd": new Slick.Event(),
"onSelectedRowsChanged": new Slick.Event(),
// Methods
"registerPlugin": registerPlugin,
"unregisterPlugin": unregisterPlugin,
"getColumns": getColumns,
"setColumns": setColumns,
"getColumnIndex": getColumnIndex,
"updateColumnHeader": updateColumnHeader,
"setSortColumn": setSortColumn,
"autosizeColumns": autosizeColumns,
"getOptions": getOptions,
"setOptions": setOptions,
"getData": getData,
"getDataLength": getDataLength,
"getDataItem": getDataItem,
"setData": setData,
"getSelectionModel": getSelectionModel,
"setSelectionModel": setSelectionModel,
"getSelectedRows": getSelectedRows,
"setSelectedRows": setSelectedRows,
"render": render,
"invalidate": invalidate,
"invalidateRow": invalidateRow,
"invalidateRows": invalidateRows,
"invalidateAllRows": invalidateAllRows,
"updateCell": updateCell,
"updateRow": updateRow,
"getViewport": getVisibleRange,
"resizeCanvas": resizeCanvas,
"updateRowCount": updateRowCount,
"scrollRowIntoView": scrollRowIntoView,
"getCanvasNode": getCanvasNode,
"getCellFromPoint": getCellFromPoint,
"getCellFromEvent": getCellFromEvent,
"getActiveCell": getActiveCell,
"setActiveCell": setActiveCell,
"getActiveCellNode": getActiveCellNode,
"getActiveCellPosition": getActiveCellPosition,
"resetActiveCell": resetActiveCell,
"editActiveCell": makeActiveCellEditable,
"getCellEditor": getCellEditor,
"getCellNode": getCellNode,
"getCellNodeBox": getCellNodeBox,
"canCellBeSelected": canCellBeSelected,
"canCellBeActive": canCellBeActive,
"navigatePrev": navigatePrev,
"navigateNext": navigateNext,
"navigateUp": navigateUp,
"navigateDown": navigateDown,
"navigateLeft": navigateLeft,
"navigateRight": navigateRight,
"gotoCell": gotoCell,
"getTopPanel": getTopPanel,
"showTopPanel": showTopPanel,
"hideTopPanel": hideTopPanel,
"showHeaderRowColumns": showHeaderRowColumns,
"hideHeaderRowColumns": hideHeaderRowColumns,
"getHeaderRow": getHeaderRow,
"getHeaderRowColumn": getHeaderRowColumn,
"getGridPosition": getGridPosition,
"flashCell": flashCell,
"addCellCssStyles": addCellCssStyles,
"setCellCssStyles": setCellCssStyles,
"removeCellCssStyles": removeCellCssStyles,
"destroy": destroy,
// IEditor implementation
"getEditorLock": getEditorLock,
"getEditController": getEditController
});
init();
}
}(jQuery));
|
/*!
* jquery.fx.tweener-transitions.js
* extends jquery with transition tweens
*/
(function($, window) {
// shim layer with setTimeout fallback
var requestAnimationFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
function camelize(string) {
return string.replace(/(\-[a-z])/g, function($1){return $1.toUpperCase().replace('-','');});
}
function hyphenate(string) {
return string.replace(/([A-Z])/g, function($1){return "-"+$1.toLowerCase();});
}
// retrieves a the vendor prefixed style name for the given property
var getVendorStyle = (function() {
var cache = {};
var vendorPrefixes = ['Webkit', 'Moz', 'O', 'Ms'], elem = document.createElement('div');
return function (styleName, hyphenated) {
var camelized = camelize(styleName);
hyphenated = typeof hyphenated == 'boolean' ? hyphenated : false;
var result = cache[camelized] = typeof cache[camelized] != 'undefined' ? cache[camelized] : (function(camelized) {
var result = null;
document.documentElement.appendChild(elem);
if (typeof (elem.style[camelized]) == 'string') result = camelized;
if (!result) {
var capitalized = camelized.substring(0, 1).toUpperCase() + camelized.substring(1);
for (var i = 0; i < vendorPrefixes.length; i++) {
var prop = vendorPrefixes[i] + capitalized;
if (typeof elem.style[prop] == 'string') {
result = prop;
break;
}
}
}
elem.parentNode.removeChild(elem);
return result;
})(camelized);
if (result && hyphenated) {
result = hyphenate(result);
}
return result;
};
})();
var isPixelStyle = (function () {
var cache = {}, doc = document, elem = doc.createElement('div');
return function(prop) {
prop = getVendorStyle(camelize(prop));
return cache[prop] = typeof cache[prop] != 'undefined' ? cache[prop] : (function(prop) {
doc.body.appendChild(elem);
elem.style[prop] = "1px";
var result = elem.style[prop].match(/^[\d\.]*px$/) != null;
doc.body.removeChild(elem);
return result;
})(prop);
};
})();
var isTransitionSupported = function(property, from, to, element) {
var doc = document.documentElement,
camelized = getVendorStyle(property),
hyphenated = hyphenate(camelized),
style = doc.appendChild(document.createElement("style")),
rule = [
'capTest{',
'0%{', hyphenated, ':', from, '}',
'100%{', hyphenated, ':', to, '}',
'}'
].join(''),
prefixes = ' moz ms o webkit'.split(' '),
prefixCount = prefixes.length,
canAnimate = false;
element = doc.appendChild(element ? element.cloneNode(false) : document.createElement('div'));
// Detect invalid start value. (Webkit tries to use default.)
element.style[camelized] = to;
// Iterate through supported prefixes.
for (var i = 0; i < prefixCount; i++) {
// Variations on current prefix.
var prefix = prefixes[i],
hPrefix = (prefix) ? '-' + prefix + '-' : '',
uPrefix = (prefix) ? prefix.toUpperCase() + '_' : '';
// Test for support.
if (CSSRule[uPrefix + 'KEYFRAMES_RULE']) {
// Rule supported; add keyframe rule to test stylesheet.
var ruleString = '@'+ hPrefix + 'keyframes ' + rule;
try {
style.sheet.insertRule(ruleString, 0);
// Apply animation.
var animationProp = camelize(hPrefix + 'animation');
element.style[animationProp] = 'capTest 1s 0s both';
// Get initial computed style.
var before = getComputedStyle(element)[camelized];
// Skip to last frame of animation.
// BUG: Firefox doesn't support reverse or update node style while attached.
doc.removeChild(element);
element.style[animationProp] = 'capTest 1s -1s alternate both';
doc.appendChild(element);
// BUG: Webkit doesn't update style when animation skipped ahead.
element.style[animationProp] = 'capTest 1s 0 reverse both';
// Get final computed style.
var after = getComputedStyle(element)[camelized];
// If before and after are different, property and values are animable.
canAnimate = before !== after;
//canAnimate = true;
break;
} catch (e) {
}
}
}
// Clean up the test elements.
doc.removeChild(element);
doc.removeChild(style);
return canAnimate;
};
function splitCSS(string) {
var match, split = [], current = "", literal;
while( match = string.match(/\s*(,|\(|\))\s*/)) {
current+= string.substring(0, match.index);
var token = match[0];
if (token == '(') {
literal = true;
} else if (token == ')') {
current+= token;
literal = null;
}
if (literal) {
current+= token;
} else if (current) {
split.push(current);
current = "";
}
string = string.substring(match.index + match[0].length);
}
return split;
}
var getStyle = function( el, prop ) {
var inline = el.style[prop];
if (typeof inline != '') {
return inline;
};
return getComputedStyle(el, prop);
};
var transitionStyle = getVendorStyle('transition');
var transitionEvents = ("transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd").split(/\s+/);
var transitionEasings = {
//'swing': 'cubic-bezier(.02, .01, .47, 1)'
'swing': 'ease-in-out'
};
function getTransitionStyles(elem, add, remove) {
add = add instanceof Array ? add : [];
remove = remove instanceof Array ? remove : [];
remove = remove.concat($.map(add, function(obj) {
return obj.name;
}));
var $elem = $(elem);
var properties = $elem.css(transitionStyle + "Property").split(/[\s,]+/);
var durations = $elem.css(transitionStyle + "Duration").split(/[\s,]+/);
var delays = $elem.css(transitionStyle + "Delay").split(/[\s,]+/);
var timingFunctions = splitCSS($elem.css(transitionStyle + "TimingFunction"));
var transitions = $.map(properties, function(prop, index) {
return {
name: prop,
duration: durations[index],
delay: delays[index],
timingFunction: timingFunctions[index]
};
});
// remove props
transitions = $.map(transitions, function(obj, index) {
if (obj.name == 'none' || obj.name == 'all' || $.inArray(obj.name, remove ) >= 0 ) {
return null;
}
return obj;
});
// add props
$.each(add, function(index, obj) {
transitions.push(obj);
});
var css = {};
css[transitionStyle + "Property"] = $.map(transitions, function(obj) { return obj.name; }).join(", ");
css[transitionStyle + "Duration"] = $.map(transitions, function(obj) { return obj.duration; }).join(", ");
css[transitionStyle + "Delay"] = $.map(transitions, function(obj) { return obj.delay; }).join(", ");
css[transitionStyle + "TimingFunction"] = $.map(transitions, function(obj) { return obj.timingFunction; }).join(", ");
return css;
}
var createTween = (function() {
// constants:
var
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" );
return function ( prop, value ) {
var pixelStyle = !jQuery.cssNumber[ prop ] && isPixelStyle(prop);
var tween = this.createTween( prop, value );
tween.unit = !pixelStyle ? "" : "px";
target = tween.cur(),
parts = rfxnum.exec( value ),
unit = parts && parts[ 3 ] || ( !pixelStyle ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( !pixelStyle || unit !== "px" && +target ) &&
rfxnum.exec( jQuery.css( tween.elem, prop ) ),
scale = 1,
maxIterations = 20;
if ( start && start[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || start[ 3 ];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
// Update tween properties
if ( parts ) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
};
})();
function getDuration(tweens) {
var duration = 0;
$.each(tweens, function(index, tween) {
duration = Math.max(duration, tween.delay + tween.duration);
});
return duration;
}
var tweenRunner = function( anim, percent ) {
var elem = anim.elem, $elem = $(elem);
var tween = this;
var s = this.delay / anim.duration;
var e = (this.delay + this.duration) / anim.duration;
var p = Math.min(Math.max(0, percent - s) / (e - s), 1);
if (p == 0) {
//console.log("run tween: ", tween.prop, tween.end + tween.unit);
}
if (p >= 0) {
var eased,
hooks = jQuery.Tween.propHooks[ this.prop ];
if ( this.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
p, this.duration * p, 0, 1, this.duration
);
} else {
this.pos = eased = p;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
jQuery.Tween.propHooks._default.set( this );
}
}
if (this.pos == 1 && !this.finished) {
this.finished = true;
tweenFinished.call(anim, this);
}
return this;
};
var transitionRunner = function( anim, percent ) {
var tween = this;
var elem = anim.elem, $elem = $(elem);
function transitionEndHandler(event) {
var vendorProp = event.originalEvent.propertyName;
var tween = $.map(anim.tweens, function(tween, index) {
return getVendorStyle(tween.prop, true) == vendorProp ? tween : null;
})[0];
if (tween && !tween.finished) {
stopTween( true );
tween.finished = true;
tweenFinished.call(anim, tween);
if (anim.finished) {
$elem.off("transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd", arguments.callee);
}
}
}
function stopTween( gotoEnd ) {
var css = getTransitionStyles(elem, null, [getVendorStyle(tween.prop, true)]);
css[getVendorStyle(tween.prop)] = gotoEnd ? tween.end + tween.unit : tween.cur() + tween.unit;
$elem.css(css);
}
$elem.promise().done(function() {
if (!tween.finished) {
stopTween();
}
});
if (percent == 1) {
stopTween( true );
}
if (percent == 0) {
$elem.css(getVendorStyle(tween.prop), tween.start + tween.unit);
var add = [
{
name: getVendorStyle(tween.prop, true),
duration: Number(tween.duration / 1000).toFixed(2) + "s",
delay: Number(tween.delay / 1000).toFixed(2) + "s",
timingFunction: 'linear'
}
];
$elem.on("transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd", transitionEndHandler);
function step() {
if ( tween.options.step ) {
// read only when needed for step callback
tween.now = tween.cur();
tween.options.step.call( anim.elem, tween.now, tween );
}
if (!anim.finished) {
window.requestAnimationFrame(step);
}
}
$elem.css(getTransitionStyles(elem, add));
window.requestAnimationFrame(function() {
if (tween.finished) return;
$elem.css(getVendorStyle(tween.prop), tween.end + tween.unit);
console.log("run transition: ", tween.prop, tween.start + tween.unit + " -> " + tween.end + tween.unit, "duration: ", tween.duration, "delay: ", tween.delay, elem);
step();
});
}
return this;
};
function tweenFinished(tween) {
var anim = this;
if (!anim.finished && $.map(anim.tweens, function(tween, index) { return !tween.finished ? tween : null; }).length == 0) {
anim.finished = true;
anim.stop( true );
}
return false;
}
jQuery.Animation.tweener(function( prop, value ) {
var anim = this;
var tween = createTween.apply(anim, arguments);
var elem = anim.elem, $elem = $(elem);
var duration = typeof anim.opts.specialDuration == 'object' && typeof anim.opts.specialDuration[prop] != 'undefined' ? anim.opts.specialDuration[prop] : anim.opts.duration;
var delay = typeof anim.opts.specialDelay == 'object' && typeof anim.opts.specialDelay[prop] != 'undefined' ? anim.opts.specialDelay[prop] : anim.opts.delay;
var easing = typeof anim.opts.specialEasing == 'object' && typeof anim.opts.specialEasing[prop] != 'undefined' ? anim.opts.specialEasing[prop] : anim.opts.easing;
duration = typeof duration == 'number' ? duration : 0;
delay = typeof delay == 'number' ? delay : 0;
easing = easing || 'swing';
tween.delay = delay;
tween.duration = duration;
var isTransition = false;
tween.run = function( percent ) {
if (percent == 0) {
isTransition = ( typeof anim.opts.cssTransitions != 'boolean' || anim.opts.cssTransitions != false ) && isTransitionSupported(getVendorStyle(prop), tween.start + tween.unit, tween.end + tween.unit);
}
if (isTransition) {
transitionRunner.call(this, anim, percent);
} else {
tweenRunner.call(this, anim, percent);
}
return tween;
};
var duration = getDuration(anim.tweens);
anim.duration = duration + 100000;
return tween;
});
})(jQuery, window); |
import React from "react";
import { shallow } from "enzyme";
import App from "../App";
test("App renders correctly.", () =>
{
const wrapper = shallow(<App />);
expect(wrapper).toMatchSnapshot();
});
test("App renders correctly when className is set.", () =>
{
const wrapper = shallow(<App className="home" />);
expect(wrapper).toMatchSnapshot();
});
test("App changes the text of button after click.", () =>
{
const wrapper = shallow(<App />);
expect(wrapper.find("button").text()).toEqual("Click: 0");
wrapper.find("button").simulate("click");
expect(wrapper.state("clicked")).toEqual(1);
expect(wrapper.find("button").text()).toEqual("Click: 1");
});
|
/* global require, process, __dirname, console */
var express = require('express'),
http = require('http'),
path = require('path'),
sio = require('socket.io'),
app = express(),
server,
io;
// all environments
app.set('port', process.env.PORT || 3000);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
/**
* Socket.IO
*/
io = sio.listen(server);
io.sockets.on('connection', function (socket) {
"use strict";
socket.on('join', function (name) {
console.log(name + ' joined the chat');
socket.nickname = name;
socket.rooms = [];
if(name) {
socket.broadcast.emit('announcement', name + ' joined the chat.');
}
});
socket.on('joinRoom', function (name) {
console.log(socket.nickname + ' joined the room ' + name);
socket.rooms.push(name);
socket.join(name);
socket.broadcast.to(name).emit('roomAnnouncement', socket.nickname + ' joined the room.', name);
});
socket.on('text', function (msg, room) {
if(room && room !== 'main') {
console.log(socket.nickname + ' send the message "' + msg + '" to the room "' + room + '"');
socket.broadcast.to(room).emit('text', socket.nickname, msg, room);
} else {
console.log(socket.nickname + ' send the message "' + msg + '" to all');
socket.broadcast.emit('text', socket.nickname, msg);
}
});
socket.on('disconnect', function () {
if(socket.nickname) {
console.log(socket.nickname + ' left the chat');
socket.broadcast.emit('left', socket.nickname + ' has left the chat');
}
});
}); |
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
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; }
/*
* Copyright (C) 2015 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
WebInspector.MultipleScopeBarItem = (function (_WebInspector$Object) {
_inherits(MultipleScopeBarItem, _WebInspector$Object);
function MultipleScopeBarItem(scopeBarItems) {
_classCallCheck(this, MultipleScopeBarItem);
_get(Object.getPrototypeOf(MultipleScopeBarItem.prototype), "constructor", this).call(this);
this._element = document.createElement("li");
this._element.classList.add("multiple");
this._titleElement = document.createElement("span");
this._element.appendChild(this._titleElement);
this._element.addEventListener("click", this._clicked.bind(this));
this._selectElement = document.createElement("select");
this._selectElement.addEventListener("change", this._selectElementSelectionChanged.bind(this));
this._element.appendChild(this._selectElement);
wrappedSVGDocument("Images/UpDownArrows.svg", "arrows", null, (function (element) {
this._element.appendChild(element);
}).bind(this));
this.scopeBarItems = scopeBarItems;
}
// Public
_createClass(MultipleScopeBarItem, [{
key: "_clicked",
// Private
value: function _clicked(event) {
// Only support click to select when the item is not selected yet.
// Clicking when selected will cause the menu it appear instead.
if (this._element.classList.contains("selected")) return;
this.selected = true;
}
}, {
key: "_selectElementSelectionChanged",
value: function _selectElementSelectionChanged(event) {
this.selectedScopeBarItem = this._scopeBarItems[this._selectElement.selectedIndex];
}
}, {
key: "_itemSelectionDidChange",
value: function _itemSelectionDidChange(event) {
if (this._ignoreItemSelectedEvent) return;
this.selectedScopeBarItem = event.target.selected ? event.target : null;
}
}, {
key: "element",
get: function get() {
return this._element;
}
}, {
key: "exclusive",
get: function get() {
return false;
}
}, {
key: "scopeBarItems",
get: function get() {
return this._scopeBarItems;
},
set: function set(scopeBarItems) {
if (this._scopeBarItems) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this._scopeBarItems[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var scopeBarItem = _step.value;
scopeBarItem.removeEventListener(null, null, this);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator["return"]) {
_iterator["return"]();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
this._scopeBarItems = scopeBarItems || [];
this._selectedScopeBarItem = null;
this._selectElement.removeChildren();
function createOption(scopeBarItem) {
var optionElement = document.createElement("option");
var maxPopupMenuLength = 130; // <rdar://problem/13445374> <select> with very long option has clipped text and popup menu is still very wide
optionElement.textContent = scopeBarItem.label.length <= maxPopupMenuLength ? scopeBarItem.label : scopeBarItem.label.substring(0, maxPopupMenuLength) + "…";
return optionElement;
}
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = this._scopeBarItems[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var scopeBarItem = _step2.value;
if (scopeBarItem.selected && !this._selectedScopeBarItem) this._selectedScopeBarItem = scopeBarItem;else if (scopeBarItem.selected) {
// Only one selected item is allowed at a time.
// Deselect any other items after the first.
scopeBarItem.selected = false;
}
scopeBarItem.addEventListener(WebInspector.ScopeBarItem.Event.SelectionChanged, this._itemSelectionDidChange, this);
this._selectElement.appendChild(createOption(scopeBarItem));
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2["return"]) {
_iterator2["return"]();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
this._lastSelectedScopeBarItem = this._selectedScopeBarItem || this._scopeBarItems[0] || null;
this._titleElement.textContent = this._lastSelectedScopeBarItem ? this._lastSelectedScopeBarItem.label : "";
this._element.classList.toggle("selected", !!this._selectedScopeBarItem);
this._selectElement.selectedIndex = this._scopeBarItems.indexOf(this._selectedScopeBarItem);
}
}, {
key: "selected",
get: function get() {
return !!this._selectedScopeBarItem;
},
set: function set(selected) {
this.selectedScopeBarItem = selected ? this._lastSelectedScopeBarItem : null;
}
}, {
key: "selectedScopeBarItem",
get: function get() {
return this._selectedScopeBarItem;
},
set: function set(selectedScopeBarItem) {
this._ignoreItemSelectedEvent = true;
if (this._selectedScopeBarItem) {
this._selectedScopeBarItem.selected = false;
this._lastSelectedScopeBarItem = this._selectedScopeBarItem;
} else if (!this._lastSelectedScopeBarItem) this._lastSelectedScopeBarItem = selectedScopeBarItem;
this._element.classList.toggle("selected", !!selectedScopeBarItem);
this._selectedScopeBarItem = selectedScopeBarItem || null;
this._selectElement.selectedIndex = this._scopeBarItems.indexOf(this._selectedScopeBarItem);
if (this._selectedScopeBarItem) {
this._titleElement.textContent = this._selectedScopeBarItem.label;
this._selectedScopeBarItem.selected = true;
}
var withModifier = WebInspector.modifierKeys.metaKey && !WebInspector.modifierKeys.ctrlKey && !WebInspector.modifierKeys.altKey && !WebInspector.modifierKeys.shiftKey;
this.dispatchEventToListeners(WebInspector.ScopeBarItem.Event.SelectionChanged, { withModifier: withModifier });
this._ignoreItemSelectedEvent = false;
}
}]);
return MultipleScopeBarItem;
})(WebInspector.Object);
|
export default {
difficult_word_definitions: {
abandoned: 'having been deserted or left',
abandonment: 'the action or fact of abandoning or being abandoned',
abide: 'accept or act in accordance with (a rule, decision, or recommendation)',
access: 'the means or opportunity to approach or enter a place',
acquire: 'buy or obtain (an asset or object) for oneself',
aid: 'help, typically of a practical nature',
allowable: 'allowed, especially within a set of regulations; permissible',
area: 'a region or part of a town, a country, or the world',
assign: 'allocate (a job or duty)',
assignment: 'a task or piece of work allocated to someone as part of a job or course of study',
authorization: 'the action of authorizing',
available: "able to be used or obtained; at someone's disposal",
aware: 'having knowledge or perception of a situation or fact',
beneficial: 'resulting in good; favourable or advantageous',
bylaw: 'a regulation made by a local authority or corporation.',
cancellation: 'the action of cancelling something',
cease: 'come or bring to an end',
chronological: '(of a record of events) following the order in which they occurred',
civil: 'relating to ordinary citizens and their concerns, as distinct from military or ecclesiastical matters',
clause: 'a unit of grammatical organization next below the sentence in rank and in traditional grammar said to consist of a subject and predicate.',
climatic: 'relating to climate',
code: 'a system of words, letters, figures, or symbols used to represent others, especially for the purposes of secrecy',
commission: 'an instruction, command, or role given to a person or group',
commissioner: 'a person appointed to a role on or by a commission.',
communication: 'the imparting or exchanging of information by speaking, writing, or using some other medium',
compensation: 'something, typically money, awarded to someone in recognition of loss, suffering, or injury',
consent: 'permission for something to happen or agreement to do something',
consult: 'seek information or advice from (someone, especially an expert or professional)',
consultation: 'the action or process of formally consulting or discussing',
contact: 'the state of physical touching',
continually: 'repeated frequently in the same way; regularly',
courthouse: 'a building in which a judicial court is held.',
credit: 'the ability of a customer to obtain goods or services before payment, based on the trust that payment will be made in the future',
deem: 'regard or consider in a specified way',
device: 'a thing made or adapted for a particular purpose, especially a piece of mechanical or electronic equipment',
discontent: "dissatisfaction with one's circumstances; lack of contentment",
displayed: '(of information) shown on a computer screen or other device',
disruptive: 'causing or tending to cause disruption',
document: 'a piece of written, printed, or electronic matter that provides information or evidence or that serves as an official record.',
driver: 'a person who drives a vehicle',
dwelling: 'a house, flat, or other place of residence',
eligible: 'having the right to do or obtain something; satisfying the appropriate conditions',
energy: 'the strength and vitality required for sustained physical or mental activity',
establish: 'set up on a firm or permanent basis',
estimate: 'roughly calculate or judge the value, number, quantity, or extent of',
evidence: 'the available body of facts or information indicating whether a belief or proposition is true or valid',
excessive: 'more than is necessary, normal, or desirable; immoderate',
external: 'belonging to or forming the outer surface or structure of something',
fee: 'a payment made to a professional person or to a professional or public body in exchange for advice or services',
file: 'a folder or box for holding loose papers together and in order for easy reference',
filing: 'a small particle rubbed off by a file when smoothing or shaping something',
finally: 'after a long time, typically when there has been difficulty or delay',
financial: 'relating to finance',
financially: 'in a way that relates to finance',
granted: 'admittedly; it is true (used to introduce a factor which is opposed to the main line of argument but is not regarded as so strong as to invalidate it)',
habitation: 'the fact of living in a particular place',
harassment: 'aggressive pressure or intimidation',
identification: 'the action or process of identifying someone or something or the fact of being identified',
illegal: 'contrary to or forbidden by law, especially criminal law',
income: 'money received, especially on a regular basis, for work or through investments',
indemnity: 'security or protection against a loss or other financial burden',
indisposed: 'slightly unwell',
infrastructure: 'the basic physical and organizational structures and facilities (e.g. buildings, roads, power supplies) needed for the operation of a society or enterprise',
inhabitable: 'suitable to live in; habitable',
injury: 'an instance of being injured',
inspector: 'an official employed to ensure that official regulations are obeyed, especially in public services',
invalid: 'a person made weak or disabled by illness or injury',
job: 'a paid position of regular employment',
jurisdiction: 'the official power to make legal decisions and judgements',
justify: 'show or prove to be right or reasonable',
landlord: 'a man (in legal use also a woman) who rents out land, a building, or accommodation.',
legal: 'relating to the law',
license: 'grant a licence to',
lodge: 'a small house at the gates of a park or in the grounds of a large house, occupied by a gatekeeper, gardener, or other employee.',
maintenance: 'the process of preserving a condition or situation or the state of being preserved',
mandatary: 'a person or state receiving a mandate.',
minimize: 'reduce (something, especially something undesirable, to the smallest possible amount or degree',
municipal: 'relating to a town or district or its governing body',
mutually: 'with mutual action; in a mutual relationship',
negligence: 'failure to take proper care over something',
negligent: 'failing to take proper care over something',
notify: 'inform (someone, of something, typically in a formal or official manner',
obtain: 'get, acquire, or secure (something,',
pest: 'a destructive insect or other animal that attacks crops, food, livestock, etc.',
plead: 'make an emotional appeal',
postponement: 'the action of postponing something; deferral',
prejudice: 'preconceived opinion that is not based on reason or actual experience',
previous: 'existing or occurring before in time or order',
prior: 'existing or coming before in time, order, or importance',
professional: 'relating to or belonging to a profession',
receptive: 'willing to consider or accept new suggestions and ideas',
recipient: 'a person or thing that receives or is awarded something',
recourse: 'a source of help in a difficult situation',
recover: 'return to a normal state of health, mind, or strength',
refrain: 'stop oneself from doing something',
refund: 'pay back (money,, typically to a customer who is not satisfied with goods or services bought',
regie: 'In France and certain other European countries: a government department that controls an industry or service; specifically one with complete control of the importation, manufacture, and taxation of tobacco, salt, and other resources (now historical,. Also: a government monopoly used as a means of taxation; especially the tobacco monopoly in the former Turkish Empire (now historical,.',
registered: 'entered or recorded on an official list or directory',
relocation: "the action of moving to a new place and establishing one's home or business there",
rendered: '(of fat, melted in order to separate out the impurities',
rental: 'an amount paid or received as rent',
reputable: 'having a good reputation',
require: 'need for a particular purpose',
resiliate: 'To annul, cancel (a bargain, contract, etc.,. Chiefly Canadian Law in later use.',
respond: 'say something in reply',
response: 'a verbal or written answer',
retake: 'take (something, again',
security: 'the state of being free from danger or threat',
sin: 'an immoral act considered to be a transgression against divine law',
solidarity: 'unity or agreement of feeling or action, especially among individuals with a common interest; mutual support within a group',
source: 'a place, person, or thing from which something originates or can be obtained',
specific: 'clearly defined or identified',
specifically: 'in a way that is exact and clear; precisely',
spousal: 'relating to marriage or to a husband or wife',
spouse: 'a husband or wife, considered in relation to their partner.',
sublet: 'lease (a property, to a subtenant',
submit: 'accept or yield to a superior force or to the authority or will of another person',
subtenant: 'a person who leases property from a tenant.',
technically: 'according to the facts or exact meaning of something; strictly',
temporary: 'lasting for only a limited period of time; not permanent',
testimony: 'a formal written or spoken statement, especially one given in a court of law',
text: 'a book or other written or printed work, regarded in terms of its content rather than its physical form',
transfer: 'move from one place to another',
unfit: '(of a thing, not of the necessary quality or standard to meet a particular purpose',
uninhabitable: '(of a place, unsuitable for living in'
}
}
|
// Returns a validator that executes multiple validators in sequence, returning the first error
// encountered
export function composeValidators(...validators) {
return async (...args) => {
for (const validator of validators) {
const error = await validator(...args)
if (error) {
return error
}
}
return null
}
}
export function debounce(validator, delay) {
let timeoutPromise
let lastValue
let lastModel
return (value, model) => {
lastValue = value
lastModel = model
if (!timeoutPromise) {
timeoutPromise = new Promise(resolve =>
setTimeout(() => {
resolve(validator(lastValue, lastModel))
timeoutPromise = null
lastValue = null
lastModel = null
}, delay),
)
}
return timeoutPromise
}
}
export function required(msg) {
return val => (val !== undefined && val !== null && val !== '' ? null : msg)
}
export function minLength(
length,
msg = `Enter at least ${length} character${length > 1 ? 's' : ''}`,
) {
return val => (('' + val).length >= length ? null : msg)
}
export function maxLength(
length,
msg = `Enter at most ${length} character${length > 1 ? 's' : ''}`,
) {
return val => (('' + val).length <= length ? null : msg)
}
export function regex(regex, msg) {
return val => (regex.test('' + val) ? null : msg)
}
export function matchesOther(otherName, msg) {
return (val, model) => (val === model[otherName] ? null : msg)
}
export function numberRange(min, max, msg) {
return val => {
const parsed = parseInt(val, 10)
return parsed >= min && parsed <= max ? null : msg
}
}
|
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const debug = require('debug')('app:config:prod')
const es3ifyPlugin = require('es3ify-webpack-plugin')
const baseWebpackConfig = require('./webpack.base.conf')
//const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
//const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
debug(`合并webpack ${config.build.env.NODE_ENV}环境配置`)
let webpackConfig = merge(baseWebpackConfig, {
module: {
loaders: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true
})
},
devtool: config.build.productionSourceMap ? '#source-map' : false,
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash:8].js'),
chunkFilename: utils.assetsPath('js/[name].[chunkhash:8].js')
},
plugins: [
new webpack.DefinePlugin({
'process.env': config.build.env
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
screw_ie8: false,
warnings: false
},
mangle: {
screw_ie8: false
},
sourceMap: true
}),
new webpack.optimize.OccurenceOrderPlugin(),
new ExtractTextPlugin(utils.assetsPath('css/[name].[contenthash:8].css')),
new es3ifyPlugin(),
new HtmlWebpackPlugin({
filename: config.build.index,
template: './src/index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency'
}),
/**
* DllReferencePlugin webpack插件,解决三方依赖库每次构建打包的问题,提高打包效率
* 并同时解决多项目下三方库共用的问题
*/
// new webpack.DllReferencePlugin({
// context: __dirname,
// manifest: require('../dist/vendor-manifest.json'),
// }),
/**
* 三方依赖库抽取
*/
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (module, count) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
chunks: ['vendor']
}),
]
})
debug(`合并webpack ${config.build.env.NODE_ENV}环境配置成功`)
module.exports = webpackConfig |
import React, { Component } from 'react'
import getGoogleVisionAnnotations from '../../services/getGoogleVisionAnnotations'
import Annotations from '../Annotations'
import Snapshot from '../Snapshot'
import './App.css'
export default class App extends Component {
constructor (props) {
super(props)
this.handleSnapshot = this.handleSnapshot.bind(this)
this.state = {
image: null
}
}
handleSnapshot (image) {
this.setState({
image
})
getGoogleVisionAnnotations(image)
.then(data => {
this.setState({
data
})
})
}
render () {
const { data, image } = this.state
return (
<div className='App'>
<h1>React Vision</h1>
<div className='links'>
<a href='https://github.com/davidchristie/react-vision'>
GitHub
</a>
</div>
<div className='container'>
<div className='column'>
<Snapshot onSnapshot={this.handleSnapshot} />
</div>
<div className='column'>
{
image
? <Annotations data={data} image={image} />
: null
}
</div>
</div>
</div>
)
}
}
|
/*!
* back-to-thunk - index.js
* Copyright(c) 2014 dead_horse <[email protected]>
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
*/
var is = require('is-type-of');
var co = require('co');
/**
* Expose `toThunk`
*/
module.exports = toThunk;
/**
* Convert `obj` into a normalized thunk.
*
* @param {Mixed} obj
* @param {Mixed} ctx
* @return {Function}
* @api public
*/
function toThunk(obj, ctx) {
if (Array.isArray(obj)) {
return objectToThunk.call(ctx, obj);
}
if (is.generatorFunction(obj)) {
return co(obj.call(ctx));
}
if (is.generator(obj)) {
return co(obj);
}
if (is.promise(obj)) {
return promiseToThunk(obj);
}
if (is.function(obj)) {
return obj;
}
if (is.object(obj)) {
return objectToThunk.call(ctx, obj);
}
return obj;
}
/**
* Convert an object of yieldables to a thunk.
*
* @param {Object} obj
* @return {Function}
* @api private
*/
function objectToThunk(obj){
var ctx = this;
return function(done){
var keys = Object.keys(obj);
var pending = keys.length;
var results = new obj.constructor();
var finished;
if (!pending) {
setImmediate(function(){
done(null, results)
});
return;
}
for (var i = 0; i < keys.length; i++) {
run(obj[keys[i]], keys[i]);
}
function run(fn, key) {
if (finished) return;
try {
fn = toThunk(fn, ctx);
if ('function' != typeof fn) {
results[key] = fn;
return --pending || done(null, results);
}
fn.call(ctx, function(err, res){
if (finished) return;
if (err) {
finished = true;
return done(err);
}
results[key] = res;
--pending || done(null, results);
});
} catch (err) {
finished = true;
done(err);
}
}
}
}
/**
* Convert `promise` to a thunk.
*
* @param {Object} promise
* @return {Function}
* @api private
*/
function promiseToThunk(promise) {
return function(fn){
promise.then(function(res) {
fn(null, res);
}, fn);
}
}
|
// Generated by CoffeeScript 1.4.0
(function() {
$.extend($.fn, {
backboneLink: function(options) {
var attr, model, save;
if (options == null) {
options = {};
}
model = options.model, attr = options.attr, save = options.save;
if (save == null) {
save = true;
}
return $(this).each(function() {
var check;
check = $(this).find('[data-backbone-link-attr]');
return (check.length ? check : $(this)).each(function() {
var $t, checkbox;
$t = $(this);
$t.backboneUnlink();
$t.data({
backboneLinkModel: model
});
checkbox = $t.is(':checkbox');
$t.data({
backboneLinkInputChange: function() {
var attributes, newVal, oldVal;
oldVal = model.get(attr);
newVal = checkbox ? $t.prop('checked') : $t.val() || null;
if (newVal !== oldVal) {
(attributes = {})[attr] = newVal;
return model[save ? 'save' : 'set'](attributes, {
wait: true,
attr: attr
});
}
}
});
$t.data({
backboneLinkModelChange: function() {
var newVal, oldVal, valOrText;
valOrText = $t.is(':input') ? 'val' : 'text';
oldVal = checkbox ? $t.prop('checked') : $t[valOrText]();
newVal = model.get(attr);
newVal = newVal === null ? '' : newVal;
if (newVal !== oldVal) {
if (checkbox) {
return $t.prop({
checked: !!newVal
});
} else {
return $t[valOrText](newVal);
}
}
}
});
if ($t.is(':input')) {
$t.on('change', $t.data().backboneLinkInputChange);
}
model.on("change:" + attr, $t.data().backboneLinkModelChange);
return $t.data().backboneLinkModelChange();
});
});
},
backboneUnlink: function() {
return $(this).each(function() {
var $t, model;
$t = $(this);
model = $t.data().backboneLinkModel;
if (model) {
$t.off('change', $t.data().backboneLinkInputChange);
return model.off(null, $t.data().backboneLinkModelChange);
}
});
}
});
}).call(this);
|
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/dist/";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(361);
/***/ }),
/***/ 3:
/***/ (function(module, exports) {
/* globals __VUE_SSR_CONTEXT__ */
// this module is a runtime utility for cleaner component module output and will
// be included in the final webpack user bundle
module.exports = function normalizeComponent (
rawScriptExports,
compiledTemplate,
injectStyles,
scopeId,
moduleIdentifier /* server only */
) {
var esModule
var scriptExports = rawScriptExports = rawScriptExports || {}
// ES6 modules interop
var type = typeof rawScriptExports.default
if (type === 'object' || type === 'function') {
esModule = rawScriptExports
scriptExports = rawScriptExports.default
}
// Vue.extend constructor export interop
var options = typeof scriptExports === 'function'
? scriptExports.options
: scriptExports
// render functions
if (compiledTemplate) {
options.render = compiledTemplate.render
options.staticRenderFns = compiledTemplate.staticRenderFns
}
// scopedId
if (scopeId) {
options._scopeId = scopeId
}
var hook
if (moduleIdentifier) { // server build
hook = function (context) {
// 2.3 injection
context =
context || // cached call
(this.$vnode && this.$vnode.ssrContext) || // stateful
(this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__
}
// inject component styles
if (injectStyles) {
injectStyles.call(this, context)
}
// register component module identifier for async chunk inferrence
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier)
}
}
// used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook
} else if (injectStyles) {
hook = injectStyles
}
if (hook) {
var functional = options.functional
var existing = functional
? options.render
: options.beforeCreate
if (!functional) {
// inject component registration as beforeCreate hook
options.beforeCreate = existing
? [].concat(existing, hook)
: [hook]
} else {
// register for functioal component in vue file
options.render = function renderWithStyleInjection (h, context) {
hook.call(context)
return existing(h, context)
}
}
}
return {
esModule: esModule,
exports: scriptExports,
options: options
}
}
/***/ }),
/***/ 9:
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _input = __webpack_require__(10);
var _input2 = _interopRequireDefault(_input);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* istanbul ignore next */
_input2.default.install = function (Vue) {
Vue.component(_input2.default.name, _input2.default);
};
exports.default = _input2.default;
/***/ }),
/***/ 10:
/***/ (function(module, exports, __webpack_require__) {
var Component = __webpack_require__(3)(
/* script */
__webpack_require__(11),
/* template */
__webpack_require__(15),
/* styles */
null,
/* scopeId */
null,
/* moduleIdentifier (server only) */
null
)
module.exports = Component.exports
/***/ }),
/***/ 11:
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _emitter = __webpack_require__(12);
var _emitter2 = _interopRequireDefault(_emitter);
var _calcTextareaHeight = __webpack_require__(13);
var _calcTextareaHeight2 = _interopRequireDefault(_calcTextareaHeight);
var _merge = __webpack_require__(14);
var _merge2 = _interopRequireDefault(_merge);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = {
name: 'ElInput',
componentName: 'ElInput',
mixins: [_emitter2.default],
data: function data() {
return {
currentValue: this.value,
textareaCalcStyle: {}
};
},
props: {
value: [String, Number],
placeholder: String,
size: String,
resize: String,
readonly: Boolean,
autofocus: Boolean,
icon: String,
disabled: Boolean,
type: {
type: String,
default: 'text'
},
name: String,
autosize: {
type: [Boolean, Object],
default: false
},
rows: {
type: Number,
default: 2
},
autoComplete: {
type: String,
default: 'off'
},
autoClear: {
type: Boolean,
default: false
},
form: String,
maxlength: Number,
minlength: Number,
max: {},
min: {},
step: {},
validateEvent: {
type: Boolean,
default: true
},
onIconClick: Function
},
computed: {
validating: function validating() {
return this.$parent.validateState === 'validating';
},
hasClear: function hasClear() {
return this.autoClear && this.currentValue.length > 0;
},
textareaStyle: function textareaStyle() {
return (0, _merge2.default)({}, this.textareaCalcStyle, { resize: this.resize });
}
},
watch: {
'value': function value(val, oldValue) {
this.setCurrentValue(val);
}
},
methods: {
handleEnter: function handleEnter(event) {
this.$emit('keyupenter', event);
},
handleBlur: function handleBlur(event) {
this.$emit('blur', event);
if (this.validateEvent) {
this.dispatch('ElFormItem', 'el.form.blur', [this.currentValue]);
}
},
inputFocus: function inputFocus() {
this.$refs.input.focus();
},
inputSelect: function inputSelect() {
this.$refs.input.select();
},
resizeTextarea: function resizeTextarea() {
if (this.$isServer) return;
var autosize = this.autosize,
type = this.type;
if (!autosize || type !== 'textarea') return;
var minRows = autosize.minRows;
var maxRows = autosize.maxRows;
this.textareaCalcStyle = (0, _calcTextareaHeight2.default)(this.$refs.textarea, minRows, maxRows);
},
handleFocus: function handleFocus(event) {
this.$emit('focus', event);
},
handleInput: function handleInput(event) {
var value = event.target.value;
this.$emit('input', value);
this.setCurrentValue(value);
this.$emit('change', value);
},
handleIconClick: function handleIconClick(event) {
if (this.onIconClick) {
this.onIconClick(event);
}
this.$emit('click', event);
},
handleClearClick: function handleClearClick() {
this.setCurrentValue('');
this.$emit('clear');
},
setCurrentValue: function setCurrentValue(value) {
var _this = this;
if (value === this.currentValue) return;
this.$nextTick(function (_) {
_this.resizeTextarea();
});
this.currentValue = value;
if (this.validateEvent) {
this.dispatch('ElFormItem', 'el.form.change', [value]);
}
}
},
created: function created() {
this.$on('inputSelect', this.inputSelect);
},
mounted: function mounted() {
var _this2 = this;
this.resizeTextarea();
this.$nextTick(function () {
if (_this2.autofocus) {
if (_this2.$refs.textarea) {
_this2.$refs.textarea.focus();
}
if (_this2.$refs.input) {
_this2.$refs.input.focus();
}
}
});
}
}; //
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/***/ }),
/***/ 12:
/***/ (function(module, exports) {
"use strict";
exports.__esModule = true;
function _broadcast(componentName, eventName, params) {
this.$children.forEach(function (child) {
var name = child.$options.componentName;
if (name === componentName) {
child.$emit.apply(child, [eventName].concat(params));
} else {
_broadcast.apply(child, [componentName, eventName].concat([params]));
}
});
}
exports.default = {
methods: {
dispatch: function dispatch(componentName, eventName, params) {
var parent = this.$parent || this.$root;
var name = parent.$options.componentName;
while (parent && (!name || name !== componentName)) {
parent = parent.$parent;
if (parent) {
name = parent.$options.componentName;
}
}
if (parent) {
parent.$emit.apply(parent, [eventName].concat(params));
}
},
broadcast: function broadcast(componentName, eventName, params) {
_broadcast.call(this, componentName, eventName, params);
}
}
};
/***/ }),
/***/ 13:
/***/ (function(module, exports) {
'use strict';
exports.__esModule = true;
exports.default = calcTextareaHeight;
var hiddenTextarea = void 0;
var HIDDEN_STYLE = '\n height:0 !important;\n visibility:hidden !important;\n overflow:hidden !important;\n position:absolute !important;\n z-index:-1000 !important;\n top:0 !important;\n right:0 !important\n';
var CONTEXT_STYLE = ['letter-spacing', 'line-height', 'padding-top', 'padding-bottom', 'font-family', 'font-weight', 'font-size', 'text-rendering', 'text-transform', 'width', 'text-indent', 'padding-left', 'padding-right', 'border-width', 'box-sizing'];
function calculateNodeStyling(node) {
var style = window.getComputedStyle(node);
var boxSizing = style.getPropertyValue('box-sizing');
var paddingSize = parseFloat(style.getPropertyValue('padding-bottom')) + parseFloat(style.getPropertyValue('padding-top'));
var borderSize = parseFloat(style.getPropertyValue('border-bottom-width')) + parseFloat(style.getPropertyValue('border-top-width'));
var contextStyle = CONTEXT_STYLE.map(function (name) {
return name + ':' + style.getPropertyValue(name);
}).join(';');
return { contextStyle: contextStyle, paddingSize: paddingSize, borderSize: borderSize, boxSizing: boxSizing };
}
function calcTextareaHeight(targetNode) {
var minRows = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var maxRows = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
if (!hiddenTextarea) {
hiddenTextarea = document.createElement('textarea');
document.body.appendChild(hiddenTextarea);
}
var _calculateNodeStyling = calculateNodeStyling(targetNode),
paddingSize = _calculateNodeStyling.paddingSize,
borderSize = _calculateNodeStyling.borderSize,
boxSizing = _calculateNodeStyling.boxSizing,
contextStyle = _calculateNodeStyling.contextStyle;
hiddenTextarea.setAttribute('style', contextStyle + ';' + HIDDEN_STYLE);
hiddenTextarea.value = targetNode.value || targetNode.placeholder || '';
var height = hiddenTextarea.scrollHeight;
if (boxSizing === 'border-box') {
height = height + borderSize;
} else if (boxSizing === 'content-box') {
height = height - paddingSize;
}
hiddenTextarea.value = '';
var singleRowHeight = hiddenTextarea.scrollHeight - paddingSize;
if (minRows !== null) {
var minHeight = singleRowHeight * minRows;
if (boxSizing === 'border-box') {
minHeight = minHeight + paddingSize + borderSize;
}
height = Math.max(minHeight, height);
}
if (maxRows !== null) {
var maxHeight = singleRowHeight * maxRows;
if (boxSizing === 'border-box') {
maxHeight = maxHeight + paddingSize + borderSize;
}
height = Math.min(maxHeight, height);
}
return { height: height + 'px' };
};
/***/ }),
/***/ 14:
/***/ (function(module, exports) {
"use strict";
exports.__esModule = true;
exports.default = function (target) {
for (var i = 1, j = arguments.length; i < j; i++) {
var source = arguments[i] || {};
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
var value = source[prop];
if (value !== undefined) {
target[prop] = value;
}
}
}
}
return target;
};
;
/***/ }),
/***/ 15:
/***/ (function(module, exports) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _c('div', {
class: [
_vm.type === 'textarea' ? 'el-textarea' : 'el-input',
_vm.size ? 'el-input--' + _vm.size : '',
{
'is-disabled': _vm.disabled,
'el-input-group': _vm.$slots.prepend || _vm.$slots.append,
'el-input-group--append': _vm.$slots.append,
'el-input-group--prepend': _vm.$slots.prepend
}
]
}, [(_vm.type !== 'textarea') ? [(_vm.$slots.prepend) ? _c('div', {
staticClass: "el-input-group__prepend"
}, [_vm._t("prepend")], 2) : _vm._e(), _vm._t("icon", [(_vm.icon) ? _c('i', {
staticClass: "el-input__icon",
class: [
'el-icon-' + _vm.icon,
_vm.icon,
_vm.onIconClick ? 'is-clickable' : ''
],
on: {
"click": _vm.handleIconClick
}
}) : _vm._e()]), (_vm.type !== 'textarea') ? _c('input', _vm._b({
ref: "input",
staticClass: "el-input__inner",
class: {
'el-input__inner--no-icon': !_vm.icon
},
attrs: {
"autocomplete": _vm.autoComplete
},
domProps: {
"value": _vm.currentValue
},
on: {
"keyup": function($event) {
if (!('button' in $event) && _vm._k($event.keyCode, "enter", 13)) { return null; }
_vm.handleEnter($event)
},
"input": _vm.handleInput,
"focus": _vm.handleFocus,
"blur": _vm.handleBlur
}
}, 'input', _vm.$props, false)) : _vm._e(), (_vm.validating) ? _c('i', {
staticClass: "el-input__icon el-icon-loading"
}) : _vm._e(), (_vm.hasClear && !_vm.validating) ? _c('i', {
staticClass: "el-input__icon el-icon-circle-cross",
on: {
"click": _vm.handleClearClick
}
}) : _vm._e(), (_vm.$slots.append) ? _c('div', {
staticClass: "el-input-group__append"
}, [_vm._t("append")], 2) : _vm._e()] : _c('textarea', _vm._b({
ref: "textarea",
staticClass: "el-textarea__inner",
style: (_vm.textareaStyle),
domProps: {
"value": _vm.currentValue
},
on: {
"input": _vm.handleInput,
"focus": _vm.handleFocus,
"blur": _vm.handleBlur
}
}, 'textarea', _vm.$props, false))], 2)
},staticRenderFns: []}
/***/ }),
/***/ 19:
/***/ (function(module, exports) {
module.exports = require("vue");
/***/ }),
/***/ 28:
/***/ (function(module, exports) {
"use strict";
exports.__esModule = true;
exports.hasOwn = hasOwn;
exports.toObject = toObject;
var hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn(obj, key) {
return hasOwnProperty.call(obj, key);
};
function extend(to, _from) {
for (var key in _from) {
to[key] = _from[key];
}
return to;
};
function toObject(arr) {
var res = {};
for (var i = 0; i < arr.length; i++) {
if (arr[i]) {
extend(res, arr[i]);
}
}
return res;
};
/***/ }),
/***/ 45:
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _button = __webpack_require__(46);
var _button2 = _interopRequireDefault(_button);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* istanbul ignore next */
_button2.default.install = function (Vue) {
Vue.component(_button2.default.name, _button2.default);
};
exports.default = _button2.default;
/***/ }),
/***/ 46:
/***/ (function(module, exports, __webpack_require__) {
var Component = __webpack_require__(3)(
/* script */
__webpack_require__(47),
/* template */
__webpack_require__(48),
/* styles */
null,
/* scopeId */
null,
/* moduleIdentifier (server only) */
null
)
module.exports = Component.exports
/***/ }),
/***/ 47:
/***/ (function(module, exports) {
'use strict';
exports.__esModule = true;
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
exports.default = {
name: 'ElButton',
props: {
active: Boolean,
type: {
type: String,
default: 'default'
},
size: String,
icon: {
type: String,
default: ''
},
nativeType: {
type: String,
default: 'button'
},
loading: Boolean,
disabled: Boolean,
plain: Boolean,
plainLight: Boolean,
autofocus: Boolean
},
methods: {
handleClick: function handleClick(evt) {
this.$emit('click', evt);
}
}
};
/***/ }),
/***/ 48:
/***/ (function(module, exports) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _c('button', {
staticClass: "el-button",
class: [
_vm.type ? 'el-button--' + _vm.type : '',
_vm.size ? 'el-button--' + _vm.size : '',
_vm.active ? 'is-active' : '',
{
'is-disabled': _vm.disabled,
'is-loading': _vm.loading,
'is-plain': _vm.plain,
'is-plain-light': _vm.plainLight
}
],
attrs: {
"disabled": _vm.disabled,
"autofocus": _vm.autofocus,
"type": _vm.nativeType
},
on: {
"click": _vm.handleClick
}
}, [(_vm.loading) ? _c('i', {
staticClass: "el-icon-loading"
}) : _vm._e(), (_vm.icon && !_vm.loading) ? _c('i', {
class: 'el-icon-' + _vm.icon
}) : _vm._e(), (_vm.$slots.default) ? _c('span', [_vm._t("default")], 2) : _vm._e()])
},staticRenderFns: []}
/***/ }),
/***/ 74:
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _locale = __webpack_require__(75);
exports.default = {
methods: {
t: function t() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _locale.t.apply(this, args);
}
}
};
/***/ }),
/***/ 75:
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.i18n = exports.use = exports.t = undefined;
var _zhCN = __webpack_require__(76);
var _zhCN2 = _interopRequireDefault(_zhCN);
var _vue = __webpack_require__(19);
var _vue2 = _interopRequireDefault(_vue);
var _deepmerge = __webpack_require__(77);
var _deepmerge2 = _interopRequireDefault(_deepmerge);
var _format = __webpack_require__(78);
var _format2 = _interopRequireDefault(_format);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var format = (0, _format2.default)(_vue2.default);
var lang = _zhCN2.default;
var merged = false;
var i18nHandler = function i18nHandler() {
var vuei18n = Object.getPrototypeOf(this || _vue2.default).$t;
if (typeof vuei18n === 'function' && !!_vue2.default.locale) {
if (!merged) {
merged = true;
_vue2.default.locale(_vue2.default.config.lang, (0, _deepmerge2.default)(lang, _vue2.default.locale(_vue2.default.config.lang) || {}, { clone: true }));
}
return vuei18n.apply(this, arguments);
}
};
var t = exports.t = function t(path, options) {
var value = i18nHandler.apply(this, arguments);
if (value !== null && value !== undefined) return value;
var array = path.split('.');
var current = lang;
for (var i = 0, j = array.length; i < j; i++) {
var property = array[i];
value = current[property];
if (i === j - 1) return format(value, options);
if (!value) return '';
current = value;
}
return '';
};
var use = exports.use = function use(l) {
lang = l || lang;
};
var i18n = exports.i18n = function i18n(fn) {
i18nHandler = fn || i18nHandler;
};
exports.default = { use: use, t: t, i18n: i18n };
/***/ }),
/***/ 76:
/***/ (function(module, exports) {
'use strict';
exports.__esModule = true;
exports.default = {
el: {
colorpicker: {
confirm: '确定',
clear: '清空'
},
datepicker: {
now: '此刻',
today: '今天',
cancel: '取消',
clear: '清空',
confirm: '确定',
selectDate: '选择日期',
selectTime: '选择时间',
startDate: '开始日期',
startTime: '开始时间',
endDate: '结束日期',
endTime: '结束时间',
year: '年',
month1: '1 月',
month2: '2 月',
month3: '3 月',
month4: '4 月',
month5: '5 月',
month6: '6 月',
month7: '7 月',
month8: '8 月',
month9: '9 月',
month10: '10 月',
month11: '11 月',
month12: '12 月',
// week: '周次',
weeks: {
sun: '日',
mon: '一',
tue: '二',
wed: '三',
thu: '四',
fri: '五',
sat: '六'
},
months: {
jan: '一月',
feb: '二月',
mar: '三月',
apr: '四月',
may: '五月',
jun: '六月',
jul: '七月',
aug: '八月',
sep: '九月',
oct: '十月',
nov: '十一月',
dec: '十二月'
}
},
select: {
loading: '加载中',
noMatch: '无匹配数据',
noData: '无数据',
placeholder: '请选择'
},
cascader: {
noMatch: '无匹配数据',
loading: '加载中',
placeholder: '请选择'
},
pagination: {
goto: '前往',
pagesize: '条/页',
total: '共 {total} 条',
pageClassifier: '页'
},
messagebox: {
title: '提示',
confirm: '确定',
cancel: '取消',
error: '输入的数据不合法!'
},
upload: {
delete: '删除',
preview: '查看图片',
continue: '继续上传'
},
table: {
emptyText: '暂无数据',
confirmFilter: '筛选',
resetFilter: '重置',
clearFilter: '全部',
sumText: '合计'
},
tree: {
emptyText: '暂无数据'
},
transfer: {
noMatch: '无匹配数据',
noData: '无数据',
titles: ['列表 1', '列表 2'],
filterPlaceholder: '请输入搜索内容',
noCheckedFormat: '共 {total} 项',
hasCheckedFormat: '已选 {checked}/{total} 项'
}
}
};
/***/ }),
/***/ 77:
/***/ (function(module, exports) {
module.exports = require("deepmerge");
/***/ }),
/***/ 78:
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.default = function (Vue) {
/**
* template
*
* @param {String} string
* @param {Array} ...args
* @return {String}
*/
function template(string) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (args.length === 1 && _typeof(args[0]) === 'object') {
args = args[0];
}
if (!args || !args.hasOwnProperty) {
args = {};
}
return string.replace(RE_NARGS, function (match, prefix, i, index) {
var result = void 0;
if (string[index - 1] === '{' && string[index + match.length] === '}') {
return i;
} else {
result = (0, _util.hasOwn)(args, i) ? args[i] : null;
if (result === null || result === undefined) {
return '';
}
return result;
}
});
}
return template;
};
var _util = __webpack_require__(28);
var RE_NARGS = /(%|)\{([0-9a-zA-Z_]+)\}/g;
/**
* String format template
* - Inspired:
* https://github.com/Matt-Esch/string-template/index.js
*/
/***/ }),
/***/ 81:
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _checkbox = __webpack_require__(82);
var _checkbox2 = _interopRequireDefault(_checkbox);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* istanbul ignore next */
_checkbox2.default.install = function (Vue) {
Vue.component(_checkbox2.default.name, _checkbox2.default);
};
exports.default = _checkbox2.default;
/***/ }),
/***/ 82:
/***/ (function(module, exports, __webpack_require__) {
var Component = __webpack_require__(3)(
/* script */
__webpack_require__(83),
/* template */
__webpack_require__(84),
/* styles */
null,
/* scopeId */
null,
/* moduleIdentifier (server only) */
null
)
module.exports = Component.exports
/***/ }),
/***/ 83:
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _emitter = __webpack_require__(12);
var _emitter2 = _interopRequireDefault(_emitter);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = {
name: 'ElCheckbox',
mixins: [_emitter2.default],
componentName: 'ElCheckbox',
data: function data() {
return {
selfModel: false,
focus: false
};
},
computed: {
model: {
get: function get() {
return this.isGroup ? this.store : this.value !== undefined ? this.value : this.selfModel;
},
set: function set(val) {
if (this.isGroup) {
var isLimitExceeded = false;
this._checkboxGroup.min !== undefined && val.length < this._checkboxGroup.min && (isLimitExceeded = true);
this._checkboxGroup.max !== undefined && val.length > this._checkboxGroup.max && (isLimitExceeded = true);
isLimitExceeded === false && this.dispatch('ElCheckboxGroup', 'input', [val]);
} else {
this.$emit('input', val);
this.selfModel = val;
}
}
},
isChecked: function isChecked() {
if ({}.toString.call(this.model) === '[object Boolean]') {
return this.model;
} else if (Array.isArray(this.model)) {
return this.model.indexOf(this.label) > -1;
} else if (this.model !== null && this.model !== undefined) {
return this.model === this.trueLabel;
}
},
isGroup: function isGroup() {
var parent = this.$parent;
while (parent) {
if (parent.$options.componentName !== 'ElCheckboxGroup') {
parent = parent.$parent;
} else {
this._checkboxGroup = parent;
return true;
}
}
return false;
},
store: function store() {
return this._checkboxGroup ? this._checkboxGroup.value : this.value;
}
},
props: {
value: {},
label: {},
indeterminate: Boolean,
disabled: Boolean,
checked: Boolean,
name: String,
trueLabel: [String, Number],
falseLabel: [String, Number],
size: String
},
methods: {
addToStore: function addToStore() {
if (Array.isArray(this.model) && this.model.indexOf(this.label) === -1) {
this.model.push(this.label);
} else {
this.model = this.trueLabel || true;
}
},
handleChange: function handleChange(ev) {
var _this = this;
this.$emit('change', ev);
if (this.isGroup) {
this.$nextTick(function (_) {
_this.dispatch('ElCheckboxGroup', 'change', [_this._checkboxGroup.value]);
});
}
}
},
created: function created() {
this.checked && this.addToStore();
}
}; //
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/***/ }),
/***/ 84:
/***/ (function(module, exports) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _c('label', {
staticClass: "el-checkbox"
}, [_c('span', {
staticClass: "el-checkbox__input",
class: [{
'is-disabled': _vm.disabled,
'is-checked': _vm.isChecked,
'is-indeterminate': _vm.indeterminate,
'is-focus': _vm.focus
}]
}, [_c('span', {
staticClass: "el-checkbox__inner",
class: [
_vm.size ? 'el-checkbox__inner--' + _vm.size : ''
]
}), (_vm.trueLabel || _vm.falseLabel) ? _c('input', {
directives: [{
name: "model",
rawName: "v-model",
value: (_vm.model),
expression: "model"
}],
staticClass: "el-checkbox__original",
attrs: {
"type": "checkbox",
"name": _vm.name,
"disabled": _vm.disabled,
"true-value": _vm.trueLabel,
"false-value": _vm.falseLabel
},
domProps: {
"checked": Array.isArray(_vm.model) ? _vm._i(_vm.model, null) > -1 : _vm._q(_vm.model, _vm.trueLabel)
},
on: {
"change": _vm.handleChange,
"focus": function($event) {
_vm.focus = true
},
"blur": function($event) {
_vm.focus = false
},
"__c": function($event) {
var $$a = _vm.model,
$$el = $event.target,
$$c = $$el.checked ? (_vm.trueLabel) : (_vm.falseLabel);
if (Array.isArray($$a)) {
var $$v = null,
$$i = _vm._i($$a, $$v);
if ($$el.checked) {
$$i < 0 && (_vm.model = $$a.concat([$$v]))
} else {
$$i > -1 && (_vm.model = $$a.slice(0, $$i).concat($$a.slice($$i + 1)))
}
} else {
_vm.model = $$c
}
}
}
}) : _c('input', {
directives: [{
name: "model",
rawName: "v-model",
value: (_vm.model),
expression: "model"
}],
staticClass: "el-checkbox__original",
attrs: {
"type": "checkbox",
"disabled": _vm.disabled,
"name": _vm.name
},
domProps: {
"value": _vm.label,
"checked": Array.isArray(_vm.model) ? _vm._i(_vm.model, _vm.label) > -1 : (_vm.model)
},
on: {
"change": _vm.handleChange,
"focus": function($event) {
_vm.focus = true
},
"blur": function($event) {
_vm.focus = false
},
"__c": function($event) {
var $$a = _vm.model,
$$el = $event.target,
$$c = $$el.checked ? (true) : (false);
if (Array.isArray($$a)) {
var $$v = _vm.label,
$$i = _vm._i($$a, $$v);
if ($$el.checked) {
$$i < 0 && (_vm.model = $$a.concat([$$v]))
} else {
$$i > -1 && (_vm.model = $$a.slice(0, $$i).concat($$a.slice($$i + 1)))
}
} else {
_vm.model = $$c
}
}
}
})]), (_vm.$slots.default || _vm.label) ? _c('span', {
staticClass: "el-checkbox__label"
}, [_vm._t("default"), (!_vm.$slots.default) ? [_vm._v(_vm._s(_vm.label))] : _vm._e()], 2) : _vm._e()])
},staticRenderFns: []}
/***/ }),
/***/ 89:
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _checkboxGroup = __webpack_require__(90);
var _checkboxGroup2 = _interopRequireDefault(_checkboxGroup);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* istanbul ignore next */
_checkboxGroup2.default.install = function (Vue) {
Vue.component(_checkboxGroup2.default.name, _checkboxGroup2.default);
};
exports.default = _checkboxGroup2.default;
/***/ }),
/***/ 90:
/***/ (function(module, exports, __webpack_require__) {
var Component = __webpack_require__(3)(
/* script */
__webpack_require__(91),
/* template */
__webpack_require__(92),
/* styles */
null,
/* scopeId */
null,
/* moduleIdentifier (server only) */
null
)
module.exports = Component.exports
/***/ }),
/***/ 91:
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _emitter = __webpack_require__(12);
var _emitter2 = _interopRequireDefault(_emitter);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = {
name: 'ElCheckboxGroup',
componentName: 'ElCheckboxGroup',
mixins: [_emitter2.default],
props: {
value: {},
min: Number,
max: Number,
size: String,
fill: String,
textColor: String
},
watch: {
value: function value(_value) {
this.dispatch('ElFormItem', 'el.form.change', [_value]);
}
}
};
/***/ }),
/***/ 92:
/***/ (function(module, exports) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _c('div', {
staticClass: "el-checkbox-group"
}, [_vm._t("default")], 2)
},staticRenderFns: []}
/***/ }),
/***/ 361:
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _main = __webpack_require__(362);
var _main2 = _interopRequireDefault(_main);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* istanbul ignore next */
_main2.default.install = function (Vue) {
Vue.component(_main2.default.name, _main2.default);
};
exports.default = _main2.default;
/***/ }),
/***/ 362:
/***/ (function(module, exports, __webpack_require__) {
var Component = __webpack_require__(3)(
/* script */
__webpack_require__(363),
/* template */
__webpack_require__(367),
/* styles */
null,
/* scopeId */
null,
/* moduleIdentifier (server only) */
null
)
module.exports = Component.exports
/***/ }),
/***/ 363:
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _button = __webpack_require__(45);
var _button2 = _interopRequireDefault(_button);
var _emitter = __webpack_require__(12);
var _emitter2 = _interopRequireDefault(_emitter);
var _locale = __webpack_require__(74);
var _locale2 = _interopRequireDefault(_locale);
var _transferPanel = __webpack_require__(364);
var _transferPanel2 = _interopRequireDefault(_transferPanel);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
exports.default = {
name: 'ElTransfer',
mixins: [_emitter2.default, _locale2.default],
components: {
TransferPanel: _transferPanel2.default,
ElButton: _button2.default
},
props: {
data: {
type: Array,
default: function _default() {
return [];
}
},
titles: {
type: Array,
default: function _default() {
return [];
}
},
buttonTexts: {
type: Array,
default: function _default() {
return [];
}
},
filterPlaceholder: {
type: String,
default: ''
},
filterMethod: Function,
leftDefaultChecked: {
type: Array,
default: function _default() {
return [];
}
},
rightDefaultChecked: {
type: Array,
default: function _default() {
return [];
}
},
renderContent: Function,
value: {
type: Array,
default: function _default() {
return [];
}
},
footerFormat: {
type: Object,
default: function _default() {
return {};
}
},
filterable: Boolean,
props: {
type: Object,
default: function _default() {
return {
label: 'label',
key: 'key',
disabled: 'disabled'
};
}
}
},
data: function data() {
return {
leftChecked: [],
rightChecked: []
};
},
computed: {
sourceData: function sourceData() {
var _this = this;
return this.data.filter(function (item) {
return _this.value.indexOf(item[_this.props.key]) === -1;
});
},
targetData: function targetData() {
var _this2 = this;
return this.data.filter(function (item) {
return _this2.value.indexOf(item[_this2.props.key]) > -1;
});
}
},
watch: {
value: function value(val) {
this.dispatch('ElFormItem', 'el.form.change', val);
}
},
methods: {
onSourceCheckedChange: function onSourceCheckedChange(val) {
this.leftChecked = val;
},
onTargetCheckedChange: function onTargetCheckedChange(val) {
this.rightChecked = val;
},
addToLeft: function addToLeft() {
var currentValue = this.value.slice();
this.rightChecked.forEach(function (item) {
var index = currentValue.indexOf(item);
if (index > -1) {
currentValue.splice(index, 1);
}
});
this.$emit('input', currentValue);
this.$emit('change', currentValue, 'left', this.rightChecked);
},
addToRight: function addToRight() {
var _this3 = this;
var currentValue = this.value.slice();
this.leftChecked.forEach(function (item) {
if (_this3.value.indexOf(item) === -1) {
currentValue = currentValue.concat(item);
}
});
this.$emit('input', currentValue);
this.$emit('change', currentValue, 'right', this.leftChecked);
}
}
};
/***/ }),
/***/ 364:
/***/ (function(module, exports, __webpack_require__) {
var Component = __webpack_require__(3)(
/* script */
__webpack_require__(365),
/* template */
__webpack_require__(366),
/* styles */
null,
/* scopeId */
null,
/* moduleIdentifier (server only) */
null
)
module.exports = Component.exports
/***/ }),
/***/ 365:
/***/ (function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _checkboxGroup = __webpack_require__(89);
var _checkboxGroup2 = _interopRequireDefault(_checkboxGroup);
var _checkbox = __webpack_require__(81);
var _checkbox2 = _interopRequireDefault(_checkbox);
var _input = __webpack_require__(9);
var _input2 = _interopRequireDefault(_input);
var _locale = __webpack_require__(74);
var _locale2 = _interopRequireDefault(_locale);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
exports.default = {
mixins: [_locale2.default],
name: 'ElTransferPanel',
componentName: 'ElTransferPanel',
components: {
ElCheckboxGroup: _checkboxGroup2.default,
ElCheckbox: _checkbox2.default,
ElInput: _input2.default,
OptionContent: {
props: {
option: Object
},
render: function render(h) {
var getParent = function getParent(vm) {
if (vm.$options.componentName === 'ElTransferPanel') {
return vm;
} else if (vm.$parent) {
return getParent(vm.$parent);
} else {
return vm;
}
};
var parent = getParent(this);
return parent.renderContent ? parent.renderContent(h, this.option) : h(
'span',
null,
[this.option[parent.labelProp] || this.option[parent.keyProp]]
);
}
}
},
props: {
data: {
type: Array,
default: function _default() {
return [];
}
},
renderContent: Function,
placeholder: String,
title: String,
filterable: Boolean,
footerFormat: Object,
filterMethod: Function,
defaultChecked: Array,
props: Object
},
data: function data() {
return {
checked: [],
allChecked: false,
query: '',
inputHover: false
};
},
watch: {
checked: function checked(val) {
this.updateAllChecked();
this.$emit('checked-change', val);
},
data: function data() {
var _this = this;
var checked = [];
var filteredDataKeys = this.filteredData.map(function (item) {
return item[_this.keyProp];
});
this.checked.forEach(function (item) {
if (filteredDataKeys.indexOf(item) > -1) {
checked.push(item);
}
});
this.checked = checked;
},
checkableData: function checkableData() {
this.updateAllChecked();
},
defaultChecked: {
immediate: true,
handler: function handler(val, oldVal) {
var _this2 = this;
if (oldVal && val.length === oldVal.length && val.every(function (item) {
return oldVal.indexOf(item) > -1;
})) return;
var checked = [];
var checkableDataKeys = this.checkableData.map(function (item) {
return item[_this2.keyProp];
});
val.forEach(function (item) {
if (checkableDataKeys.indexOf(item) > -1) {
checked.push(item);
}
});
this.checked = checked;
}
}
},
computed: {
filteredData: function filteredData() {
var _this3 = this;
return this.data.filter(function (item) {
if (typeof _this3.filterMethod === 'function') {
return _this3.filterMethod(_this3.query, item);
} else {
var label = item[_this3.labelProp] || item[_this3.keyProp].toString();
return label.toLowerCase().indexOf(_this3.query.toLowerCase()) > -1;
}
});
},
checkableData: function checkableData() {
var _this4 = this;
return this.filteredData.filter(function (item) {
return !item[_this4.disabledProp];
});
},
checkedSummary: function checkedSummary() {
var checkedLength = this.checked.length;
var dataLength = this.data.length;
var _footerFormat = this.footerFormat,
noChecked = _footerFormat.noChecked,
hasChecked = _footerFormat.hasChecked;
if (noChecked && hasChecked) {
return checkedLength > 0 ? hasChecked.replace(/\${checked}/g, checkedLength).replace(/\${total}/g, dataLength) : noChecked.replace(/\${total}/g, dataLength);
} else {
return checkedLength > 0 ? this.t('el.transfer.hasCheckedFormat', { total: dataLength, checked: checkedLength }) : this.t('el.transfer.noCheckedFormat', { total: dataLength });
}
},
isIndeterminate: function isIndeterminate() {
var checkedLength = this.checked.length;
return checkedLength > 0 && checkedLength < this.checkableData.length;
},
hasNoMatch: function hasNoMatch() {
return this.query.length > 0 && this.filteredData.length === 0;
},
inputIcon: function inputIcon() {
return this.query.length > 0 && this.inputHover ? 'circle-close' : 'search';
},
labelProp: function labelProp() {
return this.props.label || 'label';
},
keyProp: function keyProp() {
return this.props.key || 'key';
},
disabledProp: function disabledProp() {
return this.props.disabled || 'disabled';
}
},
methods: {
updateAllChecked: function updateAllChecked() {
var _this5 = this;
var checkableDataKeys = this.checkableData.map(function (item) {
return item[_this5.keyProp];
});
this.allChecked = checkableDataKeys.length > 0 && checkableDataKeys.every(function (item) {
return _this5.checked.indexOf(item) > -1;
});
},
handleAllCheckedChange: function handleAllCheckedChange(value) {
var _this6 = this;
this.checked = value.target.checked ? this.checkableData.map(function (item) {
return item[_this6.keyProp];
}) : [];
},
clearQuery: function clearQuery() {
if (this.inputIcon === 'circle-close') {
this.query = '';
}
}
}
};
/***/ }),
/***/ 366:
/***/ (function(module, exports) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _c('div', {
staticClass: "el-transfer-panel"
}, [_c('p', {
staticClass: "el-transfer-panel__header"
}, [_vm._v(_vm._s(_vm.title))]), _c('div', {
staticClass: "el-transfer-panel__body"
}, [(_vm.filterable) ? _c('el-input', {
staticClass: "el-transfer-panel__filter",
attrs: {
"size": "small",
"placeholder": _vm.placeholder,
"icon": _vm.inputIcon
},
on: {
"click": _vm.clearQuery
},
nativeOn: {
"mouseenter": function($event) {
_vm.inputHover = true
},
"mouseleave": function($event) {
_vm.inputHover = false
}
},
model: {
value: (_vm.query),
callback: function($$v) {
_vm.query = $$v
},
expression: "query"
}
}) : _vm._e(), _c('el-checkbox-group', {
directives: [{
name: "show",
rawName: "v-show",
value: (!_vm.hasNoMatch && _vm.data.length > 0),
expression: "!hasNoMatch && data.length > 0"
}],
staticClass: "el-transfer-panel__list",
class: {
'is-filterable': _vm.filterable
},
model: {
value: (_vm.checked),
callback: function($$v) {
_vm.checked = $$v
},
expression: "checked"
}
}, _vm._l((_vm.filteredData), function(item) {
return _c('el-checkbox', {
key: item[_vm.keyProp],
staticClass: "el-transfer-panel__item",
attrs: {
"label": item[_vm.keyProp],
"disabled": item[_vm.disabledProp]
}
}, [_c('option-content', {
attrs: {
"option": item
}
})], 1)
})), _c('p', {
directives: [{
name: "show",
rawName: "v-show",
value: (_vm.hasNoMatch),
expression: "hasNoMatch"
}],
staticClass: "el-transfer-panel__empty"
}, [_vm._v(_vm._s(_vm.t('el.transfer.noMatch')))]), _c('p', {
directives: [{
name: "show",
rawName: "v-show",
value: (_vm.data.length === 0 && !_vm.hasNoMatch),
expression: "data.length === 0 && !hasNoMatch"
}],
staticClass: "el-transfer-panel__empty"
}, [_vm._v(_vm._s(_vm.t('el.transfer.noData')))])], 1), _c('p', {
staticClass: "el-transfer-panel__footer"
}, [_c('el-checkbox', {
attrs: {
"indeterminate": _vm.isIndeterminate
},
on: {
"change": _vm.handleAllCheckedChange
},
model: {
value: (_vm.allChecked),
callback: function($$v) {
_vm.allChecked = $$v
},
expression: "allChecked"
}
}, [_vm._v(_vm._s(_vm.checkedSummary))]), _vm._t("default")], 2)])
},staticRenderFns: []}
/***/ }),
/***/ 367:
/***/ (function(module, exports) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _c('div', {
staticClass: "el-transfer"
}, [_c('transfer-panel', _vm._b({
attrs: {
"data": _vm.sourceData,
"title": _vm.titles[0] || _vm.t('el.transfer.titles.0'),
"default-checked": _vm.leftDefaultChecked,
"placeholder": _vm.filterPlaceholder || _vm.t('el.transfer.filterPlaceholder')
},
on: {
"checked-change": _vm.onSourceCheckedChange
}
}, 'transfer-panel', _vm.$props, false), [_vm._t("left-footer")], 2), _c('div', {
staticClass: "el-transfer__buttons"
}, [_c('el-button', {
attrs: {
"type": "primary",
"size": "small",
"disabled": _vm.rightChecked.length === 0
},
nativeOn: {
"click": function($event) {
_vm.addToLeft($event)
}
}
}, [_c('i', {
staticClass: "el-icon-arrow-left"
}), (_vm.buttonTexts[0] !== undefined) ? _c('span', [_vm._v(_vm._s(_vm.buttonTexts[0]))]) : _vm._e()]), _c('el-button', {
attrs: {
"type": "primary",
"size": "small",
"disabled": _vm.leftChecked.length === 0
},
nativeOn: {
"click": function($event) {
_vm.addToRight($event)
}
}
}, [(_vm.buttonTexts[1] !== undefined) ? _c('span', [_vm._v(_vm._s(_vm.buttonTexts[1]))]) : _vm._e(), _c('i', {
staticClass: "el-icon-arrow-right"
})])], 1), _c('transfer-panel', _vm._b({
attrs: {
"data": _vm.targetData,
"title": _vm.titles[1] || _vm.t('el.transfer.titles.1'),
"default-checked": _vm.rightDefaultChecked,
"placeholder": _vm.filterPlaceholder || _vm.t('el.transfer.filterPlaceholder')
},
on: {
"checked-change": _vm.onTargetCheckedChange
}
}, 'transfer-panel', _vm.$props, false), [_vm._t("right-footer")], 2)], 1)
},staticRenderFns: []}
/***/ })
/******/ }); |
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [])
|
// https://github.com/ghiculescu/jekyll-table-of-contents
(function($){
$.fn.toc = function(options) {
var defaults = {
noBackToTopLinks: false,
title: '文章目录',
minimumHeaders: 2,
headers: 'h1, h2, h3, h4, h5, h6',
listType: 'ul', // values: [ol|ul]
showEffect: 'show', // values: [show|slideDown|fadeIn|none]
showSpeed: 0 // set to 0 to deactivate effect
},
settings = $.extend(defaults, options);
function fixedEncodeURIComponent (str) {
return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
var headers = $(settings.headers).filter(function() {
// get all headers with an ID
var previousSiblingName = $(this).prev().attr( "name" );
if (!this.id && previousSiblingName) {
this.id = $(this).attr( "id", previousSiblingName.replace(/\./g, "-") );
}
return this.id;
}), output = $(this);
if (!headers.length || headers.length < settings.minimumHeaders || !output.length) {
$(this).hide();
$('.post-directory-title').css('display', 'none');
return;
}
if (0 === settings.showSpeed) {
settings.showEffect = 'none';
}
var render = {
show: function() { output.hide().html(html).show(settings.showSpeed); },
slideDown: function() { output.hide().html(html).slideDown(settings.showSpeed); },
fadeIn: function() { output.hide().html(html).fadeIn(settings.showSpeed); },
none: function() { output.html(html); }
};
var get_level = function(ele) { return parseInt(ele.nodeName.replace("H", ""), 10); }
var highest_level = headers.map(function(_, ele) { return get_level(ele); }).get().sort()[0];
var return_to_top = '<i class="icon-arrow-up back-to-top"> </i>';
var level = get_level(headers[0]),
this_level,
html = "<p><strong class=\"toc-title\">" + settings.title + "</strong></p>\n";
html += " <"+settings.listType+" class=\"toc\">";
headers.on('click', function() {
if (!settings.noBackToTopLinks) {
window.location.hash = this.id;
}
})
.addClass('clickable-header')
.each(function(_, header) {
this_level = get_level(header);
if (!settings.noBackToTopLinks && this_level === highest_level) {
$(header).addClass('top-level-header').after(return_to_top);
}
if (this_level === level) {// same level as before; same indenting
html += "<li class=\"toc-item toc-level-" + this_level + "\">";
html += "<a class=\"jumper\" href='#" + fixedEncodeURIComponent(header.id) + "'>";
html += "<span class='toc-text'>" + header.innerHTML + "</span>";
html += "</a>";
} else if (this_level <= level){ // higher level than before; end parent ol
for(i = this_level; i < level; i++) {
html += "</li></"+settings.listType+">"
}
html += "<li class='toc-item toc-level-" + this_level + "'><a class=\"jumper\" href='#" + fixedEncodeURIComponent(header.id) + "'>";
html += "<span class='toc-text'>" + header.innerHTML + "</span>";
html += "</a>";
}
else if (this_level > level) { // lower level than before; expand the previous to contain a ol
for(i = this_level; i > level; i--) {
html += "<"+settings.listType+" class='toc-child'><li class='toc-item toc-level-" + i + "'>"
}
html += "<a class=\"jumper\" href='#" + fixedEncodeURIComponent(header.id) + "'>";
html += "<span class='toc-text'>" + header.innerHTML + "</span>";
html += "</a>";
}
level = this_level; // update for the next one
});
html += "</"+settings.listType+">";
if (!settings.noBackToTopLinks) {
$(document).on('click', '.back-to-top', function() {
$(window).scrollTop(0);
window.location.hash = '';
});
}
render[settings.showEffect]();
};
})(jQuery);
$(document).ready(function(){
$('.post-directory').toc();
var fixmeTop = $('#post-directory-module').offset().top;
var tocSections = $('.clickable-header');
var tocSectionOffsets = [];
var calculateTocSections = function(){
tocSectionOffsets = [];
tocSections.each(function(index, section){
tocSectionOffsets.push(section.offsetTop);
})
}
calculateTocSections();
// Calculates the toc section offsets, which can change as images get loaded
$(window).bind('load', calculateTocSections);
var highlightTocSection = function(){
var highlightIndex = 0;
var sectionsCount = tocSectionOffsets.length;
var currentScroll = $(window).scrollTop();
if (currentScroll+60 > tocSectionOffsets[sectionsCount-1]) {
highlightIndex = sectionsCount;
} else {
for (var i=0; i<sectionsCount; i++) {
if (currentScroll+60 <= tocSectionOffsets[i]) {
highlightIndex = i;
break;
}
}
}
if (highlightIndex == 0) {
highlightIndex += 1;
}
$('.toc-item .jumper').removeClass('on');
$('.toc-item .jumper').eq(highlightIndex-1).addClass('on');
}
highlightTocSection();
var updateTocHeight = function() {
var height = document.documentElement.clientHeight;
height = height || 'auto';
$('.post-directory').css('max-height', height);
}
$(window).scroll(function() {
var currentScroll = $(window).scrollTop();
if (currentScroll >= fixmeTop) {
$('#post-directory-module').css({
top: '0',
position: 'fixed',
width: 'inherit'
});
$('.post-directory').css('overflow', 'auto');
} else {
$('#post-directory-module').css({
position: 'inherit',
width: 'inherit'
});
$('.post-directory').css('overflow', 'hidden');
$('.post-directory').scrollTop(0);
}
highlightTocSection();
});
updateTocHeight();
$(window).on("resize", function() {
updateTocHeight();
});
});
$(".jumper").on("click", function( e ) {
e.preventDefault();
$("body, html").animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 600);
});
|
/**
* Args:
* ["keys"]: string array of current level of object keys
* ["path"]: string array of path from top level object. Order matters: Left -> Right
*
* Pops the correct amount of keys off the path array to go up to the next object. Helper
* funciton for augmentColorObjects()
*
*/
const goToParentKeyInPath = (keys, path) => {
if (keys.some(key => path.includes(key))) {
path = path.splice(0, path.indexOf(path.filter(key => keys.indexOf(key) !== -1)[0]));
}
/**
* spread into an empty array to copy elements since they are passed by reference
* must to do this to allow for recursion
*/
return [...path];
};
/**
* Args:
* {
* {obj}: top level object to search for colors objects to augment.
* [path]?: optional. path from top level object. ordered left to right
* augmentColorFunc(): MUI's theme.palette.augmentColor function
* }
*
* Note: all arguments are bundled in an object to leverage named parameters
*
* Recursively searches for lowest level objects that only have a main color
* and are children of the any of the keys specified in the `modKeys` array.
* Other top level keys are ignored and not traversed. Lowest level objects must
* have a `main` key with a color valid specified to allow for MUI's augmentColor
* funciton to work.
*
* Modifies the object that is passed.
*/
const augmentColorObjects = ({ obj, path = [], augmentColorFunc, modKeys = [] }) => {
const keys = Object.keys(obj);
path = goToParentKeyInPath(keys, path);
/**
* When augmentColor is called it modifies the passed object to have multiple
* keys in addition to `main` such as `light`, `dark`, `contrastText`, etc.
* No need to do the dive checking and updating if it already has happened
*/
if (!keys.includes('light')) {
/**
* If there is a main key then we've reached the bottom and need to update
* the object and recurse back out.
*/
if (keys.includes('main')) {
obj = augmentColorFunc(obj);
} else {
keys.map(subObj => {
/**
* Ensure top level object keys are the ones we want to parse or it's
* already in the path as a parent
* There are many objects in the theme.palette that we don't need to update
*/
if (modKeys.includes(subObj) || modKeys.some(key => path.includes(key))) {
path = goToParentKeyInPath(keys, path);
path.push(subObj);
return augmentColorObjects({ obj: obj[subObj], path, augmentColorFunc, modKeys });
}
// Ignores all other objects we don't care about within the top level object
return null;
});
}
}
return obj;
};
export default augmentColorObjects;
|
var structtesting_1_1internal_1_1_all_of_result7 =
[
[ "type", "structtesting_1_1internal_1_1_all_of_result7.html#a47ab0d670258434b0e65530591948e8c", null ]
]; |
var gulp = require('gulp');
var browserify = require('browserify');
var glob = require('glob');
var source = require('vinyl-source-stream');
var rename = require('gulp-rename');
var estream = require('event-stream');
var template = require('art-template');
var fs = require('fs');
var path = require('path');
var shell = require('shelljs');
var open = require('open');
template.config('base', path.join(__dirname, 'test', 'mocha'));
template.config('extname', '.tpl.html');
var indexTitle = 'Mocha测试';
var indexDir = path.join(__dirname, 'test', 'mocha');
gulp.task('default', function (done) {
console.log('default gulp task');
var scriptFileNames = [];
glob('./test/*.spec.js', function (err, fileEntries) {
if(err) {
done(err);
}
//
var tasks = fileEntries.map(function (fileEntry) {
return browserify(fileEntry)
.bundle()
.pipe(source(fileEntry))
.pipe(rename(function (filePath) {
var fileBasename = filePath.basename;
fileBasename = fileBasename.substring(0, fileBasename.indexOf('.spec'));
fileBasename = fileBasename + '.test';
filePath.dirname = 'browser';
filePath.basename = fileBasename;
filePath.extname = filePath.extname;
scriptFileNames.push(path.join('../browser', fileBasename + filePath.extname).replace(/\\/g, '/'));
})).pipe(gulp.dest('./test'));
});
estream.merge(tasks).on('end', function () {
done.apply(null, arguments);
var templateData = {
pageTitle: indexTitle,
scriptFileNames: scriptFileNames
};
console.log(scriptFileNames);
var indexHtml = template('index', templateData);
fs.writeFileSync(path.join(indexDir, 'index.html'), indexHtml);
//
//shell.cd(__dirname);
//open("http://localhost/test/mocha/index.html");
//
setTimeout(function () {
//shell.exec('http-server -p80');
}, 0);
});
//
});
}); |
'use strict';
var assert = require('assert');
var fs = require('fs');
var os = require('os');
var path = require('path');
var memFs = require('mem-fs');
var mkdirp = require('mkdirp');
var rimraf = require('rimraf');
var through = require('through2');
var editor = require('..');
describe('#commit()', function () {
var fixtureDir = path.join(os.tmpdir(), '/mem-fs-editor-test-fixture');
var output = path.join(os.tmpdir(), '/mem-fs-editor-test');
beforeEach(function(done) {
rimraf.sync(fixtureDir);
var store = memFs.create();
this.fs = editor.create(store);
mkdirp.sync(fixtureDir);
// Create a 100 files to exercise the stream high water mark
var i = 100;
while (i--) {
fs.writeFileSync(path.join(fixtureDir, 'file-' + i + '.txt'), 'foo');
}
this.fs.copy(fixtureDir + '/**', output);
rimraf(output, done);
});
it('triggers callback when done', function (done) {
this.fs.commit(done);
});
it('call filters and update memory model', function (done) {
var called = 0;
var filter = through.obj(function (file, enc, cb) {
called++;
file.contents = new Buffer('modified');
this.push(file)
cb();
});
this.fs.commit([filter], function () {
assert.equal(called, 100);
assert.equal(this.fs.read(path.join(output, 'file-1.txt')), 'modified');
done();
}.bind(this));
});
it('write file to disk', function (done) {
this.fs.commit(function () {
assert(fs.existsSync(path.join(output, 'file-1.txt')));
assert(fs.existsSync(path.join(output, 'file-50.txt')));
assert(fs.existsSync(path.join(output, 'file-99.txt')));
done();
});
});
it('delete file from disk', function (done) {
var file = path.join(output, 'delete.txt');
mkdirp.sync(output);
fs.writeFileSync(file, 'to delete');
this.fs.delete(file);
this.fs.commit(function () {
assert(!fs.existsSync(file));
done();
});
});
it('delete directories from disk', function (done) {
var file = path.join(output, 'nested/delete.txt');
mkdirp.sync(path.join(output, 'nested'));
fs.writeFileSync(file, 'to delete');
this.fs.delete(path.join(output, 'nested'));
this.fs.commit(function () {
assert(!fs.existsSync(file));
done();
});
});
it('reset file status after commiting', function (done) {
this.fs.commit(function () {
assert.equal(this.fs.store.get(path.join(output, '/file-a.txt')).state, undefined);
done();
}.bind(this));
});
});
|
const test = require('ava');
const { TestSubjectMocker, Mock } = require('../index');
const testSubjectPath = './TestProj/subject';
const dep1Path = './TestProj/dependency1';
const dep2Path = './TestProj/dependency2';
const arrayPath = './TestProj/arrayDependency';
const constructorPath = './TestProj/constructorDependency.js';
const functionPath = './TestProj/functionDependency';
const objectPath = './TestProj/objectDependency';
const valuePath = './TestProj/valueDependency';
const makeDepValAssertion = (testContext, testSubject, dep1Val, dep2Val) => {
testContext.truthy(testSubject.dependency1() === dep1Val);
testContext.truthy(testSubject.dependency2() === dep2Val);
};
test('Module path required', t => {
t.throws(
() => {
TestSubjectMocker();
}
);
});
test('Relative path rejected', t => {
t.throws(
() => {
TestSubjectMocker('./relative/path.js');
}
);
});
test('No overrides preserves non-mocked behavior', t => {
try {
const testSubjectMocker = new TestSubjectMocker(testSubjectPath);
makeDepValAssertion(t, testSubjectMocker.generateSubject(), 1, 2);
} catch (err) {
console.log(err);
}
});
test('Single mock default functionality', t => {
const mock1 = new Mock(dep1Path, () => 3);
const testSubjectMocker = new TestSubjectMocker(testSubjectPath, mock1);
makeDepValAssertion(t, testSubjectMocker.generateSubject(), 3, 2);
});
test('Mock array default functionality', t => {
const mock1 = new Mock(dep1Path, () => 3);
const mock2 = new Mock(dep2Path, () => 4);
const testSubjectMocker = new TestSubjectMocker(testSubjectPath, [mock1, mock2]);
makeDepValAssertion(t, testSubjectMocker.generateSubject(), 3, 4);
});
test('Different data types', t => {
const arr = [1, 2, 3, 4, 5];
const obj = {a: 2};
const val = 2;
const pathValMappings = [
[arrayPath, arr, []],
[constructorPath, function () { this.a = val; }, function () { this.a = 0; }],
[functionPath, () => val, () => val],
[objectPath, obj, {a: 0}],
[valuePath, val, 0]
];
const mocks = pathValMappings.map(mapping => {
return new Mock(mapping[0], mapping[1]);
});
const validate = (subject) => {
t.deepEqual(subject.arrayDependency, arr);
t.deepEqual((new subject.ConstructorDependency()).a, val);
t.deepEqual(subject.functionDependency(), val);
t.deepEqual(subject.objectDependency.a, val);
t.deepEqual(subject.valueDependency, val);
};
const defaultMockSubject = (new TestSubjectMocker(testSubjectPath, mocks)).generateSubject();
const overrideMockSubject = (new TestSubjectMocker(testSubjectPath)).generateSubject(mocks);
validate(defaultMockSubject);
validate(overrideMockSubject);
const defaultMocks = pathValMappings.map(mapping => {
return new Mock(mapping[0], mapping[2]);
});
const overrideDefaultMockSubject = (new TestSubjectMocker(testSubjectPath, defaultMocks)).generateSubject(mocks);
validate(overrideDefaultMockSubject);
});
test('Clear mocks', t => {
const mock1 = new Mock(dep1Path, () => 3);
const mock2 = new Mock(dep2Path, () => 4);
const testSubjectMocker = new TestSubjectMocker(testSubjectPath);
makeDepValAssertion(t, testSubjectMocker.generateSubject([mock1, mock2]), 3, 4);
testSubjectMocker.clearMocks();
makeDepValAssertion(t, testSubjectMocker.generateSubject(), 1, 2);
});
|
var Icon = require('../icon');
var element = require('magic-virtual-element');
var clone = require('../clone');
exports.render = function render(component) {
var props = clone(component.props);
delete props.children;
return element(
Icon,
props,
element('path', { d: 'M16.24 7.76C15.07 6.59 13.54 6 12 6v6l-4.24 4.24c2.34 2.34 6.14 2.34 8.49 0 2.34-2.34 2.34-6.14-.01-8.48zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z' })
);
}; |
var app = app || {};
app.Book = Backbone.Model.extend({
defaults: {
coverImage: 'img/placeholder.png',
title: 'No title',
author: 'Unknown',
releaseDate: 'Unknown',
keywords: 'None'
},
parse: function( response ) {
response.id = response._id;
return response;
}
}); |
import { MESSAGE_RECEIVED } from '../actions';
const initialState = {
list: [],
entities: {},
};
export const messages = (state = initialState, action) => {
switch (action.type) {
case MESSAGE_RECEIVED:
return {
...state,
list: [...state.list, action.payload.id],
entities: { ...state.entities, [action.payload.id]: action.payload },
};
default:
return state;
}
};
const getAllMessages = state =>
state.messages.list.map(itemId => state.messages.entities[itemId]);
export const getMessages = (state, filter) => {
const allMessages = getAllMessages(state);
switch (filter) {
case 'all':
return allMessages;
case 'info':
return allMessages.filter(message => message.type === 'info');
case 'error':
return allMessages.filter(message => message.type === 'error');
default:
throw new Error(`Unknown filter ${filter}`);
}
};
|
'use strict';
const Promise = require('bluebird');
const Scraper = require('./lib/scraper.js');
module.exports = (options, callback) => {
return Promise.try(() => {
return new Scraper(options).scrape(callback);
});
};
module.exports.defaults = Scraper.defaults;
|
__history = [{"date":"Mon, 21 Sep 2015 15:44:31 GMT","sloc":40,"lloc":7,"functions":3,"deliveredBugs":0.07739760316291208,"maintainability":84.30882304461832,"lintErrors":[],"difficulty":5.25},{"date":"Mon, 21 Sep 2015 16:02:39 GMT","sloc":40,"lloc":7,"functions":3,"deliveredBugs":0.07739760316291208,"maintainability":84.30882304461832,"lintErrors":[],"difficulty":5.25},{"date":"Mon, 21 Sep 2015 16:16:12 GMT","sloc":40,"lloc":7,"functions":3,"deliveredBugs":0.07739760316291208,"maintainability":84.30882304461832,"lintErrors":[],"difficulty":5.25},{"date":"Mon, 21 Sep 2015 16:17:37 GMT","sloc":40,"lloc":7,"functions":3,"deliveredBugs":0.07739760316291208,"maintainability":84.30882304461832,"lintErrors":[],"difficulty":5.25}] |
/* global describe, it, beforeEach, afterEach */
/*!
* The MIT License (MIT)
*
* Copyright (c) 2019 Mark van Seventer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// @see https://sharp.pixelplumbing.com/en/stable/api-colour/#tint
// Strict mode.
'use strict'
// Package modules.
const expect = require('must')
const sinon = require('sinon')
const Yargs = require('yargs')
// Local modules.
const queue = require('../../../lib/queue')
const sharp = require('../../mocks/sharp')
const tint = require('../../../cmd/colour-manipulation/tint')
// Test suite.
describe('tint <rgb>', () => {
const cli = (new Yargs()).command(tint)
// Default rgb.
const rgb = 'rgba(0,0,0)'
// Reset.
afterEach('queue', () => queue.splice(0))
afterEach('sharp', sharp.prototype.reset)
// Run.
beforeEach((done) => cli.parse(['tint', rgb], done))
// Tests.
it('must set the colourspace flag', () => {
expect(cli.parsed.argv).to.have.property('rgb', rgb)
})
it('must update the pipeline', () => {
expect(queue.pipeline).to.have.length(1)
expect(queue.pipeline).to.include('tint')
})
it('must execute the pipeline', () => {
const pipeline = queue.drain(sharp())
sinon.assert.called(pipeline.tint)
})
})
|
var clv = require("../../../../index.js");
var assert = require("assert");
describe("Generated test - rm/rm/undo/rm/ins/rm/undo/ins/rm/undo - 10-ops-8acd8242-df34-4d85-91e5-86da219ce5ba", function() {
var doc1 = new clv.string.Document("812d9e90-5327-11e7-a6c7-cf7652268eec", 0, null);
var doc2 = new clv.string.Document("812f9a60-5327-11e7-a6c7-cf7652268eec", 0, null);
var data1 = "Hello World";
var data2 = "Hello World";
var serverData = {"id":"301bfa16-a2de-47b9-bb9f-752daccfe83a","data":"Hello World","ops":[],"execOrder":0,"context":null};
it("Site 812d9e90-5327-11e7-a6c7-cf7652268eec operations should be executed without errors", function() {
var commit1 = [{"type":1,"at":4,"value":"o"}];
var commitTuple1 = doc1.commit(commit1);
data1 = clv.string.exec(data1, commitTuple1.toExec);
var commit2 = [{"type":1,"at":3,"value":"l"}];
var commitTuple2 = doc1.commit(commit2);
data1 = clv.string.exec(data1, commitTuple2.toExec);
var update1 = [{"siteId":"812f9a60-5327-11e7-a6c7-cf7652268eec","seqId":1,"context":{"vector":{},"size":0},"invCount":0,"load":{"type":1,"at":8,"value":"rl"},"execOrder":1},{"siteId":"812d9e90-5327-11e7-a6c7-cf7652268eec","seqId":1,"context":{"vector":{},"size":0},"invCount":0,"load":{"type":1,"at":4,"value":"o"},"execOrder":2}];
var updateTuple1 = doc1.update(update1);
data1 = clv.string.exec(data1, updateTuple1.toExec);
var update2 = [{"siteId":"812d9e90-5327-11e7-a6c7-cf7652268eec","seqId":2,"context":{"vector":{"812d9e90-5327-11e7-a6c7-cf7652268eec":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":1},"invCount":0,"load":{"type":1,"at":3,"value":"l"},"execOrder":3}];
var updateTuple2 = doc1.update(update2);
data1 = clv.string.exec(data1, updateTuple2.toExec);
var update3 = [{"siteId":"812f9a60-5327-11e7-a6c7-cf7652268eec","seqId":1,"context":{"vector":{"812f9a60-5327-11e7-a6c7-cf7652268eec":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":1},"invCount":1,"load":{"type":0,"at":8,"value":"rl"},"execOrder":4}];
var updateTuple3 = doc1.update(update3);
data1 = clv.string.exec(data1, updateTuple3.toExec);
var commitTuple3 = doc1.undo();
data1 = clv.string.exec(data1, commitTuple3.toExec);
var update4 = [{"siteId":"812f9a60-5327-11e7-a6c7-cf7652268eec","seqId":2,"context":{"vector":{"812f9a60-5327-11e7-a6c7-cf7652268eec":{"seqId":1,"invCluster":{"1":1},"invClusterSize":1},"812d9e90-5327-11e7-a6c7-cf7652268eec":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":0,"at":8,"value":"tr"},"execOrder":5},{"siteId":"812d9e90-5327-11e7-a6c7-cf7652268eec","seqId":2,"context":{"vector":{"812d9e90-5327-11e7-a6c7-cf7652268eec":{"seqId":2,"invCluster":{},"invClusterSize":0}},"size":1},"invCount":1,"load":{"type":0,"at":3,"value":"l"},"execOrder":6}];
var updateTuple4 = doc1.update(update4);
data1 = clv.string.exec(data1, updateTuple4.toExec);
var commit4 = [{"type":1,"at":3,"value":"l"}];
var commitTuple4 = doc1.commit(commit4);
data1 = clv.string.exec(data1, commitTuple4.toExec);
var commit5 = [{"type":0,"at":2,"value":"yeq"}];
var commitTuple5 = doc1.commit(commit5);
data1 = clv.string.exec(data1, commitTuple5.toExec);
var update5 = [{"siteId":"812f9a60-5327-11e7-a6c7-cf7652268eec","seqId":3,"context":{"vector":{"812f9a60-5327-11e7-a6c7-cf7652268eec":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1},"812d9e90-5327-11e7-a6c7-cf7652268eec":{"seqId":2,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":1,"at":0,"value":"H"},"execOrder":7},{"siteId":"812d9e90-5327-11e7-a6c7-cf7652268eec","seqId":3,"context":{"vector":{"812d9e90-5327-11e7-a6c7-cf7652268eec":{"seqId":2,"invCluster":{"2":1},"invClusterSize":1},"812f9a60-5327-11e7-a6c7-cf7652268eec":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":1,"at":3,"value":"l"},"execOrder":8}];
var updateTuple5 = doc1.update(update5);
data1 = clv.string.exec(data1, updateTuple5.toExec);
var update6 = [{"siteId":"812d9e90-5327-11e7-a6c7-cf7652268eec","seqId":4,"context":{"vector":{"812d9e90-5327-11e7-a6c7-cf7652268eec":{"seqId":3,"invCluster":{"2":1},"invClusterSize":1},"812f9a60-5327-11e7-a6c7-cf7652268eec":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":0,"at":2,"value":"yeq"},"execOrder":9}];
var updateTuple6 = doc1.update(update6);
data1 = clv.string.exec(data1, updateTuple6.toExec);
var update7 = [{"siteId":"812f9a60-5327-11e7-a6c7-cf7652268eec","seqId":3,"context":{"vector":{"812f9a60-5327-11e7-a6c7-cf7652268eec":{"seqId":3,"invCluster":{"1":1},"invClusterSize":1},"812d9e90-5327-11e7-a6c7-cf7652268eec":{"seqId":2,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":1,"load":{"type":0,"at":0,"value":"H"},"execOrder":10}];
var updateTuple7 = doc1.update(update7);
data1 = clv.string.exec(data1, updateTuple7.toExec);
});
it("Site 812f9a60-5327-11e7-a6c7-cf7652268eec operations should be executed without errors", function() {
var commit1 = [{"type":1,"at":8,"value":"rl"}];
var commitTuple1 = doc2.commit(commit1);
data2 = clv.string.exec(data2, commitTuple1.toExec);
var update1 = [{"siteId":"812f9a60-5327-11e7-a6c7-cf7652268eec","seqId":1,"context":{"vector":{},"size":0},"invCount":0,"load":{"type":1,"at":8,"value":"rl"},"execOrder":1}];
var updateTuple1 = doc2.update(update1);
data2 = clv.string.exec(data2, updateTuple1.toExec);
var commitTuple2 = doc2.undo();
data2 = clv.string.exec(data2, commitTuple2.toExec);
var update2 = [{"siteId":"812d9e90-5327-11e7-a6c7-cf7652268eec","seqId":1,"context":{"vector":{},"size":0},"invCount":0,"load":{"type":1,"at":4,"value":"o"},"execOrder":2}];
var updateTuple2 = doc2.update(update2);
data2 = clv.string.exec(data2, updateTuple2.toExec);
var commit3 = [{"type":0,"at":8,"value":"tr"}];
var commitTuple3 = doc2.commit(commit3);
data2 = clv.string.exec(data2, commitTuple3.toExec);
var update3 = [{"siteId":"812d9e90-5327-11e7-a6c7-cf7652268eec","seqId":2,"context":{"vector":{"812d9e90-5327-11e7-a6c7-cf7652268eec":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":1},"invCount":0,"load":{"type":1,"at":3,"value":"l"},"execOrder":3},{"siteId":"812f9a60-5327-11e7-a6c7-cf7652268eec","seqId":1,"context":{"vector":{"812f9a60-5327-11e7-a6c7-cf7652268eec":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":1},"invCount":1,"load":{"type":0,"at":8,"value":"rl"},"execOrder":4}];
var updateTuple3 = doc2.update(update3);
data2 = clv.string.exec(data2, updateTuple3.toExec);
var update4 = [{"siteId":"812f9a60-5327-11e7-a6c7-cf7652268eec","seqId":2,"context":{"vector":{"812f9a60-5327-11e7-a6c7-cf7652268eec":{"seqId":1,"invCluster":{"1":1},"invClusterSize":1},"812d9e90-5327-11e7-a6c7-cf7652268eec":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":0,"at":8,"value":"tr"},"execOrder":5}];
var updateTuple4 = doc2.update(update4);
data2 = clv.string.exec(data2, updateTuple4.toExec);
var commit4 = [{"type":1,"at":0,"value":"H"}];
var commitTuple4 = doc2.commit(commit4);
data2 = clv.string.exec(data2, commitTuple4.toExec);
var update5 = [{"siteId":"812d9e90-5327-11e7-a6c7-cf7652268eec","seqId":2,"context":{"vector":{"812d9e90-5327-11e7-a6c7-cf7652268eec":{"seqId":2,"invCluster":{},"invClusterSize":0}},"size":1},"invCount":1,"load":{"type":0,"at":3,"value":"l"},"execOrder":6},{"siteId":"812f9a60-5327-11e7-a6c7-cf7652268eec","seqId":3,"context":{"vector":{"812f9a60-5327-11e7-a6c7-cf7652268eec":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1},"812d9e90-5327-11e7-a6c7-cf7652268eec":{"seqId":2,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":1,"at":0,"value":"H"},"execOrder":7}];
var updateTuple5 = doc2.update(update5);
data2 = clv.string.exec(data2, updateTuple5.toExec);
var commitTuple5 = doc2.undo();
data2 = clv.string.exec(data2, commitTuple5.toExec);
var update6 = [{"siteId":"812d9e90-5327-11e7-a6c7-cf7652268eec","seqId":3,"context":{"vector":{"812d9e90-5327-11e7-a6c7-cf7652268eec":{"seqId":2,"invCluster":{"2":1},"invClusterSize":1},"812f9a60-5327-11e7-a6c7-cf7652268eec":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":1,"at":3,"value":"l"},"execOrder":8},{"siteId":"812d9e90-5327-11e7-a6c7-cf7652268eec","seqId":4,"context":{"vector":{"812d9e90-5327-11e7-a6c7-cf7652268eec":{"seqId":3,"invCluster":{"2":1},"invClusterSize":1},"812f9a60-5327-11e7-a6c7-cf7652268eec":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":0,"at":2,"value":"yeq"},"execOrder":9}];
var updateTuple6 = doc2.update(update6);
data2 = clv.string.exec(data2, updateTuple6.toExec);
var update7 = [{"siteId":"812f9a60-5327-11e7-a6c7-cf7652268eec","seqId":3,"context":{"vector":{"812f9a60-5327-11e7-a6c7-cf7652268eec":{"seqId":3,"invCluster":{"1":1},"invClusterSize":1},"812d9e90-5327-11e7-a6c7-cf7652268eec":{"seqId":2,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":1,"load":{"type":0,"at":0,"value":"H"},"execOrder":10}];
var updateTuple7 = doc2.update(update7);
data2 = clv.string.exec(data2, updateTuple7.toExec);
});
it("Server operations should be executed without errors", function() {
function updateServer(op) {
var server = new clv.string.Document(null, serverData.execOrder, serverData.context);
server.update(serverData.ops);
var serverTuple = server.update(op);
serverData.data = clv.string.exec(serverData.data, serverTuple.toExec);
serverData.context = server.getContext();
serverData.ops.push(op);
serverData.execOrder = server.getExecOrder();
}
var serverUpdate0 = {"siteId":"812f9a60-5327-11e7-a6c7-cf7652268eec","seqId":1,"context":{"vector":{},"size":0},"invCount":0,"load":{"type":1,"at":8,"value":"rl"},"execOrder":1};
updateServer(serverUpdate0);
var serverUpdate1 = {"siteId":"812d9e90-5327-11e7-a6c7-cf7652268eec","seqId":1,"context":{"vector":{},"size":0},"invCount":0,"load":{"type":1,"at":4,"value":"o"},"execOrder":2};
updateServer(serverUpdate1);
var serverUpdate2 = {"siteId":"812d9e90-5327-11e7-a6c7-cf7652268eec","seqId":2,"context":{"vector":{"812d9e90-5327-11e7-a6c7-cf7652268eec":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":1},"invCount":0,"load":{"type":1,"at":3,"value":"l"},"execOrder":3};
updateServer(serverUpdate2);
var serverUpdate3 = {"siteId":"812f9a60-5327-11e7-a6c7-cf7652268eec","seqId":1,"context":{"vector":{"812f9a60-5327-11e7-a6c7-cf7652268eec":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":1},"invCount":1,"load":{"type":0,"at":8,"value":"rl"},"execOrder":4};
updateServer(serverUpdate3);
var serverUpdate4 = {"siteId":"812f9a60-5327-11e7-a6c7-cf7652268eec","seqId":2,"context":{"vector":{"812f9a60-5327-11e7-a6c7-cf7652268eec":{"seqId":1,"invCluster":{"1":1},"invClusterSize":1},"812d9e90-5327-11e7-a6c7-cf7652268eec":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":0,"at":8,"value":"tr"},"execOrder":5};
updateServer(serverUpdate4);
var serverUpdate5 = {"siteId":"812d9e90-5327-11e7-a6c7-cf7652268eec","seqId":2,"context":{"vector":{"812d9e90-5327-11e7-a6c7-cf7652268eec":{"seqId":2,"invCluster":{},"invClusterSize":0}},"size":1},"invCount":1,"load":{"type":0,"at":3,"value":"l"},"execOrder":6};
updateServer(serverUpdate5);
var serverUpdate6 = {"siteId":"812f9a60-5327-11e7-a6c7-cf7652268eec","seqId":3,"context":{"vector":{"812f9a60-5327-11e7-a6c7-cf7652268eec":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1},"812d9e90-5327-11e7-a6c7-cf7652268eec":{"seqId":2,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":1,"at":0,"value":"H"},"execOrder":7};
updateServer(serverUpdate6);
var serverUpdate7 = {"siteId":"812d9e90-5327-11e7-a6c7-cf7652268eec","seqId":3,"context":{"vector":{"812d9e90-5327-11e7-a6c7-cf7652268eec":{"seqId":2,"invCluster":{"2":1},"invClusterSize":1},"812f9a60-5327-11e7-a6c7-cf7652268eec":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":1,"at":3,"value":"l"},"execOrder":8};
updateServer(serverUpdate7);
var serverUpdate8 = {"siteId":"812d9e90-5327-11e7-a6c7-cf7652268eec","seqId":4,"context":{"vector":{"812d9e90-5327-11e7-a6c7-cf7652268eec":{"seqId":3,"invCluster":{"2":1},"invClusterSize":1},"812f9a60-5327-11e7-a6c7-cf7652268eec":{"seqId":2,"invCluster":{"1":1},"invClusterSize":1}},"size":2},"invCount":0,"load":{"type":0,"at":2,"value":"yeq"},"execOrder":9};
updateServer(serverUpdate8);
var serverUpdate9 = {"siteId":"812f9a60-5327-11e7-a6c7-cf7652268eec","seqId":3,"context":{"vector":{"812f9a60-5327-11e7-a6c7-cf7652268eec":{"seqId":3,"invCluster":{"1":1},"invClusterSize":1},"812d9e90-5327-11e7-a6c7-cf7652268eec":{"seqId":2,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":1,"load":{"type":0,"at":0,"value":"H"},"execOrder":10};
updateServer(serverUpdate9);
});
it("All sites should have same data with the server", function() {
assert.equal(data1, serverData.data, "Site 1 data should be equal to server");
assert.equal(data2, serverData.data, "Site 2 data should be equal to server");
});
});
|
import WebpackHotMiddleware from 'webpack-hot-middleware'
import applyExpressMiddleware from '../utils/apply-express-middleware'
import _debug from 'debug'
const debug = _debug('app:server:webpack-hmr')
export default function (compiler, opts) {
debug('Enable Webpack Hot Module Replacement (HMR).')
const middleware = WebpackHotMiddleware(compiler, opts)
return async function koaWebpackHMR (ctx, next) {
let hasNext = await applyExpressMiddleware(middleware, ctx.req, ctx.res)
if (hasNext && next) {
await next()
}
}
}
|
// {{ License }}
;(function() {
function bootstrap(redeyed, exports) {
'use strict'
// {{ spans }}
// {{ default-theme }}
function resolveTheme() {
throw new Error('Resolving a theme by filename only works server side. \n' +
'Manually resolve or create a theme {Object} and pass that to "highlight" instead.')
}
// {{ peacock-highlight }}
return { highlight: highlight }
}
if (typeof define === 'function' && define.amd) {
// amd
define(['redeyed'], function(redeyed) {
return bootstrap(redeyed)
})
} else if (typeof window === 'object') {
// no amd -> attach to window if it exists
// Note that this requires 'redeyed' to be defined on the window which in turn requires 'esprima'
// Therefore those scripts have to be loaded first
window.peacock = bootstrap(window.redeyed)
}
})()
|
Subsets and Splits