code stringlengths 2 1.05M |
|---|
const _ = require('underscore');
const DrawCard = require('../../drawcard.js');
const { Locations, CardTypes } = require('../../Constants');
const testOfSkillCost = function() {
return {
action: { name: 'testOfSkillCost', getCostMessage: () => ['naming {0}', []] },
canPay: function() {
return true;
},
resolve: function(context, result = { resolved: false }) {
let choices = [CardTypes.Attachment, CardTypes.Character, CardTypes.Event];
context.game.promptWithHandlerMenu(context.player, {
activePromptTitle: 'Select a card type',
context: context,
choices: choices,
handlers: _.map(choices, choice => {
return () => {
context.costs.testOfSkillCost = choice;
result.value = true;
result.resolved = true;
};
})
});
return result;
},
pay: function() {
}
};
};
class TestOfSkill extends DrawCard {
setupCardAbilities(ability) {
this.action({
title: 'Reveal cards and take ones matching named type',
condition: context => context.player.conflictDeck.size() >= (context.player.cardsInPlay.some(card => card.hasTrait('duelist')) ? 4 : 3),
cost: [ability.costs.reveal(context => context.player.conflictDeck.first(
context.player.cardsInPlay.some(card => card.hasTrait('duelist')) ? 4 : 3
)), testOfSkillCost()],
cannotBeMirrored: true,
effect: 'take cards into their hand',
handler: context => {
let [matchingCards, cardsToDiscard] = _.partition(context.costs.reveal, card => card.type === context.costs.testOfSkillCost && card.location === Locations.ConflictDeck);
//Handle situations where card is played from deck, such as with pillow book
matchingCards = _.reject(matchingCards, c=> c.uuid === context.source.uuid);
let discardHandler = () => {
cardsToDiscard = cardsToDiscard.concat(matchingCards);
this.game.addMessage('{0} discards {1}', context.player, cardsToDiscard);
_.each(cardsToDiscard, card => {
context.player.moveCard(card, Locations.ConflictDiscardPile);
});
};
let takeCardHandler = card => {
this.game.addMessage('{0} adds {1} to their hand', context.player, card);
context.player.moveCard(card, Locations.Hand);
return _.reject(matchingCards, c => c.uuid === card.uuid);
};
if(matchingCards.length === 0) {
return discardHandler();
}
this.game.promptWithHandlerMenu(context.player, {
activePromptTitle: 'Select a card',
context: context,
cards: matchingCards,
cardHandler: card => {
matchingCards = takeCardHandler(card);
if(matchingCards.length === 0) {
return discardHandler();
}
this.game.promptWithHandlerMenu(context.player, {
activePromptTitle: 'Select a card',
context: context,
cards: matchingCards,
cardHandler: card => {
matchingCards = takeCardHandler(card);
discardHandler();
},
choices: ['Done'],
handlers: [discardHandler]
});
},
choices: ['Done'],
handlers: [discardHandler]
});
}
});
}
}
TestOfSkill.id = 'test-of-skill';
module.exports = TestOfSkill;
|
YUI.add('router', function (Y, NAME) {
/**
Provides URL-based routing using HTML5 `pushState()` or the location hash.
@module app
@submodule router
@since 3.4.0
**/
var HistoryHash = Y.HistoryHash,
QS = Y.QueryString,
YArray = Y.Array,
YLang = Y.Lang,
YObject = Y.Object,
win = Y.config.win,
// Holds all the active router instances. This supports the static
// `dispatch()` method which causes all routers to dispatch.
instances = [],
// We have to queue up pushState calls to avoid race conditions, since the
// popstate event doesn't actually provide any info on what URL it's
// associated with.
saveQueue = [],
/**
Fired when the router is ready to begin dispatching to route handlers.
You shouldn't need to wait for this event unless you plan to implement some
kind of custom dispatching logic. It's used internally in order to avoid
dispatching to an initial route if a browser history change occurs first.
@event ready
@param {Boolean} dispatched `true` if routes have already been dispatched
(most likely due to a history change).
@fireOnce
**/
EVT_READY = 'ready';
/**
Provides URL-based routing using HTML5 `pushState()` or the location hash.
This makes it easy to wire up route handlers for different application states
while providing full back/forward navigation support and bookmarkable, shareable
URLs.
@class Router
@param {Object} [config] Config properties.
@param {Boolean} [config.html5] Overrides the default capability detection
and forces this router to use (`true`) or not use (`false`) HTML5
history.
@param {String} [config.root=''] Root path from which all routes should be
evaluated.
@param {Array} [config.routes=[]] Array of route definition objects.
@constructor
@extends Base
@since 3.4.0
**/
function Router() {
Router.superclass.constructor.apply(this, arguments);
}
Y.Router = Y.extend(Router, Y.Base, {
// -- Protected Properties -------------------------------------------------
/**
Whether or not `_dispatch()` has been called since this router was
instantiated.
@property _dispatched
@type Boolean
@default undefined
@protected
**/
/**
Whether or not we're currently in the process of dispatching to routes.
@property _dispatching
@type Boolean
@default undefined
@protected
**/
/**
History event handle for the `history:change` or `hashchange` event
subscription.
@property _historyEvents
@type EventHandle
@protected
**/
/**
Cached copy of the `html5` attribute for internal use.
@property _html5
@type Boolean
@protected
**/
/**
Map which holds the registered param handlers in the form:
`name` -> RegExp | Function.
@property _params
@type Object
@protected
@since 3.12.0
**/
/**
Whether or not the `ready` event has fired yet.
@property _ready
@type Boolean
@default undefined
@protected
**/
/**
Regex used to break up a URL string around the URL's path.
Subpattern captures:
1. Origin, everything before the URL's path-part.
2. The URL's path-part.
3. The URL's query.
4. The URL's hash fragment.
@property _regexURL
@type RegExp
@protected
@since 3.5.0
**/
_regexURL: /^((?:[^\/#?:]+:\/\/|\/\/)[^\/]*)?([^?#]*)(\?[^#]*)?(#.*)?$/,
/**
Regex used to match parameter placeholders in route paths.
Subpattern captures:
1. Parameter prefix character. Either a `:` for subpath parameters that
should only match a single level of a path, or `*` for splat parameters
that should match any number of path levels.
2. Parameter name, if specified, otherwise it is a wildcard match.
@property _regexPathParam
@type RegExp
@protected
**/
_regexPathParam: /([:*])([\w\-]+)?/g,
/**
Regex that matches and captures the query portion of a URL, minus the
preceding `?` character, and discarding the hash portion of the URL if any.
@property _regexUrlQuery
@type RegExp
@protected
**/
_regexUrlQuery: /\?([^#]*).*$/,
/**
Regex that matches everything before the path portion of a URL (the origin).
This will be used to strip this part of the URL from a string when we
only want the path.
@property _regexUrlOrigin
@type RegExp
@protected
**/
_regexUrlOrigin: /^(?:[^\/#?:]+:\/\/|\/\/)[^\/]*/,
/**
Collection of registered routes.
@property _routes
@type Array
@protected
**/
// -- Lifecycle Methods ----------------------------------------------------
initializer: function (config) {
var self = this;
self._html5 = self.get('html5');
self._params = {};
self._routes = [];
self._url = self._getURL();
// Necessary because setters don't run on init.
self._setRoutes(config && config.routes ? config.routes :
self.get('routes'));
// Set up a history instance or hashchange listener.
if (self._html5) {
self._history = new Y.HistoryHTML5({force: true});
self._historyEvents =
Y.after('history:change', self._afterHistoryChange, self);
} else {
self._historyEvents =
Y.on('hashchange', self._afterHistoryChange, win, self);
}
// Fire a `ready` event once we're ready to route. We wait first for all
// subclass initializers to finish, then for window.onload, and then an
// additional 20ms to allow the browser to fire a useless initial
// `popstate` event if it wants to (and Chrome always wants to).
self.publish(EVT_READY, {
defaultFn : self._defReadyFn,
fireOnce : true,
preventable: false
});
self.once('initializedChange', function () {
Y.once('load', function () {
setTimeout(function () {
self.fire(EVT_READY, {dispatched: !!self._dispatched});
}, 20);
});
});
// Store this router in the collection of all active router instances.
instances.push(this);
},
destructor: function () {
var instanceIndex = YArray.indexOf(instances, this);
// Remove this router from the collection of active router instances.
if (instanceIndex > -1) {
instances.splice(instanceIndex, 1);
}
if (this._historyEvents) {
this._historyEvents.detach();
}
},
// -- Public Methods -------------------------------------------------------
/**
Dispatches to the first route handler that matches the current URL, if any.
If `dispatch()` is called before the `ready` event has fired, it will
automatically wait for the `ready` event before dispatching. Otherwise it
will dispatch immediately.
@method dispatch
@chainable
**/
dispatch: function () {
this.once(EVT_READY, function () {
var req, res;
this._ready = true;
if (!this.upgrade()) {
req = this._getRequest('dispatch');
res = this._getResponse(req);
this._dispatch(req, res);
}
});
return this;
},
/**
Gets the current route path.
@method getPath
@return {String} Current route path.
**/
getPath: function () {
return this._getPath();
},
/**
Returns `true` if this router has at least one route that matches the
specified URL, `false` otherwise. This also checks that any named `param`
handlers also accept app param values in the `url`.
This method enforces the same-origin security constraint on the specified
`url`; any URL which is not from the same origin as the current URL will
always return `false`.
@method hasRoute
@param {String} url URL to match.
@return {Boolean} `true` if there's at least one matching route, `false`
otherwise.
**/
hasRoute: function (url) {
var path, routePath, routes;
if (!this._hasSameOrigin(url)) {
return false;
}
if (!this._html5) {
url = this._upgradeURL(url);
}
// Get just the path portion of the specified `url`. The `match()`
// method does some special checking that the `path` is within the root.
path = this.removeQuery(url.replace(this._regexUrlOrigin, ''));
routes = this.match(path);
if (!routes.length) {
return false;
}
routePath = this.removeRoot(path);
// Check that there's at least one route whose param handlers also
// accept all the param values.
return !!YArray.filter(routes, function (route) {
// Get the param values for the route and path to see whether the
// param handlers accept or reject the param values. Include any
// route whose named param handlers accept *all* param values. This
// will return `false` if a param handler rejects a param value.
return this._getParamValues(route, routePath);
}, this).length;
},
/**
Returns an array of route objects that match the specified URL path.
If this router has a `root`, then the specified `path` _must_ be
semantically within the `root` path to match any routes.
This method is called internally to determine which routes match the current
path whenever the URL changes. You may override it if you want to customize
the route matching logic, although this usually shouldn't be necessary.
Each returned route object has the following properties:
* `callback`: A function or a string representing the name of a function
this router that should be executed when the route is triggered.
* `keys`: An array of strings representing the named parameters defined in
the route's path specification, if any.
* `path`: The route's path specification, which may be either a string or
a regex.
* `regex`: A regular expression version of the route's path specification.
This regex is used to determine whether the route matches a given path.
@example
router.route('/foo', function () {});
router.match('/foo');
// => [{callback: ..., keys: [], path: '/foo', regex: ...}]
@method match
@param {String} path URL path to match. This should be an absolute path that
starts with a slash: "/".
@return {Object[]} Array of route objects that match the specified path.
**/
match: function (path) {
var root = this.get('root');
if (root) {
// The `path` must be semantically within this router's `root` path
// or mount point, if it's not then no routes should be considered a
// match.
if (!this._pathHasRoot(root, path)) {
return [];
}
// Remove this router's `root` from the `path` before checking the
// routes for any matches.
path = this.removeRoot(path);
}
return YArray.filter(this._routes, function (route) {
return path.search(route.regex) > -1;
});
},
/**
Adds a handler for a route param specified by _name_.
Param handlers can be registered via this method and are used to
validate/format values of named params in routes before dispatching to the
route's handler functions. Using param handlers allows routes to defined
using string paths which allows for `req.params` to use named params, but
still applying extra validation or formatting to the param values parsed
from the URL.
If a param handler regex or function returns a value of `false`, `null`,
`undefined`, or `NaN`, the current route will not match and be skipped. All
other return values will be used in place of the original param value parsed
from the URL.
@example
router.param('postId', function (value) {
return parseInt(value, 10);
});
router.param('username', /^\w+$/);
router.route('/posts/:postId', function (req) {
Y.log('Post: ' + req.params.id);
});
router.route('/users/:username', function (req) {
// `req.params.username` is an array because the result of calling
// `exec()` on the regex is assigned as the param's value.
Y.log('User: ' + req.params.username[0]);
});
router.route('*', function () {
Y.log('Catch-all no routes matched!');
});
// URLs which match routes:
router.save('/posts/1'); // => "Post: 1"
router.save('/users/ericf'); // => "User: ericf"
// URLs which do not match routes because params fail validation:
router.save('/posts/a'); // => "Catch-all no routes matched!"
router.save('/users/ericf,rgrove'); // => "Catch-all no routes matched!"
@method param
@param {String} name Name of the param used in route paths.
@param {Function|RegExp} handler Function to invoke or regular expression to
`exec()` during route dispatching whose return value is used as the new
param value. Values of `false`, `null`, `undefined`, or `NaN` will cause
the current route to not match and be skipped. When a function is
specified, it will be invoked in the context of this instance with the
following parameters:
@param {String} handler.value The current param value parsed from the URL.
@param {String} handler.name The name of the param.
@chainable
@since 3.12.0
**/
param: function (name, handler) {
this._params[name] = handler;
return this;
},
/**
Removes the `root` URL from the front of _url_ (if it's there) and returns
the result. The returned path will always have a leading `/`.
@method removeRoot
@param {String} url URL.
@return {String} Rootless path.
**/
removeRoot: function (url) {
var root = this.get('root'),
path;
// Strip out the non-path part of the URL, if any (e.g.
// "http://foo.com"), so that we're left with just the path.
url = url.replace(this._regexUrlOrigin, '');
// Return the host-less URL if there's no `root` path to further remove.
if (!root) {
return url;
}
path = this.removeQuery(url);
// Remove the `root` from the `url` if it's the same or its path is
// semantically within the root path.
if (path === root || this._pathHasRoot(root, path)) {
url = url.substring(root.length);
}
return url.charAt(0) === '/' ? url : '/' + url;
},
/**
Removes a query string from the end of the _url_ (if one exists) and returns
the result.
@method removeQuery
@param {String} url URL.
@return {String} Queryless path.
**/
removeQuery: function (url) {
return url.replace(/\?.*$/, '');
},
/**
Replaces the current browser history entry with a new one, and dispatches to
the first matching route handler, if any.
Behind the scenes, this method uses HTML5 `pushState()` in browsers that
support it (or the location hash in older browsers and IE) to change the
URL.
The specified URL must share the same origin (i.e., protocol, host, and
port) as the current page, or an error will occur.
@example
// Starting URL: http://example.com/
router.replace('/path/');
// New URL: http://example.com/path/
router.replace('/path?foo=bar');
// New URL: http://example.com/path?foo=bar
router.replace('/');
// New URL: http://example.com/
@method replace
@param {String} [url] URL to set. This URL needs to be of the same origin as
the current URL. This can be a URL relative to the router's `root`
attribute. If no URL is specified, the page's current URL will be used.
@chainable
@see save()
**/
replace: function (url) {
return this._queue(url, true);
},
/**
Adds a route handler for the specified `route`.
The `route` parameter may be a string or regular expression to represent a
URL path, or a route object. If it's a string (which is most common), it may
contain named parameters: `:param` will match any single part of a URL path
(not including `/` characters), and `*param` will match any number of parts
of a URL path (including `/` characters). These named parameters will be
made available as keys on the `req.params` object that's passed to route
handlers.
If the `route` parameter is a regex, all pattern matches will be made
available as numbered keys on `req.params`, starting with `0` for the full
match, then `1` for the first subpattern match, and so on.
Alternatively, an object can be provided to represent the route and it may
contain a `path` property which is a string or regular expression which
causes the route to be process as described above. If the route object
already contains a `regex` or `regexp` property, the route will be
considered fully-processed and will be associated with any `callacks`
specified on the object and those specified as parameters to this method.
**Note:** Any additional data contained on the route object will be
preserved.
Here's a set of sample routes along with URL paths that they match:
* Route: `/photos/:tag/:page`
* URL: `/photos/kittens/1`, params: `{tag: 'kittens', page: '1'}`
* URL: `/photos/puppies/2`, params: `{tag: 'puppies', page: '2'}`
* Route: `/file/*path`
* URL: `/file/foo/bar/baz.txt`, params: `{path: 'foo/bar/baz.txt'}`
* URL: `/file/foo`, params: `{path: 'foo'}`
**Middleware**: Routes also support an arbitrary number of callback
functions. This allows you to easily reuse parts of your route-handling code
with different route. This method is liberal in how it processes the
specified `callbacks`, you can specify them as separate arguments, or as
arrays, or both.
If multiple route match a given URL, they will be executed in the order they
were added. The first route that was added will be the first to be executed.
**Passing Control**: Invoking the `next()` function within a route callback
will pass control to the next callback function (if any) or route handler
(if any). If a value is passed to `next()`, it's assumed to be an error,
therefore stopping the dispatch chain, unless that value is: `"route"`,
which is special case and dispatching will skip to the next route handler.
This allows middleware to skip any remaining middleware for a particular
route.
@example
router.route('/photos/:tag/:page', function (req, res, next) {
Y.log('Current tag: ' + req.params.tag);
Y.log('Current page number: ' + req.params.page);
});
// Using middleware.
router.findUser = function (req, res, next) {
req.user = this.get('users').findById(req.params.user);
next();
};
router.route('/users/:user', 'findUser', function (req, res, next) {
// The `findUser` middleware puts the `user` object on the `req`.
Y.log('Current user:' req.user.get('name'));
});
@method route
@param {String|RegExp|Object} route Route to match. May be a string or a
regular expression, or a route object.
@param {Array|Function|String} callbacks* Callback functions to call
whenever this route is triggered. These can be specified as separate
arguments, or in arrays, or both. If a callback is specified as a
string, the named function will be called on this router instance.
@param {Object} callbacks.req Request object containing information about
the request. It contains the following properties.
@param {Array|Object} callbacks.req.params Captured parameters matched
by the route path specification. If a string path was used and
contained named parameters, then this will be a key/value hash mapping
parameter names to their matched values. If a regex path was used,
this will be an array of subpattern matches starting at index 0 for
the full match, then 1 for the first subpattern match, and so on.
@param {String} callbacks.req.path The current URL path.
@param {Number} callbacks.req.pendingCallbacks Number of remaining
callbacks the route handler has after this one in the dispatch chain.
@param {Number} callbacks.req.pendingRoutes Number of matching routes
after this one in the dispatch chain.
@param {Object} callbacks.req.query Query hash representing the URL
query string, if any. Parameter names are keys, and are mapped to
parameter values.
@param {Object} callbacks.req.route Reference to the current route
object whose callbacks are being dispatched.
@param {Object} callbacks.req.router Reference to this router instance.
@param {String} callbacks.req.src What initiated the dispatch. In an
HTML5 browser, when the back/forward buttons are used, this property
will have a value of "popstate". When the `dispath()` method is
called, the `src` will be `"dispatch"`.
@param {String} callbacks.req.url The full URL.
@param {Object} callbacks.res Response object containing methods and
information that relate to responding to a request. It contains the
following properties.
@param {Object} callbacks.res.req Reference to the request object.
@param {Function} callbacks.next Function to pass control to the next
callback or the next matching route if no more callbacks (middleware)
exist for the current route handler. If you don't call this function,
then no further callbacks or route handlers will be executed, even if
there are more that match. If you do call this function, then the next
callback (if any) or matching route handler (if any) will be called.
All of these functions will receive the same `req` and `res` objects
that were passed to this route (so you can use these objects to pass
data along to subsequent callbacks and routes).
@param {String} [callbacks.next.err] Optional error which will stop the
dispatch chaining for this `req`, unless the value is `"route"`, which
is special cased to jump skip past any callbacks for the current route
and pass control the next route handler.
@chainable
**/
route: function (route, callbacks) {
// Grab callback functions from var-args.
callbacks = YArray(arguments, 1, true);
var keys, regex;
// Supports both the `route(path, callbacks)` and `route(config)` call
// signatures, allowing for fully-processed route configs to be passed.
if (typeof route === 'string' || YLang.isRegExp(route)) {
// Flatten `callbacks` into a single dimension array.
callbacks = YArray.flatten(callbacks);
keys = [];
regex = this._getRegex(route, keys);
route = {
callbacks: callbacks,
keys : keys,
path : route,
regex : regex
};
} else {
// Look for any configured `route.callbacks` and fallback to
// `route.callback` for back-compat, append var-arg `callbacks`,
// then flatten the entire collection to a single dimension array.
callbacks = YArray.flatten(
[route.callbacks || route.callback || []].concat(callbacks)
);
// Check for previously generated regex, also fallback to `regexp`
// for greater interop.
keys = route.keys;
regex = route.regex || route.regexp;
// Generates the route's regex if it doesn't already have one.
if (!regex) {
keys = [];
regex = this._getRegex(route.path, keys);
}
// Merge specified `route` config object with processed data.
route = Y.merge(route, {
callbacks: callbacks,
keys : keys,
path : route.path || regex,
regex : regex
});
}
this._routes.push(route);
return this;
},
/**
Saves a new browser history entry and dispatches to the first matching route
handler, if any.
Behind the scenes, this method uses HTML5 `pushState()` in browsers that
support it (or the location hash in older browsers and IE) to change the
URL and create a history entry.
The specified URL must share the same origin (i.e., protocol, host, and
port) as the current page, or an error will occur.
@example
// Starting URL: http://example.com/
router.save('/path/');
// New URL: http://example.com/path/
router.save('/path?foo=bar');
// New URL: http://example.com/path?foo=bar
router.save('/');
// New URL: http://example.com/
@method save
@param {String} [url] URL to set. This URL needs to be of the same origin as
the current URL. This can be a URL relative to the router's `root`
attribute. If no URL is specified, the page's current URL will be used.
@chainable
@see replace()
**/
save: function (url) {
return this._queue(url);
},
/**
Upgrades a hash-based URL to an HTML5 URL if necessary. In non-HTML5
browsers, this method is a noop.
@method upgrade
@return {Boolean} `true` if the URL was upgraded, `false` otherwise.
**/
upgrade: function () {
if (!this._html5) {
return false;
}
// Get the resolve hash path.
var hashPath = this._getHashPath();
if (hashPath) {
// This is an HTML5 browser and we have a hash-based path in the
// URL, so we need to upgrade the URL to a non-hash URL. This
// will trigger a `history:change` event, which will in turn
// trigger a dispatch.
this.once(EVT_READY, function () {
this.replace(hashPath);
});
return true;
}
return false;
},
// -- Protected Methods ----------------------------------------------------
/**
Wrapper around `decodeURIComponent` that also converts `+` chars into
spaces.
@method _decode
@param {String} string String to decode.
@return {String} Decoded string.
@protected
**/
_decode: function (string) {
return decodeURIComponent(string.replace(/\+/g, ' '));
},
/**
Shifts the topmost `_save()` call off the queue and executes it. Does
nothing if the queue is empty.
@method _dequeue
@chainable
@see _queue
@protected
**/
_dequeue: function () {
var self = this,
fn;
// If window.onload hasn't yet fired, wait until it has before
// dequeueing. This will ensure that we don't call pushState() before an
// initial popstate event has fired.
if (!YUI.Env.windowLoaded) {
Y.once('load', function () {
self._dequeue();
});
return this;
}
fn = saveQueue.shift();
return fn ? fn() : this;
},
/**
Dispatches to the first route handler that matches the specified _path_.
If called before the `ready` event has fired, the dispatch will be aborted.
This ensures normalized behavior between Chrome (which fires a `popstate`
event on every pageview) and other browsers (which do not).
@method _dispatch
@param {object} req Request object.
@param {String} res Response object.
@chainable
@protected
**/
_dispatch: function (req, res) {
var self = this,
routes = self.match(req.path),
callbacks = [],
routePath, paramValues;
self._dispatching = self._dispatched = true;
if (!routes || !routes.length) {
self._dispatching = false;
return self;
}
routePath = self.removeRoot(req.path);
function next(err) {
var callback, name, route;
if (err) {
// Special case "route" to skip to the next route handler
// avoiding any additional callbacks for the current route.
if (err === 'route') {
callbacks = [];
next();
} else {
Y.error(err);
}
} else if ((callback = callbacks.shift())) {
if (typeof callback === 'string') {
name = callback;
callback = self[name];
if (!callback) {
Y.error('Router: Callback not found: ' + name, null, 'router');
}
}
// Allow access to the number of remaining callbacks for the
// route.
req.pendingCallbacks = callbacks.length;
callback.call(self, req, res, next);
} else if ((route = routes.shift())) {
paramValues = self._getParamValues(route, routePath);
if (!paramValues) {
// Skip this route because one of the param handlers
// rejected a param value in the `routePath`.
next('route');
return;
}
// Expose the processed param values.
req.params = paramValues;
// Allow access to current route and the number of remaining
// routes for this request.
req.route = route;
req.pendingRoutes = routes.length;
// Make a copy of this route's `callbacks` so the original array
// is preserved.
callbacks = route.callbacks.concat();
// Execute this route's `callbacks`.
next();
}
}
next();
self._dispatching = false;
return self._dequeue();
},
/**
Returns the resolved path from the hash fragment, or an empty string if the
hash is not path-like.
@method _getHashPath
@param {String} [hash] Hash fragment to resolve into a path. By default this
will be the hash from the current URL.
@return {String} Current hash path, or an empty string if the hash is empty.
@protected
**/
_getHashPath: function (hash) {
hash || (hash = HistoryHash.getHash());
// Make sure the `hash` is path-like.
if (hash && hash.charAt(0) === '/') {
return this._joinURL(hash);
}
return '';
},
/**
Gets the location origin (i.e., protocol, host, and port) as a URL.
@example
http://example.com
@method _getOrigin
@return {String} Location origin (i.e., protocol, host, and port).
@protected
**/
_getOrigin: function () {
var location = Y.getLocation();
return location.origin || (location.protocol + '//' + location.host);
},
/**
Getter for the `params` attribute.
@method _getParams
@return {Object} Mapping of param handlers: `name` -> RegExp | Function.
@protected
@since 3.12.0
**/
_getParams: function () {
return Y.merge(this._params);
},
/**
Gets the param values for the specified `route` and `path`, suitable to use
form `req.params`.
**Note:** This method will return `false` if a named param handler rejects a
param value.
@method _getParamValues
@param {Object} route The route to get param values for.
@param {String} path The route path (root removed) that provides the param
values.
@return {Boolean|Array|Object} The collection of processed param values.
Either a hash of `name` -> `value` for named params processed by this
router's param handlers, or an array of matches for a route with unnamed
params. If a named param handler rejects a value, then `false` will be
returned.
@protected
@since 3.16.0
**/
_getParamValues: function (route, path) {
var matches, paramsMatch, paramValues;
// Decode each of the path params so that the any URL-encoded path
// segments are decoded in the `req.params` object.
matches = YArray.map(route.regex.exec(path) || [], function (match) {
// Decode matches, or coerce `undefined` matches to an empty
// string to match expectations of working with `req.params`
// in the context of route dispatching, and normalize
// browser differences in their handling of regex NPCGs:
// https://github.com/yui/yui3/issues/1076
return (match && this._decode(match)) || '';
}, this);
// Simply return the array of decoded values when the route does *not*
// use named parameters.
if (matches.length - 1 !== route.keys.length) {
return matches;
}
// Remove the first "match" from the param values, because it's just the
// `path` processed by the route's regex, and map the values to the keys
// to create the name params collection.
paramValues = YArray.hash(route.keys, matches.slice(1));
// Pass each named param value to its handler, if there is one, for
// validation/processing. If a param value is rejected by a handler,
// then the params don't match and a falsy value is returned.
paramsMatch = YArray.every(route.keys, function (name) {
var paramHandler = this._params[name],
value = paramValues[name];
if (paramHandler && value && typeof value === 'string') {
// Check if `paramHandler` is a RegExp, because this
// is true in Android 2.3 and other browsers!
// `typeof /.*/ === 'function'`
value = YLang.isRegExp(paramHandler) ?
paramHandler.exec(value) :
paramHandler.call(this, value, name);
if (value !== false && YLang.isValue(value)) {
// Update the named param to the value from the handler.
paramValues[name] = value;
return true;
}
// Consider the param value as rejected by the handler.
return false;
}
return true;
}, this);
if (paramsMatch) {
return paramValues;
}
// Signal that a param value was rejected by a named param handler.
return false;
},
/**
Gets the current route path.
@method _getPath
@return {String} Current route path.
@protected
**/
_getPath: function () {
var path = (!this._html5 && this._getHashPath()) ||
Y.getLocation().pathname;
return this.removeQuery(path);
},
/**
Returns the current path root after popping off the last path segment,
making it useful for resolving other URL paths against.
The path root will always begin and end with a '/'.
@method _getPathRoot
@return {String} The URL's path root.
@protected
@since 3.5.0
**/
_getPathRoot: function () {
var slash = '/',
path = Y.getLocation().pathname,
segments;
if (path.charAt(path.length - 1) === slash) {
return path;
}
segments = path.split(slash);
segments.pop();
return segments.join(slash) + slash;
},
/**
Gets the current route query string.
@method _getQuery
@return {String} Current route query string.
@protected
**/
_getQuery: function () {
var location = Y.getLocation(),
hash, matches;
if (this._html5) {
return location.search.substring(1);
}
hash = HistoryHash.getHash();
matches = hash.match(this._regexUrlQuery);
return hash && matches ? matches[1] : location.search.substring(1);
},
/**
Creates a regular expression from the given route specification. If _path_
is already a regex, it will be returned unmodified.
@method _getRegex
@param {String|RegExp} path Route path specification.
@param {Array} keys Array reference to which route parameter names will be
added.
@return {RegExp} Route regex.
@protected
**/
_getRegex: function (path, keys) {
if (YLang.isRegExp(path)) {
return path;
}
// Special case for catchall paths.
if (path === '*') {
return (/.*/);
}
path = path.replace(this._regexPathParam, function (match, operator, key) {
// Only `*` operators are supported for key-less matches to allowing
// in-path wildcards like: '/foo/*'.
if (!key) {
return operator === '*' ? '.*' : match;
}
keys.push(key);
return operator === '*' ? '(.*?)' : '([^/#?]+)';
});
return new RegExp('^' + path + '$');
},
/**
Gets a request object that can be passed to a route handler.
@method _getRequest
@param {String} src What initiated the URL change and need for the request.
@return {Object} Request object.
@protected
**/
_getRequest: function (src) {
return {
path : this._getPath(),
query : this._parseQuery(this._getQuery()),
url : this._getURL(),
router: this,
src : src
};
},
/**
Gets a response object that can be passed to a route handler.
@method _getResponse
@param {Object} req Request object.
@return {Object} Response Object.
@protected
**/
_getResponse: function (req) {
return {req: req};
},
/**
Getter for the `routes` attribute.
@method _getRoutes
@return {Object[]} Array of route objects.
@protected
**/
_getRoutes: function () {
return this._routes.concat();
},
/**
Gets the current full URL.
@method _getURL
@return {String} URL.
@protected
**/
_getURL: function () {
var url = Y.getLocation().toString();
if (!this._html5) {
url = this._upgradeURL(url);
}
return url;
},
/**
Returns `true` when the specified `url` is from the same origin as the
current URL; i.e., the protocol, host, and port of the URLs are the same.
All host or path relative URLs are of the same origin. A scheme-relative URL
is first prefixed with the current scheme before being evaluated.
@method _hasSameOrigin
@param {String} url URL to compare origin with the current URL.
@return {Boolean} Whether the URL has the same origin of the current URL.
@protected
**/
_hasSameOrigin: function (url) {
var origin = ((url && url.match(this._regexUrlOrigin)) || [])[0];
// Prepend current scheme to scheme-relative URLs.
if (origin && origin.indexOf('//') === 0) {
origin = Y.getLocation().protocol + origin;
}
return !origin || origin === this._getOrigin();
},
/**
Joins the `root` URL to the specified _url_, normalizing leading/trailing
`/` characters.
@example
router.set('root', '/foo');
router._joinURL('bar'); // => '/foo/bar'
router._joinURL('/bar'); // => '/foo/bar'
router.set('root', '/foo/');
router._joinURL('bar'); // => '/foo/bar'
router._joinURL('/bar'); // => '/foo/bar'
@method _joinURL
@param {String} url URL to append to the `root` URL.
@return {String} Joined URL.
@protected
**/
_joinURL: function (url) {
var root = this.get('root');
// Causes `url` to _always_ begin with a "/".
url = this.removeRoot(url);
if (url.charAt(0) === '/') {
url = url.substring(1);
}
return root && root.charAt(root.length - 1) === '/' ?
root + url :
root + '/' + url;
},
/**
Returns a normalized path, ridding it of any '..' segments and properly
handling leading and trailing slashes.
@method _normalizePath
@param {String} path URL path to normalize.
@return {String} Normalized path.
@protected
@since 3.5.0
**/
_normalizePath: function (path) {
var dots = '..',
slash = '/',
i, len, normalized, segments, segment, stack;
if (!path || path === slash) {
return slash;
}
segments = path.split(slash);
stack = [];
for (i = 0, len = segments.length; i < len; ++i) {
segment = segments[i];
if (segment === dots) {
stack.pop();
} else if (segment) {
stack.push(segment);
}
}
normalized = slash + stack.join(slash);
// Append trailing slash if necessary.
if (normalized !== slash && path.charAt(path.length - 1) === slash) {
normalized += slash;
}
return normalized;
},
/**
Parses a URL query string into a key/value hash. If `Y.QueryString.parse` is
available, this method will be an alias to that.
@method _parseQuery
@param {String} query Query string to parse.
@return {Object} Hash of key/value pairs for query parameters.
@protected
**/
_parseQuery: QS && QS.parse ? QS.parse : function (query) {
var decode = this._decode,
params = query.split('&'),
i = 0,
len = params.length,
result = {},
param;
for (; i < len; ++i) {
param = params[i].split('=');
if (param[0]) {
result[decode(param[0])] = decode(param[1] || '');
}
}
return result;
},
/**
Returns `true` when the specified `path` is semantically within the
specified `root` path.
If the `root` does not end with a trailing slash ("/"), one will be added
before the `path` is evaluated against the root path.
@example
this._pathHasRoot('/app', '/app/foo'); // => true
this._pathHasRoot('/app/', '/app/foo'); // => true
this._pathHasRoot('/app/', '/app/'); // => true
this._pathHasRoot('/app', '/foo/bar'); // => false
this._pathHasRoot('/app/', '/foo/bar'); // => false
this._pathHasRoot('/app/', '/app'); // => false
this._pathHasRoot('/app', '/app'); // => false
@method _pathHasRoot
@param {String} root Root path used to evaluate whether the specificed
`path` is semantically within. A trailing slash ("/") will be added if
it does not already end with one.
@param {String} path Path to evaluate for containing the specified `root`.
@return {Boolean} Whether or not the `path` is semantically within the
`root` path.
@protected
@since 3.13.0
**/
_pathHasRoot: function (root, path) {
var rootPath = root.charAt(root.length - 1) === '/' ? root : root + '/';
return path.indexOf(rootPath) === 0;
},
/**
Queues up a `_save()` call to run after all previously-queued calls have
finished.
This is necessary because if we make multiple `_save()` calls before the
first call gets dispatched, then both calls will dispatch to the last call's
URL.
All arguments passed to `_queue()` will be passed on to `_save()` when the
queued function is executed.
@method _queue
@chainable
@see _dequeue
@protected
**/
_queue: function () {
var args = arguments,
self = this;
saveQueue.push(function () {
if (self._html5) {
if (Y.UA.ios && Y.UA.ios < 5) {
// iOS <5 has buggy HTML5 history support, and needs to be
// synchronous.
self._save.apply(self, args);
} else {
// Wrapped in a timeout to ensure that _save() calls are
// always processed asynchronously. This ensures consistency
// between HTML5- and hash-based history.
setTimeout(function () {
self._save.apply(self, args);
}, 1);
}
} else {
self._dispatching = true; // otherwise we'll dequeue too quickly
self._save.apply(self, args);
}
return self;
});
return !this._dispatching ? this._dequeue() : this;
},
/**
Returns the normalized result of resolving the `path` against the current
path. Falsy values for `path` will return just the current path.
@method _resolvePath
@param {String} path URL path to resolve.
@return {String} Resolved path.
@protected
@since 3.5.0
**/
_resolvePath: function (path) {
if (!path) {
return Y.getLocation().pathname;
}
if (path.charAt(0) !== '/') {
path = this._getPathRoot() + path;
}
return this._normalizePath(path);
},
/**
Resolves the specified URL against the current URL.
This method resolves URLs like a browser does and will always return an
absolute URL. When the specified URL is already absolute, it is assumed to
be fully resolved and is simply returned as is. Scheme-relative URLs are
prefixed with the current protocol. Relative URLs are giving the current
URL's origin and are resolved and normalized against the current path root.
@method _resolveURL
@param {String} url URL to resolve.
@return {String} Resolved URL.
@protected
@since 3.5.0
**/
_resolveURL: function (url) {
var parts = url && url.match(this._regexURL),
origin, path, query, hash, resolved;
if (!parts) {
return Y.getLocation().toString();
}
origin = parts[1];
path = parts[2];
query = parts[3];
hash = parts[4];
// Absolute and scheme-relative URLs are assumed to be fully-resolved.
if (origin) {
// Prepend the current scheme for scheme-relative URLs.
if (origin.indexOf('//') === 0) {
origin = Y.getLocation().protocol + origin;
}
return origin + (path || '/') + (query || '') + (hash || '');
}
// Will default to the current origin and current path.
resolved = this._getOrigin() + this._resolvePath(path);
// A path or query for the specified URL trumps the current URL's.
if (path || query) {
return resolved + (query || '') + (hash || '');
}
query = this._getQuery();
return resolved + (query ? ('?' + query) : '') + (hash || '');
},
/**
Saves a history entry using either `pushState()` or the location hash.
This method enforces the same-origin security constraint; attempting to save
a `url` that is not from the same origin as the current URL will result in
an error.
@method _save
@param {String} [url] URL for the history entry.
@param {Boolean} [replace=false] If `true`, the current history entry will
be replaced instead of a new one being added.
@chainable
@protected
**/
_save: function (url, replace) {
var urlIsString = typeof url === 'string',
currentPath, root, hash;
// Perform same-origin check on the specified URL.
if (urlIsString && !this._hasSameOrigin(url)) {
Y.error('Security error: The new URL must be of the same origin as the current URL.');
return this;
}
// Joins the `url` with the `root`.
if (urlIsString) {
url = this._joinURL(url);
}
// Force _ready to true to ensure that the history change is handled
// even if _save is called before the `ready` event fires.
this._ready = true;
if (this._html5) {
this._history[replace ? 'replace' : 'add'](null, {url: url});
} else {
currentPath = Y.getLocation().pathname;
root = this.get('root');
hash = HistoryHash.getHash();
if (!urlIsString) {
url = hash;
}
// Determine if the `root` already exists in the current location's
// `pathname`, and if it does then we can exclude it from the
// hash-based path. No need to duplicate the info in the URL.
if (root === currentPath || root === this._getPathRoot()) {
url = this.removeRoot(url);
}
// The `hashchange` event only fires when the new hash is actually
// different. This makes sure we'll always dequeue and dispatch
// _all_ router instances, mimicking the HTML5 behavior.
if (url === hash) {
Y.Router.dispatch();
} else {
HistoryHash[replace ? 'replaceHash' : 'setHash'](url);
}
}
return this;
},
/**
Setter for the `params` attribute.
@method _setParams
@param {Object} params Map in the form: `name` -> RegExp | Function.
@return {Object} The map of params: `name` -> RegExp | Function.
@protected
@since 3.12.0
**/
_setParams: function (params) {
this._params = {};
YObject.each(params, function (regex, name) {
this.param(name, regex);
}, this);
return Y.merge(this._params);
},
/**
Setter for the `routes` attribute.
@method _setRoutes
@param {Object[]} routes Array of route objects.
@return {Object[]} Array of route objects.
@protected
**/
_setRoutes: function (routes) {
this._routes = [];
YArray.each(routes, function (route) {
this.route(route);
}, this);
return this._routes.concat();
},
/**
Upgrades a hash-based URL to a full-path URL, if necessary.
The specified `url` will be upgraded if its of the same origin as the
current URL and has a path-like hash. URLs that don't need upgrading will be
returned as-is.
@example
app._upgradeURL('http://example.com/#/foo/'); // => 'http://example.com/foo/';
@method _upgradeURL
@param {String} url The URL to upgrade from hash-based to full-path.
@return {String} The upgraded URL, or the specified URL untouched.
@protected
@since 3.5.0
**/
_upgradeURL: function (url) {
// We should not try to upgrade paths for external URLs.
if (!this._hasSameOrigin(url)) {
return url;
}
var hash = (url.match(/#(.*)$/) || [])[1] || '',
hashPrefix = Y.HistoryHash.hashPrefix,
hashPath;
// Strip any hash prefix, like hash-bangs.
if (hashPrefix && hash.indexOf(hashPrefix) === 0) {
hash = hash.replace(hashPrefix, '');
}
// If the hash looks like a URL path, assume it is, and upgrade it!
if (hash) {
hashPath = this._getHashPath(hash);
if (hashPath) {
return this._resolveURL(hashPath);
}
}
return url;
},
// -- Protected Event Handlers ---------------------------------------------
/**
Handles `history:change` and `hashchange` events.
@method _afterHistoryChange
@param {EventFacade} e
@protected
**/
_afterHistoryChange: function (e) {
var self = this,
src = e.src,
prevURL = self._url,
currentURL = self._getURL(),
req, res;
self._url = currentURL;
// Handles the awkwardness that is the `popstate` event. HTML5 browsers
// fire `popstate` right before they fire `hashchange`, and Chrome fires
// `popstate` on page load. If this router is not ready or the previous
// and current URLs only differ by their hash, then we want to ignore
// this `popstate` event.
if (src === 'popstate' &&
(!self._ready || prevURL.replace(/#.*$/, '') === currentURL.replace(/#.*$/, ''))) {
return;
}
req = self._getRequest(src);
res = self._getResponse(req);
self._dispatch(req, res);
},
// -- Default Event Handlers -----------------------------------------------
/**
Default handler for the `ready` event.
@method _defReadyFn
@param {EventFacade} e
@protected
**/
_defReadyFn: function (e) {
this._ready = true;
}
}, {
// -- Static Properties ----------------------------------------------------
NAME: 'router',
ATTRS: {
/**
Whether or not this browser is capable of using HTML5 history.
Setting this to `false` will force the use of hash-based history even on
HTML5 browsers, but please don't do this unless you understand the
consequences.
@attribute html5
@type Boolean
@initOnly
**/
html5: {
// Android versions lower than 3.0 are buggy and don't update
// window.location after a pushState() call, so we fall back to
// hash-based history for them.
//
// See http://code.google.com/p/android/issues/detail?id=17471
valueFn: function () { return Y.Router.html5; },
writeOnce: 'initOnly'
},
/**
Map of params handlers in the form: `name` -> RegExp | Function.
If a param handler regex or function returns a value of `false`, `null`,
`undefined`, or `NaN`, the current route will not match and be skipped.
All other return values will be used in place of the original param
value parsed from the URL.
This attribute is intended to be used to set params at init time, or to
completely reset all params after init. To add params after init without
resetting all existing params, use the `param()` method.
@attribute params
@type Object
@default `{}`
@see param
@since 3.12.0
**/
params: {
value : {},
getter: '_getParams',
setter: '_setParams'
},
/**
Absolute root path from which all routes should be evaluated.
For example, if your router is running on a page at
`http://example.com/myapp/` and you add a route with the path `/`, your
route will never execute, because the path will always be preceded by
`/myapp`. Setting `root` to `/myapp` would cause all routes to be
evaluated relative to that root URL, so the `/` route would then execute
when the user browses to `http://example.com/myapp/`.
@example
router.set('root', '/myapp');
router.route('/foo', function () { ... });
Y.log(router.hasRoute('/foo')); // => false
Y.log(router.hasRoute('/myapp/foo')); // => true
// Updates the URL to: "/myapp/foo"
router.save('/foo');
@attribute root
@type String
@default `''`
**/
root: {
value: ''
},
/**
Array of route objects.
Each item in the array must be an object with the following properties
in order to be processed by the router:
* `path`: String or regex representing the path to match. See the docs
for the `route()` method for more details.
* `callbacks`: Function or a string representing the name of a
function on this router instance that should be called when the
route is triggered. An array of functions and/or strings may also be
provided. See the docs for the `route()` method for more details.
If a route object contains a `regex` or `regexp` property, or if its
`path` is a regular express, then the route will be considered to be
fully-processed. Any fully-processed routes may contain the following
properties:
* `regex`: The regular expression representing the path to match, this
property may also be named `regexp` for greater compatibility.
* `keys`: Array of named path parameters used to populate `req.params`
objects when dispatching to route handlers.
Any additional data contained on these route objects will be retained.
This is useful to store extra metadata about a route; e.g., a `name` to
give routes logical names.
This attribute is intended to be used to set routes at init time, or to
completely reset all routes after init. To add routes after init without
resetting all existing routes, use the `route()` method.
@attribute routes
@type Object[]
@default `[]`
@see route
**/
routes: {
value : [],
getter: '_getRoutes',
setter: '_setRoutes'
}
},
// Used as the default value for the `html5` attribute, and for testing.
html5: Y.HistoryBase.html5 && (!Y.UA.android || Y.UA.android >= 3),
// To make this testable.
_instances: instances,
/**
Dispatches to the first route handler that matches the specified `path` for
all active router instances.
This provides a mechanism to cause all active router instances to dispatch
to their route handlers without needing to change the URL or fire the
`history:change` or `hashchange` event.
@method dispatch
@static
@since 3.6.0
**/
dispatch: function () {
var i, len, router, req, res;
for (i = 0, len = instances.length; i < len; i += 1) {
router = instances[i];
if (router) {
req = router._getRequest('dispatch');
res = router._getResponse(req);
router._dispatch(req, res);
}
}
}
});
/**
The `Controller` class was deprecated in YUI 3.5.0 and is now an alias for the
`Router` class. Use that class instead. This alias will be removed in a future
version of YUI.
@class Controller
@constructor
@extends Base
@deprecated Use `Router` instead.
@see Router
**/
Y.Controller = Y.Router;
}, 'patched-v3.18.0', {"optional": ["querystring-parse"], "requires": ["array-extras", "base-build", "history"]});
|
$.ajaxSetup({
cache: false
});
function init(){
$.fn.pluginName;
}
$(document).ready(function(){
//Alert
var error = window.location.search;
//Initial
var pageInitial = $('#sidebarHome a').attr('href');
// //Shift Scheduler
if(error.indexOf("?alert=shift_requested") !== -1){
$('#alert').append(
"<div class=\"alert alert-success alert-dismissable\">" +
"<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>" +
"<strong>Success!</strong> Shift has been successfully requested. " +
"</div>");
var page = $('#sidebarShiftScheduler a').attr('href');
$('#content').load(page);
}
//Trade-A-Shift
else if(error.indexOf("?alert=shift_posted") !== -1){
$('#alert').append(
"<div class=\"alert alert-success alert-dismissable\">" +
"<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>" +
"<strong>Success!</strong> Shift has been successfully posted to Take-A-Shift. " +
"</div>");
var page = $('#sidebarShiftTrader a').attr('href');
$('#content').load(page);
}
//Take-A-Shift
else if(error.indexOf("?alert=shift_taken") !== -1){
$('#alert').append(
"<div class=\"alert alert-success alert-dismissable\">" +
"<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>" +
"<strong>Success!</strong> Shift has been taken successfully. Awaiting approval from manager." +
"</div>");
var page = $('#sidebarShiftTrader a').attr('href');
$('#content').load(page);
}
// //Time Keeper IMPLEMENT ONCE TIME KEEPER WORKS
// else if(error.indexOf("?alert=time_recorded") !== -1){
// $('#alert').append(
// "<div class=\"alert alert-success alert-dismissable\">" +
// "<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>" +
// "<strong>Success!</strong> Hours worked have been successfully recorded." +
// "</div>");
// var page = $('#sidebarTimeKeeper a').attr('href');
// $('#content').load(page);
// }
//Account Option page, password changed successfully
else if(error.indexOf("?alert=password_change") !== -1){
$('#alert').append(
"<div class=\"alert alert-success alert-dismissable\">" +
"<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>" +
"<strong>Success!</strong> Password has been changed." +
"</div>");
var page = $('#topbarOptions a').attr('href');
$('#content').load(page);
}
//Account Option page, old password entered wrong
else if(error.indexOf("?alert=password_wrong") !== -1){
$('#alert').append(
"<div class=\"alert alert-danger alert-dismissable\">" +
"<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>" +
"<strong>Error!</strong> Old password did not match user password." +
"</div>");
var page = $('#topbarOptions a').attr('href');
$('#content').load(page);
}
//Account Options page, new passwords did not match
else if(error.indexOf("?alert=password_failed") !== -1){
$('#alert').append(
"<div class=\"alert alert-danger alert-dismissable\">" +
"<button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>" +
"<strong>Error!</strong> Password change failed. Passwords did not match." +
"</div>");
var page = $('#topbarOptions a').attr('href');
$('#content').load(page);
}
else{
$('#content').load(pageInitial);
};
//Home
$('#sidebarHome').click(function(){
var page = $('#sidebarHome a').attr('href');
var currentPath = window.location.pathname;
$('#content').load(page);
return false;
});
//Calendar
$('#sidebarCalendar').click(function(){
var page = $('#sidebarCalendar a').attr('href');
$('#content').load(page);
return false;
});
//Shift Scheduler
$('#sidebarShiftScheduler').click(function(){
var page = $('#sidebarShiftScheduler a').attr('href');
$('#content').load(page);
return false;
});
//Shift Trader
$('#sidebarShiftTrader').click(function(){
var page = $('#sidebarShiftTrader a').attr('href');
$('#content').load(page);
return false;
});
//Time Keeper
$('#sidebarTimeKeeper').click(function(){
var page = $('#sidebarTimeKeeper a').attr('href');
$('#content').load(page);
return false;
});
//Account Options
$('#topbarOptions').click(function(){
var page = $('#topbarOptions a').attr('href');
$('#content').load(page);
return false;
});
}); |
//>>built
define(["dojo/_base/lang","dojo/_base/declare","dojo/_base/window","dojo/_base/config","dojo/dom-construct"],function(d,c,e,g,h){return c("dojox.analytics.Urchin",null,{acct:"",constructor:function(a){this.tracker=null;d.mixin(this,a);this.acct=this.acct||g.urchin;var c=/loaded|complete/;a="https:"==e.doc.location.protocol?"https://ssl.":"http://www.";var f=e.doc.getElementsByTagName("head")[0],b=h.create("script",{src:a+"google-analytics.com/ga.js"},f);b.onload=b.onreadystatechange=d.hitch(this,
function(a){if(a&&"load"==a.type||c.test(b.readyState))b.onload=b.onreadystatechange=null,this._gotGA(),f.removeChild(b)})},_gotGA:function(){this.tracker=_gat._getTracker(this.acct);this.GAonLoad.apply(this,arguments)},GAonLoad:function(){this.trackPageView()},trackPageView:function(a){this.tracker._trackPageview.apply(this.tracker,arguments)}})}); |
'use strict';
window.jstag = function () {
var t = {
_q: [],
_c: {},
ts: new Date().getTime(),
ver: '2.0.0'
};
var as = Array.prototype.slice;
t.init = function (c) {
t._c = c;
if (// begin load of core tag
// in > 2.0.0 this tag will handle loading io based on account
// and no longer require changes to async tag
!c.synchronous) {
t.loadtagmgr(c);
}
return this;
};
t.loadtagmgr = function (c) {
var newtag = document.createElement('script');
newtag.type = 'text/javascript';
newtag.async = true;
newtag.src = c.url + '/api/tag/' + c.cid + '/lio.js';
var i = document.getElementsByTagName('script')[0];
i.parentNode.insertBefore(newtag, i);
};
function chainable(fn) {
return function () {
fn.apply(this, arguments);
return this;
};
}
function queueStub() {
var args = ['ready'].concat(as.call(arguments));
return chainable(function () {
args.push(as.call(arguments));
this._q.push(args);
});
}
t.ready = queueStub();
t.send = queueStub('send');
t.mock = queueStub('mock');
t.identify = queueStub('identify');
t.pageView = queueStub('pageView');
t.bind = chainable(function (e) {
t._q.push([
e,
as.call(arguments, 1)
]);
});
t.block = chainable(function () {
t._c.blockload = true;
});
t.unblock = chainable(function () {
t._c.blockload = false;
});
return t;
}();
/* eslint-disable */
window.jstag.init({
cid: '{{account.id}}',
url: '//c.lytics.io',
min: true,
loadid: false
}); |
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
index: './client/js/index.jsx',
newpost: './client/js/newpost.jsx'
},
output: {
// __dirname is the path of webpack.js
path: __dirname + '/../build',
filename: '[name].js'
},
module: {
loaders: [
{
test: /\.jsx$/, loader: 'babel-loader'
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract(
'css-loader?sourceMap!postcss-loader'
)
}
]
},
plugins: [new ExtractTextPlugin('client.css')],
postcss: [require('autoprefixer-core'), require('csswring')({map: true})],
debug: true,
devtool: 'source-map'
}
|
$(document).ready(function() {
var scroll_timer;
var displayed = false;
var $link = $('#top-link');
var $window = $(window);
var top = $(document.body).children(0).position().top;
$window.scroll(function() {
clearTimeout(scroll_timer);
scroll_timer = setTimeout(function() {
if ($window.scrollTop() <= top) {
displayed = false;
$link.fadeOut(500);
}
else if (displayed == false) {
displayed = true;
$link.stop(true, true).fadeIn(500);
}
}, 100);
});
$link.click(function() {
$('html, body').animate({scrollTop: 0}, 'slow');
displayed = false;
$link.fadeOut(500);
return false;
});
}); |
function validate() {
return false;
}
/*
* TODO: Fetch a cookie and check boxes according to what it says
*/
function checkCookie() {
checkboxes = document.getElementsByClassName('romajicheckbox');
cookie = getCookie();
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = cookie[i].checked;
}
}
/*
* TODO: checkRow and checkAllBox must also check if all romajicheckboxes (except for
* the one named "all") are checked. This will not be implemented until then.
*/
function checkAll(source) {
checkboxes = document.getElementsByClassName('romajicheckbox');
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = source.checked;
}
setSize();
checkDakuten();
}
function checkIfAll() {
checkboxes = document.getElementsByClassName('romajicheckbox');
allbox = checkboxes[0];
checkboxes = shift(checkboxes);
allchecked = true;
for (var i = 0, n = checkboxes.length; i < n; i++) {
if (checkboxes[i].checked == false) {
allchecked = false;
}
}
allbox.checked = allchecked;
}
/*SHIFT*/
function shift(source) {
temp = [];
for (var i = 1, n = source.length; i < n; i++) {
temp.push(source[i]);
}
return temp;
}
/*CONTAINS*/
function contains(source, element) {
//alert("contains called!");
contain = false;
//alert("success!");
for (var i = 0, n = source.length; i < n; i++) {
//alert("loop successful!");
if (source[i] == element) {
contain = true;
}
}
return contain;
}
/*
* Called when an all-box is clicked. Checks or unchecks all boxes in a row.
*/
function checkRow(source) {
childname = source.name.replace("all", "");
checkboxes = document.getElementsByName(childname);
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = source.checked;
}
setSize();
checkIfAll();
checkDakuten();
}
/*
* Called when a non all-box is clicked. If the box was checked, it will check if
* all other boxes are checked; if so, it will check the corresponding all-box.
* If the box was unchecked, it will uncheck the corresponding all-box.
*/
function checkAllBox(source) {
if (source.checked == true) {
checkboxes = document.getElementsByName(source.name);
allchecked = true;
for (var i = 0, n = checkboxes.length; i < n; i++) {
if (checkboxes[i].checked == false) {
allchecked = false;
}
}
if (allchecked == true) {
master = document.getElementsByName("all" + source.name);
master[0].checked = true;
}
} else {
master = document.getElementsByName("all" + source.name);
master[0].checked = false;
}
//setSize();
checkIfAll();
checkDakuten();
}
function checkDakuten() {
dakuten = document.getElementById('dakuten').checked;
if (dakuten) {
setSize();
a1 = ["ka","ki","ku","ke","ko","sa","shi","su","se","so","ta","chi","tsu","te","to"];
a2 = ["ha","hi","fhu","he","ho"];
number = 0;
checkboxes = document.getElementsByClassName('romajicheckbox');
for (var i = 0, n = a1.length; i < n; i++) {
for (var j = 0, o = checkboxes.length; j < o; j++) {
if (checkboxes[j].value == a1[i] && checkboxes[j].checked == true) {
number++;
}
}
}
for (var a = 0, b = a2.length; a < b; a++) {
for (var c = 0, d = checkboxes.length; c < d; c++) {
if (checkboxes[c].value == a2[a] && checkboxes[c].checked == true) {
number = number + 2;
}
}
}
numberOfRomaji = parseInt(document.getElementById('number01').value);
numberOfRomaji = numberOfRomaji + number;
//alert(numberOfRomaji);
document.getElementById('number01').value = numberOfRomaji;
} else {
setSize();
}
}
/*
* Called when the Submit button is clicked.
*/
function generate() {
numberOfRomaji = document.getElementById('number01').value;
checkboxes = document.getElementsByClassName('romajicheckbox');
somethingchecked = false;
dakuten = document.getElementById('dakuten').checked;
for (var i = 0, n = checkboxes.length; i < n; i++) {
if (checkboxes[i].checked == true) {
somethingchecked = true;
}
}
if (somethingchecked == false) { //if nothing is checked
window.alert("You need to select some romaji!");
} else if (numberOfRomaji == "" || numberOfRomaji <= 0) { //if "generate how many romaji" is zero or null
window.alert("You must generate at least one romaji!");
} else {
var values = [];
var randomizedList = [];
var s = "";
//gets all checkboxes, and then pushes the non all-box ones into the values array
allcheckboxes = document.getElementsByClassName('romajicheckbox');
for (var j = 0, n = allcheckboxes.length; j < n; j++) {
if (!allcheckboxes[j].name.includes("all") && allcheckboxes[j].checked == true) {
values.push(allcheckboxes[j].value);
}
}
if (dakuten) {
addDakuten(values);
}
//generate the list of romaji
var current = "";
var previous = "";
k = 0;
while (k < numberOfRomaji) {
current = values[Math.floor(Math.random() * (values.length))];
//if the current element is not a duplicate of the previous
if (current != previous) {
randomizedList.push(current);
previous = current;
k++;
}
}
var columns = 10;
var x = 0;
s = s + "<table><tr>"
while (x < randomizedList.length) {
s = s + "<td>" + randomizedList[x] + " </td>";
if ((x + 1) % columns == 0 && x > 0) {
s = s + "</tr><tr>";
}
x++;
}
s = s + "</tr></table>";
window.open("data:text/html, <html><head><style>td{padding:20px;}</style></head><body>Generated " + randomizedList.length + " randomized romaji. Print this!<br><br>" + s + "</body></html>");
}
}
function addDakuten(source) {
temp = source;
a1 = ["ka","ki","ku","ke","ko","sa","shi","su","se","so","ta","chi","tsu","te","to"];
a1_1 = ["ga","gi","gu","ge","go","za","zji","zu","ze","zo","da","dji","dzu","de","do"];
for (var i = 0, n = a1.length; i < n; i++) {
if (contains(source, a1[i])) {
temp.push(a1_1[i]);
}
}
//alert("addDakuten successful!");
a2 = ["ha","hi","fhu","he","ho"];
a2_1 = ["pa","pi","pu","pe","po"];
a2_2 = ["ba","bi","bu","be","bo"];
for (var i = 0, n = a2.length; i < n; i++) {
if (contains(source, a2[i])) {
temp.push(a2_1[i]);
temp.push(a2_2[i]);
}
}
//alert(temp);
}
function setSize() {
var values = [];
allcheckboxes = document.getElementsByClassName('romajicheckbox');
for (var j = 0, n = allcheckboxes.length; j < n; j++) {
if (!allcheckboxes[j].name.includes("all") && allcheckboxes[j].checked == true) {
values.push(allcheckboxes[j].value);
}
}
numberSelector = document.getElementById('number01');
numberSelector.value = values.length;
}
function setCookie() {
checkboxes = document.getElementsByClassName('romajicheckbox');
document.cookie = checkboxes;
}
function getCookie() {
checkboxes = document.cookie;
return checkboxes;
} |
/**
* FrameworkRouter uses a Framework object to implement an HTTP request
* listener that routes, decodes, validates, and calls user defined handlers.
*/
'use strict';
/**
* Module dependencies.
*/
var debug = require('debug')('swagger-framework:framework:router');
var lodash = require('lodash');
var routington = require('routington');
var url = require('url');
var http = require('../http');
var middleware = require('./middleware');
/**
* Initialize a new `FrameworkRouter`.
*
* @param {Framework} framework
* @api private
*/
function FrameworkRouter(framework) {
debug('create framework router');
this.framework = framework;
this.encoder = lodash.clone(http.encoder);
this.decoder = lodash.clone(http.decoder);
}
/**
* Stack middleware.
*
* @api private
*/
FrameworkRouter.prototype.stack = function(operation) {
var stack = [];
var ctx = {
operation: operation,
router: this,
};
stack.push(middleware.before(ctx));
stack.push(middleware.header(ctx));
stack.push(middleware.produces(ctx));
stack.push(middleware.path(ctx));
stack.push(middleware.query(ctx));
stack.push(middleware.authenticate(ctx));
stack.push(middleware.raw(ctx));
stack.push(middleware.consumes(ctx));
stack.push(middleware.form(ctx));
stack.push(middleware.body(ctx));
stack.push(middleware.authorize(ctx));
stack.push(middleware.after(ctx));
var fn = operation.fn;
if (fn && fn.length) stack = stack.concat(fn);
return stack.filter(function(fn) {
return typeof fn === 'function';
});
};
/**
* Build routes
*
* @api private
*/
FrameworkRouter.prototype.build = function(trie) {
var self = this;
if (!trie) trie = routington();
debug('framework router build');
lodash.forOwn(self.framework.apis, function(api) {
lodash.forOwn(api.resources, function(resource) {
// convert swagger path to routington
var path = resource.spec.path.replace(/\{(\w+)\}/g, function(src, dst) {
return ':' + dst;
});
// define resource path
var node = trie.define(path)[0];
// attach resource
node.resource = resource;
node.methods = {};
// add resource methods to trie
lodash.forOwn(resource.operations, function(operation, method) {
debug('%s %s build', method, path);
node.methods[method] = {
stack: self.stack(operation),
operation: operation
};
});
node.handle = function(req, res, parentNext) {
var method = node.methods[req.method];
if (!method) {
if (req.method === 'OPTIONS') {
http.options(req, res, Object.keys(node.methods));
return res.sf.reply(200, null);
}
if (req.method === 'HEAD') {
method = node.methods.GET;
}
}
if (!method) {
debug('%s %s method not found', req.method, req.sf.url.pathname);
return res.sf.reply(405);
}
req.sf.operation = method.operation;
// set etag support
req.sf.replyOptions.etag = method.operation.option('etag', false);
var i = 0;
(function next(err) {
if (err) {
debug('%s %s method error: %s', req.method, req.sf.url.pathname,
err);
return res.sf.reply(500, err);
}
var fn = method.stack[i++];
if (fn) {
fn(req, res, next);
} else {
if (typeof parentNext === 'function') {
parentNext();
} else {
// TODO: what should we do here?
debug('%s %s no more middleware', req.method,
req.sf.url.pathname);
res.sf.reply(400);
}
}
})();
};
});
});
return trie;
};
/**
* Setup and return route function.
*
* @api private
*/
FrameworkRouter.prototype.setup = function(options) {
var self = this;
// create trie
var trie = self.build();
// query string
var decode = self.decoder['application/x-www-form-urlencoded'];
return function(req, res) {
var replyOptions = {};
// swagger object
req.sf = res.sf = {
reply: http.reply(req, res, replyOptions),
router: self,
url: url.parse(req.url),
};
req.sf.replyOptions = replyOptions;
req.sf.url.query = decode(req.sf.url.query);
// setup
if (options.setup) options.setup(req, res);
return trie.match(req.sf.url.pathname);
};
};
/**
* Returns callback suitable `http.createServer()`.
*
* @api private
*/
FrameworkRouter.prototype.dispatcher = function(options) {
debug('framework router dispatcher');
options = options || {};
var route = this.setup(options);
// dispatch request
return function(req, res, next) {
var match = route(req, res);
debug('%s %s', req.method, req.sf.url.pathname);
// match path
if (match && match.node && match.node.handle) {
req.sf._params = match.param;
return match.node.handle(req, res, next);
}
if (typeof next === 'function') {
next();
} else {
res.sf.reply(404);
}
};
};
/**
* Expose FrameworkRouter.
*/
module.exports = FrameworkRouter;
|
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'adv_link', 'cs', {
acccessKey: 'Přístupový klíč',
advanced: 'Rozšířené',
advisoryContentType: 'Pomocný typ obsahu',
advisoryTitle: 'Pomocný titulek',
anchor: {
toolbar: 'Záložka',
menu: 'Vlastnosti záložky',
title: 'Vlastnosti záložky',
name: 'Název záložky',
errorName: 'Zadejte prosím název záložky',
remove: 'Odstranit záložku'
},
anchorId: 'Podle Id objektu',
anchorName: 'Podle jména kotvy',
charset: 'Přiřazená znaková sada',
cssClasses: 'Třída stylu',
emailAddress: 'E-mailová adresa',
emailBody: 'Tělo zprávy',
emailSubject: 'Předmět zprávy',
id: 'Id',
info: 'Informace o odkazu',
langCode: 'Kód jazyka',
langDir: 'Směr jazyka',
langDirLTR: 'Zleva doprava (LTR)',
langDirRTL: 'Zprava doleva (RTL)',
menu: 'Změnit odkaz',
name: 'Jméno',
noAnchors: '(Ve stránce není definována žádná kotva!)',
noEmail: 'Zadejte prosím e-mailovou adresu',
noUrl: 'Zadejte prosím URL odkazu',
other: '<jiný>',
popupDependent: 'Závislost (Netscape)',
popupFeatures: 'Vlastnosti vyskakovacího okna',
popupFullScreen: 'Celá obrazovka (IE)',
popupLeft: 'Levý okraj',
popupLocationBar: 'Panel umístění',
popupMenuBar: 'Panel nabídky',
popupResizable: 'Umožňující měnit velikost',
popupScrollBars: 'Posuvníky',
popupStatusBar: 'Stavový řádek',
popupToolbar: 'Panel nástrojů',
popupTop: 'Horní okraj',
rel: 'Vztah',
selectAnchor: 'Vybrat kotvu',
styles: 'Styl',
tabIndex: 'Pořadí prvku',
target: 'Cíl',
targetFrame: '<rámec>',
targetFrameName: 'Název cílového rámu',
targetPopup: '<vyskakovací okno>',
targetPopupName: 'Název vyskakovacího okna',
title: 'Odkaz',
toAnchor: 'Kotva v této stránce',
toEmail: 'E-mail',
toUrl: 'URL',
toolbar: 'Odkaz',
type: 'Typ odkazu',
unlink: 'Odstranit odkaz',
upload: 'Odeslat'
} );
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M4.01 8.54C5.2 9.23 6 10.52 6 12c0 1.47-.81 2.77-2 3.46V18h16V6H4l.01 2.54zm4.13 3.99 1.26.99 2.39-.64-2.4-4.16 1.4-.38 4.01 3.74 2.44-.65c.51-.14 1.04.17 1.18.68.13.51-.17 1.04-.69 1.19l-8.86 2.36-1.66-2.88.93-.25z",
opacity: ".3"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M20.19 4H4c-1.1 0-1.99.9-1.99 2v4c1.1 0 1.99.9 1.99 2s-.89 2-2 2v4c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.81-2-1.81-2zM20 18H4v-2.54c1.19-.69 2-1.99 2-3.46 0-1.48-.8-2.77-1.99-3.46L4 6h16v12z"
}, "1"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M17.73 13.3c.52-.15.82-.68.69-1.19-.14-.51-.67-.82-1.18-.68l-2.44.65-4.01-3.74-1.4.38 2.4 4.16-2.39.64-1.26-.99-.93.25 1.66 2.88 8.86-2.36z"
}, "2")], 'AirplaneTicketTwoTone');
exports.default = _default; |
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2022 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
var Class = require('../../utils/Class');
var Components = require('./components');
var Image = require('../../gameobjects/image/Image');
/**
* @classdesc
* An Arcade Physics Image is an Image with an Arcade Physics body and related components.
* The body can be dynamic or static.
*
* The main difference between an Arcade Image and an Arcade Sprite is that you cannot animate an Arcade Image.
*
* @class Image
* @extends Phaser.GameObjects.Image
* @memberof Phaser.Physics.Arcade
* @constructor
* @since 3.0.0
*
* @extends Phaser.Physics.Arcade.Components.Acceleration
* @extends Phaser.Physics.Arcade.Components.Angular
* @extends Phaser.Physics.Arcade.Components.Bounce
* @extends Phaser.Physics.Arcade.Components.Debug
* @extends Phaser.Physics.Arcade.Components.Drag
* @extends Phaser.Physics.Arcade.Components.Enable
* @extends Phaser.Physics.Arcade.Components.Friction
* @extends Phaser.Physics.Arcade.Components.Gravity
* @extends Phaser.Physics.Arcade.Components.Immovable
* @extends Phaser.Physics.Arcade.Components.Mass
* @extends Phaser.Physics.Arcade.Components.Pushable
* @extends Phaser.Physics.Arcade.Components.Size
* @extends Phaser.Physics.Arcade.Components.Velocity
* @extends Phaser.GameObjects.Components.Alpha
* @extends Phaser.GameObjects.Components.BlendMode
* @extends Phaser.GameObjects.Components.Depth
* @extends Phaser.GameObjects.Components.Flip
* @extends Phaser.GameObjects.Components.GetBounds
* @extends Phaser.GameObjects.Components.Origin
* @extends Phaser.GameObjects.Components.Pipeline
* @extends Phaser.GameObjects.Components.ScrollFactor
* @extends Phaser.GameObjects.Components.Size
* @extends Phaser.GameObjects.Components.Texture
* @extends Phaser.GameObjects.Components.Tint
* @extends Phaser.GameObjects.Components.Transform
* @extends Phaser.GameObjects.Components.Visible
*
* @param {Phaser.Scene} scene - The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time.
* @param {number} x - The horizontal position of this Game Object in the world.
* @param {number} y - The vertical position of this Game Object in the world.
* @param {(string|Phaser.Textures.Texture)} texture - The key, or instance of the Texture this Game Object will use to render with, as stored in the Texture Manager.
* @param {(string|number)} [frame] - An optional frame from the Texture this Game Object is rendering with.
*/
var ArcadeImage = new Class({
Extends: Image,
Mixins: [
Components.Acceleration,
Components.Angular,
Components.Bounce,
Components.Debug,
Components.Drag,
Components.Enable,
Components.Friction,
Components.Gravity,
Components.Immovable,
Components.Mass,
Components.Pushable,
Components.Size,
Components.Velocity
],
initialize:
function ArcadeImage (scene, x, y, texture, frame)
{
Image.call(this, scene, x, y, texture, frame);
/**
* This Game Object's Physics Body.
*
* @name Phaser.Physics.Arcade.Image#body
* @type {?(Phaser.Physics.Arcade.Body|Phaser.Physics.Arcade.StaticBody)}
* @default null
* @since 3.0.0
*/
this.body = null;
}
});
module.exports = ArcadeImage;
|
module('Davis.Route');
test("converting a string path into a regex", function () {
var route = factory('route')
ok((route.path instanceof RegExp), "should convert the path into a regular expression if it isn't already one");
ok(route.path.test('/foo'), "path regexp should match the right paths")
ok(!route.path.test('/bar'), "path regexp should not match the wrong paths")
ok(route.path.test("/foo"))
empty(route.paramNames, "should have no param names")
})
test("capturing the param names from a route", function () {
var route = factory('route', {
path: '/foo/:foo_id/bar/:bar_id'
})
ok(2, route.paramNames.length, "should have an entry for each param name in the path");
equal('foo_id', route.paramNames[0], "should capture the param names in the order that they appear")
equal('bar_id', route.paramNames[1], "should capture the param names in the order that they appear")
ok(route.path.test('/foo/12/bar/blah'), "should match the right kind of paths");
ok(!route.path.test('/bar/12/foo/blah'), "should not match the wrong kind of paths");
})
test('inoking a routes callback', function () {
var routeRan = false;
var route = factory('route', {
callback: function () {
routeRan = true
return "foo"
}
})
var response = route.run({
path: '/foo'
});
ok(routeRan, 'should run route callback when calling run');
equal(response, "foo", "should return whatever the callback returns")
})
test("handling route middleware", function () {
var handler = function () {},
middleware = function () {}
route = new Davis.Route('get', '/foo', [middleware, handler])
ok(route.handlers instanceof Array)
equal(2, route.handlers.length)
})
test("calling all handlers for a route", function () {
var handlerCalled = false,
middlewareCalled1 = false,
middlewareCalled2 = false,
handler = function (req) { handlerCalled = true },
middleware1 = function (req, next) { middlewareCalled1 = true ; next(req) },
middleware2 = function (req, next) { middlewareCalled2 = true ; next(req) },
route = new Davis.Route('get', '/foo', [middleware1, middleware2, handler])
route.run({path: '/foo'})
ok(handlerCalled)
ok(middlewareCalled1)
ok(middlewareCalled2)
})
test("middleware can modify the request for a route", function () {
var middleware = function (req, next) { req.foo = 'bar' ; next(req) }
route = new Davis.Route('get', '/foo', [middleware, function (req) {
equal(req.foo, 'bar')
}])
route.run({path: '/foo'})
})
test("middleware can halt execution by not calling next", function () {
var routeComplete = false,
middleware = function () {},
route = new Davis.Route('get', '/foo', middleware, function (req) {
routeComplete = true
})
route.run({path: '/foo'})
ok(!routeComplete)
})
test("wildcard matches", function () {
var route = new Davis.Route('get', '/foo/*splat', $.noop)
ok(route.path.test('/foo/bar/baz'))
ok(!route.path.test('/foo'))
ok(route.path.test('/foo/bar'))
})
test("wildcard param names", function () {
var params = null,
request = new Davis.Request ('/foo/bar/baz')
var route = new Davis.Route ('get', '/foo/*splat', function (req) {
params = req.params
})
route.run(request)
equal(params.splat, 'bar/baz')
})
test("wildcard and normal param names", function () {
var params = null,
request = new Davis.Request ('/foo/bar/baz/qwerty_123')
var route = new Davis.Route ('get', '/foo/:bar/*splat', function (req) {
params = req.params
})
route.run(request)
equal(params.bar, 'bar')
equal(params.splat, 'baz/qwerty_123')
})
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2020 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
var renderWebGL = require('../../utils/NOOP');
var renderCanvas = require('../../utils/NOOP');
if (typeof WEBGL_RENDERER)
{
renderWebGL = require('./RenderTextureWebGLRenderer');
}
if (typeof CANVAS_RENDERER)
{
renderCanvas = require('./RenderTextureCanvasRenderer');
}
module.exports = {
renderWebGL: renderWebGL,
renderCanvas: renderCanvas
};
|
import React, { Component, PropTypes } from 'react';
import _find from 'lodash/find';
import _without from 'lodash/without';
import Button from 'react-mdl/lib/Button';
import { provinces as allProvinces } from 'funong-common/lib/appConstants';
import { Dialog } from 'modules/common/dialog';
class ProvincesSelectorDialog extends Component {
static propTypes = {
close: PropTypes.func.isRequired,
show: PropTypes.bool.isRequired,
onSubmit: PropTypes.func.isRequired,
provinces: PropTypes.array.isRequired,
};
constructor(props) {
super(props);
const { provinces } = props;
this.state = { provinces: [...provinces] };
}
select = (province) => {
this.setState({ provinces: [...this.state.provinces, province] });
}
deselect = (province) => {
this.setState({ provinces: _without(this.state.provinces, province) });
}
submit = () => {
this.props.onSubmit(this.state.provinces);
}
render() {
const { close, show } = this.props;
const { provinces } = this.state;
return (
<Dialog
show={show}
onHide={close}
onCancel={close}
title={'选择服务区域'}
scrollableContent={
<div>
{allProvinces.map((p, i) => {
const selected = !!_find(provinces, (province) => province.value === p.value);
return (
<Button
key={i}
colored={selected}
onClick={(e) => {
e.preventDefault();
if (selected) {
this.deselect(p);
} else {
this.select(p);
}
}}
>{p.title}</Button>
);
})}
</div>
}
submit={{
onSubmit: (e) => { e.preventDefault(); this.submit(); },
disabled: provinces.length === 0,
}}
/>
);
}
}
export default ProvincesSelectorDialog;
|
'use strict';
angular.module('utils', ['ionic'])
/**
* @name getData
* @param {string} path to file, relative to www/data
* @param {function} optional callback accepts error object
* @returns {object} promise yielding json file contents
*/
.provider('getData', function ($logProvider) {
var $http = angular.injector(['ng']).get('$http');
this.$get = function () {
return function (path, failure) {
return $http.get('/data/' + path).catch(
function (error) {
if (failure) {
return failure(error);
} else {
$logProvider.get().error('getData', JSON.stringify(error));
}
});
};
};
})
// based on http://learn.ionicframework.com/formulas/localstorage/
/**
* @name localStorage
*/
.service('localStorage', ['$window', function ($window) {
/**
* set value
* @param {string} key
* @param {object} value
*/
this.set = function (key, value) {
$window.localStorage[key] = value;
};
this.get = function (key, defaultValue) {
return $window.localStorage[key] || defaultValue;
};
this.setObject = function (key, value) {
$window.localStorage[key] = JSON.stringify(value);
};
this.getObject = function (key) {
return JSON.parse($window.localStorage[key] || '{}');
};
}])
.constant('_', window._) // underscore.js access
// TODO test media service: Adapted from
// http://forum.ionicframework.com/t/how-to-play-local-audio-files/7479/5
// for media plugin :
// http://plugins.cordova.io/#/package/org.apache.cordova.media
// Usage:
// MediaSrv.loadMedia('sounds/mysound.mp3').then(function (media) {
// media.play();
// });
.factory('MediaSrv', function ($q, $ionicPlatform, $window, $log) {
function loadMedia(src, onError, onStatus, onStop) {
var defer = $q.defer();
$ionicPlatform.ready(function () {
var mediaSuccess = function () {
if (onStop) {
onStop();
}
};
var mediaError = function (err) {
_logError(src, err);
if (onError) {
onError(err);
}
};
var mediaStatus = function (status) {
if (onStatus) {
onStatus(status);
}
};
if ($ionicPlatform.is('android')) {
src = '/android_asset/www/' + src;
}
defer.resolve(new $window.Media(src, mediaSuccess, mediaError, mediaStatus));
});
return defer.promise;
}
function _logError(src, err) {
$log.error('media error', {
code: err.code,
message: getErrorMessage(err.code)
});
}
function getStatusMessage(status) {
if (status === 0) {
return 'Media.MEDIA_NONE';
} else if (status === 1) {
return 'Media.MEDIA_STARTING';
} else if (status === 2) {
return 'Media.MEDIA_RUNNING';
} else if (status === 3) {
return 'Media.MEDIA_PAUSED';
} else if (status === 4) {
return 'Media.MEDIA_STOPPED';
} else {
return 'Unknown status <' + status + '>';
}
}
function getErrorMessage(code) {
if (code === 1) {
return 'MediaError.MEDIA_ERR_ABORTED';
} else if (code === 2) {
return 'MediaError.MEDIA_ERR_NETWORK';
} else if (code === 3) {
return 'MediaError.MEDIA_ERR_DECODE';
} else if (code === 4) {
return 'MediaError.MEDIA_ERR_NONE_SUPPORTED';
} else {
return 'Unknown code <' + code + '>';
}
}
var service = {
loadMedia: loadMedia,
getStatusMessage: getStatusMessage,
getErrorMessage: getErrorMessage
};
return service;
});
|
/* globals Drop */
import Component from '@ember/component';
import { observer } from '@ember/object';
import { run } from '@ember/runloop';
export default Component.extend({
tagName: '',
contentChanged: observer('content', function() {
this.initialize();
}),
didInsertElement() {
this.initialize();
},
willDestroyElement() {
if (this.get('drop')) {
this.get('drop').destroy();
}
},
initialize() {
run.scheduleOnce('afterRender', this, function() {
let content = document.createElement('div');
if (this.get('content') && Array.isArray(this.get('content'))) {
this.get('content').forEach((element) => {
if (element.type) {
let elementToAppend = document.createElement(element.type);
if (element.classes) {
elementToAppend.classList.add(element.classes);
}
if (element.text) {
elementToAppend.textContent = element.text;
}
if (element.events) {
if (element.events.click && typeof element.events.click === 'function') {
elementToAppend.onclick = element.events.click;
}
}
let containerDiv = document.createElement('div');
containerDiv.appendChild(elementToAppend);
content.appendChild(containerDiv);
}
});
}
content.classList.add('content');
let drop = new Drop({
classes: this.get('classes') || '',
constrainToScrollParent: this.get('constrainToScrollParent') !== false,
constrainToWindow: this.get('constrainToWindow') !== false,
content,
openOn: this.get('openOn') || 'click',
position: this.get('position') || 'bottom left',
remove: this.get('remove'),
target: document.querySelector(this.get('targetSelector')),
tetherOptions: this.get('tetherOptions') || {}
});
this.set('drop', drop);
});
}
});
|
module.exports = require("npm:cssom@0.3.0/lib/index"); |
// returns JSON if JSON, false if not
// valueIfJSON - value to return instead of json
module.exports = function checkJSON(json, valueIfJSON) {
try {
json = JSON.parse(json);
} catch (e) {
return false;
}
return valueIfJSON || json;
};
|
jQuery.noConflict();
/*! GLOBAL.VARS */
var ocomltxt = [];
ocomltxt.en = {
more: "More",
readmore: "Read More",
close: "Close",
link2txt: "Paste link in <strong>email</strong> or <strong>IM</strong>",
finish: "Finish",
alreadymember: "Already a member?",
login: "Login",
logout: "Logout",
joinnow: "Join Now",
welcome: "Welcome",
visitorname: "visitor-name"
};
/*! LANG DETECT */
var ocomlang = "en";
/*!
* JQUERY.UI v1.9.2 - 2012-12-05
* http://jqueryui.com
* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.position.js, jquery.ui.autocomplete.js, jquery.ui.menu.js
* Copyright (c) 2012 jQuery Foundation and other contributors Licensed MIT
*/
(function (e, t)
{
function i(t, n)
{
var r, i, o, u = t.nodeName.toLowerCase();
return "area" === u ? (r = t.parentNode, i = r.name, !t.href || !i || r.nodeName.toLowerCase() !== "map" ? !1 : (o = e("img[usemap=#" + i + "]")[0], !! o && s(o))) : (/input|select|textarea|button|object/.test(u) ? !t.disabled : "a" === u ? t.href || n : n) && s(t)
}
function s(t)
{
return e.expr.filters.visible(t) && !e(t).parents().andSelf().filter(function ()
{
return e.css(this, "visibility") === "hidden"
}).length
}
var n = 0,
r = /^ui-id-\d+$/;
e.ui = e.ui ||
{};
if (e.ui.version) return;
e.extend(e.ui,
{
version: "1.9.2",
keyCode:
{
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
}
}), e.fn.extend(
{
_focus: e.fn.focus,
focus: function (t, n)
{
return typeof t == "number" ? this.each(function ()
{
var r = this;
setTimeout(function ()
{
e(r).focus(), n && n.call(r)
}, t)
}) : this._focus.apply(this, arguments)
},
scrollParent: function ()
{
var t;
return e.ui.ie && /(static|relative)/.test(this.css("position")) || /absolute/.test(this.css("position")) ? t = this.parents().filter(function ()
{
return /(relative|absolute|fixed)/.test(e.css(this, "position")) && /(auto|scroll)/.test(e.css(this, "overflow") + e.css(this, "overflow-y") + e.css(this, "overflow-x"))
}).eq(0) : t = this.parents().filter(function ()
{
return /(auto|scroll)/.test(e.css(this, "overflow") + e.css(this, "overflow-y") + e.css(this, "overflow-x"))
}).eq(0), /fixed/.test(this.css("position")) || !t.length ? e(document) : t
},
zIndex: function (n)
{
if (n !== t) return this.css("zIndex", n);
if (this.length)
{
var r = e(this[0]),
i, s;
while (r.length && r[0] !== document)
{
i = r.css("position");
if (i === "absolute" || i === "relative" || i === "fixed")
{
s = parseInt(r.css("zIndex"), 10);
if (!isNaN(s) && s !== 0) return s
}
r = r.parent()
}
}
return 0
},
uniqueId: function ()
{
return this.each(function ()
{
this.id || (this.id = "ui-id-" + ++n)
})
},
removeUniqueId: function ()
{
return this.each(function ()
{
r.test(this.id) && e(this).removeAttr("id")
})
}
}), e.extend(e.expr[":"],
{
data: e.expr.createPseudo ? e.expr.createPseudo(function (t)
{
return function (n)
{
return !!e.data(n, t)
}
}) : function (t, n, r)
{
return !!e.data(t, r[3])
},
focusable: function (t)
{
return i(t, !isNaN(e.attr(t, "tabindex")))
},
tabbable: function (t)
{
var n = e.attr(t, "tabindex"),
r = isNaN(n);
return (r || n >= 0) && i(t, !r)
}
}), e(function ()
{
var t = document.body,
n = t.appendChild(n = document.createElement("div"));
n.offsetHeight, e.extend(n.style,
{
minHeight: "100px",
height: "auto",
padding: 0,
borderWidth: 0
}), e.support.minHeight = n.offsetHeight === 100, e.support.selectstart = "onselectstart" in n, t.removeChild(n).style.display = "none"
}), e("<a>").outerWidth(1).jquery || e.each(["Width", "Height"], function (n, r)
{
function u(t, n, r, s)
{
return e.each(i, function ()
{
n -= parseFloat(e.css(t, "padding" + this)) || 0, r && (n -= parseFloat(e.css(t, "border" + this + "Width")) || 0), s && (n -= parseFloat(e.css(t, "margin" + this)) || 0)
}), n
}
var i = r === "Width" ? ["Left", "Right"] : ["Top", "Bottom"],
s = r.toLowerCase(),
o = {
innerWidth: e.fn.innerWidth,
innerHeight: e.fn.innerHeight,
outerWidth: e.fn.outerWidth,
outerHeight: e.fn.outerHeight
};
e.fn["inner" + r] = function (n)
{
return n === t ? o["inner" + r].call(this) : this.each(function ()
{
e(this).css(s, u(this, n) + "px")
})
}, e.fn["outer" + r] = function (t, n)
{
return typeof t != "number" ? o["outer" + r].call(this, t) : this.each(function ()
{
e(this).css(s, u(this, t, !0, n) + "px")
})
}
}), e("<a>").data("a-b", "a").removeData("a-b").data("a-b") && (e.fn.removeData = function (t)
{
return function (n)
{
return arguments.length ? t.call(this, e.camelCase(n)) : t.call(this)
}
}(e.fn.removeData)),
function ()
{
var t = /msie ([\w.]+)/.exec(navigator.userAgent.toLowerCase()) || [];
e.ui.ie = t.length ? !0 : !1, e.ui.ie6 = parseFloat(t[1], 10) === 6
}(), e.fn.extend(
{
disableSelection: function ()
{
return this.bind((e.support.selectstart ? "selectstart" : "mousedown") + ".ui-disableSelection", function (e)
{
e.preventDefault()
})
},
enableSelection: function ()
{
return this.unbind(".ui-disableSelection")
}
}), e.extend(e.ui,
{
plugin:
{
add: function (t, n, r)
{
var i, s = e.ui[t].prototype;
for (i in r) s.plugins[i] = s.plugins[i] || [], s.plugins[i].push([n, r[i]])
},
call: function (e, t, n)
{
var r, i = e.plugins[t];
if (!i || !e.element[0].parentNode || e.element[0].parentNode.nodeType === 11) return;
for (r = 0; r < i.length; r++) e.options[i[r][0]] && i[r][1].apply(e.element, n)
}
},
contains: e.contains,
hasScroll: function (t, n)
{
if (e(t).css("overflow") === "hidden") return !1;
var r = n && n === "left" ? "scrollLeft" : "scrollTop",
i = !1;
return t[r] > 0 ? !0 : (t[r] = 1, i = t[r] > 0, t[r] = 0, i)
},
isOverAxis: function (e, t, n)
{
return e > t && e < t + n
},
isOver: function (t, n, r, i, s, o)
{
return e.ui.isOverAxis(t, r, s) && e.ui.isOverAxis(n, i, o)
}
})
})(jQuery);
(function (e, t)
{
var n = 0,
r = Array.prototype.slice,
i = e.cleanData;
e.cleanData = function (t)
{
for (var n = 0, r;
(r = t[n]) != null; n++) try
{
e(r).triggerHandler("remove")
}
catch (s)
{}
i(t)
}, e.widget = function (t, n, r)
{
var i, s, o, u, a = t.split(".")[0];
t = t.split(".")[1], i = a + "-" + t, r || (r = n, n = e.Widget), e.expr[":"][i.toLowerCase()] = function (t)
{
return !!e.data(t, i)
}, e[a] = e[a] ||
{}, s = e[a][t], o = e[a][t] = function (e, t)
{
if (!this._createWidget) return new o(e, t);
arguments.length && this._createWidget(e, t)
}, e.extend(o, s,
{
version: r.version,
_proto: e.extend(
{}, r),
_childConstructors: []
}), u = new n, u.options = e.widget.extend(
{}, u.options), e.each(r, function (t, i)
{
e.isFunction(i) && (r[t] = function ()
{
var e = function ()
{
return n.prototype[t].apply(this, arguments)
}, r = function (e)
{
return n.prototype[t].apply(this, e)
};
return function ()
{
var t = this._super,
n = this._superApply,
s;
return this._super = e, this._superApply = r, s = i.apply(this, arguments), this._super = t, this._superApply = n, s
}
}())
}), o.prototype = e.widget.extend(u,
{
widgetEventPrefix: s ? u.widgetEventPrefix : t
}, r,
{
constructor: o,
namespace: a,
widgetName: t,
widgetBaseClass: i,
widgetFullName: i
}), s ? (e.each(s._childConstructors, function (t, n)
{
var r = n.prototype;
e.widget(r.namespace + "." + r.widgetName, o, n._proto)
}), delete s._childConstructors) : n._childConstructors.push(o), e.widget.bridge(t, o)
}, e.widget.extend = function (n)
{
var i = r.call(arguments, 1),
s = 0,
o = i.length,
u, a;
for (; s < o; s++)
for (u in i[s]) a = i[s][u], i[s].hasOwnProperty(u) && a !== t && (e.isPlainObject(a) ? n[u] = e.isPlainObject(n[u]) ? e.widget.extend(
{}, n[u], a) : e.widget.extend(
{}, a) : n[u] = a);
return n
}, e.widget.bridge = function (n, i)
{
var s = i.prototype.widgetFullName || n;
e.fn[n] = function (o)
{
var u = typeof o == "string",
a = r.call(arguments, 1),
f = this;
return o = !u && a.length ? e.widget.extend.apply(null, [o].concat(a)) : o, u ? this.each(function ()
{
var r, i = e.data(this, s);
if (!i) return e.error("cannot call methods on " + n + " prior to initialization; " + "attempted to call method '" + o + "'");
if (!e.isFunction(i[o]) || o.charAt(0) === "_") return e.error("no such method '" + o + "' for " + n + " widget instance");
r = i[o].apply(i, a);
if (r !== i && r !== t) return f = r && r.jquery ? f.pushStack(r.get()) : r, !1
}) : this.each(function ()
{
var t = e.data(this, s);
t ? t.option(o ||
{})._init() : e.data(this, s, new i(o, this))
}), f
}
}, e.Widget = function () {}, e.Widget._childConstructors = [], e.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options:
{
disabled: !1,
create: null
},
_createWidget: function (t, r)
{
r = e(r || this.defaultElement || this)[0], this.element = e(r), this.uuid = n++, this.eventNamespace = "." + this.widgetName + this.uuid, this.options = e.widget.extend(
{}, this.options, this._getCreateOptions(), t), this.bindings = e(), this.hoverable = e(), this.focusable = e(), r !== this && (e.data(r, this.widgetName, this), e.data(r, this.widgetFullName, this), this._on(!0, this.element,
{
remove: function (e)
{
e.target === r && this.destroy()
}
}), this.document = e(r.style ? r.ownerDocument : r.document || r), this.window = e(this.document[0].defaultView || this.document[0].parentWindow)), this._create(), this._trigger("create", null, this._getCreateEventData()), this._init()
},
_getCreateOptions: e.noop,
_getCreateEventData: e.noop,
_create: e.noop,
_init: e.noop,
destroy: function ()
{
this._destroy(), this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)), this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName + "-disabled " + "ui-state-disabled"), this.bindings.unbind(this.eventNamespace), this.hoverable.removeClass("ui-state-hover"), this.focusable.removeClass("ui-state-focus")
},
_destroy: e.noop,
widget: function ()
{
return this.element
},
option: function (n, r)
{
var i = n,
s, o, u;
if (arguments.length === 0) return e.widget.extend(
{}, this.options);
if (typeof n == "string")
{
i = {}, s = n.split("."), n = s.shift();
if (s.length)
{
o = i[n] = e.widget.extend(
{}, this.options[n]);
for (u = 0; u < s.length - 1; u++) o[s[u]] = o[s[u]] ||
{}, o = o[s[u]];
n = s.pop();
if (r === t) return o[n] === t ? null : o[n];
o[n] = r
}
else
{
if (r === t) return this.options[n] === t ? null : this.options[n];
i[n] = r
}
}
return this._setOptions(i), this
},
_setOptions: function (e)
{
var t;
for (t in e) this._setOption(t, e[t]);
return this
},
_setOption: function (e, t)
{
return this.options[e] = t, e === "disabled" && (this.widget().toggleClass(this.widgetFullName + "-disabled ui-state-disabled", !! t).attr("aria-disabled", t), this.hoverable.removeClass("ui-state-hover"), this.focusable.removeClass("ui-state-focus")), this
},
enable: function ()
{
return this._setOption("disabled", !1)
},
disable: function ()
{
return this._setOption("disabled", !0)
},
_on: function (t, n, r)
{
var i, s = this;
typeof t != "boolean" && (r = n, n = t, t = !1), r ? (n = i = e(n), this.bindings = this.bindings.add(n)) : (r = n, n = this.element, i = this.widget()), e.each(r, function (r, o)
{
function u()
{
if (!t && (s.options.disabled === !0 || e(this).hasClass("ui-state-disabled"))) return;
return (typeof o == "string" ? s[o] : o).apply(s, arguments)
}
typeof o != "string" && (u.guid = o.guid = o.guid || u.guid || e.guid++);
var a = r.match(/^(\w+)\s*(.*)$/),
f = a[1] + s.eventNamespace,
l = a[2];
l ? i.delegate(l, f, u) : n.bind(f, u)
})
},
_off: function (e, t)
{
t = (t || "").split(" ").join(this.eventNamespace + " ") + this.eventNamespace, e.unbind(t).undelegate(t)
},
_delay: function (e, t)
{
function n()
{
return (typeof e == "string" ? r[e] : e).apply(r, arguments)
}
var r = this;
return setTimeout(n, t || 0)
},
_hoverable: function (t)
{
this.hoverable = this.hoverable.add(t), this._on(t,
{
mouseenter: function (t)
{
e(t.currentTarget).addClass("ui-state-hover")
},
mouseleave: function (t)
{
e(t.currentTarget).removeClass("ui-state-hover")
}
})
},
_focusable: function (t)
{
this.focusable = this.focusable.add(t), this._on(t,
{
focusin: function (t)
{
e(t.currentTarget).addClass("ui-state-focus")
},
focusout: function (t)
{
e(t.currentTarget).removeClass("ui-state-focus")
}
})
},
_trigger: function (t, n, r)
{
var i, s, o = this.options[t];
r = r ||
{}, n = e.Event(n), n.type = (t === this.widgetEventPrefix ? t : this.widgetEventPrefix + t).toLowerCase(), n.target = this.element[0], s = n.originalEvent;
if (s)
for (i in s) i in n || (n[i] = s[i]);
return this.element.trigger(n, r), !(e.isFunction(o) && o.apply(this.element[0], [n].concat(r)) === !1 || n.isDefaultPrevented())
}
}, e.each(
{
show: "fadeIn",
hide: "fadeOut"
}, function (t, n)
{
e.Widget.prototype["_" + t] = function (r, i, s)
{
typeof i == "string" && (i = {
effect: i
});
var o, u = i ? i === !0 || typeof i == "number" ? n : i.effect || n : t;
i = i ||
{}, typeof i == "number" && (i = {
duration: i
}), o = !e.isEmptyObject(i), i.complete = s, i.delay && r.delay(i.delay), o && e.effects && (e.effects.effect[u] || e.uiBackCompat !== !1 && e.effects[u]) ? r[t](i) : u !== t && r[u] ? r[u](i.duration, i.easing, s) : r.queue(function (n)
{
e(this)[t](), s && s.call(r[0]), n()
})
}
}), e.uiBackCompat !== !1 && (e.Widget.prototype._getCreateOptions = function ()
{
return e.metadata && e.metadata.get(this.element[0])[this.widgetName]
})
})(jQuery);
(function (e, t)
{
function h(e, t, n)
{
return [parseInt(e[0], 10) * (l.test(e[0]) ? t / 100 : 1), parseInt(e[1], 10) * (l.test(e[1]) ? n / 100 : 1)]
}
function p(t, n)
{
return parseInt(e.css(t, n), 10) || 0
}
e.ui = e.ui ||
{};
var n, r = Math.max,
i = Math.abs,
s = Math.round,
o = /left|center|right/,
u = /top|center|bottom/,
a = /[\+\-]\d+%?/,
f = /^\w+/,
l = /%$/,
c = e.fn.position;
e.position = {
scrollbarWidth: function ()
{
if (n !== t) return n;
var r, i, s = e("<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),
o = s.children()[0];
return e("body").append(s), r = o.offsetWidth, s.css("overflow", "scroll"), i = o.offsetWidth, r === i && (i = s[0].clientWidth), s.remove(), n = r - i
},
getScrollInfo: function (t)
{
var n = t.isWindow ? "" : t.element.css("overflow-x"),
r = t.isWindow ? "" : t.element.css("overflow-y"),
i = n === "scroll" || n === "auto" && t.width < t.element[0].scrollWidth,
s = r === "scroll" || r === "auto" && t.height < t.element[0].scrollHeight;
return {
width: i ? e.position.scrollbarWidth() : 0,
height: s ? e.position.scrollbarWidth() : 0
}
},
getWithinInfo: function (t)
{
var n = e(t || window),
r = e.isWindow(n[0]);
return {
element: n,
isWindow: r,
offset: n.offset() ||
{
left: 0,
top: 0
},
scrollLeft: n.scrollLeft(),
scrollTop: n.scrollTop(),
width: r ? n.width() : n.outerWidth(),
height: r ? n.height() : n.outerHeight()
}
}
}, e.fn.position = function (t)
{
if (!t || !t.of) return c.apply(this, arguments);
t = e.extend(
{}, t);
var n, l, d, v, m, g = e(t.of),
y = e.position.getWithinInfo(t.within),
b = e.position.getScrollInfo(y),
w = g[0],
E = (t.collision || "flip").split(" "),
S = {};
return w.nodeType === 9 ? (l = g.width(), d = g.height(), v = {
top: 0,
left: 0
}) : e.isWindow(w) ? (l = g.width(), d = g.height(), v = {
top: g.scrollTop(),
left: g.scrollLeft()
}) : w.preventDefault ? (t.at = "left top", l = d = 0, v = {
top: w.pageY,
left: w.pageX
}) : (l = g.outerWidth(), d = g.outerHeight(), v = g.offset()), m = e.extend(
{}, v), e.each(["my", "at"], function ()
{
var e = (t[this] || "").split(" "),
n, r;
e.length === 1 && (e = o.test(e[0]) ? e.concat(["center"]) : u.test(e[0]) ? ["center"].concat(e) : ["center", "center"]), e[0] = o.test(e[0]) ? e[0] : "center", e[1] = u.test(e[1]) ? e[1] : "center", n = a.exec(e[0]), r = a.exec(e[1]), S[this] = [n ? n[0] : 0, r ? r[0] : 0], t[this] = [f.exec(e[0])[0], f.exec(e[1])[0]]
}), E.length === 1 && (E[1] = E[0]), t.at[0] === "right" ? m.left += l : t.at[0] === "center" && (m.left += l / 2), t.at[1] === "bottom" ? m.top += d : t.at[1] === "center" && (m.top += d / 2), n = h(S.at, l, d), m.left += n[0], m.top += n[1], this.each(function ()
{
var o, u, a = e(this),
f = a.outerWidth(),
c = a.outerHeight(),
w = p(this, "marginLeft"),
x = p(this, "marginTop"),
T = f + w + p(this, "marginRight") + b.width,
N = c + x + p(this, "marginBottom") + b.height,
C = e.extend(
{}, m),
k = h(S.my, a.outerWidth(), a.outerHeight());
t.my[0] === "right" ? C.left -= f : t.my[0] === "center" && (C.left -= f / 2), t.my[1] === "bottom" ? C.top -= c : t.my[1] === "center" && (C.top -= c / 2), C.left += k[0], C.top += k[1], e.support.offsetFractions || (C.left = s(C.left), C.top = s(C.top)), o = {
marginLeft: w,
marginTop: x
}, e.each(["left", "top"], function (r, i)
{
e.ui.position[E[r]] && e.ui.position[E[r]][i](C,
{
targetWidth: l,
targetHeight: d,
elemWidth: f,
elemHeight: c,
collisionPosition: o,
collisionWidth: T,
collisionHeight: N,
offset: [n[0] + k[0], n[1] + k[1]],
my: t.my,
at: t.at,
within: y,
elem: a
})
}), e.fn.bgiframe && a.bgiframe(), t.using && (u = function (e)
{
var n = v.left - C.left,
s = n + l - f,
o = v.top - C.top,
u = o + d - c,
h = {
target:
{
element: g,
left: v.left,
top: v.top,
width: l,
height: d
},
element:
{
element: a,
left: C.left,
top: C.top,
width: f,
height: c
},
horizontal: s < 0 ? "left" : n > 0 ? "right" : "center",
vertical: u < 0 ? "top" : o > 0 ? "bottom" : "middle"
};
l < f && i(n + s) < l && (h.horizontal = "center"), d < c && i(o + u) < d && (h.vertical = "middle"), r(i(n), i(s)) > r(i(o), i(u)) ? h.important = "horizontal" : h.important = "vertical", t.using.call(this, e, h)
}), a.offset(e.extend(C,
{
using: u
}))
})
}, e.ui.position = {
fit:
{
left: function (e, t)
{
var n = t.within,
i = n.isWindow ? n.scrollLeft : n.offset.left,
s = n.width,
o = e.left - t.collisionPosition.marginLeft,
u = i - o,
a = o + t.collisionWidth - s - i,
f;
t.collisionWidth > s ? u > 0 && a <= 0 ? (f = e.left + u + t.collisionWidth - s - i, e.left += u - f) : a > 0 && u <= 0 ? e.left = i : u > a ? e.left = i + s - t.collisionWidth : e.left = i : u > 0 ? e.left += u : a > 0 ? e.left -= a : e.left = r(e.left - o, e.left)
},
top: function (e, t)
{
var n = t.within,
i = n.isWindow ? n.scrollTop : n.offset.top,
s = t.within.height,
o = e.top - t.collisionPosition.marginTop,
u = i - o,
a = o + t.collisionHeight - s - i,
f;
t.collisionHeight > s ? u > 0 && a <= 0 ? (f = e.top + u + t.collisionHeight - s - i, e.top += u - f) : a > 0 && u <= 0 ? e.top = i : u > a ? e.top = i + s - t.collisionHeight : e.top = i : u > 0 ? e.top += u : a > 0 ? e.top -= a : e.top = r(e.top - o, e.top)
}
},
flip:
{
left: function (e, t)
{
var n = t.within,
r = n.offset.left + n.scrollLeft,
s = n.width,
o = n.isWindow ? n.scrollLeft : n.offset.left,
u = e.left - t.collisionPosition.marginLeft,
a = u - o,
f = u + t.collisionWidth - s - o,
l = t.my[0] === "left" ? -t.elemWidth : t.my[0] === "right" ? t.elemWidth : 0,
c = t.at[0] === "left" ? t.targetWidth : t.at[0] === "right" ? -t.targetWidth : 0,
h = -2 * t.offset[0],
p, d;
if (a < 0)
{
p = e.left + l + c + h + t.collisionWidth - s - r;
if (p < 0 || p < i(a)) e.left += l + c + h
}
else if (f > 0)
{
d = e.left - t.collisionPosition.marginLeft + l + c + h - o;
if (d > 0 || i(d) < f) e.left += l + c + h
}
},
top: function (e, t)
{
var n = t.within,
r = n.offset.top + n.scrollTop,
s = n.height,
o = n.isWindow ? n.scrollTop : n.offset.top,
u = e.top - t.collisionPosition.marginTop,
a = u - o,
f = u + t.collisionHeight - s - o,
l = t.my[1] === "top",
c = l ? -t.elemHeight : t.my[1] === "bottom" ? t.elemHeight : 0,
h = t.at[1] === "top" ? t.targetHeight : t.at[1] === "bottom" ? -t.targetHeight : 0,
p = -2 * t.offset[1],
d, v;
a < 0 ? (v = e.top + c + h + p + t.collisionHeight - s - r, e.top + c + h + p > a && (v < 0 || v < i(a)) && (e.top += c + h + p)) : f > 0 && (d = e.top - t.collisionPosition.marginTop + c + h + p - o, e.top + c + h + p > f && (d > 0 || i(d) < f) && (e.top += c + h + p))
}
},
flipfit:
{
left: function ()
{
e.ui.position.flip.left.apply(this, arguments), e.ui.position.fit.left.apply(this, arguments)
},
top: function ()
{
e.ui.position.flip.top.apply(this, arguments), e.ui.position.fit.top.apply(this, arguments)
}
}
},
function ()
{
var t, n, r, i, s, o = document.getElementsByTagName("body")[0],
u = document.createElement("div");
t = document.createElement(o ? "div" : "body"), r = {
visibility: "hidden",
width: 0,
height: 0,
border: 0,
margin: 0,
background: "none"
}, o && e.extend(r,
{
position: "absolute",
left: "-1000px",
top: "-1000px"
});
for (s in r) t.style[s] = r[s];
t.appendChild(u), n = o || document.documentElement, n.insertBefore(t, n.firstChild), u.style.cssText = "position: absolute; left: 10.7432222px;", i = e(u).offset().left, e.support.offsetFractions = i > 10 && i < 11, t.innerHTML = "", n.removeChild(t)
}(), e.uiBackCompat !== !1 && function (e)
{
var n = e.fn.position;
e.fn.position = function (r)
{
if (!r || !r.offset) return n.call(this, r);
var i = r.offset.split(" "),
s = r.at.split(" ");
return i.length === 1 && (i[1] = i[0]), /^\d/.test(i[0]) && (i[0] = "+" + i[0]), /^\d/.test(i[1]) && (i[1] = "+" + i[1]), s.length === 1 && (/left|center|right/.test(s[0]) ? s[1] = "center" : (s[1] = s[0], s[0] = "center")), n.call(this, e.extend(r,
{
at: s[0] + i[0] + " " + s[1] + i[1],
offset: t
}))
}
}(jQuery)
})(jQuery);
(function (e, t)
{
var n = 0;
e.widget("ui.autocomplete",
{
version: "1.9.2",
defaultElement: "<input>",
options:
{
appendTo: "body",
autoFocus: !1,
delay: 300,
minLength: 1,
position:
{
my: "left top",
at: "left bottom",
collision: "none"
},
source: null,
change: null,
close: null,
focus: null,
open: null,
response: null,
search: null,
select: null
},
pending: 0,
_create: function ()
{
var t, n, r;
this.isMultiLine = this._isMultiLine(), this.valueMethod = this.element[this.element.is("input,textarea") ? "val" : "text"], this.isNewMenu = !0, this.element.addClass("ui-autocomplete-input").attr("autocomplete", "off"), this._on(this.element,
{
keydown: function (i)
{
if (this.element.prop("readOnly"))
{
t = !0, r = !0, n = !0;
return
}
t = !1, r = !1, n = !1;
var s = e.ui.keyCode;
switch (i.keyCode)
{
case s.PAGE_UP:
t = !0, this._move("previousPage", i);
break;
case s.PAGE_DOWN:
t = !0, this._move("nextPage", i);
break;
case s.UP:
t = !0, this._keyEvent("previous", i);
break;
case s.DOWN:
t = !0, this._keyEvent("next", i);
break;
case s.ENTER:
case s.NUMPAD_ENTER:
this.menu.active && (t = !0, i.preventDefault(), this.menu.select(i));
break;
case s.TAB:
this.menu.active && this.menu.select(i);
break;
case s.ESCAPE:
this.menu.element.is(":visible") && (this._value(this.term), this.close(i), i.preventDefault());
break;
default:
n = !0, this._searchTimeout(i)
}
},
keypress: function (r)
{
if (t)
{
t = !1, r.preventDefault();
return
}
if (n) return;
var i = e.ui.keyCode;
switch (r.keyCode)
{
case i.PAGE_UP:
this._move("previousPage", r);
break;
case i.PAGE_DOWN:
this._move("nextPage", r);
break;
case i.UP:
this._keyEvent("previous", r);
break;
case i.DOWN:
this._keyEvent("next", r)
}
},
input: function (e)
{
if (r)
{
r = !1, e.preventDefault();
return
}
this._searchTimeout(e)
},
focus: function ()
{
this.selectedItem = null, this.previous = this._value()
},
blur: function (e)
{
if (this.cancelBlur)
{
delete this.cancelBlur;
return
}
clearTimeout(this.searching), this.close(e), this._change(e)
}
}), this._initSource(), this.menu = e("<ul>").addClass("ui-autocomplete").appendTo(this.document.find(this.options.appendTo || "body")[0]).menu(
{
input: e(),
role: null
}).zIndex(this.element.zIndex() + 1).hide().data("menu"), this._on(this.menu.element,
{
mousedown: function (t)
{
t.preventDefault(), this.cancelBlur = !0, this._delay(function ()
{
delete this.cancelBlur
});
var n = this.menu.element[0];
e(t.target).closest(".ui-menu-item").length || this._delay(function ()
{
var t = this;
this.document.one("mousedown", function (r)
{
r.target !== t.element[0] && r.target !== n && !e.contains(n, r.target) && t.close()
})
})
},
menufocus: function (t, n)
{
if (this.isNewMenu)
{
this.isNewMenu = !1;
if (t.originalEvent && /^mouse/.test(t.originalEvent.type))
{
this.menu.blur(), this.document.one("mousemove", function ()
{
e(t.target).trigger(t.originalEvent)
});
return
}
}
var r = n.item.data("ui-autocomplete-item") || n.item.data("item.autocomplete");
!1 !== this._trigger("focus", t,
{
item: r
}) ? t.originalEvent && /^key/.test(t.originalEvent.type) && this._value(r.value) : this.liveRegion.text(r.value)
},
menuselect: function (e, t)
{
var n = t.item.data("ui-autocomplete-item") || t.item.data("item.autocomplete"),
r = this.previous;
this.element[0] !== this.document[0].activeElement && (this.element.focus(), this.previous = r, this._delay(function ()
{
this.previous = r, this.selectedItem = n
})), !1 !== this._trigger("select", e,
{
item: n
}) && this._value(n.value), this.term = this._value(), this.close(e), this.selectedItem = n
}
}), this.liveRegion = e("<span>",
{
role: "status",
"aria-live": "polite"
}).addClass("ui-helper-hidden-accessible").insertAfter(this.element), e.fn.bgiframe && this.menu.element.bgiframe(), this._on(this.window,
{
beforeunload: function ()
{
this.element.removeAttr("autocomplete")
}
})
},
_destroy: function ()
{
clearTimeout(this.searching), this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete"), this.menu.element.remove(), this.liveRegion.remove()
},
_setOption: function (e, t)
{
this._super(e, t), e === "source" && this._initSource(), e === "appendTo" && this.menu.element.appendTo(this.document.find(t || "body")[0]), e === "disabled" && t && this.xhr && this.xhr.abort()
},
_isMultiLine: function ()
{
return this.element.is("textarea") ? !0 : this.element.is("input") ? !1 : this.element.prop("isContentEditable")
},
_initSource: function ()
{
var t, n, r = this;
e.isArray(this.options.source) ? (t = this.options.source, this.source = function (n, r)
{
r(e.ui.autocomplete.filter(t, n.term))
}) : typeof this.options.source == "string" ? (n = this.options.source, this.source = function (t, i)
{
r.xhr && r.xhr.abort(), r.xhr = e.ajax(
{
url: n,
data: t,
dataType: "json",
success: function (e)
{
i(e)
},
error: function ()
{
i([])
}
})
}) : this.source = this.options.source
},
_searchTimeout: function (e)
{
clearTimeout(this.searching), this.searching = this._delay(function ()
{
this.term !== this._value() && (this.selectedItem = null, this.search(null, e))
}, this.options.delay)
},
search: function (e, t)
{
e = e != null ? e : this._value(), this.term = this._value();
if (e.length < this.options.minLength) return this.close(t);
if (this._trigger("search", t) === !1) return;
return this._search(e)
},
_search: function (e)
{
this.pending++, this.element.addClass("ui-autocomplete-loading"), this.cancelSearch = !1, this.source(
{
term: e
}, this._response())
},
_response: function ()
{
var e = this,
t = ++n;
return function (r)
{
t === n && e.__response(r), e.pending--, e.pending || e.element.removeClass("ui-autocomplete-loading")
}
},
__response: function (e)
{
e && (e = this._normalize(e)), this._trigger("response", null,
{
content: e
}), !this.options.disabled && e && e.length && !this.cancelSearch ? (this._suggest(e), this._trigger("open")) : this._close()
},
close: function (e)
{
this.cancelSearch = !0, this._close(e)
},
_close: function (e)
{
this.menu.element.is(":visible") && (this.menu.element.hide(), this.menu.blur(), this.isNewMenu = !0, this._trigger("close", e))
},
_change: function (e)
{
this.previous !== this._value() && this._trigger("change", e,
{
item: this.selectedItem
})
},
_normalize: function (t)
{
return t.length && t[0].label && t[0].value ? t : e.map(t, function (t)
{
return typeof t == "string" ?
{
label: t,
value: t
} : e.extend(
{
label: t.label || t.value,
value: t.value || t.label
}, t)
})
},
_suggest: function (t)
{
var n = this.menu.element.empty().zIndex(this.element.zIndex() + 1);
this._renderMenu(n, t), this.menu.refresh(), n.show(), this._resizeMenu(), n.position(e.extend(
{
of: this.element
}, this.options.position)), this.options.autoFocus && this.menu.next()
},
_resizeMenu: function ()
{
var e = this.menu.element;
e.outerWidth(Math.max(e.width("").outerWidth() + 1, this.element.outerWidth()))
},
_renderMenu: function (t, n)
{
var r = this;
e.each(n, function (e, n)
{
r._renderItemData(t, n)
})
},
_renderItemData: function (e, t)
{
return this._renderItem(e, t).data("ui-autocomplete-item", t)
},
_renderItem: function (t, n)
{
return e("<li>").append(e("<a>").text(n.label)).appendTo(t)
},
_move: function (e, t)
{
if (!this.menu.element.is(":visible"))
{
this.search(null, t);
return
}
if (this.menu.isFirstItem() && /^previous/.test(e) || this.menu.isLastItem() && /^next/.test(e))
{
this._value(this.term), this.menu.blur();
return
}
this.menu[e](t)
},
widget: function ()
{
return this.menu.element
},
_value: function ()
{
return this.valueMethod.apply(this.element, arguments)
},
_keyEvent: function (e, t)
{
if (!this.isMultiLine || this.menu.element.is(":visible")) this._move(e, t), t.preventDefault()
}
}), e.extend(e.ui.autocomplete,
{
escapeRegex: function (e)
{
return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
},
filter: function (t, n)
{
var r = new RegExp(e.ui.autocomplete.escapeRegex(n), "i");
return e.grep(t, function (e)
{
return r.test(e.label || e.value || e)
})
}
}), e.widget("ui.autocomplete", e.ui.autocomplete,
{
options:
{
messages:
{
noResults: "No search results.",
results: function (e)
{
return e + (e > 1 ? " results are" : " result is") + " available, use up and down arrow keys to navigate."
}
}
},
__response: function (e)
{
var t;
this._superApply(arguments);
if (this.options.disabled || this.cancelSearch) return;
e && e.length ? t = this.options.messages.results(e.length) : t = this.options.messages.noResults, this.liveRegion.text(t)
}
})
})(jQuery);
(function (e, t)
{
var n = !1;
e.widget("ui.menu",
{
version: "1.9.2",
defaultElement: "<ul>",
delay: 300,
options:
{
icons:
{
submenu: "ui-icon-carat-1-e"
},
menus: "ul",
position:
{
my: "left top",
at: "right top"
},
role: "menu",
blur: null,
focus: null,
select: null
},
_create: function ()
{
this.activeMenu = this.element, this.element.uniqueId().addClass("ui-menu ui-widget ui-widget-content ui-corner-all").toggleClass("ui-menu-icons", !! this.element.find(".ui-icon").length).attr(
{
role: this.options.role,
tabIndex: 0
}).bind("click" + this.eventNamespace, e.proxy(function (e)
{
this.options.disabled && e.preventDefault()
}, this)), this.options.disabled && this.element.addClass("ui-state-disabled").attr("aria-disabled", "true"), this._on(
{
"mousedown .ui-menu-item > a": function (e)
{
e.preventDefault()
},
"click .ui-state-disabled > a": function (e)
{
e.preventDefault()
},
"click .ui-menu-item:has(a)": function (t)
{
var r = e(t.target).closest(".ui-menu-item");
!n && r.not(".ui-state-disabled").length && (n = !0, this.select(t), r.has(".ui-menu").length ? this.expand(t) : this.element.is(":focus") || (this.element.trigger("focus", [!0]), this.active && this.active.parents(".ui-menu").length === 1 && clearTimeout(this.timer)))
},
"mouseenter .ui-menu-item": function (t)
{
var n = e(t.currentTarget);
n.siblings().children(".ui-state-active").removeClass("ui-state-active"), this.focus(t, n)
},
mouseleave: "collapseAll",
"mouseleave .ui-menu": "collapseAll",
focus: function (e, t)
{
var n = this.active || this.element.children(".ui-menu-item").eq(0);
t || this.focus(e, n)
},
blur: function (t)
{
this._delay(function ()
{
e.contains(this.element[0], this.document[0].activeElement) || this.collapseAll(t)
})
},
keydown: "_keydown"
}), this.refresh(), this._on(this.document,
{
click: function (t)
{
e(t.target).closest(".ui-menu").length || this.collapseAll(t), n = !1
}
})
},
_destroy: function ()
{
this.element.removeAttr("aria-activedescendant").find(".ui-menu").andSelf().removeClass("ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons").removeAttr("role").removeAttr("tabIndex").removeAttr("aria-labelledby").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-disabled").removeUniqueId().show(), this.element.find(".ui-menu-item").removeClass("ui-menu-item").removeAttr("role").removeAttr("aria-disabled").children("a").removeUniqueId().removeClass("ui-corner-all ui-state-hover").removeAttr("tabIndex").removeAttr("role").removeAttr("aria-haspopup").children().each(function ()
{
var t = e(this);
t.data("ui-menu-submenu-carat") && t.remove()
}), this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content")
},
_keydown: function (t)
{
function a(e)
{
return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
}
var n, r, i, s, o, u = !0;
switch (t.keyCode)
{
case e.ui.keyCode.PAGE_UP:
this.previousPage(t);
break;
case e.ui.keyCode.PAGE_DOWN:
this.nextPage(t);
break;
case e.ui.keyCode.HOME:
this._move("first", "first", t);
break;
case e.ui.keyCode.END:
this._move("last", "last", t);
break;
case e.ui.keyCode.UP:
this.previous(t);
break;
case e.ui.keyCode.DOWN:
this.next(t);
break;
case e.ui.keyCode.LEFT:
this.collapse(t);
break;
case e.ui.keyCode.RIGHT:
this.active && !this.active.is(".ui-state-disabled") && this.expand(t);
break;
case e.ui.keyCode.ENTER:
case e.ui.keyCode.SPACE:
this._activate(t);
break;
case e.ui.keyCode.ESCAPE:
this.collapse(t);
break;
default:
u = !1, r = this.previousFilter || "", i = String.fromCharCode(t.keyCode), s = !1, clearTimeout(this.filterTimer), i === r ? s = !0 : i = r + i, o = new RegExp("^" + a(i), "i"), n = this.activeMenu.children(".ui-menu-item").filter(function ()
{
return o.test(e(this).children("a").text())
}), n = s && n.index(this.active.next()) !== -1 ? this.active.nextAll(".ui-menu-item") : n, n.length || (i = String.fromCharCode(t.keyCode), o = new RegExp("^" + a(i), "i"), n = this.activeMenu.children(".ui-menu-item").filter(function ()
{
return o.test(e(this).children("a").text())
})), n.length ? (this.focus(t, n), n.length > 1 ? (this.previousFilter = i, this.filterTimer = this._delay(function ()
{
delete this.previousFilter
}, 1e3)) : delete this.previousFilter) : delete this.previousFilter
}
u && t.preventDefault()
},
_activate: function (e)
{
this.active.is(".ui-state-disabled") || (this.active.children("a[aria-haspopup='true']").length ? this.expand(e) : this.select(e))
},
refresh: function ()
{
var t, n = this.options.icons.submenu,
r = this.element.find(this.options.menus);
r.filter(":not(.ui-menu)").addClass("ui-menu ui-widget ui-widget-content ui-corner-all").hide().attr(
{
role: this.options.role,
"aria-hidden": "true",
"aria-expanded": "false"
}).each(function ()
{
var t = e(this),
r = t.prev("a"),
i = e("<span>").addClass("ui-menu-icon ui-icon " + n).data("ui-menu-submenu-carat", !0);
r.attr("aria-haspopup", "true").prepend(i), t.attr("aria-labelledby", r.attr("id"))
}), t = r.add(this.element), t.children(":not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role", "presentation").children("a").uniqueId().addClass("ui-corner-all").attr(
{
tabIndex: -1,
role: this._itemRole()
}), t.children(":not(.ui-menu-item)").each(function ()
{
var t = e(this);
/[^\-—–\s]/.test(t.text()) || t.addClass("ui-widget-content ui-menu-divider")
}), t.children(".ui-state-disabled").attr("aria-disabled", "true"), this.active && !e.contains(this.element[0], this.active[0]) && this.blur()
},
_itemRole: function ()
{
return {
menu: "menuitem",
listbox: "option"
}[this.options.role]
},
focus: function (e, t)
{
var n, r;
this.blur(e, e && e.type === "focus"), this._scrollIntoView(t), this.active = t.first(), r = this.active.children("a").addClass("ui-state-focus"), this.options.role && this.element.attr("aria-activedescendant", r.attr("id")), this.active.parent().closest(".ui-menu-item").children("a:first").addClass("ui-state-active"), e && e.type === "keydown" ? this._close() : this.timer = this._delay(function ()
{
this._close()
}, this.delay), n = t.children(".ui-menu"), n.length && /^mouse/.test(e.type) && this._startOpening(n), this.activeMenu = t.parent(), this._trigger("focus", e,
{
item: t
})
},
_scrollIntoView: function (t)
{
var n, r, i, s, o, u;
this._hasScroll() && (n = parseFloat(e.css(this.activeMenu[0], "borderTopWidth")) || 0, r = parseFloat(e.css(this.activeMenu[0], "paddingTop")) || 0, i = t.offset().top - this.activeMenu.offset().top - n - r, s = this.activeMenu.scrollTop(), o = this.activeMenu.height(), u = t.height(), i < 0 ? this.activeMenu.scrollTop(s + i) : i + u > o && this.activeMenu.scrollTop(s + i - o + u))
},
blur: function (e, t)
{
t || clearTimeout(this.timer);
if (!this.active) return;
this.active.children("a").removeClass("ui-state-focus"), this.active = null, this._trigger("blur", e,
{
item: this.active
})
},
_startOpening: function (e)
{
clearTimeout(this.timer);
if (e.attr("aria-hidden") !== "true") return;
this.timer = this._delay(function ()
{
this._close(), this._open(e)
}, this.delay)
},
_open: function (t)
{
var n = e.extend(
{
of: this.active
}, this.options.position);
clearTimeout(this.timer), this.element.find(".ui-menu").not(t.parents(".ui-menu")).hide().attr("aria-hidden", "true"), t.show().removeAttr("aria-hidden").attr("aria-expanded", "true").position(n)
},
collapseAll: function (t, n)
{
clearTimeout(this.timer), this.timer = this._delay(function ()
{
var r = n ? this.element : e(t && t.target).closest(this.element.find(".ui-menu"));
r.length || (r = this.element), this._close(r), this.blur(t), this.activeMenu = r
}, this.delay)
},
_close: function (e)
{
e || (e = this.active ? this.active.parent() : this.element), e.find(".ui-menu").hide().attr("aria-hidden", "true").attr("aria-expanded", "false").end().find("a.ui-state-active").removeClass("ui-state-active")
},
collapse: function (e)
{
var t = this.active && this.active.parent().closest(".ui-menu-item", this.element);
t && t.length && (this._close(), this.focus(e, t))
},
expand: function (e)
{
var t = this.active && this.active.children(".ui-menu ").children(".ui-menu-item").first();
t && t.length && (this._open(t.parent()), this._delay(function ()
{
this.focus(e, t)
}))
},
next: function (e)
{
this._move("next", "first", e)
},
previous: function (e)
{
this._move("prev", "last", e)
},
isFirstItem: function ()
{
return this.active && !this.active.prevAll(".ui-menu-item").length
},
isLastItem: function ()
{
return this.active && !this.active.nextAll(".ui-menu-item").length
},
_move: function (e, t, n)
{
var r;
this.active && (e === "first" || e === "last" ? r = this.active[e === "first" ? "prevAll" : "nextAll"](".ui-menu-item").eq(-1) : r = this.active[e + "All"](".ui-menu-item").eq(0));
if (!r || !r.length || !this.active) r = this.activeMenu.children(".ui-menu-item")[t]();
this.focus(n, r)
},
nextPage: function (t)
{
var n, r, i;
if (!this.active)
{
this.next(t);
return
}
if (this.isLastItem()) return;
this._hasScroll() ? (r = this.active.offset().top, i = this.element.height(), this.active.nextAll(".ui-menu-item").each(function ()
{
return n = e(this), n.offset().top - r - i < 0
}), this.focus(t, n)) : this.focus(t, this.activeMenu.children(".ui-menu-item")[this.active ? "last" : "first"]())
},
previousPage: function (t)
{
var n, r, i;
if (!this.active)
{
this.next(t);
return
}
if (this.isFirstItem()) return;
this._hasScroll() ? (r = this.active.offset().top, i = this.element.height(), this.active.prevAll(".ui-menu-item").each(function ()
{
return n = e(this), n.offset().top - r + i > 0
}), this.focus(t, n)) : this.focus(t, this.activeMenu.children(".ui-menu-item").first())
},
_hasScroll: function ()
{
return this.element.outerHeight() < this.element.prop("scrollHeight")
},
select: function (t)
{
this.active = this.active || e(t.target).closest(".ui-menu-item");
var n = {
item: this.active
};
this.active.has(".ui-menu").length || this.collapseAll(t, !0), this._trigger("select", t, n)
}
})
})(jQuery);
/*!
* jQuery JSONP Core Plugin 2.4.0 (2012-08-21)
*
* https://github.com/jaubourg/jquery-jsonp
*
* Copyright (c) 2012 Julian Aubourg
*
* This document is licensed as free software under the terms of the
* MIT License: http://www.opensource.org/licenses/mit-license.php
*/
(function (f)
{
function d()
{}
function v(F)
{
c = [F];
}
function o(H, F, G)
{
return H && H.apply(F.context || F, G);
}
function n(F)
{
return /\?/.test(F) ? "&" : "?";
}
var p = "async",
t = "charset",
r = "",
D = "error",
u = "insertBefore",
s = "_jqjsp",
A = "on",
g = A + "click",
k = A + D,
q = A + "load",
y = A + "readystatechange",
b = "readyState",
C = "removeChild",
j = "<script>",
z = "success",
B = "timeout",
e = window,
a = f.Deferred,
h = f("head")[0] || document.documentElement,
x = {}, m = 0,
c, l = {
callback: s,
url: location.href
}, w = e.opera,
i = !! f("<div>").html("<!--[if IE]><i><![endif]-->").find("i").length;
function E(K)
{
K = f.extend(
{}, l, K);
var I = K.success,
P = K.error,
H = K.complete,
Y = K.dataFilter,
aa = K.callbackParameter,
Q = K.callback,
Z = K.cache,
G = K.pageCache,
J = K.charset,
L = K.url,
ac = K.data,
S = K.timeout,
O, W = 0,
U = d,
R, N, F, ab, M, V;
a && a(function (ad)
{
ad.done(I).fail(P);
I = ad.resolve;
P = ad.reject;
}).promise(K);
K.abort = function ()
{
! (W++) && U();
};
if (o(K.beforeSend, K, [K]) === !1 || W)
{
return K;
}
L = L || r;
ac = ac ? ((typeof ac) == "string" ? ac : f.param(ac, K.traditional)) : r;
L += ac ? (n(L) + ac) : r;
aa && (L += n(L) + encodeURIComponent(aa) + "=?");
!Z && !G && (L += n(L) + "_" + (new Date()).getTime() + "=");
L = L.replace(/=\?(&|$)/, "=" + Q + "$1");
function X(ad)
{
if (!(W++))
{
U();
G && (x[L] = {
s: [ad]
});
Y && (ad = Y.apply(K, [ad]));
o(I, K, [ad, z, K]);
o(H, K, [K, z]);
}
}
function T(ad)
{
if (!(W++))
{
U();
G && ad != B && (x[L] = ad);
o(P, K, [K, ad]);
o(H, K, [K, ad]);
}
}
if (G && (O = x[L]))
{
O.s ? X(O.s[0]) : T(O);
}
else
{
e[Q] = v;
ab = f(j)[0];
ab.id = s + m++;
if (J)
{
ab[t] = J;
}
w && w.version() < 11.6 ? ((M = f(j)[0]).text = "document.getElementById('" + ab.id + "')." + k + "()") : (ab[p] = p);
if (i)
{
ab.htmlFor = ab.id;
ab.event = g;
}
ab[q] = ab[k] = ab[y] = function (ad)
{
if (!ab[b] || !/i/.test(ab[b]))
{
try
{
ab[g] && ab[g]();
}
catch (ae)
{}
ad = c;
c = 0;
ad ? X(ad[0]) : T(D);
}
};
ab.src = L;
U = function (ad)
{
V && clearTimeout(V);
ab[y] = ab[q] = ab[k] = null;
h[C](ab);
M && h[C](M);
};
h[u](ab, (F = h.firstChild));
M && h[u](M, F);
V = S > 0 && setTimeout(function ()
{
T(B);
}, S);
}
return K;
}
E.setup = function (F)
{
f.extend(l, F);
};
f.jsonp = E;
})(jQuery);
/*! HP01 */
jQuery(document).ready(function (b)
{
b("div.hp01cta a,div.hp01sub a").append('<span class="hp01arw"/>');
b("div.hp01subcta a").each(function ()
{
var c = b(this).clone().html("");
b(this).closest("div.hp01sub").find("img").wrapAll('<span data-lbl="img"></span>').wrapAll(c);
});
if (document.getElementById("hp01v0"))
{
if (b("#hp-feature-1").hasClass("hp01black"))
{
b("div.hp01tabs").addClass("hp01black");
}
else
{
b("div.hp01tabs").removeClass("hp01black");
}
b("div.hp01tabs").append('<div class="hp01ftab" /><div class="hp01etab" />');
var d = (b("div.hp01activetab a").first().attr("href").split("feature-")[1] * 1);
b("#hp-feature-" + d).addClass("hp01activefeature");
b("#hp-feature-" + d + " .hp01sub").css("top", b("#hp-feature-" + d + " div.hp01main").height() + "px");
b("#hp01features").css("left", (-1 * 974 * (d - 1)) + "px");
b("#hp01features").attr("data-current", d);
if (d == 1)
{
b("#hp01v0").addClass("hp01firstfeature");
}
if (d == b("#hp01features").children("div.hp01feature").length)
{
b("#hp01v0").addClass("hp01lastfeature");
}
b("div.hp01tab").on("click", "a", function (c)
{
if (!b(this).parent().hasClass("hp01activetab"))
{
a(b(this).attr("href").split("feature-")[1] * 1);
}
c.preventDefault();
});
b("#hp01v0[data-hp01rotate]").each(function ()
{
setTimeout(function ()
{
a();
}, b("#hp01v0").attr("data-hp01rotate") * 1000);
});
function a(i)
{
var h = b("#hp01features").attr("data-current");
var e = b("#hp01features").children("div.hp01feature").length;
var g = ((i - h) > 0) ? i - h : h - i;
b("#hp01features").attr("data-current", i);
b("#hp01features").addClass("hp01movin");
b("div.hp01tabs").animate(
{
top: "-98px"
}, 200, function ()
{
b("div.hp01activetab").removeClass("hp01activetab");
b("#hp01tab-" + i).addClass("hp01activetab");
if (b("#hp-feature-" + i).hasClass("hp01black"))
{
b("div.hp01tabs").addClass("hp01black");
}
else
{
b("div.hp01tabs").removeClass("hp01black");
}
});
b("#hp01features").animate(
{
left: (-1 * 974 * (i - 1)) + "px"
}, g * 400, "easeInSine", function ()
{
b("#hp01features").removeClass("hp01movin");
b("div.hp01tabs").animate(
{
top: "0"
}, 400, "easeOutSine");
if (b("#hp-feature-" + i + " .hp01sub")[0])
{
b("#hp-feature-" + i + " .hp01sub").animate(
{
top: b("#hp-feature-" + i + " div.hp01main").height() + "px"
}, 400, "easeOutSine", function ()
{
b("div.hp01activefeature .hp01sub").css("top", "450px");
b("div.hp01activefeature").removeClass("hp01activefeature");
b("#hp-feature-" + i).addClass("hp01activefeature");
});
}
else
{
b("div.hp01activefeature .hp01sub").css("top", "450px");
b("div.hp01activefeature").removeClass("hp01activefeature");
b("#hp-feature-" + i).addClass("hp01activefeature");
}
});
}
}
});
/*! HP02 */
jQuery(document).ready(function (a)
{
a("ul.hp02info").each(function ()
{
a(this).children("li").each(function (e)
{
var f = a(this).closest("div.hp02v0").find("div.hp02graphic img").attr("src");
var g = a(this).children("a").length;
a(this).addClass("hp02-" + g + "links");
a(this).find("a").each(function (i)
{
var h = (i == 1) ? 200 : 0;
a(this).css("background", 'url("' + f + '") -' + ((e * 400) + h) + "px 0 no-repeat");
});
});
a(this).attr("data-islide", 1).parent().parent().addClass("hp02first");
if (a(this).children("li").length > 1)
{
var b = a(this).children("li").length;
var parent = a(this).parent().parent();
var d = a('<a href="#next" data-trackas="infograph" data-lbl="next-slide" class="hp02nav hp02next"><span>Next Slide</span></a>');
parent.append(d);
d.bind("click", function (h)
{
var g = a(this).parent().find("ul.hp02info");
var i = g.attr("data-islide") * 1;
var f = g.css("left").split("px")[0] * 1;
if ((i + 1) <= b)
{
g.animate(
{
left: -400 * i + "px"
}, 300, "easeInSine", function ()
{
if ((i + 1) == b)
{
g.parent().parent().addClass("hp02last");
a("a.hp02next").attr("data-lbl", "notrack");
}
else
{
g.parent().parent().removeClass("hp02first");
a("a.hp02prev").attr("data-lbl", "previous-slide");
}
});
g.attr("data-islide", i + 1);
}
else
{
if (!g.hasClass("hp02movin"))
{
g.addClass("hp02movin");
g.animate(
{
left: (f + (-30)) + "px"
}, 100, "easeInSine", function ()
{
g.animate(
{
left: f + "px"
}, 300, "easeOutBounce", function ()
{
g.removeClass("hp02movin");
});
});
}
}
h.preventDefault();
});
var c = a('<a href="#prev" data-trackas="infograph" data-lbl="notrack" class="hp02nav hp02prev"><span>Previous Slide</span></a>');
parent.append(c);
c.bind("click", function (h)
{
var g = a(this).parent().find("ul.hp02info");
var i = g.attr("data-islide") * 1;
var f = g.css("left").split("px")[0] * 1;
if ((i - 1) > 0)
{
a(this).attr("data-trackas", "infograph");
g.animate(
{
left: (f + 400) + "px"
}, 300, "easeInSine", function ()
{
if ((i - 1) == 1)
{
g.parent().parent().addClass("hp02first");
a("a.hp02prev").attr("data-lbl", "notrack");
}
else
{
g.parent().parent().removeClass("hp02last");
a("a.hp02next").attr("data-lbl", "next-slide");
}
});
g.attr("data-islide", i - 1);
}
else
{
if (!g.hasClass("hp02movin"))
{
g.addClass("hp02movin");
g.animate(
{
left: (f + (30)) + "px"
}, 100, "easeInSine", function ()
{
g.animate(
{
left: f + "px"
}, 300, "easeOutBounce", function ()
{
g.removeClass("hp02movin");
});
});
}
}
h.preventDefault();
});
}
});
});
/*! HP05 */
/*! HP TRACKING */
/*! U06 */
jQuery(document).ready(function (b)
{
if (b(".f01v8, .u06-toggle, .hide-u06")[0])
{
var a = b("#u06v1").attr("data-openff");
var c = b("#u06v1").attr("data-closeff");
b('<h3 class="u06v1-open"><a href="#openfooter" data-trackas="ffooter" data-lbl="open">' + a + '</a></h3><h3 class="u06v1-close"><a href="#closefooter" data-trackas="ffooter" data-lbl="close">' + c + "</a></h3>").insertAfter(".u06v1");
b("h3.u06v1-open a").click(function (d)
{
b("h3.u06v1-open").fadeOut("fast");
b("h3.u06v1-close, .u06v1z2").fadeIn("fast");
b(".u06v1w1").animate(
{
height: "toggle"
});
d.preventDefault();
});
b("h3.u06v1-close a").click(function (d)
{
b(".u06v1z2, h3.u06v1-close").fadeOut("fast");
b("h3.u06v1-open").fadeIn("slow");
b(".u06v1w1").animate(
{
height: "toggle"
});
d.preventDefault();
});
}
}); |
/*
* Copyright (c) 2017. MIT-license for Jari Van Melckebeke
* Note that there was a lot of educational work in this project,
* this project was (or is) used for an assignment from Realdolmen in Belgium.
* Please just don't abuse my work
*/
import extend from './extend';
import { hooks } from './hooks';
import isUndefined from './is-undefined';
function warn(msg) {
if (hooks.suppressDeprecationWarnings === false &&
(typeof console !== 'undefined') && console.warn) {
console.warn('Deprecation warning: ' + msg);
}
}
export function deprecate(msg, fn) {
var firstTime = true;
return extend(function () {
if (hooks.deprecationHandler != null) {
hooks.deprecationHandler(null, msg);
}
if (firstTime) {
warn(msg + '\nArguments: ' + Array.prototype.slice.call(arguments).join(', ') + '\n' + (new Error()).stack);
firstTime = false;
}
return fn.apply(this, arguments);
}, fn);
}
var deprecations = {};
export function deprecateSimple(name, msg) {
if (hooks.deprecationHandler != null) {
hooks.deprecationHandler(name, msg);
}
if (!deprecations[name]) {
warn(msg);
deprecations[name] = true;
}
}
hooks.suppressDeprecationWarnings = false;
hooks.deprecationHandler = null;
|
/*
Experiment for chrome.tabCapture.capture
Pros:
- manipulate all audio types (html5, flash,...)
- everything is done in background script = no need for hacky page scripts
Cons:
- chrome.tabCapture.capture needs to be called from popup.html context manualy
- cant automaticaly add filter when opening new tab (becaue of ^)
- needs "tabcapture" permission
Im not sure about performance. But I guess it should be the same
*/
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log('chrome.runtime.onMessage.addListener');
if (request.action === 'eq-init') {
chrome.tabCapture.capture({
audio : true,
video : false
}, function(stream) {
console.log('stream', stream);
//I can attach all my filter here...
});
}
});
|
function helloWorld() {
return "Hello world!";
} |
import { bindable, customElement, noView } from 'aurelia-templating';
import { inject } from 'aurelia-dependency-injection';
import { computedFrom } from 'aurelia-framework';
import { AttributeManager } from '../common/attributeManager';
import { getBooleanFromAttributeValue } from '../common/attributes';
import { Ui5Control} from '../control/control';
@customElement('ui5-list-item-base')
@inject(Element)
export class Ui5ListItemBase extends Ui5Control{
_listitembase = null;
_parent = null;
_relation = null;
@bindable ui5Id = null;
@bindable ui5Class = null;
@bindable ui5Tooltip = null;
@bindable prevId = null;
@bindable() type = 'Inactive';
@bindable() visible = true;
@bindable() unread = false;
@bindable() selected = false;
@bindable() counter = null;
@bindable() highlight = 'None';
@bindable() highlightText = '';
@bindable() navigated = false;
@bindable() press = this.defaultFunc;
@bindable() detailPress = this.defaultFunc;
/* inherited from sap.ui.core.Control*/
@bindable() busy = false;
@bindable() busyIndicatorDelay = 1000;
@bindable() busyIndicatorSize = 'Medium';
@bindable() visible = true;
@bindable() fieldGroupIds = '[]';
@bindable() validateFieldGroup = this.defaultFunc;
/* inherited from sap.ui.core.Element*/
/* inherited from sap.ui.base.ManagedObject*/
@bindable() validationSuccess = this.defaultFunc;
@bindable() validationError = this.defaultFunc;
@bindable() parseError = this.defaultFunc;
@bindable() formatError = this.defaultFunc;
@bindable() modelContextChange = this.defaultFunc;
/* inherited from sap.ui.base.EventProvider*/
/* inherited from sap.ui.base.Object*/
constructor(element) {
super(element);
this.element = element;
this.attributeManager = new AttributeManager(this.element);
}
@computedFrom('_listitembase')
get UIElement() {
return this._listitembase;
}
fillProperties(params){
params.type = this.type;
params.visible = getBooleanFromAttributeValue(this.visible);
params.unread = getBooleanFromAttributeValue(this.unread);
params.selected = getBooleanFromAttributeValue(this.selected);
params.counter = this.counter?parseInt(this.counter):0;
params.highlight = this.highlight;
params.highlightText = this.highlightText;
params.navigated = getBooleanFromAttributeValue(this.navigated);
params.press = this.press==null ? this.defaultFunc: this.press;
params.detailPress = this.detailPress==null ? this.defaultFunc: this.detailPress;
super.fillProperties(params);
}
defaultFunc() {
}
attached() {
var that = this;
var params = {};
this.fillProperties(params);
if (this.ui5Id)
this._listitembase = new sap.m.ListItemBase(this.ui5Id, params);
else
this._listitembase = new sap.m.ListItemBase(params);
if(this.ui5Class)
this._listitembase.addStyleClass(this.ui5Class);
if(this.ui5Tooltip)
this._listitembase.setTooltip(this.ui5Tooltip);
if ($(this.element).closest("[ui5-container]").length > 0) {
this._parent = $(this.element).closest("[ui5-container]")[0].au.controller.viewModel;
if (!this._parent.UIElement || (this._parent.UIElement.sId != this._listitembase.sId)) {
var prevSibling = null;
this._relation = this._parent.addChild(this._listitembase, this.element, this.prevId);
this.attributeManager.addAttributes({"ui5-container": '' });
}
else {
this._parent = $(this.element.parentElement).closest("[ui5-container]")[0].au.controller.viewModel;
var prevSibling = null;
this._relation = this._parent.addChild(this._listitembase, this.element, this.prevId);
this.attributeManager.addAttributes({"ui5-container": '' });
}
}
else {
if(this._listitembase.placeAt)
this._listitembase.placeAt(this.element.parentElement);
this.attributeManager.addAttributes({"ui5-container": '' });
this.attributeManager.addClasses("ui5-hide");
}
//<!container>
//</!container>
this.attributeManager.addAttributes({"ui5-id": this._listitembase.sId});
}
detached() {
try{
if ($(this.element).closest("[ui5-container]").length > 0) {
if (this._parent && this._relation) {
if(this._listitembase)
this._parent.removeChildByRelation(this._listitembase, this._relation);
}
}
else{
this._listitembase.destroy();
}
super.detached();
}
catch(err){}
}
addChild(child, elem, afterElement) {
var path = jQuery.makeArray($(elem).parentsUntil(this.element));
for (elem of path) {
try{
if (elem.localName == 'tooltip') { this._listitembase.setTooltip(child); return elem.localName;}
if (elem.localName == 'customdata') { var _index = afterElement?Math.floor(afterElement+1):null; if (_index)this._listitembase.insertCustomData(child, _index); else this._listitembase.addCustomData(child, 0); return elem.localName; }
if (elem.localName == 'layoutdata') { this._listitembase.setLayoutData(child); return elem.localName;}
if (elem.localName == 'dependents') { var _index = afterElement?Math.floor(afterElement+1):null; if (_index)this._listitembase.insertDependent(child, _index); else this._listitembase.addDependent(child, 0); return elem.localName; }
if (elem.localName == 'dragdropconfig') { var _index = afterElement?Math.floor(afterElement+1):null; if (_index)this._listitembase.insertDragDropConfig(child, _index); else this._listitembase.addDragDropConfig(child, 0); return elem.localName; }
}
catch(err){}
}
}
removeChildByRelation(child, relation) {
try{
if (relation == 'tooltip') { this._listitembase.destroyTooltip(child); }
if (relation == 'customdata') { this._listitembase.removeCustomData(child);}
if (relation == 'layoutdata') { this._listitembase.destroyLayoutData(child); }
if (relation == 'dependents') { this._listitembase.removeDependent(child);}
if (relation == 'dragdropconfig') { this._listitembase.removeDragDropConfig(child);}
}
catch(err){}
}
typeChanged(newValue){if(newValue!=null && newValue!=undefined && this._listitembase!==null){ this._listitembase.setType(newValue);}}
visibleChanged(newValue){if(newValue!=null && newValue!=undefined && this._listitembase!==null){ this._listitembase.setVisible(getBooleanFromAttributeValue(newValue));}}
unreadChanged(newValue){if(newValue!=null && newValue!=undefined && this._listitembase!==null){ this._listitembase.setUnread(getBooleanFromAttributeValue(newValue));}}
selectedChanged(newValue){if(newValue!=null && newValue!=undefined && this._listitembase!==null){ this._listitembase.setSelected(getBooleanFromAttributeValue(newValue));}}
counterChanged(newValue){if(newValue!=null && newValue!=undefined && this._listitembase!==null){ this._listitembase.setCounter(newValue);}}
highlightChanged(newValue){if(newValue!=null && newValue!=undefined && this._listitembase!==null){ this._listitembase.setHighlight(newValue);}}
highlightTextChanged(newValue){if(newValue!=null && newValue!=undefined && this._listitembase!==null){ this._listitembase.setHighlightText(newValue);}}
navigatedChanged(newValue){if(newValue!=null && newValue!=undefined && this._listitembase!==null){ this._listitembase.setNavigated(getBooleanFromAttributeValue(newValue));}}
pressChanged(newValue){if(newValue!=null && newValue!=undefined && this._listitembase!==null){ this._listitembase.attachPress(newValue);}}
detailPressChanged(newValue){if(newValue!=null && newValue!=undefined && this._listitembase!==null){ this._listitembase.attachDetailPress(newValue);}}
busyChanged(newValue){if(this._listitembase!==null){ this._listitembase.setBusy(getBooleanFromAttributeValue(newValue));}}
busyIndicatorDelayChanged(newValue){if(this._listitembase!==null){ this._listitembase.setBusyIndicatorDelay(newValue);}}
busyIndicatorSizeChanged(newValue){if(this._listitembase!==null){ this._listitembase.setBusyIndicatorSize(newValue);}}
visibleChanged(newValue){if(this._listitembase!==null){ this._listitembase.setVisible(getBooleanFromAttributeValue(newValue));}}
fieldGroupIdsChanged(newValue){if(this._listitembase!==null){ this._listitembase.setFieldGroupIds(newValue);}}
/* inherited from sap.ui.core.Control*/
validateFieldGroupChanged(newValue){if(newValue!=null && newValue!=undefined && this._listitembase!==null){ this._listitembase.attachValidateFieldGroup(newValue);}}
/* inherited from sap.ui.core.Element*/
/* inherited from sap.ui.base.ManagedObject*/
validationSuccessChanged(newValue){if(newValue!=null && newValue!=undefined && this._listitembase!==null){ this._listitembase.attachValidationSuccess(newValue);}}
validationErrorChanged(newValue){if(newValue!=null && newValue!=undefined && this._listitembase!==null){ this._listitembase.attachValidationError(newValue);}}
parseErrorChanged(newValue){if(newValue!=null && newValue!=undefined && this._listitembase!==null){ this._listitembase.attachParseError(newValue);}}
formatErrorChanged(newValue){if(newValue!=null && newValue!=undefined && this._listitembase!==null){ this._listitembase.attachFormatError(newValue);}}
modelContextChangeChanged(newValue){if(newValue!=null && newValue!=undefined && this._listitembase!==null){ this._listitembase.attachModelContextChange(newValue);}}
/* inherited from sap.ui.base.EventProvider*/
/* inherited from sap.ui.base.Object*/
} |
SystemJS.config({
transpiler: 'plugin-babel',
map: {
'plugin-babel':
'./node_modules/systemjs-plugin-babel/plugin-babel.js',
'systemjs-babel-build':
'./node_modules/systemjs-plugin-babel/systemjs-babel-browser.js',
// app start script
'main': './scripts/main.js',
'data': './scripts/data.js'
}
}); |
describe('assessment: aLinksNotSeparatedBySymbols', function () {
var client, assessments, quailResults, cases;
// Evaluate the test page with Quail.
before('load webdrivers and run evaluations with Quail', function () {
return quailTestRunner.setup({
url: 'http://localhost:9999/aLinksNotSeparatedBySymbols/aLinksNotSeparatedBySymbols.html',
assessments: [
'aLinksNotSeparatedBySymbols'
]
})
.spread(function (_client_, _assessments_, _quailResults_) {
client = _client_;
assessments = _assessments_;
quailResults = _quailResults_;
cases = quailResults.tests.aLinksNotSeparatedBySymbols.cases;
});
});
after('end the webdriver session', function () {
return quailTestRunner.teardown(client);
});
it('should return the correct number of tests', function () {
expect(quailResults.stats.tests).to.equal(1);
});
it('should return the correct number of cases', function () {
expect(quailResults.stats.cases).to.equal(6);
});
it('should have correct key under the test results', function () {
expect(quailResults.tests).to.include.keys('aLinksNotSeparatedBySymbols');
});
it('should return the proper assessment for assert-1', function () {
expect(cases).quailGetById('assert-1').to.have.quailStatus('failed');
});
it('should return the proper assessment for assert-2', function () {
expect(cases).quailGetById('assert-2').to.have.quailStatus('inapplicable');
});
it('should return the proper assessment for assert-3', function () {
expect(cases).quailGetById('assert-3').to.have.quailStatus('passed');
});
it('should return the proper assessment for assert-4', function () {
expect(cases).quailGetById('assert-4').to.have.quailStatus('inapplicable');
});
it('should return the proper assessment for assert-5', function () {
expect(cases).quailGetById('assert-5').to.have.quailStatus('passed');
});
it('should return the proper assessment for assert-6', function () {
expect(cases).quailGetById('assert-6').to.have.quailStatus('inapplicable');
});
});
|
// ==========================================================================
// Project: SproutCore Runtime
// Copyright: ©2011 Strobe Inc. and contributors.
// License: Licensed under MIT license (see license.js)
// ==========================================================================
require('sproutcore-runtime/~tests/suites/mutable_array');
var suite = SC.MutableArrayTests;
suite.module('popObject');
suite.test("[].popObject() => [] + returns undefined + NO notify", function() {
var obj, observer;
obj = this.newObject([]);
observer = this.newObserver(obj, '[]', 'length');
equals(obj.popObject(), undefined, 'popObject results');
same(this.toArray(obj), [], 'post item results');
if (observer.isEnabled) {
equals(observer.validate('[]'), false, 'should NOT have notified []');
equals(observer.validate('length'), false, 'should NOT have notified length');
}
});
suite.test("[X].popObject() => [] + notify", function() {
var obj, before, after, observer, ret;
before = this.newFixture(1);
after = [];
obj = this.newObject(before);
observer = this.newObserver(obj, '[]', 'length');
ret = obj.popObject();
equals(ret, before[0], 'return object');
same(this.toArray(obj), after, 'post item results');
equals(SC.get(obj, 'length'), after.length, 'length');
if (observer.isEnabled) {
equals(observer.validate('[]'), true, 'should NOT have notified []');
equals(observer.validate('length'), true, 'should NOT have notified length');
}
});
suite.test("[A,B,C].popObject() => [A,B] + notify", function() {
var obj, before, after, observer, ret;
before = this.newFixture(3);
after = [before[0], before[1]];
obj = this.newObject(before);
observer = this.newObserver(obj, '[]', 'length');
ret = obj.popObject();
equals(ret, before[2], 'return object');
same(this.toArray(obj), after, 'post item results');
equals(SC.get(obj, 'length'), after.length, 'length');
if (observer.isEnabled) {
equals(observer.validate('[]'), true, 'should NOT have notified []');
equals(observer.validate('length'), true, 'should NOT have notified length');
}
}); |
'use strict';
// Carpools controller
angular.module('carpools').controller('CarpoolsController',[
'$scope', '$stateParams', '$location', '$modal', '$log', 'Authentication', 'Carpools', '$timeout',
function($scope, $stateParams, $location, $modal, $log, Authentication, Carpools, $timeout) {
$scope.authentication = Authentication;
$scope.pageView = 'LIST';
$scope.search = {};
if(!$scope.authentication.user) {
$location.path('/signin');
}
$scope.init = function() {
$scope.find();
$scope.initSearch();
};
$scope.initSearch = function() {
var autocomplete = new google.maps.places.Autocomplete(document.getElementById('destination'));
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
$scope.$apply(function() {
$scope.placeSearch = {
name: place.name
};
if(place.geometry && place.geometry.location) {
$scope.placeSearch.location = {
lat: place.geometry.location.G,
lng: place.geometry.location.K
}
}
});
});
};
$scope.canShowDrive = function() {
return this.placeSearch !== undefined && this.placeSearch.location !== undefined;
};
$scope.drive = function () {
var modalInstance = $modal.open({
animation: true,
templateUrl: 'modules/carpools/views/register-ride.client.view.html',
controller: 'RegisterRideController',
resolve: {
carpool: function() {
var result = new Carpools();
if ($scope.placeSearch) {
result.destination = {
name: $scope.placeSearch.name,
location: {
lat: $scope.placeSearch.location.lat,
lng: $scope.placeSearch.location.lng
}
};
}
return result;
}
}
});
modalInstance.result.then(function (carpool) {
$log.info(carpool);
$scope.carpools.push(carpool);
$location.path('carpools/' + carpool._id);
}, function () {
$scope.search = {};
$log.info('Modal dismissed at: ' + new Date());
});
};
$scope.joinCarpool = function(carpool) {
carpool.riders.push($scope.authentication.user._id);
carpool.$update(function(response) {
$location.path('carpools/' + carpool._id);
}, function(errorResponse) {
carpool.riders.pop();
$scope.error = errorResponse.data.message;
});
};
$scope.unjoinCarpool = function(carpool) {
var rider;
for (var i in carpool.riders) {
if (carpool.riders[i]._id === $scope.authentication.user._id) {
rider = carpool.riders[i];
carpool.riders.splice(i, 1);
}
}
carpool.$update(function() {
$location.path('/');
}, function(errorResponse) {
if(rider) {
carpool.riders.push(rider);
}
$scope.error = errorResponse.data.message;
});
};
// Create new Carpool
$scope.create = function() {
// Create new Carpool object
var carpool = new Carpools ({
name: this.name
});
// Redirect after save
carpool.$save(function(response) {
$location.path('carpools/' + response._id);
// Clear form fields
$scope.name = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Carpool
$scope.remove = function(carpool) {
if ( carpool ) {
carpool.$remove();
for (var i in $scope.carpools) {
if ($scope.carpools [i] === carpool) {
$scope.carpools.splice(i, 1);
}
}
} else {
$scope.carpool.$remove(function() {
$location.path('carpools');
});
}
};
// Update existing Carpool
$scope.update = function() {
var carpool = $scope.carpool;
carpool.$update(function() {
$location.path('carpools/' + carpool._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Carpools
$scope.find = function() {
Carpools.query(function(carpools) {
// check if they have a carpool already
var myCarpool = findUserCarpool(carpools);
if (myCarpool) {
// route to summary
$location.path('carpools/' + myCarpool._id);
}
// remove car pools without seats
for (var i=0; i<carpools.length; i++) {
var carpool = carpools[i];
if (!$scope.canJoinCarPool(carpool)) {
carpools.splice(i, 1);
i--;
}
}
$scope.carpools = carpools;
});
};
function findUserCarpool(carpools) {
for (var i=0; i<carpools.length; i++) {
var carpool = carpools[i];
// check driver name
if (carpool.user._id === $scope.authentication.user._id) {
return carpool;
}
// check for rider status
for (var j=0; j<carpool.riders.length; j++) {
var rider = carpool.riders[j];
if (rider._id === $scope.authentication.user._id) {
return carpool;
}
}
}
return undefined;
}
// Find existing Carpool
$scope.findOne = function() {
Carpools.get({
carpoolId: $stateParams.carpoolId
}, function(carpool) {
// check if expired
if (carpool.expired) {
$location.path('/');
}
$scope.carpool = carpool;
$scope.updateNotification();
window.setInterval(function() {
$scope.updateNotification();
}, 10000);
});
};
$scope.updateNotification = function() {
if($scope.carpool && $scope.carpool.departureTime) {
var tenMinutesFromNow = new Date();
var departureTime = new Date($scope.carpool.departureTime);
tenMinutesFromNow.setMinutes(tenMinutesFromNow.getMinutes() + 10);
if((new Date() < departureTime) && (departureTime < tenMinutesFromNow)) {
$scope.notification = {
message: "Your ride is leaving soon!",
type: 'alert-info'
};
$scope.$apply();
} else if(new Date() > departureTime) {
$scope.notification = {
message: "Your ride has already left!",
type: 'alert-danger'
};
$scope.$apply();
}
}
};
$scope.getRiders = function(carpool) {
var riders = '';
if (carpool && carpool.riders && carpool.riders.length > 0) {
riders += carpool.riders[0].displayName;
for (var i=1; i<carpool.riders.length; i++) {
riders += ', ' + carpool.riders[i].displayName;
}
}
return riders;
};
$scope.isRider = function(rider) {
return rider._id === $scope.authentication.user._id;
};
$scope.canJoinCarPool = function(carpool) {
var result = true;
if (carpool.numSeats - carpool.riders.length <= 0) {
result = false;
} else if (new Date(carpool.departureTime) < new Date()) {
result = false;
}
return result;
};
$scope.delay = (function() {
var promise = null;
return function(callback, ms) {
$timeout.cancel(promise); //clearTimeout(timer);
promise = $timeout(callback, ms); //timer = setTimeout(callback, ms);
};
})();
}
]);
|
define(function (require) {
"use strict";
var _ = require("underscore");
var $ = require("jquery");
// abstract class
var Proto = function () {
};
Proto.prototype = {
_optionsDefault: {
fillStyle: "#ffffff",
strokeStyle: "#ffffff",
font: "bold 12px sans-serif"
},
_options: {},
_promises: {},
_params: {},
_cache: new WeakMap(),
setOptions: function (options, params) {
this._options = _.extend({}, this._optionsDefault, options);
this._params = params;
},
abort: function () {
_.forEach(this._promises, function (promise, data, list) {
if (promise.status() === "pending") {
promise.abort();
delete list[data];
}
});
},
getPosition: function (params) {
// i wish i can use WeakMap here
var data = {
date: new Date().toISOString().slice(0, 10),
object: this._params.index,
center: params.center
},
json = JSON.stringify(data);
if (!this._promises[json]) {
this._promises[json] = $.ajax({
url: this._url,
data: data
});
}
return this._promises[json];
},
getImage: function (view) {
if (!this._cache.has(view._params)) {
// console.log("NEW VIEW")
this._cache.set(view._params, new WeakMap());
}
if (!this._cache.get(view._params).has(this)) {
// console.log("NEW THIS")
this._cache.get(view._params).set(this, this.getPosition(view._params)
.then(view._extract(this)));
}
return this._cache.get(view._params).get(this);
}
};
return Proto;
});
|
import router from 'kolibri.coreVue.router';
import store from 'kolibri.coreVue.vuex.store';
import {
showAvailableChannelsPage,
showSelectContentPage,
updateTreeViewTopic,
} from '../modules/wizard/handlers';
import { ContentWizardPages } from '../constants';
import { selectContentTopicLink } from '../views/ManageContentPage/manageContentLinks';
// To update the treeview topic programatically
export function navigateToTopicUrl(node, query) {
router.push(selectContentTopicLink(node, query));
}
export default [
{
name: ContentWizardPages.AVAILABLE_CHANNELS,
path: '/content/channels',
handler: ({ query }) => {
return showAvailableChannelsPage(store, {
for_export: String(query.for_export) === 'true',
address_id: query.address_id,
drive_id: query.drive_id,
});
},
},
{
name: ContentWizardPages.SELECT_CONTENT,
path: '/content/channels/:channel_id',
handler: ({ query, params }) => {
// HACK don't refresh state when going from SELECT_CONTENT_TOPIC back to here
const cachedChannelPath = store.state.manageContent.wizard.pathCache[params.channel_id];
if (cachedChannelPath) {
return updateTreeViewTopic(store, cachedChannelPath[0]);
}
return showSelectContentPage(store, {
channel_id: params.channel_id,
address_id: query.address_id,
drive_id: query.drive_id,
for_export: String(query.for_export) === 'true',
});
},
},
{
name: ContentWizardPages.SELECT_CONTENT_TOPIC,
path: '/content/channels/:channel_id/node/:node_id',
handler: toRoute => {
// If wizardState is not fully-hydrated, redirect to top-level channel page
if (!store.state.manageContent.wizard.transferType) {
router.replace({ ...toRoute, name: ContentWizardPages.SELECT_CONTENT });
} else {
const { params } = toRoute;
let nextNode;
if (!params.node) {
nextNode = {
// Works fine without title at the moment.
path: store.state.manageContent.wizard.pathCache[params.node_id],
id: params.node_id,
};
} else {
nextNode = params.node;
}
return updateTreeViewTopic(store, nextNode);
}
},
},
];
|
var _foo = /*#__PURE__*/new WeakSet();
class A extends B {
constructor(...args) {
super(...args);
babelHelpers.classPrivateMethodInitSpec(this, _foo);
}
}
function _foo2() {
let _A;
babelHelpers.get(babelHelpers.getPrototypeOf(A.prototype), "x", this);
}
|
import {test} from '../qunit';
import {localeModule} from '../qunit-locale';
import moment from '../../moment';
localeModule('ar-sa');
test('parse', function (assert) {
var tests = 'يناير:يناير_فبراير:فبراير_مارس:مارس_أبريل:أبريل_مايو:مايو_يونيو:يونيو_يوليو:يوليو_أغسطس:أغسطس_سبتمبر:سبتمبر_أكتوبر:أكتوبر_نوفمبر:نوفمبر_ديسمبر:ديسمبر'.split('_'), i;
function equalTest(input, mmm, i) {
assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1) + ' instead is month ' + moment(input, mmm).month());
}
for (i = 0; i < 12; i++) {
tests[i] = tests[i].split(':');
equalTest(tests[i][0], 'MMM', i);
equalTest(tests[i][1], 'MMM', i);
equalTest(tests[i][0], 'MMMM', i);
equalTest(tests[i][1], 'MMMM', i);
equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i);
equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i);
equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i);
equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i);
}
});
test('format', function (assert) {
var a = [
['dddd, MMMM Do YYYY, h:mm:ss a', 'الأحد، فبراير ١٤ ٢٠١٠، ٣:٢٥:٥٠ م'],
['ddd, hA', 'أحد، ٣م'],
['M Mo MM MMMM MMM', '٢ ٢ ٠٢ فبراير فبراير'],
['YYYY YY', '٢٠١٠ ١٠'],
['D Do DD', '١٤ ١٤ ١٤'],
['d do dddd ddd dd', '٠ ٠ الأحد أحد ح'],
['DDD DDDo DDDD', '٤٥ ٤٥ ٠٤٥'],
['w wo ww', '٨ ٨ ٠٨'],
['h hh', '٣ ٠٣'],
['H HH', '١٥ ١٥'],
['m mm', '٢٥ ٢٥'],
['s ss', '٥٠ ٥٠'],
['a A', 'م م'],
['[the] DDDo [day of the year]', 'the ٤٥ day of the year'],
['LT', '١٥:٢٥'],
['LTS', '١٥:٢٥:٥٠'],
['L', '١٤/٠٢/٢٠١٠'],
['LL', '١٤ فبراير ٢٠١٠'],
['LLL', '١٤ فبراير ٢٠١٠ ١٥:٢٥'],
['LLLL', 'الأحد ١٤ فبراير ٢٠١٠ ١٥:٢٥'],
['l', '١٤/٢/٢٠١٠'],
['ll', '١٤ فبراير ٢٠١٠'],
['lll', '١٤ فبراير ٢٠١٠ ١٥:٢٥'],
['llll', 'أحد ١٤ فبراير ٢٠١٠ ١٥:٢٥']
],
b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)),
i;
for (i = 0; i < a.length; i++) {
assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]);
}
});
test('format ordinal', function (assert) {
assert.equal(moment([2011, 0, 1]).format('DDDo'), '١', '1');
assert.equal(moment([2011, 0, 2]).format('DDDo'), '٢', '2');
assert.equal(moment([2011, 0, 3]).format('DDDo'), '٣', '3');
assert.equal(moment([2011, 0, 4]).format('DDDo'), '٤', '4');
assert.equal(moment([2011, 0, 5]).format('DDDo'), '٥', '5');
assert.equal(moment([2011, 0, 6]).format('DDDo'), '٦', '6');
assert.equal(moment([2011, 0, 7]).format('DDDo'), '٧', '7');
assert.equal(moment([2011, 0, 8]).format('DDDo'), '٨', '8');
assert.equal(moment([2011, 0, 9]).format('DDDo'), '٩', '9');
assert.equal(moment([2011, 0, 10]).format('DDDo'), '١٠', '10');
assert.equal(moment([2011, 0, 11]).format('DDDo'), '١١', '11');
assert.equal(moment([2011, 0, 12]).format('DDDo'), '١٢', '12');
assert.equal(moment([2011, 0, 13]).format('DDDo'), '١٣', '13');
assert.equal(moment([2011, 0, 14]).format('DDDo'), '١٤', '14');
assert.equal(moment([2011, 0, 15]).format('DDDo'), '١٥', '15');
assert.equal(moment([2011, 0, 16]).format('DDDo'), '١٦', '16');
assert.equal(moment([2011, 0, 17]).format('DDDo'), '١٧', '17');
assert.equal(moment([2011, 0, 18]).format('DDDo'), '١٨', '18');
assert.equal(moment([2011, 0, 19]).format('DDDo'), '١٩', '19');
assert.equal(moment([2011, 0, 20]).format('DDDo'), '٢٠', '20');
assert.equal(moment([2011, 0, 21]).format('DDDo'), '٢١', '21');
assert.equal(moment([2011, 0, 22]).format('DDDo'), '٢٢', '22');
assert.equal(moment([2011, 0, 23]).format('DDDo'), '٢٣', '23');
assert.equal(moment([2011, 0, 24]).format('DDDo'), '٢٤', '24');
assert.equal(moment([2011, 0, 25]).format('DDDo'), '٢٥', '25');
assert.equal(moment([2011, 0, 26]).format('DDDo'), '٢٦', '26');
assert.equal(moment([2011, 0, 27]).format('DDDo'), '٢٧', '27');
assert.equal(moment([2011, 0, 28]).format('DDDo'), '٢٨', '28');
assert.equal(moment([2011, 0, 29]).format('DDDo'), '٢٩', '29');
assert.equal(moment([2011, 0, 30]).format('DDDo'), '٣٠', '30');
assert.equal(moment([2011, 0, 31]).format('DDDo'), '٣١', '31');
});
test('format month', function (assert) {
var expected = 'يناير يناير_فبراير فبراير_مارس مارس_أبريل أبريل_مايو مايو_يونيو يونيو_يوليو يوليو_أغسطس أغسطس_سبتمبر سبتمبر_أكتوبر أكتوبر_نوفمبر نوفمبر_ديسمبر ديسمبر'.split('_'), i;
for (i = 0; i < expected.length; i++) {
assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]);
}
});
test('format week', function (assert) {
var expected = 'الأحد أحد ح_الإثنين إثنين ن_الثلاثاء ثلاثاء ث_الأربعاء أربعاء ر_الخميس خميس خ_الجمعة جمعة ج_السبت سبت س'.split('_'), i;
for (i = 0; i < expected.length; i++) {
assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]);
}
});
test('from', function (assert) {
var start = moment([2007, 1, 28]);
assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'ثوان', '44 seconds = a few seconds');
assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'دقيقة', '45 seconds = a minute');
assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'دقيقة', '89 seconds = a minute');
assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '٢ دقائق', '90 seconds = 2 minutes');
assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '٤٤ دقائق', '44 minutes = 44 minutes');
assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'ساعة', '45 minutes = an hour');
assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'ساعة', '89 minutes = an hour');
assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '٢ ساعات', '90 minutes = 2 hours');
assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '٥ ساعات', '5 hours = 5 hours');
assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '٢١ ساعات', '21 hours = 21 hours');
assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'يوم', '22 hours = a day');
assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'يوم', '35 hours = a day');
assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '٢ أيام', '36 hours = 2 days');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'يوم', '1 day = a day');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '٥ أيام', '5 days = 5 days');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '٢٥ أيام', '25 days = 25 days');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'شهر', '26 days = a month');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'شهر', '30 days = a month');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'شهر', '43 days = a month');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '٢ أشهر', '46 days = 2 months');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '٢ أشهر', '75 days = 2 months');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '٣ أشهر', '76 days = 3 months');
assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'شهر', '1 month = a month');
assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '٥ أشهر', '5 months = 5 months');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'سنة', '345 days = a year');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '٢ سنوات', '548 days = 2 years');
assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'سنة', '1 year = a year');
assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '٥ سنوات', '5 years = 5 years');
});
test('suffix', function (assert) {
assert.equal(moment(30000).from(0), 'في ثوان', 'prefix');
assert.equal(moment(0).from(30000), 'منذ ثوان', 'suffix');
});
test('now from now', function (assert) {
assert.equal(moment().fromNow(), 'منذ ثوان', 'now from now should display as in the past');
});
test('fromNow', function (assert) {
assert.equal(moment().add({s: 30}).fromNow(), 'في ثوان', 'in a few seconds');
assert.equal(moment().add({d: 5}).fromNow(), 'في ٥ أيام', 'in 5 days');
});
test('calendar day', function (assert) {
var a = moment().hours(12).minutes(0).seconds(0);
assert.equal(moment(a).calendar(), 'اليوم على الساعة ١٢:٠٠', 'today at the same time');
assert.equal(moment(a).add({m: 25}).calendar(), 'اليوم على الساعة ١٢:٢٥', 'Now plus 25 min');
assert.equal(moment(a).add({h: 1}).calendar(), 'اليوم على الساعة ١٣:٠٠', 'Now plus 1 hour');
assert.equal(moment(a).add({d: 1}).calendar(), 'غدا على الساعة ١٢:٠٠', 'tomorrow at the same time');
assert.equal(moment(a).subtract({h: 1}).calendar(), 'اليوم على الساعة ١١:٠٠', 'Now minus 1 hour');
assert.equal(moment(a).subtract({d: 1}).calendar(), 'أمس على الساعة ١٢:٠٠', 'yesterday at the same time');
});
test('calendar next week', function (assert) {
var i, m;
for (i = 2; i < 7; i++) {
m = moment().add({d: i});
assert.equal(m.calendar(), m.format('dddd [على الساعة] LT'), 'Today + ' + i + ' days current time');
m.hours(0).minutes(0).seconds(0).milliseconds(0);
assert.equal(m.calendar(), m.format('dddd [على الساعة] LT'), 'Today + ' + i + ' days beginning of day');
m.hours(23).minutes(59).seconds(59).milliseconds(999);
assert.equal(m.calendar(), m.format('dddd [على الساعة] LT'), 'Today + ' + i + ' days end of day');
}
});
test('calendar last week', function (assert) {
var i, m;
for (i = 2; i < 7; i++) {
m = moment().subtract({d: i});
assert.equal(m.calendar(), m.format('dddd [على الساعة] LT'), 'Today - ' + i + ' days current time');
m.hours(0).minutes(0).seconds(0).milliseconds(0);
assert.equal(m.calendar(), m.format('dddd [على الساعة] LT'), 'Today - ' + i + ' days beginning of day');
m.hours(23).minutes(59).seconds(59).milliseconds(999);
assert.equal(m.calendar(), m.format('dddd [على الساعة] LT'), 'Today - ' + i + ' days end of day');
}
});
test('calendar all else', function (assert) {
var weeksAgo = moment().subtract({w: 1}),
weeksFromNow = moment().add({w: 1});
assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago');
assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week');
weeksAgo = moment().subtract({w: 2});
weeksFromNow = moment().add({w: 2});
assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago');
assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks');
});
test('weeks year starting wednesday custom', function (assert) {
assert.equal(moment('2003 1 6', 'gggg w d').format('YYYY-MM-DD'), '٢٠٠٣-٠١-٠٤', '2003 1 6 : gggg w d');
assert.equal(moment('2003 1 0', 'gggg w e').format('YYYY-MM-DD'), '٢٠٠٢-١٢-٢٩', '2003 1 0 : gggg w e');
assert.equal(moment('2003 1 6', 'gggg w d').format('gggg w d'), '٢٠٠٣ ١ ٦', '2003 1 6 : gggg w d');
assert.equal(moment('2003 1 0', 'gggg w e').format('gggg w e'), '٢٠٠٣ ١ ٠', '2003 1 0 : gggg w e');
});
test('weeks year starting sunday formatted', function (assert) {
assert.equal(moment([2011, 11, 31]).format('w ww wo'), '٥٣ ٥٣ ٥٣', '2011 11 31');
assert.equal(moment([2012, 0, 6]).format('w ww wo'), '١ ٠١ ١', '2012 0 6');
assert.equal(moment([2012, 0, 7]).format('w ww wo'), '١ ٠١ ١', '2012 0 7');
assert.equal(moment([2012, 0, 13]).format('w ww wo'), '٢ ٠٢ ٢', '2012 0 13');
assert.equal(moment([2012, 0, 14]).format('w ww wo'), '٢ ٠٢ ٢', '2012 0 14');
});
|
var lgUtils = require('./core/lg-utilities');
module.exports = function lostOffsetDecl(css, settings) {
css.walkDecls('lost-offset', function lostOffsetDeclFunction(decl) {
var declArr = [];
var lostOffset;
var lostOffsetNumerator;
var lostOffsetDirection;
var lostOffsetRounder = settings.rounder;
var lostOffsetGutter = settings.gutter;
function cloneAllBefore(props) {
Object.keys(props).forEach(function traverseProps(prop) {
decl.cloneBefore({
prop: prop,
value: props[prop],
});
});
}
const sanitizedDecl = lgUtils.glueFractionMembers(decl.value);
declArr = sanitizedDecl.split(' ');
lostOffset = declArr[0];
lostOffsetNumerator = declArr[0].split('/')[0];
if (
(declArr[1] !== undefined && declArr[1] === 'row') ||
declArr[1] === 'column'
) {
lostOffsetDirection = declArr[1];
}
if (declArr[2] !== undefined && declArr[2].search(/^\d/) !== -1) {
lostOffsetGutter = declArr[2];
}
decl.parent.nodes.forEach(function lostOffsetRounderFunction(declaration) {
if (declaration.prop === 'lost-offset-rounder') {
lostOffsetRounder = declaration.value;
declaration.remove();
}
});
decl.parent.nodes.forEach(function lostOffsetDirectionFunction(
declaration
) {
if (declaration.prop === 'lost-offset-direction') {
lostOffsetDirection = declaration.value;
declaration.remove();
}
});
decl.parent.nodes.forEach(function lostOffsetGutterFunction(declaration) {
if (declaration.prop === 'lost-offset-gutter') {
lostOffsetGutter = declaration.value;
declaration.remove();
}
});
if (lostOffsetDirection === 'column') {
if (lostOffset === 'clear') {
decl.cloneBefore({
prop: 'margin-top',
value: 'auto!important',
});
decl.cloneBefore({
prop: 'margin-bottom',
value: 'auto!important',
});
} else if (lostOffset === 'clear-top') {
decl.cloneBefore({
prop: 'margin-top',
value: 'auto!important',
});
} else if (lostOffset === 'clear-bottom') {
decl.cloneBefore({
prop: 'margin-bottom',
value: 'auto!important',
});
} else if (lostOffsetNumerator > 0) {
if (lostOffsetGutter !== '0') {
decl.cloneBefore({
prop: 'margin-bottom',
value:
'calc(' +
lostOffsetRounder +
'% * ' +
lostOffset +
' - (' +
lostOffsetGutter +
' - ' +
lostOffsetGutter +
' * ' +
lostOffset +
') + (' +
lostOffsetGutter +
' * 2)) !important',
});
} else {
decl.cloneBefore({
prop: 'margin-bottom',
value:
'calc(' +
lostOffsetRounder +
'% * ' +
lostOffset +
') !important',
});
}
} else if (lostOffsetNumerator < 0) {
if (lostOffsetGutter !== '0') {
decl.cloneBefore({
prop: 'margin-top',
value:
'calc(' +
lostOffsetRounder +
'% * (' +
lostOffset +
' * -1) - (' +
lostOffsetGutter +
' - ' +
lostOffsetGutter +
' * (' +
lostOffset +
' * -1)) + ' +
lostOffsetGutter +
') !important',
});
} else {
decl.cloneBefore({
prop: 'margin-top',
value:
'calc(' +
lostOffsetRounder +
'% * ' +
lostOffset +
') !important',
});
}
} else {
decl.cloneBefore({
prop: 'margin-top',
value: '0 !important',
});
decl.cloneBefore({
prop: 'margin-bottom',
value: lostOffsetGutter + ' !important',
});
}
} else if (lostOffset === 'clear') {
decl.cloneBefore({
prop: 'margin-left',
value: 'auto!important',
});
decl.cloneBefore({
prop: 'margin-right',
value: 'auto!important',
});
} else if (lostOffset === 'clear-left') {
decl.cloneBefore({
prop: 'margin-left',
value: 'auto!important',
});
} else if (lostOffset === 'clear-right') {
decl.cloneBefore({
prop: 'margin-right',
value: 'auto!important',
});
} else if (lostOffsetNumerator > 0) {
if (lostOffsetGutter !== '0') {
decl.cloneBefore({
prop: 'margin-left',
value:
'calc(' +
lostOffsetRounder +
'% * (-' +
lostOffset +
' * -1) - (' +
lostOffsetGutter +
' - ' +
lostOffsetGutter +
' * (-' +
lostOffset +
' * -1)) + ' +
lostOffsetGutter +
') !important',
});
} else {
decl.cloneBefore({
prop: 'margin-left',
value:
'calc(' + lostOffsetRounder + '% * ' + lostOffset + ') !important',
});
}
} else if (lostOffsetNumerator < 0) {
if (lostOffsetGutter !== '0') {
decl.cloneBefore({
prop: 'margin-left',
value:
'calc(' +
lostOffsetRounder +
'% * ' +
lostOffset +
' - (' +
lostOffsetGutter +
' - ' +
lostOffsetGutter +
' * ' +
lostOffset +
') + ' +
lostOffsetGutter +
') !important',
});
} else {
decl.cloneBefore({
prop: 'margin-left',
value:
'calc(' + lostOffsetRounder + '% * ' + lostOffset + ') !important',
});
}
} else {
cloneAllBefore({
'margin-left': '0 !important',
'margin-right': lostOffsetGutter + ' !important',
});
}
decl.remove();
});
};
|
import React from 'react';
const AddCircleIcon = props => (
<svg {...props.size || { width: '24px', height: '24px' }} {...props} viewBox="0 0 24 24">
{props.title && <title>{props.title}</title>}
<path d="M0 0h24v24H0z" fill="none" />
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11h-4v4h-2v-4H7v-2h4V7h2v4h4v2z" />
</svg>
);
export default AddCircleIcon;
|
/*!
* Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file.
*/
import '@ciscospark/internal-plugin-mercury';
import {registerInternalPlugin} from '@ciscospark/spark-core';
import Locus from './locus';
registerInternalPlugin(`locus`, Locus);
export default Locus;
export {locusEventKeys as eventKeys} from './event-keys';
export {USE_INCOMING, USE_CURRENT, EQUAL, FETCH} from './locus';
|
/*global Router, Meteor, Session, $*/
(function () {
'use strict';
Router.route('/login', {
name: 'login',
template: 'login_page',
layoutTemplate: null,
waitOn: function () {
Meteor.subscribe('friends');
return Meteor.subscribe('getUserData');
}
});
}()); |
const URL = require('url')
const Path = require('path')
export class UrlGenerator {
app = null
req = null
defaultUrl = null
constructor(app, defaultUrl = null) {
this.app = app
if (!defaultUrl.isNil) {
this.defaultUrl = defaultUrl
return
} else if (this.app.port === 443) {
defaultUrl = 'https://localhost'
} else if (this.app.port === 80) {
defaultUrl = 'http://localhost'
} else {
defaultUrl = `http://localhost:${this.app.port}`
}
this.defaultUrl = URL.parse(app.config.get('app.url', defaultUrl))
if (
!this.defaultUrl.path.isNil &&
this.defaultUrl.path !== '' &&
this.defaultUrl.path !== '/'
) {
throw new Error('`app.url` can not contain a path.')
}
}
/**
* Clone the instance to be used within a
* request cycle.
*
* @param object req
*
* @return object
*/
clone(req) {
const cloned = new this.constructor(this.app, this.defaultUrl)
cloned.req = req
return cloned
}
/**
* Generate a URL for a route name and it’s parameters
*
* @param {string} name Name of the route to generate
* @param {Object|Array|string} parameters Parameter values for the route.
* @param {Object|null} req Origin request to generate URL from, uses correct host/protocol
* @param {boolean|null} secure Whether or not to force https, null uses default behavior
* @return {string}
*/
route(name, parameters, req, secure) {
const route = this.app.routes.namedRoutes[name]
if (route.isNil) {
throw new Error(`Undefined route name: ${name}`)
}
if (!Array.isArray(parameters)) {
parameters = [parameters]
}
const numberOfParameters = parameters.length
let isObject = false
if (numberOfParameters === 1 && typeof parameters[0] === 'object') {
isObject = true
parameters = parameters[0]
}
if (isObject) {
parameters = { ...parameters }
}
let index = 0
const path = route.path.replace(/:([a-z0-0_-]+)(?:\(([^)]+)\))?(\?)?/g, (_, name) => {
if (isObject) {
const value = parameters[name] || ''
delete parameters[name]
return value
}
if (numberOfParameters < index) {
return ''
}
return parameters[index++] || ''
})
if (!isObject) {
parameters = null
}
return this.make(
{
pathname: path,
query: {},
},
parameters,
req,
secure,
)
}
/**
* Generate a URL
*
* @param {string} url URL/Path to generate
* @param {Object} query Query string parameters
* @param {Object|null} req Original request to generate URL from, uses correct host/protocol
* @param {boolean|null} secure Whether or not to force https, null uses default behavior
* @return {string}
*/
make(url, query, req, secure = null) {
if (req === true || req === false) {
secure = req
req = null
}
if (req.isNil) {
req = this.req
}
if (typeof url === 'string') {
if (url.indexOf('://') > 0 || url.indexOf('//') === 0) {
return url
}
if (url.indexOf('#') >= 0 || url.indexOf('?') >= 0) {
url = URL.parse(url, true)
delete url.path
delete url.href
delete url.search
} else {
url = { pathname: url }
}
}
if (!query.isNil) {
if (url.query.isNil) {
url.query = query
} else {
url.query = { ...url.query, ...query }
}
}
url.pathname = `/${Path.normalize(url.pathname || '/').replace(/(^\/|\/+$)/g, '')}`
url.protocol = this.getProtocol(req, secure)
url.host = this.getHost(req)
return this.format(req, url)
}
/**
* Generate the current URL
*
* @param {Object} query Additional query string parameters to add to the current URL
* @param {Object|null} req Original request to generate URL from, uses correct host/protocol
* @param {boolean|null} secure Whether or not to force https, null uses default behavior
* @return {string}
*/
current(query = {}, req, secure = null) {
req = req || this.req
if (req.isNil) {
throw new Error('`current` requires a request object')
}
return this.make(req.originalUrl, query, req, secure)
}
getProtocol(req = null, secure = null) {
if (secure === true) {
return 'https:'
} else if (secure === false) {
return 'http:'
}
if (req.isNil) {
return this.defaultUrl.protocol || 'http:'
}
if (req.secure) {
return 'https:'
}
return 'http:'
}
getHost(req = null) {
if (req.isNil) {
return this.defaultUrl.host || 'localhost'
}
return req.get('Host')
}
format(req, url) {
return URL.format(url)
}
}
|
const { getScheme, getProtocol } = require("../lib/util/URLAbsoluteSpecifier");
/**
* @type {Array<{specifier: string, expected: string|undefined}>}
*/
const samples = [
{
specifier: "@babel/core",
expected: undefined
},
{
specifier: "webpack",
expected: undefined
},
{
specifier: "1webpack:///c:/windows/dir",
expected: undefined
},
{
specifier: "webpack:///c:/windows/dir",
expected: "webpack"
},
{
specifier: "WEBPACK2020:///c:/windows/dir",
expected: "webpack2020"
},
{
specifier: "my-data:image/jpg;base64",
expected: "my-data"
},
{
specifier: "My+Data:image/jpg;base64",
expected: "my+data"
},
{
specifier: "mY+dATA:image/jpg;base64",
expected: "my+data"
},
{
specifier: "my-data/next:image/",
expected: undefined
},
{
specifier: "my-data\\next:image/",
expected: undefined
},
{
specifier: "D:\\path\\file.js",
expected: undefined
},
{
specifier: "d:/path/file.js",
expected: undefined
},
{
specifier: "z:#foo",
expected: undefined
},
{
specifier: "Z:?query",
expected: undefined
},
{
specifier: "C:",
expected: undefined
}
];
describe("getScheme", () => {
samples.forEach(({ specifier, expected }, i) => {
it(`should handle ${specifier}`, () => {
expect(getScheme(specifier)).toBe(expected);
});
});
});
describe("getProtocol", () => {
samples.forEach(({ specifier, expected }, i) => {
it(`should handle ${specifier}`, () => {
expect(getProtocol(specifier)).toBe(
expected ? expected + ":" : undefined
);
});
});
});
|
angular.module('app')
.controller('nrgiUserAdminCreateCtrl', function(
$scope,
$location,
nrgiNotifier,
nrgiIdentitySrvc,
nrgiUserSrvc,
nrgiUserMethodSrvc
) {
$scope.role_options = [
{value:'admin',text:'Administrator'}
]
// fix submit button functionality
$scope.userCreate = function() {
var new_user_data = {
first_name: $scope.first_name,
last_name: $scope.last_name,
username: $scope.username,
email: $scope.email,
password: $scope.password,
// ADD ROLE IN CREATION EVENT
roles: [$scope.role_select],
address: [$scope.address],
language: [$scope.language]
};
nrgiUserMethodSrvc.createUser(new_user_data).then(function() {
nrgiNotifier.notify('User account created!');
$location.path('/admin/user-admin');
}, function(reason) {
nrgiNotifier.error(reason);
})
};
}); |
'use strict';
var ANIMATE_TIMER_KEY = '$$animateCss';
/**
* @ngdoc service
* @name $animateCss
* @kind object
*
* @description
* The `$animateCss` service is a useful utility to trigger customized CSS-based transitions/keyframes
* from a JavaScript-based animation or directly from a directive. The purpose of `$animateCss` is NOT
* to side-step how `$animate` and ngAnimate work, but the goal is to allow pre-existing animations or
* directives to create more complex animations that can be purely driven using CSS code.
*
* Note that only browsers that support CSS transitions and/or keyframe animations are capable of
* rendering animations triggered via `$animateCss` (bad news for IE9 and lower).
*
* ## Usage
* Once again, `$animateCss` is designed to be used inside of a registered JavaScript animation that
* is powered by ngAnimate. It is possible to use `$animateCss` directly inside of a directive, however,
* any automatic control over cancelling animations and/or preventing animations from being run on
* child elements will not be handled by Angular. For this to work as expected, please use `$animate` to
* trigger the animation and then setup a JavaScript animation that injects `$animateCss` to trigger
* the CSS animation.
*
* The example below shows how we can create a folding animation on an element using `ng-if`:
*
* ```html
* <!-- notice the `fold-animation` CSS class -->
* <div ng-if="onOff" class="fold-animation">
* This element will go BOOM
* </div>
* <button ng-click="onOff=true">Fold In</button>
* ```
*
* Now we create the **JavaScript animation** that will trigger the CSS transition:
*
* ```js
* ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
* return {
* enter: function(element, doneFn) {
* var height = element[0].offsetHeight;
* return $animateCss(element, {
* from: { height:'0px' },
* to: { height:height + 'px' },
* duration: 1 // one second
* });
* }
* }
* }]);
* ```
*
* ## More Advanced Uses
*
* `$animateCss` is the underlying code that ngAnimate uses to power **CSS-based animations** behind the scenes. Therefore CSS hooks
* like `.ng-EVENT`, `.ng-EVENT-active`, `.ng-EVENT-stagger` are all features that can be triggered using `$animateCss` via JavaScript code.
*
* This also means that just about any combination of adding classes, removing classes, setting styles, dynamically setting a keyframe animation,
* applying a hardcoded duration or delay value, changing the animation easing or applying a stagger animation are all options that work with
* `$animateCss`. The service itself is smart enough to figure out the combination of options and examine the element styling properties in order
* to provide a working animation that will run in CSS.
*
* The example below showcases a more advanced version of the `.fold-animation` from the example above:
*
* ```js
* ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
* return {
* enter: function(element, doneFn) {
* var height = element[0].offsetHeight;
* return $animateCss(element, {
* addClass: 'red large-text pulse-twice',
* easing: 'ease-out',
* from: { height:'0px' },
* to: { height:height + 'px' },
* duration: 1 // one second
* });
* }
* }
* }]);
* ```
*
* Since we're adding/removing CSS classes then the CSS transition will also pick those up:
*
* ```css
* /* since a hardcoded duration value of 1 was provided in the JavaScript animation code,
* the CSS classes below will be transitioned despite them being defined as regular CSS classes */
* .red { background:red; }
* .large-text { font-size:20px; }
*
* /* we can also use a keyframe animation and $animateCss will make it work alongside the transition */
* .pulse-twice {
* animation: 0.5s pulse linear 2;
* -webkit-animation: 0.5s pulse linear 2;
* }
*
* @keyframes pulse {
* from { transform: scale(0.5); }
* to { transform: scale(1.5); }
* }
*
* @-webkit-keyframes pulse {
* from { -webkit-transform: scale(0.5); }
* to { -webkit-transform: scale(1.5); }
* }
* ```
*
* Given this complex combination of CSS classes, styles and options, `$animateCss` will figure everything out and make the animation happen.
*
* ## How the Options are handled
*
* `$animateCss` is very versatile and intelligent when it comes to figuring out what configurations to apply to the element to ensure the animation
* works with the options provided. Say for example we were adding a class that contained a keyframe value and we wanted to also animate some inline
* styles using the `from` and `to` properties.
*
* ```js
* var animator = $animateCss(element, {
* from: { background:'red' },
* to: { background:'blue' }
* });
* animator.start();
* ```
*
* ```css
* .rotating-animation {
* animation:0.5s rotate linear;
* -webkit-animation:0.5s rotate linear;
* }
*
* @keyframes rotate {
* from { transform: rotate(0deg); }
* to { transform: rotate(360deg); }
* }
*
* @-webkit-keyframes rotate {
* from { -webkit-transform: rotate(0deg); }
* to { -webkit-transform: rotate(360deg); }
* }
* ```
*
* The missing pieces here are that we do not have a transition set (within the CSS code nor within the `$animateCss` options) and the duration of the animation is
* going to be detected from what the keyframe styles on the CSS class are. In this event, `$animateCss` will automatically create an inline transition
* style matching the duration detected from the keyframe style (which is present in the CSS class that is being added) and then prepare both the transition
* and keyframe animations to run in parallel on the element. Then when the animation is underway the provided `from` and `to` CSS styles will be applied
* and spread across the transition and keyframe animation.
*
* ## What is returned
*
* `$animateCss` works in two stages: a preparation phase and an animation phase. Therefore when `$animateCss` is first called it will NOT actually
* start the animation. All that is going on here is that the element is being prepared for the animation (which means that the generated CSS classes are
* added and removed on the element). Once `$animateCss` is called it will return an object with the following properties:
*
* ```js
* var animator = $animateCss(element, { ... });
* ```
*
* Now what do the contents of our `animator` variable look like:
*
* ```js
* {
* // starts the animation
* start: Function,
*
* // ends (aborts) the animation
* end: Function
* }
* ```
*
* To actually start the animation we need to run `animation.start()` which will then return a promise that we can hook into to detect when the animation ends.
* If we choose not to run the animation then we MUST run `animation.end()` to perform a cleanup on the element (since some CSS classes and stlyes may have been
* applied to the element during the preparation phase). Note that all other properties such as duration, delay, transitions and keyframes are just properties
* and that changing them will not reconfigure the parameters of the animation.
*
* ### runner.done() vs runner.then()
* It is documented that `animation.start()` will return a promise object and this is true, however, there is also an additional method available on the
* runner called `.done(callbackFn)`. The done method works the same as `.finally(callbackFn)`, however, it does **not trigger a digest to occur**.
* Therefore, for performance reasons, it's always best to use `runner.done(callback)` instead of `runner.then()`, `runner.catch()` or `runner.finally()`
* unless you really need a digest to kick off afterwards.
*
* Keep in mind that, to make this easier, ngAnimate has tweaked the JS animations API to recognize when a runner instance is returned from $animateCss
* (so there is no need to call `runner.done(doneFn)` inside of your JavaScript animation code).
* Check the {@link ngAnimate.$animateCss#usage animation code above} to see how this works.
*
* @param {DOMElement} element the element that will be animated
* @param {object} options the animation-related options that will be applied during the animation
*
* * `event` - The DOM event (e.g. enter, leave, move). When used, a generated CSS class of `ng-EVENT` and `ng-EVENT-active` will be applied
* to the element during the animation. Multiple events can be provided when spaces are used as a separator. (Note that this will not perform any DOM operation.)
* * `structural` - Indicates that the `ng-` prefix will be added to the event class. Setting to `false` or omitting will turn `ng-EVENT` and
* `ng-EVENT-active` in `EVENT` and `EVENT-active`. Unused if `event` is omitted.
* * `easing` - The CSS easing value that will be applied to the transition or keyframe animation (or both).
* * `transitionStyle` - The raw CSS transition style that will be used (e.g. `1s linear all`).
* * `keyframeStyle` - The raw CSS keyframe animation style that will be used (e.g. `1s my_animation linear`).
* * `from` - The starting CSS styles (a key/value object) that will be applied at the start of the animation.
* * `to` - The ending CSS styles (a key/value object) that will be applied across the animation via a CSS transition.
* * `addClass` - A space separated list of CSS classes that will be added to the element and spread across the animation.
* * `removeClass` - A space separated list of CSS classes that will be removed from the element and spread across the animation.
* * `duration` - A number value representing the total duration of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `0`
* is provided then the animation will be skipped entirely.
* * `delay` - A number value representing the total delay of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `true` is
* used then whatever delay value is detected from the CSS classes will be mirrored on the elements styles (e.g. by setting delay true then the style value
* of the element will be `transition-delay: DETECTED_VALUE`). Using `true` is useful when you want the CSS classes and inline styles to all share the same
* CSS delay value.
* * `stagger` - A numeric time value representing the delay between successively animated elements
* ({@link ngAnimate#css-staggering-animations Click here to learn how CSS-based staggering works in ngAnimate.})
* * `staggerIndex` - The numeric index representing the stagger item (e.g. a value of 5 is equal to the sixth item in the stagger; therefore when a
* `stagger` option value of `0.1` is used then there will be a stagger delay of `600ms`)
* * `applyClassesEarly` - Whether or not the classes being added or removed will be used when detecting the animation. This is set by `$animate` when enter/leave/move animations are fired to ensure that the CSS classes are resolved in time. (Note that this will prevent any transitions from occuring on the classes being added and removed.)
* * `cleanupStyles` - Whether or not the provided `from` and `to` styles will be removed once
* the animation is closed. This is useful for when the styles are used purely for the sake of
* the animation and do not have a lasting visual effect on the element (e.g. a colapse and open animation).
* By default this value is set to `false`.
*
* @return {object} an object with start and end methods and details about the animation.
*
* * `start` - The method to start the animation. This will return a `Promise` when called.
* * `end` - This method will cancel the animation and remove all applied CSS classes and styles.
*/
var ONE_SECOND = 1000;
var BASE_TEN = 10;
var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3;
var CLOSING_TIME_BUFFER = 1.5;
var DETECT_CSS_PROPERTIES = {
transitionDuration: TRANSITION_DURATION_PROP,
transitionDelay: TRANSITION_DELAY_PROP,
transitionProperty: TRANSITION_PROP + PROPERTY_KEY,
animationDuration: ANIMATION_DURATION_PROP,
animationDelay: ANIMATION_DELAY_PROP,
animationIterationCount: ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY
};
var DETECT_STAGGER_CSS_PROPERTIES = {
transitionDuration: TRANSITION_DURATION_PROP,
transitionDelay: TRANSITION_DELAY_PROP,
animationDuration: ANIMATION_DURATION_PROP,
animationDelay: ANIMATION_DELAY_PROP
};
function getCssKeyframeDurationStyle(duration) {
return [ANIMATION_DURATION_PROP, duration + 's'];
}
function getCssDelayStyle(delay, isKeyframeAnimation) {
var prop = isKeyframeAnimation ? ANIMATION_DELAY_PROP : TRANSITION_DELAY_PROP;
return [prop, delay + 's'];
}
function computeCssStyles($window, element, properties) {
var styles = Object.create(null);
var detectedStyles = $window.getComputedStyle(element) || {};
forEach(properties, function(formalStyleName, actualStyleName) {
var val = detectedStyles[formalStyleName];
if (val) {
var c = val.charAt(0);
// only numerical-based values have a negative sign or digit as the first value
if (c === '-' || c === '+' || c >= 0) {
val = parseMaxTime(val);
}
// by setting this to null in the event that the delay is not set or is set directly as 0
// then we can still allow for zegative values to be used later on and not mistake this
// value for being greater than any other negative value.
if (val === 0) {
val = null;
}
styles[actualStyleName] = val;
}
});
return styles;
}
function parseMaxTime(str) {
var maxValue = 0;
var values = str.split(/\s*,\s*/);
forEach(values, function(value) {
// it's always safe to consider only second values and omit `ms` values since
// getComputedStyle will always handle the conversion for us
if (value.charAt(value.length - 1) == 's') {
value = value.substring(0, value.length - 1);
}
value = parseFloat(value) || 0;
maxValue = maxValue ? Math.max(value, maxValue) : value;
});
return maxValue;
}
function truthyTimingValue(val) {
return val === 0 || val != null;
}
function getCssTransitionDurationStyle(duration, applyOnlyDuration) {
var style = TRANSITION_PROP;
var value = duration + 's';
if (applyOnlyDuration) {
style += DURATION_KEY;
} else {
value += ' linear all';
}
return [style, value];
}
function createLocalCacheLookup() {
var cache = Object.create(null);
return {
flush: function() {
cache = Object.create(null);
},
count: function(key) {
var entry = cache[key];
return entry ? entry.total : 0;
},
get: function(key) {
var entry = cache[key];
return entry && entry.value;
},
put: function(key, value) {
if (!cache[key]) {
cache[key] = { total: 1, value: value };
} else {
cache[key].total++;
}
}
};
}
// we do not reassign an already present style value since
// if we detect the style property value again we may be
// detecting styles that were added via the `from` styles.
// We make use of `isDefined` here since an empty string
// or null value (which is what getPropertyValue will return
// for a non-existing style) will still be marked as a valid
// value for the style (a falsy value implies that the style
// is to be removed at the end of the animation). If we had a simple
// "OR" statement then it would not be enough to catch that.
function registerRestorableStyles(backup, node, properties) {
forEach(properties, function(prop) {
backup[prop] = isDefined(backup[prop])
? backup[prop]
: node.style.getPropertyValue(prop);
});
}
var $AnimateCssProvider = ['$animateProvider', function($animateProvider) {
var gcsLookup = createLocalCacheLookup();
var gcsStaggerLookup = createLocalCacheLookup();
this.$get = ['$window', '$$jqLite', '$$AnimateRunner', '$timeout',
'$$forceReflow', '$sniffer', '$$rAFScheduler', '$animate',
function($window, $$jqLite, $$AnimateRunner, $timeout,
$$forceReflow, $sniffer, $$rAFScheduler, $animate) {
var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
var parentCounter = 0;
function gcsHashFn(node, extraClasses) {
var KEY = "$$ngAnimateParentKey";
var parentNode = node.parentNode;
var parentID = parentNode[KEY] || (parentNode[KEY] = ++parentCounter);
return parentID + '-' + node.getAttribute('class') + '-' + extraClasses;
}
function computeCachedCssStyles(node, className, cacheKey, properties) {
var timings = gcsLookup.get(cacheKey);
if (!timings) {
timings = computeCssStyles($window, node, properties);
if (timings.animationIterationCount === 'infinite') {
timings.animationIterationCount = 1;
}
}
// we keep putting this in multiple times even though the value and the cacheKey are the same
// because we're keeping an interal tally of how many duplicate animations are detected.
gcsLookup.put(cacheKey, timings);
return timings;
}
function computeCachedCssStaggerStyles(node, className, cacheKey, properties) {
var stagger;
// if we have one or more existing matches of matching elements
// containing the same parent + CSS styles (which is how cacheKey works)
// then staggering is possible
if (gcsLookup.count(cacheKey) > 0) {
stagger = gcsStaggerLookup.get(cacheKey);
if (!stagger) {
var staggerClassName = pendClasses(className, '-stagger');
$$jqLite.addClass(node, staggerClassName);
stagger = computeCssStyles($window, node, properties);
// force the conversion of a null value to zero incase not set
stagger.animationDuration = Math.max(stagger.animationDuration, 0);
stagger.transitionDuration = Math.max(stagger.transitionDuration, 0);
$$jqLite.removeClass(node, staggerClassName);
gcsStaggerLookup.put(cacheKey, stagger);
}
}
return stagger || {};
}
var cancelLastRAFRequest;
var rafWaitQueue = [];
function waitUntilQuiet(callback) {
rafWaitQueue.push(callback);
$$rAFScheduler.waitUntilQuiet(function() {
gcsLookup.flush();
gcsStaggerLookup.flush();
// DO NOT REMOVE THIS LINE OR REFACTOR OUT THE `pageWidth` variable.
// PLEASE EXAMINE THE `$$forceReflow` service to understand why.
var pageWidth = $$forceReflow();
// we use a for loop to ensure that if the queue is changed
// during this looping then it will consider new requests
for (var i = 0; i < rafWaitQueue.length; i++) {
rafWaitQueue[i](pageWidth);
}
rafWaitQueue.length = 0;
});
}
function computeTimings(node, className, cacheKey) {
var timings = computeCachedCssStyles(node, className, cacheKey, DETECT_CSS_PROPERTIES);
var aD = timings.animationDelay;
var tD = timings.transitionDelay;
timings.maxDelay = aD && tD
? Math.max(aD, tD)
: (aD || tD);
timings.maxDuration = Math.max(
timings.animationDuration * timings.animationIterationCount,
timings.transitionDuration);
return timings;
}
return function init(element, initialOptions) {
// we always make a copy of the options since
// there should never be any side effects on
// the input data when running `$animateCss`.
var options = copy(initialOptions);
var restoreStyles = {};
var node = getDomNode(element);
if (!node
|| !node.parentNode
|| !$animate.enabled()) {
return closeAndReturnNoopAnimator();
}
options = prepareAnimationOptions(options);
var temporaryStyles = [];
var classes = element.attr('class');
var styles = packageStyles(options);
var animationClosed;
var animationPaused;
var animationCompleted;
var runner;
var runnerHost;
var maxDelay;
var maxDelayTime;
var maxDuration;
var maxDurationTime;
if (options.duration === 0 || (!$sniffer.animations && !$sniffer.transitions)) {
return closeAndReturnNoopAnimator();
}
var method = options.event && isArray(options.event)
? options.event.join(' ')
: options.event;
var isStructural = method && options.structural;
var structuralClassName = '';
var addRemoveClassName = '';
if (isStructural) {
structuralClassName = pendClasses(method, EVENT_CLASS_PREFIX, true);
} else if (method) {
structuralClassName = method;
}
if (options.addClass) {
addRemoveClassName += pendClasses(options.addClass, ADD_CLASS_SUFFIX);
}
if (options.removeClass) {
if (addRemoveClassName.length) {
addRemoveClassName += ' ';
}
addRemoveClassName += pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX);
}
// there may be a situation where a structural animation is combined together
// with CSS classes that need to resolve before the animation is computed.
// However this means that there is no explicit CSS code to block the animation
// from happening (by setting 0s none in the class name). If this is the case
// we need to apply the classes before the first rAF so we know to continue if
// there actually is a detected transition or keyframe animation
if (options.applyClassesEarly && addRemoveClassName.length) {
applyAnimationClasses(element, options);
}
var preparationClasses = [structuralClassName, addRemoveClassName].join(' ').trim();
var fullClassName = classes + ' ' + preparationClasses;
var activeClasses = pendClasses(preparationClasses, ACTIVE_CLASS_SUFFIX);
var hasToStyles = styles.to && Object.keys(styles.to).length > 0;
var containsKeyframeAnimation = (options.keyframeStyle || '').length > 0;
// there is no way we can trigger an animation if no styles and
// no classes are being applied which would then trigger a transition,
// unless there a is raw keyframe value that is applied to the element.
if (!containsKeyframeAnimation
&& !hasToStyles
&& !preparationClasses) {
return closeAndReturnNoopAnimator();
}
var cacheKey, stagger;
if (options.stagger > 0) {
var staggerVal = parseFloat(options.stagger);
stagger = {
transitionDelay: staggerVal,
animationDelay: staggerVal,
transitionDuration: 0,
animationDuration: 0
};
} else {
cacheKey = gcsHashFn(node, fullClassName);
stagger = computeCachedCssStaggerStyles(node, preparationClasses, cacheKey, DETECT_STAGGER_CSS_PROPERTIES);
}
if (!options.$$skipPreparationClasses) {
$$jqLite.addClass(element, preparationClasses);
}
var applyOnlyDuration;
if (options.transitionStyle) {
var transitionStyle = [TRANSITION_PROP, options.transitionStyle];
applyInlineStyle(node, transitionStyle);
temporaryStyles.push(transitionStyle);
}
if (options.duration >= 0) {
applyOnlyDuration = node.style[TRANSITION_PROP].length > 0;
var durationStyle = getCssTransitionDurationStyle(options.duration, applyOnlyDuration);
// we set the duration so that it will be picked up by getComputedStyle later
applyInlineStyle(node, durationStyle);
temporaryStyles.push(durationStyle);
}
if (options.keyframeStyle) {
var keyframeStyle = [ANIMATION_PROP, options.keyframeStyle];
applyInlineStyle(node, keyframeStyle);
temporaryStyles.push(keyframeStyle);
}
var itemIndex = stagger
? options.staggerIndex >= 0
? options.staggerIndex
: gcsLookup.count(cacheKey)
: 0;
var isFirst = itemIndex === 0;
// this is a pre-emptive way of forcing the setup classes to be added and applied INSTANTLY
// without causing any combination of transitions to kick in. By adding a negative delay value
// it forces the setup class' transition to end immediately. We later then remove the negative
// transition delay to allow for the transition to naturally do it's thing. The beauty here is
// that if there is no transition defined then nothing will happen and this will also allow
// other transitions to be stacked on top of each other without any chopping them out.
if (isFirst && !options.skipBlocking) {
blockTransitions(node, SAFE_FAST_FORWARD_DURATION_VALUE);
}
var timings = computeTimings(node, fullClassName, cacheKey);
var relativeDelay = timings.maxDelay;
maxDelay = Math.max(relativeDelay, 0);
maxDuration = timings.maxDuration;
var flags = {};
flags.hasTransitions = timings.transitionDuration > 0;
flags.hasAnimations = timings.animationDuration > 0;
flags.hasTransitionAll = flags.hasTransitions && timings.transitionProperty == 'all';
flags.applyTransitionDuration = hasToStyles && (
(flags.hasTransitions && !flags.hasTransitionAll)
|| (flags.hasAnimations && !flags.hasTransitions));
flags.applyAnimationDuration = options.duration && flags.hasAnimations;
flags.applyTransitionDelay = truthyTimingValue(options.delay) && (flags.applyTransitionDuration || flags.hasTransitions);
flags.applyAnimationDelay = truthyTimingValue(options.delay) && flags.hasAnimations;
flags.recalculateTimingStyles = addRemoveClassName.length > 0;
if (flags.applyTransitionDuration || flags.applyAnimationDuration) {
maxDuration = options.duration ? parseFloat(options.duration) : maxDuration;
if (flags.applyTransitionDuration) {
flags.hasTransitions = true;
timings.transitionDuration = maxDuration;
applyOnlyDuration = node.style[TRANSITION_PROP + PROPERTY_KEY].length > 0;
temporaryStyles.push(getCssTransitionDurationStyle(maxDuration, applyOnlyDuration));
}
if (flags.applyAnimationDuration) {
flags.hasAnimations = true;
timings.animationDuration = maxDuration;
temporaryStyles.push(getCssKeyframeDurationStyle(maxDuration));
}
}
if (maxDuration === 0 && !flags.recalculateTimingStyles) {
return closeAndReturnNoopAnimator();
}
if (options.delay != null) {
var delayStyle;
if (typeof options.delay !== "boolean") {
delayStyle = parseFloat(options.delay);
// number in options.delay means we have to recalculate the delay for the closing timeout
maxDelay = Math.max(delayStyle, 0);
}
if (flags.applyTransitionDelay) {
temporaryStyles.push(getCssDelayStyle(delayStyle));
}
if (flags.applyAnimationDelay) {
temporaryStyles.push(getCssDelayStyle(delayStyle, true));
}
}
// we need to recalculate the delay value since we used a pre-emptive negative
// delay value and the delay value is required for the final event checking. This
// property will ensure that this will happen after the RAF phase has passed.
if (options.duration == null && timings.transitionDuration > 0) {
flags.recalculateTimingStyles = flags.recalculateTimingStyles || isFirst;
}
maxDelayTime = maxDelay * ONE_SECOND;
maxDurationTime = maxDuration * ONE_SECOND;
if (!options.skipBlocking) {
flags.blockTransition = timings.transitionDuration > 0;
flags.blockKeyframeAnimation = timings.animationDuration > 0 &&
stagger.animationDelay > 0 &&
stagger.animationDuration === 0;
}
if (options.from) {
if (options.cleanupStyles) {
registerRestorableStyles(restoreStyles, node, Object.keys(options.from));
}
applyAnimationFromStyles(element, options);
}
if (flags.blockTransition || flags.blockKeyframeAnimation) {
applyBlocking(maxDuration);
} else if (!options.skipBlocking) {
blockTransitions(node, false);
}
// TODO(matsko): for 1.5 change this code to have an animator object for better debugging
return {
$$willAnimate: true,
end: endFn,
start: function() {
if (animationClosed) return;
runnerHost = {
end: endFn,
cancel: cancelFn,
resume: null, //this will be set during the start() phase
pause: null
};
runner = new $$AnimateRunner(runnerHost);
waitUntilQuiet(start);
// we don't have access to pause/resume the animation
// since it hasn't run yet. AnimateRunner will therefore
// set noop functions for resume and pause and they will
// later be overridden once the animation is triggered
return runner;
}
};
function endFn() {
close();
}
function cancelFn() {
close(true);
}
function close(rejected) { // jshint ignore:line
// if the promise has been called already then we shouldn't close
// the animation again
if (animationClosed || (animationCompleted && animationPaused)) return;
animationClosed = true;
animationPaused = false;
if (!options.$$skipPreparationClasses) {
$$jqLite.removeClass(element, preparationClasses);
}
$$jqLite.removeClass(element, activeClasses);
blockKeyframeAnimations(node, false);
blockTransitions(node, false);
forEach(temporaryStyles, function(entry) {
// There is only one way to remove inline style properties entirely from elements.
// By using `removeProperty` this works, but we need to convert camel-cased CSS
// styles down to hyphenated values.
node.style[entry[0]] = '';
});
applyAnimationClasses(element, options);
applyAnimationStyles(element, options);
if (Object.keys(restoreStyles).length) {
forEach(restoreStyles, function(value, prop) {
value ? node.style.setProperty(prop, value)
: node.style.removeProperty(prop);
});
}
// the reason why we have this option is to allow a synchronous closing callback
// that is fired as SOON as the animation ends (when the CSS is removed) or if
// the animation never takes off at all. A good example is a leave animation since
// the element must be removed just after the animation is over or else the element
// will appear on screen for one animation frame causing an overbearing flicker.
if (options.onDone) {
options.onDone();
}
// if the preparation function fails then the promise is not setup
if (runner) {
runner.complete(!rejected);
}
}
function applyBlocking(duration) {
if (flags.blockTransition) {
blockTransitions(node, duration);
}
if (flags.blockKeyframeAnimation) {
blockKeyframeAnimations(node, !!duration);
}
}
function closeAndReturnNoopAnimator() {
runner = new $$AnimateRunner({
end: endFn,
cancel: cancelFn
});
// should flush the cache animation
waitUntilQuiet(noop);
close();
return {
$$willAnimate: false,
start: function() {
return runner;
},
end: endFn
};
}
function start() {
if (animationClosed) return;
if (!node.parentNode) {
close();
return;
}
var startTime, events = [];
// even though we only pause keyframe animations here the pause flag
// will still happen when transitions are used. Only the transition will
// not be paused since that is not possible. If the animation ends when
// paused then it will not complete until unpaused or cancelled.
var playPause = function(playAnimation) {
if (!animationCompleted) {
animationPaused = !playAnimation;
if (timings.animationDuration) {
var value = blockKeyframeAnimations(node, animationPaused);
animationPaused
? temporaryStyles.push(value)
: removeFromArray(temporaryStyles, value);
}
} else if (animationPaused && playAnimation) {
animationPaused = false;
close();
}
};
// checking the stagger duration prevents an accidently cascade of the CSS delay style
// being inherited from the parent. If the transition duration is zero then we can safely
// rely that the delay value is an intential stagger delay style.
var maxStagger = itemIndex > 0
&& ((timings.transitionDuration && stagger.transitionDuration === 0) ||
(timings.animationDuration && stagger.animationDuration === 0))
&& Math.max(stagger.animationDelay, stagger.transitionDelay);
if (maxStagger) {
$timeout(triggerAnimationStart,
Math.floor(maxStagger * itemIndex * ONE_SECOND),
false);
} else {
triggerAnimationStart();
}
// this will decorate the existing promise runner with pause/resume methods
runnerHost.resume = function() {
playPause(true);
};
runnerHost.pause = function() {
playPause(false);
};
function triggerAnimationStart() {
// just incase a stagger animation kicks in when the animation
// itself was cancelled entirely
if (animationClosed) return;
applyBlocking(false);
forEach(temporaryStyles, function(entry) {
var key = entry[0];
var value = entry[1];
node.style[key] = value;
});
applyAnimationClasses(element, options);
$$jqLite.addClass(element, activeClasses);
if (flags.recalculateTimingStyles) {
fullClassName = node.className + ' ' + preparationClasses;
cacheKey = gcsHashFn(node, fullClassName);
timings = computeTimings(node, fullClassName, cacheKey);
relativeDelay = timings.maxDelay;
maxDelay = Math.max(relativeDelay, 0);
maxDuration = timings.maxDuration;
if (maxDuration === 0) {
close();
return;
}
flags.hasTransitions = timings.transitionDuration > 0;
flags.hasAnimations = timings.animationDuration > 0;
}
if (flags.applyAnimationDelay) {
relativeDelay = typeof options.delay !== "boolean" && truthyTimingValue(options.delay)
? parseFloat(options.delay)
: relativeDelay;
maxDelay = Math.max(relativeDelay, 0);
timings.animationDelay = relativeDelay;
delayStyle = getCssDelayStyle(relativeDelay, true);
temporaryStyles.push(delayStyle);
node.style[delayStyle[0]] = delayStyle[1];
}
maxDelayTime = maxDelay * ONE_SECOND;
maxDurationTime = maxDuration * ONE_SECOND;
if (options.easing) {
var easeProp, easeVal = options.easing;
if (flags.hasTransitions) {
easeProp = TRANSITION_PROP + TIMING_KEY;
temporaryStyles.push([easeProp, easeVal]);
node.style[easeProp] = easeVal;
}
if (flags.hasAnimations) {
easeProp = ANIMATION_PROP + TIMING_KEY;
temporaryStyles.push([easeProp, easeVal]);
node.style[easeProp] = easeVal;
}
}
if (timings.transitionDuration) {
events.push(TRANSITIONEND_EVENT);
}
if (timings.animationDuration) {
events.push(ANIMATIONEND_EVENT);
}
startTime = Date.now();
var timerTime = maxDelayTime + CLOSING_TIME_BUFFER * maxDurationTime;
var endTime = startTime + timerTime;
var animationsData = element.data(ANIMATE_TIMER_KEY) || [];
var setupFallbackTimer = true;
if (animationsData.length) {
var currentTimerData = animationsData[0];
setupFallbackTimer = endTime > currentTimerData.expectedEndTime;
if (setupFallbackTimer) {
$timeout.cancel(currentTimerData.timer);
} else {
animationsData.push(close);
}
}
if (setupFallbackTimer) {
var timer = $timeout(onAnimationExpired, timerTime, false);
animationsData[0] = {
timer: timer,
expectedEndTime: endTime
};
animationsData.push(close);
element.data(ANIMATE_TIMER_KEY, animationsData);
}
element.on(events.join(' '), onAnimationProgress);
if (options.to) {
if (options.cleanupStyles) {
registerRestorableStyles(restoreStyles, node, Object.keys(options.to));
}
applyAnimationToStyles(element, options);
}
}
function onAnimationExpired() {
var animationsData = element.data(ANIMATE_TIMER_KEY);
// this will be false in the event that the element was
// removed from the DOM (via a leave animation or something
// similar)
if (animationsData) {
for (var i = 1; i < animationsData.length; i++) {
animationsData[i]();
}
element.removeData(ANIMATE_TIMER_KEY);
}
}
function onAnimationProgress(event) {
event.stopPropagation();
var ev = event.originalEvent || event;
var timeStamp = ev.$manualTimeStamp || ev.timeStamp || Date.now();
/* Firefox (or possibly just Gecko) likes to not round values up
* when a ms measurement is used for the animation */
var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES));
/* $manualTimeStamp is a mocked timeStamp value which is set
* within browserTrigger(). This is only here so that tests can
* mock animations properly. Real events fallback to event.timeStamp,
* or, if they don't, then a timeStamp is automatically created for them.
* We're checking to see if the timeStamp surpasses the expected delay,
* but we're using elapsedTime instead of the timeStamp on the 2nd
* pre-condition since animations sometimes close off early */
if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) {
// we set this flag to ensure that if the transition is paused then, when resumed,
// the animation will automatically close itself since transitions cannot be paused.
animationCompleted = true;
close();
}
}
}
};
}];
}];
|
import deferred from '@redux-saga/deferred'
import * as is from '@redux-saga/is'
import { TASK, TASK_CANCEL } from '@redux-saga/symbols'
import { RUNNING, CANCELLED, ABORTED, DONE } from './task-status'
import { assignWithSymbols, check, createSetContextWarning, noop } from './utils'
import forkQueue from './forkQueue'
import * as sagaError from './sagaError'
export default function newTask(env, mainTask, parentContext, parentEffectId, meta, isRoot, cont = noop) {
let status = RUNNING
let taskResult
let taskError
let deferredEnd = null
const cancelledDueToErrorTasks = []
const context = Object.create(parentContext)
const queue = forkQueue(
mainTask,
function onAbort() {
cancelledDueToErrorTasks.push(...queue.getTasks().map(t => t.meta.name))
},
end,
)
/**
This may be called by a parent generator to trigger/propagate cancellation
cancel all pending tasks (including the main task), then end the current task.
Cancellation propagates down to the whole execution tree held by this Parent task
It's also propagated to all joiners of this task and their execution tree/joiners
Cancellation is noop for terminated/Cancelled tasks tasks
**/
function cancel() {
if (status === RUNNING) {
// Setting status to CANCELLED does not necessarily mean that the task/iterators are stopped
// effects in the iterator's finally block will still be executed
status = CANCELLED
queue.cancelAll()
// Ending with a TASK_CANCEL will propagate the Cancellation to all joiners
end(TASK_CANCEL, false)
}
}
function end(result, isErr) {
if (!isErr) {
// The status here may be RUNNING or CANCELLED
// If the status is CANCELLED, then we do not need to change it here
if (result === TASK_CANCEL) {
status = CANCELLED
} else if (status !== CANCELLED) {
status = DONE
}
taskResult = result
deferredEnd && deferredEnd.resolve(result)
} else {
status = ABORTED
sagaError.addSagaFrame({ meta, cancelledTasks: cancelledDueToErrorTasks })
if (task.isRoot) {
const sagaStack = sagaError.toString()
// we've dumped the saga stack to string and are passing it to user's code
// we know that it won't be needed anymore and we need to clear it
sagaError.clear()
env.onError(result, { sagaStack })
}
taskError = result
deferredEnd && deferredEnd.reject(result)
}
task.cont(result, isErr)
task.joiners.forEach(joiner => {
joiner.cb(result, isErr)
})
task.joiners = null
}
function setContext(props) {
if (process.env.NODE_ENV !== 'production') {
check(props, is.object, createSetContextWarning('task', props))
}
assignWithSymbols(context, props)
}
function toPromise() {
if (deferredEnd) {
return deferredEnd.promise
}
deferredEnd = deferred()
if (status === ABORTED) {
deferredEnd.reject(taskError)
} else if (status !== RUNNING) {
deferredEnd.resolve(taskResult)
}
return deferredEnd.promise
}
const task = {
// fields
[TASK]: true,
id: parentEffectId,
meta,
isRoot,
context,
joiners: [],
queue,
// methods
cancel,
cont,
end,
setContext,
toPromise,
isRunning: () => status === RUNNING,
/*
This method is used both for answering the cancellation status of the task and answering for CANCELLED effects.
In most cases, the cancellation of a task propagates to all its unfinished children (including
all forked tasks and the mainTask), so a naive implementation of this method would be:
`() => status === CANCELLED || mainTask.status === CANCELLED`
But there are cases that the task is aborted by an error and the abortion caused the mainTask to be cancelled.
In such cases, the task is supposed to be aborted rather than cancelled, however the above naive implementation
would return true for `task.isCancelled()`. So we need make sure that the task is running before accessing
mainTask.status.
There are cases that the task is cancelled when the mainTask is done (the task is waiting for forked children
when cancellation occurs). In such cases, you may wonder `yield io.cancelled()` would return true because
`status === CANCELLED` holds, and which is wrong. However, after the mainTask is done, the iterator cannot yield
any further effects, so we can ignore such cases.
See discussions in #1704
*/
isCancelled: () => status === CANCELLED || (status === RUNNING && mainTask.status === CANCELLED),
isAborted: () => status === ABORTED,
result: () => taskResult,
error: () => taskError,
}
return task
}
|
import { QueryBuilder as BaseQueryBuilder } from 'objection'
import './ModelNotFoundError'
export class QueryBuilder extends BaseQueryBuilder {
static registeredFilters = {}
static registerFilter(name, filter) {
this.registeredFilters[name] = filter
}
constructor(modelClass) {
super(modelClass)
const filters = modelClass.eager.isNil ? null : modelClass.eagerFilters
this.eager(modelClass.eager, filters)
}
paginate(req, perPage = 25, { query, param } = {}) {
let page = 1
if (!param.isNil) {
page = Number.parseInt(req.params[param]) || 1
} else {
page = Number.parseInt(req.query[query || 'page']) || 1
}
page = Math.max(1, page)
const start = (page - 1) * perPage
const end = start + perPage
return this.range(start, end).runAfter(result => {
result.totalPages = Math.ceil(result.total / perPage)
result.perPage = perPage
result.page = page
result.start = start
result.end = Math.min(end, result.total)
return result
})
}
orFail() {
return this.runAfter(result => {
if (
result.isNil ||
(Array.isArray(result) && result.length === 0) ||
(Array.isArray(result.results) && result.results.length === 0)
) {
throw new ModelNotFoundError(this._modelClass)
}
return result
})
}
eager(exp, filters) {
if (typeof exp === 'string') {
filters = Object.assign({}, this.constructor.registeredFilters, filters || {})
}
return super.eager(exp, filters)
}
}
|
/*
* server/index.js
*/
'use strict';
exports = module.exports = require('./app').run();
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @interface
*/
UI.TextEditorFactory = function() {};
UI.TextEditorFactory.prototype = {
/**
* @param {!UI.TextEditor.Options} options
* @return {!UI.TextEditor}
*/
createEditor(options) {}
};
/**
* @interface
* @extends {Common.EventTarget}
*/
UI.TextEditor = function() {};
UI.TextEditor.prototype = {
/**
* @return {!UI.Widget}
*/
widget() {},
/**
* @return {!TextUtils.TextRange}
*/
fullRange() {},
/**
* @return {!TextUtils.TextRange}
*/
selection() {},
/**
* @param {!TextUtils.TextRange} selection
*/
setSelection(selection) {},
/**
* @param {!TextUtils.TextRange=} textRange
* @return {string}
*/
text(textRange) {},
/**
* @return {string}
*/
textWithCurrentSuggestion() {},
/**
* @param {string} text
*/
setText(text) {},
/**
* @param {number} lineNumber
* @return {string}
*/
line(lineNumber) {},
newlineAndIndent() {},
/**
* @param {function(!KeyboardEvent)} handler
*/
addKeyDownHandler(handler) {},
/**
* @param {?UI.AutocompleteConfig} config
*/
configureAutocomplete(config) {},
clearAutocomplete() {},
/**
* @param {number} lineNumber
* @param {number} columnNumber
* @return {!{x: number, y: number}}
*/
visualCoordinates(lineNumber, columnNumber) {},
/**
* @param {number} lineNumber
* @param {number} columnNumber
* @return {?{startColumn: number, endColumn: number, type: string}}
*/
tokenAtTextPosition(lineNumber, columnNumber) {}
};
/** @enum {symbol} */
UI.TextEditor.Events = {
TextChanged: Symbol('TextChanged'),
SuggestionChanged: Symbol('SuggestionChanged')
};
/**
* @typedef {{
* bracketMatchingSetting: (!Common.Setting|undefined),
* lineNumbers: boolean,
* lineWrapping: boolean,
* mimeType: (string|undefined),
* autoHeight: (boolean|undefined),
* padBottom: (boolean|undefined),
* maxHighlightLength: (number|undefined),
* placeholder: (string|undefined)
* }}
*/
UI.TextEditor.Options;
/**
* @typedef {{
* substituteRangeCallback: ((function(number, number):?TextUtils.TextRange)|undefined),
* tooltipCallback: ((function(number, number):!Promise<?Element>)|undefined),
* suggestionsCallback: ((function(!TextUtils.TextRange, !TextUtils.TextRange, boolean=):?Promise.<!UI.SuggestBox.Suggestions>)|undefined),
* isWordChar: ((function(string):boolean)|undefined),
* anchorBehavior: (UI.GlassPane.AnchorBehavior|undefined)
* }}
*/
UI.AutocompleteConfig;
|
var assert = require('assert');
var self = this;
describe('Bug #131: Undefined query parameters generated when populating optional one-way associations', function () {
before(function (done) {
var fixtures = {
FileFixture: {
identity: 'file',
attributes: {
name: {
type : 'string',
required : true
}
}
},
PersonFixture: {
identity: 'person',
attributes: {
name: {
type : 'string',
required : true
},
avatar: {
model: 'file'
}
}
}
};
CREATE_TEST_WATERLINE(self, 'test_bug_131', fixtures, done);
});
after(function (done) {
DELETE_TEST_WATERLINE('test_bug_131', done);
});
describe('... finding and populating a person created without an avatar', function () {
/////////////////////////////////////////////////////
// TEST SETUP
////////////////////////////////////////////////////
before(function (done) {
self.collections.Person.create({ name: 'mike' }, done);
});
/////////////////////////////////////////////////////
// TEST METHODS
////////////////////////////////////////////////////
it('should not try to send undefined parameters to the database', function (done) {
self.collections.Person.getDB().on('beginQuery', function (query) {
var params = query && query.params && query.params.params ?
query.params.params : undefined;
if (params) {
for (var param in params) {
if (params.hasOwnProperty(param)) {
assert(params[param] !== undefined);
}
}
}
});
self.collections.Person.find({ name: 'mike' }).populate('avatar').exec(done);
});
});
});
|
describe('Wildling Bandit', function() {
integration(function() {
beforeEach(function() {
const deck1 = this.buildDeck('lannister', [
'Sneak Attack',
'Wildling Bandit'
]);
const deck2 = this.buildDeck('lannister', [
'Time of Plenty'
]);
this.player1.selectDeck(deck1);
this.player2.selectDeck(deck2);
this.startGame();
this.keepStartingHands();
this.bandit = this.player1.findCardByName('Wildling Bandit');
this.player1.clickCard(this.bandit);
this.completeSetup();
this.player1.selectPlot('Sneak Attack');
this.player2.selectPlot('Time of Plenty');
this.selectFirstPlayer(this.player1);
this.completeMarshalPhase();
});
describe('when attacking a more wealthy opponent', function() {
beforeEach(function() {
this.player1.clickPrompt('Military');
this.player1.clickCard(this.bandit);
this.player1.clickPrompt('Done');
});
it('should increase the strength of Wildling Bandit by 2', function() {
expect(this.player1Object.gold).toBe(5);
expect(this.player2Object.gold).toBe(6);
expect(this.bandit.getStrength()).toBe(3);
});
});
});
});
|
import { set } from 'lodash';
import { getModule, replaceCodeMemory } from '../utils';
export default async function generateCssFrameworkBootstrap(params) {
switch (params.cssPreprocessor) {
case 'css':
set(params.build, ['public', 'css', 'main.css'], await getModule('css-framework/bootstrap/main.css'));
if (params.cssPreprocessorOptions.includes('minifiedCss')) {
set(params.build, ['public', 'css', 'vendor', 'bootstrap.min.css'], await getModule('css-framework/bootstrap/css/bootstrap.min.css'));
} else {
set(params.build, ['public', 'css', 'vendor', 'bootstrap.css'], await getModule('css-framework/bootstrap/css/bootstrap.css'));
}
break;
case 'less':
set(params.build, ['public', 'css', 'main.less'], await getModule('css-framework/bootstrap/main.less'));
params.build.public.css.vendor = {
bootstrap: {
mixins: {
'alerts.less': await getModule('css-framework/bootstrap/less/mixins/alerts.less'),
'background-variant.less': await getModule('css-framework/bootstrap/less/mixins/background-variant.less'),
'border-radius.less': await getModule('css-framework/bootstrap/less/mixins/border-radius.less'),
'buttons.less': await getModule('css-framework/bootstrap/less/mixins/buttons.less'),
'center-block.less': await getModule('css-framework/bootstrap/less/mixins/center-block.less'),
'clearfix.less': await getModule('css-framework/bootstrap/less/mixins/clearfix.less'),
'forms.less': await getModule('css-framework/bootstrap/less/mixins/forms.less'),
'gradients.less': await getModule('css-framework/bootstrap/less/mixins/gradients.less'),
'grid.less': await getModule('css-framework/bootstrap/less/mixins/grid.less'),
'grid-framework.less': await getModule('css-framework/bootstrap/less/mixins/grid-framework.less'),
'hide-text.less': await getModule('css-framework/bootstrap/less/mixins/hide-text.less'),
'image.less': await getModule('css-framework/bootstrap/less/mixins/image.less'),
'labels.less': await getModule('css-framework/bootstrap/less/mixins/labels.less'),
'list-group.less': await getModule('css-framework/bootstrap/less/mixins/list-group.less'),
'nav-divider.less': await getModule('css-framework/bootstrap/less/mixins/nav-divider.less'),
'nav-vertical-align.less': await getModule('css-framework/bootstrap/less/mixins/nav-vertical-align.less'),
'opacity.less': await getModule('css-framework/bootstrap/less/mixins/opacity.less'),
'pagination.less': await getModule('css-framework/bootstrap/less/mixins/pagination.less'),
'panels.less': await getModule('css-framework/bootstrap/less/mixins/panels.less'),
'progress-bar.less': await getModule('css-framework/bootstrap/less/mixins/progress-bar.less'),
'reset-filter.less': await getModule('css-framework/bootstrap/less/mixins/reset-filter.less'),
'reset-text.less': await getModule('css-framework/bootstrap/less/mixins/reset-text.less'),
'resize.less': await getModule('css-framework/bootstrap/less/mixins/resize.less'),
'responsive-visibility.less': await getModule('css-framework/bootstrap/less/mixins/responsive-visibility.less'),
'size.less': await getModule('css-framework/bootstrap/less/mixins/size.less'),
'tab-focus.less': await getModule('css-framework/bootstrap/less/mixins/tab-focus.less'),
'table-row.less': await getModule('css-framework/bootstrap/less/mixins/table-row.less'),
'text-emphasis.less': await getModule('css-framework/bootstrap/less/mixins/text-emphasis.less'),
'text-overflow.less': await getModule('css-framework/bootstrap/less/mixins/text-overflow.less'),
'vendor-prefixes.less': await getModule('css-framework/bootstrap/less/mixins/vendor-prefixes.less')
},
'alerts.less': await getModule('css-framework/bootstrap/less/alerts.less'),
'badges.less': await getModule('css-framework/bootstrap/less/badges.less'),
'bootstrap.less': await getModule('css-framework/bootstrap/less/bootstrap.less'),
'breadcrumbs.less': await getModule('css-framework/bootstrap/less/breadcrumbs.less'),
'button-groups.less': await getModule('css-framework/bootstrap/less/button-groups.less'),
'buttons.less': await getModule('css-framework/bootstrap/less/buttons.less'),
'carousel.less': await getModule('css-framework/bootstrap/less/carousel.less'),
'close.less': await getModule('css-framework/bootstrap/less/close.less'),
'code.less': await getModule('css-framework/bootstrap/less/code.less'),
'component-animations.less': await getModule('css-framework/bootstrap/less/component-animations.less'),
'dropdowns.less': await getModule('css-framework/bootstrap/less/dropdowns.less'),
'forms.less': await getModule('css-framework/bootstrap/less/forms.less'),
'glyphicons.less': await getModule('css-framework/bootstrap/less/glyphicons.less'),
'grid.less': await getModule('css-framework/bootstrap/less/grid.less'),
'input-groups.less': await getModule('css-framework/bootstrap/less/input-groups.less'),
'jumbotron.less': await getModule('css-framework/bootstrap/less/jumbotron.less'),
'labels.less': await getModule('css-framework/bootstrap/less/labels.less'),
'list-group.less': await getModule('css-framework/bootstrap/less/list-group.less'),
'media.less': await getModule('css-framework/bootstrap/less/media.less'),
'mixins.less': await getModule('css-framework/bootstrap/less/mixins.less'),
'modals.less': await getModule('css-framework/bootstrap/less/modals.less'),
'navbar.less': await getModule('css-framework/bootstrap/less/navbar.less'),
'navs.less': await getModule('css-framework/bootstrap/less/navs.less'),
'normalize.less': await getModule('css-framework/bootstrap/less/normalize.less'),
'pager.less': await getModule('css-framework/bootstrap/less/pager.less'),
'pagination.less': await getModule('css-framework/bootstrap/less/pagination.less'),
'panels.less': await getModule('css-framework/bootstrap/less/panels.less'),
'popovers.less': await getModule('css-framework/bootstrap/less/popovers.less'),
'print.less': await getModule('css-framework/bootstrap/less/print.less'),
'progress-bars.less': await getModule('css-framework/bootstrap/less/progress-bars.less'),
'responsive-embed.less': await getModule('css-framework/bootstrap/less/responsive-embed.less'),
'responsive-utilities.less': await getModule('css-framework/bootstrap/less/responsive-utilities.less'),
'scaffolding.less': await getModule('css-framework/bootstrap/less/scaffolding.less'),
'tables.less': await getModule('css-framework/bootstrap/less/tables.less'),
'theme.less': await getModule('css-framework/bootstrap/less/theme.less'),
'thumbnails.less': await getModule('css-framework/bootstrap/less/thumbnails.less'),
'tooltip.less': await getModule('css-framework/bootstrap/less/tooltip.less'),
'type.less': await getModule('css-framework/bootstrap/less/type.less'),
'utilities.less': await getModule('css-framework/bootstrap/less/utilities.less'),
'variables.less': await getModule('css-framework/bootstrap/less/variables.less'),
'wells.less': await getModule('css-framework/bootstrap/less/wells.less')
}
};
break;
case 'sass':
set(params.build, ['public', 'css', 'main.scss'], await getModule('css-framework/bootstrap/main.scss'));
set(params.build, ['public', 'css', 'vendor', '_bootstrap.scss'], await getModule('css-framework/bootstrap/sass/_bootstrap.scss'));
params.build.public.css.vendor.bootstrap = {
mixins: {
'_alerts.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_alerts.scss'),
'_background-variant.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_background-variant.scss'),
'_border-radius.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_border-radius.scss'),
'_buttons.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_buttons.scss'),
'_center-block.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_center-block.scss'),
'_clearfix.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_clearfix.scss'),
'_forms.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_forms.scss'),
'_gradients.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_gradients.scss'),
'_grid.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_grid.scss'),
'_grid-framework.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_grid-framework.scss'),
'_hide-text.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_hide-text.scss'),
'_image.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_image.scss'),
'_labels.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_labels.scss'),
'_list-group.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_list-group.scss'),
'_nav-divider.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_nav-divider.scss'),
'_nav-vertical-align.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_nav-vertical-align.scss'),
'_opacity.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_opacity.scss'),
'_pagination.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_pagination.scss'),
'_panels.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_panels.scss'),
'_progress-bar.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_progress-bar.scss'),
'_reset-filter.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_reset-filter.scss'),
'_reset-text.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_reset-text.scss'),
'_resize.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_resize.scss'),
'_responsive-visibility.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_responsive-visibility.scss'),
'_size.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_size.scss'),
'_tab-focus.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_tab-focus.scss'),
'_table-row.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_table-row.scss'),
'_text-emphasis.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_text-emphasis.scss'),
'_text-overflow.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_text-overflow.scss'),
'_vendor-prefixes.scss': await getModule('css-framework/bootstrap/sass/bootstrap/mixins/_vendor-prefixes.scss')
},
'_alerts.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_alerts.scss'),
'_badges.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_badges.scss'),
'_breadcrumbs.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_breadcrumbs.scss'),
'_button-groups.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_button-groups.scss'),
'_buttons.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_buttons.scss'),
'_carousel.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_carousel.scss'),
'_close.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_close.scss'),
'_code.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_code.scss'),
'_component-animations.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_component-animations.scss'),
'_dropdowns.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_dropdowns.scss'),
'_forms.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_forms.scss'),
'_glyphicons.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_glyphicons.scss'),
'_grid.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_grid.scss'),
'_input-groups.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_input-groups.scss'),
'_jumbotron.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_jumbotron.scss'),
'_labels.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_labels.scss'),
'_list-group.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_list-group.scss'),
'_media.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_media.scss'),
'_mixins.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_mixins.scss'),
'_modals.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_modals.scss'),
'_navbar.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_navbar.scss'),
'_navs.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_navs.scss'),
'_normalize.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_normalize.scss'),
'_pager.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_pager.scss'),
'_pagination.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_pagination.scss'),
'_panels.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_panels.scss'),
'_popovers.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_popovers.scss'),
'_print.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_print.scss'),
'_progress-bars.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_progress-bars.scss'),
'_responsive-embed.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_responsive-embed.scss'),
'_responsive-utilities.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_responsive-utilities.scss'),
'_scaffolding.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_scaffolding.scss'),
'_tables.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_tables.scss'),
'_theme.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_theme.scss'),
'_thumbnails.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_thumbnails.scss'),
'_tooltip.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_tooltip.scss'),
'_type.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_type.scss'),
'_utilities.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_utilities.scss'),
'_variables.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_variables.scss'),
'_wells.scss': await getModule('css-framework/bootstrap/sass/bootstrap/_wells.scss')
};
break;
default:
break;
}
if (params.cssPreprocessorOptions.includes('minifiedJs')) {
set(params.build, ['public', 'js', 'lib', 'bootstrap.min.js'], await getModule('css-framework/bootstrap/js/bootstrap.min.js'));
set(params.build, ['public', 'js', 'lib', 'jquery.min.js'], await getModule('css-framework/jquery/jquery.min.js'));
} else {
set(params.build, ['public', 'js', 'lib', 'bootstrap.js'], await getModule('css-framework/bootstrap/js/bootstrap.js'));
set(params.build, ['public', 'js', 'lib', 'jquery.js'], await getModule('css-framework/jquery/jquery.js'));
}
set(params.build, ['public', 'fonts', 'glyphicons-halflings-regular.eot'], await getModule('css-framework/bootstrap/fonts//glyphicons-halflings-regular.eot'));
set(params.build, ['public', 'fonts', 'glyphicons-halflings-regular.svg'], await getModule('css-framework/bootstrap/fonts//glyphicons-halflings-regular.svg'));
set(params.build, ['public', 'fonts', 'glyphicons-halflings-regular.ttf'], await getModule('css-framework/bootstrap/fonts//glyphicons-halflings-regular.ttf'));
set(params.build, ['public', 'fonts', 'glyphicons-halflings-regular.woff'], await getModule('css-framework/bootstrap/fonts//glyphicons-halflings-regular.woff'));
set(params.build, ['public', 'fonts', 'glyphicons-halflings-regular.woff2'], await getModule('css-framework/bootstrap/fonts//glyphicons-halflings-regular.woff2'));
const htmlJsImport = params.cssPreprocessorOptions.includes('minifiedCss') ?
await getModule('css-framework/bootstrap/html-js-min-import.html') :
await getModule('css-framework/bootstrap/html-js-import.html');
const htmlCssImport = params.cssPreprocessorOptions.includes('minifiedCss') ?
await getModule('css-framework/bootstrap/html-css-min-import.html') :
await getModule('css-framework/bootstrap/html-css-import.html');
const jadeJsImport = params.cssPreprocessorOptions.includes('minifiedCss') ?
await getModule('css-framework/bootstrap/jade-js-min-import.jade') :
await getModule('css-framework/bootstrap/jade-js-import.jade');
const jadeCssImport = params.cssPreprocessorOptions.includes('minifiedCss') ?
await getModule('css-framework/bootstrap/jade-css-min-import.jade') :
await getModule('css-framework/bootstrap/jade-css-import.jade');
if (params.jsFramework === 'angularjs') {
await replaceCodeMemory(params, 'app/index.html', 'JS_FRAMEWORK_LIB_IMPORT', htmlJsImport, { indentLevel: 1 });
if (params.cssPreprocessor === 'css') {
await replaceCodeMemory(params, 'app/index.html', 'CSS_FRAMEWORK_IMPORT', htmlCssImport, { indentLevel: 1 });
}
} else {
switch (params.templateEngine) {
case 'jade':
await replaceCodeMemory(params, 'views/layout.jade', 'JS_FRAMEWORK_LIB_IMPORT', jadeJsImport, { indentLevel: 2 });
if (params.cssPreprocessor === 'css') {
await replaceCodeMemory(params, 'views/layout.jade', 'CSS_FRAMEWORK_IMPORT', jadeCssImport, { indentLevel: 2 });
}
break;
case 'handlebars':
await replaceCodeMemory(params, 'views/layouts/main.handlebars', 'JS_FRAMEWORK_LIB_IMPORT', htmlJsImport);
if (params.cssPreprocessor === 'css') {
await replaceCodeMemory(params, 'views/layouts/main.handlebars', 'CSS_FRAMEWORK_IMPORT', htmlCssImport);
}
break;
case 'nunjucks':
await replaceCodeMemory(params, 'views/layout.html', 'JS_FRAMEWORK_LIB_IMPORT', htmlJsImport);
if (params.cssPreprocessor === 'css') {
await replaceCodeMemory(params, 'views/layout.html', 'CSS_FRAMEWORK_IMPORT', htmlCssImport);
}
break;
default:
break;
}
}
}
|
/**
* Copyright 2015 Telerik AD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["ar-JO"] = {
name: "ar-JO",
numberFormat: {
pattern: ["n-"],
decimals: 3,
",": ",",
".": ".",
groupSize: [3],
percent: {
pattern: ["-n %","n %"],
decimals: 3,
",": ",",
".": ".",
groupSize: [3],
symbol: "%"
},
currency: {
name: "Jordanian Dinar",
abbr: "JOD",
pattern: ["$n-","$ n"],
decimals: 3,
",": ",",
".": ".",
groupSize: [3],
symbol: "د.ا."
}
},
calendars: {
standard: {
days: {
names: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"],
namesAbbr: ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"],
namesShort: ["ح","ن","ث","ر","خ","ج","س"]
},
months: {
names: ["كانون الثاني","شباط","آذار","نيسان","أيار","حزيران","تموز","آب","أيلول","تشرين الأول","تشرين الثاني","كانون الأول"],
namesAbbr: ["كانون الثاني","شباط","آذار","نيسان","أيار","حزيران","تموز","آب","أيلول","تشرين الأول","تشرين الثاني","كانون الأول"]
},
AM: ["ص","ص","ص"],
PM: ["م","م","م"],
patterns: {
d: "dd/MM/yyyy",
D: "dd MMMM, yyyy",
F: "dd MMMM, yyyy hh:mm:ss tt",
g: "dd/MM/yyyy hh:mm tt",
G: "dd/MM/yyyy hh:mm:ss tt",
m: "dd MMMM",
M: "dd MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "hh:mm tt",
T: "hh:mm:ss tt",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM, yyyy",
Y: "MMMM, yyyy"
},
"/": "/",
":": ":",
firstDay: 6
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); |
// Copyright (c) Microsoft Corp. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information.
describe("Flyout control directive tests", function () {
var testTimeout = 5000;
var scope,
compile;
beforeEach(angular.mock.module("winjs"));
beforeEach(angular.mock.inject(function ($rootScope, $compile) {
scope = $rootScope.$new();
compile = $compile;
}));
function initControl(markup) {
var element = angular.element(markup)[0];
document.body.appendChild(element);
var compiledControl = compile(element)(scope)[0];
scope.$digest();
return compiledControl;
}
it("should initialize a simple Flyout control", function () {
var compiledControl = initControl("<win-flyout></win-flyout>");
expect(compiledControl.winControl).toBeDefined();
expect(compiledControl.winControl instanceof WinJS.UI.Flyout);
expect(compiledControl.className).toContain("win-flyout");
});
it("should use the alignment attribute", function () {
var compiledControl = initControl("<win-flyout alignment=\"'left'\"></win-flyout>");
expect(compiledControl.winControl.alignment).toEqual("left");
});
it("should use the placement attribute", function () {
var compiledControl = initControl("<win-flyout placement=\"'right'\"></win-flyout>");
expect(compiledControl.winControl.placement).toEqual("right");
});
it("should use the anchor attribute", function () {
var anchorEl = document.createElement("div");
anchorEl.className = "flyoutTestAnchorElement";
document.body.appendChild(anchorEl);
scope.flyoutAnchor = anchorEl;
var compiledControl = initControl("<win-flyout anchor='flyoutAnchor'></win-flyout>");
expect(compiledControl.winControl.anchor).toBe(anchorEl);
});
it("should use the onshow and onhide event handlers", function () {
var gotBeforeShowEvent = false,
gotAfterShowEvent = false,
gotBeforeHideEvent = false,
gotAfterHideEvent = false;
scope.beforeShowEventHandler = function (e) {
gotBeforeShowEvent = true;
};
scope.afterShowEventHandler = function (e) {
gotAfterShowEvent = true;
};
scope.beforeHideEventHandler = function (e) {
gotBeforeHideEvent = true;
};
scope.afterHideEventHandler = function (e) {
gotAfterHideEvent = true;
};
var compiledControl = initControl("<win-flyout on-before-show='beforeShowEventHandler($event)' on-after-show='afterShowEventHandler($event)' " +
"on-before-hide='beforeHideEventHandler($event)' on-after-hide='afterHideEventHandler($event)'></win-flyout>");
runs(function () {
compiledControl.winControl.show(document.body);
});
waitsFor(function () {
return (gotBeforeShowEvent && gotAfterShowEvent);
}, "the Flyout's before+aftershow events", testTimeout);
runs(function () {
compiledControl.winControl.hide();
});
waitsFor(function () {
return (gotBeforeHideEvent && gotAfterHideEvent);
}, "the Flyout's before+afterhide events", testTimeout);
});
afterEach(function () {
var controls = document.querySelectorAll(".win-flyout");
for (var i = 0; i < controls.length; i++) {
controls[i].parentNode.removeChild(controls[i]);
}
var anchors = document.querySelectorAll(".flyoutTestAnchorElement");
for (var i = 0; i < anchors.length; i++) {
anchors[i].parentNode.removeChild(anchors[i]);
}
});
});
|
const webpack = require('webpack')
const chokidar = require('chokidar')
const fs = require('fs')
const debounce = require('lodash.debounce')
const { log, warn, fatal } = require('../helpers/logger')
const { spawn } = require('../helpers/spawn')
const appPaths = require('../app-paths')
const nodePackager = require('../helpers/node-packager')
const getPackageJson = require('../helpers/get-package-json')
const getPackage = require('../helpers/get-package')
class ElectronRunner {
constructor () {
this.pid = 0
this.watcher = null
}
init () {}
async run (quasarConfFile, argv) {
const url = quasarConfFile.quasarConf.build.APP_URL
if (this.pid) {
if (this.url !== url) {
await this.stop()
}
else {
return
}
}
this.url = url
const compiler = webpack(quasarConfFile.webpackConf.main)
return new Promise(resolve => {
log(`Building main Electron process...`)
this.watcher = compiler.watch({}, async (err, stats) => {
if (err) {
console.log(err)
return
}
log(`Webpack built Electron main process`)
log()
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n')
log()
if (stats.hasErrors()) {
warn(`Electron main build failed with errors`)
return
}
await this.__stopElectron()
this.__startElectron(argv._)
resolve()
})
const preloadFile = appPaths.resolve.electron('main-process/electron-preload.js')
if (fs.existsSync(preloadFile)) {
// Start watching for electron-preload.js changes
this.preloadWatcher = chokidar
.watch(preloadFile, { watchers: { chokidar: { ignoreInitial: true } } })
this.preloadWatcher.on('change', debounce(async () => {
console.log()
log(`electron-preload.js changed`)
await this.__stopElectron()
this.__startElectron(argv._)
resolve()
}, 1000))
}
})
}
build (quasarConfFile) {
const cfg = quasarConfFile.quasarConf
return new Promise(resolve => {
spawn(
nodePackager,
[ 'install', '--production' ].concat(cfg.electron.unPackagedInstallParams),
{ cwd: cfg.build.distDir },
code => {
if (code) {
fatal(`[FAIL] ${nodePackager} failed installing dependencies`)
}
resolve()
}
)
}).then(() => {
return new Promise(async resolve => {
if (typeof cfg.electron.beforePackaging === 'function') {
log('Running beforePackaging()')
log()
const result = cfg.electron.beforePackaging({
appPaths,
unpackagedDir: cfg.build.distDir
})
if (result && result.then) {
await result
}
log()
log('[SUCCESS] Done running beforePackaging()')
}
resolve()
})
}).then(() => {
const bundlerName = cfg.electron.bundler
const bundlerConfig = cfg.electron[bundlerName]
const bundler = require('./bundler').getBundler(bundlerName)
const pkgName = `electron-${bundlerName}`
return new Promise((resolve, reject) => {
log(`Bundling app with electron-${bundlerName}...`)
log()
const bundlePromise = bundlerName === 'packager'
? bundler({
...bundlerConfig,
electronVersion: getPackageJson('electron').version
})
: bundler.build(bundlerConfig)
bundlePromise
.then(() => {
log()
log(`[SUCCESS] ${pkgName} built the app`)
log()
resolve()
})
.catch(err => {
log()
warn(`[FAIL] ${pkgName} could not build`)
log()
console.error(err + '\n')
reject()
})
})
})
}
stop () {
return new Promise(resolve => {
let counter = 0
const maxCounter = (this.watcher ? 1 : 0) + (this.preloadWatcher ? 1 : 0)
const finalize = () => {
counter++
if (maxCounter <= counter) {
this.__stopElectron().then(resolve)
}
}
if (this.watcher) {
this.watcher.close(finalize)
this.watcher = null
}
if (this.preloadWatcher) {
this.preloadWatcher.close().then(finalize)
this.preloadWatcher = null
}
if (maxCounter === 0) {
finalize()
}
})
}
__startElectron (extraParams) {
log(`Booting up Electron process...`)
this.pid = spawn(
getPackage('electron'),
[
'--inspect=5858',
appPaths.resolve.app('.quasar/electron/electron-main.js')
].concat(extraParams),
{ cwd: appPaths.appDir },
code => {
if (this.killPromise) {
this.killPromise()
this.killPromise = null
}
else if (code) {
warn()
fatal(`Electron process ended with error code: ${code}\n`)
}
else { // else it wasn't killed by us
warn()
fatal('Electron process was killed. Exiting...\n')
}
}
)
}
__stopElectron () {
const pid = this.pid
if (!pid) {
return Promise.resolve()
}
log('Shutting down Electron process...')
this.pid = 0
return new Promise(resolve => {
this.killPromise = resolve
process.kill(pid)
})
}
}
module.exports = new ElectronRunner()
|
consoleApp.directive('consoletab', function() {
return {
restrict: 'E',
scope: {
object: '=',
kill: '&',
remove: '&',
select: '&',
selected: '=',
mode: '=',
minimize: '&'
},
templateUrl: MoufInstanceManager.rootUrl+"src-dev/views/javascript/console-tab-directive.html",
link: function($scope, element, attrs) {
}
};
});
|
import galaxy from "lib/apis/galaxy"
describe("APIs", () => {
describe("galaxy", () => {
const fetch = galaxy.__get__("fetch")
afterEach(() => {
fetch.__ResetDependency__("request")
})
it("makes a correct request to galaxy", () => {
const request = sinon.stub().yields(null, { statusCode: 200, body: {} })
fetch.__Rewire__("request", request)
return galaxy("foo/bar").then(() => {
expect(request.args[0][0]).toBe("https://galaxy-staging-herokuapp.com/foo/bar")
expect(request.args[0][1]).toEqual({
headers: {
Accept: "application/vnd.galaxy-public+json",
"Content-Type": "application/hal+json",
"Http-Authorization": "galaxy_token",
},
method: "GET",
timeout: 5000,
})
})
})
it("resolves when there is a successful JSON response", () => {
const request = sinon.stub().yields(null, { statusCode: 200, body: { foo: "bar" } })
fetch.__Rewire__("request", request)
return galaxy("foo/bar").then(({ body: { foo } }) => {
expect(foo).toBe("bar")
})
})
it("tries to parse the response when there is a String and resolves with it", () => {
const request = sinon.stub().yields(null, {
statusCode: 200,
body: JSON.stringify({ foo: "bar" }),
})
fetch.__Rewire__("request", request)
return galaxy("foo/bar").then(({ body: { foo } }) => {
expect(foo).toBe("bar")
})
})
it("rejects request errors", () => {
const request = sinon.stub().yields(new Error("bad"))
fetch.__Rewire__("request", request)
return expectPromiseRejectionToMatch(galaxy("foo/bar"), /bad/)
})
it("rejects API errors", () => {
const request = sinon.stub().yields(null, { statusCode: 400, body: "Unauthorized" })
fetch.__Rewire__("request", request)
return expectPromiseRejectionToMatch(galaxy("foo/bar"), "Unauthorized")
})
it("rejects parse errors", () => {
const request = sinon.stub().yields(null, { statusCode: 200, body: "not json" })
fetch.__Rewire__("request", request)
return expectPromiseRejectionToMatch(galaxy("foo/bar"), /Unexpected token/)
})
})
})
|
import 'babel-polyfill';
import assert from 'assert';
const trueGetter = { getTrue() { return true; } };
describe('client', () => {
describe('true-getter', () => {
describe('get-true', () => {
it('returns true value', () => {
assert.equal(true, trueGetter.getTrue());
});
});
});
}); |
var Table = require('cli-table');
module.exports = function(users) {
var table = new Table({
head: [
'userId', 'Full Names', 'username', 'Role','email', 'password'
],
chars: {
'top': '═',
'top-mid': '╤',
'top-left': '╔',
'top-right': '╗',
'bottom': '═',
'bottom-mid': '╧',
'bottom-left': '╚',
'bottom-right': '╝',
'left': '║',
'left-mid': '╟',
'mid': '─',
'mid-mid': '┼',
'right': '║',
'right-mid': '╢',
'middle': '│'
},
style: {
'padding-left': 0,
'padding-right': 0
},
colWidths: [30, 50, 30,10, 50, 70]
});
if (users._id === undefined) {
for (var key in users) {
var user = users[key];
table.push(
[
user._id,
user.name.first + " " + user.name.last,
user.username,
user.role,
user.email,
user.password
]
);
}
} else {
table.push([
users._id,
users.name.first + " " + users.name.last,
users.username,
users.role,
users.email,
users.password
]);
}
console.log(table.toString());
};
|
(function(window) {
"use strict"
window.webgazer = window.webgazer || {};
webgazer.tracker = webgazer.tracker || {};
webgazer.util = webgazer.util || {};
webgazer.params = webgazer.params || {};
/**
* Initialize clmtrackr object
*/
var ClmGaze = function() {
this.clm = new clm.tracker(webgazer.params.camConstraints);
this.clm.init(pModel);
var F = [ [1, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 1],
[0, 0, 1, 0, 1, 0],
[0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1]];
//Parameters Q and R may require some fine tuning
var Q = [ [1/4, 0, 0, 0, 1/2, 0],
[0, 1/4, 0, 0, 0, 1/2],
[0, 0, 1/4, 0, 1/2, 0],
[0, 0, 0, 1/4, 0, 1/2],
[1/2, 0, 1/2, 0, 1, 0],
[0, 1/2, 0, 1/2, 0, 1]];// * delta_t
var delta_t = 1/10; // The amount of time between frames
Q = numeric.mul(Q, delta_t);
var H = [ [1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0]];
var pixel_error = 6.5; //We will need to fine tune this value
//This matrix represents the expected measurement error
var R = numeric.mul(numeric.identity(4), pixel_error);
var P_initial = numeric.mul(numeric.identity(6), 0.0001); //Initial covariance matrix
var x_initial = [[200], [150], [250], [180], [0], [0]]; // Initial measurement matrix
this.leftKalman = new self.webgazer.util.KalmanFilter(F, H, Q, R, P_initial, x_initial);
this.rightKalman = new self.webgazer.util.KalmanFilter(F, H, Q, R, P_initial, x_initial);
};
webgazer.tracker.ClmGaze = ClmGaze;
/**
* Isolates the two patches that correspond to the user's eyes
* @param {Canvas} imageCanvas - canvas corresponding to the webcam stream
* @param {number} width - of imageCanvas
* @param {number} height - of imageCanvas
* @return {Object} the two eye-patches, first left, then right eye
*/
ClmGaze.prototype.getEyePatches = function(imageCanvas, width, height) {
if (imageCanvas.width === 0) {
return null;
}
var positions = this.clm.track(imageCanvas);
var score = this.clm.getScore();
if (!positions) {
return false;
}
//Fit the detected eye in a rectangle
var leftOriginX = (positions[23][0]);
var leftOriginY = (positions[24][1]);
var leftWidth = (positions[25][0] - positions[23][0]);
var leftHeight = (positions[26][1] - positions[24][1]);
var rightOriginX = (positions[30][0]);
var rightOriginY = (positions[29][1]);
var rightWidth = (positions[28][0] - positions[30][0]);
var rightHeight = (positions[31][1] - positions[29][1]);
//Apply Kalman Filtering
var leftBox = [leftOriginX, leftOriginY, leftOriginX + leftWidth, leftOriginY + leftHeight];
leftBox = this.leftKalman.update(leftBox);
leftOriginX = Math.round(leftBox[0]);
leftOriginY = Math.round(leftBox[1]);
leftWidth = Math.round(leftBox[2] - leftBox[0]);
leftHeight = Math.round(leftBox[3] - leftBox[1]);
//Apply Kalman Filtering
var rightBox = [rightOriginX, rightOriginY, rightOriginX + rightWidth, rightOriginY + rightHeight];
rightBox = this.rightKalman.update(rightBox);
rightOriginX = Math.round(rightBox[0]);
rightOriginY = Math.round(rightBox[1]);
rightWidth = Math.round(rightBox[2] - rightBox[0]);
rightHeight = Math.round(rightBox[3] - rightBox[1]);
if (leftWidth === 0 || rightWidth === 0){
console.log('an eye patch had zero width');
return null;
}
if (leftHeight === 0 || rightHeight === 0){
console.log("an eye patch had zero height");
return null;
}
var eyeObjs = {};
var leftImageData = imageCanvas.getContext('2d').getImageData(leftOriginX, leftOriginY, leftWidth, leftHeight);
eyeObjs.left = {
patch: leftImageData,
imagex: leftOriginX,
imagey: leftOriginY,
width: leftWidth,
height: leftHeight
};
var rightImageData = imageCanvas.getContext('2d').getImageData(rightOriginX, rightOriginY, rightWidth, rightHeight);
eyeObjs.right = {
patch: rightImageData,
imagex: rightOriginX,
imagey: rightOriginY,
width: rightWidth,
height: rightHeight
};
eyeObjs.positions = positions;
return eyeObjs;
};
ClmGaze.prototype.name = 'clmtrackr';
}(window));
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let VideoCall = props =>
<SvgIcon {...props}>
<path d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4zM14 13h-3v3H9v-3H6v-2h3V8h2v3h3v2z" />
</SvgIcon>;
VideoCall = pure(VideoCall);
VideoCall.muiName = 'SvgIcon';
export default VideoCall;
|
var log = require('../util/log');
var reddcoreDefaults = require('../config');
var Connection = require('./Connection');
var Peer = require('./Peer');
var async = require('async');
var dns = require('dns');
var networks = require('../networks');
var util = require('util');
GetAdjustedTime = function() {
// TODO: Implement actual adjustment
return Math.floor(new Date().getTime() / 1000);
};
function PeerManager(config) {
// extend defaults with config
this.config = config || {};
for (var i in reddcoreDefaults)
if (reddcoreDefaults.hasOwnProperty(i) && this.config[i] === undefined)
this.config[i] = reddcoreDefaults[i];
this.active = false;
this.timer = null;
this.peers = [];
this.pool = [];
this.connections = [];
this.isConnected = false;
this.peerDiscovery = false;
// Move these to the Node's settings object
this.interval = 5000;
this.minConnections = 8;
this.minKnownPeers = 10;
// keep track of tried seeds and results
this.seeds = {
resolved: [],
failed: []
};
}
var EventEmitter = require('events').EventEmitter;
util.inherits(PeerManager, EventEmitter);
PeerManager.Connection = Connection;
PeerManager.prototype.start = function() {
this.active = true;
if (!this.timer) {
this.timer = setInterval(this.checkStatus.bind(this), this.interval);
}
};
PeerManager.prototype.stop = function() {
this.active = false;
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
for (var i = 0; i < this.connections.length; i++) {
this.connections[i].socket.end();
};
};
PeerManager.prototype.addPeer = function(peer, port) {
if (peer instanceof Peer) {
this.peers.push(peer);
} else if ("string" == typeof peer) {
this.addPeer(new Peer(peer, port));
} else {
log.err('Node.addPeer(): Invalid value provided for peer', {
val: peer
});
throw 'Node.addPeer(): Invalid value provided for peer.';
}
};
PeerManager.prototype.removePeer = function(peer) {
var index = this.peers.indexOf(peer);
var exists = !!~index;
if (exists) this.peers.splice(index, 1);
return exists;
};
PeerManager.prototype.checkStatus = function checkStatus() {
// Make sure we are connected to all forcePeers
if (this.peers.length) {
var peerIndex = {};
this.peers.forEach(function(peer) {
peerIndex[peer.toString()] = peer;
});
// Ignore the ones we're already connected to
this.connections.forEach(function(conn) {
var peerName = conn.peer.toString();
if ("undefined" !== peerIndex[peerName]) {
delete peerIndex[peerName];
}
});
// for debug purposes, print how many of our peers are actually connected
var connected = 0
this.peers.forEach(function(p) {
if (p.connection && !p.connection._connecting) connected++
});
log.debug(connected + ' of ' + this.peers.length + ' peers connected');
Object.keys(peerIndex).forEach(function(i) {
this.connectTo(peerIndex[i]);
}.bind(this));
}
};
PeerManager.prototype.connectTo = function(peer) {
log.info('connecting to ' + peer);
try {
return this.addConnection(peer.createConnection(), peer);
} catch (e) {
log.err('creating connection', e);
return null;
}
};
PeerManager.prototype.addConnection = function(socketConn, peer) {
var conn = new Connection(socketConn, peer, this.config);
this.connections.push(conn);
this.emit('connection', conn);
conn.addListener('version', this.handleVersion.bind(this));
conn.addListener('verack', this.handleReady.bind(this));
conn.addListener('addr', this.handleAddr.bind(this));
conn.addListener('getaddr', this.handleGetAddr.bind(this));
conn.addListener('error', this.handleError.bind(this));
conn.addListener('disconnect', this.handleDisconnect.bind(this));
return conn;
};
PeerManager.prototype.handleVersion = function(e) {
e.peer.version = e.message.version;
e.peer.start_height = e.message.start_height;
if (!e.conn.inbound) {
// TODO: Advertise our address (if listening)
}
// Get recent addresses
if (this.peerDiscovery &&
(e.message.version >= 31402 || this.peers.length < 1000)) {
e.conn.sendGetAddr();
e.conn.getaddr = true;
}
};
PeerManager.prototype.handleReady = function(e) {
log.info('connected to ' + e.conn.peer.host + ':' + e.conn.peer.port);
this.emit('connect', {
pm: this,
conn: e.conn,
socket: e.socket,
peer: e.peer
});
if (this.isConnected == false) {
this.emit('netConnected', e);
this.isConnected = true;
}
};
PeerManager.prototype.handleAddr = function(e) {
if (!this.peerDiscovery) return;
var now = GetAdjustedTime();
e.message.addrs.forEach(function(addr) {
try {
// In case of an invalid time, assume "5 days ago"
if (addr.time <= 100000000 || addr.time > (now + 10 * 60)) {
addr.time = now - 5 * 24 * 60 * 60;
}
var peer = new Peer(addr.ip, addr.port, addr.services);
peer.lastSeen = addr.time;
// TODO: Handle duplicate peers
this.peers.push(peer);
// TODO: Handle addr relay
} catch (e) {
log.warn("Invalid addr received: " + e.message);
}
}.bind(this));
if (e.message.addrs.length < 1000) {
e.conn.getaddr = false;
}
};
PeerManager.prototype.handleGetAddr = function(e) {
// TODO: Reply with addr message.
};
PeerManager.prototype.handleError = function(e) {
log.err('unkown error with peer ' + e.peer + ' (disconnecting): ' + e.err);
this.handleDisconnect.apply(this, [].slice.call(arguments));
};
PeerManager.prototype.handleDisconnect = function(e) {
log.info('disconnected from peer ' + e.peer);
var i = this.connections.indexOf(e.conn);
if (i != -1) this.connections.splice(i, 1);
this.removePeer(e.peer);
if (this.pool.length) {
log.info('replacing peer using the pool of ' + this.pool.length + ' seeds');
this.addPeer(this.pool.pop());
}
if (!this.connections.length) {
this.emit('netDisconnected');
this.isConnected = false;
}
};
PeerManager.prototype.getActiveConnection = function() {
var activeConnections = this.connections.filter(function(conn) {
return conn.active;
});
if (activeConnections.length) {
var randomIndex = Math.floor(Math.random() * activeConnections.length);
var candidate = activeConnections[randomIndex];
if (candidate.socket.writable) {
return candidate;
} else {
// Socket is not writable, remove it from active connections
activeConnections.splice(randomIndex, 1);
// Then try again
// TODO: This causes an infinite recursion when all connections are dead,
// although it shouldn't.
return this.getActiveConnection();
}
} else {
return null;
}
};
PeerManager.prototype.getActiveConnections = function() {
return this.connections.slice(0);
};
PeerManager.prototype.discover = function(options, callback) {
var self = this;
var seeds = networks[self.config.network].dnsSeeds;
self.limit = options.limit || 12;
var dnsExecutor = seeds.map(function(seed) {
return function(done) {
// have we already resolved this seed?
if (~self.seeds.resolved.indexOf(seed)) {
// if so, just pass back cached peer list
return done(null, self.seeds.results[seed]);
}
// has this seed failed to resolve?
if (~self.seeds.failed.indexOf(seed)) {
// if so, pass back empty results
return done(null, []);
}
log.info('resolving dns seed ' + seed);
dns.resolve(seed, function(err, peers) {
if (err) {
log.err('failed to resolve dns seed ' + seed, err);
self.seeds.failed.push(seed);
return done(null, []);
}
log.info('found ' + peers.length + ' peers from ' + seed);
self.seeds.resolved.push(seed);
// transform that list into a list of Peer instances
peers = peers.map(function(ip) {
return new Peer(ip, networks[self.config.network].defaultClientPort);
});
peers.forEach(function(p) {
if (self.peers.length < self.limit) self.addPeer(p);
else self.pool.push(p);
});
self.emit('peers', peers);
return done(null, peers);
});
};
});
// try resolving all seeds
async.parallel(dnsExecutor, function(err, results) {
var peers = [];
// consolidate all resolved peers into one list
results.forEach(function(peerlist) {
peers = peers.concat(peerlist);
});
if (typeof callback === 'function') callback(null, peers);
});
return self;
};
module.exports = PeerManager;
|
/**
* @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'a11yhelp', 'uk', {
title: 'Спеціальні Інструкції',
contents: 'Довідка. Натисніть ESC і вона зникне.',
legend: [
{
name: 'Основне',
items: [
{
name: 'Панель Редактора',
legend: 'Press ${toolbarFocus} to navigate to the toolbar. Move to the next and previous toolbar group with TAB and SHIFT-TAB. Move to the next and previous toolbar button with RIGHT ARROW or LEFT ARROW. Press SPACE or ENTER to activate the toolbar button.' // MISSING
},
{
name: 'Діалог Редактора',
legend: 'Inside a dialog, press TAB to navigate to next dialog field, press SHIFT + TAB to move to previous field, press ENTER to submit dialog, press ESC to cancel dialog. For dialogs that have multiple tab pages, press ALT + F10 to navigate to tab-list. Then move to next tab with TAB OR RIGTH ARROW. Move to previous tab with SHIFT + TAB or LEFT ARROW. Press SPACE or ENTER to select the tab page.' // MISSING
},
{
name: 'Контекстне Меню Редактора',
legend: 'Press ${contextMenu} or APPLICATION KEY to open context-menu. Then move to next menu option with TAB or DOWN ARROW. Move to previous option with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the menu option. Open sub-menu of current option with SPACE or ENTER or RIGHT ARROW. Go back to parent menu item with ESC or LEFT ARROW. Close context menu with ESC.' // MISSING
},
{
name: 'Скринька Списків Редактора',
legend: 'Inside a list-box, move to next list item with TAB OR DOWN ARROW. Move to previous list item with SHIFT + TAB or UP ARROW. Press SPACE or ENTER to select the list option. Press ESC to close the list-box.' // MISSING
},
{
name: 'Editor Element Path Bar', // MISSING
legend: 'Press ${elementsPathFocus} to navigate to the elements path bar. Move to next element button with TAB or RIGHT ARROW. Move to previous button with SHIFT+TAB or LEFT ARROW. Press SPACE or ENTER to select the element in editor.' // MISSING
}
]
},
{
name: 'Команди',
items: [
{
name: 'Відмінити команду',
legend: 'Press ${undo}' // MISSING
},
{
name: ' Redo command', // MISSING
legend: 'Press ${redo}' // MISSING
},
{
name: ' Bold command', // MISSING
legend: 'Press ${bold}' // MISSING
},
{
name: ' Italic command', // MISSING
legend: 'Press ${italic}' // MISSING
},
{
name: ' Underline command', // MISSING
legend: 'Press ${underline}' // MISSING
},
{
name: ' Link command', // MISSING
legend: 'Press ${link}' // MISSING
},
{
name: ' Toolbar Collapse command', // MISSING
legend: 'Press ${toolbarCollapse}' // MISSING
},
{
name: ' Access previous focus space command', // MISSING
legend: 'Press ${accessPreviousSpace} to access the closest unreachable focus space before the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces.' // MISSING
},
{
name: ' Access next focus space command', // MISSING
legend: 'Press ${accessNextSpace} to access the closest unreachable focus space after the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces.' // MISSING
},
{
name: ' Accessibility Help', // MISSING
legend: 'Press ${a11yHelp}' // MISSING
}
]
}
]
});
|
app.collections.languages=Backbone.Collection.extend({initialize:function(){console.log("initializing languages collection")},model:app.models.language,localStorage:new Backbone.LocalStorage("languages")}) |
define(function(require) {
var angular = require('angular');
var uiRouter = angular.module('ui.router');
require('angular-ui-router');
var RequireProvider = require('ngRequire/RequireProvider');
return angular.module('ngRequire', [
uiRouter.name
]).provider('$require', RequireProvider).config(function(
$stateProvider,
$controllerProvider,
$compileProvider,
$provide,
$requireProvider) {
$requireProvider.$stateProvider = $stateProvider;
$requireProvider.$controllerProvider = $controllerProvider;
$requireProvider.$compileProvider = $compileProvider;
$requireProvider.$provide = $provide;
}).config(function($urlRouterProvider) {
$urlRouterProvider.when('', '/');
});
});
|
/** @jsx React.DOM */
"use strict";
var TestUtils = require('react/addons').addons.TestUtils;
jest.dontMock('../DefaultContent');
var DefaultContent = require('../DefaultContent');
describe("#render", function() {
var comp;
var fakeCreateText = jasmine.createSpy("fakeCreateText");
var fakeCreateTodo = jasmine.createSpy("fakeCreateTodo");
function fakeNewItem(type) {
return type === "text" ? fakeCreateText : fakeCreateTodo;
}
beforeEach(function() {
comp = TestUtils.renderIntoDocument(<DefaultContent newItem={fakeNewItem} />);
});
it("should render HTML content", function() {
expect(comp.getDOMNode().outerHTML.length > 0).toBe(true);
});
it("should add a new text entry when clicking on Text link", function() {
var newTextLink = TestUtils.findRenderedDOMComponentWithClass(comp, "new-text");
TestUtils.Simulate.click(newTextLink);
expect(fakeCreateText).toHaveBeenCalled();
});
it("should add a new todo entry when clicking on Todo link", function() {
var newTodoLink = TestUtils.findRenderedDOMComponentWithClass(comp, "new-todo");
TestUtils.Simulate.click(newTodoLink);
expect(fakeCreateTodo).toHaveBeenCalled();
});
});
|
import { x } from "./dep?f";
export default class def {
method() {
return x;
}
}
new def().method();
|
(function () {
'use strict';
angular
.module('app.dashboard')
.controller('Dashboard', Dashboard);
function Dashboard($state, dataservice, logger) {
var vm = this;
vm.customers = [];
vm.gotoCustomer = gotoCustomer;
vm.title = 'Dashboard';
activate();
function activate() {
return getCustomers().then(function () {
logger.info('Activated Dashboard View');
});
}
function getCustomers() {
return dataservice.getCustomers().then(function (data) {
vm.customers = data;
return vm.customers;
});
}
function gotoCustomer(c) {
$state.go('customer.detail', {id: c.id});
}
}
})();
|
{
"name": "validify.js",
"url": "https://github.com/arimus/validify.js.git"
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var MdFileUpload = function MdFileUpload(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'm8.4 30h23.2v3.4h-23.2v-3.4z m6.6-3.4v-10h-6.6l11.6-11.6 11.6 11.6h-6.6v10h-10z' })
)
);
};
exports.default = MdFileUpload;
module.exports = exports['default']; |
/**
* Generate a script template to test each function of a script.
*
* @param {String} api_name The ServiceNow api_name of the script include.
* @return {String}
*/
function snd_Spoke_generateTest(api_name) {
function getSource(api_name) {
var gr = new GlideRecord('sys_script_include');
gr.addQuery('api_name', '=', api_name);
gr.setLimit(1);
gr.query();
return gr.next() ? '' + gr.script : '';
}
function getMethods(obj) {
var methods = [];
for (var method in obj) {
if (obj.hasOwnProperty(method) && typeof obj[method] == 'function') {
methods.push(method);
}
}
methods.sort();
return methods;
}
function describe(name, indent, content) {
content = content ? ' ' + content.replace(/\n/g, '\n ' + indent) + '\n' : ' \n';
return indent + 'describe("' + name + '", function () {\n' +
indent + content +
indent + '});';
}
function toSentence(method, no_cap) {
var newSentence = true;
return method.replace(/[A-Z]{2,}|^[a-z]|[A-Z._]/g, function(v, i) {
if (v.length > 1) return v;
if (newSentence) {
newSentence = false;
return (i === 0 && no_cap) ? v : v.toUpperCase();
}
if (v === '.') {
newSentence = true;
return ' ';
}
return " " + (v === '_' ? '' : v.toLowerCase());
});
}
function getObject(api_name) {
var obj = (function () { return this;})(),
path = api_name.split('.'),
i;
for (i = 0; i < path.length; i++) {
obj = obj[path[i]];
}
return obj;
}
function explain(source, method, is_proto) {
var end = 0,
search = (is_proto ? 'prototype.' : '') + method,
alt_end,
result,
match,
start;
do {
result = '';
start = source.indexOf(search, end);
if (start < 0) break;
end = source.indexOf('{', start);
alt_end = source.indexOf(';', start);
if (alt_end > 0 && alt_end < end) {
end = alt_end;
}
if (end < 0) break;
result = source.substr(start, end - start).trim();
} while (result.indexOf('function') < 0);
if (!result) {
match = source.match(new SNRegExp('(?!prototype\\s*=\\s*{.+?)' + method + ':\\s*[^)]+\\)'));
if (match) result = match[0];
}
return result || (search + ' function not defined in source code');
}
var source = getSource(api_name),
obj = getObject(api_name),
content = '\n',
comment,
methods,
is_private,
type,
i;
if (typeof obj === 'function') {
type = obj.prototype.type || api_name;
type += obj.prototype.type ? ' class' : ' object';
methods = getMethods(obj.prototype);
for (i = 0; i < methods.length; i++) {
is_private = methods[i].indexOf('_') == 0 ? ' private' : '';
comment = '// test ' + explain(source, methods[i], true);
content += describe(toSentence(methods[i] + is_private + ' method', true), '', comment) + '\n\n';
}
} else {
type = api_name + ' object';
}
if (type.indexOf('x_') === 0) {
type = type.substr(type.indexOf('.'));
}
methods = getMethods(obj);
for (i = 0; i < methods.length; i++) {
is_private = methods[i].indexOf('_') == 0 ? ' private' : '';
comment = '// test ' + explain(source, methods[i]);
content += describe(toSentence(methods[i] + is_private + ' function', true), '', comment) + '\n';
if (i + 1 < methods.length) content += '\n'; // prevent double newline at end
}
if (type.match('^[a-z]')) type = ' ' + type;
return describe(toSentence('The' + type), '', content);
} |
var PlaceHolderConfigurer = require('../../../lib/beans/support/placeHolderConfigurer');
describe('PlaceHolderConfigurer', function() {
describe('placeHolderConfigurer', function() {
it('should advice right', function(done) {
var placeHolderConfigurer = new PlaceHolderConfigurer();
placeHolderConfigurer.setBeanName('car');
placeHolderConfigurer.getBeanName('car');
placeHolderConfigurer.setProperties();
done();
});
});
}); |
/**
@class Utility for creating primitive geometries at runtime.
*/
J3D.Primitive = {};
/**
* Create a primitive cube
* @param w width of the cube
* @param h height of the cube
* @param d depth of the cube
* @param sixway A sizway texture is a texture where the faces are laid our in a 3x2 pattern in order from top-left to bottom-right. TODO: Add exact list of faces.
*/
J3D.Primitive.Cube = function(w, h, d, sixway) {
var c = J3D.Primitive.getEmpty();
w = w * 0.5;
h = h * 0.5;
d = d * 0.5;
var buv = [0, 1, 0, 1];
var uv = [];
uv[0] = (sixway) ? [0, 0.5, 0, 1/3] : buv;
uv[1] = (sixway) ? [0.5, 1, 0, 1/3] : buv;
uv[2] = (sixway) ? [0, 0.5, 1/3, 2/3] : buv;
uv[3] = (sixway) ? [0.5, 1, 1/3, 2/3] : buv;
uv[4] = (sixway) ? [0, 0.5, 2/3, 1] : buv;
uv[5] = (sixway) ? [0.5, 1, 2/3, 1] : buv;
J3D.Primitive.addQuad(c,
new v3(-w, h, d),
new v3(w, h, d),
new v3(w, -h, d),
new v3(-w, -h, d),
uv[0]
);
J3D.Primitive.addQuad(c,
new v3(w, h, -d),
new v3(-w, h, -d),
new v3(-w, -h, -d),
new v3(w, -h, -d),
uv[1]
);
J3D.Primitive.addQuad(c,
new v3(-w, h, -d),
new v3(-w, h, d),
new v3(-w, -h, d),
new v3(-w, -h, -d),
uv[2]
);
J3D.Primitive.addQuad(c,
new v3(w, h, d),
new v3(w, h, -d),
new v3(w, -h, -d),
new v3(w, -h, d),
uv[3]
);
J3D.Primitive.addQuad(c,
new v3(w, h, d),
new v3(-w, h, d),
new v3(-w, h, -d),
new v3(w, h, -d),
uv[4]
);
J3D.Primitive.addQuad(c,
new v3(w, -h, d),
new v3(w, -h, -d),
new v3(-w, -h, -d),
new v3(-w, -h, d),
uv[5]
);
return new J3D.Mesh(c);
}
/**
* Create a full screen quad. Used mostly for post effects.
*/
J3D.Primitive.FullScreenQuad = function() {
var c = new J3D.Geometry();
c.addArray("aVertexPosition", new Float32Array([-1, 1, 1, 1, 1, -1, -1, 1, 1, -1, -1, -1]), 2);
c.addArray("aTextureCoord", new Float32Array([0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0]), 2);
return c;
}
/**
* Creates a primitive plane
* @param w width of the plane
* @param h height of the plane
* @param wd number of vertical segments
* @param hd number of horizontal segments
* @param wo horizontal offset (i.e. how much to move the anchor on x)
* @param ho vertical offset (i.e. how much to move the anchor on y)
* @param uv object with uv coordinates us = u start, ue = u end, vs = v start, ve = v end
*/
J3D.Primitive.Plane = function(w, h, wd, hd, wo, ho, uv) {
var c = J3D.Primitive.getEmpty();
if(!wo) wo = 0;
if(!ho) ho = 0;
w = w * 0.5;
h = h * 0.5;
if(!wd) wd = 1;
if(!hd) hd = 1;
var wStart = -w + wo;
var wEnd = w + wo;
var hStart = h + ho;
var hEnd = -h + ho;
var uStart = (uv && uv.us) ? uv.us : 0;
var uEnd = (uv && uv.ue) ? uv.ue : 1;
var vStart = (uv && uv.vs) ? uv.vs : 0;
var vEnd = (uv && uv.ve) ? uv.ve : 1;
var wb = (w * 2) / wd;
var hb = (h * 2) / hd;
for(var i = 0; i < wd; i++) {
for(var j = 0; j < hd; j++) {
var bvStart = wStart + i * wb;
var bvEnd = bvStart + wb;
var bhStart = hStart - j * hb;
var bhEnd = bhStart - hb;
var va = new v3(bvStart, bhStart, 0);
var vb = new v3(bvEnd, bhStart, 0);
var vc = new v3(bvEnd, bhEnd, 0);
var vd = new v3(bvStart, bhEnd, 0);
var us = uStart + (1 / wd * i) * (uEnd - uStart);
var ue = uStart + (1 / wd * (i + 1)) * (uEnd - uStart);
var vs = 1 - (vStart + (1 / hd * (j + 1)) * (vEnd - vStart));
var ve = 1 - (vStart + (1 / hd * j) * (vEnd - vStart));
J3D.Primitive.addQuad(c, va, vb, vc, vd, [us, ue, vs, ve]);
}
}
return new J3D.Mesh(c);
}
/**
* Creates a sphere. Code adapted from Three.js (https://github.com/mrdoob/three.js/blob/master/src/extras/geometries/SphereGeometry.js) & Papervision3d.
*
* @param radius the radius of the sphere
*
* @param segmentsWidth number of vertical segments
*
* @param segmentsHeight number of horizontal segments
*/
J3D.Primitive.Sphere = function(radius, segmentsWidth, segmentsHeight) {
var c = J3D.Primitive.getEmpty();
var vertices = [];
var uvs = [];
var radius = radius || 50;
var segmentsX = Math.max(3, Math.floor(segmentsWidth) || 8);
var segmentsY = Math.max(3, Math.floor(segmentsHeight) || 6);
var phiStart = 0;
var phiLength = Math.PI * 2;
var thetaStart = 0;
var thetaLength = Math.PI;
var x, y;
for (y = 0; y <= segmentsY; y ++) {
for (x = 0; x <= segmentsX; x ++) {
var u = x / segmentsX;
var v = y / segmentsY;
var xp = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
var yp = radius * Math.cos(thetaStart + v * thetaLength);
var zp = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
vertices.push(new v3(xp, yp, zp));
uvs.push([u, 1 - v]);
}
}
for (y = 0; y < segmentsY; y ++) {
for (x = 0; x < segmentsX; x ++) {
var o = segmentsX + 1;
var vt1 = vertices[ y * o + x + 0 ];
var vt2 = vertices[ y * o + x + 1 ];
var vt3 = vertices[ (y + 1) * o + x + 1 ];
var vt4 = vertices[ (y + 1) * o + x + 0 ];
var uv1 = uvs[ y * o + x + 0 ];
var uv2 = uvs[ y * o + x + 1 ];
var uv3 = uvs[ (y + 1) * o + x + 1 ];
var uv4 = uvs[ (y + 1) * o + x + 0 ];
var n1 = vt1.cp().norm();
var n2 = vt2.cp().norm();
var n3 = vt3.cp().norm();
var n4 = vt4.cp().norm();
var p = Math.floor(c.vertices.length / 3);
c.vertices.push(vt1.x, vt1.y, vt1.z, vt2.x, vt2.y, vt2.z, vt3.x, vt3.y, vt3.z, vt4.x, vt4.y, vt4.z);
c.uv1.push(uv1[0], uv1[1], uv2[0], uv2[1], uv3[0], uv3[1], uv4[0], uv4[1]);
//c.uv1.push(0, 0, 1, 0, 1, 1, 0, 1);
c.normals.push(n1.x, n1.y, n1.z, n2.x, n2.y, n2.z, n3.x, n3.y, n3.z, n4.x, n4.y, n4.z);
c.tris.push(p + 0, p + 1, p + 2, p + 0, p + 2, p + 3);
}
}
J3D.MathUtil.calculateTangents(c);
return new J3D.Mesh(c);
}
/**
* Similar to sphere, but inverts all the normals and UVs.
*
* @param segmentsWidth number of vertical segments
*
* @param segmentsHeight number of horizontal segments
*
*/
J3D.Primitive.SingleTextureSkybox = function(segmentsWidth, segmentsHeight) {
var c = J3D.Primitive.getEmpty();
var vertices = [];
var uvs = [];
var radius = radius || 50;
var segmentsX = Math.max(3, Math.floor(segmentsWidth) || 8);
var segmentsY = Math.max(3, Math.floor(segmentsHeight) || 6);
var phiStart = 0;
var phiLength = Math.PI * 2;
var thetaStart = 0;
var thetaLength = Math.PI;
var x, y;
for (y = 0; y <= segmentsY; y ++) {
for (x = 0; x <= segmentsX; x ++) {
var u = x / segmentsX;
var v = y / segmentsY;
var xp = Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength) * -1;
var yp = Math.cos(thetaStart + v * thetaLength);
var zp = Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
var vx = new v3(xp, yp, zp);
var ad = Math.max( Math.max(vx.x, vx.y), vx.z );
var ad2 = Math.min( Math.min(vx.x, vx.y), vx.z );
var r, t;
if(Math.abs(ad2) > ad) {
ad = ad2;
r = -radius;
} else {
r = radius;
}
if(ad == vx.x) {
t = r / vx.x;
vx.x = vx.x * r / vx.x;
vx.y *= t;
vx.z *= t;
} else if(ad == vx.y) {
t = r / vx.y;
vx.y = r;
vx.x *= t;
vx.z *= t;
} else if(ad == vx.z) {
t = r / vx.z;
vx.z = r;
vx.x *= t;
vx.y *= t;
}
vertices.push(vx);
uvs.push([u, v]);
}
}
for (y = 0; y <= segmentsY; y ++) {
for (x = 0; x < segmentsX; x ++) {
var vt1 = vertices[ y * segmentsX + x + 0 ];
var vt2 = vertices[ y * segmentsX + x + 1 ];
var vt3 = vertices[ (y + 1) * segmentsX + x + 1 ];
var vt4 = vertices[ (y + 1) * segmentsX + x + 0 ];
var uv1 = uvs[ y * segmentsX + x + 0 ];
var uv2 = uvs[ y * segmentsX + x + 1 ];
var uv3 = uvs[ (y + 1) * segmentsX + x + 1 ];
var uv4 = uvs[ (y + 1) * segmentsX + x + 0 ];
var p = c.vertices.length / 3;
c.vertices.push(
vt1.x, vt1.y, vt1.z,
vt2.x, vt2.y, vt2.z,
vt3.x, vt3.y, vt3.z,
vt4.x, vt4.y, vt4.z
);
c.uv1.push(
uv1[0], uv1[1],
uv2[0], uv2[1],
uv3[0], uv3[1],
uv4[0], uv4[1]
);
// 0, 1, 2, 0, 2, 3 (inv: 0, 2, 1, 0, 3, 2)
c.tris.push(p + 0, p + 2, p + 1, p + 0, p + 3, p + 2);
}
}
return new J3D.Mesh(c);
}
/**
* Utility function. Returns an empty object to populate with geometry. Contains empty arrays for vertices, normals, uv1 and indices (called tris).
*/
J3D.Primitive.getEmpty = function(){
var g = {};
g.vertices = [];
g.normals = [];
g.uv1 = [];
g.tangents = [];
g.tris = [];
return g;
}
/**
* Add a quad to an object containing graphics data.
*
* @param g graphics object to add the quad to
* @param p1 coordinates of first point
* @param p2 coordinates of second point
* @param p3 coordinates of third point
* @param p4 coordinates of fourth point
* @param uv an array with uv coordinates [minU, maxU, minV, maxV]
*/
J3D.Primitive.addQuad = function(g, p1, p2, p3, p4, uv) {
if(!J3D.Primitive.__tv1) J3D.Primitive.__tv1 = new v3();
//
var n1 = J3D.Primitive.__tv1;
v3.calculateNormal(p1, p2, p3, n1).norm();
var p = g.vertices.length / 3;
if(!uv || !uv.length || uv.length != 4) uv = [0, 1, 0, 1];
g.vertices.push(p1.x, p1.y, p1.z, p2.x, p2.y, p2.z, p3.x, p3.y, p3.z, p4.x, p4.y, p4.z);
g.normals.push (n1.x, n1.y, n1.z, n1.x, n1.y, n1.z, n1.x, n1.y, n1.z, n1.x, n1.y, n1.z);
g.uv1.push(uv[0],uv[3], uv[1],uv[3], uv[1],uv[2], uv[0],uv[2]);
g.tris.push(p, p + 1, p + 2, p, p + 2, p + 3);
} |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict-local
*/
// flowlint ambiguous-object-type:error
'use strict';
const React = require('react');
const ReactRelayContext = require('../ReactRelayContext');
const invariant = require('invariant');
const {createOperationDescriptor, getRequest} = require('relay-runtime');
import type {Variables, Snapshot} from 'relay-runtime';
type Props = {
environment: $FlowFixMe,
query: $FlowFixMe,
variables: Variables,
children: React.Element<$FlowFixMe>,
...
};
class RelayTestRenderer extends React.Component<Props, $FlowFixMe> {
constructor(props: Props) {
super(props);
invariant(
React.Children.count(this.props.children) === 1,
'Expected only a single child to be passed to `RelayTestContainer`',
);
invariant(
React.isValidElement(this.props.children),
'Expected child of `RelayTestContainer` to be a React element',
);
const {query, environment, variables} = props;
const operation = getRequest((query: $FlowFixMe));
const operationDescriptor = createOperationDescriptor(operation, variables);
const snapshot = environment.lookup(
operationDescriptor.fragment,
operationDescriptor,
);
this.state = {data: snapshot.data};
environment.subscribe(snapshot, this._onChange);
}
_onChange = (snapshot: Snapshot): void => {
this.setState({data: snapshot.data});
};
render(): React.Element<typeof ReactRelayContext.Provider> {
const childProps = this.props.children.props;
const newProps = {...childProps, ...this.state.data};
return (
<ReactRelayContext.Provider
value={{
environment:
this.props.environment || this.props.children.props.environment,
}}>
{React.cloneElement(
this.props.children,
newProps,
// $FlowFixMe: error found when enabling flow for this file.
this.props.children.children,
)}
</ReactRelayContext.Provider>
);
}
}
module.exports = RelayTestRenderer;
|
define({
"enableUndoRedo": "Aktiver Angre/Gjenta",
"toolbarVisible": "Verktøylinje synlig",
"toolbarOptions": "Verktøylinjealternativer",
"mergeVisible": "Slå sammen",
"cutVisible": "Klipp ut",
"reshapeVisible": "Omforme",
"back": "Bak",
"label": "Lag",
"edit": "Redigerbar",
"update": "Deaktiver geometrioppdatering",
"fields": "Felter",
"actions": "Handlinger",
"editpageName": "Navn",
"editpageAlias": "Alias",
"editpageVisible": "Synlig",
"editpageEditable": "Redigerbar",
"noLayers": "Det er ingen redigerbare geoobjektlag tilgjengelig",
"configureFields": "Konfigurer felter for lagene",
"useFilterEdit": "Bruk geoobjektmal-filter",
"display": "Vis",
"autoApplyEditWhenGeometryIsMoved": "Bruk redigeringen automatisk når geometrien flyttes",
"snappingTolerance": "Angi toleransen for festing i piksler",
"popupTolerance": "Angi toleransen for attributtredigeringspopupen i piksler",
"stickyMoveTolerance": "Angi toleransen for fast flytting i pisker"
}); |
// Negative ease produces ease out, positive produces ease in.
// Range around -1 to 1
function getDynamicallyEasedInterpolation (ease) {
return function (p) {
return dynamicEaseInterpolation(p, ease);
};
}
function dynamicEaseInterpolation(p, ease) {
// invert negative value and positive so they work on the same logarithmic scale.
if (ease >= 0.0) {
ease = ease * 2.25 + 1;
// superelipse
return Math.pow( 1 - Math.pow( 1 - p, ease ), 1 / ease );
} else {
ease = Math.abs(ease) * 2.25 + 1;
// superelipse shifted
return 1 - Math.pow( 1 - Math.pow(p, ease ), 1 / ease );
}
} |
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
var _CloseIcon;
const _excluded = ["action", "children", "className", "closeText", "color", "icon", "iconMapping", "onClose", "role", "severity", "variant"];
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled';
import { darken, lighten } from '@material-ui/system';
import styled from '../styles/styled';
import useThemeProps from '../styles/useThemeProps';
import capitalize from '../utils/capitalize';
import Paper from '../Paper';
import alertClasses, { getAlertUtilityClass } from './alertClasses';
import IconButton from '../IconButton';
import SuccessOutlinedIcon from '../internal/svg-icons/SuccessOutlined';
import ReportProblemOutlinedIcon from '../internal/svg-icons/ReportProblemOutlined';
import ErrorOutlineIcon from '../internal/svg-icons/ErrorOutline';
import InfoOutlinedIcon from '../internal/svg-icons/InfoOutlined';
import CloseIcon from '../internal/svg-icons/Close';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
const useUtilityClasses = ownerState => {
const {
variant,
color,
severity,
classes
} = ownerState;
const slots = {
root: ['root', `${variant}${capitalize(color || severity)}`, `${variant}`],
icon: ['icon'],
message: ['message'],
action: ['action']
};
return composeClasses(slots, getAlertUtilityClass, classes);
};
const AlertRoot = styled(Paper, {
name: 'MuiAlert',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
ownerState
} = props;
return [styles.root, styles[ownerState.variant], styles[`${ownerState.variant}${capitalize(ownerState.color || ownerState.severity)}`]];
}
})(({
theme,
ownerState
}) => {
const getColor = theme.palette.mode === 'light' ? darken : lighten;
const getBackgroundColor = theme.palette.mode === 'light' ? lighten : darken;
const color = ownerState.color || ownerState.severity;
return _extends({}, theme.typography.body2, {
borderRadius: theme.shape.borderRadius,
backgroundColor: 'transparent',
display: 'flex',
padding: '6px 16px'
}, color && ownerState.variant === 'standard' && {
color: getColor(theme.palette[color].light, 0.6),
backgroundColor: getBackgroundColor(theme.palette[color].light, 0.9),
[`& .${alertClasses.icon}`]: {
color: theme.palette.mode === 'dark' ? theme.palette[color].main : theme.palette[color].light
}
}, color && ownerState.variant === 'outlined' && {
color: getColor(theme.palette[color].light, 0.6),
border: `1px solid ${theme.palette[color].light}`,
[`& .${alertClasses.icon}`]: {
color: theme.palette.mode === 'dark' ? theme.palette[color].main : theme.palette[color].light
}
}, color && ownerState.variant === 'filled' && {
color: '#fff',
fontWeight: theme.typography.fontWeightMedium,
backgroundColor: theme.palette.mode === 'dark' ? theme.palette[color].dark : theme.palette[color].main
});
});
const AlertIcon = styled('div', {
name: 'MuiAlert',
slot: 'Icon',
overridesResolver: (props, styles) => styles.icon
})({
marginRight: 12,
padding: '7px 0',
display: 'flex',
fontSize: 22,
opacity: 0.9
});
const AlertMessage = styled('div', {
name: 'MuiAlert',
slot: 'Message',
overridesResolver: (props, styles) => styles.message
})({
padding: '8px 0'
});
const AlertAction = styled('div', {
name: 'MuiAlert',
slot: 'Action',
overridesResolver: (props, styles) => styles.action
})({
display: 'flex',
alignItems: 'flex-start',
padding: '4px 0 0 16px',
marginLeft: 'auto',
marginRight: -8
});
const defaultIconMapping = {
success: /*#__PURE__*/_jsx(SuccessOutlinedIcon, {
fontSize: "inherit"
}),
warning: /*#__PURE__*/_jsx(ReportProblemOutlinedIcon, {
fontSize: "inherit"
}),
error: /*#__PURE__*/_jsx(ErrorOutlineIcon, {
fontSize: "inherit"
}),
info: /*#__PURE__*/_jsx(InfoOutlinedIcon, {
fontSize: "inherit"
})
};
const Alert = /*#__PURE__*/React.forwardRef(function Alert(inProps, ref) {
const props = useThemeProps({
props: inProps,
name: 'MuiAlert'
});
const {
action,
children,
className,
closeText = 'Close',
color,
icon,
iconMapping = defaultIconMapping,
onClose,
role = 'alert',
severity = 'success',
variant = 'standard'
} = props,
other = _objectWithoutPropertiesLoose(props, _excluded);
const ownerState = _extends({}, props, {
color,
severity,
variant
});
const classes = useUtilityClasses(ownerState);
return /*#__PURE__*/_jsxs(AlertRoot, _extends({
role: role,
square: true,
elevation: 0,
ownerState: ownerState,
className: clsx(classes.root, className),
ref: ref
}, other, {
children: [icon !== false ? /*#__PURE__*/_jsx(AlertIcon, {
ownerState: ownerState,
className: classes.icon,
children: icon || iconMapping[severity] || defaultIconMapping[severity]
}) : null, /*#__PURE__*/_jsx(AlertMessage, {
ownerState: ownerState,
className: classes.message,
children: children
}), action != null ? /*#__PURE__*/_jsx(AlertAction, {
className: classes.action,
children: action
}) : null, action == null && onClose ? /*#__PURE__*/_jsx(AlertAction, {
ownerState: ownerState,
className: classes.action,
children: /*#__PURE__*/_jsx(IconButton, {
size: "small",
"aria-label": closeText,
title: closeText,
color: "inherit",
onClick: onClose,
children: _CloseIcon || (_CloseIcon = /*#__PURE__*/_jsx(CloseIcon, {
fontSize: "small"
}))
})
}) : null]
}));
});
process.env.NODE_ENV !== "production" ? Alert.propTypes
/* remove-proptypes */
= {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The action to display. It renders after the message, at the end of the alert.
*/
action: PropTypes.node,
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* Override the default label for the *close popup* icon button.
*
* For localization purposes, you can use the provided [translations](/guides/localization/).
* @default 'Close'
*/
closeText: PropTypes.string,
/**
* The main color for the alert. Unless provided, the value is taken from the `severity` prop.
*/
color: PropTypes
/* @typescript-to-proptypes-ignore */
.oneOfType([PropTypes.oneOf(['error', 'info', 'success', 'warning']), PropTypes.string]),
/**
* Override the icon displayed before the children.
* Unless provided, the icon is mapped to the value of the `severity` prop.
*/
icon: PropTypes.node,
/**
* The component maps the `severity` prop to a range of different icons,
* for instance success to `<SuccessOutlined>`.
* If you wish to change this mapping, you can provide your own.
* Alternatively, you can use the `icon` prop to override the icon displayed.
*/
iconMapping: PropTypes.shape({
error: PropTypes.node,
info: PropTypes.node,
success: PropTypes.node,
warning: PropTypes.node
}),
/**
* Callback fired when the component requests to be closed.
* When provided and no `action` prop is set, a close icon button is displayed that triggers the callback when clicked.
* @param {React.SyntheticEvent} event The event source of the callback.
*/
onClose: PropTypes.func,
/**
* The ARIA role attribute of the element.
* @default 'alert'
*/
role: PropTypes.string,
/**
* The severity of the alert. This defines the color and icon used.
* @default 'success'
*/
severity: PropTypes.oneOf(['error', 'info', 'success', 'warning']),
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.object,
/**
* The variant to use.
* @default 'standard'
*/
variant: PropTypes
/* @typescript-to-proptypes-ignore */
.oneOfType([PropTypes.oneOf(['filled', 'outlined', 'standard']), PropTypes.string])
} : void 0;
export default Alert; |
export const isDev = () => process.env.NODE_ENV === 'development';
export const isProd = () => process.env.NODE_ENV === 'production';
export const isDebugProd = () => process.env.DEBUG_PROD === 'true';
|
require('dotenv-extended').load();
var restify = require('restify');
var builder = require('botbuilder');
var bot = require('./bot');
// Create chat bot
var connector = new builder.ConsoleConnector();
bot.create(connector);
connector.listen();
|
'use strict';
var foo = function() { return 'foo'; };
assert.equal( foo(), 'foo' );
|
Ext.define('MyApp.util.JsonWriter', {
extend : 'Ext.data.writer.Json',
getRecordData : function(record) {
console.log('Util.JsonWriter',record.data,record.raw);
Ext.applyIf(record.data, record.getAssociatedData());
return record.raw;
}
});
|
define('a', function () {
return 'A';
});
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
var es = require("event-stream");
var debounce = require("debounce");
var _filter = require("gulp-filter");
var rename = require("gulp-rename");
var _ = require("underscore");
var path = require("path");
var fs = require("fs");
var _rimraf = require("rimraf");
var git = require("./git");
var VinylFile = require("vinyl");
var NoCancellationToken = { isCancellationRequested: function () { return false; } };
function incremental(streamProvider, initial, supportsCancellation) {
var input = es.through();
var output = es.through();
var state = 'idle';
var buffer = Object.create(null);
var token = !supportsCancellation ? null : { isCancellationRequested: function () { return Object.keys(buffer).length > 0; } };
var run = function (input, isCancellable) {
state = 'running';
var stream = !supportsCancellation ? streamProvider() : streamProvider(isCancellable ? token : NoCancellationToken);
input
.pipe(stream)
.pipe(es.through(null, function () {
state = 'idle';
eventuallyRun();
}))
.pipe(output);
};
if (initial) {
run(initial, false);
}
var eventuallyRun = debounce(function () {
var paths = Object.keys(buffer);
if (paths.length === 0) {
return;
}
var data = paths.map(function (path) { return buffer[path]; });
buffer = Object.create(null);
run(es.readArray(data), true);
}, 500);
input.on('data', function (f) {
buffer[f.path] = f;
if (state === 'idle') {
eventuallyRun();
}
});
return es.duplex(input, output);
}
exports.incremental = incremental;
function fixWin32DirectoryPermissions() {
if (!/win32/.test(process.platform)) {
return es.through();
}
return es.mapSync(function (f) {
if (f.stat && f.stat.isDirectory && f.stat.isDirectory()) {
f.stat.mode = 16877;
}
return f;
});
}
exports.fixWin32DirectoryPermissions = fixWin32DirectoryPermissions;
function setExecutableBit(pattern) {
var setBit = es.mapSync(function (f) {
f.stat.mode = 33261;
return f;
});
if (!pattern) {
return setBit;
}
var input = es.through();
var filter = _filter(pattern, { restore: true });
var output = input
.pipe(filter)
.pipe(setBit)
.pipe(filter.restore);
return es.duplex(input, output);
}
exports.setExecutableBit = setExecutableBit;
function toFileUri(filePath) {
var match = filePath.match(/^([a-z])\:(.*)$/i);
if (match) {
filePath = '/' + match[1].toUpperCase() + ':' + match[2];
}
return 'file://' + filePath.replace(/\\/g, '/');
}
exports.toFileUri = toFileUri;
function skipDirectories() {
return es.mapSync(function (f) {
if (!f.isDirectory()) {
return f;
}
});
}
exports.skipDirectories = skipDirectories;
function cleanNodeModule(name, excludes, includes) {
var toGlob = function (path) { return '**/node_modules/' + name + (path ? '/' + path : ''); };
var negate = function (str) { return '!' + str; };
var allFilter = _filter(toGlob('**'), { restore: true });
var globs = [toGlob('**')].concat(excludes.map(_.compose(negate, toGlob)));
var input = es.through();
var nodeModuleInput = input.pipe(allFilter);
var output = nodeModuleInput.pipe(_filter(globs));
if (includes) {
var includeGlobs = includes.map(toGlob);
output = es.merge(output, nodeModuleInput.pipe(_filter(includeGlobs)));
}
output = output.pipe(allFilter.restore);
return es.duplex(input, output);
}
exports.cleanNodeModule = cleanNodeModule;
function loadSourcemaps() {
var input = es.through();
var output = input
.pipe(es.map(function (f, cb) {
if (f.sourceMap) {
cb(null, f);
return;
}
if (!f.contents) {
cb(new Error('empty file'));
return;
}
var contents = f.contents.toString('utf8');
var reg = /\/\/# sourceMappingURL=(.*)$/g;
var lastMatch = null, match = null;
while (match = reg.exec(contents)) {
lastMatch = match;
}
if (!lastMatch) {
f.sourceMap = {
version: 3,
names: [],
mappings: '',
sources: [f.relative.replace(/\//g, '/')],
sourcesContent: [contents]
};
cb(null, f);
return;
}
f.contents = new Buffer(contents.replace(/\/\/# sourceMappingURL=(.*)$/g, ''), 'utf8');
fs.readFile(path.join(path.dirname(f.path), lastMatch[1]), 'utf8', function (err, contents) {
if (err) {
return cb(err);
}
f.sourceMap = JSON.parse(contents);
cb(null, f);
});
}));
return es.duplex(input, output);
}
exports.loadSourcemaps = loadSourcemaps;
function stripSourceMappingURL() {
var input = es.through();
var output = input
.pipe(es.mapSync(function (f) {
var contents = f.contents.toString('utf8');
f.contents = new Buffer(contents.replace(/\n\/\/# sourceMappingURL=(.*)$/gm, ''), 'utf8');
return f;
}));
return es.duplex(input, output);
}
exports.stripSourceMappingURL = stripSourceMappingURL;
function rimraf(dir) {
var retries = 0;
var retry = function (cb) {
_rimraf(dir, { maxBusyTries: 1 }, function (err) {
if (!err) {
return cb();
}
;
if (err.code === 'ENOTEMPTY' && ++retries < 5) {
return setTimeout(function () { return retry(cb); }, 10);
}
return cb(err);
});
};
return function (cb) { return retry(cb); };
}
exports.rimraf = rimraf;
function getVersion(root) {
var version = process.env['BUILD_SOURCEVERSION'];
if (!version || !/^[0-9a-f]{40}$/i.test(version)) {
version = git.getVersion(root);
}
return version;
}
exports.getVersion = getVersion;
function rebase(count) {
return rename(function (f) {
var parts = f.dirname.split(/[\/\\]/);
f.dirname = parts.slice(count).join(path.sep);
});
}
exports.rebase = rebase;
function filter(fn) {
var result = es.through(function (data) {
if (fn(data)) {
this.emit('data', data);
}
else {
result.restore.push(data);
}
});
result.restore = es.through();
return result;
}
exports.filter = filter;
|
/* jslint node: true */
/*!
* rinco - mustache compile
* Copyright(c) 2014 Allan Esquina
* MIT Licensed
*/
'use strict';
var rinco = require('../rinco');
var mustache = require('mustache');
var fs = require('../fs');
var config = require('../constants');
// Parse templates files
rinco.render.middleware.register(function rinco_mustache(next, content, data) {
// Parse template with mustache
content = mustache.to_html((config.USER_CONFIG.mustache_delimiter || '') + ' ' + content, data);
// Return rendered content
next(content, data);
});
|
define(function() {
function escapeRegExp(str) {
if (str == null) return '';
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
}
function defaultToWhiteSpace(characters) {
if (characters == null)
return '\\s';
else if (characters.source)
return characters.source;
else
return '[' + escapeRegExp(characters) + ']';
}
return {
defaultToWhiteSpace: defaultToWhiteSpace,
escapeRegExp: escapeRegExp
};
});
|
var gulp = require('gulp'),
browserify = require('gulp-browserify');
gulp.task('scripts', function () {
gulp.src(['app/main.js'])
.pipe(browserify({
debug: true,
transform: [ 'reactify' ]
}))
.pipe(gulp.dest('./public/javascripts/'));
});
gulp.task('default', ['scripts']);
|
absConfig.pushAfterBootstrap('abs.connexionFeature.signupPage'); |
// require('bootstrap/dist/css/bootstrap.min.css');
require('iconfontDir/iconfont.css');
require('lessDir/base.less');
require('metisMenu/metisMenu.min');
require('bootstrap/dist/js/bootstrap.min.js');
require('vendorDir/promise.min');
$(() => {
$('#side-menu').metisMenu();
$('#side-menu').css('visibility', 'visible');
(() => {
const width = (window.innerWidth > 0) ? window.innerWidth : window.screen.width;
if (width < 768) {
$('div.navbar-collapse').addClass('collapse');
// topOffset = 100; // 2-row-menu
const topOffset = $('nav.navbar').height() + 1 + 1;
let height = ((window.innerHeight > 0) ? window.innerHeight : window.screen.height) - 4;
height = height - topOffset;
if (height < 1) height = 1;
if (height > topOffset) {
$('#page-wrapper').css('min-height', (height) + 'px');
}
} else {
$('div.navbar-collapse').removeClass('collapse');
}
const url = window.location.href;
let element = $('ul.nav a').filter(function filterCb() {
return this.href === url;
}).addClass('active')
.parent('li');
let ifContinue = true;
while (ifContinue) {
if (element.is('li')) {
element = element.parent('ul').addClass('in')
.parent('li')
.addClass('active');
} else {
ifContinue = false;
}
}
})();
/* 事件绑定 开始 */
/* 事件绑定 结束 */
/* 各种定时器 开始 */
/* 各种定时器 结束 */
});
|
function Person(name, age) {
if (!(this instanceof arguments.callee)) {
return new Person(name, age);
}
this.name = name;
this.age = age;
}
var p1 = new Person("With new", 12);
var p3 = new Person("With new 2", 12);
var p2 = Person("Withoud new", 13);
console.log(p1);
console.log(p2);
console.log(p3); |
version https://git-lfs.github.com/spec/v1
oid sha256:7046f5962346897cebc68c8853c9de44f55dfa98c4ec130533fc0c8836267bc5
size 115147
|
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Editor configuration settings.
*
* Follow this link for more information:
* http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/Configuration/Configuration_Options
*/
FCKConfig.AutoDetectLanguage = false ;
FCKConfig.Plugins.Add( 'dragresizetable' );
FCKConfig.ToolbarSets["Default"] = [
['Source','DocProps','-','Save','NewPage','Preview','-','Templates'],
['Cut','Copy','Paste','PasteText','PasteWord','-','Print','SpellCheck'],
['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
'/',
['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'],
['OrderedList','UnorderedList','-','Outdent','Indent'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],
['Link','Unlink','Anchor'],
['Image','Flash','Table','Rule','Smiley','SpecialChar','PageBreak'],
'/',
['Style','FontFormat','FontName','FontSize'],
['TextColor','BGColor'],
['About']
] ;
FCKConfig.ToolbarSets["Basic"] = [
['Source','-','Bold','Italic','-','OrderedList','UnorderedList','-','Link','Unlink','-','FontFormat','Outdent', 'Indent','-','About']
] ;
// To enable ToolbarSet = 'Default', ie more options, you must update the
// admin_header.html template in the default module, and adjust the
// fck_add() method accordingly. Remember to clear browser cache if you don't
// see results. |
E2.p = E2.plugins["instance_array_modulator"] = function(core, node)
{
this.desc = 'Create a scene that represents <b>count</b> instances of the supplied <b>mesh</b>, starting at position <b>start</b>, offset by <b>delta</b> each instance.';
this.input_slots = [
{ name: 'count', dt: core.datatypes.FLOAT, desc: 'The number of instances to create.', lo: 0, def: 1 },
{ name: 'mesh', dt: core.datatypes.MESH, desc: 'The mesh to instantiate.', def: null },
{ name: 'start', dt: core.datatypes.VECTOR, desc: 'The starting position.', def: core.renderer.vector_origin },
{ name: 'offset', dt: core.datatypes.VECTOR, desc: 'The offset vector.', def: core.renderer.vector_origin }
];
this.output_slots = [
{ name: 'scene', dt: core.datatypes.SCENE, desc: 'Scene representing <b>count</b> instances.' }
];
this.gl = core.renderer.context;
};
E2.p.prototype.update_input = function(slot, data)
{
if(slot.index === 0)
this.count = data;
else if(slot.index === 1)
{
var s = this.scene = new Scene(this.gl, null, null);
if(data)
{
s.meshes = [data];
s.vertex_count = data.vertex_count;
}
}
else if(slot.index === 2)
this.start = data;
else
this.offset = data;
};
E2.p.prototype.update_state = function()
{
var s = this.scene;
if(s.meshes.length < 1)
return;
var m = s.meshes[0];
var st = this.start;
var of = this.offset;
var inst = [];
var o = st.slice(0);
for(var i = 0; i < this.count; i++)
{
var mat = mat4.create();
// TODO: Inline these two ops here for better performance.
mat4.identity(mat);
mat4.translate(mat, o);
inst.push(mat);
o[0] += of[0];
o[1] += of[1];
o[2] += of[2];
}
m.instances = inst;
};
E2.p.prototype.update_output = function(slot)
{
return this.scene;
};
E2.p.prototype.state_changed = function(ui)
{
if(!ui)
{
this.scene = new Scene(this.gl, null, null);
this.count = 1;
this.start = [0, 0, 0];
this.offset = [0, 0, 0];
}
};
|
import AccountsRoute from './Accounts';
import CardsRoute from './Cards';
import LoansRoute from './Loans';
import OrdersRoute from './Orders';
import PaymentsRoute from './Payments';
import TransfersRoute from './Transfers';
export {
AccountsRoute,
CardsRoute,
LoansRoute,
OrdersRoute,
PaymentsRoute,
TransfersRoute
};
|
import React from "react"
import { mount } from "enzyme"
import { RemoveButton } from "client/components/remove_button"
import {
TextInputUrl,
Button,
BackgroundOverlay,
} from "client/components/rich_text/components/input_url"
describe("TextInputUrl", () => {
let props
const getWrapper = props => {
return mount(<TextInputUrl {...props} />)
}
beforeEach(() => {
props = {
confirmLink: jest.fn(),
onClickOff: jest.fn(),
pluginType: undefined,
removeLink: jest.fn(),
selectionTarget: {},
urlValue: null,
}
})
it("Renders input and appy button", () => {
const component = getWrapper(props)
const input = component.find("input").getElement()
const button = component.find(Button).getElement()
expect(input.props.placeholder).toBe("Paste or type a link")
expect(input.props.value).toBe("")
expect(button.props.children).toBe("Apply")
})
it("Can render an existing link", () => {
props.urlValue = "http://artsy.net"
const component = getWrapper(props)
const input = component.find("input").getElement()
expect(input.props.value).toBe("http://artsy.net")
})
it("Renders remove button if has url", () => {
props.urlValue = "http://artsy.net"
const component = getWrapper(props)
expect(component.find(RemoveButton).exists()).toBe(true)
})
it("Can input a url", () => {
const component = getWrapper(props)
const input = component.find("input")
const value = "http://link.com"
input.simulate("change", { target: { value } })
expect(component.state().url).toBe(value)
})
it("Can save a link on button click", () => {
const component = getWrapper(props)
const url = "http://link.com"
const button = component.find(Button)
component.setState({ url })
button.simulate("mouseDown")
expect(props.confirmLink.mock.calls[0][0]).toBe(url)
})
it("Can save a link with plugins", () => {
props.pluginType = "artist"
const component = getWrapper(props)
const url = "http://link.com"
const button = component.find(Button)
component.setState({ url })
button.simulate("mouseDown")
expect(props.confirmLink.mock.calls[0][0]).toBe(url)
expect(props.confirmLink.mock.calls[0][1]).toBe(props.pluginType)
})
it("Does not save empty links", () => {
const component = getWrapper(props)
const url = ""
const button = component.find(Button)
component.setState({ url })
button.simulate("mouseDown")
expect(props.confirmLink.mock.calls.length).toBe(0)
expect(props.removeLink.mock.calls.length).toBe(1)
})
it("Can remove a link", () => {
props.urlValue = "http://artsy.net"
const component = getWrapper(props)
component.find(RemoveButton).simulate("mouseDown")
expect(props.removeLink.mock.calls.length).toBe(1)
})
it("Calls #onClickOff on background click", () => {
const component = getWrapper(props)
component.find(BackgroundOverlay).simulate("click")
expect(props.onClickOff).toBeCalled()
})
describe("#onKeyDown", () => {
it("Calls #confirmLink on enter", () => {
props.urlValue = "http://artsy.net"
const e = {
key: "Enter",
preventDefault: jest.fn(),
target: { value: "http://artsy.net/articles" },
}
const component = getWrapper(props)
component.instance().onKeyDown(e)
expect(e.preventDefault).toBeCalled()
expect(props.confirmLink.mock.calls[0][0]).toBe(
"http://artsy.net/articles"
)
})
it("Calls #onClickOff on esc", () => {
const e = { key: "Escape", preventDefault: jest.fn() }
const component = getWrapper(props)
component.instance().onKeyDown(e)
expect(props.onClickOff).toBeCalled()
})
it("Calls #onExitInput on tab", () => {
const e = { key: "Tab", preventDefault: jest.fn() }
const component = getWrapper(props)
component.instance().onExitInput = jest.fn()
component.update()
component.instance().onKeyDown(e)
expect(component.instance().onExitInput).toBeCalledWith(e)
})
})
describe("#onExitInput", () => {
it("Calls #confirmLink if url is present", () => {
props.urlValue = "http://artsy.net"
const e = {
key: "Tab",
preventDefault: jest.fn(),
target: { value: "http://artsy.net/articles" },
}
const component = getWrapper(props)
component.instance().onExitInput(e)
expect(props.confirmLink.mock.calls[0][0]).toBe(
"http://artsy.net/articles"
)
})
it("Calls #removeLink if url has been deleted", () => {
props.urlValue = "http://artsy.net"
const e = {
key: "Tab",
preventDefault: jest.fn(),
target: { value: "" },
}
const component = getWrapper(props)
component.instance().onExitInput(e)
expect(props.removeLink).toBeCalled()
})
it("Calls #onClickOff if url was not edited", () => {
const e = {
key: "Tab",
preventDefault: jest.fn(),
target: { value: "" },
}
const component = getWrapper(props)
component.instance().onExitInput(e)
expect(props.onClickOff).toBeCalled()
})
})
})
|
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
switch (arguments.length) {
case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);
case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);
case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);
}
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
import { Component, View, Host } from 'angular2/angular2';
import { FaNode } from '../core/node';
export let FaGestureHandler = class {
constructor(parent) {
let GestureHandler = famous.components.GestureHandler;
this.node = parent.node;
this.gestures = new GestureHandler(this.node);
}
onInit() {
var g = this;
this.drag ? this.gestures.on({ event: 'drag' }, g.drag.currentValue.bind(this.node)) : false;
this.tap ? this.gestures.on({ event: 'tap' }, g.tap.currentValue.bind(this.node)) : false;
this.rotate ? this.gestures.on({ event: 'rotate' }, g.rotate.currentValue.bind(this.node)) : false;
this.pinch ? this.gestures.on({ event: 'drag' }, g.pinch.currentValue.bind(this.node)) : false;
}
onChange(changes) {
// add some gestures
}
};
FaGestureHandler = __decorate([
Component({
selector: 'fa-gesture-handler',
properties: ['drag', 'tap', 'rotate', 'pinch']
}),
View({
template: ``
}),
__param(0, Host()),
__metadata('design:paramtypes', [FaNode])
], FaGestureHandler);
|
import Colors from 'material-ui/lib/styles/colors';
import ColorManipulator from 'material-ui/lib/utils/color-manipulator';
import Spacing from 'material-ui/lib/styles/spacing';
import zIndex from 'material-ui/lib/styles/zIndex';
export const config = {
colors: {
main: '#008DD0',
highlight: '#F15A29',
green: '#40AC31',
lightBlue: '#33A4D9',
success: '#40AC31',
textColor: '#666',
},
font: 'Roboto, sans-serif',
}
export const muiTheme = {
spacing: Spacing,
zIndex: zIndex,
fontFamily: 'Roboto, sans-serif',
palette: {
primary1Color: config.colors.main,
primary2Color: Colors.cyan700,
primary3Color: Colors.lightBlack,
accent1Color: config.colors.highlight,
accent2Color: Colors.grey100,
accent3Color: Colors.grey500,
textColor: Colors.darkBlack,
alternateTextColor: Colors.white,
canvasColor: Colors.white,
borderColor: Colors.grey300,
disabledColor: ColorManipulator.fade(Colors.darkBlack, 0.3),
pickerHeaderColor: Colors.cyan500,
}
};
//
// export default {
// config,
// muiTheme,
// }
|
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
let React;
let ReactDOM;
describe('SyntheticEvent', () => {
let container;
beforeEach(() => {
React = require('react');
ReactDOM = require('react-dom');
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
container = null;
});
it('should be able to `preventDefault`', () => {
let node;
let expectedCount = 0;
const eventHandler = syntheticEvent => {
expect(syntheticEvent.isDefaultPrevented()).toBe(false);
syntheticEvent.preventDefault();
expect(syntheticEvent.isDefaultPrevented()).toBe(true);
expect(syntheticEvent.defaultPrevented).toBe(true);
expectedCount++;
};
node = ReactDOM.render(<div onClick={eventHandler} />, container);
const event = document.createEvent('Event');
event.initEvent('click', true, true);
node.dispatchEvent(event);
expect(expectedCount).toBe(1);
});
it('should be prevented if nativeEvent is prevented', () => {
let node;
let expectedCount = 0;
const eventHandler = syntheticEvent => {
expect(syntheticEvent.isDefaultPrevented()).toBe(true);
expectedCount++;
};
node = ReactDOM.render(<div onClick={eventHandler} />, container);
let event;
event = document.createEvent('Event');
event.initEvent('click', true, true);
event.preventDefault();
node.dispatchEvent(event);
event = document.createEvent('Event');
event.initEvent('click', true, true);
// Emulate IE8
Object.defineProperty(event, 'defaultPrevented', {
get() {},
});
Object.defineProperty(event, 'returnValue', {
get() {
return false;
},
});
node.dispatchEvent(event);
expect(expectedCount).toBe(2);
});
it('should be able to `stopPropagation`', () => {
let node;
let expectedCount = 0;
const eventHandler = syntheticEvent => {
expect(syntheticEvent.isPropagationStopped()).toBe(false);
syntheticEvent.stopPropagation();
expect(syntheticEvent.isPropagationStopped()).toBe(true);
expectedCount++;
};
node = ReactDOM.render(<div onClick={eventHandler} />, container);
const event = document.createEvent('Event');
event.initEvent('click', true, true);
node.dispatchEvent(event);
expect(expectedCount).toBe(1);
});
it('should be able to `persist`', () => {
let node;
let expectedCount = 0;
let syntheticEvent;
const eventHandler = e => {
expect(e.isPersistent()).toBe(false);
e.persist();
syntheticEvent = e;
expect(e.isPersistent()).toBe(true);
expectedCount++;
};
node = ReactDOM.render(<div onClick={eventHandler} />, container);
const event = document.createEvent('Event');
event.initEvent('click', true, true);
node.dispatchEvent(event);
expect(syntheticEvent.type).toBe('click');
expect(syntheticEvent.bubbles).toBe(true);
expect(syntheticEvent.cancelable).toBe(true);
expect(expectedCount).toBe(1);
});
it('should be nullified and log warnings if the synthetic event has not been persisted', () => {
let node;
let expectedCount = 0;
let syntheticEvent;
const eventHandler = e => {
syntheticEvent = e;
expectedCount++;
};
node = ReactDOM.render(<div onClick={eventHandler} />, container);
const event = document.createEvent('Event');
event.initEvent('click', true, true);
node.dispatchEvent(event);
const getExpectedWarning = property =>
'Warning: This synthetic event is reused for performance reasons. If ' +
`you're seeing this, you're accessing the property \`${property}\` on a ` +
'released/nullified synthetic event. This is set to null. If you must ' +
'keep the original synthetic event around, use event.persist(). ' +
'See https://fb.me/react-event-pooling for more information.';
// once for each property accessed
expect(() => expect(syntheticEvent.type).toBe(null)).toWarnDev(
getExpectedWarning('type'),
);
expect(() => expect(syntheticEvent.nativeEvent).toBe(null)).toWarnDev(
getExpectedWarning('nativeEvent'),
);
expect(() => expect(syntheticEvent.target).toBe(null)).toWarnDev(
getExpectedWarning('target'),
);
expect(expectedCount).toBe(1);
});
it('should warn when setting properties of a synthetic event that has not been persisted', () => {
let node;
let expectedCount = 0;
let syntheticEvent;
const eventHandler = e => {
syntheticEvent = e;
expectedCount++;
};
node = ReactDOM.render(<div onClick={eventHandler} />, container);
const event = document.createEvent('Event');
event.initEvent('click', true, true);
node.dispatchEvent(event);
expect(() => {
syntheticEvent.type = 'MouseEvent';
}).toWarnDev(
'Warning: This synthetic event is reused for performance reasons. If ' +
"you're seeing this, you're setting the property `type` on a " +
'released/nullified synthetic event. This is effectively a no-op. If you must ' +
'keep the original synthetic event around, use event.persist(). ' +
'See https://fb.me/react-event-pooling for more information.',
);
expect(expectedCount).toBe(1);
});
it('should warn when calling `preventDefault` if the synthetic event has not been persisted', () => {
let node;
let expectedCount = 0;
let syntheticEvent;
const eventHandler = e => {
syntheticEvent = e;
expectedCount++;
};
node = ReactDOM.render(<div onClick={eventHandler} />, container);
const event = document.createEvent('Event');
event.initEvent('click', true, true);
node.dispatchEvent(event);
expect(() => syntheticEvent.preventDefault()).toWarnDev(
'Warning: This synthetic event is reused for performance reasons. If ' +
"you're seeing this, you're accessing the method `preventDefault` on a " +
'released/nullified synthetic event. This is a no-op function. If you must ' +
'keep the original synthetic event around, use event.persist(). ' +
'See https://fb.me/react-event-pooling for more information.',
);
expect(expectedCount).toBe(1);
});
it('should warn when calling `stopPropagation` if the synthetic event has not been persisted', () => {
let node;
let expectedCount = 0;
let syntheticEvent;
const eventHandler = e => {
syntheticEvent = e;
expectedCount++;
};
node = ReactDOM.render(<div onClick={eventHandler} />, container);
const event = document.createEvent('Event');
event.initEvent('click', true, true);
node.dispatchEvent(event);
expect(() => syntheticEvent.stopPropagation()).toWarnDev(
'Warning: This synthetic event is reused for performance reasons. If ' +
"you're seeing this, you're accessing the method `stopPropagation` on a " +
'released/nullified synthetic event. This is a no-op function. If you must ' +
'keep the original synthetic event around, use event.persist(). ' +
'See https://fb.me/react-event-pooling for more information.',
);
expect(expectedCount).toBe(1);
});
it('should properly log warnings when events simulated with rendered components', () => {
let event;
function assignEvent(e) {
event = e;
}
const node = ReactDOM.render(<div onClick={assignEvent} />, container);
node.click();
// access a property to cause the warning
expect(() => {
event.nativeEvent; // eslint-disable-line no-unused-expressions
}).toWarnDev(
'Warning: This synthetic event is reused for performance reasons. If ' +
"you're seeing this, you're accessing the property `nativeEvent` on a " +
'released/nullified synthetic event. This is set to null. If you must ' +
'keep the original synthetic event around, use event.persist(). ' +
'See https://fb.me/react-event-pooling for more information.',
);
});
it('should warn if Proxy is supported and the synthetic event is added a property', () => {
let node;
let expectedCount = 0;
let syntheticEvent;
const eventHandler = e => {
if (typeof Proxy === 'function') {
expect(() => {
e.foo = 'bar';
}).toWarnDev(
'Warning: This synthetic event is reused for performance reasons. If ' +
"you're seeing this, you're adding a new property in the synthetic " +
'event object. The property is never released. ' +
'See https://fb.me/react-event-pooling for more information.',
);
} else {
e.foo = 'bar';
}
syntheticEvent = e;
expectedCount++;
};
node = ReactDOM.render(<div onClick={eventHandler} />, container);
const event = document.createEvent('Event');
event.initEvent('click', true, true);
node.dispatchEvent(event);
expect(syntheticEvent.foo).toBe('bar');
expect(expectedCount).toBe(1);
});
});
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["Swup"] = factory();
else
root["Swup"] = factory();
})(window, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 2);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Link = exports.markSwupElements = exports.getCurrentUrl = exports.transitionEnd = exports.fetch = exports.getDataFromHTML = exports.createHistoryRecord = exports.classify = undefined;
var _classify = __webpack_require__(8);
var _classify2 = _interopRequireDefault(_classify);
var _createHistoryRecord = __webpack_require__(9);
var _createHistoryRecord2 = _interopRequireDefault(_createHistoryRecord);
var _getDataFromHTML = __webpack_require__(10);
var _getDataFromHTML2 = _interopRequireDefault(_getDataFromHTML);
var _fetch = __webpack_require__(11);
var _fetch2 = _interopRequireDefault(_fetch);
var _transitionEnd = __webpack_require__(12);
var _transitionEnd2 = _interopRequireDefault(_transitionEnd);
var _getCurrentUrl = __webpack_require__(13);
var _getCurrentUrl2 = _interopRequireDefault(_getCurrentUrl);
var _markSwupElements = __webpack_require__(14);
var _markSwupElements2 = _interopRequireDefault(_markSwupElements);
var _Link = __webpack_require__(15);
var _Link2 = _interopRequireDefault(_Link);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var classify = exports.classify = _classify2.default;
var createHistoryRecord = exports.createHistoryRecord = _createHistoryRecord2.default;
var getDataFromHTML = exports.getDataFromHTML = _getDataFromHTML2.default;
var fetch = exports.fetch = _fetch2.default;
var transitionEnd = exports.transitionEnd = _transitionEnd2.default;
var getCurrentUrl = exports.getCurrentUrl = _getCurrentUrl2.default;
var markSwupElements = exports.markSwupElements = _markSwupElements2.default;
var Link = exports.Link = _Link2.default;
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var query = exports.query = function query(selector) {
var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document;
if (typeof selector !== 'string') {
return selector;
}
return context.querySelector(selector);
};
var queryAll = exports.queryAll = function queryAll(selector) {
var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document;
if (typeof selector !== 'string') {
return selector;
}
return Array.prototype.slice.call(context.querySelectorAll(selector));
};
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _index = __webpack_require__(3);
var _index2 = _interopRequireDefault(_index);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = _index2.default; // this is here for webpack to expose Swup as window.Swup
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
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; }; }();
// modules
var _delegate = __webpack_require__(4);
var _delegate2 = _interopRequireDefault(_delegate);
var _cache = __webpack_require__(6);
var _cache2 = _interopRequireDefault(_cache);
var _loadPage = __webpack_require__(7);
var _loadPage2 = _interopRequireDefault(_loadPage);
var _renderPage = __webpack_require__(16);
var _renderPage2 = _interopRequireDefault(_renderPage);
var _triggerEvent = __webpack_require__(17);
var _triggerEvent2 = _interopRequireDefault(_triggerEvent);
var _on = __webpack_require__(18);
var _on2 = _interopRequireDefault(_on);
var _off = __webpack_require__(19);
var _off2 = _interopRequireDefault(_off);
var _updateTransition = __webpack_require__(20);
var _updateTransition2 = _interopRequireDefault(_updateTransition);
var _getAnimationPromises = __webpack_require__(21);
var _getAnimationPromises2 = _interopRequireDefault(_getAnimationPromises);
var _getPageData = __webpack_require__(22);
var _getPageData2 = _interopRequireDefault(_getPageData);
var _plugins = __webpack_require__(23);
var _utils = __webpack_require__(1);
var _helpers = __webpack_require__(0);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Swup = function () {
function Swup(setOptions) {
_classCallCheck(this, Swup);
// default options
var defaults = {
animateHistoryBrowsing: false,
animationSelector: '[class*="transition-"]',
linkSelector: 'a[href^="' + window.location.origin + '"]:not([data-no-swup]), a[href^="/"]:not([data-no-swup]), a[href^="#"]:not([data-no-swup])',
cache: true,
containers: ['#swup'],
requestHeaders: {
'X-Requested-With': 'swup',
Accept: 'text/html, application/xhtml+xml'
},
plugins: [],
skipPopStateHandling: function skipPopStateHandling(event) {
return !(event.state && event.state.source === 'swup');
}
};
// merge options
var options = _extends({}, defaults, setOptions);
// handler arrays
this._handlers = {
animationInDone: [],
animationInStart: [],
animationOutDone: [],
animationOutStart: [],
animationSkipped: [],
clickLink: [],
contentReplaced: [],
disabled: [],
enabled: [],
openPageInNewTab: [],
pageLoaded: [],
pageRetrievedFromCache: [],
pageView: [],
popState: [],
samePage: [],
samePageWithHash: [],
serverError: [],
transitionStart: [],
transitionEnd: [],
willReplaceContent: []
};
// variable for id of element to scroll to after render
this.scrollToElement = null;
// variable for promise used for preload, so no new loading of the same page starts while page is loading
this.preloadPromise = null;
// variable for save options
this.options = options;
// variable for plugins array
this.plugins = [];
// variable for current transition object
this.transition = {};
// variable for keeping event listeners from "delegate"
this.delegatedListeners = {};
// make modules accessible in instance
this.cache = new _cache2.default();
this.cache.swup = this;
this.loadPage = _loadPage2.default;
this.renderPage = _renderPage2.default;
this.triggerEvent = _triggerEvent2.default;
this.on = _on2.default;
this.off = _off2.default;
this.updateTransition = _updateTransition2.default;
this.getAnimationPromises = _getAnimationPromises2.default;
this.getPageData = _getPageData2.default;
this.log = function () {}; // here so it can be used by plugins
this.use = _plugins.use;
this.unuse = _plugins.unuse;
this.findPlugin = _plugins.findPlugin;
// enable swup
this.enable();
}
_createClass(Swup, [{
key: 'enable',
value: function enable() {
var _this = this;
// check for Promise support
if (typeof Promise === 'undefined') {
console.warn('Promise is not supported');
return;
}
// add event listeners
this.delegatedListeners.click = (0, _delegate2.default)(document, this.options.linkSelector, 'click', this.linkClickHandler.bind(this));
window.addEventListener('popstate', this.popStateHandler.bind(this));
// initial save to cache
var page = (0, _helpers.getDataFromHTML)(document.documentElement.outerHTML, this.options.containers);
page.url = page.responseURL = (0, _helpers.getCurrentUrl)();
if (this.options.cache) {
this.cache.cacheUrl(page);
}
// mark swup blocks in html
(0, _helpers.markSwupElements)(document.documentElement, this.options.containers);
// mount plugins
this.options.plugins.forEach(function (plugin) {
_this.use(plugin);
});
// modify initial history record
window.history.replaceState(Object.assign({}, window.history.state, {
url: window.location.href,
random: Math.random(),
source: 'swup'
}), document.title, window.location.href);
// trigger enabled event
this.triggerEvent('enabled');
// add swup-enabled class to html tag
document.documentElement.classList.add('swup-enabled');
// trigger page view event
this.triggerEvent('pageView');
}
}, {
key: 'destroy',
value: function destroy() {
var _this2 = this;
// remove delegated listeners
this.delegatedListeners.click.destroy();
this.delegatedListeners.mouseover.destroy();
// remove popstate listener
window.removeEventListener('popstate', this.popStateHandler.bind(this));
// empty cache
this.cache.empty();
// unmount plugins
this.options.plugins.forEach(function (plugin) {
_this2.unuse(plugin);
});
// remove swup data atributes from blocks
(0, _utils.queryAll)('[data-swup]').forEach(function (element) {
delete element.dataset.swup;
});
// remove handlers
this.off();
// trigger disable event
this.triggerEvent('disabled');
// remove swup-enabled class from html tag
document.documentElement.classList.remove('swup-enabled');
}
}, {
key: 'linkClickHandler',
value: function linkClickHandler(event) {
// no control key pressed
if (!event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey) {
// index of pressed button needs to be checked because Firefox triggers click on all mouse buttons
if (event.button === 0) {
this.triggerEvent('clickLink', event);
event.preventDefault();
var link = new _helpers.Link(event.delegateTarget);
if (link.getAddress() == (0, _helpers.getCurrentUrl)() || link.getAddress() == '') {
// link to the same URL
if (link.getHash() != '') {
// link to the same URL with hash
this.triggerEvent('samePageWithHash', event);
var element = document.querySelector(link.getHash());
if (element != null) {
history.replaceState({
url: link.getAddress() + link.getHash(),
random: Math.random(),
source: 'swup'
}, document.title, link.getAddress() + link.getHash());
} else {
// referenced element not found
console.warn('Element for offset not found (' + link.getHash() + ')');
}
} else {
// link to the same URL without hash
this.triggerEvent('samePage', event);
}
} else {
// link to different url
if (link.getHash() != '') {
this.scrollToElement = link.getHash();
}
// get custom transition from data
var customTransition = event.delegateTarget.dataset.swupTransition;
// load page
this.loadPage({ url: link.getAddress(), customTransition: customTransition }, false);
}
}
} else {
// open in new tab (do nothing)
this.triggerEvent('openPageInNewTab', event);
}
}
}, {
key: 'popStateHandler',
value: function popStateHandler(event) {
if (this.options.skipPopStateHandling(event)) return;
var link = new _helpers.Link(event.state ? event.state.url : window.location.pathname);
if (link.getHash() !== '') {
this.scrollToElement = link.getHash();
} else {
event.preventDefault();
}
this.triggerEvent('popState', event);
this.loadPage({ url: link.getAddress() }, event);
}
}]);
return Swup;
}();
exports.default = Swup;
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
var closest = __webpack_require__(5);
/**
* Delegates event to a selector.
*
* @param {Element} element
* @param {String} selector
* @param {String} type
* @param {Function} callback
* @param {Boolean} useCapture
* @return {Object}
*/
function delegate(element, selector, type, callback, useCapture) {
var listenerFn = listener.apply(this, arguments);
element.addEventListener(type, listenerFn, useCapture);
return {
destroy: function() {
element.removeEventListener(type, listenerFn, useCapture);
}
}
}
/**
* Finds closest match and invokes callback.
*
* @param {Element} element
* @param {String} selector
* @param {String} type
* @param {Function} callback
* @return {Function}
*/
function listener(element, selector, type, callback) {
return function(e) {
e.delegateTarget = closest(e.target, selector);
if (e.delegateTarget) {
callback.call(element, e);
}
}
}
module.exports = delegate;
/***/ }),
/* 5 */
/***/ (function(module, exports) {
var DOCUMENT_NODE_TYPE = 9;
/**
* A polyfill for Element.matches()
*/
if (typeof Element !== 'undefined' && !Element.prototype.matches) {
var proto = Element.prototype;
proto.matches = proto.matchesSelector ||
proto.mozMatchesSelector ||
proto.msMatchesSelector ||
proto.oMatchesSelector ||
proto.webkitMatchesSelector;
}
/**
* Finds the closest parent that matches a selector.
*
* @param {Element} element
* @param {String} selector
* @return {Function}
*/
function closest (element, selector) {
while (element && element.nodeType !== DOCUMENT_NODE_TYPE) {
if (typeof element.matches === 'function' &&
element.matches(selector)) {
return element;
}
element = element.parentNode;
}
}
module.exports = closest;
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Cache = exports.Cache = function () {
function Cache() {
_classCallCheck(this, Cache);
this.pages = {};
this.last = null;
}
_createClass(Cache, [{
key: 'cacheUrl',
value: function cacheUrl(page) {
if (page.url in this.pages === false) {
this.pages[page.url] = page;
}
this.last = this.pages[page.url];
this.swup.log('Cache (' + Object.keys(this.pages).length + ')', this.pages);
}
}, {
key: 'getPage',
value: function getPage(url) {
return this.pages[url];
}
}, {
key: 'getCurrentPage',
value: function getCurrentPage() {
return this.getPage(window.location.pathname + window.location.search);
}
}, {
key: 'exists',
value: function exists(url) {
return url in this.pages;
}
}, {
key: 'empty',
value: function empty() {
this.pages = {};
this.last = null;
this.swup.log('Cache cleared');
}
}, {
key: 'remove',
value: function remove(url) {
delete this.pages[url];
}
}]);
return Cache;
}();
exports.default = Cache;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _helpers = __webpack_require__(0);
var loadPage = function loadPage(data, popstate) {
var _this = this;
// create array for storing animation promises
var animationPromises = [],
xhrPromise = void 0;
var animateOut = function animateOut() {
_this.triggerEvent('animationOutStart');
// handle classes
document.documentElement.classList.add('is-changing');
document.documentElement.classList.add('is-leaving');
document.documentElement.classList.add('is-animating');
if (popstate) {
document.documentElement.classList.add('is-popstate');
}
document.documentElement.classList.add('to-' + (0, _helpers.classify)(data.url));
// animation promise stuff
animationPromises = _this.getAnimationPromises('out');
Promise.all(animationPromises).then(function () {
_this.triggerEvent('animationOutDone');
});
// create history record if this is not a popstate call
if (!popstate) {
// create pop element with or without anchor
var state = void 0;
if (_this.scrollToElement != null) {
state = data.url + _this.scrollToElement;
} else {
state = data.url;
}
(0, _helpers.createHistoryRecord)(state);
}
};
this.triggerEvent('transitionStart', popstate);
// set transition object
if (data.customTransition != null) {
this.updateTransition(window.location.pathname, data.url, data.customTransition);
document.documentElement.classList.add('to-' + (0, _helpers.classify)(data.customTransition));
} else {
this.updateTransition(window.location.pathname, data.url);
}
// start/skip animation
if (!popstate || this.options.animateHistoryBrowsing) {
animateOut();
} else {
this.triggerEvent('animationSkipped');
}
// start/skip loading of page
if (this.cache.exists(data.url)) {
xhrPromise = new Promise(function (resolve) {
resolve();
});
this.triggerEvent('pageRetrievedFromCache');
} else {
if (!this.preloadPromise || this.preloadPromise.route != data.url) {
xhrPromise = new Promise(function (resolve, reject) {
(0, _helpers.fetch)(_extends({}, data, { headers: _this.options.requestHeaders }), function (response) {
if (response.status === 500) {
_this.triggerEvent('serverError');
reject(data.url);
return;
} else {
// get json data
var page = _this.getPageData(response);
if (page != null) {
page.url = data.url;
} else {
reject(data.url);
return;
}
// render page
_this.cache.cacheUrl(page);
_this.triggerEvent('pageLoaded');
}
resolve();
});
});
} else {
xhrPromise = this.preloadPromise;
}
}
// when everything is ready, handle the outcome
Promise.all(animationPromises.concat([xhrPromise])).then(function () {
// render page
_this.renderPage(_this.cache.getPage(data.url), popstate);
_this.preloadPromise = null;
}).catch(function (errorUrl) {
// rewrite the skipPopStateHandling function to redirect manually when the history.go is processed
_this.options.skipPopStateHandling = function () {
window.location = errorUrl;
return true;
};
// go back to the actual page were still at
window.history.go(-1);
});
};
exports.default = loadPage;
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var classify = function classify(text) {
var output = text.toString().toLowerCase().replace(/\s+/g, '-') // Replace spaces with -
.replace(/\//g, '-') // Replace / with -
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
if (output[0] === '/') output = output.splice(1);
if (output === '') output = 'homepage';
return output;
};
exports.default = classify;
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var createHistoryRecord = function createHistoryRecord(url) {
window.history.pushState({
url: url || window.location.href.split(window.location.hostname)[1],
random: Math.random(),
source: 'swup'
}, document.getElementsByTagName('title')[0].innerText, url || window.location.href.split(window.location.hostname)[1]);
};
exports.default = createHistoryRecord;
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _utils = __webpack_require__(1);
var getDataFromHTML = function getDataFromHTML(html, containers) {
var content = html.replace('<body', '<div id="swupBody"').replace('</body>', '</div>');
var fakeDom = document.createElement('div');
fakeDom.innerHTML = content;
var blocks = [];
var _loop = function _loop(i) {
if (fakeDom.querySelector(containers[i]) == null) {
// page in invalid
return {
v: null
};
} else {
(0, _utils.queryAll)(containers[i]).forEach(function (item, index) {
(0, _utils.queryAll)(containers[i], fakeDom)[index].dataset.swup = blocks.length; // marks element with data-swup
blocks.push((0, _utils.queryAll)(containers[i], fakeDom)[index].outerHTML);
});
}
};
for (var i = 0; i < containers.length; i++) {
var _ret = _loop(i);
if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
}
var json = {
title: fakeDom.querySelector('title').innerText,
pageClass: fakeDom.querySelector('#swupBody').className,
originalContent: html,
blocks: blocks
};
// to prevent memory leaks
fakeDom.innerHTML = '';
fakeDom = null;
return json;
};
exports.default = getDataFromHTML;
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var fetch = function fetch(setOptions) {
var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var defaults = {
url: window.location.pathname + window.location.search,
method: 'GET',
data: null,
headers: {}
};
var options = _extends({}, defaults, setOptions);
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request.status !== 500) {
callback(request);
} else {
callback(request);
}
}
};
request.open(options.method, options.url, true);
Object.keys(options.headers).forEach(function (key) {
request.setRequestHeader(key, options.headers[key]);
});
request.send(options.data);
return request;
};
exports.default = fetch;
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var transitionEnd = function transitionEnd() {
var el = document.createElement('div');
var transEndEventNames = {
WebkitTransition: 'webkitTransitionEnd',
MozTransition: 'transitionend',
OTransition: 'oTransitionEnd otransitionend',
transition: 'transitionend'
};
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return transEndEventNames[name];
}
}
return false;
};
exports.default = transitionEnd;
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var getCurrentUrl = function getCurrentUrl() {
return window.location.pathname + window.location.search;
};
exports.default = getCurrentUrl;
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _utils = __webpack_require__(1);
var markSwupElements = function markSwupElements(element, containers) {
var blocks = 0;
var _loop = function _loop(i) {
if (element.querySelector(containers[i]) == null) {
console.warn('Element ' + containers[i] + ' is not in current page.');
} else {
(0, _utils.queryAll)(containers[i]).forEach(function (item, index) {
(0, _utils.queryAll)(containers[i], element)[index].dataset.swup = blocks;
blocks++;
});
}
};
for (var i = 0; i < containers.length; i++) {
_loop(i);
}
};
exports.default = markSwupElements;
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Link = function () {
function Link(elementOrUrl) {
_classCallCheck(this, Link);
if (elementOrUrl instanceof Element || elementOrUrl instanceof SVGElement) {
this.link = elementOrUrl;
} else {
this.link = document.createElement('a');
this.link.href = elementOrUrl;
}
}
_createClass(Link, [{
key: 'getPath',
value: function getPath() {
var path = this.link.pathname;
if (path[0] !== '/') {
path = '/' + path;
}
return path;
}
}, {
key: 'getAddress',
value: function getAddress() {
var path = this.link.pathname + this.link.search;
if (this.link.getAttribute('xlink:href')) {
path = this.link.getAttribute('xlink:href');
}
if (path[0] !== '/') {
path = '/' + path;
}
return path;
}
}, {
key: 'getHash',
value: function getHash() {
return this.link.hash;
}
}]);
return Link;
}();
exports.default = Link;
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _utils = __webpack_require__(1);
var _helpers = __webpack_require__(0);
var renderPage = function renderPage(page, popstate) {
var _this = this;
document.documentElement.classList.remove('is-leaving');
// replace state in case the url was redirected
var link = new _helpers.Link(page.responseURL);
if (window.location.pathname !== link.getPath()) {
window.history.replaceState({
url: link.getPath(),
random: Math.random(),
source: 'swup'
}, document.title, link.getPath());
// save new record for redirected url
this.cache.cacheUrl(_extends({}, page, { url: link.getPath() }));
}
// only add for non-popstate transitions
if (!popstate || this.options.animateHistoryBrowsing) {
document.documentElement.classList.add('is-rendering');
}
this.triggerEvent('willReplaceContent', popstate);
// replace blocks
for (var i = 0; i < page.blocks.length; i++) {
document.body.querySelector('[data-swup="' + i + '"]').outerHTML = page.blocks[i];
}
// set title
document.title = page.title;
this.triggerEvent('contentReplaced', popstate);
this.triggerEvent('pageView', popstate);
// empty cache if it's disabled (because pages could be preloaded and stuff)
if (!this.options.cache) {
this.cache.empty();
}
// start animation IN
setTimeout(function () {
if (!popstate || _this.options.animateHistoryBrowsing) {
_this.triggerEvent('animationInStart');
document.documentElement.classList.remove('is-animating');
}
}, 10);
// handle end of animation
var animationPromises = this.getAnimationPromises('in');
if (!popstate || this.options.animateHistoryBrowsing) {
Promise.all(animationPromises).then(function () {
_this.triggerEvent('animationInDone');
_this.triggerEvent('transitionEnd', popstate);
// remove "to-{page}" classes
document.documentElement.className.split(' ').forEach(function (classItem) {
if (new RegExp('^to-').test(classItem) || classItem === 'is-changing' || classItem === 'is-rendering' || classItem === 'is-popstate') {
document.documentElement.classList.remove(classItem);
}
});
});
} else {
this.triggerEvent('transitionEnd', popstate);
}
// reset scroll-to element
this.scrollToElement = null;
};
exports.default = renderPage;
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var triggerEvent = function triggerEvent(eventName, originalEvent) {
// call saved handlers with "on" method and pass originalEvent object if available
this._handlers[eventName].forEach(function (handler) {
try {
handler(originalEvent);
} catch (error) {
console.error(error);
}
});
// trigger event on document with prefix "swup:"
var event = new CustomEvent('swup:' + eventName, { detail: eventName });
document.dispatchEvent(event);
};
exports.default = triggerEvent;
/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var on = function on(event, handler) {
if (this._handlers[event]) {
this._handlers[event].push(handler);
} else {
console.warn("Unsupported event " + event + ".");
}
};
exports.default = on;
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var off = function off(event, handler) {
var _this = this;
if (event != null) {
if (handler != null) {
if (this._handlers[event] && this._handlers[event].filter(function (savedHandler) {
return savedHandler === handler;
}).length) {
var toRemove = this._handlers[event].filter(function (savedHandler) {
return savedHandler === handler;
})[0];
var index = this._handlers[event].indexOf(toRemove);
if (index > -1) {
this._handlers[event].splice(index, 1);
}
} else {
console.warn("Handler for event '" + event + "' no found.");
}
} else {
this._handlers[event] = [];
}
} else {
Object.keys(this._handlers).forEach(function (keys) {
_this._handlers[keys] = [];
});
}
};
exports.default = off;
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var updateTransition = function updateTransition(from, to, custom) {
// transition routes
this.transition = {
from: from,
to: to,
custom: custom
};
};
exports.default = updateTransition;
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _utils = __webpack_require__(1);
var _helpers = __webpack_require__(0);
var getAnimationPromises = function getAnimationPromises() {
var promises = [];
var animatedElements = (0, _utils.queryAll)(this.options.animationSelector);
animatedElements.forEach(function (element) {
var promise = new Promise(function (resolve) {
element.addEventListener((0, _helpers.transitionEnd)(), function (event) {
if (element == event.target) {
resolve();
}
});
});
promises.push(promise);
});
return promises;
};
exports.default = getAnimationPromises;
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _helpers = __webpack_require__(0);
var getPageData = function getPageData(request) {
// this method can be replaced in case other content than html is expected to be received from server
// this function should always return {title, pageClass, originalContent, blocks, responseURL}
// in case page has invalid structure - return null
var html = request.responseText;
var pageObject = (0, _helpers.getDataFromHTML)(html, this.options.containers);
if (pageObject) {
pageObject.responseURL = request.responseURL ? request.responseURL : window.location.href;
} else {
console.warn('Received page is invalid.');
return null;
}
return pageObject;
};
exports.default = getPageData;
/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var use = exports.use = function use(plugin) {
if (!plugin.isSwupPlugin) {
console.warn('Not swup plugin instance ' + plugin + '.');
return;
}
this.plugins.push(plugin);
plugin.swup = this;
if (typeof plugin._beforeMount === 'function') {
plugin._beforeMount();
}
plugin.mount();
return this.plugins;
};
var unuse = exports.unuse = function unuse(plugin) {
var pluginReference = void 0;
if (typeof plugin === 'string') {
pluginReference = this.plugins.find(function (p) {
return plugin === p.name;
});
} else {
pluginReference = plugin;
}
if (!pluginReference) {
console.warn('No such plugin.');
return;
}
pluginReference.unmount();
if (typeof pluginReference._afterUnmount === 'function') {
pluginReference._afterUnmount();
}
var index = this.plugins.indexOf(pluginReference);
this.plugins.splice(index, 1);
return this.plugins;
};
var findPlugin = exports.findPlugin = function findPlugin(pluginName) {
return this.plugins.find(function (p) {
return pluginName === p.name;
});
};
/***/ })
/******/ ]);
}); |
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import capitalize from '../utils/capitalize';
import Modal from '../Modal';
import Backdrop from '../Backdrop';
import Fade from '../Fade';
import { duration } from '../styles/transitions';
import Paper from '../Paper';
export var styles = function styles(theme) {
return {
/* Styles applied to the root element. */
root: {
'@media print': {
// Use !important to override the Modal inline-style.
position: 'absolute !important'
}
},
/* Styles applied to the container element if `scroll="paper"`. */
scrollPaper: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center'
},
/* Styles applied to the container element if `scroll="body"`. */
scrollBody: {
overflowY: 'auto',
overflowX: 'hidden',
textAlign: 'center',
'&:after': {
content: '""',
display: 'inline-block',
verticalAlign: 'middle',
height: '100%',
width: '0'
}
},
/* Styles applied to the container element. */
container: {
height: '100%',
'@media print': {
height: 'auto'
},
// We disable the focus ring for mouse, touch and keyboard users.
outline: 0
},
/* Styles applied to the `Paper` component. */
paper: {
margin: 32,
position: 'relative',
overflowY: 'auto',
// Fix IE11 issue, to remove at some point.
'@media print': {
overflowY: 'visible',
boxShadow: 'none'
}
},
/* Styles applied to the `Paper` component if `scroll="paper"`. */
paperScrollPaper: {
display: 'flex',
flexDirection: 'column',
maxHeight: 'calc(100% - 64px)'
},
/* Styles applied to the `Paper` component if `scroll="body"`. */
paperScrollBody: {
display: 'inline-block',
verticalAlign: 'middle',
textAlign: 'left' // 'initial' doesn't work on IE11
},
/* Styles applied to the `Paper` component if `maxWidth=false`. */
paperWidthFalse: {
maxWidth: 'calc(100% - 64px)'
},
/* Styles applied to the `Paper` component if `maxWidth="xs"`. */
paperWidthXs: {
maxWidth: Math.max(theme.breakpoints.values.xs, 444),
'&$paperScrollBody': _defineProperty({}, theme.breakpoints.down(Math.max(theme.breakpoints.values.xs, 444) + 32 * 2), {
maxWidth: 'calc(100% - 64px)'
})
},
/* Styles applied to the `Paper` component if `maxWidth="sm"`. */
paperWidthSm: {
maxWidth: theme.breakpoints.values.sm,
'&$paperScrollBody': _defineProperty({}, theme.breakpoints.down(theme.breakpoints.values.sm + 32 * 2), {
maxWidth: 'calc(100% - 64px)'
})
},
/* Styles applied to the `Paper` component if `maxWidth="md"`. */
paperWidthMd: {
maxWidth: theme.breakpoints.values.md,
'&$paperScrollBody': _defineProperty({}, theme.breakpoints.down(theme.breakpoints.values.md + 32 * 2), {
maxWidth: 'calc(100% - 64px)'
})
},
/* Styles applied to the `Paper` component if `maxWidth="lg"`. */
paperWidthLg: {
maxWidth: theme.breakpoints.values.lg,
'&$paperScrollBody': _defineProperty({}, theme.breakpoints.down(theme.breakpoints.values.lg + 32 * 2), {
maxWidth: 'calc(100% - 64px)'
})
},
/* Styles applied to the `Paper` component if `maxWidth="xl"`. */
paperWidthXl: {
maxWidth: theme.breakpoints.values.xl,
'&$paperScrollBody': _defineProperty({}, theme.breakpoints.down(theme.breakpoints.values.xl + 32 * 2), {
maxWidth: 'calc(100% - 64px)'
})
},
/* Styles applied to the `Paper` component if `fullWidth={true}`. */
paperFullWidth: {
width: 'calc(100% - 64px)'
},
/* Styles applied to the `Paper` component if `fullScreen={true}`. */
paperFullScreen: {
margin: 0,
width: '100%',
maxWidth: '100%',
height: '100%',
maxHeight: 'none',
borderRadius: 0,
'&$paperScrollBody': {
margin: 0,
maxWidth: '100%'
}
}
};
};
var defaultTransitionDuration = {
enter: duration.enteringScreen,
exit: duration.leavingScreen
};
/**
* Dialogs are overlaid modal paper based components with a backdrop.
*/
var Dialog = /*#__PURE__*/React.forwardRef(function Dialog(props, ref) {
var BackdropProps = props.BackdropProps,
children = props.children,
classes = props.classes,
className = props.className,
_props$disableBackdro = props.disableBackdropClick,
disableBackdropClick = _props$disableBackdro === void 0 ? false : _props$disableBackdro,
_props$disableEscapeK = props.disableEscapeKeyDown,
disableEscapeKeyDown = _props$disableEscapeK === void 0 ? false : _props$disableEscapeK,
_props$fullScreen = props.fullScreen,
fullScreen = _props$fullScreen === void 0 ? false : _props$fullScreen,
_props$fullWidth = props.fullWidth,
fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth,
_props$maxWidth = props.maxWidth,
maxWidth = _props$maxWidth === void 0 ? 'sm' : _props$maxWidth,
onBackdropClick = props.onBackdropClick,
onClose = props.onClose,
onEscapeKeyDown = props.onEscapeKeyDown,
open = props.open,
_props$PaperComponent = props.PaperComponent,
PaperComponent = _props$PaperComponent === void 0 ? Paper : _props$PaperComponent,
_props$PaperProps = props.PaperProps,
PaperProps = _props$PaperProps === void 0 ? {} : _props$PaperProps,
_props$scroll = props.scroll,
scroll = _props$scroll === void 0 ? 'paper' : _props$scroll,
_props$TransitionComp = props.TransitionComponent,
TransitionComponent = _props$TransitionComp === void 0 ? Fade : _props$TransitionComp,
_props$transitionDura = props.transitionDuration,
transitionDuration = _props$transitionDura === void 0 ? defaultTransitionDuration : _props$transitionDura,
TransitionProps = props.TransitionProps,
ariaDescribedby = props['aria-describedby'],
ariaLabelledby = props['aria-labelledby'],
other = _objectWithoutProperties(props, ["BackdropProps", "children", "classes", "className", "disableBackdropClick", "disableEscapeKeyDown", "fullScreen", "fullWidth", "maxWidth", "onBackdropClick", "onClose", "onEscapeKeyDown", "open", "PaperComponent", "PaperProps", "scroll", "TransitionComponent", "transitionDuration", "TransitionProps", "aria-describedby", "aria-labelledby"]);
var backdropClick = React.useRef();
var handleMouseDown = function handleMouseDown(event) {
// We don't want to close the dialog when clicking the dialog content.
// Make sure the event starts and ends on the same DOM element.
backdropClick.current = event.target === event.currentTarget;
};
var handleBackdropClick = function handleBackdropClick(event) {
// Ignore the events not coming from the "backdrop".
if (!backdropClick.current) {
return;
}
backdropClick.current = null;
if (onBackdropClick) {
onBackdropClick(event);
}
if (!disableBackdropClick && onClose) {
onClose(event, 'backdropClick');
}
};
return /*#__PURE__*/React.createElement(Modal, _extends({
className: clsx(classes.root, className),
BackdropComponent: Backdrop,
BackdropProps: _extends({
transitionDuration: transitionDuration
}, BackdropProps),
closeAfterTransition: true,
disableBackdropClick: disableBackdropClick,
disableEscapeKeyDown: disableEscapeKeyDown,
onEscapeKeyDown: onEscapeKeyDown,
onClose: onClose,
open: open,
ref: ref,
onClick: handleBackdropClick
}, other), /*#__PURE__*/React.createElement(TransitionComponent, _extends({
appear: true,
in: open,
timeout: transitionDuration,
role: "none presentation"
}, TransitionProps), /*#__PURE__*/React.createElement("div", {
className: clsx(classes.container, classes["scroll".concat(capitalize(scroll))]),
onMouseDown: handleMouseDown
}, /*#__PURE__*/React.createElement(PaperComponent, _extends({
elevation: 24,
role: "dialog",
"aria-describedby": ariaDescribedby,
"aria-labelledby": ariaLabelledby
}, PaperProps, {
className: clsx(classes.paper, classes["paperScroll".concat(capitalize(scroll))], classes["paperWidth".concat(capitalize(String(maxWidth)))], PaperProps.className, fullScreen && classes.paperFullScreen, fullWidth && classes.paperFullWidth)
}), children))));
});
process.env.NODE_ENV !== "production" ? Dialog.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The id(s) of the element(s) that describe the dialog.
*/
'aria-describedby': PropTypes.string,
/**
* The id(s) of the element(s) that label the dialog.
*/
'aria-labelledby': PropTypes.string,
/**
* @ignore
*/
BackdropProps: PropTypes.object,
/**
* Dialog children, usually the included sub-components.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* If `true`, clicking the backdrop will not fire the `onClose` callback.
* @default false
*/
disableBackdropClick: PropTypes.bool,
/**
* If `true`, hitting escape will not fire the `onClose` callback.
* @default false
*/
disableEscapeKeyDown: PropTypes.bool,
/**
* If `true`, the dialog will be full-screen
* @default false
*/
fullScreen: PropTypes.bool,
/**
* If `true`, the dialog stretches to `maxWidth`.
*
* Notice that the dialog width grow is limited by the default margin.
* @default false
*/
fullWidth: PropTypes.bool,
/**
* Determine the max-width of the dialog.
* The dialog width grows with the size of the screen.
* Set to `false` to disable `maxWidth`.
* @default 'sm'
*/
maxWidth: PropTypes.oneOf(['lg', 'md', 'sm', 'xl', 'xs', false]),
/**
* Callback fired when the backdrop is clicked.
*/
onBackdropClick: PropTypes.func,
/**
* Callback fired when the component requests to be closed.
*
* @param {object} event The event source of the callback.
* @param {string} reason Can be: `"escapeKeyDown"`, `"backdropClick"`.
*/
onClose: PropTypes.func,
/**
* Callback fired when the escape key is pressed,
* `disableKeyboard` is false and the modal is in focus.
*/
onEscapeKeyDown: PropTypes.func,
/**
* If `true`, the Dialog is open.
*/
open: PropTypes.bool.isRequired,
/**
* The component used to render the body of the dialog.
* @default Paper
*/
PaperComponent: PropTypes.elementType,
/**
* Props applied to the [`Paper`](/api/paper/) element.
* @default {}
*/
PaperProps: PropTypes.object,
/**
* Determine the container for scrolling the dialog.
* @default 'paper'
*/
scroll: PropTypes.oneOf(['body', 'paper']),
/**
* The component used for the transition.
* [Follow this guide](/components/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.
* @default Fade
*/
TransitionComponent: PropTypes.elementType,
/**
* The duration for the transition, in milliseconds.
* You may specify a single timeout for all transitions, or individually with an object.
* @default { enter: duration.enteringScreen, exit: duration.leavingScreen }
*/
transitionDuration: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({
appear: PropTypes.number,
enter: PropTypes.number,
exit: PropTypes.number
})]),
/**
* Props applied to the transition element.
* By default, the element is based on this [`Transition`](http://reactcommunity.org/react-transition-group/transition) component.
*/
TransitionProps: PropTypes.object
} : void 0;
export default withStyles(styles, {
name: 'MuiDialog'
})(Dialog); |
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import { isFragment } from 'react-is';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled';
import capitalize from '../utils/capitalize';
import { alpha } from '../styles/colorManipulator';
import styled from '../styles/styled';
import useThemeProps from '../styles/useThemeProps';
import buttonGroupClasses, { getButtonGroupUtilityClass } from './buttonGroupClasses';
import { jsx as _jsx } from "react/jsx-runtime";
const overridesResolver = (props, styles) => {
const {
styleProps
} = props;
return _extends({
[`& .${buttonGroupClasses.grouped}`]: _extends({}, styles.grouped, styles[`grouped${capitalize(styleProps.orientation)}`], styles[`grouped${capitalize(styleProps.variant)}`], styles[`grouped${capitalize(styleProps.variant)}${capitalize(styleProps.orientation)}`], styles[`grouped${capitalize(styleProps.variant)}${capitalize(styleProps.color)}`])
}, styles.root, styles[styleProps.variant], styleProps.disableElevation === true && styles.disableElevation, styleProps.fullWidth && styles.fullWidth, styleProps.orientation === 'vertical' && styles.vertical);
};
const useUtilityClasses = styleProps => {
const {
classes,
color,
disabled,
disableElevation,
fullWidth,
orientation,
variant
} = styleProps;
const slots = {
root: ['root', variant, orientation === 'vertical' && 'vertical', fullWidth && 'fullWidth', disableElevation && 'disableElevation'],
grouped: ['grouped', `grouped${capitalize(orientation)}`, `grouped${capitalize(variant)}`, `grouped${capitalize(variant)}${capitalize(orientation)}`, color !== 'default' && `grouped${capitalize(variant)}${capitalize(color)}`, disabled && 'disabled']
};
return composeClasses(slots, getButtonGroupUtilityClass, classes);
};
const ButtonGroupRoot = styled('div', {
name: 'MuiButtonGroup',
slot: 'Root',
overridesResolver
})(({
theme,
styleProps
}) => _extends({
display: 'inline-flex',
borderRadius: theme.shape.borderRadius
}, styleProps.variant === 'contained' && {
boxShadow: theme.shadows[2]
}, styleProps.disableElevation && {
boxShadow: 'none'
}, styleProps.fullWidth && {
width: '100%'
}, styleProps.orientation === 'vertical' && {
flexDirection: 'column'
}, {
[`& .${buttonGroupClasses.grouped}`]: _extends({
minWidth: 40,
'&:not(:first-of-type)': _extends({}, styleProps.orientation === 'horizontal' && {
borderTopLeftRadius: 0,
borderBottomLeftRadius: 0
}, styleProps.orientation === 'vertical' && {
borderTopRightRadius: 0,
borderTopLeftRadius: 0
}, styleProps.variant === 'outlined' && styleProps.orientation === 'horizontal' && {
marginLeft: -1
}, styleProps.variant === 'outlined' && styleProps.orientation === 'vertical' && {
marginTop: -1
}),
'&:not(:last-of-type)': _extends({}, styleProps.orientation === 'horizontal' && {
borderTopRightRadius: 0,
borderBottomRightRadius: 0
}, styleProps.orientation === 'vertical' && {
borderBottomRightRadius: 0,
borderBottomLeftRadius: 0
}, styleProps.variant === 'text' && styleProps.orientation === 'horizontal' && {
borderRight: `1px solid ${theme.palette.mode === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)'}`
}, styleProps.variant === 'text' && styleProps.orientation === 'vertical' && {
borderBottom: `1px solid ${theme.palette.mode === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)'}`
}, styleProps.variant === 'text' && styleProps.color !== 'inherit' && {
borderColor: alpha(theme.palette[styleProps.color].main, 0.5)
}, styleProps.variant === 'outlined' && styleProps.orientation === 'horizontal' && {
borderRightColor: 'transparent'
}, styleProps.variant === 'outlined' && styleProps.orientation === 'vertical' && {
borderBottomColor: 'transparent'
}, styleProps.variant === 'contained' && styleProps.orientation === 'horizontal' && {
borderRight: `1px solid ${theme.palette.grey[400]}`,
[`&.${buttonGroupClasses.disabled}`]: {
borderRight: `1px solid ${theme.palette.action.disabled}`
}
}, styleProps.variant === 'contained' && styleProps.orientation === 'vertical' && {
borderBottom: `1px solid ${theme.palette.grey[400]}`,
[`&.${buttonGroupClasses.disabled}`]: {
borderBottom: `1px solid ${theme.palette.action.disabled}`
}
}, styleProps.variant === 'contained' && styleProps.color !== 'inherit' && {
borderColor: theme.palette[styleProps.color].dark
}),
'&:hover': _extends({}, styleProps.variant === 'outlined' && styleProps.color !== 'inherit' && {
borderColor: theme.palette[styleProps.color].main
}, styleProps.variant === 'contained' && {
boxShadow: 'none'
})
}, styleProps.variant === 'contained' && {
boxShadow: 'none'
})
}));
const ButtonGroup = /*#__PURE__*/React.forwardRef(function ButtonGroup(inProps, ref) {
const props = useThemeProps({
props: inProps,
name: 'MuiButtonGroup'
});
const {
children,
className,
color = 'primary',
component = 'div',
disabled = false,
disableElevation = false,
disableFocusRipple = false,
disableRipple = false,
fullWidth = false,
orientation = 'horizontal',
size = 'medium',
variant = 'outlined'
} = props,
other = _objectWithoutPropertiesLoose(props, ["children", "className", "color", "component", "disabled", "disableElevation", "disableFocusRipple", "disableRipple", "fullWidth", "orientation", "size", "variant"]);
const styleProps = _extends({}, props, {
color,
component,
disabled,
disableElevation,
disableFocusRipple,
disableRipple,
fullWidth,
orientation,
size,
variant
});
const classes = useUtilityClasses(styleProps);
return /*#__PURE__*/_jsx(ButtonGroupRoot, _extends({
as: component,
role: "group",
className: clsx(classes.root, className),
ref: ref,
styleProps: styleProps
}, other, {
children: React.Children.map(children, child => {
if (! /*#__PURE__*/React.isValidElement(child)) {
return null;
}
if (process.env.NODE_ENV !== 'production') {
if (isFragment(child)) {
console.error(["Material-UI: The ButtonGroup component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n'));
}
}
return /*#__PURE__*/React.cloneElement(child, {
className: clsx(classes.grouped, child.props.className),
color: child.props.color || color,
disabled: child.props.disabled || disabled,
disableElevation: child.props.disableElevation || disableElevation,
disableFocusRipple,
disableRipple,
fullWidth,
size: child.props.size || size,
variant: child.props.variant || variant
});
})
}));
});
process.env.NODE_ENV !== "production" ? ButtonGroup.propTypes
/* remove-proptypes */
= {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The color of the component. It supports those theme colors that make sense for this component.
* @default 'primary'
*/
color: PropTypes
/* @typescript-to-proptypes-ignore */
.oneOfType([PropTypes.oneOf(['inherit', 'primary', 'secondary']), PropTypes.string]),
/**
* The component used for the root node.
* Either a string to use a HTML element or a component.
*/
component: PropTypes.elementType,
/**
* If `true`, the component is disabled.
* @default false
*/
disabled: PropTypes.bool,
/**
* If `true`, no elevation is used.
* @default false
*/
disableElevation: PropTypes.bool,
/**
* If `true`, the button keyboard focus ripple is disabled.
* @default false
*/
disableFocusRipple: PropTypes.bool,
/**
* If `true`, the button ripple effect is disabled.
* @default false
*/
disableRipple: PropTypes.bool,
/**
* If `true`, the buttons will take up the full width of its container.
* @default false
*/
fullWidth: PropTypes.bool,
/**
* The component orientation (layout flow direction).
* @default 'horizontal'
*/
orientation: PropTypes.oneOf(['horizontal', 'vertical']),
/**
* The size of the component.
* `small` is equivalent to the dense button styling.
* @default 'medium'
*/
size: PropTypes.oneOf(['large', 'medium', 'small']),
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.object,
/**
* The variant to use.
* @default 'outlined'
*/
variant: PropTypes
/* @typescript-to-proptypes-ignore */
.oneOfType([PropTypes.oneOf(['contained', 'outlined', 'text']), PropTypes.string])
} : void 0;
export default ButtonGroup; |
let key = 'key';
export {key};
|
var tolerate = require('tolerance'),
_ = require('lodash'),
Base = require('./base');
function exists(toCheck) {
var _exists = require('fs').existsSync || require('path').existsSync;
if (require('fs').accessSync) {
_exists = function (toCheck) {
try {
require('fs').accessSync(toCheck);
return true;
} catch (e) {
return false;
}
};
}
return _exists(toCheck);
}
function getSpecificDbImplementation(options) {
options = options || {};
options.type = options.type || 'inmemory';
if (_.isFunction(options.type)) {
return options.type;
}
options.type = options.type.toLowerCase();
var dbPath = __dirname + "/databases/" + options.type + ".js";
if (!exists(dbPath)) {
var errMsg = 'Implementation for db "' + options.type + '" does not exist!';
console.log(errMsg);
throw new Error(errMsg);
}
try {
var db = require(dbPath);
return db;
} catch (err) {
if (err.message.indexOf('Cannot find module') >= 0 &&
err.message.indexOf("'") > 0 &&
err.message.lastIndexOf("'") !== err.message.indexOf("'")) {
var moduleName = err.message.substring(err.message.indexOf("'") + 1, err.message.lastIndexOf("'"));
console.log('Please install module "' + moduleName +
'" to work with db implementation "' + options.type + '"!');
}
throw err;
}
}
module.exports = {
Store: Base,
create: function(options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
var Store;
try {
Store = getSpecificDbImplementation(options);
} catch (err) {
if (callback) callback(err);
throw err;
}
var store = new Store(options);
if (callback) {
process.nextTick(function () {
tolerate(function (callback) {
store.connect(callback);
}, options.timeout || 0, callback || function () {
});
});
}
return store;
}
};
|
/**
Ember Metal
@module ember
@submodule ember-metal
*/
// BEGIN IMPORTS
import Ember from "ember-metal/core";
import merge from "ember-metal/merge";
import {
instrument,
reset,
subscribe,
unsubscribe
} from "ember-metal/instrumentation";
import {
EMPTY_META,
GUID_KEY,
META_DESC,
apply,
applyStr,
canInvoke,
generateGuid,
getMeta,
guidFor,
inspect,
isArray,
makeArray,
meta,
metaPath,
setMeta,
tryCatchFinally,
tryFinally,
tryInvoke,
typeOf,
uuid,
wrap
} from "ember-metal/utils";
import EmberError from "ember-metal/error";
import EnumerableUtils from "ember-metal/enumerable_utils";
import Cache from "ember-metal/cache";
import {
create,
hasPropertyAccessors
} from "ember-metal/platform";
import {
filter,
forEach,
indexOf,
map
} from "ember-metal/array";
import Logger from "ember-metal/logger";
import {
_getPath,
get,
getWithDefault,
normalizeTuple
} from "ember-metal/property_get";
import {
addListener,
hasListeners,
listenersDiff,
listenersFor,
listenersUnion,
on,
removeListener,
sendEvent,
suspendListener,
suspendListeners,
watchedEvents
} from "ember-metal/events";
import ObserverSet from "ember-metal/observer_set";
import {
beginPropertyChanges,
changeProperties,
endPropertyChanges,
overrideChains,
propertyDidChange,
propertyWillChange
} from "ember-metal/property_events";
import {
Descriptor,
defineProperty
} from "ember-metal/properties";
import {
set,
trySet
} from "ember-metal/property_set";
import {
Map,
MapWithDefault,
OrderedSet
} from "ember-metal/map";
import getProperties from "ember-metal/get_properties";
import setProperties from "ember-metal/set_properties";
import {
watchKey,
unwatchKey
} from "ember-metal/watch_key";
import {
ChainNode,
finishChains,
flushPendingChains,
removeChainWatcher
} from "ember-metal/chains";
import {
watchPath,
unwatchPath
} from "ember-metal/watch_path";
import {
destroy,
isWatching,
rewatch,
unwatch,
watch
} from "ember-metal/watching";
import expandProperties from "ember-metal/expand_properties";
import {
ComputedProperty,
computed,
cacheFor
} from "ember-metal/computed";
// side effect of defining the computed.* macros
import "ember-metal/computed_macros";
import {
_suspendBeforeObserver,
_suspendBeforeObservers,
_suspendObserver,
_suspendObservers,
addBeforeObserver,
addObserver,
beforeObserversFor,
observersFor,
removeBeforeObserver,
removeObserver
} from "ember-metal/observer";
import {
IS_BINDING,
Mixin,
aliasMethod,
beforeObserver,
immediateObserver,
mixin,
observer,
required
} from "ember-metal/mixin";
import {
Binding,
bind,
isGlobalPath,
oneWay
} from "ember-metal/binding";
import run from "ember-metal/run_loop";
import Libraries from "ember-metal/libraries";
import isNone from 'ember-metal/is_none';
import isEmpty from 'ember-metal/is_empty';
import isBlank from 'ember-metal/is_blank';
import isPresent from 'ember-metal/is_present';
import keys from 'ember-metal/keys';
// END IMPORTS
// BEGIN EXPORTS
var EmberInstrumentation = Ember.Instrumentation = {};
EmberInstrumentation.instrument = instrument;
EmberInstrumentation.subscribe = subscribe;
EmberInstrumentation.unsubscribe = unsubscribe;
EmberInstrumentation.reset = reset;
Ember.instrument = instrument;
Ember.subscribe = subscribe;
Ember._Cache = Cache;
Ember.generateGuid = generateGuid;
Ember.GUID_KEY = GUID_KEY;
Ember.create = create;
Ember.keys = keys;
Ember.platform = {
defineProperty: defineProperty,
hasPropertyAccessors: hasPropertyAccessors
};
var EmberArrayPolyfills = Ember.ArrayPolyfills = {};
EmberArrayPolyfills.map = map;
EmberArrayPolyfills.forEach = forEach;
EmberArrayPolyfills.filter = filter;
EmberArrayPolyfills.indexOf = indexOf;
Ember.Error = EmberError;
Ember.guidFor = guidFor;
Ember.META_DESC = META_DESC;
Ember.EMPTY_META = EMPTY_META;
Ember.meta = meta;
Ember.getMeta = getMeta;
Ember.setMeta = setMeta;
Ember.metaPath = metaPath;
Ember.inspect = inspect;
Ember.typeOf = typeOf;
Ember.tryCatchFinally = tryCatchFinally;
Ember.isArray = isArray;
Ember.makeArray = makeArray;
Ember.canInvoke = canInvoke;
Ember.tryInvoke = tryInvoke;
Ember.tryFinally = tryFinally;
Ember.wrap = wrap;
Ember.apply = apply;
Ember.applyStr = applyStr;
Ember.uuid = uuid;
Ember.Logger = Logger;
Ember.get = get;
Ember.getWithDefault = getWithDefault;
Ember.normalizeTuple = normalizeTuple;
Ember._getPath = _getPath;
Ember.EnumerableUtils = EnumerableUtils;
Ember.on = on;
Ember.addListener = addListener;
Ember.removeListener = removeListener;
Ember._suspendListener = suspendListener;
Ember._suspendListeners = suspendListeners;
Ember.sendEvent = sendEvent;
Ember.hasListeners = hasListeners;
Ember.watchedEvents = watchedEvents;
Ember.listenersFor = listenersFor;
Ember.listenersDiff = listenersDiff;
Ember.listenersUnion = listenersUnion;
Ember._ObserverSet = ObserverSet;
Ember.propertyWillChange = propertyWillChange;
Ember.propertyDidChange = propertyDidChange;
Ember.overrideChains = overrideChains;
Ember.beginPropertyChanges = beginPropertyChanges;
Ember.endPropertyChanges = endPropertyChanges;
Ember.changeProperties = changeProperties;
Ember.Descriptor = Descriptor;
Ember.defineProperty = defineProperty;
Ember.set = set;
Ember.trySet = trySet;
Ember.OrderedSet = OrderedSet;
Ember.Map = Map;
Ember.MapWithDefault = MapWithDefault;
Ember.getProperties = getProperties;
Ember.setProperties = setProperties;
Ember.watchKey = watchKey;
Ember.unwatchKey = unwatchKey;
Ember.flushPendingChains = flushPendingChains;
Ember.removeChainWatcher = removeChainWatcher;
Ember._ChainNode = ChainNode;
Ember.finishChains = finishChains;
Ember.watchPath = watchPath;
Ember.unwatchPath = unwatchPath;
Ember.watch = watch;
Ember.isWatching = isWatching;
Ember.unwatch = unwatch;
Ember.rewatch = rewatch;
Ember.destroy = destroy;
Ember.expandProperties = expandProperties;
Ember.ComputedProperty = ComputedProperty;
Ember.computed = computed;
Ember.cacheFor = cacheFor;
Ember.addObserver = addObserver;
Ember.observersFor = observersFor;
Ember.removeObserver = removeObserver;
Ember.addBeforeObserver = addBeforeObserver;
Ember._suspendBeforeObserver = _suspendBeforeObserver;
Ember._suspendBeforeObservers = _suspendBeforeObservers;
Ember._suspendObserver = _suspendObserver;
Ember._suspendObservers = _suspendObservers;
Ember.beforeObserversFor = beforeObserversFor;
Ember.removeBeforeObserver = removeBeforeObserver;
Ember.IS_BINDING = IS_BINDING;
Ember.required = required;
Ember.aliasMethod = aliasMethod;
Ember.observer = observer;
Ember.immediateObserver = immediateObserver;
Ember.beforeObserver = beforeObserver;
Ember.mixin = mixin;
Ember.Mixin = Mixin;
Ember.oneWay = oneWay;
Ember.bind = bind;
Ember.Binding = Binding;
Ember.isGlobalPath = isGlobalPath;
Ember.run = run;
Ember.libraries = new Libraries();
Ember.libraries.registerCoreLibrary('Ember', Ember.VERSION);
Ember.isNone = isNone;
Ember.isEmpty = isEmpty;
Ember.isBlank = isBlank;
if (Ember.FEATURES.isEnabled('ember-metal-is-present')) {
Ember.isPresent = isPresent;
}
Ember.merge = merge;
/**
A function may be assigned to `Ember.onerror` to be called when Ember
internals encounter an error. This is useful for specialized error handling
and reporting code.
```javascript
Ember.onerror = function(error) {
Em.$.ajax('/report-error', 'POST', {
stack: error.stack,
otherInformation: 'whatever app state you want to provide'
});
};
```
Internally, `Ember.onerror` is used as Backburner's error handler.
@event onerror
@for Ember
@param {Exception} error the error object
*/
Ember.onerror = null;
// END EXPORTS
// do this for side-effects of updating Ember.assert, warn, etc when
// ember-debug is present
if (Ember.__loader.registry['ember-debug']) {
requireModule('ember-debug');
}
export default Ember;
|
"use strict";
meta.class("Element.Section", "Element.Basic",
{
onCreate: function()
{
var header = document.createElement("header");
header.onclick = this.handleClick.bind(this);
this.domElement.appendChild(header);
this.caret = new Element.Caret(header);
this.caret.open = true;
this.caret.on("update", this.handleCaretUpdate.bind(this));
this.h2 = document.createElement("h2");
header.appendChild(this.h2);
this.contentHolder = document.createElement("content");
this.domElement.appendChild(this.contentHolder);
},
handleClick: function(domEvent)
{
domEvent.preventDefault();
domEvent.stopPropagation();
this.caret.open = !this.caret.open;
},
handleCaretUpdate: function(event)
{
if(this.caret.open) {
this.contentHolder.classList.remove("hidden");
}
else {
this.contentHolder.classList.add("hidden");
}
},
set value(value) {
this.h2.innerHTML = value;
},
get value() {
return this.h2.innerHTML;
},
set open(value) {
this.caret.open = value;
},
get open() {
return this.caret.open;
},
//
elementTag: "section",
caret: null,
h2: null,
}); |
/*global jQuery */
/*jshint multistr:true browser:true */
/*!
* FitVids 1.0.3
*
* Copyright 2013, Chris Coyier - https://css-tricks.com + Dave Rupert - https://daverupert.com
* Credit to Thierry Koblentz - https://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/
* Released under the WTFPL license - https://sam.zoy.org/wtfpl/
*
* Date: Thu Sept 01 18:00:00 2011 -0500
*/
(function( $ ){
"use strict";
$.fn.fitVids = function( options ) {
var settings = {
customSelector: null
};
if(!document.getElementById('fit-vids-style')) {
var div = document.createElement('div'),
ref = document.getElementsByTagName('base')[0] || document.getElementsByTagName('script')[0],
cssStyles = '­<style>.fluid-width-video-wrapper{width:100%;position:relative;padding:0;}.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed {position:absolute;top:0;left:0;width:100%;height:100%;}</style>';
div.className = 'fit-vids-style';
div.id = 'fit-vids-style';
div.style.display = 'none';
div.innerHTML = cssStyles;
ref.parentNode.insertBefore(div,ref);
}
if ( options ) {
$.extend( settings, options );
}
return this.each(function(){
var selectors = [
"iframe[src*='player.vimeo.com']",
"iframe[src*='youtube.com']",
"iframe[src*='youtube-nocookie.com']",
"iframe[src*='kickstarter.com'][src*='video.html']",
"object",
"embed"
];
if (settings.customSelector) {
selectors.push(settings.customSelector);
}
var $allVideos = $(this).find(selectors.join(','));
$allVideos = $allVideos.not("object object"); // SwfObj conflict patch
$allVideos.each(function(){
var $this = $(this);
if (this.tagName.toLowerCase() === 'embed' && $this.parent('object').length || $this.parent('.fluid-width-video-wrapper').length) { return; }
var height = ( this.tagName.toLowerCase() === 'object' || ($this.attr('height') && !isNaN(parseInt($this.attr('height'), 10))) ) ? parseInt($this.attr('height'), 10) : $this.height(),
width = !isNaN(parseInt($this.attr('width'), 10)) ? parseInt($this.attr('width'), 10) : $this.width(),
aspectRatio = height / width;
if(!$this.attr('id')){
var videoID = 'fitvid' + Math.floor(Math.random()*999999);
$this.attr('id', videoID);
}
$this.wrap('<div class="fluid-width-video-wrapper"></div>').parent('.fluid-width-video-wrapper').css('padding-top', (aspectRatio * 100)+"%");
$this.removeAttr('height').removeAttr('width');
});
});
};
// Works with either jQuery or Zepto
})( window.jQuery || window.Zepto );
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.