code stringlengths 2 1.05M |
|---|
module.exports = {
"env": {
"browser": true,
"es6": true
},
"extends": "eslint:recommended",
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"parserOptions": {
"ecmaVersion": 2018
},
"rules": {
"accessor-pairs": "error",
"array-bracket-newline": "error",
"array-bracket-spacing": "error",
"array-callback-return": "error",
"array-element-newline": "error",
"arrow-body-style": "error",
"arrow-parens": "error",
"arrow-spacing": "error",
"block-scoped-var": "off",
"block-spacing": [
"error",
"always"
],
"brace-style": [
"error",
"1tbs",
{
"allowSingleLine": true
}
],
"callback-return": "error",
"camelcase": "error",
"capitalized-comments": "off",
"class-methods-use-this": "error",
"comma-dangle": "error",
"comma-spacing": [
"error",
{
"after": true,
"before": false
}
],
"comma-style": [
"error",
"last"
],
"complexity": "error",
"computed-property-spacing": [
"error",
"always"
],
"consistent-return": "error",
"consistent-this": "off",
"curly": "error",
"default-case": "error",
"dot-location": "error",
"dot-notation": "error",
"eol-last": "error",
"eqeqeq": "error",
"func-call-spacing": "error",
"func-name-matching": "error",
"func-names": "off",
"func-style": [
"error",
"expression"
],
"function-paren-newline": "error",
"generator-star-spacing": "error",
"global-require": "error",
"guard-for-in": "error",
"handle-callback-err": "error",
"id-blacklist": "error",
"id-length": "off",
"id-match": "error",
"implicit-arrow-linebreak": "error",
"indent": "error",
"indent-legacy": "error",
"init-declarations": "off",
"jsx-quotes": "error",
"key-spacing": "off",
"keyword-spacing": [
"error",
{
"after": true,
"before": true
}
],
"line-comment-position": "off",
"linebreak-style": [
"error",
"unix"
],
"lines-around-comment": "error",
"lines-around-directive": "off",
"lines-between-class-members": "error",
"max-classes-per-file": "error",
"max-depth": "error",
"max-len": "off",
"max-lines": "error",
"max-lines-per-function": "off",
"max-nested-callbacks": "error",
"max-params": "error",
"max-statements": "off",
"max-statements-per-line": "off",
"multiline-comment-style": [
"error",
"separate-lines"
],
"new-cap": "error",
"new-parens": "error",
"newline-after-var": "off",
"newline-before-return": "off",
"newline-per-chained-call": "error",
"no-alert": "error",
"no-array-constructor": "error",
"no-async-promise-executor": "error",
"no-await-in-loop": "error",
"no-bitwise": "error",
"no-buffer-constructor": "error",
"no-caller": "error",
"no-catch-shadow": "error",
"no-confusing-arrow": "error",
"no-continue": "error",
"no-div-regex": "error",
"no-duplicate-imports": "error",
"no-else-return": "error",
"no-empty-function": "error",
"no-eq-null": "error",
"no-eval": "error",
"no-extend-native": "error",
"no-extra-bind": "error",
"no-extra-label": "error",
"no-extra-parens": "off",
"no-floating-decimal": "error",
"no-implicit-coercion": "error",
"no-implicit-globals": "error",
"no-implied-eval": "error",
"no-inline-comments": "off",
"no-inner-declarations": [
"error",
"functions"
],
"no-invalid-this": "off",
"no-iterator": "error",
"no-label-var": "error",
"no-labels": "error",
"no-lone-blocks": "error",
"no-lonely-if": "error",
"no-loop-func": "error",
"no-magic-numbers": "off",
"no-misleading-character-class": "error",
"no-mixed-operators": "error",
"no-mixed-requires": "error",
"no-multi-assign": "error",
"no-multi-spaces": "off",
"no-multi-str": "error",
"no-multiple-empty-lines": "error",
"no-native-reassign": "error",
"no-negated-condition": "off",
"no-negated-in-lhs": "error",
"no-nested-ternary": "error",
"no-new": "error",
"no-new-func": "error",
"no-new-object": "error",
"no-new-require": "error",
"no-new-wrappers": "error",
"no-octal-escape": "error",
"no-param-reassign": "off",
"no-path-concat": "error",
"no-plusplus": "off",
"no-process-env": "error",
"no-process-exit": "error",
"no-proto": "error",
"no-prototype-builtins": "error",
"no-restricted-globals": "error",
"no-restricted-imports": "error",
"no-restricted-modules": "error",
"no-restricted-properties": "error",
"no-restricted-syntax": "error",
"no-return-assign": "error",
"no-return-await": "error",
"no-script-url": "error",
"no-self-compare": "error",
"no-sequences": "error",
"no-shadow": "off",
"no-shadow-restricted-names": "error",
"no-spaced-func": "error",
"no-sync": "error",
"no-tabs": "error",
"no-template-curly-in-string": "error",
"no-ternary": "off",
"no-throw-literal": "error",
"no-trailing-spaces": "error",
"no-undef-init": "error",
"no-undefined": "off",
"no-underscore-dangle": "error",
"no-unmodified-loop-condition": "error",
"no-unneeded-ternary": "error",
"no-unused-expressions": "error",
"no-use-before-define": "off",
"no-useless-call": "error",
"no-useless-catch": "error",
"no-useless-computed-key": "error",
"no-useless-concat": "error",
"no-useless-constructor": "error",
"no-useless-rename": "error",
"no-useless-return": "error",
"no-var": "off",
"no-void": "error",
"no-warning-comments": "error",
"no-whitespace-before-property": "error",
"no-with": "error",
"nonblock-statement-body-position": "error",
"object-curly-newline": "error",
"object-curly-spacing": [
"error",
"always"
],
"object-shorthand": "off",
"one-var": "off",
"one-var-declaration-per-line": "off",
"operator-assignment": "error",
"operator-linebreak": "error",
"padded-blocks": "off",
"padding-line-between-statements": "error",
"prefer-arrow-callback": "off",
"prefer-const": "error",
"prefer-destructuring": "off",
"prefer-numeric-literals": "error",
"prefer-object-spread": "error",
"prefer-promise-reject-errors": "error",
"prefer-reflect": "off",
"prefer-rest-params": "off",
"prefer-spread": "error",
"prefer-template": "off",
"quote-props": "off",
"quotes": [
"error",
"double"
],
"radix": "error",
"require-atomic-updates": "error",
"require-await": "error",
"require-jsdoc": "error",
"require-unicode-regexp": "off",
"rest-spread-spacing": "error",
"semi": "error",
"semi-spacing": [
"error",
{
"after": true,
"before": false
}
],
"semi-style": [
"error",
"last"
],
"sort-imports": "error",
"sort-keys": "off",
"sort-vars": "off",
"space-before-blocks": "error",
"space-before-function-paren": "off",
"space-in-parens": [
"error",
"always"
],
"space-infix-ops": "error",
"space-unary-ops": "error",
"spaced-comment": [
"error",
"always"
],
"strict": "error",
"switch-colon-spacing": "error",
"symbol-description": "error",
"template-curly-spacing": "error",
"template-tag-spacing": "error",
"unicode-bom": [
"error",
"never"
],
"valid-jsdoc": "error",
"vars-on-top": "off",
"wrap-regex": "error",
"yield-star-spacing": "error",
"yoda": [
"error",
"never"
]
}
};
|
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import Paper from '../Paper';
import StepConnector from '../StepConnector';
export const styles = {
/* Styles applied to the root element. */
root: {
display: 'flex',
padding: 24
},
/* Styles applied to the root element if `orientation="horizontal"`. */
horizontal: {
flexDirection: 'row',
alignItems: 'center'
},
/* Styles applied to the root element if `orientation="vertical"`. */
vertical: {
flexDirection: 'column'
},
/* Styles applied to the root element if `alternativeLabel={true}`. */
alternativeLabel: {
alignItems: 'flex-start'
}
};
const defaultConnector = /*#__PURE__*/React.createElement(StepConnector, null);
const Stepper = React.forwardRef(function Stepper(props, ref) {
const {
activeStep = 0,
alternativeLabel = false,
children,
classes,
className,
connector: connectorProp = defaultConnector,
nonLinear = false,
orientation = 'horizontal'
} = props,
other = _objectWithoutPropertiesLoose(props, ["activeStep", "alternativeLabel", "children", "classes", "className", "connector", "nonLinear", "orientation"]);
const connector = React.isValidElement(connectorProp) ? React.cloneElement(connectorProp, {
orientation
}) : null;
const childrenArray = React.Children.toArray(children);
const steps = childrenArray.map((step, index) => {
const controlProps = {
alternativeLabel,
connector: connectorProp,
last: index + 1 === childrenArray.length,
orientation
};
const state = {
index,
active: false,
completed: false,
disabled: false
};
if (activeStep === index) {
state.active = true;
} else if (!nonLinear && activeStep > index) {
state.completed = true;
} else if (!nonLinear && activeStep < index) {
state.disabled = true;
}
return [!alternativeLabel && connector && index !== 0 && React.cloneElement(connector, _extends({
key: index
}, state)), React.cloneElement(step, _extends({}, controlProps, {}, state, {}, step.props))];
});
return /*#__PURE__*/React.createElement(Paper, _extends({
square: true,
elevation: 0,
className: clsx(classes.root, classes[orientation], className, alternativeLabel && classes.alternativeLabel),
ref: ref
}, other), steps);
});
process.env.NODE_ENV !== "production" ? Stepper.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* Set the active step (zero based index).
* Set to -1 to disable all the steps.
*/
activeStep: PropTypes.number,
/**
* If set to 'true' and orientation is horizontal,
* then the step label will be positioned under the icon.
*/
alternativeLabel: PropTypes.bool,
/**
* Two or more `<Step />` components.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* An element to be placed between each step.
*/
connector: PropTypes.element,
/**
* If set the `Stepper` will not assist in controlling steps for linear flow.
*/
nonLinear: PropTypes.bool,
/**
* The stepper orientation (layout flow direction).
*/
orientation: PropTypes.oneOf(['horizontal', 'vertical'])
} : void 0;
export default withStyles(styles, {
name: 'MuiStepper'
})(Stepper); |
/*
Highmaps JS v8.2.2 (2020-10-22)
Tilemap module
(c) 2010-2019 Highsoft AS
License: www.highcharts.com/license
*/
(function(d){"object"===typeof module&&module.exports?(d["default"]=d,module.exports=d):"function"===typeof define&&define.amd?define("highcharts/modules/tilemap",["highcharts","highcharts/modules/map"],function(g){d(g);d.Highcharts=g;return d}):d("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(d){function g(d,u,e,w){d.hasOwnProperty(u)||(d[u]=w.apply(null,e))}d=d?d._modules:{};g(d,"Series/TilemapSeries.js",[d["Core/Series/Series.js"],d["Mixins/ColorSeries.js"],d["Core/Globals.js"],
d["Core/Utilities.js"]],function(d,u,e,w){function g(a,b,c){a=a.options;return{xPad:(a.colsize||1)/-b,yPad:(a.rowsize||1)/-c}}u=u.colorPointMixin;var z=w.addEvent,h=w.clamp,A=w.extend,y=w.pick;"";e.tileShapeTypes={hexagon:{alignDataLabel:e.seriesTypes.scatter.prototype.alignDataLabel,getSeriesPadding:function(a){return g(a,3,2)},haloPath:function(a){if(!a)return[];var b=this.tileEdges;return[["M",b.x2-a,b.y1+a],["L",b.x3+a,b.y1+a],["L",b.x4+1.5*a,b.y2],["L",b.x3+a,b.y3-a],["L",b.x2-a,b.y3-a],["L",
b.x1-1.5*a,b.y2],["Z"]]},translate:function(){var a=this.options,b=this.xAxis,c=this.yAxis,d=a.pointPadding||0,e=(a.colsize||1)/3,g=(a.rowsize||1)/2,n;this.generatePoints();this.points.forEach(function(a){var t=h(Math.floor(b.len-b.translate(a.x-2*e,0,1,0,1)),-b.len,2*b.len),k=h(Math.floor(b.len-b.translate(a.x-e,0,1,0,1)),-b.len,2*b.len),q=h(Math.floor(b.len-b.translate(a.x+e,0,1,0,1)),-b.len,2*b.len),v=h(Math.floor(b.len-b.translate(a.x+2*e,0,1,0,1)),-b.len,2*b.len),r=h(Math.floor(c.translate(a.y-
g,0,1,0,1)),-c.len,2*c.len),f=h(Math.floor(c.translate(a.y,0,1,0,1)),-c.len,2*c.len),l=h(Math.floor(c.translate(a.y+g,0,1,0,1)),-c.len,2*c.len),m=y(a.pointPadding,d),p=m*Math.abs(k-t)/Math.abs(l-f);p=b.reversed?-p:p;var x=b.reversed?-m:m;m=c.reversed?-m:m;a.x%2&&(n=n||Math.round(Math.abs(l-r)/2)*(c.reversed?-1:1),r+=n,f+=n,l+=n);a.plotX=a.clientX=(k+q)/2;a.plotY=f;t+=p+x;k+=x;q-=x;v-=p+x;r-=m;l+=m;a.tileEdges={x1:t,x2:k,x3:q,x4:v,y1:r,y2:f,y3:l};a.shapeType="path";a.shapeArgs={d:[["M",k,r],["L",q,
r],["L",v,f],["L",q,l],["L",k,l],["L",t,f],["Z"]]}});this.translateColors()}},diamond:{alignDataLabel:e.seriesTypes.scatter.prototype.alignDataLabel,getSeriesPadding:function(a){return g(a,2,2)},haloPath:function(a){if(!a)return[];var b=this.tileEdges;return[["M",b.x2,b.y1+a],["L",b.x3+a,b.y2],["L",b.x2,b.y3-a],["L",b.x1-a,b.y2],["Z"]]},translate:function(){var a=this.options,b=this.xAxis,c=this.yAxis,d=a.pointPadding||0,e=a.colsize||1,g=(a.rowsize||1)/2,n;this.generatePoints();this.points.forEach(function(a){var p=
h(Math.round(b.len-b.translate(a.x-e,0,1,0,0)),-b.len,2*b.len),k=h(Math.round(b.len-b.translate(a.x,0,1,0,0)),-b.len,2*b.len),q=h(Math.round(b.len-b.translate(a.x+e,0,1,0,0)),-b.len,2*b.len),v=h(Math.round(c.translate(a.y-g,0,1,0,0)),-c.len,2*c.len),r=h(Math.round(c.translate(a.y,0,1,0,0)),-c.len,2*c.len),f=h(Math.round(c.translate(a.y+g,0,1,0,0)),-c.len,2*c.len),l=y(a.pointPadding,d),m=l*Math.abs(k-p)/Math.abs(f-r);m=b.reversed?-m:m;l=c.reversed?-l:l;a.x%2&&(n=Math.abs(f-v)/2*(c.reversed?-1:1),v+=
n,r+=n,f+=n);a.plotX=a.clientX=k;a.plotY=r;p+=m;q-=m;v-=l;f+=l;a.tileEdges={x1:p,x2:k,x3:q,y1:v,y2:r,y3:f};a.shapeType="path";a.shapeArgs={d:[["M",k,v],["L",q,r],["L",k,f],["L",p,r],["Z"]]}});this.translateColors()}},circle:{alignDataLabel:e.seriesTypes.scatter.prototype.alignDataLabel,getSeriesPadding:function(a){return g(a,2,2)},haloPath:function(a){return e.seriesTypes.scatter.prototype.pointClass.prototype.haloPath.call(this,a+(a&&this.radius))},translate:function(){var a=this.options,b=this.xAxis,
c=this.yAxis,d=a.pointPadding||0,e=(a.rowsize||1)/2,g=a.colsize||1,n,t,u,k,q=!1;this.generatePoints();this.points.forEach(function(a){var p=h(Math.round(b.len-b.translate(a.x,0,1,0,0)),-b.len,2*b.len),f=h(Math.round(c.translate(a.y,0,1,0,0)),-c.len,2*c.len),l=d,m=!1;"undefined"!==typeof a.pointPadding&&(l=a.pointPadding,q=m=!0);if(!k||q)n=Math.abs(h(Math.floor(b.len-b.translate(a.x+g,0,1,0,0)),-b.len,2*b.len)-p),t=Math.abs(h(Math.floor(c.translate(a.y+e,0,1,0,0)),-c.len,2*c.len)-f),u=Math.floor(Math.sqrt(n*
n+t*t)/2),k=Math.min(n,u,t)-l,q&&!m&&(q=!1);a.x%2&&(f+=t*(c.reversed?-1:1));a.plotX=a.clientX=p;a.plotY=f;a.radius=k;a.shapeType="circle";a.shapeArgs={x:p,y:f,r:k}});this.translateColors()}},square:{alignDataLabel:e.seriesTypes.heatmap.prototype.alignDataLabel,translate:e.seriesTypes.heatmap.prototype.translate,getSeriesPadding:function(){},haloPath:e.seriesTypes.heatmap.prototype.pointClass.prototype.haloPath}};z(e.Axis,"afterSetAxisTranslation",function(){if(!this.recomputingForTilemap&&"colorAxis"!==
this.coll){var a=this,b=a.series.map(function(b){return b.getSeriesPixelPadding&&b.getSeriesPixelPadding(a)}).reduce(function(a,b){return(a&&a.padding)>(b&&b.padding)?a:b},void 0)||{padding:0,axisLengthFactor:1},c=Math.round(b.padding*b.axisLengthFactor);b.padding&&(a.len-=c,a.recomputingForTilemap=!0,a.setAxisTranslation(),delete a.recomputingForTilemap,a.minPixelPadding+=b.padding,a.len+=c)}});d.seriesType("tilemap","heatmap",{marker:null,states:{hover:{halo:{enabled:!0,size:2,opacity:.5,attributes:{zIndex:3}}}},
pointPadding:2,tileShape:"hexagon"},{markerAttribs:e.seriesTypes.scatter.prototype.markerAttribs,pointAttribs:e.seriesTypes.column.prototype.pointAttribs,getSymbol:e.noop,drawPoints:function(){var a=this;e.seriesTypes.column.prototype.drawPoints.call(this);this.points.forEach(function(b){b.graphic&&b.graphic[a.chart.styledMode?"css":"animate"](a.colorAttribs(b))})},setOptions:function(){var a=e.seriesTypes.heatmap.prototype.setOptions.apply(this,Array.prototype.slice.call(arguments));this.tileShape=
e.tileShapeTypes[a.tileShape];return a},alignDataLabel:function(){return this.tileShape.alignDataLabel.apply(this,Array.prototype.slice.call(arguments))},getSeriesPixelPadding:function(a){var b=a.isXAxis,c=this.tileShape.getSeriesPadding(this);if(!c)return{padding:0,axisLengthFactor:1};var d=Math.round(a.translate(b?2*c.xPad:c.yPad,0,1,0,1));a=Math.round(a.translate(b?c.xPad:0,0,1,0,1));return{padding:Math.abs(d-a)||0,axisLengthFactor:b?2:1.1}},translate:function(){return this.tileShape.translate.apply(this,
Array.prototype.slice.call(arguments))}},A({haloPath:function(){return this.series.tileShape.haloPath.apply(this,Array.prototype.slice.call(arguments))}},u));""});g(d,"masters/modules/tilemap.src.js",[],function(){})});
//# sourceMappingURL=tilemap.js.map |
Tasks = new Mongo.Collection('tasks'); |
var fs = require('fs-extra'),
_ = require('lodash'),
url = require('url'),
debug = require('ghost-ignition').debug('custom-redirects'),
config = require('../config'),
errors = require('../errors'),
logging = require('../logging');
/**
* you can extend Ghost with a custom redirects file
* see https://github.com/TryGhost/Ghost/issues/7707
* file loads synchronously, because we need to register the routes before anything else
*/
module.exports = function redirects(blogApp) {
debug('redirects loading');
try {
var redirects = fs.readFileSync(config.getContentPath('data') + '/redirects.json', 'utf-8');
redirects = JSON.parse(redirects);
_.each(redirects, function (redirect) {
if (!redirect.from || !redirect.to) {
logging.warn(new errors.IncorrectUsageError({
message: 'One of your custom redirects is in a wrong format.',
level: 'normal',
help: JSON.stringify(redirect),
context: 'redirects.json'
}));
return;
}
/**
* always delete trailing slashes, doesn't matter if regex or not
* Example:
* - you define /my-blog-post-1/ as from property
* - /my-blog-post-1 or /my-blog-post-1/ should work
*/
if (redirect.from.match(/\/$/)) {
redirect.from = redirect.from.slice(0, -1);
}
if (redirect.from[redirect.from.length - 1] !== '$') {
redirect.from += '\/?$';
}
blogApp.get(new RegExp(redirect.from), function (req, res) {
var maxAge = redirect.permanent ? config.get('caching:customRedirects:maxAge') : 0,
parsedUrl = url.parse(req.originalUrl);
res.set({
'Cache-Control': 'public, max-age=' + maxAge
});
res.redirect(redirect.permanent ? 301 : 302, url.format({
pathname: parsedUrl.pathname.replace(new RegExp(redirect.from), redirect.to),
search: parsedUrl.search
}));
});
});
} catch (err) {
if (err.code !== 'ENOENT') {
logging.error(new errors.IncorrectUsageError({
message: 'Your redirects.json is broken.',
help: 'Check if your JSON is valid.'
}));
}
}
debug('redirects loaded');
};
|
/**
* @license Highstock JS v1.1.5 (2012-03-15)
* Prototype adapter
*
* @author Michael Nelson, Torstein Hønsi.
*
* Feel free to use and modify this script.
* Highcharts license: www.highcharts.com/license.
*/
// JSLint options:
/*global Effect, Class, Event, Element, $, $$, $A */
// Adapter interface between prototype and the Highcharts charting library
var HighchartsAdapter = (function () {
var hasEffect = typeof Effect !== 'undefined';
return {
/**
* Initialize the adapter. This is run once as Highcharts is first run.
* @param {Object} pathAnim The helper object to do animations across adapters.
*/
init: function (pathAnim) {
if (hasEffect) {
/**
* Animation for Highcharts SVG element wrappers only
* @param {Object} element
* @param {Object} attribute
* @param {Object} to
* @param {Object} options
*/
Effect.HighchartsTransition = Class.create(Effect.Base, {
initialize: function (element, attr, to, options) {
var from,
opts;
this.element = element;
this.key = attr;
from = element.attr ? element.attr(attr) : $(element).getStyle(attr);
// special treatment for paths
if (attr === 'd') {
this.paths = pathAnim.init(
element,
element.d,
to
);
this.toD = to;
// fake values in order to read relative position as a float in update
from = 0;
to = 1;
}
opts = Object.extend((options || {}), {
from: from,
to: to,
attribute: attr
});
this.start(opts);
},
setup: function () {
HighchartsAdapter._extend(this.element);
// If this is the first animation on this object, create the _highcharts_animation helper that
// contain pointers to the animation objects.
if (!this.element._highchart_animation) {
this.element._highchart_animation = {};
}
// Store a reference to this animation instance.
this.element._highchart_animation[this.key] = this;
},
update: function (position) {
var paths = this.paths,
element = this.element,
obj;
if (paths) {
position = pathAnim.step(paths[0], paths[1], position, this.toD);
}
if (element.attr) { // SVGElement
element.attr(this.options.attribute, position);
} else { // HTML, #409
obj = {};
obj[this.options.attribute] = position;
$(element).setStyle(obj);
}
},
finish: function () {
// Delete the property that holds this animation now that it is finished.
// Both canceled animations and complete ones gets a 'finish' call.
delete this.element._highchart_animation[this.key];
}
});
}
},
/**
* Downloads a script and executes a callback when done.
* @param {String} scriptLocation
* @param {Function} callback
*/
getScript: function (scriptLocation, callback) {
var head = $$('head')[0]; // Returns an array, so pick the first element.
if (head) {
// Append a new 'script' element, set its type and src attributes, add a 'load' handler that calls the callback
head.appendChild(new Element('script', { type: 'text/javascript', src: scriptLocation}).observe('load', callback));
}
},
/**
* Custom events in prototype needs to be namespaced. This method adds a namespace 'h:' in front of
* events that are not recognized as native.
*/
addNS: function (eventName) {
var HTMLEvents = /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
MouseEvents = /^(?:click|mouse(?:down|up|over|move|out))$/;
return (HTMLEvents.test(eventName) || MouseEvents.test(eventName)) ?
eventName :
'h:' + eventName;
},
// el needs an event to be attached. el is not necessarily a dom element
addEvent: function (el, event, fn) {
if (el.addEventListener || el.attachEvent) {
Event.observe($(el), HighchartsAdapter.addNS(event), fn);
} else {
HighchartsAdapter._extend(el);
el._highcharts_observe(event, fn);
}
},
// motion makes things pretty. use it if effects is loaded, if not... still get to the end result.
animate: function (el, params, options) {
var key,
fx;
// default options
options = options || {};
options.delay = 0;
options.duration = (options.duration || 500) / 1000;
options.afterFinish = options.complete;
// animate wrappers and DOM elements
if (hasEffect) {
for (key in params) {
// The fx variable is seemingly thrown away here, but the Effect.setup will add itself to the _highcharts_animation object
// on the element itself so its not really lost.
fx = new Effect.HighchartsTransition($(el), key, params[key], options);
}
} else {
if (el.attr) { // #409 without effects
for (key in params) {
el.attr(key, params[key]);
}
}
if (options.complete) {
options.complete();
}
}
if (!el.attr) { // HTML element, #409
$(el).setStyle(params);
}
},
// this only occurs in higcharts 2.0+
stop: function (el) {
var key;
if (el._highcharts_extended && el._highchart_animation) {
for (key in el._highchart_animation) {
// Cancel the animation
// The 'finish' function in the Effect object will remove the reference
el._highchart_animation[key].cancel();
}
}
},
// um.. each
each: function (arr, fn) {
$A(arr).each(fn);
},
/**
* Get the cumulative offset relative to the top left of the page. This method, unlike its
* jQuery and MooTools counterpart, still suffers from issue #208 regarding the position
* of a chart within a fixed container.
*/
offset: function (el) {
return $(el).cumulativeOffset();
},
// fire an event based on an event name (event) and an object (el).
// again, el may not be a dom element
fireEvent: function (el, event, eventArguments, defaultFunction) {
if (el.fire) {
el.fire(HighchartsAdapter.addNS(event), eventArguments);
} else if (el._highcharts_extended) {
eventArguments = eventArguments || {};
el._highcharts_fire(event, eventArguments);
}
if (eventArguments && eventArguments.defaultPrevented) {
defaultFunction = null;
}
if (defaultFunction) {
defaultFunction(eventArguments);
}
},
removeEvent: function (el, event, handler) {
if ($(el).stopObserving) {
if (event) {
event = HighchartsAdapter.addNS(event);
}
$(el).stopObserving(event, handler);
} if (window === el) {
Event.stopObserving(el, event, handler);
} else {
HighchartsAdapter._extend(el);
el._highcharts_stop_observing(event, handler);
}
},
// um, grep
grep: function (arr, fn) {
return arr.findAll(fn);
},
// um, map
map: function (arr, fn) {
return arr.map(fn);
},
// deep merge. merge({a : 'a', b : {b1 : 'b1', b2 : 'b2'}}, {b : {b2 : 'b2_prime'}, c : 'c'}) => {a : 'a', b : {b1 : 'b1', b2 : 'b2_prime'}, c : 'c'}
/*merge: function(){
function doCopy(copy, original) {
var value,
key,
undef,
nil,
same,
obj,
arr,
node;
for (key in original) {
value = original[key];
undef = typeof(value) === 'undefined';
nil = value === null;
same = original === copy[key];
if (undef || nil || same) {
continue;
}
obj = typeof(value) === 'object';
arr = value && obj && value.constructor == Array;
node = !!value.nodeType;
if (obj && !arr && !node) {
copy[key] = doCopy(typeof copy[key] == 'object' ? copy[key] : {}, value);
}
else {
copy[key] = original[key];
}
}
return copy;
}
var args = arguments, retVal = {};
for (var i = 0; i < args.length; i++) {
retVal = doCopy(retVal, args[i]);
}
return retVal;
},*/
merge: function () { // the built-in prototype merge function doesn't do deep copy
function doCopy(copy, original) {
var value, key;
for (key in original) {
value = original[key];
if (value && typeof value === 'object' && value.constructor !== Array &&
typeof value.nodeType !== 'number') {
copy[key] = doCopy(copy[key] || {}, value); // copy
} else {
copy[key] = original[key];
}
}
return copy;
}
function merge() {
var args = arguments,
i,
retVal = {};
for (i = 0; i < args.length; i++) {
retVal = doCopy(retVal, args[i]);
}
return retVal;
}
return merge.apply(this, arguments);
},
// extend an object to handle highchart events (highchart objects, not svg elements).
// this is a very simple way of handling events but whatever, it works (i think)
_extend: function (object) {
if (!object._highcharts_extended) {
Object.extend(object, {
_highchart_events: {},
_highchart_animation: null,
_highcharts_extended: true,
_highcharts_observe: function (name, fn) {
this._highchart_events[name] = [this._highchart_events[name], fn].compact().flatten();
},
_highcharts_stop_observing: function (name, fn) {
if (name) {
if (fn) {
this._highchart_events[name] = [this._highchart_events[name]].compact().flatten().without(fn);
} else {
delete this._highchart_events[name];
}
} else {
this._highchart_events = {};
}
},
_highcharts_fire: function (name, args) {
(this._highchart_events[name] || []).each(function (fn) {
// args is never null here
if (args.stopped) {
return; // "throw $break" wasn't working. i think because of the scope of 'this'.
}
// Attach a simple preventDefault function to skip default handler if called
args.preventDefault = function () {
args.defaultPrevented = true;
};
// If the event handler return false, prevent the default handler from executing
if (fn.bind(this)(args) === false) {
args.preventDefault();
}
}
.bind(this));
}
});
}
}
};
}());
|
var http = require('http');
var util = require('util');
var cheerio = require('cheerio');
// Create an Object from an Array of objects.
function toObject(objects, keyName, valueName) {
return objects.reduce(function(acc, obj) {
acc[obj[keyName]] = obj[valueName];
return acc;
}, {});
}
function parse(html) {
var $ = cheerio.load(html);
function pickColor(_i, item) {
var $item = $(item);
var shade = $item.find('.shade').text().toLowerCase();
var hex = $item.find('.hex').text();
return { shade: shade, hex: hex };
}
function pickGroupColors(_i, group) {
var $group = $(group);
var colorName = $group.find('li.main-color .name').text();
var name = colorName.toLowerCase().split(' ').join('-');
var $items = $group.find('li.color:not(.main-color)');
var groupColors = $items.map(pickColor).toArray();
var colors = toObject(groupColors, 'shade', 'hex');
return { name: name, colors: colors };
}
var $groups = $('.color-group');
var colorGroups = $groups.map(pickGroupColors).toArray();
var colorSet = toObject(colorGroups, 'name', 'colors');
// Put black and white at the top level.
if ('' in colorSet) {
util._extend(colorSet, colorSet['']);
delete colorSet[''];
}
return colorSet;
}
function fetch(callback) {
http.get('http://www.google.com/design/spec/style/color.html', function(res) {
if (res.statusCode !== 200) {
callback('Status code: ' + res.statusCode);
return;
}
var html = '';
res.setEncoding('utf8');
res.on('readable', function() {
html += res.read();
});
res.on('end', function() {
var colorSet = parse(html);
callback(null, colorSet);
});
res.on('error', callback);
}).on('error', callback);
}
module.exports = fetch;
|
/*!
* jQuery JavaScript Library v1.10.1 -wrap,-ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-effects,-deprecated
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-06-03T15:16Z
*/
(function( window, undefined ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//"use strict";
var
// The deferred used on DOM ready
readyList,
// A central reference to the root jQuery(document)
rootjQuery,
// Support: IE<10
// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
location = window.location,
document = window.document,
docElem = document.documentElement,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "1.10.1 -wrap,-ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-effects,-deprecated",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler
completed = function( event ) {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
},
// Clean-up method for dom ready events
detach = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
/* jshint eqeqeq: false */
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
var key;
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Support: IE<9
// Handle iteration over inherited properties before own properties.
if ( jQuery.support.ownLast ) {
for ( key in obj ) {
return core_hasOwn.call( obj, key );
}
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
if ( data === null ) {
return data;
}
if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
if ( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
}
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && jQuery.trim( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var args, proxy, tmp;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
},
// A method for quickly swapping in/out CSS properties to get correct calculations.
// Note: this method belongs to the css module but it's needed here for the support module.
// If support gets modularized, this method should be moved back to the css module.
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
/*!
* Sizzle CSS Selector Engine v1.9.4-pre
* http://sizzlejs.com/
*
* Copyright 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-05-27
*/
(function( window, undefined ) {
var i,
support,
cachedruns,
Expr,
getText,
isXML,
compile,
outermostContext,
sortInput,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
hasDuplicate = false,
sortOrder = function() { return 0; },
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rsibling = new RegExp( whitespace + "*[+~]" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( documentIsHTML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* For feature detection
* @param {Function} fn The function to test for native support
*/
function isNative( fn ) {
return rnative.test( fn + "" );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key += " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied if the test fails
* @param {Boolean} test The result of a test. If true, null will be set as the handler in leiu of the specified handler
*/
function addHandle( attrs, handler, test ) {
attrs = attrs.split("|");
var current,
i = attrs.length,
setHandle = test ? null : handler;
while ( i-- ) {
// Don't override a user's handler
if ( !(current = Expr.attrHandle[ attrs[i] ]) || current === handler ) {
Expr.attrHandle[ attrs[i] ] = setHandle;
}
}
}
/**
* Fetches boolean attributes by node
* @param {Element} elem
* @param {String} name
*/
function boolHandler( elem, name ) {
// XML does not need to be checked as this will not be assigned for XML documents
var val = elem.getAttributeNode( name );
return val && val.specified ?
val.value :
elem[ name ] === true ? name.toLowerCase() : null;
}
/**
* Fetches attributes without interpolation
* http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
* @param {Element} elem
* @param {String} name
*/
function interpolationHandler( elem, name ) {
// XML does not need to be checked as this will not be assigned for XML documents
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
/**
* Uses defaultValue to retrieve value in IE6/7
* @param {Element} elem
* @param {String} name
*/
function valueHandler( elem ) {
// Ignore the value *property* on inputs by using defaultValue
// Fallback to Sizzle.attr by returning undefined where appropriate
// XML does not need to be checked as this will not be assigned for XML documents
if ( elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns Returns -1 if a precedes b, 1 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Detect xml
* @param {Element|Object} elem An element or a document
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var doc = node ? node.ownerDocument || node : preferredDoc,
parent = doc.parentWindow;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsHTML = !isXML( doc );
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
if ( parent && parent.frameElement ) {
parent.attachEvent( "onbeforeunload", function() {
setDocument();
});
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
support.attributes = assert(function( div ) {
// Support: IE<8
// Prevent attribute/property "interpolation"
div.innerHTML = "<a href='#'></a>";
addHandle( "type|href|height|width", interpolationHandler, div.firstChild.getAttribute("href") === "#" );
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
addHandle( booleans, boolHandler, div.getAttribute("disabled") == null );
div.className = "i";
return !div.getAttribute("className");
});
// Support: IE<9
// Retrieving value should defer to defaultValue
support.input = assert(function( div ) {
div.innerHTML = "<input>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
});
// IE6/7 still return empty string for value,
// but are actually retrieving the property
addHandle( "value", valueHandler, support.attributes && support.input );
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if getElementsByClassName can be trusted
support.getElementsByClassName = assert(function( div ) {
div.innerHTML = "<div class='a'></div><div class='a i'></div>";
// Support: Safari<4
// Catch class over-caching
div.firstChild.className = "i";
// Support: Opera<10
// Catch gEBCN failure to find non-leading classes
return div.getElementsByClassName("i").length === 2;
});
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = isNative(doc.querySelectorAll)) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Support: Opera 10-12/IE8
// ^= $= *= and empty values
// Should not select anything
// Support: Windows 8 Native Apps
// The type attribute is restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "t", "" );
if ( div.querySelectorAll("[t^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = isNative( (matches = docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = isNative(docElem.contains) || docElem.compareDocumentPosition ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( doc.createElement("div") ) & 1;
});
// Document order sorting
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b );
if ( compare ) {
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === doc || contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
}
// Not directly comparable, sort on existence of method
return a.compareDocumentPosition ? -1 : 1;
} :
function( a, b ) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
// Parentless nodes are either documents or disconnected
} else if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return doc;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = ( fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined );
return val === undefined ?
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null :
val;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] && match[4] !== undefined ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && context.parentNode || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector )
);
return results;
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Initialize against the default document
setDocument();
// Support: Chrome<<14
// Always assume duplicates if they aren't passed to the comparison function
[0, 0].sort( sortOrder );
support.detectDuplicates = hasDuplicate;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function( support ) {
var all, a, input, select, fragment, opt, eventName, isSupported, i,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Finish early in limited (non-browser) environments
all = div.getElementsByTagName("*") || [];
a = div.getElementsByTagName("a")[ 0 ];
if ( !a || !a.style || !all.length ) {
return support;
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
support.getSetAttribute = div.className !== "t";
// IE strips leading whitespace when .innerHTML is used
support.leadingWhitespace = div.firstChild.nodeType === 3;
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
support.tbody = !div.getElementsByTagName("tbody").length;
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
support.htmlSerialize = !!div.getElementsByTagName("link").length;
// Get the style information from getAttribute
// (IE uses .cssText instead)
support.style = /top/.test( a.getAttribute("style") );
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
support.hrefNormalized = a.getAttribute("href") === "/a";
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
support.opacity = /^0.5/.test( a.style.opacity );
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
support.cssFloat = !!a.style.cssFloat;
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
support.checkOn = !!input.value;
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
support.optSelected = opt.selected;
// Tests for enctype support on a form (#6743)
support.enctype = !!document.createElement("form").enctype;
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>";
// Will be defined later
support.inlineBlockNeedsLayout = false;
support.shrinkWrapBlocks = false;
support.pixelPosition = false;
support.deleteExpando = true;
support.noCloneEvent = true;
support.reliableMarginRight = true;
support.boxSizingReliable = true;
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE<9
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
// Check if we can trust getAttribute("value")
input = document.createElement("input");
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "checked", "t" );
input.setAttribute( "name", "t" );
fragment = document.createDocumentFragment();
fragment.appendChild( input );
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event)
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
for ( i in { submit: true, change: true, focusin: true }) {
div.setAttribute( eventName = "on" + i, "t" );
support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false;
}
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Support: IE<9
// Iteration over object's inherited properties before its own.
for ( i in jQuery( support ) ) {
break;
}
support.ownLast = i !== "0";
// Run tests that need a body at doc ready
jQuery(function() {
var container, marginDiv, tds,
divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
body.appendChild( container ).appendChild( div );
// Support: IE8
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Support: IE8
// Check if empty table cells still have offsetWidth/Height
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior.
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
// Workaround failing boxSizing test due to offsetWidth returning wrong value
// with some non-1 values of body zoom, ticket #13543
jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() {
support.boxSizing = div.offsetWidth === 4;
});
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = div.appendChild( document.createElement("div") );
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== core_strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Support: IE6
// Check if elements with layout shrink-wrap their children
div.style.display = "block";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
if ( support.inlineBlockNeedsLayout ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
// Null elements to avoid leaks in IE
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
all = select = fragment = opt = a = input = null;
return support;
})({});
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
function internalData( elem, name, data, pvt /* Internal Use Only */ ){
if ( !jQuery.acceptData( elem ) ) {
return;
}
var ret, thisCache,
internalKey = jQuery.expando,
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
// Avoid exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
cache[ id ] = isNode ? {} : { toJSON: jQuery.noop };
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( typeof name === "string" ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
i = name.length;
while ( i-- ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
/* jshint eqeqeq: false */
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
/* jshint eqeqeq: true */
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
jQuery.extend({
cache: {},
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"applet": true,
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data ) {
return internalData( elem, name, data );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
// Do not set data on non-element because it will not be cleared (#8335).
if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) {
return false;
}
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var attrs, name,
data = null,
i = 0,
elem = this[0];
// Special expections of .data basically thwart jQuery.access,
// so implement the relevant behavior ourselves
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attrs = elem.attributes;
for ( ; i < attrs.length; i++ ) {
name = attrs[i].name;
if ( name.indexOf("data-") === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
return arguments.length > 1 ?
// Sets one value
this.each(function() {
jQuery.data( this, key, value );
}) :
// Gets one value
// Try to fetch any internally stored data first
elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null;
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery._removeData( elem, type + "queue" );
jQuery._removeData( elem, key );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook,
rclass = /[\t\r\n\f]/g,
rreturn = /\r/g,
rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
getSetInput = jQuery.support.input;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
elem.className = jQuery.trim( cur );
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
elem.className = value ? jQuery.trim( cur ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.match( core_rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
// Toggle whole class name
} else if ( type === core_strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var ret, hooks, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// Use proper attribute retrieval(#6932, #12072)
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) {
optionSet = true;
}
}
// force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === core_strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( core_rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
elem[ propName ] = false;
// Support: IE<9
// Also clear defaultChecked/defaultSelected (if appropriate)
} else {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr;
jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ?
function( elem, name, isXML ) {
var fn = jQuery.expr.attrHandle[ name ],
ret = isXML ?
undefined :
/* jshint eqeqeq: false */
(jQuery.expr.attrHandle[ name ] = undefined) !=
getter( elem, name, isXML ) ?
name.toLowerCase() :
null;
jQuery.expr.attrHandle[ name ] = fn;
return ret;
} :
function( elem, name, isXML ) {
return isXML ?
undefined :
elem[ jQuery.camelCase( "default-" + name ) ] ?
name.toLowerCase() :
null;
};
});
// fix oldIE attroperties
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = {
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
return name === "value" || value === elem.getAttribute( name ) ?
value :
undefined;
}
};
jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords =
// Some attributes are constructed with empty-string values when not defined
function( elem, name, isXML ) {
var ret;
return isXML ?
undefined :
(ret = elem.getAttributeNode( name )) && ret.value !== "" ?
ret.value :
null;
};
jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return ret && ret.specified ?
ret.value :
undefined;
},
set: nodeHook.set
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
};
});
}
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !jQuery.support.hrefNormalized ) {
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !jQuery.support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = core_hasOwn.call( event, "type" ) ? event.type : event,
namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = core_slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
/* jshint eqeqeq: false */
for ( ; cur != this; cur = cur.parentNode || this ) {
/* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Even when returnValue equals to undefined Firefox will still show alert
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === core_strundefined ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "submitBubbles" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "submitBubbles", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "changeBubbles", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
var isSimple = /^.[^:#\[\.,]*$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i,
ret = [],
self = this,
len = self.length;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
cur = ret.push( cur );
break;
}
}
}
return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( jQuery.unique(all) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
ret = jQuery.unique( ret );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
ret = ret.reverse();
}
}
return this.pushStack( ret );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( isSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var
// Snapshot the DOM in case .domManip sweeps something relevant into its fragment
args = jQuery.map( this, function( elem ) {
return [ elem.nextSibling, elem.parentNode ];
}),
i = 0;
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
var next = args[ i++ ],
parent = args[ i++ ];
if ( parent ) {
// Don't use the snapshot next if it has moved (#13810)
if ( next && next.parentNode !== parent ) {
next = this.nextSibling;
}
jQuery( this ).remove();
parent.insertBefore( elem, next );
}
// Allow new content to include elements from the context set
}, true );
// Force removal if there was no new content (e.g., from empty arguments)
return i ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback, allowIntersection ) {
// Flatten any nested arrays
args = core_concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[0] = value.call( this, index, self.html() );
}
self.domManip( args, callback, allowIntersection );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[i], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Hope ajax is available...
jQuery._evalUrl( node.src );
} else {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
// Support: IE<8
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone(true);
jQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
core_push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( manipulation_rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
// Fix all IE cloning issues
for ( i = 0; (node = srcElements[i]) != null; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
fixCloneNodeIssues( node, destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0; (node = srcElements[i]) != null; i++ ) {
cloneCopyEvent( node, destElements[i] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment( context ),
nodes = [],
i = 0;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test( elem ) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test( elem ) ?
tmp :
0;
j = elem && elem.childNodes.length;
while ( j-- ) {
if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
jQuery.merge( nodes, tmp.childNodes );
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while ( tmp.firstChild ) {
tmp.removeChild( tmp.firstChild );
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if ( tmp ) {
safe.removeChild( tmp );
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( safe.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
tmp = null;
return safe;
},
cleanData: function( elems, /* internal */ acceptData ) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( typeof elem.removeAttribute !== core_strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
core_deletedIds.push( id );
}
}
}
}
},
_evalUrl: function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
}
});
var iframe, getStyles, curCSS,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
if ( !values[ index ] ) {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
var len, styles,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
var bool = typeof state === "boolean";
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var num, val, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
// NOTE: we've included the "window" in window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
return window.getComputedStyle( elem, null );
};
curCSS = function( elem, name, _computed ) {
var width, minWidth, maxWidth,
computed = _computed || getStyles( elem ),
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined,
style = elem.style;
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, _computed ) {
var left, rs, rsLeft,
computed = _computed || getStyles( elem ),
ret = computed ? computed[ name ] : undefined,
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = ( iframe ||
jQuery("<iframe frameborder='0' width='0' height='0'/>")
.css( "cssText", "display:block !important" )
).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document;
doc.write("<!doctype html><html><body>");
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
// Called ONLY from within css_defaultDisplay
function actualDisplay( name, doc ) {
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
display = jQuery.css( elem[0], "display" );
elem.remove();
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there is no filter style applied in a css rule or unset inline opacity, we are done
if ( value === "" || currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function(){
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !manipulation_rcheckableType.test( type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.extend({
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
});
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== core_strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
};
jQuery.offset = {
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
parentOffset = { top: 0, left: 0 },
elem = this[ 0 ];
// fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// we assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
if ( typeof module === "object" && module && typeof module.exports === "object" ) {
// Expose jQuery as module.exports in loaders that implement the Node
// module pattern (including browserify). Do not create the global, since
// the user will be storing it themselves locally, and globals are frowned
// upon in the Node module world.
module.exports = jQuery;
} else {
// Otherwise expose jQuery to the global object as usual
window.jQuery = window.$ = jQuery;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function () { return jQuery; } );
}
}
})( window );
|
/* */
(function(process) {
"use strict";
var rawAsap = require('./browser-raw');
var freeTasks = [];
module.exports = asap;
function asap(task) {
var rawTask;
if (freeTasks.length) {
rawTask = freeTasks.pop();
} else {
rawTask = new RawTask();
}
rawTask.task = task;
rawTask.domain = process.domain;
rawAsap(rawTask);
}
function RawTask() {
this.task = null;
this.domain = null;
}
RawTask.prototype.call = function() {
if (this.domain) {
this.domain.enter();
}
var threw = true;
try {
this.task.call();
threw = false;
if (this.domain) {
this.domain.exit();
}
} finally {
if (threw) {
rawAsap.requestFlush();
}
this.task = null;
this.domain = null;
freeTasks.push(this);
}
};
})(require('process'));
|
import { isObject } from 'utils/is';
import { getMatchingKeypaths, getKeypath, normalise } from 'shared/keypaths';
import runloop from 'global/runloop';
export default function Ractive$set ( keypath, value ) {
var map, promise;
promise = runloop.start( this, true );
// Set multiple keypaths in one go
if ( isObject( keypath ) ) {
map = keypath;
for ( keypath in map ) {
if ( map.hasOwnProperty( keypath) ) {
value = map[ keypath ];
set( this, keypath, value );
}
}
}
// Set a single keypath
else {
set( this, keypath, value );
}
runloop.end();
return promise;
}
function set ( ractive, keypath, value ) {
keypath = getKeypath( normalise( keypath ) );
if ( keypath.isPattern ) {
getMatchingKeypaths( ractive, keypath ).forEach( keypath => {
ractive.viewmodel.set( keypath, value );
});
} else {
ractive.viewmodel.set( keypath, value );
}
} |
/**
* Impact++ core that requires the primary modules and enhances ImpactJS's core.
* @namespace ig
* @author Collin Hover - collinhover.com
* @example
* // getting started with Impact++ is easy!
* // add the two basic scripts to the end of your game HTML file:
* // first the ImpactJS main script
* <script type="text/javascript" src="lib/impact/impact.js"></script>
* // then your game's main script
* <script type="text/javascript" src="lib/game/main.js"></script>
* // now inside your game's main script file
* // you'll set it up the same as when using ImpactJS
* // define the main module (script)
* ig.module(
* 'game.main'
* )
* // then require the other modules
* .requires(
* // to hook Impact++ into your game
* // all you need to do is require one module
* 'plusplus.core.plusplus',
* // then don't forget your levels
* 'game.levels.name'
* )
* // now define how your game starts up
* .defines(function () {
*
* // always use strict
* "use strict";
*
* // store the config in a local variable
* // this is a good pattern to follow in general
* var _c = ig.CONFIG;
*
* // now have your game extend ig.GameExtended
* var myGameClass = ig.GameExtended.extend({
* // game settings go here
* });
*
* // (optionally, add custom settings in 'plusplus/config-user.js')
*
* // then start the game as usual with your game and config
* ig.main(
* // you'll need a canvas element with an id of 'canvas'
* "#canvas",
* // your game class
* myGameClass,
* // this value does nothing
* 60,
* // the width / height / scale of your game
* // don't forget that Impact++ can scale dynamically
* // and can be resolution independent (see config)
* _c.GAME_WIDTH,
* _c.GAME_HEIGHT,
* _c.SCALE,
* // and the Impact++ customizable loader
* // within which you can easily change the logos!
* ig.LoaderExtended
* );
*
* // and whenever you create a new entity remember...
* // plain entities extend ig.EntityExtended
* var myEntityClass = ig.EntityExtended.extend({
* // entity settings go here
* });
* // and in a similar vein...
* // characters entities extend ig.Character
* // creature entities extend ig.Creature
* // particles entities extend ig.Particle
* // player entities extend ig.Player
* // and so on (we've got lots of abstracts)
*
* });
* // for a basic tutorial
* // check out the Jump n' Run example
* // in the "examples/jumpnrun" directory
* // or for a more advanced tutorial
* // check out the SUPER COLLIDER! example
* // in the "examples/supercollider" directory
* // which includes almost every feature in Impact++!
*/
// first, some modifications necessary before we start
/**
* Enhancements and fixes to Impact's merge method.
* <br>- ignores undefined values and copy null values
* <br>- handles true / false values converted to string by weltmeister (editor)
* @private
*/
ig.merge = function(original, extended) {
original = original || {};
if (extended) {
for (var key in extended) {
var ext = extended[key];
var extType = typeof ext;
if (extType !== 'undefined') {
if (
extType !== 'object' ||
ext instanceof HTMLElement ||
ext instanceof ig.Class
) {
// ugly, perhaps there is a better way?
if (extType === 'string') {
if (ext === 'true') {
ext = true;
} else if (ext === 'false') {
ext = false;
}
}
original[key] = ext;
} else {
if (!original[key] || typeof(original[key]) !== 'object') {
original[key] = (ext instanceof Array) ? [] : {};
}
ig.merge(original[key], ext);
}
}
}
}
return original;
};
// start Impact++
ig.module(
'plusplus.core.plusplus'
)
.requires(
'plusplus.core.config',
'plusplus.core.loader',
'plusplus.core.game',
'plusplus.helpers.signals'
)
.defines(function() {
"use strict";
var _c = ig.CONFIG;
/**
* Modifications and enhancements to Impact's system.
* @class ig.System
* @extends ig.Class
* @memberof ig
* @author Collin Hover - collinhover.com
*/
ig.System.inject({
/**
* Size of system based on minimum of width and height.
* @type Number
* @default
*/
size: 240,
/**
* Signal dispatched when system is resized.
* <br>- created on init.
* @type ig.Signal
*/
onResized: null,
/**
* Initializes system and creates extra properties such as resize signal
* @param {String} canvasId
* @param {Number} fps
* @param {Number} width
* @param {Number} height
* @param {Number} scale
*/
init: function(canvasId, fps, width, height, scale) {
this.onResized = new ig.Signal();
this.fps = fps;
this.clock = new ig.Timer();
this.canvas = ig.$(canvasId);
this.context = this.canvas.getContext('2d');
this.getDrawPos = ig.System.drawMode;
this.resize(width, height, scale);
},
/**
* Runs system, accounting for maximum framerate.
*/
run: function() {
ig.Timer.step();
// only do run if timer has stepped
if (ig.Timer.stepped) {
this.tick = this.clock.tick();
this.delegate.run();
ig.input.clearPressed();
if (this.newGameClass) {
this.setGameNow(this.newGameClass);
this.newGameClass = null;
}
}
},
/**
* Resizes system and dispatches resize signal.
* @param {Number} width
* @param {Number} height
* @param {Number} scale
* @param {Boolean} [force=false] whether to force global resize (only do this when absolutely necessary).
*/
resize: function(width, height, scale, force) {
var modifier;
if (ig.ua.pixelRatio > 1 && (!this.context.webkitBackingStorePixelRatio || this.context.webkitBackingStorePixelRatio > 1)) {
modifier = ig.ua.pixelRatio;
} else {
modifier = 1;
}
this.width = width * modifier;
this.height = height * modifier;
if (typeof scale !== 'undefined' && scale !== null) {
this.scale = scale;
}
this.realWidth = this.width * this.scale;
this.realHeight = this.height * this.scale;
// retina support
this.canvas.width = this.realWidth;
this.canvas.height = this.realHeight;
this.canvas.style.width = Math.round(this.realWidth / modifier) + "px";
this.canvas.style.height = Math.round(this.realHeight / modifier) + "px";
this.size = Math.min(this.width, this.height);
// switch to crisp scaling when using a scale other than 1
if (this.scale !== 1 && _c.AUTO_CRISP_SCALING) {
ig.System.scaleMode = ig.System.SCALE.CRISP;
}
ig.System.scaleMode(this.canvas, this.context);
this.onResized.dispatch(force);
}
});
});
|
var searchData=
[
['opticaldistance',['OpticalDistance',['../classcom_1_1lasarobotics_1_1library_1_1sensor_1_1modernrobotics_1_1_optical_distance.html',1,'com::lasarobotics::library::sensor::modernrobotics']]]
];
|
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var rangeParser = require('parse-numeric-range');
module.exports = function (language) {
if (!language) {
return '';
}
var obj = {
path: null,
nocopy: false
// removes the () part completly from the string, so the {} logic is untouched
};if (language.split('(').length > 1) {
var i0 = language.indexOf('(');
var i1 = language.lastIndexOf(')');
var params = language.slice(i0 + 1, i1);
language = language.slice(0, i0) + language.slice(i1 + 1, language.length);
var query = params.split('&').map(function (param) {
return param.split('=');
});
query.forEach(function (q) {
if (q[0] === 'path') {
obj.path = q[1].replace(/"/g, '');
}
if (q[0] === 'nocopy') {
obj.nocopy = true;
}
});
}
if (language.split('{').length > 1) {
var _language$split = language.split('{'),
_language$split2 = _slicedToArray(_language$split, 2),
splitLanguage = _language$split2[0],
rangeStr = _language$split2[1];
rangeStr = rangeStr.slice(0, -1);
return _extends({
splitLanguage: splitLanguage,
highlightLines: rangeParser.parse(rangeStr).filter(function (n) {
return n > 0;
})
}, obj);
}
return _extends({ splitLanguage: language }, obj);
};
// ```js{1,2-10}(path="src/components/index.js"&nocopy) |
//! moment.js locale configuration
//! locale : japanese (ja)
//! author : LI Long : https://github.com/baryon
import moment from '../moment';
export default moment.defineLocale('ja', {
months : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
weekdays : '日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日'.split('_'),
weekdaysShort : '日_月_火_水_木_金_土'.split('_'),
weekdaysMin : '日_月_火_水_木_金_土'.split('_'),
longDateFormat : {
LT : 'Ah時m分',
LTS : 'Ah時m分s秒',
L : 'YYYY/MM/DD',
LL : 'YYYY年M月D日',
LLL : 'YYYY年M月D日Ah時m分',
LLLL : 'YYYY年M月D日Ah時m分 dddd'
},
meridiemParse: /午前|午後/i,
isPM : function (input) {
return input === '午後';
},
meridiem : function (hour, minute, isLower) {
if (hour < 12) {
return '午前';
} else {
return '午後';
}
},
calendar : {
sameDay : '[今日] LT',
nextDay : '[明日] LT',
nextWeek : '[来週]dddd LT',
lastDay : '[昨日] LT',
lastWeek : '[前週]dddd LT',
sameElse : 'L'
},
ordinalParse : /\d{1,2}日/,
ordinal : function (number, period) {
switch (period) {
case 'd':
case 'D':
case 'DDD':
return number + '日';
default:
return number;
}
},
relativeTime : {
future : '%s後',
past : '%s前',
s : '数秒',
m : '1分',
mm : '%d分',
h : '1時間',
hh : '%d時間',
d : '1日',
dd : '%d日',
M : '1ヶ月',
MM : '%dヶ月',
y : '1年',
yy : '%d年'
}
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:f496b65a5c0d027523555084a35b76b6d1560f8cb3bd944963be4cb1dc670eec
size 4711
|
describe('node-jsx', function() {
it('should work', function() {
require('./index').install();
expect(require('./test-module')).toBe('jonx');
});
}); |
import { setOwner } from '@ember/-internals/owner';
import { runDestroy, buildOwner, moduleFor, AbstractTestCase } from 'internal-test-helpers';
import Service, { inject as injectService } from '@ember/service';
import { Object as EmberObject } from '@ember/-internals/runtime';
import EmberRoute from '../../lib/system/route';
import { defineProperty } from '../../../metal';
let route, routeOne, routeTwo, lookupHash;
moduleFor(
'Route',
class extends AbstractTestCase {
constructor() {
super();
route = EmberRoute.create();
}
teardown() {
super.teardown();
runDestroy(route);
route = routeOne = routeTwo = lookupHash = undefined;
}
['@test default store utilizes the container to acquire the model factory'](assert) {
assert.expect(4);
let Post = EmberObject.extend();
let post = {};
Post.reopenClass({
find() {
return post;
},
});
let ownerOptions = {
ownerOptions: {
hasRegistration() {
return true;
},
factoryFor(fullName) {
assert.equal(fullName, 'model:post', 'correct factory was looked up');
return {
class: Post,
create() {
return Post.create();
},
};
},
},
};
let owner = buildOwner(ownerOptions);
setOwner(route, owner);
// Override the computed property by redefining it
defineProperty(route, '_qp', null, null);
assert.equal(route.model({ post_id: 1 }), post);
assert.equal(route.findModel('post', 1), post, '#findModel returns the correct post');
runDestroy(owner);
}
["@test 'store' can be injected by data persistence frameworks"](assert) {
assert.expect(8);
runDestroy(route);
let owner = buildOwner();
let post = {
id: 1,
};
let Store = EmberObject.extend({
find(type, value) {
assert.ok(true, 'injected model was called');
assert.equal(type, 'post', 'correct type was called');
assert.equal(value, 1, 'correct value was called');
return post;
},
});
owner.register('route:index', EmberRoute);
owner.register('store:main', Store);
owner.inject('route', 'store', 'store:main');
route = owner.lookup('route:index');
assert.equal(route.model({ post_id: 1 }), post, '#model returns the correct post');
assert.equal(route.findModel('post', 1), post, '#findModel returns the correct post');
runDestroy(owner);
}
["@test assert if 'store.find' method is not found"]() {
runDestroy(route);
let owner = buildOwner();
let Post = EmberObject.extend();
owner.register('route:index', EmberRoute);
owner.register('model:post', Post);
route = owner.lookup('route:index');
expectAssertion(function() {
route.findModel('post', 1);
}, 'Post has no method `find`.');
runDestroy(owner);
}
['@test asserts if model class is not found']() {
runDestroy(route);
let owner = buildOwner();
owner.register('route:index', EmberRoute);
route = owner.lookup('route:index');
expectAssertion(function() {
route.model({ post_id: 1 });
}, /You used the dynamic segment post_id in your route undefined, but <Ember.Object:ember\d+>.Post did not exist and you did not override your route's `model` hook./);
runDestroy(owner);
}
["@test 'store' does not need to be injected"](assert) {
runDestroy(route);
let owner = buildOwner();
owner.register('route:index', EmberRoute);
route = owner.lookup('route:index');
ignoreAssertion(function() {
route.model({ post_id: 1 });
});
assert.ok(true, 'no error was raised');
runDestroy(owner);
}
["@test modelFor doesn't require the router"](assert) {
let owner = buildOwner();
setOwner(route, owner);
let foo = { name: 'foo' };
let FooRoute = EmberRoute.extend({
currentModel: foo,
});
owner.register('route:foo', FooRoute);
assert.strictEqual(route.modelFor('foo'), foo);
runDestroy(owner);
}
["@test modelFor doesn't require the routerMicrolib"](assert) {
let route = EmberRoute.create({
_router: { _routerMicrolib: null },
});
let owner = buildOwner();
setOwner(route, owner);
let foo = { name: 'foo' };
let FooRoute = EmberRoute.extend({
currentModel: foo,
});
owner.register('route:foo', FooRoute);
assert.strictEqual(route.modelFor('foo'), foo);
runDestroy(owner);
}
['@test .send just calls an action if the router is absent'](assert) {
assert.expect(7);
let route = EmberRoute.extend({
actions: {
returnsTrue(foo, bar) {
assert.equal(foo, 1);
assert.equal(bar, 2);
assert.equal(this, route);
return true;
},
returnsFalse() {
assert.ok(true, 'returnsFalse was called');
return false;
},
},
}).create();
assert.equal(route.send('returnsTrue', 1, 2), true);
assert.equal(route.send('returnsFalse'), false);
assert.equal(route.send('nonexistent', 1, 2, 3), undefined);
runDestroy(route);
}
['@test .send just calls an action if the routers internal router property is absent'](assert) {
assert.expect(7);
let route = EmberRoute.extend({
router: {},
actions: {
returnsTrue(foo, bar) {
assert.equal(foo, 1);
assert.equal(bar, 2);
assert.equal(this, route);
return true;
},
returnsFalse() {
assert.ok(true, 'returnsFalse was called');
return false;
},
},
}).create();
assert.equal(true, route.send('returnsTrue', 1, 2));
assert.equal(false, route.send('returnsFalse'));
assert.equal(undefined, route.send('nonexistent', 1, 2, 3));
runDestroy(route);
}
['@test .send asserts if called on a destroyed route']() {
route.routeName = 'rip-alley';
runDestroy(route);
expectAssertion(() => {
route.send('trigger-me-dead');
}, "Attempted to call .send() with the action 'trigger-me-dead' on the destroyed route 'rip-alley'.");
}
}
);
moduleFor(
'Route serialize',
class extends AbstractTestCase {
constructor() {
super();
route = EmberRoute.create();
}
teardown() {
runDestroy(route);
}
['@test returns the models properties if params does not include *_id'](assert) {
let model = { id: 2, firstName: 'Ned', lastName: 'Ryerson' };
assert.deepEqual(
route.serialize(model, ['firstName', 'lastName']),
{ firstName: 'Ned', lastName: 'Ryerson' },
'serialized correctly'
);
}
['@test returns model.id if params include *_id'](assert) {
let model = { id: 2 };
assert.deepEqual(route.serialize(model, ['post_id']), { post_id: 2 }, 'serialized correctly');
}
['@test returns checks for existence of model.post_id before trying model.id'](assert) {
let model = { post_id: 3 };
assert.deepEqual(route.serialize(model, ['post_id']), { post_id: 3 }, 'serialized correctly');
}
['@test returns undefined if model is not set'](assert) {
assert.equal(route.serialize(undefined, ['post_id']), undefined, 'serialized correctly');
}
}
);
moduleFor(
'Route interaction',
class extends AbstractTestCase {
constructor() {
super();
let owner = {
lookup(fullName) {
return lookupHash[fullName];
},
};
routeOne = EmberRoute.create({ routeName: 'one' });
routeTwo = EmberRoute.create({ routeName: 'two' });
setOwner(routeOne, owner);
setOwner(routeTwo, owner);
lookupHash = {
'route:one': routeOne,
'route:two': routeTwo,
};
}
teardown() {
runDestroy(routeOne);
runDestroy(routeTwo);
}
['@test route._qp does not crash if the controller has no QP, or setProperties'](assert) {
lookupHash['controller:test'] = {};
routeOne.controllerName = 'test';
let qp = routeOne.get('_qp');
assert.deepEqual(qp.map, {}, 'map should be empty');
assert.deepEqual(qp.propertyNames, [], 'property names should be empty');
assert.deepEqual(qp.qps, [], 'qps is should be empty');
}
["@test controllerFor uses route's controllerName if specified"](assert) {
let testController = {};
lookupHash['controller:test'] = testController;
routeOne.controllerName = 'test';
assert.equal(routeTwo.controllerFor('one'), testController);
}
}
);
moduleFor(
'Route injected properties',
class extends AbstractTestCase {
['@test services can be injected into routes'](assert) {
let owner = buildOwner();
owner.register(
'route:application',
EmberRoute.extend({
authService: injectService('auth'),
})
);
owner.register('service:auth', Service.extend());
let appRoute = owner.lookup('route:application');
let authService = owner.lookup('service:auth');
assert.equal(authService, appRoute.get('authService'), 'service.auth is injected');
}
}
);
moduleFor(
'Route with engines',
class extends AbstractTestCase {
["@test paramsFor considers an engine's mountPoint"](assert) {
let router = {
_deserializeQueryParams() {},
_routerMicrolib: {
state: {
routeInfos: [{ name: 'posts' }],
params: {
'foo.bar': { a: 'b' },
'foo.bar.posts': { c: 'd' },
},
},
},
};
let engineInstance = buildOwner({
ownerOptions: {
routable: true,
mountPoint: 'foo.bar',
lookup(name) {
if (name === 'route:posts') {
return postsRoute;
} else if (name === 'route:application') {
return applicationRoute;
}
},
},
});
let applicationRoute = EmberRoute.create({
_router: router,
routeName: 'application',
fullRouteName: 'foo.bar',
});
let postsRoute = EmberRoute.create({
_router: router,
routeName: 'posts',
fullRouteName: 'foo.bar.posts',
});
let route = EmberRoute.create({ _router: router });
setOwner(applicationRoute, engineInstance);
setOwner(postsRoute, engineInstance);
setOwner(route, engineInstance);
assert.deepEqual(
route.paramsFor('application'),
{ a: 'b' },
'params match for root `application` route in engine'
);
assert.deepEqual(
route.paramsFor('posts'),
{ c: 'd' },
'params match for `posts` route in engine'
);
}
["@test modelFor considers an engine's mountPoint"](assert) {
let applicationModel = { id: '1' };
let postsModel = { id: '2' };
let router = {
_routerMicrolib: {
activeTransition: {
resolvedModels: {
'foo.bar': applicationModel,
'foo.bar.posts': postsModel,
},
},
},
};
let engineInstance = buildOwner({
ownerOptions: {
routable: true,
mountPoint: 'foo.bar',
lookup(name) {
if (name === 'route:posts') {
return postsRoute;
} else if (name === 'route:application') {
return applicationRoute;
}
},
},
});
let applicationRoute = EmberRoute.create({
_router: router,
routeName: 'application',
});
let postsRoute = EmberRoute.create({
_router: router,
routeName: 'posts',
});
let route = EmberRoute.create({ _router: router });
setOwner(applicationRoute, engineInstance);
setOwner(postsRoute, engineInstance);
setOwner(route, engineInstance);
assert.strictEqual(route.modelFor('application'), applicationModel);
assert.strictEqual(route.modelFor('posts'), postsModel);
}
["@test transitionTo considers an engine's mountPoint"](assert) {
let router = {
transitionTo(route) {
return route;
},
};
let engineInstance = buildOwner({
ownerOptions: {
routable: true,
mountPoint: 'foo.bar',
},
});
let route = EmberRoute.create({ _router: router });
setOwner(route, engineInstance);
assert.strictEqual(
route.transitionTo('application'),
'foo.bar.application',
'properly prefixes application route'
);
assert.strictEqual(
route.transitionTo('posts'),
'foo.bar.posts',
'properly prefixes child routes'
);
assert.throws(() => route.transitionTo('/posts'), 'throws when trying to use a url');
let queryParams = {};
assert.strictEqual(
route.transitionTo(queryParams),
queryParams,
'passes query param only transitions through'
);
}
["@test intermediateTransitionTo considers an engine's mountPoint"](assert) {
let lastRoute;
let router = {
intermediateTransitionTo(route) {
lastRoute = route;
},
};
let engineInstance = buildOwner({
ownerOptions: {
routable: true,
mountPoint: 'foo.bar',
},
});
let route = EmberRoute.create({ _router: router });
setOwner(route, engineInstance);
route.intermediateTransitionTo('application');
assert.strictEqual(lastRoute, 'foo.bar.application', 'properly prefixes application route');
route.intermediateTransitionTo('posts');
assert.strictEqual(lastRoute, 'foo.bar.posts', 'properly prefixes child routes');
assert.throws(
() => route.intermediateTransitionTo('/posts'),
'throws when trying to use a url'
);
let queryParams = {};
route.intermediateTransitionTo(queryParams);
assert.strictEqual(lastRoute, queryParams, 'passes query param only transitions through');
}
["@test replaceWith considers an engine's mountPoint"](assert) {
let router = {
replaceWith(route) {
return route;
},
};
let engineInstance = buildOwner({
ownerOptions: {
routable: true,
mountPoint: 'foo.bar',
},
});
let route = EmberRoute.create({ _router: router });
setOwner(route, engineInstance);
assert.strictEqual(
route.replaceWith('application'),
'foo.bar.application',
'properly prefixes application route'
);
assert.strictEqual(
route.replaceWith('posts'),
'foo.bar.posts',
'properly prefixes child routes'
);
assert.throws(() => route.replaceWith('/posts'), 'throws when trying to use a url');
let queryParams = {};
assert.strictEqual(
route.replaceWith(queryParams),
queryParams,
'passes query param only transitions through'
);
}
}
);
|
var Model = function ( attributes ) {
this.attributes = attributes;
this.callbacks = {};
this.transformers = {};
};
Model.prototype = {
set: function ( attr, newValue ) {
var transformer, oldValue = this.attributes[ attr ];
if ( transformer = this.transformers[ attr ] ) {
newValue = transformer.call( this, newValue, oldValue );
}
if ( oldValue !== newValue ) {
this.attributes[ attr ] = newValue;
this.fire( 'change', attr, newValue );
}
},
get: function ( attr ) {
return this.attributes[ attr ];
},
reset: function ( newData ) {
var attr;
this.attributes = {};
for ( attr in newData ) {
if ( newData.hasOwnProperty( attr ) ) {
this.set( attr, newData[ attr ] );
}
}
},
transform: function ( attr, transformer ) {
this.transformers[ attr ] = transformer;
if ( this.attributes.hasOwnProperty( attr ) ) {
this.set( attr, this.get( attr ) );
}
},
on: function ( eventName, callback ) {
var self = this;
if ( !this.callbacks[ eventName ] ) {
this.callbacks[ eventName ] = [];
}
this.callbacks[ eventName ].push( callback );
return {
cancel: function () {
self.off( eventName, callback );
}
}
},
off: function ( eventName, callback ) {
var callbacks, index;
callbacks = this.callbacks[ eventName ];
if ( !callbacks ) {
return;
}
index = callbacks.indexOf( callback );
if ( index !== -1 ) {
callbacks.splice( index, 1 );
}
},
fire: function ( eventName ) {
var args, callbacks, i;
callbacks = this.callbacks[ eventName ];
if ( !callbacks ) {
return;
}
args = Array.prototype.slice.call( arguments, 1 );
i = callbacks.length;
while ( i-- ) {
callbacks[i].apply( null, args );
}
}
};
Model.adaptor = {
filter: function ( object ) {
return object instanceof Model;
},
wrap: function ( ractive, object, keypath, prefix ) {
var listener, setting;
listener = object.on( 'change', function ( attr, value ) {
if ( setting ) {
return;
}
setting = true;
ractive.set( prefix( attr, value ) );
setting = false;
});
return {
get: function () {
return object.attributes;
},
teardown: function () {
listener.cancel();
},
set: function ( attr, value ) {
if ( setting ) {
return;
}
setting = true;
object.set( attr, value );
setting = false;
},
reset: function ( newData ) {
var attr;
if ( newData instanceof Model ) {
return false; // teardown
}
if ( !newData || typeof newData !== 'object' ) {
return false;
}
object.reset( newData );
ractive.update( keypath );
}
};
}
};
export default Model; |
//Written by Nabanita Maji and Cliff Shaffer
"use strict";
/*global alert: true, ODSA */
(function ($) {
var jsav;
var x;
var y;
var mat1,mat2;
var mat1data;
var mat2data;
function runit() {
ODSA.AV.reset(true);
jsav = new JSAV($('.avcontainer'));
jsav.umsg("The following two matrices need to be multiplied.");
x = 0; y = 0;
mat1data=[[2,3],[6,7],[4,9]];
mat2data=[[1,10,5],[12,8,11]];
mat1 = new jsav.ds.matrix(mat1data,{style:"matrix",left:x+30,top:y+0});
for(var i=0;i<3;i++)
for(var j=0;j<2;j++)
mat1.css(i,j,{"background-color":"Wheat"});
mat1.show();
jsav.label("X",{left:x+190,top:y+10});
mat2 = new jsav.ds.matrix(mat2data,{style:"matrix",left:x+280,top:y+0});
for(var i=0;i<2;i++)
for(var j=0;j<3;j++)
mat2.css(i,j,{"background-color":"PowderBlue"});
mat2.show();
jsav.displayInit();
jsav.step();
jsav.umsg ("Each of the two matrices are transformed into corresponding symmeric matrices by using its transpose as shown.");
var r21 = jsav.g.rect(0,200,435,220);
r21.show();
var l11 = jsav.g.line(70,130,70,150, {"stroke-width": 3});
l11.show();
var l12 = jsav.g.line(70,170,70,200, {"stroke-width": 3, "arrow-end": "classic-wide-long"});
l12.show();
var l21 = jsav.g.line(350,110,350,150, {"stroke-width": 3});
l21.show();
var l22 = jsav.g.line(350,170,350,200, {"stroke-width": 3, "arrow-end": "classic-wide-long"});
l22.show();
var r2 = jsav.g.rect(0,150,200,20);
jsav.label("Transformation (Cost:O(mn))",{left:5,top:135});
r2.show();
var r3 = jsav.g.rect(250,150,200,20);
jsav.label("Transformation (Cost:O(mn))",{left:255,top:135});
r3.show();
var mat1Transformed = transform(mat1data,3,2,0);
var mat1TransDisp = new jsav.ds.matrix(mat1Transformed,{style:"matrix",left:x+10,top:y+200});
for(var i=0;i<3;i++)
for(var j=3;j<5;j++)
mat1TransDisp.css(i,j,{"background-color":"Wheat"});
for(var i=3;i<5;i++)
for(var j=0;j<3;j++)
mat1TransDisp.css(i,j,{"background-color":"Khaki"});
mat1TransDisp.show();
jsav.label("X",{left:x+210,top:y+270});
var mat2Transformed = transform(mat2data,2,3,1);
var mat2TransDisp = new jsav.ds.matrix(mat2Transformed,{style:"matrix",left:x+250,top:y+200});
for(var i=0;i<3;i++)
for(var j=3;j<5;j++)
mat2TransDisp.css(i,j,{"background-color":"LightSteelBlue"});
for(var i=3;i<5;i++)
for(var j=0;j<3;j++)
mat2TransDisp.css(i,j,{"background-color":"PowderBlue"});
mat2TransDisp.show();
jsav.step();
jsav.umsg("Then the two symmetric matrices are multiplied.");
var r31 = jsav.g.rect(535,200,200,220);
r31.show();
var l31 = jsav.g.line(450,300,520,300, {"stroke-width": 3, "arrow-end": "classic-wide-long"});
l31.show();
jsav.label("Multiply",{left:450,top:300});
var product = multiply(mat1Transformed,mat2Transformed,5,5,5);
var productDisp = new jsav.ds.matrix(product,{style:"matrix",left:x+550,top:y+200});
productDisp.show();
jsav.step();
for(var i=0;i<3;i++)
for(var j=0;j<3;j++)
productDisp.css(i,j,{"background-color":"#CCFF99"});
var r32 = jsav.g.rect(560,220,95,100);
r31.show();
var r4 = jsav.g.rect(550,150,200,20);
jsav.label("Reverse Transform (O(mn))",{left:555,top:135});
r4.show();
var l31 = jsav.g.line(640,150,640,120, {"stroke-width": 3, "arrow-end": "classic-wide-long"});
l31.show();
var l32 = jsav.g.line(640,170,640,200, {"stroke-width": 3});
l32.show();
jsav.umsg("The 3*3 matrix in the upper left corner gives the output array.");
jsav.step();
var verifyprod = multiply(mat1data,mat2data,3,3,2);
var verifyprodDisp = new jsav.ds.matrix(verifyprod,{style:"matrix",left:x+600,top:y+0});
for(var i=0;i<3;i++)
for(var j=0;j<3;j++)
verifyprodDisp.css(i,j,{"background-color":"#CCFF99"});
verifyprodDisp.show();
jsav.label("Output Array", {left: 610, top: -15});
jsav.umsg("Total cost = O(mn) + cost of symmetric multiply.");
jsav.recorded();
}
function transpose(matrix,row,col){
var result = new Array(col);;
for(var i=0;i<col;i++)
result[i]=new Array(row);
for(var i=0;i<col;i++){
for(var j=0;j<row;j++){
result[i][j] = matrix[j][i];
}
}
return result;
}
function zeroMat(row,col){
var result = new Array(row);
for(var i=0;i<row;i++)
result[i]=new Array(col);
for(var i=0;i<row;i++)
for(var j=0;j<col;j++)
result[i][j]=0;
return result;
}
function transform(matrix,row,col,flag){
var num = row+col;
var result = zeroMat(num,num);
var matrixT = transpose(matrix,row,col) ;
for(var i=0;i<row;i++){
for(var j=0;j<col;j++){
if(flag==0){
result[i][row+j]=matrix[i][j];
result[row+j][i]=matrixT[j][i];
}
else if(flag==1) {
result[j][col+i]=matrixT[j][i];
result[col+i][j]=matrix[i][j];
}
}
}
return result;
}
function multiply(mat1,mat2,row,col,mid){
var result = zeroMat(row,col);
for(var i=0;i<row;i++)
for(var j=0;j<col;j++)
for(var k=0;k<mid;k++)
result[i][j]+=mat1[i][k]*mat2[k][j];
return result;
}
function about() {
var mystring = "Example of Reduction\nWritten by Nabanita Maji and Cliff Shaffer\nCreated as part of the OpenDSA hypertextbook project.\nFor more information, see http://algoviz.org/OpenDSA\nWritten during March, 2015\nJSAV library version " + JSAV.version();
alert(mystring);
}
// Connect action callbacks to the HTML entities
$('#about').click(about);
$('#runit').click(runit);
$('#help').click(help);
$('#reset').click(ODSA.AV.reset);
}(jQuery));
|
import React, { cloneElement } from 'react';
import classNames from 'classnames';
import ValidComponentChildren from './utils/ValidComponentChildren';
const Breadcrumb = React.createClass({
propTypes: {
/**
* bootstrap className
* @private
*/
bsClass: React.PropTypes.string
},
getDefaultProps() {
return {
bsClass: 'breadcrumb'
};
},
render() {
const { className, ...props } = this.props;
return (
<ol
{...props}
role="navigation"
aria-label="breadcrumbs"
className={classNames(className, this.props.bsClass)}>
{ValidComponentChildren.map(this.props.children, this.renderBreadcrumbItem)}
</ol>
);
},
renderBreadcrumbItem(child, index) {
return cloneElement(child, { key: child.key || index });
}
});
export default Breadcrumb;
|
#pragma strict
var key : int;
var input : InputItem;
function UpdateInput () {
//Just get the values from Unity's input
input.got = Input.GetMouseButton(key);
input.down = Input.GetMouseButtonDown(key);
input.up = Input.GetMouseButtonUp(key);
}
|
'use strict';
/**
* SHA512 HMAC based player authentication back-end. Generates tokens
* according to the following scheme:
* ```
* <PLAYER-TSID>|<HMAC>
* ```
* The HMAC consists of the player TSID and a timestamp, hashed with a
* secret key.
*
* Tokens are considered valid if the plain-text TSID matches the one
* in the hash code, and the timestamp is within the accepted range
* (see the {@link https://github.com/mixu/token|token} package
* documentation for details regarding token expiry).
*
* Since the generated tokens contain the player TSID, there is no need
* to store them in persistent storage.
*
* @module
*/
// public interface
module.exports = {
init: init,
authenticate: authenticate,
getToken: getToken,
getTokenLifespan: getTokenLifespan,
};
var _ = require('lodash');
var assert = require('assert');
var auth = require('comm/auth');
var token = require('token');
var utils = require('utils');
/**
* Initializes the {@link https://github.com/mixu/token|token} library
* with parameters from the global server configuration.
*
* @param {object} config configuration settings
*/
function init(config) {
assert(_.isObject(config) && config.secret !== undefined &&
utils.isInt(config.timeStep), 'invalid or missing HMAC auth config');
token.defaults.secret = config.secret;
token.defaults.timeStep = config.timeStep;
}
/**
* Authenticates a client/player.
*
* @param {string} t authentication token supplied by the client
* @returns {string} player TSID (if successfully authenticated)
* @throws {AuthError} if the given token could not be parsed or is
* invalid/expired
*/
function authenticate(t) {
var tsid, tdata;
try {
tsid = t.split('|')[0];
tdata = t.split('|')[1];
}
catch (e) {
throw new auth.AuthError('invalid token data: ' + t, e);
}
var res = token.verify(tsid, tdata);
if (!res) {
throw new auth.AuthError('invalid or expired token: ' + t);
}
return tsid;
}
/**
* Generates an authentication token for the given player.
*
* @param {Player} player the player to generate a token for
* @param {object} [options] custom options, overriding those set via
* {@link module:comm/abe/hmac~init|init} (for testing)
* @returns {string} a valid authentication token
*/
function getToken(player, options) {
var tdata = token.generate(player.tsid, options);
var ret = player.tsid + '|' + tdata;
log.debug('generated token for %s: %s', player, ret);
return ret;
}
/**
* Returns the minimal guaranteed lifespan of an authentication token
* generated by this module.
*
* @returns {number} guaranteed minimal token lifespan **in seconds**
*/
function getTokenLifespan() {
return token.defaults.timeStep;
}
|
'use strict';
const path = require('path');
const childProcess = require('child_process');
const crossSpawn = require('cross-spawn');
const stripFinalNewline = require('strip-final-newline');
const npmRunPath = require('npm-run-path');
const onetime = require('onetime');
const makeError = require('./lib/error');
const normalizeStdio = require('./lib/stdio');
const {spawnedKill, spawnedCancel, setupTimeout, setExitHandler} = require('./lib/kill');
const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = require('./lib/stream.js');
const {mergePromise, getSpawnedPromise} = require('./lib/promise.js');
const {joinCommand, parseCommand} = require('./lib/command.js');
const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;
const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => {
const env = extendEnv ? {...process.env, ...envOption} : envOption;
if (preferLocal) {
return npmRunPath.env({env, cwd: localDir, execPath});
}
return env;
};
const handleArguments = (file, args, options = {}) => {
const parsed = crossSpawn._parse(file, args, options);
file = parsed.command;
args = parsed.args;
options = parsed.options;
options = {
maxBuffer: DEFAULT_MAX_BUFFER,
buffer: true,
stripFinalNewline: true,
extendEnv: true,
preferLocal: false,
localDir: options.cwd || process.cwd(),
execPath: process.execPath,
encoding: 'utf8',
reject: true,
cleanup: true,
all: false,
windowsHide: true,
...options
};
options.env = getEnv(options);
options.stdio = normalizeStdio(options);
if (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') {
// #116
args.unshift('/q');
}
return {file, args, options, parsed};
};
const handleOutput = (options, value, error) => {
if (typeof value !== 'string' && !Buffer.isBuffer(value)) {
// When `execa.sync()` errors, we normalize it to '' to mimic `execa()`
return error === undefined ? undefined : '';
}
if (options.stripFinalNewline) {
return stripFinalNewline(value);
}
return value;
};
const execa = (file, args, options) => {
const parsed = handleArguments(file, args, options);
const command = joinCommand(file, args);
let spawned;
try {
spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options);
} catch (error) {
// Ensure the returned error is always both a promise and a child process
const dummySpawned = new childProcess.ChildProcess();
const errorPromise = Promise.reject(makeError({
error,
stdout: '',
stderr: '',
all: '',
command,
parsed,
timedOut: false,
isCanceled: false,
killed: false
}));
return mergePromise(dummySpawned, errorPromise);
}
const spawnedPromise = getSpawnedPromise(spawned);
const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise);
const processDone = setExitHandler(spawned, parsed.options, timedPromise);
const context = {isCanceled: false};
spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));
spawned.cancel = spawnedCancel.bind(null, spawned, context);
const handlePromise = async () => {
const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone);
const stdout = handleOutput(parsed.options, stdoutResult);
const stderr = handleOutput(parsed.options, stderrResult);
const all = handleOutput(parsed.options, allResult);
if (error || exitCode !== 0 || signal !== null) {
const returnedError = makeError({
error,
exitCode,
signal,
stdout,
stderr,
all,
command,
parsed,
timedOut,
isCanceled: context.isCanceled,
killed: spawned.killed
});
if (!parsed.options.reject) {
return returnedError;
}
throw returnedError;
}
return {
command,
exitCode: 0,
stdout,
stderr,
all,
failed: false,
timedOut: false,
isCanceled: false,
killed: false
};
};
const handlePromiseOnce = onetime(handlePromise);
crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed);
handleInput(spawned, parsed.options.input);
spawned.all = makeAllStream(spawned, parsed.options);
return mergePromise(spawned, handlePromiseOnce);
};
module.exports = execa;
module.exports.sync = (file, args, options) => {
const parsed = handleArguments(file, args, options);
const command = joinCommand(file, args);
validateInputSync(parsed.options);
let result;
try {
result = childProcess.spawnSync(parsed.file, parsed.args, parsed.options);
} catch (error) {
throw makeError({
error,
stdout: '',
stderr: '',
all: '',
command,
parsed,
timedOut: false,
isCanceled: false,
killed: false
});
}
const stdout = handleOutput(parsed.options, result.stdout, result.error);
const stderr = handleOutput(parsed.options, result.stderr, result.error);
if (result.error || result.status !== 0 || result.signal !== null) {
const error = makeError({
stdout,
stderr,
error: result.error,
signal: result.signal,
exitCode: result.status,
command,
parsed,
timedOut: result.error && result.error.code === 'ETIMEDOUT',
isCanceled: false,
killed: result.signal !== null
});
if (!parsed.options.reject) {
return error;
}
throw error;
}
return {
command,
exitCode: 0,
stdout,
stderr,
failed: false,
timedOut: false,
isCanceled: false,
killed: false
};
};
module.exports.command = (command, options) => {
const [file, ...args] = parseCommand(command);
return execa(file, args, options);
};
module.exports.commandSync = (command, options) => {
const [file, ...args] = parseCommand(command);
return execa.sync(file, args, options);
};
module.exports.node = (scriptPath, args, options = {}) => {
if (args && !Array.isArray(args) && typeof args === 'object') {
options = args;
args = [];
}
const stdio = normalizeStdio.node(options);
const defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect'));
const {
nodePath = process.execPath,
nodeOptions = defaultExecArgv
} = options;
return execa(
nodePath,
[
...nodeOptions,
scriptPath,
...(Array.isArray(args) ? args : [])
],
{
...options,
stdin: undefined,
stdout: undefined,
stderr: undefined,
stdio,
shell: false
}
);
};
|
module.exports = {
env: {
development: {
presets: [
'@quasar/babel-preset-app'
]
},
production: {
presets: [ 'es2015-rollup' ],
comments: false
}
}
}
|
/**
* SettingsHB Controller
*
* @description Controller for settings heartbeat dev tool
*/
(function() {
'use strict';
angular
.module('starter.controllers')
.controller('SettingsHBCtrl', SettingsHBCtrl);
SettingsHBCtrl.$inject = ['$scope', 'NetworkService'];
function SettingsHBCtrl($scope, NetworkService) {
if (localStorage.connection) {
$scope.heartbeatStatus = localStorage.connection;
} else {
$scope.heartbeatStatus = 100100;
}
$scope.hbUpdate = function() {
localStorage.connection = $scope.heartbeatStatus;
if ($scope.heartbeatStatus == 100100) NetworkService.networkEvent('online');
if ($scope.heartbeatStatus == 100103) NetworkService.networkEvent('offline');
};
}
})(); |
require("should");
var dataUtil = require("../../../data-util/production/finishing-printing/daily-operation-data-util");
var helper = require("../../../helper");
var validate = require("dl-models").validator.production.finishingPrinting.dailyOperation;
var codeGenerator = require('../../../../src/utils/code-generator');
var moment = require('moment');
var DailyOperationManager = require("../../../../src/managers/production/finishing-printing/daily-operation-manager");
var dailyOperationManager;
var dateNow;
var dateBefore;
before('#00. connect db', function (done) {
helper.getDb()
.then(db => {
dailyOperationManager = new DailyOperationManager(db, {
username: 'dev'
});
dateNow = new Date();
dateBefore = new Date();
done();
})
.catch(e => {
done(e);
});
});
var dataDaily;
var dataInput;
it("#01. should success when create data", function (done) {
dataUtil.getNewData("input")
.then(data => {
dateBefore = dateBefore.setDate(dateBefore.getDate() - 10);
data.dateInput = moment(dateBefore).format('YYYY-MM-DD');
dataInput = data;
dailyOperationManager.create(data)
.then((item) => {
dailyOperationManager.getSingleByIdOrDefault(item)
.then(daily => {
validate(daily);
dataDaily = daily;
done();
})
.catch((e) => {
done(e);
});
})
.catch((e) => {
done(e);
});
})
.catch((e) => {
done(e);
});
});
it("#02. should success when get read data", function (done) {
dailyOperationManager.read({})
.then((item) => {
var daily = item.data;
daily.should.instanceof(Array);
daily.length.should.not.equal(0);
done();
})
.catch((e) => {
done(e);
});
});
it("#03. should success when get read data with keyword", function (done) {
dailyOperationManager.read({ "keyword": dataDaily.step.process })
.then((item) => {
var daily = item.data;
daily.should.instanceof(Array);
daily.length.should.not.equal(0);
done();
})
.catch((e) => {
done(e);
});
});
it("#04. should success when get report without parameter", function (done) {
dailyOperationManager.getDailyOperationReport({})
.then((item) => {
var daily = item.data;
daily.should.instanceof(Array);
daily.length.should.not.equal(0);
done();
})
.catch((e) => {
done(e);
});
});
it("#05. should success when get report with machine parameter", function (done) {
dailyOperationManager.getDailyOperationReport({ "machine": dataDaily.machineId })
.then((item) => {
var daily = item.data;
daily.should.instanceof(Array);
daily.length.should.not.equal(0);
done();
})
.catch((e) => {
done(e);
});
});
it("#06. should success when get report with kanban parameter", function (done) {
dailyOperationManager.getDailyOperationReport({ "kanban": dataDaily.kanbanId })
.then((item) => {
var daily = item.data;
daily.should.instanceof(Array);
daily.length.should.not.equal(0);
done();
})
.catch((e) => {
done(e);
});
});
var dataReport;
it("#07. should success when get report with date parameter", function (done) {
dailyOperationManager.getDailyOperationReport({ "dateFrom": moment(dateBefore).format('YYYY-MM-DD'), "dateTo": moment(dateNow).format('YYYY-MM-DD') })
.then((item) => {
dataReport = item;
dataReport.data.should.instanceof(Array);
dataReport.data.length.should.not.equal(0);
done();
})
.catch((e) => {
done(e);
});
});
// it("#08. should success when get data for Excel", function (done) {
// dailyOperationManager.getXls(dataReport, { "dateFrom": moment(dateBefore).format('YYYY-MM-DD'), "dateTo": moment(dateNow).format('YYYY-MM-DD') }, 7)
// .then((item) => {
// item.should.have.property('data');
// item.should.have.property('options');
// item.should.have.property('name');
// done();
// })
// .catch((e) => {
// done(e);
// });
// });
it("#08.(2) should success create Excel with id", function (done) {
var _idExcel = [];
for (var temp of dataReport.data) {
temp.kanban = null;
temp.machine = null;
temp.dateInput = null;
temp.timeInput = null;
temp.input = null;
temp.dateOutput = null;
temp.timeOutput = null;
temp.goodOutput = null;
temp.badOutput = null;
temp.badOutputDescription = null;
_idExcel.push(temp)
}
dataReport.data = _idExcel;
dailyOperationManager.getXls(dataReport, { "dateFrom": moment(dateBefore).format('YYYY-MM-DD'), "dateTo": moment(dateNow).format('YYYY-MM-DD') }, 7)
.then((item) => {
item.should.have.property('data');
item.should.have.property('options');
item.should.have.property('name');
done();
})
.catch((e) => {
done(e);
});
});
it("#08.(3) should success create Excel with id", function (done) {
var _idExcel = [];
for (var temp of dataReport.data) {
temp.kanban = null;
temp.machine = null;
temp.dateInput = null;
temp.timeInput = null;
temp.input = null;
temp.dateOutput = null;
temp.timeOutput = null;
temp.goodOutput = null;
temp.badOutput = null;
temp.badOutputDescription = null;
_idExcel.push(temp)
}
dataReport.data = _idExcel;
dailyOperationManager.getXls(dataReport, { "dateFrom": moment(dateBefore).format('YYYY-MM-DD') }, 7)
.then((item) => {
item.should.have.property('data');
item.should.have.property('options');
item.should.have.property('name');
done();
})
.catch((e) => {
done(e);
});
});
it("#08.(4) should success create Excel with id", function (done) {
var _idExcel = [];
for (var temp of dataReport.data) {
temp.kanban = null;
temp.machine = null;
temp.dateInput = null;
temp.timeInput = null;
temp.input = null;
temp.dateOutput = null;
temp.timeOutput = null;
temp.goodOutput = null;
temp.badOutput = null;
temp.badOutputDescription = null;
_idExcel.push(temp)
}
dataReport.data = _idExcel;
dailyOperationManager.getXls(dataReport, { "dateTo": moment(dateNow).format('YYYY-MM-DD') }, 7)
.then((item) => {
item.should.have.property('data');
item.should.have.property('options');
item.should.have.property('name');
done();
})
.catch((e) => {
done(e);
});
});
var dailyOutput;
it("#09. should success when create data output", function (done) {
dataUtil.getNewData("output")
.then(data => {
data.dateOutput = moment(dateNow).format('YYYY-MM-DD');
data.kanban = dataInput.kanban;
data.kanbanId = dataInput.kanbanId;
data.machine = dataInput.machine;
data.machineId = dataInput.machineId;
data.step = dataInput.step;
data.stepId = dataInput.stepId;
dailyOperationManager.create(data)
.then((item) => {
dailyOperationManager.getSingleByIdOrDefault(item)
.then(daily => {
validate(daily);
dailyOutput = daily;
done();
})
.catch((e) => {
done(e);
});
})
.catch((e) => {
done(e);
});
})
.catch((e) => {
done(e);
});
});
it("#09.(2) should success when get data", function (done) {
var data= dataInput;
var filter = {
"machineCode": data.machine.code,
"type": "input",
"dateFrom": new Date(),
"dateTo": new Date(),
};
dailyOperationManager.getMonitoringMontlyReport(filter)
.then((result) => {
done();
})
.catch((e) => {
done(e);
});
})
it("#10. should success when get report with date parameter", function (done) {
dailyOperationManager.getDailyOperationBadReport({ "dateFrom": moment(dateBefore).format('YYYY-MM-DD'), "dateTo": moment(dateNow).format('YYYY-MM-DD') })
.then((result) => {
result.should.instanceof(Array);
result.length.should.not.equal(0);
done();
})
.catch((e) => {
done(e);
});
});
var queryDailyMachine = {};
var xlsDailyMachine;
var monthList = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
it("#11. should success when get report daily machine", function (done) {
var temp = new Date().getFullYear() + 1;
queryDailyMachine.area = "Area Pre Treatment";
queryDailyMachine.dateFrom = "1900-01-01";
queryDailyMachine.dateTo = "" + temp + "-01-01";
queryDailyMachine.order = {
"_id.date": 1
};
dailyOperationManager.getDailyMachine(queryDailyMachine, 7)
.then((result) => {
result.info.should.instanceof(Array);
result.info.length.should.not.equal(0);
xlsDailyMachine = result.info;
done();
})
.catch((e) => {
done(e);
});
});
it("#12. should success when get report daily machine with order asc", function (done) {
queryDailyMachine.order = {
"_id.day": "asc"
};
dailyOperationManager.getDailyMachine(queryDailyMachine, 7)
.then((result) => {
result.info.should.instanceof(Array);
result.info.length.should.not.equal(0);
xlsDailyMachine = result.info;
done();
})
.catch((e) => {
done(e);
});
});
it("#13. should success when get report daily machine with order desc", function (done) {
queryDailyMachine.order = {
"_id.day": "desc"
};
dailyOperationManager.getDailyMachine(queryDailyMachine, 7)
.then((result) => {
result.info.should.instanceof(Array);
result.info.length.should.not.equal(0);
xlsDailyMachine = result.info;
done();
})
.catch((e) => {
done(e);
});
});
it("#14. should success when get report with date parameter", function (done) {
var dataXls = {}
dataXls = {
info: xlsDailyMachine
}
dailyOperationManager.getXlsDailyMachine(dataXls, queryDailyMachine, 7)
.then((result) => {
result.data.should.instanceof(Array);
result.data.length.should.not.equal(0);
done();
})
.catch((e) => {
done(e);
});
});
it("#15. should success when destroy all unit test data", function (done) {
dailyOperationManager.destroy(dailyOutput._id)
.then((result) => {
dailyOperationManager.destroy(dataDaily._id)
.then((result1) => {
result.should.be.Boolean();
result.should.equal(true);
result1.should.be.Boolean();
result1.should.equal(true);
done();
})
.catch((e) => {
done(e);
});
})
.catch((e) => {
done(e);
});
});
|
YUI.add('tabview-base', function (Y, NAME) {
var getClassName = Y.ClassNameManager.getClassName,
TABVIEW = 'tabview',
TAB = 'tab',
PANEL = 'panel',
SELECTED = 'selected',
EMPTY_OBJ = {},
DOT = '.',
TabviewBase = function() {
this.init.apply(this, arguments);
};
TabviewBase.NAME = 'tabviewBase';
TabviewBase._classNames = {
tabview: getClassName(TABVIEW),
tabviewPanel: getClassName(TABVIEW, PANEL),
tabviewList: getClassName(TABVIEW, 'list'),
tab: getClassName(TAB),
tabLabel: getClassName(TAB, 'label'),
tabPanel: getClassName(TAB, PANEL),
selectedTab: getClassName(TAB, SELECTED),
selectedPanel: getClassName(TAB, PANEL, SELECTED)
};
TabviewBase._queries = {
tabview: DOT + TabviewBase._classNames.tabview,
tabviewList: '> ul',
tab: '> ul > li',
tabLabel: '> ul > li > a',
tabviewPanel: '> div',
tabPanel: '> div > div',
selectedTab: '> ul > ' + DOT + TabviewBase._classNames.selectedTab,
selectedPanel: '> div ' + DOT + TabviewBase._classNames.selectedPanel
};
Y.mix(TabviewBase.prototype, {
init: function(config) {
config = config || EMPTY_OBJ;
this._node = config.host || Y.one(config.node);
this.refresh();
},
initClassNames: function(index) {
var _classNames = Y.TabviewBase._classNames;
Y.Object.each(Y.TabviewBase._queries, function(query, name) {
// this === tabview._node
if (_classNames[name]) {
var result = this.all(query);
if (index !== undefined) {
result = result.item(index);
}
if (result) {
result.addClass(_classNames[name]);
}
}
}, this._node);
this._node.addClass(_classNames.tabview);
},
_select: function(index) {
var _classNames = Y.TabviewBase._classNames,
_queries = Y.TabviewBase._queries,
node = this._node,
oldItem = node.one(_queries.selectedTab),
oldContent = node.one(_queries.selectedPanel),
newItem = node.all(_queries.tab).item(index),
newContent = node.all(_queries.tabPanel).item(index);
if (oldItem) {
oldItem.removeClass(_classNames.selectedTab);
}
if (oldContent) {
oldContent.removeClass(_classNames.selectedPanel);
}
if (newItem) {
newItem.addClass(_classNames.selectedTab);
}
if (newContent) {
newContent.addClass(_classNames.selectedPanel);
}
},
initState: function() {
var _queries = Y.TabviewBase._queries,
node = this._node,
activeNode = node.one(_queries.selectedTab),
activeIndex = activeNode ?
node.all(_queries.tab).indexOf(activeNode) : 0;
this._select(activeIndex);
},
// collapse extra space between list-items
_scrubTextNodes: function() {
this._node.one(Y.TabviewBase._queries.tabviewList).get('childNodes').each(function(node) {
if (node.get('nodeType') === 3) { // text node
node.remove();
}
});
},
// base renderer only enlivens existing markup
refresh: function() {
this._scrubTextNodes();
this.initClassNames();
this.initState();
this.initEvents();
},
tabEventName: 'click',
initEvents: function() {
// TODO: detach prefix for delegate?
// this._node.delegate('tabview|' + this.tabEventName),
this._node.delegate(this.tabEventName,
this.onTabEvent,
Y.TabviewBase._queries.tab,
this
);
},
onTabEvent: function(e) {
e.preventDefault();
this._select(this._node.all(Y.TabviewBase._queries.tab).indexOf(e.currentTarget));
},
destroy: function() {
this._node.detach(this.tabEventName);
}
});
Y.TabviewBase = TabviewBase;
}, 'patched-v3.18.0', {"requires": ["node-event-delegate", "classnamemanager"]});
|
(function(root, factory) {
if (typeof define === "function" && define.amd) {
define(function() {
return factory(root);
});
} else if (typeof module === "object" && module.exports) {
module.exports = factory(root);
} else {
root.lottie = factory(root);
root.bodymovin = root.lottie;
}
}((window || {}), function(window) {
"use strict";
var svgNS = "http://www.w3.org/2000/svg";
var locationHref = '';
var initialDefaultFrame = -999999;
var subframeEnabled = true;
var expressionsPlugin;
var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
var cachedColors = {};
var bm_rounder = Math.round;
var bm_rnd;
var bm_pow = Math.pow;
var bm_sqrt = Math.sqrt;
var bm_abs = Math.abs;
var bm_floor = Math.floor;
var bm_max = Math.max;
var bm_min = Math.min;
var blitter = 10;
var BMMath = {};
(function(){
var propertyNames = Object.getOwnPropertyNames(Math);
var i, len = propertyNames.length;
for(i=0;i<len;i+=1){
BMMath[propertyNames[i]] = Math[propertyNames[i]];
}
}());
function ProjectInterface(){return {};}
BMMath.random = Math.random;
BMMath.abs = function(val){
var tOfVal = typeof val;
if(tOfVal === 'object' && val.length){
var absArr = createSizedArray(val.length);
var i, len = val.length;
for(i=0;i<len;i+=1){
absArr[i] = Math.abs(val[i]);
}
return absArr;
}
return Math.abs(val);
};
var defaultCurveSegments = 150;
var degToRads = Math.PI/180;
var roundCorner = 0.5519;
function roundValues(flag){
if(flag){
bm_rnd = Math.round;
}else{
bm_rnd = function(val){
return val;
};
}
}
roundValues(false);
function styleDiv(element){
element.style.position = 'absolute';
element.style.top = 0;
element.style.left = 0;
element.style.display = 'block';
element.style.transformOrigin = element.style.webkitTransformOrigin = '0 0';
element.style.backfaceVisibility = element.style.webkitBackfaceVisibility = 'visible';
element.style.transformStyle = element.style.webkitTransformStyle = element.style.mozTransformStyle = "preserve-3d";
}
function BMEnterFrameEvent(n,c,t,d){
this.type = n;
this.currentTime = c;
this.totalTime = t;
this.direction = d < 0 ? -1:1;
}
function BMCompleteEvent(n,d){
this.type = n;
this.direction = d < 0 ? -1:1;
}
function BMCompleteLoopEvent(n,c,t,d){
this.type = n;
this.currentLoop = t;
this.totalLoops = c;
this.direction = d < 0 ? -1:1;
}
function BMSegmentStartEvent(n,f,t){
this.type = n;
this.firstFrame = f;
this.totalFrames = t;
}
function BMDestroyEvent(n,t){
this.type = n;
this.target = t;
}
function randomString(length, chars){
if(chars === undefined){
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
}
var i;
var result = '';
for (i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
return result;
}
function HSVtoRGB(h, s, v) {
var r, g, b, i, f, p, q, t;
i = Math.floor(h * 6);
f = h * 6 - i;
p = v * (1 - s);
q = v * (1 - f * s);
t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0: r = v; g = t; b = p; break;
case 1: r = q; g = v; b = p; break;
case 2: r = p; g = v; b = t; break;
case 3: r = p; g = q; b = v; break;
case 4: r = t; g = p; b = v; break;
case 5: r = v; g = p; b = q; break;
}
return [ r,
g,
b ];
}
function RGBtoHSV(r, g, b) {
var max = Math.max(r, g, b), min = Math.min(r, g, b),
d = max - min,
h,
s = (max === 0 ? 0 : d / max),
v = max / 255;
switch (max) {
case min: h = 0; break;
case r: h = (g - b) + d * (g < b ? 6: 0); h /= 6 * d; break;
case g: h = (b - r) + d * 2; h /= 6 * d; break;
case b: h = (r - g) + d * 4; h /= 6 * d; break;
}
return [
h,
s,
v
];
}
function addSaturationToRGB(color,offset){
var hsv = RGBtoHSV(color[0]*255,color[1]*255,color[2]*255);
hsv[1] += offset;
if (hsv[1] > 1) {
hsv[1] = 1;
}
else if (hsv[1] <= 0) {
hsv[1] = 0;
}
return HSVtoRGB(hsv[0],hsv[1],hsv[2]);
}
function addBrightnessToRGB(color,offset){
var hsv = RGBtoHSV(color[0]*255,color[1]*255,color[2]*255);
hsv[2] += offset;
if (hsv[2] > 1) {
hsv[2] = 1;
}
else if (hsv[2] < 0) {
hsv[2] = 0;
}
return HSVtoRGB(hsv[0],hsv[1],hsv[2]);
}
function addHueToRGB(color,offset) {
var hsv = RGBtoHSV(color[0]*255,color[1]*255,color[2]*255);
hsv[0] += offset/360;
if (hsv[0] > 1) {
hsv[0] -= 1;
}
else if (hsv[0] < 0) {
hsv[0] += 1;
}
return HSVtoRGB(hsv[0],hsv[1],hsv[2]);
}
var rgbToHex = (function(){
var colorMap = [];
var i;
var hex;
for(i=0;i<256;i+=1){
hex = i.toString(16);
colorMap[i] = hex.length == 1 ? '0' + hex : hex;
}
return function(r, g, b) {
if(r<0){
r = 0;
}
if(g<0){
g = 0;
}
if(b<0){
b = 0;
}
return '#' + colorMap[r] + colorMap[g] + colorMap[b];
};
}());
function BaseEvent(){}
BaseEvent.prototype = {
triggerEvent: function (eventName, args) {
if (this._cbs[eventName]) {
var len = this._cbs[eventName].length;
for (var i = 0; i < len; i++){
this._cbs[eventName][i](args);
}
}
},
addEventListener: function (eventName, callback) {
if (!this._cbs[eventName]){
this._cbs[eventName] = [];
}
this._cbs[eventName].push(callback);
return function() {
this.removeEventListener(eventName, callback);
}.bind(this);
},
removeEventListener: function (eventName,callback){
if (!callback){
this._cbs[eventName] = null;
}else if(this._cbs[eventName]){
var i = 0, len = this._cbs[eventName].length;
while(i<len){
if(this._cbs[eventName][i] === callback){
this._cbs[eventName].splice(i,1);
i -=1;
len -= 1;
}
i += 1;
}
if(!this._cbs[eventName].length){
this._cbs[eventName] = null;
}
}
}
};
var createTypedArray = (function(){
function createRegularArray(type, len){
var i = 0, arr = [], value;
switch(type) {
case 'int16':
case 'uint8c':
value = 1;
break;
default:
value = 1.1;
break;
}
for(i = 0; i < len; i += 1) {
arr.push(value);
}
return arr;
}
function createTypedArray(type, len){
if(type === 'float32') {
return new Float32Array(len);
} else if(type === 'int16') {
return new Int16Array(len);
} else if(type === 'uint8c') {
return new Uint8ClampedArray(len);
}
}
if(typeof Uint8ClampedArray === 'function' && typeof Float32Array === 'function') {
return createTypedArray;
} else {
return createRegularArray;
}
}());
function createSizedArray(len) {
return Array.apply(null,{length:len});
}
function createNS(type) {
//return {appendChild:function(){},setAttribute:function(){},style:{}}
return document.createElementNS(svgNS, type);
}
function createTag(type) {
//return {appendChild:function(){},setAttribute:function(){},style:{}}
return document.createElement(type);
}
function DynamicPropertyContainer(){};
DynamicPropertyContainer.prototype = {
addDynamicProperty: function(prop) {
if(this.dynamicProperties.indexOf(prop) === -1) {
this.dynamicProperties.push(prop);
this.container.addDynamicProperty(this);
this._isAnimated = true;
}
},
iterateDynamicProperties: function(){
this._mdf = false;
var i, len = this.dynamicProperties.length;
for(i=0;i<len;i+=1){
this.dynamicProperties[i].getValue();
if(this.dynamicProperties[i]._mdf) {
this._mdf = true;
}
}
},
initDynamicPropertyContainer: function(container){
this.container = container;
this.dynamicProperties = [];
this._mdf = false;
this._isAnimated = false;
}
}
/*!
Transformation Matrix v2.0
(c) Epistemex 2014-2015
www.epistemex.com
By Ken Fyrstenberg
Contributions by leeoniya.
License: MIT, header required.
*/
/**
* 2D transformation matrix object initialized with identity matrix.
*
* The matrix can synchronize a canvas context by supplying the context
* as an argument, or later apply current absolute transform to an
* existing context.
*
* All values are handled as floating point values.
*
* @param {CanvasRenderingContext2D} [context] - Optional context to sync with Matrix
* @prop {number} a - scale x
* @prop {number} b - shear y
* @prop {number} c - shear x
* @prop {number} d - scale y
* @prop {number} e - translate x
* @prop {number} f - translate y
* @prop {CanvasRenderingContext2D|null} [context=null] - set or get current canvas context
* @constructor
*/
var Matrix = (function(){
var _cos = Math.cos;
var _sin = Math.sin;
var _tan = Math.tan;
var _rnd = Math.round;
function reset(){
this.props[0] = 1;
this.props[1] = 0;
this.props[2] = 0;
this.props[3] = 0;
this.props[4] = 0;
this.props[5] = 1;
this.props[6] = 0;
this.props[7] = 0;
this.props[8] = 0;
this.props[9] = 0;
this.props[10] = 1;
this.props[11] = 0;
this.props[12] = 0;
this.props[13] = 0;
this.props[14] = 0;
this.props[15] = 1;
return this;
}
function rotate(angle) {
if(angle === 0){
return this;
}
var mCos = _cos(angle);
var mSin = _sin(angle);
return this._t(mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
}
function rotateX(angle){
if(angle === 0){
return this;
}
var mCos = _cos(angle);
var mSin = _sin(angle);
return this._t(1, 0, 0, 0, 0, mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1);
}
function rotateY(angle){
if(angle === 0){
return this;
}
var mCos = _cos(angle);
var mSin = _sin(angle);
return this._t(mCos, 0, mSin, 0, 0, 1, 0, 0, -mSin, 0, mCos, 0, 0, 0, 0, 1);
}
function rotateZ(angle){
if(angle === 0){
return this;
}
var mCos = _cos(angle);
var mSin = _sin(angle);
return this._t(mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
}
function shear(sx,sy){
return this._t(1, sy, sx, 1, 0, 0);
}
function skew(ax, ay){
return this.shear(_tan(ax), _tan(ay));
}
function skewFromAxis(ax, angle){
var mCos = _cos(angle);
var mSin = _sin(angle);
return this._t(mCos, mSin, 0, 0, -mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)
._t(1, 0, 0, 0, _tan(ax), 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)
._t(mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
//return this._t(mCos, mSin, -mSin, mCos, 0, 0)._t(1, 0, _tan(ax), 1, 0, 0)._t(mCos, -mSin, mSin, mCos, 0, 0);
}
function scale(sx, sy, sz) {
sz = isNaN(sz) ? 1 : sz;
if(sx == 1 && sy == 1 && sz == 1){
return this;
}
return this._t(sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, sz, 0, 0, 0, 0, 1);
}
function setTransform(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) {
this.props[0] = a;
this.props[1] = b;
this.props[2] = c;
this.props[3] = d;
this.props[4] = e;
this.props[5] = f;
this.props[6] = g;
this.props[7] = h;
this.props[8] = i;
this.props[9] = j;
this.props[10] = k;
this.props[11] = l;
this.props[12] = m;
this.props[13] = n;
this.props[14] = o;
this.props[15] = p;
return this;
}
function translate(tx, ty, tz) {
tz = tz || 0;
if(tx !== 0 || ty !== 0 || tz !== 0){
return this._t(1,0,0,0,0,1,0,0,0,0,1,0,tx,ty,tz,1);
}
return this;
}
function transform(a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2, l2, m2, n2, o2, p2) {
var _p = this.props;
if(a2 === 1 && b2 === 0 && c2 === 0 && d2 === 0 && e2 === 0 && f2 === 1 && g2 === 0 && h2 === 0 && i2 === 0 && j2 === 0 && k2 === 1 && l2 === 0){
//NOTE: commenting this condition because TurboFan deoptimizes code when present
//if(m2 !== 0 || n2 !== 0 || o2 !== 0){
_p[12] = _p[12] * a2 + _p[15] * m2;
_p[13] = _p[13] * f2 + _p[15] * n2;
_p[14] = _p[14] * k2 + _p[15] * o2;
_p[15] = _p[15] * p2;
//}
this._identityCalculated = false;
return this;
}
var a1 = _p[0];
var b1 = _p[1];
var c1 = _p[2];
var d1 = _p[3];
var e1 = _p[4];
var f1 = _p[5];
var g1 = _p[6];
var h1 = _p[7];
var i1 = _p[8];
var j1 = _p[9];
var k1 = _p[10];
var l1 = _p[11];
var m1 = _p[12];
var n1 = _p[13];
var o1 = _p[14];
var p1 = _p[15];
/* matrix order (canvas compatible):
* ace
* bdf
* 001
*/
_p[0] = a1 * a2 + b1 * e2 + c1 * i2 + d1 * m2;
_p[1] = a1 * b2 + b1 * f2 + c1 * j2 + d1 * n2 ;
_p[2] = a1 * c2 + b1 * g2 + c1 * k2 + d1 * o2 ;
_p[3] = a1 * d2 + b1 * h2 + c1 * l2 + d1 * p2 ;
_p[4] = e1 * a2 + f1 * e2 + g1 * i2 + h1 * m2 ;
_p[5] = e1 * b2 + f1 * f2 + g1 * j2 + h1 * n2 ;
_p[6] = e1 * c2 + f1 * g2 + g1 * k2 + h1 * o2 ;
_p[7] = e1 * d2 + f1 * h2 + g1 * l2 + h1 * p2 ;
_p[8] = i1 * a2 + j1 * e2 + k1 * i2 + l1 * m2 ;
_p[9] = i1 * b2 + j1 * f2 + k1 * j2 + l1 * n2 ;
_p[10] = i1 * c2 + j1 * g2 + k1 * k2 + l1 * o2 ;
_p[11] = i1 * d2 + j1 * h2 + k1 * l2 + l1 * p2 ;
_p[12] = m1 * a2 + n1 * e2 + o1 * i2 + p1 * m2 ;
_p[13] = m1 * b2 + n1 * f2 + o1 * j2 + p1 * n2 ;
_p[14] = m1 * c2 + n1 * g2 + o1 * k2 + p1 * o2 ;
_p[15] = m1 * d2 + n1 * h2 + o1 * l2 + p1 * p2 ;
this._identityCalculated = false;
return this;
}
function isIdentity() {
if(!this._identityCalculated){
this._identity = !(this.props[0] !== 1 || this.props[1] !== 0 || this.props[2] !== 0 || this.props[3] !== 0 || this.props[4] !== 0 || this.props[5] !== 1 || this.props[6] !== 0 || this.props[7] !== 0 || this.props[8] !== 0 || this.props[9] !== 0 || this.props[10] !== 1 || this.props[11] !== 0 || this.props[12] !== 0 || this.props[13] !== 0 || this.props[14] !== 0 || this.props[15] !== 1);
this._identityCalculated = true;
}
return this._identity;
}
function equals(matr){
var i = 0;
while (i < 16) {
if(matr.props[i] !== this.props[i]) {
return false;
}
i+=1;
}
return true;
}
function clone(matr){
var i;
for(i=0;i<16;i+=1){
matr.props[i] = this.props[i];
}
}
function cloneFromProps(props){
var i;
for(i=0;i<16;i+=1){
this.props[i] = props[i];
}
}
function applyToPoint(x, y, z) {
return {
x: x * this.props[0] + y * this.props[4] + z * this.props[8] + this.props[12],
y: x * this.props[1] + y * this.props[5] + z * this.props[9] + this.props[13],
z: x * this.props[2] + y * this.props[6] + z * this.props[10] + this.props[14]
};
/*return {
x: x * me.a + y * me.c + me.e,
y: x * me.b + y * me.d + me.f
};*/
}
function applyToX(x, y, z) {
return x * this.props[0] + y * this.props[4] + z * this.props[8] + this.props[12];
}
function applyToY(x, y, z) {
return x * this.props[1] + y * this.props[5] + z * this.props[9] + this.props[13];
}
function applyToZ(x, y, z) {
return x * this.props[2] + y * this.props[6] + z * this.props[10] + this.props[14];
}
function inversePoint(pt) {
var determinant = this.props[0] * this.props[5] - this.props[1] * this.props[4];
var a = this.props[5]/determinant;
var b = - this.props[1]/determinant;
var c = - this.props[4]/determinant;
var d = this.props[0]/determinant;
var e = (this.props[4] * this.props[13] - this.props[5] * this.props[12])/determinant;
var f = - (this.props[0] * this.props[13] - this.props[1] * this.props[12])/determinant;
return [pt[0] * a + pt[1] * c + e, pt[0] * b + pt[1] * d + f, 0];
}
function inversePoints(pts){
var i, len = pts.length, retPts = [];
for(i=0;i<len;i+=1){
retPts[i] = inversePoint(pts[i]);
}
return retPts;
}
function applyToTriplePoints(pt1, pt2, pt3) {
var arr = createTypedArray('float32', 6);
if(this.isIdentity()) {
arr[0] = pt1[0];
arr[1] = pt1[1];
arr[2] = pt2[0];
arr[3] = pt2[1];
arr[4] = pt3[0];
arr[5] = pt3[1];
} else {
var p0 = this.props[0], p1 = this.props[1], p4 = this.props[4], p5 = this.props[5], p12 = this.props[12], p13 = this.props[13];
arr[0] = pt1[0] * p0 + pt1[1] * p4 + p12;
arr[1] = pt1[0] * p1 + pt1[1] * p5 + p13;
arr[2] = pt2[0] * p0 + pt2[1] * p4 + p12;
arr[3] = pt2[0] * p1 + pt2[1] * p5 + p13;
arr[4] = pt3[0] * p0 + pt3[1] * p4 + p12;
arr[5] = pt3[0] * p1 + pt3[1] * p5 + p13;
}
return arr;
}
function applyToPointArray(x,y,z){
var arr;
if(this.isIdentity()) {
arr = [x,y,z];
} else {
arr = [x * this.props[0] + y * this.props[4] + z * this.props[8] + this.props[12],x * this.props[1] + y * this.props[5] + z * this.props[9] + this.props[13],x * this.props[2] + y * this.props[6] + z * this.props[10] + this.props[14]];
}
return arr;
}
function applyToPointStringified(x, y) {
if(this.isIdentity()) {
return x + ',' + y;
}
var _p = this.props;
return (x * _p[0] + y * _p[4] + _p[12])+','+(x * _p[1] + y * _p[5] + _p[13]);
}
function toCSS() {
//Doesn't make much sense to add this optimization. If it is an identity matrix, it's very likely this will get called only once since it won't be keyframed.
/*if(this.isIdentity()) {
return '';
}*/
var i = 0;
var props = this.props;
var cssValue = 'matrix3d(';
var v = 10000;
while(i<16){
cssValue += _rnd(props[i]*v)/v;
cssValue += i === 15 ? ')':',';
i += 1;
}
return cssValue;
}
function roundMatrixProperty(val) {
var v = 10000;
if((val < 0.000001 && val > 0) || (val > -0.000001 && val < 0)) {
return _rnd(val * v) / v;
}
return val;
}
function to2dCSS() {
//Doesn't make much sense to add this optimization. If it is an identity matrix, it's very likely this will get called only once since it won't be keyframed.
/*if(this.isIdentity()) {
return '';
}*/
var props = this.props;
var _a = roundMatrixProperty(props[0]);
var _b = roundMatrixProperty(props[1]);
var _c = roundMatrixProperty(props[4]);
var _d = roundMatrixProperty(props[5]);
var _e = roundMatrixProperty(props[12]);
var _f = roundMatrixProperty(props[13]);
return "matrix(" + _a + ',' + _b + ',' + _c + ',' + _d + ',' + _e + ',' + _f + ")";
}
return function(){
this.reset = reset;
this.rotate = rotate;
this.rotateX = rotateX;
this.rotateY = rotateY;
this.rotateZ = rotateZ;
this.skew = skew;
this.skewFromAxis = skewFromAxis;
this.shear = shear;
this.scale = scale;
this.setTransform = setTransform;
this.translate = translate;
this.transform = transform;
this.applyToPoint = applyToPoint;
this.applyToX = applyToX;
this.applyToY = applyToY;
this.applyToZ = applyToZ;
this.applyToPointArray = applyToPointArray;
this.applyToTriplePoints = applyToTriplePoints;
this.applyToPointStringified = applyToPointStringified;
this.toCSS = toCSS;
this.to2dCSS = to2dCSS;
this.clone = clone;
this.cloneFromProps = cloneFromProps;
this.equals = equals;
this.inversePoints = inversePoints;
this.inversePoint = inversePoint;
this._t = this.transform;
this.isIdentity = isIdentity;
this._identity = true;
this._identityCalculated = false;
this.props = createTypedArray('float32', 16);
this.reset();
};
}());
/*
Copyright 2014 David Bau.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
(function (pool, math) {
//
// The following constants are related to IEEE 754 limits.
//
var global = this,
width = 256, // each RC4 output is 0 <= x < 256
chunks = 6, // at least six RC4 outputs for each double
digits = 52, // there are 52 significant digits in a double
rngname = 'random', // rngname: name for Math.random and Math.seedrandom
startdenom = math.pow(width, chunks),
significance = math.pow(2, digits),
overflow = significance * 2,
mask = width - 1,
nodecrypto; // node.js crypto module, initialized at the bottom.
//
// seedrandom()
// This is the seedrandom function described above.
//
function seedrandom(seed, options, callback) {
var key = [];
options = (options === true) ? { entropy: true } : (options || {});
// Flatten the seed string or build one from local entropy if needed.
var shortseed = mixkey(flatten(
options.entropy ? [seed, tostring(pool)] :
(seed === null) ? autoseed() : seed, 3), key);
// Use the seed to initialize an ARC4 generator.
var arc4 = new ARC4(key);
// This function returns a random double in [0, 1) that contains
// randomness in every bit of the mantissa of the IEEE 754 value.
var prng = function() {
var n = arc4.g(chunks), // Start with a numerator n < 2 ^ 48
d = startdenom, // and denominator d = 2 ^ 48.
x = 0; // and no 'extra last byte'.
while (n < significance) { // Fill up all significant digits by
n = (n + x) * width; // shifting numerator and
d *= width; // denominator and generating a
x = arc4.g(1); // new least-significant-byte.
}
while (n >= overflow) { // To avoid rounding up, before adding
n /= 2; // last byte, shift everything
d /= 2; // right using integer math until
x >>>= 1; // we have exactly the desired bits.
}
return (n + x) / d; // Form the number within [0, 1).
};
prng.int32 = function() { return arc4.g(4) | 0; };
prng.quick = function() { return arc4.g(4) / 0x100000000; };
prng.double = prng;
// Mix the randomness into accumulated entropy.
mixkey(tostring(arc4.S), pool);
// Calling convention: what to return as a function of prng, seed, is_math.
return (options.pass || callback ||
function(prng, seed, is_math_call, state) {
if (state) {
// Load the arc4 state from the given state if it has an S array.
if (state.S) { copy(state, arc4); }
// Only provide the .state method if requested via options.state.
prng.state = function() { return copy(arc4, {}); };
}
// If called as a method of Math (Math.seedrandom()), mutate
// Math.random because that is how seedrandom.js has worked since v1.0.
if (is_math_call) { math[rngname] = prng; return seed; }
// Otherwise, it is a newer calling convention, so return the
// prng directly.
else return prng;
})(
prng,
shortseed,
'global' in options ? options.global : (this == math),
options.state);
}
math['seed' + rngname] = seedrandom;
//
// ARC4
//
// An ARC4 implementation. The constructor takes a key in the form of
// an array of at most (width) integers that should be 0 <= x < (width).
//
// The g(count) method returns a pseudorandom integer that concatenates
// the next (count) outputs from ARC4. Its return value is a number x
// that is in the range 0 <= x < (width ^ count).
//
function ARC4(key) {
var t, keylen = key.length,
me = this, i = 0, j = me.i = me.j = 0, s = me.S = [];
// The empty key [] is treated as [0].
if (!keylen) { key = [keylen++]; }
// Set up S using the standard key scheduling algorithm.
while (i < width) {
s[i] = i++;
}
for (i = 0; i < width; i++) {
s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))];
s[j] = t;
}
// The "g" method returns the next (count) outputs as one number.
me.g = function(count) {
// Using instance members instead of closure state nearly doubles speed.
var t, r = 0,
i = me.i, j = me.j, s = me.S;
while (count--) {
t = s[i = mask & (i + 1)];
r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))];
}
me.i = i; me.j = j;
return r;
// For robust unpredictability, the function call below automatically
// discards an initial batch of values. This is called RC4-drop[256].
// See http://google.com/search?q=rsa+fluhrer+response&btnI
};
}
//
// copy()
// Copies internal state of ARC4 to or from a plain object.
//
function copy(f, t) {
t.i = f.i;
t.j = f.j;
t.S = f.S.slice();
return t;
}
//
// flatten()
// Converts an object tree to nested arrays of strings.
//
function flatten(obj, depth) {
var result = [], typ = (typeof obj), prop;
if (depth && typ == 'object') {
for (prop in obj) {
try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {}
}
}
return (result.length ? result : typ == 'string' ? obj : obj + '\0');
}
//
// mixkey()
// Mixes a string seed into a key that is an array of integers, and
// returns a shortened string seed that is equivalent to the result key.
//
function mixkey(seed, key) {
var stringseed = seed + '', smear, j = 0;
while (j < stringseed.length) {
key[mask & j] =
mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++));
}
return tostring(key);
}
//
// autoseed()
// Returns an object for autoseeding, using window.crypto and Node crypto
// module if available.
//
function autoseed() {
try {
if (nodecrypto) { return tostring(nodecrypto.randomBytes(width)); }
var out = new Uint8Array(width);
(global.crypto || global.msCrypto).getRandomValues(out);
return tostring(out);
} catch (e) {
var browser = global.navigator,
plugins = browser && browser.plugins;
return [+new Date(), global, plugins, global.screen, tostring(pool)];
}
}
//
// tostring()
// Converts an array of charcodes to a string
//
function tostring(a) {
return String.fromCharCode.apply(0, a);
}
//
// When seedrandom.js is loaded, we immediately mix a few bits
// from the built-in RNG into the entropy pool. Because we do
// not want to interfere with deterministic PRNG state later,
// seedrandom will not call math.random on its own again after
// initialization.
//
mixkey(math.random(), pool);
//
// Nodejs and AMD support: export the implementation as a module using
// either convention.
//
// End anonymous scope, and pass initial values.
})(
[], // pool: entropy pool starts empty
BMMath // math: package containing random, pow, and seedrandom
);
var BezierFactory = (function(){
/**
* BezierEasing - use bezier curve for transition easing function
* by Gaëtan Renaudeau 2014 - 2015 – MIT License
*
* Credits: is based on Firefox's nsSMILKeySpline.cpp
* Usage:
* var spline = BezierEasing([ 0.25, 0.1, 0.25, 1.0 ])
* spline.get(x) => returns the easing value | x must be in [0, 1] range
*
*/
var ob = {};
ob.getBezierEasing = getBezierEasing;
var beziers = {};
function getBezierEasing(a,b,c,d,nm){
var str = nm || ('bez_' + a+'_'+b+'_'+c+'_'+d).replace(/\./g, 'p');
if(beziers[str]){
return beziers[str];
}
var bezEasing = new BezierEasing([a,b,c,d]);
beziers[str] = bezEasing;
return bezEasing;
}
// These values are established by empiricism with tests (tradeoff: performance VS precision)
var NEWTON_ITERATIONS = 4;
var NEWTON_MIN_SLOPE = 0.001;
var SUBDIVISION_PRECISION = 0.0000001;
var SUBDIVISION_MAX_ITERATIONS = 10;
var kSplineTableSize = 11;
var kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
var float32ArraySupported = typeof Float32Array === "function";
function A (aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1; }
function B (aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1; }
function C (aA1) { return 3.0 * aA1; }
// Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2.
function calcBezier (aT, aA1, aA2) {
return ((A(aA1, aA2)*aT + B(aA1, aA2))*aT + C(aA1))*aT;
}
// Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2.
function getSlope (aT, aA1, aA2) {
return 3.0 * A(aA1, aA2)*aT*aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
}
function binarySubdivide (aX, aA, aB, mX1, mX2) {
var currentX, currentT, i = 0;
do {
currentT = aA + (aB - aA) / 2.0;
currentX = calcBezier(currentT, mX1, mX2) - aX;
if (currentX > 0.0) {
aB = currentT;
} else {
aA = currentT;
}
} while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
return currentT;
}
function newtonRaphsonIterate (aX, aGuessT, mX1, mX2) {
for (var i = 0; i < NEWTON_ITERATIONS; ++i) {
var currentSlope = getSlope(aGuessT, mX1, mX2);
if (currentSlope === 0.0) return aGuessT;
var currentX = calcBezier(aGuessT, mX1, mX2) - aX;
aGuessT -= currentX / currentSlope;
}
return aGuessT;
}
/**
* points is an array of [ mX1, mY1, mX2, mY2 ]
*/
function BezierEasing (points) {
this._p = points;
this._mSampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);
this._precomputed = false;
this.get = this.get.bind(this);
}
BezierEasing.prototype = {
get: function (x) {
var mX1 = this._p[0],
mY1 = this._p[1],
mX2 = this._p[2],
mY2 = this._p[3];
if (!this._precomputed) this._precompute();
if (mX1 === mY1 && mX2 === mY2) return x; // linear
// Because JavaScript number are imprecise, we should guarantee the extremes are right.
if (x === 0) return 0;
if (x === 1) return 1;
return calcBezier(this._getTForX(x), mY1, mY2);
},
// Private part
_precompute: function () {
var mX1 = this._p[0],
mY1 = this._p[1],
mX2 = this._p[2],
mY2 = this._p[3];
this._precomputed = true;
if (mX1 !== mY1 || mX2 !== mY2)
this._calcSampleValues();
},
_calcSampleValues: function () {
var mX1 = this._p[0],
mX2 = this._p[2];
for (var i = 0; i < kSplineTableSize; ++i) {
this._mSampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
}
},
/**
* getTForX chose the fastest heuristic to determine the percentage value precisely from a given X projection.
*/
_getTForX: function (aX) {
var mX1 = this._p[0],
mX2 = this._p[2],
mSampleValues = this._mSampleValues;
var intervalStart = 0.0;
var currentSample = 1;
var lastSample = kSplineTableSize - 1;
for (; currentSample !== lastSample && mSampleValues[currentSample] <= aX; ++currentSample) {
intervalStart += kSampleStepSize;
}
--currentSample;
// Interpolate to provide an initial guess for t
var dist = (aX - mSampleValues[currentSample]) / (mSampleValues[currentSample+1] - mSampleValues[currentSample]);
var guessForT = intervalStart + dist * kSampleStepSize;
var initialSlope = getSlope(guessForT, mX1, mX2);
if (initialSlope >= NEWTON_MIN_SLOPE) {
return newtonRaphsonIterate(aX, guessForT, mX1, mX2);
} else if (initialSlope === 0.0) {
return guessForT;
} else {
return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
}
}
};
return ob;
}());
(function () {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
}
if(!window.requestAnimationFrame)
window.requestAnimationFrame = function (callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = setTimeout(function () {
callback(currTime + timeToCall);
},
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if(!window.cancelAnimationFrame)
window.cancelAnimationFrame = function (id) {
clearTimeout(id);
};
}());
function extendPrototype(sources,destination){
var i, len = sources.length, sourcePrototype;
for (i = 0;i < len;i += 1) {
sourcePrototype = sources[i].prototype;
for (var attr in sourcePrototype) {
if (sourcePrototype.hasOwnProperty(attr)) destination.prototype[attr] = sourcePrototype[attr];
}
}
}
function getDescriptor(object, prop) {
return Object.getOwnPropertyDescriptor(object, prop);
}
function createProxyFunction(prototype) {
function ProxyFunction(){}
ProxyFunction.prototype = prototype;
return ProxyFunction;
}
function bezFunction(){
var easingFunctions = [];
var math = Math;
function pointOnLine2D(x1,y1, x2,y2, x3,y3){
var det1 = (x1*y2) + (y1*x3) + (x2*y3) - (x3*y2) - (y3*x1) - (x2*y1);
return det1 > -0.001 && det1 < 0.001;
}
function pointOnLine3D(x1,y1,z1, x2,y2,z2, x3,y3,z3){
if(z1 === 0 && z2 === 0 && z3 === 0) {
return pointOnLine2D(x1,y1, x2,y2, x3,y3);
}
var dist1 = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2) + Math.pow(z2 - z1, 2));
var dist2 = Math.sqrt(Math.pow(x3 - x1, 2) + Math.pow(y3 - y1, 2) + Math.pow(z3 - z1, 2));
var dist3 = Math.sqrt(Math.pow(x3 - x2, 2) + Math.pow(y3 - y2, 2) + Math.pow(z3 - z2, 2));
var diffDist;
if(dist1 > dist2){
if(dist1 > dist3){
diffDist = dist1 - dist2 - dist3;
} else {
diffDist = dist3 - dist2 - dist1;
}
} else if(dist3 > dist2){
diffDist = dist3 - dist2 - dist1;
} else {
diffDist = dist2 - dist1 - dist3;
}
return diffDist > -0.0001 && diffDist < 0.0001;
}
var getBezierLength = (function(){
return function(pt1,pt2,pt3,pt4){
var curveSegments = defaultCurveSegments;
var k;
var i, len;
var ptCoord,perc,addedLength = 0;
var ptDistance;
var point = [],lastPoint = [];
var lengthData = bezier_length_pool.newElement();
len = pt3.length;
for(k=0;k<curveSegments;k+=1){
perc = k/(curveSegments-1);
ptDistance = 0;
for(i=0;i<len;i+=1){
ptCoord = bm_pow(1-perc,3)*pt1[i]+3*bm_pow(1-perc,2)*perc*pt3[i]+3*(1-perc)*bm_pow(perc,2)*pt4[i]+bm_pow(perc,3)*pt2[i];
point[i] = ptCoord;
if(lastPoint[i] !== null){
ptDistance += bm_pow(point[i] - lastPoint[i],2);
}
lastPoint[i] = point[i];
}
if(ptDistance){
ptDistance = bm_sqrt(ptDistance);
addedLength += ptDistance;
}
lengthData.percents[k] = perc;
lengthData.lengths[k] = addedLength;
}
lengthData.addedLength = addedLength;
return lengthData;
};
}());
function getSegmentsLength(shapeData) {
var segmentsLength = segments_length_pool.newElement();
var closed = shapeData.c;
var pathV = shapeData.v;
var pathO = shapeData.o;
var pathI = shapeData.i;
var i, len = shapeData._length;
var lengths = segmentsLength.lengths;
var totalLength = 0;
for(i=0;i<len-1;i+=1){
lengths[i] = getBezierLength(pathV[i],pathV[i+1],pathO[i],pathI[i+1]);
totalLength += lengths[i].addedLength;
}
if(closed){
lengths[i] = getBezierLength(pathV[i],pathV[0],pathO[i],pathI[0]);
totalLength += lengths[i].addedLength;
}
segmentsLength.totalLength = totalLength;
return segmentsLength;
}
function BezierData(length){
this.segmentLength = 0;
this.points = new Array(length);
}
function PointData(partial,point){
this.partialLength = partial;
this.point = point;
}
var buildBezierData = (function(){
var storedData = {};
return function (keyData){
var pt1 = keyData.s;
var pt2 = keyData.e;
var pt3 = keyData.to;
var pt4 = keyData.ti;
var bezierName = (pt1[0]+'_'+pt1[1]+'_'+pt2[0]+'_'+pt2[1]+'_'+pt3[0]+'_'+pt3[1]+'_'+pt4[0]+'_'+pt4[1]).replace(/\./g, 'p');
if(storedData[bezierName]){
keyData.bezierData = storedData[bezierName];
return;
}
var curveSegments = defaultCurveSegments;
var k, i, len;
var ptCoord,perc,addedLength = 0;
var ptDistance;
var point,lastPoint = null;
if (pt1.length === 2 && (pt1[0] != pt2[0] || pt1[1] != pt2[1]) && pointOnLine2D(pt1[0],pt1[1],pt2[0],pt2[1],pt1[0]+pt3[0],pt1[1]+pt3[1]) && pointOnLine2D(pt1[0],pt1[1],pt2[0],pt2[1],pt2[0]+pt4[0],pt2[1]+pt4[1])){
curveSegments = 2;
}
var bezierData = new BezierData(curveSegments);
len = pt3.length;
for (k = 0; k < curveSegments; k += 1) {
point = createSizedArray(len);
perc = k / (curveSegments - 1);
ptDistance = 0;
for (i = 0; i < len; i += 1){
ptCoord = bm_pow(1-perc,3)*pt1[i]+3*bm_pow(1-perc,2)*perc*(pt1[i] + pt3[i])+3*(1-perc)*bm_pow(perc,2)*(pt2[i] + pt4[i])+bm_pow(perc,3)*pt2[i];
point[i] = ptCoord;
if(lastPoint !== null){
ptDistance += bm_pow(point[i] - lastPoint[i],2);
}
}
ptDistance = bm_sqrt(ptDistance);
addedLength += ptDistance;
bezierData.points[k] = new PointData(ptDistance, point);
lastPoint = point;
}
bezierData.segmentLength = addedLength;
keyData.bezierData = bezierData;
storedData[bezierName] = bezierData;
};
}());
function getDistancePerc(perc,bezierData){
var percents = bezierData.percents;
var lengths = bezierData.lengths;
var len = percents.length;
var initPos = bm_floor((len-1)*perc);
var lengthPos = perc*bezierData.addedLength;
var lPerc = 0;
if(initPos === len - 1 || initPos === 0 || lengthPos === lengths[initPos]){
return percents[initPos];
}else{
var dir = lengths[initPos] > lengthPos ? -1 : 1;
var flag = true;
while(flag){
if(lengths[initPos] <= lengthPos && lengths[initPos+1] > lengthPos){
lPerc = (lengthPos - lengths[initPos]) / (lengths[initPos+1] - lengths[initPos]);
flag = false;
}else{
initPos += dir;
}
if(initPos < 0 || initPos >= len - 1){
//FIX for TypedArrays that don't store floating point values with enough accuracy
if(initPos === len - 1) {
return percents[initPos];
}
flag = false;
}
}
return percents[initPos] + (percents[initPos+1] - percents[initPos])*lPerc;
}
}
function getPointInSegment(pt1, pt2, pt3, pt4, percent, bezierData) {
var t1 = getDistancePerc(percent,bezierData);
var u0 = 1;
var u1 = 1 - t1;
var ptX = Math.round((u1*u1*u1* pt1[0] + (t1*u1*u1 + u1*t1*u1 + u1*u1*t1)* pt3[0] + (t1*t1*u1 + u1*t1*t1 + t1*u1*t1)*pt4[0] + t1*t1*t1* pt2[0])* 1000) / 1000;
var ptY = Math.round((u1*u1*u1* pt1[1] + (t1*u1*u1 + u1*t1*u1 + u1*u1*t1)* pt3[1] + (t1*t1*u1 + u1*t1*t1 + t1*u1*t1)*pt4[1] + t1*t1*t1* pt2[1])* 1000) / 1000;
return [ptX, ptY];
}
function getSegmentArray() {
}
var bezier_segment_points = createTypedArray('float32', 8);
function getNewSegment(pt1,pt2,pt3,pt4,startPerc,endPerc, bezierData){
startPerc = startPerc < 0 ? 0 : startPerc > 1 ? 1 : startPerc;
var t0 = getDistancePerc(startPerc,bezierData);
endPerc = endPerc > 1 ? 1 : endPerc;
var t1 = getDistancePerc(endPerc,bezierData);
var i, len = pt1.length;
var u0 = 1 - t0;
var u1 = 1 - t1;
var u0u0u0 = u0*u0*u0;
var t0u0u0_3 = t0*u0*u0*3;
var t0t0u0_3 = t0*t0*u0*3;
var t0t0t0 = t0*t0*t0;
//
var u0u0u1 = u0*u0*u1;
var t0u0u1_3 = t0*u0*u1 + u0*t0*u1 + u0*u0*t1;
var t0t0u1_3 = t0*t0*u1 + u0*t0*t1 + t0*u0*t1;
var t0t0t1 = t0*t0*t1;
//
var u0u1u1 = u0*u1*u1;
var t0u1u1_3 = t0*u1*u1 + u0*t1*u1 + u0*u1*t1;
var t0t1u1_3 = t0*t1*u1 + u0*t1*t1 + t0*u1*t1;
var t0t1t1 = t0*t1*t1;
//
var u1u1u1 = u1*u1*u1;
var t1u1u1_3 = t1*u1*u1 + u1*t1*u1 + u1*u1*t1;
var t1t1u1_3 = t1*t1*u1 + u1*t1*t1 + t1*u1*t1;
var t1t1t1 = t1*t1*t1;
for(i=0;i<len;i+=1){
bezier_segment_points[i * 4] = Math.round((u0u0u0 * pt1[i] + t0u0u0_3 * pt3[i] + t0t0u0_3 * pt4[i] + t0t0t0 * pt2[i]) * 1000) / 1000;
bezier_segment_points[i * 4 + 1] = Math.round((u0u0u1 * pt1[i] + t0u0u1_3 * pt3[i] + t0t0u1_3 * pt4[i] + t0t0t1 * pt2[i]) * 1000) / 1000;
bezier_segment_points[i * 4 + 2] = Math.round((u0u1u1 * pt1[i] + t0u1u1_3 * pt3[i] + t0t1u1_3 * pt4[i] + t0t1t1 * pt2[i]) * 1000) / 1000;
bezier_segment_points[i * 4 + 3] = Math.round((u1u1u1 * pt1[i] + t1u1u1_3 * pt3[i] + t1t1u1_3 * pt4[i] + t1t1t1 * pt2[i]) * 1000) / 1000;
}
return bezier_segment_points;
}
return {
getSegmentsLength : getSegmentsLength,
getNewSegment : getNewSegment,
getPointInSegment : getPointInSegment,
buildBezierData : buildBezierData,
pointOnLine2D : pointOnLine2D,
pointOnLine3D : pointOnLine3D
};
}
var bez = bezFunction();
function dataFunctionManager(){
//var tCanvasHelper = createTag('canvas').getContext('2d');
function completeLayers(layers, comps, fontManager){
var layerData;
var animArray, lastFrame;
var i, len = layers.length;
var j, jLen, k, kLen;
for(i=0;i<len;i+=1){
layerData = layers[i];
if(!('ks' in layerData) || layerData.completed){
continue;
}
layerData.completed = true;
if(layerData.tt){
layers[i-1].td = layerData.tt;
}
animArray = [];
lastFrame = -1;
if(layerData.hasMask){
var maskProps = layerData.masksProperties;
jLen = maskProps.length;
for(j=0;j<jLen;j+=1){
if(maskProps[j].pt.k.i){
convertPathsToAbsoluteValues(maskProps[j].pt.k);
}else{
kLen = maskProps[j].pt.k.length;
for(k=0;k<kLen;k+=1){
if(maskProps[j].pt.k[k].s){
convertPathsToAbsoluteValues(maskProps[j].pt.k[k].s[0]);
}
if(maskProps[j].pt.k[k].e){
convertPathsToAbsoluteValues(maskProps[j].pt.k[k].e[0]);
}
}
}
}
}
if(layerData.ty===0){
layerData.layers = findCompLayers(layerData.refId, comps);
completeLayers(layerData.layers,comps, fontManager);
}else if(layerData.ty === 4){
completeShapes(layerData.shapes);
}else if(layerData.ty == 5){
completeText(layerData, fontManager);
}
}
}
function findCompLayers(id,comps){
var i = 0, len = comps.length;
while(i<len){
if(comps[i].id === id){
if(!comps[i].layers.__used) {
comps[i].layers.__used = true;
return comps[i].layers;
}
return JSON.parse(JSON.stringify(comps[i].layers));
}
i += 1;
}
}
function completeShapes(arr){
var i, len = arr.length;
var j, jLen;
var hasPaths = false;
for(i=len-1;i>=0;i-=1){
if(arr[i].ty == 'sh'){
if(arr[i].ks.k.i){
convertPathsToAbsoluteValues(arr[i].ks.k);
}else{
jLen = arr[i].ks.k.length;
for(j=0;j<jLen;j+=1){
if(arr[i].ks.k[j].s){
convertPathsToAbsoluteValues(arr[i].ks.k[j].s[0]);
}
if(arr[i].ks.k[j].e){
convertPathsToAbsoluteValues(arr[i].ks.k[j].e[0]);
}
}
}
hasPaths = true;
}else if(arr[i].ty == 'gr'){
completeShapes(arr[i].it);
}
}
/*if(hasPaths){
//mx: distance
//ss: sensitivity
//dc: decay
arr.splice(arr.length-1,0,{
"ty": "ms",
"mx":20,
"ss":10,
"dc":0.001,
"maxDist":200
});
}*/
}
function convertPathsToAbsoluteValues(path){
var i, len = path.i.length;
for(i=0;i<len;i+=1){
path.i[i][0] += path.v[i][0];
path.i[i][1] += path.v[i][1];
path.o[i][0] += path.v[i][0];
path.o[i][1] += path.v[i][1];
}
}
function checkVersion(minimum,animVersionString){
var animVersion = animVersionString ? animVersionString.split('.') : [100,100,100];
if(minimum[0]>animVersion[0]){
return true;
} else if(animVersion[0] > minimum[0]){
return false;
}
if(minimum[1]>animVersion[1]){
return true;
} else if(animVersion[1] > minimum[1]){
return false;
}
if(minimum[2]>animVersion[2]){
return true;
} else if(animVersion[2] > minimum[2]){
return false;
}
}
var checkText = (function(){
var minimumVersion = [4,4,14];
function updateTextLayer(textLayer){
var documentData = textLayer.t.d;
textLayer.t.d = {
k: [
{
s:documentData,
t:0
}
]
};
}
function iterateLayers(layers){
var i, len = layers.length;
for(i=0;i<len;i+=1){
if(layers[i].ty === 5){
updateTextLayer(layers[i]);
}
}
}
return function (animationData){
if(checkVersion(minimumVersion,animationData.v)){
iterateLayers(animationData.layers);
if(animationData.assets){
var i, len = animationData.assets.length;
for(i=0;i<len;i+=1){
if(animationData.assets[i].layers){
iterateLayers(animationData.assets[i].layers);
}
}
}
}
};
}());
var checkChars = (function() {
var minimumVersion = [4,7,99];
return function (animationData){
if(animationData.chars && !checkVersion(minimumVersion,animationData.v)){
var i, len = animationData.chars.length, j, jLen, k, kLen;
var pathData, paths;
for(i = 0; i < len; i += 1) {
if(animationData.chars[i].data && animationData.chars[i].data.shapes) {
paths = animationData.chars[i].data.shapes[0].it;
jLen = paths.length;
for(j = 0; j < jLen; j += 1) {
pathData = paths[j].ks.k;
if(!pathData.__converted) {
convertPathsToAbsoluteValues(paths[j].ks.k);
pathData.__converted = true;
}
}
}
}
}
};
}());
var checkColors = (function(){
var minimumVersion = [4,1,9];
function iterateShapes(shapes){
var i, len = shapes.length;
var j, jLen;
for(i=0;i<len;i+=1){
if(shapes[i].ty === 'gr'){
iterateShapes(shapes[i].it);
}else if(shapes[i].ty === 'fl' || shapes[i].ty === 'st'){
if(shapes[i].c.k && shapes[i].c.k[0].i){
jLen = shapes[i].c.k.length;
for(j=0;j<jLen;j+=1){
if(shapes[i].c.k[j].s){
shapes[i].c.k[j].s[0] /= 255;
shapes[i].c.k[j].s[1] /= 255;
shapes[i].c.k[j].s[2] /= 255;
shapes[i].c.k[j].s[3] /= 255;
}
if(shapes[i].c.k[j].e){
shapes[i].c.k[j].e[0] /= 255;
shapes[i].c.k[j].e[1] /= 255;
shapes[i].c.k[j].e[2] /= 255;
shapes[i].c.k[j].e[3] /= 255;
}
}
} else {
shapes[i].c.k[0] /= 255;
shapes[i].c.k[1] /= 255;
shapes[i].c.k[2] /= 255;
shapes[i].c.k[3] /= 255;
}
}
}
}
function iterateLayers(layers){
var i, len = layers.length;
for(i=0;i<len;i+=1){
if(layers[i].ty === 4){
iterateShapes(layers[i].shapes);
}
}
}
return function (animationData){
if(checkVersion(minimumVersion,animationData.v)){
iterateLayers(animationData.layers);
if(animationData.assets){
var i, len = animationData.assets.length;
for(i=0;i<len;i+=1){
if(animationData.assets[i].layers){
iterateLayers(animationData.assets[i].layers);
}
}
}
}
};
}());
var checkShapes = (function(){
var minimumVersion = [4,4,18];
function completeShapes(arr){
var i, len = arr.length;
var j, jLen;
var hasPaths = false;
for(i=len-1;i>=0;i-=1){
if(arr[i].ty == 'sh'){
if(arr[i].ks.k.i){
arr[i].ks.k.c = arr[i].closed;
}else{
jLen = arr[i].ks.k.length;
for(j=0;j<jLen;j+=1){
if(arr[i].ks.k[j].s){
arr[i].ks.k[j].s[0].c = arr[i].closed;
}
if(arr[i].ks.k[j].e){
arr[i].ks.k[j].e[0].c = arr[i].closed;
}
}
}
hasPaths = true;
}else if(arr[i].ty == 'gr'){
completeShapes(arr[i].it);
}
}
}
function iterateLayers(layers){
var layerData;
var i, len = layers.length;
var j, jLen, k, kLen;
for(i=0;i<len;i+=1){
layerData = layers[i];
if(layerData.hasMask){
var maskProps = layerData.masksProperties;
jLen = maskProps.length;
for(j=0;j<jLen;j+=1){
if(maskProps[j].pt.k.i){
maskProps[j].pt.k.c = maskProps[j].cl;
}else{
kLen = maskProps[j].pt.k.length;
for(k=0;k<kLen;k+=1){
if(maskProps[j].pt.k[k].s){
maskProps[j].pt.k[k].s[0].c = maskProps[j].cl;
}
if(maskProps[j].pt.k[k].e){
maskProps[j].pt.k[k].e[0].c = maskProps[j].cl;
}
}
}
}
}
if(layerData.ty === 4){
completeShapes(layerData.shapes);
}
}
}
return function (animationData){
if(checkVersion(minimumVersion,animationData.v)){
iterateLayers(animationData.layers);
if(animationData.assets){
var i, len = animationData.assets.length;
for(i=0;i<len;i+=1){
if(animationData.assets[i].layers){
iterateLayers(animationData.assets[i].layers);
}
}
}
}
};
}());
function completeData(animationData, fontManager){
if(animationData.__complete){
return;
}
checkColors(animationData);
checkText(animationData);
checkChars(animationData);
checkShapes(animationData);
completeLayers(animationData.layers, animationData.assets, fontManager);
animationData.__complete = true;
//blitAnimation(animationData, animationData.assets, fontManager);
}
function completeText(data, fontManager){
if(data.t.a.length === 0 && !('m' in data.t.p)){
data.singleShape = true;
}
}
var moduleOb = {};
moduleOb.completeData = completeData;
return moduleOb;
}
var dataManager = dataFunctionManager();
var FontManager = (function(){
var maxWaitingTime = 5000;
var emptyChar = {
w: 0,
size:0,
shapes:[]
};
var combinedCharacters = [];
//Hindi characters
combinedCharacters = combinedCharacters.concat([2304, 2305, 2306, 2307, 2362, 2363, 2364, 2364, 2366
, 2367, 2368, 2369, 2370, 2371, 2372, 2373, 2374, 2375, 2376, 2377, 2378, 2379
, 2380, 2381, 2382, 2383, 2387, 2388, 2389, 2390, 2391, 2402, 2403]);
function setUpNode(font, family){
var parentNode = createTag('span');
parentNode.style.fontFamily = family;
var node = createTag('span');
// Characters that vary significantly among different fonts
node.innerHTML = 'giItT1WQy@!-/#';
// Visible - so we can measure it - but not on the screen
parentNode.style.position = 'absolute';
parentNode.style.left = '-10000px';
parentNode.style.top = '-10000px';
// Large font size makes even subtle changes obvious
parentNode.style.fontSize = '300px';
// Reset any font properties
parentNode.style.fontVariant = 'normal';
parentNode.style.fontStyle = 'normal';
parentNode.style.fontWeight = 'normal';
parentNode.style.letterSpacing = '0';
parentNode.appendChild(node);
document.body.appendChild(parentNode);
// Remember width with no applied web font
var width = node.offsetWidth;
node.style.fontFamily = font + ', '+family;
return {node:node, w:width, parent:parentNode};
}
function checkLoadedFonts() {
var i, len = this.fonts.length;
var node, w;
var loadedCount = len;
for(i=0;i<len; i+= 1){
if(this.fonts[i].loaded){
loadedCount -= 1;
continue;
}
if(this.fonts[i].fOrigin === 't' || this.fonts[i].origin === 2){
if(window.Typekit && window.Typekit.load && this.typekitLoaded === 0){
this.typekitLoaded = 1;
try{window.Typekit.load({
async: true,
active: function() {
this.typekitLoaded = 2;
}.bind(this)
});}catch(e){}
}
if(this.typekitLoaded === 2) {
this.fonts[i].loaded = true;
}
} else if(this.fonts[i].fOrigin === 'n' || this.fonts[i].origin === 0){
this.fonts[i].loaded = true;
} else{
node = this.fonts[i].monoCase.node;
w = this.fonts[i].monoCase.w;
if(node.offsetWidth !== w){
loadedCount -= 1;
this.fonts[i].loaded = true;
}else{
node = this.fonts[i].sansCase.node;
w = this.fonts[i].sansCase.w;
if(node.offsetWidth !== w){
loadedCount -= 1;
this.fonts[i].loaded = true;
}
}
if(this.fonts[i].loaded){
this.fonts[i].sansCase.parent.parentNode.removeChild(this.fonts[i].sansCase.parent);
this.fonts[i].monoCase.parent.parentNode.removeChild(this.fonts[i].monoCase.parent);
}
}
}
if(loadedCount !== 0 && Date.now() - this.initTime < maxWaitingTime){
setTimeout(checkLoadedFonts.bind(this),20);
}else{
setTimeout(function(){this.loaded = true;}.bind(this),0);
}
}
function createHelper(def, fontData){
var tHelper = createNS('text');
tHelper.style.fontSize = '100px';
//tHelper.style.fontFamily = fontData.fFamily;
tHelper.setAttribute('font-family', fontData.fFamily);
tHelper.setAttribute('font-style', fontData.fStyle);
tHelper.setAttribute('font-weight', fontData.fWeight);
tHelper.textContent = '1';
if(fontData.fClass){
tHelper.style.fontFamily = 'inherit';
tHelper.className = fontData.fClass;
} else {
tHelper.style.fontFamily = fontData.fFamily;
}
def.appendChild(tHelper);
var tCanvasHelper = createTag('canvas').getContext('2d');
tCanvasHelper.font = fontData.fWeight + ' ' + fontData.fStyle + ' 100px '+ fontData.fFamily;
//tCanvasHelper.font = ' 100px '+ fontData.fFamily;
return tHelper;
}
function addFonts(fontData, defs){
if(!fontData){
this.loaded = true;
return;
}
if(this.chars){
this.loaded = true;
this.fonts = fontData.list;
return;
}
var fontArr = fontData.list;
var i, len = fontArr.length;
for(i=0; i<len; i+= 1){
fontArr[i].loaded = false;
fontArr[i].monoCase = setUpNode(fontArr[i].fFamily,'monospace');
fontArr[i].sansCase = setUpNode(fontArr[i].fFamily,'sans-serif');
if(!fontArr[i].fPath) {
fontArr[i].loaded = true;
}else if(fontArr[i].fOrigin === 'p' || fontArr[i].origin === 3){
var s = createTag('style');
s.type = "text/css";
s.innerHTML = "@font-face {" + "font-family: "+fontArr[i].fFamily+"; font-style: normal; src: url('"+fontArr[i].fPath+"');}";
defs.appendChild(s);
} else if(fontArr[i].fOrigin === 'g' || fontArr[i].origin === 1){
var l = createTag('link');
l.type = "text/css";
l.rel = "stylesheet";
l.href = fontArr[i].fPath;
document.body.appendChild(l);
} else if(fontArr[i].fOrigin === 't' || fontArr[i].origin === 2){
var sc = createTag('script');
sc.setAttribute('src',fontArr[i].fPath);
defs.appendChild(sc);
}
fontArr[i].helper = createHelper(defs,fontArr[i]);
fontArr[i].cache = {};
this.fonts.push(fontArr[i]);
}
//On some cases the font even if it is loaded, it won't load correctly when measuring text on canvas.
//Adding this timeout seems to fix it
setTimeout(function() {
checkLoadedFonts.bind(this)();
}.bind(this), 100);
}
function addChars(chars){
if(!chars){
return;
}
if(!this.chars){
this.chars = [];
}
var i, len = chars.length;
var j, jLen = this.chars.length, found;
for(i=0;i<len;i+=1){
j = 0;
found = false;
while(j<jLen){
if(this.chars[j].style === chars[i].style && this.chars[j].fFamily === chars[i].fFamily && this.chars[j].ch === chars[i].ch){
found = true;
}
j += 1;
}
if(!found){
this.chars.push(chars[i]);
jLen += 1;
}
}
}
function getCharData(char, style, font){
var i = 0, len = this.chars.length;
while( i < len) {
if(this.chars[i].ch === char && this.chars[i].style === style && this.chars[i].fFamily === font){
return this.chars[i];
}
i+= 1;
}
if(console && console.warn) {
console.warn('Missing character from exported characters list: ', char, style, font);
}
return emptyChar;
}
function measureText(char, fontName, size) {
var fontData = this.getFontByName(fontName);
var index = char.charCodeAt(0);
if(!fontData.cache[index + 1]) {
var tHelper = fontData.helper;
//Canvas version
//fontData.cache[index] = tHelper.measureText(char).width / 100;
//SVG version
//console.log(tHelper.getBBox().width)
/*tHelper.textContent = '|' + char + '|';
var doubleSize = tHelper.getComputedTextLength();
tHelper.textContent = '||';
var singleSize = tHelper.getComputedTextLength();
fontData.cache[index + 1] = (doubleSize - singleSize)/100;*/
tHelper.textContent = char;
fontData.cache[index + 1] = (tHelper.getComputedTextLength())/100;
}
return fontData.cache[index + 1] * size;
}
function getFontByName(name){
var i = 0, len = this.fonts.length;
while(i<len){
if(this.fonts[i].fName === name) {
return this.fonts[i];
}
i += 1;
}
return this.fonts[0];
}
function getCombinedCharacterCodes() {
return combinedCharacters;
}
var Font = function(){
this.fonts = [];
this.chars = null;
this.typekitLoaded = 0;
this.loaded = false;
this.initTime = Date.now();
};
//TODO: for now I'm adding these methods to the Class and not the prototype. Think of a better way to implement it.
Font.getCombinedCharacterCodes = getCombinedCharacterCodes;
Font.prototype.addChars = addChars;
Font.prototype.addFonts = addFonts;
Font.prototype.getCharData = getCharData;
Font.prototype.getFontByName = getFontByName;
Font.prototype.measureText = measureText;
return Font;
}());
var PropertyFactory = (function(){
var initFrame = initialDefaultFrame;
var math_abs = Math.abs;
function interpolateValue(frameNum, caching){
var offsetTime = this.offsetTime;
var newValue;
if(this.propType === 'multidimensional') {
newValue = createTypedArray('float32', this.pv.length);
}
var iterationIndex = caching.lastIndex;
var i = iterationIndex;
var len = this.keyframes.length- 1,flag = true;
var keyData, nextKeyData;
while(flag){
keyData = this.keyframes[i];
nextKeyData = this.keyframes[i+1];
if(i == len-1 && frameNum >= nextKeyData.t - offsetTime){
if(keyData.h){
keyData = nextKeyData;
}
iterationIndex = 0;
break;
}
if((nextKeyData.t - offsetTime) > frameNum){
iterationIndex = i;
break;
}
if(i < len - 1){
i += 1;
}else{
iterationIndex = 0;
flag = false;
}
}
var k, kLen,perc,jLen, j, fnc;
if(keyData.to){
if(!keyData.bezierData){
bez.buildBezierData(keyData);
}
var bezierData = keyData.bezierData;
if(frameNum >= nextKeyData.t-offsetTime || frameNum < keyData.t-offsetTime){
var ind = frameNum >= nextKeyData.t-offsetTime ? bezierData.points.length - 1 : 0;
kLen = bezierData.points[ind].point.length;
for(k = 0; k < kLen; k += 1){
newValue[k] = bezierData.points[ind].point[k];
}
caching._lastBezierData = null;
}else{
if(keyData.__fnct){
fnc = keyData.__fnct;
}else{
fnc = BezierFactory.getBezierEasing(keyData.o.x,keyData.o.y,keyData.i.x,keyData.i.y,keyData.n).get;
keyData.__fnct = fnc;
}
perc = fnc((frameNum-(keyData.t-offsetTime))/((nextKeyData.t-offsetTime)-(keyData.t-offsetTime)));
var distanceInLine = bezierData.segmentLength*perc;
var segmentPerc;
var addedLength = (caching.lastFrame < frameNum && caching._lastBezierData === bezierData) ? caching._lastAddedLength : 0;
j = (caching.lastFrame < frameNum && caching._lastBezierData === bezierData) ? caching._lastPoint : 0;
flag = true;
jLen = bezierData.points.length;
while(flag){
addedLength +=bezierData.points[j].partialLength;
if(distanceInLine === 0 || perc === 0 || j == bezierData.points.length - 1){
kLen = bezierData.points[j].point.length;
for(k=0;k<kLen;k+=1){
newValue[k] = bezierData.points[j].point[k];
}
break;
}else if(distanceInLine >= addedLength && distanceInLine < addedLength + bezierData.points[j+1].partialLength){
segmentPerc = (distanceInLine-addedLength)/(bezierData.points[j+1].partialLength);
kLen = bezierData.points[j].point.length;
for(k=0;k<kLen;k+=1){
newValue[k] = bezierData.points[j].point[k] + (bezierData.points[j+1].point[k] - bezierData.points[j].point[k])*segmentPerc;
}
break;
}
if(j < jLen - 1){
j += 1;
}else{
flag = false;
}
}
caching._lastPoint = j;
caching._lastAddedLength = addedLength - bezierData.points[j].partialLength;
caching._lastBezierData = bezierData;
}
}else{
var outX,outY,inX,inY, keyValue;
len = keyData.s.length;
if(this.sh && keyData.h !== 1) {
if(frameNum >= nextKeyData.t-offsetTime){
newValue[0] = keyData.e[0];
newValue[1] = keyData.e[1];
newValue[2] = keyData.e[2];
}else if(frameNum <= keyData.t-offsetTime){
newValue[0] = keyData.s[0];
newValue[1] = keyData.s[1];
newValue[2] = keyData.s[2];
}else{
var quatStart = createQuaternion(keyData.s);
var quatEnd = createQuaternion(keyData.e);
var time = (frameNum-(keyData.t-offsetTime))/((nextKeyData.t-offsetTime)-(keyData.t-offsetTime));
quaternionToEuler(newValue, slerp(quatStart, quatEnd, time));
}
} else {
for(i=0;i<len;i+=1){
if(keyData.h !== 1){
if(frameNum >= nextKeyData.t-offsetTime){
perc = 1;
}else if(frameNum < keyData.t-offsetTime){
perc = 0;
}else{
if(keyData.o.x.constructor === Array){
if(!keyData.__fnct){
keyData.__fnct = [];
}
if (!keyData.__fnct[i]) {
outX = keyData.o.x[i] || keyData.o.x[0];
outY = keyData.o.y[i] || keyData.o.y[0];
inX = keyData.i.x[i] || keyData.i.x[0];
inY = keyData.i.y[i] || keyData.i.y[0];
fnc = BezierFactory.getBezierEasing(outX,outY,inX,inY).get;
keyData.__fnct[i] = fnc;
} else {
fnc = keyData.__fnct[i];
}
} else {
if (!keyData.__fnct) {
outX = keyData.o.x;
outY = keyData.o.y;
inX = keyData.i.x;
inY = keyData.i.y;
fnc = BezierFactory.getBezierEasing(outX,outY,inX,inY).get;
keyData.__fnct = fnc;
} else{
fnc = keyData.__fnct;
}
}
perc = fnc((frameNum-(keyData.t-offsetTime))/((nextKeyData.t-offsetTime)-(keyData.t-offsetTime)));
}
}
keyValue = keyData.h === 1 ? keyData.s[i] : keyData.s[i]+(keyData.e[i]-keyData.s[i])*perc;
if(len === 1){
newValue = keyValue;
}else{
newValue[i] = keyValue;
}
}
}
}
caching.lastIndex = iterationIndex;
return newValue;
}
//based on @Toji's https://github.com/toji/gl-matrix/
function slerp(a, b, t) {
var out = [];
var ax = a[0], ay = a[1], az = a[2], aw = a[3],
bx = b[0], by = b[1], bz = b[2], bw = b[3]
var omega, cosom, sinom, scale0, scale1;
cosom = ax * bx + ay * by + az * bz + aw * bw;
if (cosom < 0.0) {
cosom = -cosom;
bx = -bx;
by = -by;
bz = -bz;
bw = -bw;
}
if ((1.0 - cosom) > 0.000001) {
omega = Math.acos(cosom);
sinom = Math.sin(omega);
scale0 = Math.sin((1.0 - t) * omega) / sinom;
scale1 = Math.sin(t * omega) / sinom;
} else {
scale0 = 1.0 - t;
scale1 = t;
}
out[0] = scale0 * ax + scale1 * bx;
out[1] = scale0 * ay + scale1 * by;
out[2] = scale0 * az + scale1 * bz;
out[3] = scale0 * aw + scale1 * bw;
return out;
}
function quaternionToEuler(out, quat) {
var qx = quat[0];
var qy = quat[1];
var qz = quat[2];
var qw = quat[3];
var heading = Math.atan2(2*qy*qw-2*qx*qz , 1 - 2*qy*qy - 2*qz*qz)
var attitude = Math.asin(2*qx*qy + 2*qz*qw)
var bank = Math.atan2(2*qx*qw-2*qy*qz , 1 - 2*qx*qx - 2*qz*qz);
out[0] = heading/degToRads;
out[1] = attitude/degToRads;
out[2] = bank/degToRads;
}
function createQuaternion(values) {
var heading = values[0] * degToRads;
var attitude = values[1] * degToRads;
var bank = values[2] * degToRads;
var c1 = Math.cos(heading / 2);
var c2 = Math.cos(attitude / 2);
var c3 = Math.cos(bank / 2);
var s1 = Math.sin(heading / 2);
var s2 = Math.sin(attitude / 2);
var s3 = Math.sin(bank / 2);
var w = c1 * c2 * c3 - s1 * s2 * s3;
var x = s1 * s2 * c3 + c1 * c2 * s3;
var y = s1 * c2 * c3 + c1 * s2 * s3;
var z = c1 * s2 * c3 - s1 * c2 * s3;
return [x,y,z,w];
}
function getValueAtCurrentTime(){
var frameNum = this.comp.renderedFrame - this.offsetTime;
var initTime = this.keyframes[0].t - this.offsetTime;
var endTime = this.keyframes[this.keyframes.length- 1].t-this.offsetTime;
if(!(frameNum === this._caching.lastFrame || (this._caching.lastFrame !== initFrame && ((this._caching.lastFrame >= endTime && frameNum >= endTime) || (this._caching.lastFrame < initTime && frameNum < initTime))))){
this._caching.lastIndex = this._caching.lastFrame < frameNum ? this._caching.lastIndex : 0;
var renderResult = this.interpolateValue(frameNum, this._caching);
this.pv = renderResult;
}
this._caching.lastFrame = frameNum;
return this.pv;
}
function setVValue(val) {
var multipliedValue;
if(this.propType === 'unidimensional') {
multipliedValue = val * this.mult;
if(math_abs(this.v - multipliedValue) > 0.00001) {
this.v = multipliedValue;
this._mdf = true;
}
} else {
var i = 0, len = this.v.length;
while (i < len) {
multipliedValue = val[i] * this.mult;
if (math_abs(this.v[i] - multipliedValue) > 0.00001) {
this.v[i] = multipliedValue;
this._mdf = true;
}
i += 1;
}
}
}
function processEffectsSequence() {
if(this.elem.globalData.frameId === this.frameId || !this.effectsSequence.length) {
return;
}
if(this.lock) {
this.setVValue(this.pv);
return;
}
this.lock = true;
this._mdf = this._isFirstFrame;
var multipliedValue;
var i, len = this.effectsSequence.length;
var finalValue = this.kf ? this.pv : this.data.k;
for(i = 0; i < len; i += 1) {
finalValue = this.effectsSequence[i](finalValue);
}
this.setVValue(finalValue);
this._isFirstFrame = false;
this.lock = false;
this.frameId = this.elem.globalData.frameId;
}
function addEffect(effectFunction) {
this.effectsSequence.push(effectFunction);
this.container.addDynamicProperty(this);
}
function ValueProperty(elem, data, mult, container){
this.propType = 'unidimensional';
this.mult = mult || 1;
this.data = data;
this.v = mult ? data.k * mult : data.k;
this.pv = data.k;
this._mdf = false;
this.elem = elem;
this.container = container;
this.comp = elem.comp;
this.k = false;
this.kf = false;
this.vel = 0;
this.effectsSequence = [];
this._isFirstFrame = true;
this.getValue = processEffectsSequence;
this.setVValue = setVValue;
this.addEffect = addEffect;
}
function MultiDimensionalProperty(elem, data, mult, container) {
this.propType = 'multidimensional';
this.mult = mult || 1;
this.data = data;
this._mdf = false;
this.elem = elem;
this.container = container;
this.comp = elem.comp;
this.k = false;
this.kf = false;
this.frameId = -1;
var i, len = data.k.length;
this.v = createTypedArray('float32', len);
this.pv = createTypedArray('float32', len);
var arr = createTypedArray('float32', len);
this.vel = createTypedArray('float32', len);
for (i = 0; i < len; i += 1) {
this.v[i] = data.k[i] * this.mult;
this.pv[i] = data.k[i];
}
this._isFirstFrame = true;
this.effectsSequence = [];
this.getValue = processEffectsSequence;
this.setVValue = setVValue;
this.addEffect = addEffect;
}
function KeyframedValueProperty(elem, data, mult, container) {
this.propType = 'unidimensional';
this.keyframes = data.k;
this.offsetTime = elem.data.st;
this.frameId = -1;
this._caching = {lastFrame: initFrame, lastIndex: 0, value: 0};
this.k = true;
this.kf = true;
this.data = data;
this.mult = mult || 1;
this.elem = elem;
this.container = container;
this.comp = elem.comp;
this.v = initFrame;
this.pv = initFrame;
this._isFirstFrame = true;
this.getValue = processEffectsSequence;
this.setVValue = setVValue;
this.interpolateValue = interpolateValue;
this.effectsSequence = [getValueAtCurrentTime.bind(this)];
this.addEffect = addEffect;
}
function KeyframedMultidimensionalProperty(elem, data, mult, container){
this.propType = 'multidimensional';
var i, len = data.k.length;
var s, e,to,ti;
for (i = 0; i < len - 1; i += 1) {
if (data.k[i].to && data.k[i].s && data.k[i].e) {
s = data.k[i].s;
e = data.k[i].e;
to = data.k[i].to;
ti = data.k[i].ti;
if((s.length === 2 && !(s[0] === e[0] && s[1] === e[1]) && bez.pointOnLine2D(s[0],s[1],e[0],e[1],s[0] + to[0],s[1] + to[1]) && bez.pointOnLine2D(s[0],s[1],e[0],e[1],e[0] + ti[0],e[1] + ti[1])) || (s.length === 3 && !(s[0] === e[0] && s[1] === e[1] && s[2] === e[2]) && bez.pointOnLine3D(s[0],s[1],s[2],e[0],e[1],e[2],s[0] + to[0],s[1] + to[1],s[2] + to[2]) && bez.pointOnLine3D(s[0],s[1],s[2],e[0],e[1],e[2],e[0] + ti[0],e[1] + ti[1],e[2] + ti[2]))){
data.k[i].to = null;
data.k[i].ti = null;
}
if(s[0] === e[0] && s[1] === e[1] && to[0] === 0 && to[1] === 0 && ti[0] === 0 && ti[1] === 0) {
if(s.length === 2 || (s[2] === e[2] && to[2] === 0 && ti[2] === 0)) {
data.k[i].to = null;
data.k[i].ti = null;
}
}
}
}
this.effectsSequence = [getValueAtCurrentTime.bind(this)];
this.keyframes = data.k;
this.offsetTime = elem.data.st;
this.k = true;
this.kf = true;
this._isFirstFrame = true;
this.mult = mult || 1;
this.elem = elem;
this.container = container;
this.comp = elem.comp;
this.getValue = processEffectsSequence;
this.setVValue = setVValue;
this.interpolateValue = interpolateValue;
this.frameId = -1;
var arrLen = data.k[0].s.length;
this.v = createTypedArray('float32', arrLen);
this.pv = createTypedArray('float32', arrLen);
for (i = 0; i < arrLen; i += 1) {
this.v[i] = initFrame;
this.pv[i] = initFrame;
}
this._caching={lastFrame:initFrame,lastIndex:0,value:createTypedArray('float32', arrLen)};
this.addEffect = addEffect;
}
function getProp(elem,data,type, mult, container) {
var p;
if(data.a === 0){
if(type === 0) {
p = new ValueProperty(elem,data,mult, container);
} else {
p = new MultiDimensionalProperty(elem,data, mult, container);
}
} else if(data.a === 1){
if(type === 0) {
p = new KeyframedValueProperty(elem,data,mult, container);
} else {
p = new KeyframedMultidimensionalProperty(elem,data, mult, container);
}
} else if(!data.k.length){
p = new ValueProperty(elem,data, mult, container);
}else if(typeof(data.k[0]) === 'number'){
p = new MultiDimensionalProperty(elem,data, mult, container);
}else{
switch(type){
case 0:
p = new KeyframedValueProperty(elem,data,mult, container);
break;
case 1:
p = new KeyframedMultidimensionalProperty(elem,data,mult, container);
break;
}
}
if(p.effectsSequence.length){
container.addDynamicProperty(p);
}
return p;
}
var ob = {
getProp: getProp
};
return ob;
}());
var TransformPropertyFactory = (function() {
function applyToMatrix(mat) {
var _mdf = this._mdf;
this.iterateDynamicProperties();
this._mdf = this._mdf || _mdf;
if (this.a) {
mat.translate(-this.a.v[0], -this.a.v[1], this.a.v[2]);
}
if (this.s) {
mat.scale(this.s.v[0], this.s.v[1], this.s.v[2]);
}
if (this.sk) {
mat.skewFromAxis(-this.sk.v, this.sa.v);
}
if (this.r) {
mat.rotate(-this.r.v);
} else {
mat.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]);
}
if (this.data.p.s) {
if (this.data.p.z) {
mat.translate(this.px.v, this.py.v, -this.pz.v);
} else {
mat.translate(this.px.v, this.py.v, 0);
}
} else {
mat.translate(this.p.v[0], this.p.v[1], -this.p.v[2]);
}
}
function processKeys(forceRender){
if (this.elem.globalData.frameId === this.frameId) {
return;
}
if(this._isDirty) {
this.precalculateMatrix();
this._isDirty = false;
}
this.iterateDynamicProperties();
if (this._mdf || forceRender) {
this.v.cloneFromProps(this.pre.props);
if (this.appliedTransformations < 1) {
this.v.translate(-this.a.v[0], -this.a.v[1], this.a.v[2]);
}
if(this.appliedTransformations < 2) {
this.v.scale(this.s.v[0], this.s.v[1], this.s.v[2]);
}
if (this.sk && this.appliedTransformations < 3) {
this.v.skewFromAxis(-this.sk.v, this.sa.v);
}
if (this.r && this.appliedTransformations < 4) {
this.v.rotate(-this.r.v);
} else if (!this.r && this.appliedTransformations < 4){
this.v.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]);
}
if (this.autoOriented && this.p.keyframes && this.p.getValueAtTime) {
var v1,v2;
if (this.p._caching.lastFrame+this.p.offsetTime <= this.p.keyframes[0].t) {
v1 = this.p.getValueAtTime((this.p.keyframes[0].t + 0.01) / this.elem.globalData.frameRate,0);
v2 = this.p.getValueAtTime(this.p.keyframes[0].t / this.elem.globalData.frameRate, 0);
} else if(this.p._caching.lastFrame+this.p.offsetTime >= this.p.keyframes[this.p.keyframes.length - 1].t) {
v1 = this.p.getValueAtTime((this.p.keyframes[this.p.keyframes.length - 1].t / this.elem.globalData.frameRate), 0);
v2 = this.p.getValueAtTime((this.p.keyframes[this.p.keyframes.length - 1].t - 0.01) / this.elem.globalData.frameRate, 0);
} else {
v1 = this.p.pv;
v2 = this.p.getValueAtTime((this.p._caching.lastFrame+this.p.offsetTime - 0.01) / this.elem.globalData.frameRate, this.p.offsetTime);
}
this.v.rotate(-Math.atan2(v1[1] - v2[1], v1[0] - v2[0]));
}
if(this.data.p.s){
if(this.data.p.z) {
this.v.translate(this.px.v, this.py.v, -this.pz.v);
} else {
this.v.translate(this.px.v, this.py.v, 0);
}
}else{
this.v.translate(this.p.v[0],this.p.v[1],-this.p.v[2]);
}
}
this.frameId = this.elem.globalData.frameId;
}
function precalculateMatrix() {
if(!this.a.k) {
this.pre.translate(-this.a.v[0], -this.a.v[1], this.a.v[2]);
this.appliedTransformations = 1;
} else {
return;
}
if(!this.s.effectsSequence.length) {
this.pre.scale(this.s.v[0], this.s.v[1], this.s.v[2]);
this.appliedTransformations = 2;
} else {
return;
}
if(this.sk) {
if(!this.sk.effectsSequence.length && !this.sa.effectsSequence.length) {
this.pre.skewFromAxis(-this.sk.v, this.sa.v);
this.appliedTransformations = 3;
} else {
return;
}
}
if (this.r) {
if(!this.r.effectsSequence.length) {
this.pre.rotate(-this.r.v);
this.appliedTransformations = 4;
} else {
return;
}
} else if(!this.rz.effectsSequence.length && !this.ry.effectsSequence.length && !this.rx.effectsSequence.length && !this.or.effectsSequence.length) {
this.pre.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]);
this.appliedTransformations = 4;
}
}
function autoOrient(){
//
//var prevP = this.getValueAtTime();
}
function addDynamicProperty(prop) {
this._addDynamicProperty(prop);
this.elem.addDynamicProperty(prop);
this._isDirty = true;
}
function TransformProperty(elem,data,container){
this.elem = elem;
this.frameId = -1;
this.propType = 'transform';
this.data = data;
this.v = new Matrix();
//Precalculated matrix with non animated properties
this.pre = new Matrix();
this.appliedTransformations = 0;
this.initDynamicPropertyContainer(container || elem);
if(data.p.s){
this.px = PropertyFactory.getProp(elem,data.p.x,0,0,this);
this.py = PropertyFactory.getProp(elem,data.p.y,0,0,this);
if(data.p.z){
this.pz = PropertyFactory.getProp(elem,data.p.z,0,0,this);
}
}else{
this.p = PropertyFactory.getProp(elem,data.p,1,0,this);
}
if(data.r) {
this.r = PropertyFactory.getProp(elem, data.r, 0, degToRads, this);
} else if(data.rx) {
this.rx = PropertyFactory.getProp(elem, data.rx, 0, degToRads, this);
this.ry = PropertyFactory.getProp(elem, data.ry, 0, degToRads, this);
this.rz = PropertyFactory.getProp(elem, data.rz, 0, degToRads, this);
if(data.or.k[0].ti) {
var i, len = data.or.k.length;
for(i=0;i<len;i+=1) {
data.or.k[i].to = data.or.k[i].ti = null;
}
}
this.or = PropertyFactory.getProp(elem, data.or, 1, degToRads, this);
//sh Indicates it needs to be capped between -180 and 180
this.or.sh = true;
}
if(data.sk){
this.sk = PropertyFactory.getProp(elem, data.sk, 0, degToRads, this);
this.sa = PropertyFactory.getProp(elem, data.sa, 0, degToRads, this);
}
if(data.a) {
this.a = PropertyFactory.getProp(elem,data.a,1,0,this);
}
if(data.s) {
this.s = PropertyFactory.getProp(elem,data.s,1,0.01,this);
}
// Opacity is not part of the transform properties, that's why it won't use this.dynamicProperties. That way transforms won't get updated if opacity changes.
if(data.o){
this.o = PropertyFactory.getProp(elem,data.o,0,0.01,elem);
} else {
this.o = {_mdf:false,v:1};
}
this._isDirty = true;
if(!this.dynamicProperties.length){
this.getValue(true);
}
}
TransformProperty.prototype = {
applyToMatrix: applyToMatrix,
getValue: processKeys,
precalculateMatrix: precalculateMatrix,
autoOrient: autoOrient
}
extendPrototype([DynamicPropertyContainer], TransformProperty);
TransformProperty.prototype.addDynamicProperty = addDynamicProperty;
TransformProperty.prototype._addDynamicProperty = DynamicPropertyContainer.prototype.addDynamicProperty;
function getTransformProperty(elem,data,container){
return new TransformProperty(elem,data,container);
}
return {
getTransformProperty: getTransformProperty
};
}());
function ShapePath(){
this.c = false;
this._length = 0;
this._maxLength = 8;
this.v = createSizedArray(this._maxLength);
this.o = createSizedArray(this._maxLength);
this.i = createSizedArray(this._maxLength);
}
ShapePath.prototype.setPathData = function(closed, len) {
this.c = closed;
this.setLength(len);
var i = 0;
while(i < len){
this.v[i] = point_pool.newElement();
this.o[i] = point_pool.newElement();
this.i[i] = point_pool.newElement();
i += 1;
}
};
ShapePath.prototype.setLength = function(len) {
while(this._maxLength < len) {
this.doubleArrayLength();
}
this._length = len;
};
ShapePath.prototype.doubleArrayLength = function() {
this.v = this.v.concat(createSizedArray(this._maxLength));
this.i = this.i.concat(createSizedArray(this._maxLength));
this.o = this.o.concat(createSizedArray(this._maxLength));
this._maxLength *= 2;
};
ShapePath.prototype.setXYAt = function(x, y, type, pos, replace) {
var arr;
this._length = Math.max(this._length, pos + 1);
if(this._length >= this._maxLength) {
this.doubleArrayLength();
}
switch(type){
case 'v':
arr = this.v;
break;
case 'i':
arr = this.i;
break;
case 'o':
arr = this.o;
break;
}
if(!arr[pos] || (arr[pos] && !replace)){
arr[pos] = point_pool.newElement();
}
arr[pos][0] = x;
arr[pos][1] = y;
};
ShapePath.prototype.setTripleAt = function(vX,vY,oX,oY,iX,iY,pos, replace) {
this.setXYAt(vX,vY,'v',pos, replace);
this.setXYAt(oX,oY,'o',pos, replace);
this.setXYAt(iX,iY,'i',pos, replace);
};
ShapePath.prototype.reverse = function() {
var newPath = new ShapePath();
newPath.setPathData(this.c, this._length);
var vertices = this.v, outPoints = this.o, inPoints = this.i;
var init = 0;
if (this.c) {
newPath.setTripleAt(vertices[0][0], vertices[0][1], inPoints[0][0], inPoints[0][1], outPoints[0][0], outPoints[0][1], 0, false);
init = 1;
}
var cnt = this._length - 1;
var len = this._length;
var i;
for (i = init; i < len; i += 1) {
newPath.setTripleAt(vertices[cnt][0], vertices[cnt][1], inPoints[cnt][0], inPoints[cnt][1], outPoints[cnt][0], outPoints[cnt][1], i, false);
cnt -= 1;
}
return newPath;
};
var ShapePropertyFactory = (function(){
var initFrame = -999999;
function interpolateShape(frameNum, previousValue, caching) {
var iterationIndex = caching.lastIndex;
var keyPropS,keyPropE,isHold, j, k, jLen, kLen, perc, vertexValue;
var kf = this.keyframes;
if(frameNum < kf[0].t-this.offsetTime){
keyPropS = kf[0].s[0];
isHold = true;
iterationIndex = 0;
}else if(frameNum >= kf[kf.length - 1].t-this.offsetTime){
if(kf[kf.length - 2].h === 1){
keyPropS = kf[kf.length - 1].s[0];
}else{
keyPropS = kf[kf.length - 2].e[0];
}
isHold = true;
}else{
var i = iterationIndex;
var len = kf.length- 1,flag = true,keyData,nextKeyData;
while(flag){
keyData = kf[i];
nextKeyData = kf[i+1];
if((nextKeyData.t - this.offsetTime) > frameNum){
break;
}
if(i < len - 1){
i += 1;
}else{
flag = false;
}
}
isHold = keyData.h === 1;
iterationIndex = i;
if(!isHold){
if(frameNum >= nextKeyData.t-this.offsetTime){
perc = 1;
}else if(frameNum < keyData.t-this.offsetTime){
perc = 0;
}else{
var fnc;
if(keyData.__fnct){
fnc = keyData.__fnct;
}else{
fnc = BezierFactory.getBezierEasing(keyData.o.x,keyData.o.y,keyData.i.x,keyData.i.y).get;
keyData.__fnct = fnc;
}
perc = fnc((frameNum-(keyData.t-this.offsetTime))/((nextKeyData.t-this.offsetTime)-(keyData.t-this.offsetTime)));
}
keyPropE = keyData.e[0];
}
keyPropS = keyData.s[0];
}
jLen = previousValue._length;
kLen = keyPropS.i[0].length;
caching.lastIndex = iterationIndex;
for(j=0;j<jLen;j+=1){
for(k=0;k<kLen;k+=1){
vertexValue = isHold ? keyPropS.i[j][k] : keyPropS.i[j][k]+(keyPropE.i[j][k]-keyPropS.i[j][k])*perc;
previousValue.i[j][k] = vertexValue;
vertexValue = isHold ? keyPropS.o[j][k] : keyPropS.o[j][k]+(keyPropE.o[j][k]-keyPropS.o[j][k])*perc;
previousValue.o[j][k] = vertexValue;
vertexValue = isHold ? keyPropS.v[j][k] : keyPropS.v[j][k]+(keyPropE.v[j][k]-keyPropS.v[j][k])*perc;
previousValue.v[j][k] = vertexValue;
}
}
window.contador = window.contador ? window.contador + 1 : 1;
}
function interpolateShapeCurrentTime(){
var frameNum = this.comp.renderedFrame - this.offsetTime;
var initTime = this.keyframes[0].t - this.offsetTime;
var endTime = this.keyframes[this.keyframes.length - 1].t - this.offsetTime;
var lastFrame = this._caching.lastFrame;
if(!(lastFrame !== initFrame && ((lastFrame < initTime && frameNum < initTime) || (lastFrame > endTime && frameNum > endTime)))){
////
this._caching.lastIndex = lastFrame < frameNum ? this._caching.lastIndex : 0;
this.interpolateShape(frameNum, this.pv, this._caching);
////
}
this._caching.lastFrame = frameNum;
return this.pv;
}
function resetShape(){
this.paths = this.localShapeCollection;
}
function shapesEqual(shape1, shape2) {
if(shape1._length !== shape2._length || shape1.c !== shape2.c){
return false;
}
var i, len = shape1._length;
for(i = 0; i < len; i += 1) {
if(shape1.v[i][0] !== shape2.v[i][0] || shape1.v[i][1] !== shape2.v[i][1] || shape1.o[i][0] !== shape2.o[i][0] || shape1.o[i][1] !== shape2.o[i][1] || shape1.i[i][0] !== shape2.i[i][0] || shape1.i[i][1] !== shape2.i[i][1]){
return false;
}
}
return true;
}
function processEffectsSequence() {
if(this.lock || this.elem.globalData.frameId === this.frameId) {
return;
}
this.lock = true;
this.frameId = this.elem.globalData.frameId;
this._mdf = false;
var finalValue = this.kf ? this.pv : this.data.ks ? this.data.ks.k : this.data.pt.k;
var i, len = this.effectsSequence.length;
for(i = 0; i < len; i += 1) {
finalValue = this.effectsSequence[i](finalValue);
}
if(!shapesEqual(this.v, finalValue)) {
this.v = shape_pool.clone(finalValue);
this.localShapeCollection.releaseShapes();
this.localShapeCollection.addShape(this.v);
this._mdf = true;
this.paths = this.localShapeCollection;
}
this.lock = false;
};
function ShapeProperty(elem, data, type){
this.propType = 'shape';
this.comp = elem.comp;
this.container = elem;
this.elem = elem;
this.data = data;
this.k = false;
this.kf = false;
this._mdf = false;
var pathData = type === 3 ? data.pt.k : data.ks.k;
this.v = shape_pool.clone(pathData);
this.pv = shape_pool.clone(this.v);
this.localShapeCollection = shapeCollection_pool.newShapeCollection();
this.paths = this.localShapeCollection;
this.paths.addShape(this.v);
this.reset = resetShape;
this.effectsSequence = [];
}
function addEffect(effectFunction) {
this.effectsSequence.push(effectFunction);
this.container.addDynamicProperty(this);
}
ShapeProperty.prototype.interpolateShape = interpolateShape;
ShapeProperty.prototype.getValue = processEffectsSequence;
ShapeProperty.prototype.getValue = processEffectsSequence;
ShapeProperty.prototype.addEffect = addEffect;
function KeyframedShapeProperty(elem,data,type){
this.propType = 'shape';
this.comp = elem.comp;
this.elem = elem;
this.container = elem;
this.offsetTime = elem.data.st;
this.keyframes = type === 3 ? data.pt.k : data.ks.k;
this.k = true;
this.kf = true;
var i, len = this.keyframes[0].s[0].i.length;
var jLen = this.keyframes[0].s[0].i[0].length;
this.v = shape_pool.newElement();
this.v.setPathData(this.keyframes[0].s[0].c, len);
this.pv = shape_pool.clone(this.v);
this.localShapeCollection = shapeCollection_pool.newShapeCollection();
this.paths = this.localShapeCollection;
this.paths.addShape(this.v);
this.lastFrame = initFrame;
this.reset = resetShape;
this._caching = {lastFrame: initFrame, lastIndex: 0};
this.effectsSequence = [interpolateShapeCurrentTime.bind(this)];
}
KeyframedShapeProperty.prototype.getValue = processEffectsSequence;
KeyframedShapeProperty.prototype.interpolateShape = interpolateShape;
KeyframedShapeProperty.prototype.addEffect = addEffect;
var EllShapeProperty = (function(){
var cPoint = roundCorner;
function EllShapeProperty(elem,data) {
/*this.v = {
v: createSizedArray(4),
i: createSizedArray(4),
o: createSizedArray(4),
c: true
};*/
this.v = shape_pool.newElement();
this.v.setPathData(true, 4);
this.localShapeCollection = shapeCollection_pool.newShapeCollection();
this.paths = this.localShapeCollection;
this.localShapeCollection.addShape(this.v);
this.d = data.d;
this.elem = elem;
this.comp = elem.comp;
this.frameId = -1;
this.initDynamicPropertyContainer(elem);
this.p = PropertyFactory.getProp(elem,data.p,1,0,this);
this.s = PropertyFactory.getProp(elem,data.s,1,0,this);
if(this.dynamicProperties.length){
this.k = true;
}else{
this.k = false;
this.convertEllToPath();
}
};
EllShapeProperty.prototype = {
reset: resetShape,
getValue: function (){
if(this.elem.globalData.frameId === this.frameId){
return;
}
this.frameId = this.elem.globalData.frameId;
this.iterateDynamicProperties();
if(this._mdf){
this.convertEllToPath();
}
},
convertEllToPath: function() {
var p0 = this.p.v[0], p1 = this.p.v[1], s0 = this.s.v[0]/2, s1 = this.s.v[1]/2;
var _cw = this.d !== 3;
var _v = this.v;
_v.v[0][0] = p0;
_v.v[0][1] = p1 - s1;
_v.v[1][0] = _cw ? p0 + s0 : p0 - s0;
_v.v[1][1] = p1;
_v.v[2][0] = p0;
_v.v[2][1] = p1 + s1;
_v.v[3][0] = _cw ? p0 - s0 : p0 + s0;
_v.v[3][1] = p1;
_v.i[0][0] = _cw ? p0 - s0 * cPoint : p0 + s0 * cPoint;
_v.i[0][1] = p1 - s1;
_v.i[1][0] = _cw ? p0 + s0 : p0 - s0;
_v.i[1][1] = p1 - s1 * cPoint;
_v.i[2][0] = _cw ? p0 + s0 * cPoint : p0 - s0 * cPoint;
_v.i[2][1] = p1 + s1;
_v.i[3][0] = _cw ? p0 - s0 : p0 + s0;
_v.i[3][1] = p1 + s1 * cPoint;
_v.o[0][0] = _cw ? p0 + s0 * cPoint : p0 - s0 * cPoint;
_v.o[0][1] = p1 - s1;
_v.o[1][0] = _cw ? p0 + s0 : p0 - s0;
_v.o[1][1] = p1 + s1 * cPoint;
_v.o[2][0] = _cw ? p0 - s0 * cPoint : p0 + s0 * cPoint;
_v.o[2][1] = p1 + s1;
_v.o[3][0] = _cw ? p0 - s0 : p0 + s0;
_v.o[3][1] = p1 - s1 * cPoint;
}
}
extendPrototype([DynamicPropertyContainer], EllShapeProperty);
return EllShapeProperty;
}());
var StarShapeProperty = (function() {
function StarShapeProperty(elem,data) {
this.v = shape_pool.newElement();
this.v.setPathData(true, 0);
this.elem = elem;
this.comp = elem.comp;
this.data = data;
this.frameId = -1;
this.d = data.d;
this.initDynamicPropertyContainer(elem);
if(data.sy === 1){
this.ir = PropertyFactory.getProp(elem,data.ir,0,0,this);
this.is = PropertyFactory.getProp(elem,data.is,0,0.01,this);
this.convertToPath = this.convertStarToPath;
} else {
this.convertToPath = this.convertPolygonToPath;
}
this.pt = PropertyFactory.getProp(elem,data.pt,0,0,this);
this.p = PropertyFactory.getProp(elem,data.p,1,0,this);
this.r = PropertyFactory.getProp(elem,data.r,0,degToRads,this);
this.or = PropertyFactory.getProp(elem,data.or,0,0,this);
this.os = PropertyFactory.getProp(elem,data.os,0,0.01,this);
this.localShapeCollection = shapeCollection_pool.newShapeCollection();
this.localShapeCollection.addShape(this.v);
this.paths = this.localShapeCollection;
if(this.dynamicProperties.length){
this.k = true;
}else{
this.k = false;
this.convertToPath();
}
};
StarShapeProperty.prototype = {
reset: resetShape,
getValue: function() {
if(this.elem.globalData.frameId === this.frameId){
return;
}
this.frameId = this.elem.globalData.frameId;
this.iterateDynamicProperties();
if(this._mdf){
this.convertToPath();
}
},
convertStarToPath: function() {
var numPts = Math.floor(this.pt.v)*2;
var angle = Math.PI*2/numPts;
/*this.v.v.length = numPts;
this.v.i.length = numPts;
this.v.o.length = numPts;*/
var longFlag = true;
var longRad = this.or.v;
var shortRad = this.ir.v;
var longRound = this.os.v;
var shortRound = this.is.v;
var longPerimSegment = 2*Math.PI*longRad/(numPts*2);
var shortPerimSegment = 2*Math.PI*shortRad/(numPts*2);
var i, rad,roundness,perimSegment, currentAng = -Math.PI/ 2;
currentAng += this.r.v;
var dir = this.data.d === 3 ? -1 : 1;
this.v._length = 0;
for(i=0;i<numPts;i+=1){
rad = longFlag ? longRad : shortRad;
roundness = longFlag ? longRound : shortRound;
perimSegment = longFlag ? longPerimSegment : shortPerimSegment;
var x = rad * Math.cos(currentAng);
var y = rad * Math.sin(currentAng);
var ox = x === 0 && y === 0 ? 0 : y/Math.sqrt(x*x + y*y);
var oy = x === 0 && y === 0 ? 0 : -x/Math.sqrt(x*x + y*y);
x += + this.p.v[0];
y += + this.p.v[1];
this.v.setTripleAt(x,y,x-ox*perimSegment*roundness*dir,y-oy*perimSegment*roundness*dir,x+ox*perimSegment*roundness*dir,y+oy*perimSegment*roundness*dir, i, true);
/*this.v.v[i] = [x,y];
this.v.i[i] = [x+ox*perimSegment*roundness*dir,y+oy*perimSegment*roundness*dir];
this.v.o[i] = [x-ox*perimSegment*roundness*dir,y-oy*perimSegment*roundness*dir];
this.v._length = numPts;*/
longFlag = !longFlag;
currentAng += angle*dir;
}
},
convertPolygonToPath: function() {
var numPts = Math.floor(this.pt.v);
var angle = Math.PI*2/numPts;
var rad = this.or.v;
var roundness = this.os.v;
var perimSegment = 2*Math.PI*rad/(numPts*4);
var i, currentAng = -Math.PI/ 2;
var dir = this.data.d === 3 ? -1 : 1;
currentAng += this.r.v;
this.v._length = 0;
for(i=0;i<numPts;i+=1){
var x = rad * Math.cos(currentAng);
var y = rad * Math.sin(currentAng);
var ox = x === 0 && y === 0 ? 0 : y/Math.sqrt(x*x + y*y);
var oy = x === 0 && y === 0 ? 0 : -x/Math.sqrt(x*x + y*y);
x += + this.p.v[0];
y += + this.p.v[1];
this.v.setTripleAt(x,y,x-ox*perimSegment*roundness*dir,y-oy*perimSegment*roundness*dir,x+ox*perimSegment*roundness*dir,y+oy*perimSegment*roundness*dir, i, true);
currentAng += angle*dir;
}
this.paths.length = 0;
this.paths[0] = this.v;
}
}
extendPrototype([DynamicPropertyContainer], StarShapeProperty);
return StarShapeProperty;
}());
var RectShapeProperty = (function() {
function RectShapeProperty(elem,data) {
this.v = shape_pool.newElement();
this.v.c = true;
this.localShapeCollection = shapeCollection_pool.newShapeCollection();
this.localShapeCollection.addShape(this.v);
this.paths = this.localShapeCollection;
this.elem = elem;
this.comp = elem.comp;
this.frameId = -1;
this.d = data.d;
this.initDynamicPropertyContainer(elem);
this.p = PropertyFactory.getProp(elem,data.p,1,0,this);
this.s = PropertyFactory.getProp(elem,data.s,1,0,this);
this.r = PropertyFactory.getProp(elem,data.r,0,0,this);
if(this.dynamicProperties.length){
this.k = true;
}else{
this.k = false;
this.convertRectToPath();
}
};
RectShapeProperty.prototype = {
convertRectToPath: function (){
var p0 = this.p.v[0], p1 = this.p.v[1], v0 = this.s.v[0]/2, v1 = this.s.v[1]/2;
var round = bm_min(v0,v1,this.r.v);
var cPoint = round*(1-roundCorner);
this.v._length = 0;
if(this.d === 2 || this.d === 1) {
this.v.setTripleAt(p0+v0, p1-v1+round,p0+v0, p1-v1+round,p0+v0,p1-v1+cPoint,0, true);
this.v.setTripleAt(p0+v0, p1+v1-round,p0+v0, p1+v1-cPoint,p0+v0, p1+v1-round,1, true);
if(round!== 0){
this.v.setTripleAt(p0+v0-round, p1+v1,p0+v0-round,p1+v1,p0+v0-cPoint,p1+v1,2, true);
this.v.setTripleAt(p0-v0+round,p1+v1,p0-v0+cPoint,p1+v1,p0-v0+round,p1+v1,3, true);
this.v.setTripleAt(p0-v0,p1+v1-round,p0-v0,p1+v1-round,p0-v0,p1+v1-cPoint,4, true);
this.v.setTripleAt(p0-v0,p1-v1+round,p0-v0,p1-v1+cPoint,p0-v0,p1-v1+round,5, true);
this.v.setTripleAt(p0-v0+round,p1-v1,p0-v0+round,p1-v1,p0-v0+cPoint,p1-v1,6, true);
this.v.setTripleAt(p0+v0-round,p1-v1,p0+v0-cPoint,p1-v1,p0+v0-round,p1-v1,7, true);
} else {
this.v.setTripleAt(p0-v0,p1+v1,p0-v0+cPoint,p1+v1,p0-v0,p1+v1,2);
this.v.setTripleAt(p0-v0,p1-v1,p0-v0,p1-v1+cPoint,p0-v0,p1-v1,3);
}
}else{
this.v.setTripleAt(p0+v0,p1-v1+round,p0+v0,p1-v1+cPoint,p0+v0,p1-v1+round,0, true);
if(round!== 0){
this.v.setTripleAt(p0+v0-round,p1-v1,p0+v0-round,p1-v1,p0+v0-cPoint,p1-v1,1, true);
this.v.setTripleAt(p0-v0+round,p1-v1,p0-v0+cPoint,p1-v1,p0-v0+round,p1-v1,2, true);
this.v.setTripleAt(p0-v0,p1-v1+round,p0-v0,p1-v1+round,p0-v0,p1-v1+cPoint,3, true);
this.v.setTripleAt(p0-v0,p1+v1-round,p0-v0,p1+v1-cPoint,p0-v0,p1+v1-round,4, true);
this.v.setTripleAt(p0-v0+round,p1+v1,p0-v0+round,p1+v1,p0-v0+cPoint,p1+v1,5, true);
this.v.setTripleAt(p0+v0-round,p1+v1,p0+v0-cPoint,p1+v1,p0+v0-round,p1+v1,6, true);
this.v.setTripleAt(p0+v0,p1+v1-round,p0+v0,p1+v1-round,p0+v0,p1+v1-cPoint,7, true);
} else {
this.v.setTripleAt(p0-v0,p1-v1,p0-v0+cPoint,p1-v1,p0-v0,p1-v1,1, true);
this.v.setTripleAt(p0-v0,p1+v1,p0-v0,p1+v1-cPoint,p0-v0,p1+v1,2, true);
this.v.setTripleAt(p0+v0,p1+v1,p0+v0-cPoint,p1+v1,p0+v0,p1+v1,3, true);
}
}
},
getValue: function(frameNum){
if(this.elem.globalData.frameId === this.frameId){
return;
}
this.frameId = this.elem.globalData.frameId;
this.iterateDynamicProperties();
if(this._mdf){
this.convertRectToPath();
}
},
reset: resetShape
}
extendPrototype([DynamicPropertyContainer], RectShapeProperty);
return RectShapeProperty;
}());
function getShapeProp(elem,data,type){
var prop;
if(type === 3 || type === 4){
var dataProp = type === 3 ? data.pt : data.ks;
var keys = dataProp.k;
if(dataProp.a === 1 || keys.length){
prop = new KeyframedShapeProperty(elem, data, type);
}else{
prop = new ShapeProperty(elem, data, type);
}
}else if(type === 5){
prop = new RectShapeProperty(elem, data);
}else if(type === 6){
prop = new EllShapeProperty(elem, data);
}else if(type === 7){
prop = new StarShapeProperty(elem, data);
}
if(prop.k){
elem.addDynamicProperty(prop);
}
return prop;
}
function getConstructorFunction() {
return ShapeProperty;
}
function getKeyframedConstructorFunction() {
return KeyframedShapeProperty;
}
var ob = {};
ob.getShapeProp = getShapeProp;
ob.getConstructorFunction = getConstructorFunction;
ob.getKeyframedConstructorFunction = getKeyframedConstructorFunction;
return ob;
}());
var ShapeModifiers = (function(){
var ob = {};
var modifiers = {};
ob.registerModifier = registerModifier;
ob.getModifier = getModifier;
function registerModifier(nm,factory){
if(!modifiers[nm]){
modifiers[nm] = factory;
}
}
function getModifier(nm,elem, data){
return new modifiers[nm](elem, data);
}
return ob;
}());
function ShapeModifier(){}
ShapeModifier.prototype.initModifierProperties = function(){};
ShapeModifier.prototype.addShapeToModifier = function(){};
ShapeModifier.prototype.addShape = function(data){
if(!this.closed){
var shapeData = {shape:data.sh, data: data, localShapeCollection:shapeCollection_pool.newShapeCollection()};
this.shapes.push(shapeData);
this.addShapeToModifier(shapeData);
if(this._isAnimated) {
data.setAsAnimated();
}
}
};
ShapeModifier.prototype.init = function(elem,data){
this.shapes = [];
this.elem = elem;
this.initDynamicPropertyContainer(elem);
this.initModifierProperties(elem,data);
this.frameId = initialDefaultFrame;
this.closed = false;
this.k = false;
if(this.dynamicProperties.length){
this.k = true;
}else{
this.getValue(true);
}
};
ShapeModifier.prototype.processKeys = function(){
if(this.elem.globalData.frameId === this.frameId){
return;
}
this.frameId = this.elem.globalData.frameId;
this.iterateDynamicProperties();
};
extendPrototype([DynamicPropertyContainer], ShapeModifier);
function TrimModifier(){
}
extendPrototype([ShapeModifier], TrimModifier);
TrimModifier.prototype.initModifierProperties = function(elem, data) {
this.s = PropertyFactory.getProp(elem, data.s, 0, 0.01, this);
this.e = PropertyFactory.getProp(elem, data.e, 0, 0.01, this);
this.o = PropertyFactory.getProp(elem, data.o, 0, 0, this);
this.sValue = 0;
this.eValue = 0;
this.getValue = this.processKeys;
this.m = data.m;
this._isAnimated = !!this.s.effectsSequence.length || !!this.e.effectsSequence.length || !!this.o.effectsSequence.length;
};
TrimModifier.prototype.addShapeToModifier = function(shapeData){
shapeData.pathsData = [];
};
TrimModifier.prototype.calculateShapeEdges = function(s, e, shapeLength, addedLength, totalModifierLength) {
var segments = [];
if (e <= 1) {
segments.push({
s: s,
e: e
});
} else if (s >= 1) {
segments.push({
s: s - 1,
e: e - 1
});
} else {
segments.push({
s: s,
e: 1
});
segments.push({
s: 0,
e: e - 1
});
}
var shapeSegments = [];
var i, len = segments.length, segmentOb;
for (i = 0; i < len; i += 1) {
segmentOb = segments[i];
if (segmentOb.e * totalModifierLength < addedLength || segmentOb.s * totalModifierLength > addedLength + shapeLength) {
} else {
var shapeS, shapeE;
if (segmentOb.s * totalModifierLength <= addedLength) {
shapeS = 0;
} else {
shapeS = (segmentOb.s * totalModifierLength - addedLength) / shapeLength;
}
if(segmentOb.e * totalModifierLength >= addedLength + shapeLength) {
shapeE = 1;
} else {
shapeE = ((segmentOb.e * totalModifierLength - addedLength) / shapeLength);
}
shapeSegments.push([shapeS, shapeE]);
}
}
if (!shapeSegments.length) {
shapeSegments.push([0, 0]);
}
return shapeSegments;
};
TrimModifier.prototype.releasePathsData = function(pathsData) {
var i, len = pathsData.length;
for (i = 0; i < len; i += 1) {
segments_length_pool.release(pathsData[i]);
}
pathsData.length = 0;
return pathsData;
};
TrimModifier.prototype.processShapes = function(_isFirstFrame) {
var s, e;
if (this._mdf || _isFirstFrame) {
var o = (this.o.v % 360) / 360;
if (o < 0) {
o += 1;
}
s = this.s.v + o;
e = this.e.v + o;
if (s === e) {
}
if (s > e) {
var _s = s;
s = e;
e = _s;
}
s = Math.round(s*1000)/1000;
e = Math.round(e*1000)/1000;
this.sValue = s;
this.eValue = e;
} else {
s = this.sValue;
e = this.eValue;
}
var shapePaths;
var i, len = this.shapes.length, j, jLen;
var pathsData, pathData, totalShapeLength, totalModifierLength = 0;
if (e === s) {
for (i = 0; i < len; i += 1) {
this.shapes[i].localShapeCollection.releaseShapes();
this.shapes[i].shape._mdf = true;
this.shapes[i].shape.paths = this.shapes[i].localShapeCollection;
}
} else if (!((e === 1 && s === 0) || (e===0 && s === 1))){
var segments = [], shapeData, localShapeCollection;
for (i = 0; i < len; i += 1) {
shapeData = this.shapes[i];
// if shape hasn't changed and trim properties haven't changed, cached previous path can be used
if (!shapeData.shape._mdf && !this._mdf && !_isFirstFrame && this.m !== 2) {
shapeData.shape.paths = shapeData.localShapeCollection;
} else {
shapePaths = shapeData.shape.paths;
jLen = shapePaths._length;
totalShapeLength = 0;
if (!shapeData.shape._mdf && shapeData.pathsData.length) {
totalShapeLength = shapeData.totalShapeLength;
} else {
pathsData = this.releasePathsData(shapeData.pathsData);
for (j = 0; j < jLen; j += 1) {
pathData = bez.getSegmentsLength(shapePaths.shapes[j]);
pathsData.push(pathData);
totalShapeLength += pathData.totalLength;
}
shapeData.totalShapeLength = totalShapeLength;
shapeData.pathsData = pathsData;
}
totalModifierLength += totalShapeLength;
shapeData.shape._mdf = true;
}
}
var shapeS = s, shapeE = e, addedLength = 0, edges;
for (i = len - 1; i >= 0; i -= 1) {
shapeData = this.shapes[i];
if (shapeData.shape._mdf) {
localShapeCollection = shapeData.localShapeCollection;
localShapeCollection.releaseShapes();
//if m === 2 means paths are trimmed individually so edges need to be found for this specific shape relative to whoel group
if (this.m === 2 && len > 1) {
edges = this.calculateShapeEdges(s, e, shapeData.totalShapeLength, addedLength, totalModifierLength);
addedLength += shapeData.totalShapeLength;
} else {
edges = [[shapeS, shapeE]];
}
jLen = edges.length;
for (j = 0; j < jLen; j += 1) {
shapeS = edges[j][0];
shapeE = edges[j][1];
segments.length = 0;
if (shapeE <= 1) {
segments.push({
s:shapeData.totalShapeLength * shapeS,
e:shapeData.totalShapeLength * shapeE
});
} else if (shapeS >= 1) {
segments.push({
s:shapeData.totalShapeLength * (shapeS - 1),
e:shapeData.totalShapeLength * (shapeE - 1)
});
} else {
segments.push({
s:shapeData.totalShapeLength * shapeS,
e:shapeData.totalShapeLength
});
segments.push({
s:0,
e:shapeData.totalShapeLength * (shapeE - 1)
});
}
var newShapesData = this.addShapes(shapeData,segments[0]);
if (segments[0].s !== segments[0].e) {
if (segments.length > 1) {
if (shapeData.shape.v.c) {
var lastShape = newShapesData.pop();
this.addPaths(newShapesData, localShapeCollection);
newShapesData = this.addShapes(shapeData, segments[1], lastShape);
} else {
this.addPaths(newShapesData, localShapeCollection);
newShapesData = this.addShapes(shapeData, segments[1]);
}
}
this.addPaths(newShapesData, localShapeCollection);
}
}
shapeData.shape.paths = localShapeCollection;
}
}
} else if (this._mdf) {
for (i = 0; i < len; i += 1) {
this.shapes[i].shape._mdf = true;
}
}
};
TrimModifier.prototype.addPaths = function(newPaths, localShapeCollection) {
var i, len = newPaths.length;
for (i = 0; i < len; i += 1) {
localShapeCollection.addShape(newPaths[i]);
}
};
TrimModifier.prototype.addSegment = function(pt1, pt2, pt3, pt4, shapePath, pos, newShape) {
shapePath.setXYAt(pt2[0], pt2[1], 'o', pos);
shapePath.setXYAt(pt3[0], pt3[1], 'i', pos + 1);
if(newShape){
shapePath.setXYAt(pt1[0], pt1[1], 'v', pos);
}
shapePath.setXYAt(pt4[0], pt4[1], 'v', pos + 1);
};
TrimModifier.prototype.addSegmentFromArray = function(points, shapePath, pos, newShape) {
shapePath.setXYAt(points[1], points[5], 'o', pos);
shapePath.setXYAt(points[2], points[6], 'i', pos + 1);
if(newShape){
shapePath.setXYAt(points[0], points[4], 'v', pos);
}
shapePath.setXYAt(points[3], points[7], 'v', pos + 1);
};
TrimModifier.prototype.addShapes = function(shapeData, shapeSegment, shapePath) {
var pathsData = shapeData.pathsData;
var shapePaths = shapeData.shape.paths.shapes;
var i, len = shapeData.shape.paths._length, j, jLen;
var addedLength = 0;
var currentLengthData,segmentCount;
var lengths;
var segment;
var shapes = [];
var initPos;
var newShape = true;
if (!shapePath) {
shapePath = shape_pool.newElement();
segmentCount = 0;
initPos = 0;
} else {
segmentCount = shapePath._length;
initPos = shapePath._length;
}
shapes.push(shapePath);
for (i = 0; i < len; i += 1) {
lengths = pathsData[i].lengths;
shapePath.c = shapePaths[i].c;
jLen = shapePaths[i].c ? lengths.length : lengths.length + 1;
for (j = 1; j < jLen; j +=1) {
currentLengthData = lengths[j-1];
if (addedLength + currentLengthData.addedLength < shapeSegment.s) {
addedLength += currentLengthData.addedLength;
shapePath.c = false;
} else if(addedLength > shapeSegment.e) {
shapePath.c = false;
break;
} else {
if (shapeSegment.s <= addedLength && shapeSegment.e >= addedLength + currentLengthData.addedLength) {
this.addSegment(shapePaths[i].v[j - 1], shapePaths[i].o[j - 1], shapePaths[i].i[j], shapePaths[i].v[j], shapePath, segmentCount, newShape);
newShape = false;
} else {
segment = bez.getNewSegment(shapePaths[i].v[j - 1], shapePaths[i].v[j], shapePaths[i].o[j - 1], shapePaths[i].i[j], (shapeSegment.s - addedLength)/currentLengthData.addedLength,(shapeSegment.e - addedLength)/currentLengthData.addedLength, lengths[j-1]);
this.addSegmentFromArray(segment, shapePath, segmentCount, newShape);
// this.addSegment(segment.pt1, segment.pt3, segment.pt4, segment.pt2, shapePath, segmentCount, newShape);
newShape = false;
shapePath.c = false;
}
addedLength += currentLengthData.addedLength;
segmentCount += 1;
}
}
if (shapePaths[i].c) {
currentLengthData = lengths[j - 1];
if (addedLength <= shapeSegment.e) {
var segmentLength = lengths[j - 1].addedLength;
if (shapeSegment.s <= addedLength && shapeSegment.e >= addedLength + segmentLength) {
this.addSegment(shapePaths[i].v[j - 1], shapePaths[i].o[j - 1], shapePaths[i].i[0], shapePaths[i].v[0], shapePath, segmentCount, newShape);
newShape = false;
} else {
segment = bez.getNewSegment(shapePaths[i].v[j - 1], shapePaths[i].v[0], shapePaths[i].o[j - 1], shapePaths[i].i[0], (shapeSegment.s - addedLength) / segmentLength, (shapeSegment.e - addedLength) / segmentLength, lengths[j - 1]);
this.addSegmentFromArray(segment, shapePath, segmentCount, newShape);
// this.addSegment(segment.pt1, segment.pt3, segment.pt4, segment.pt2, shapePath, segmentCount, newShape);
newShape = false;
shapePath.c = false;
}
} else {
shapePath.c = false;
}
addedLength += currentLengthData.addedLength;
segmentCount += 1;
}
if (shapePath._length) {
shapePath.setXYAt(shapePath.v[initPos][0], shapePath.v[initPos][1], 'i', initPos);
shapePath.setXYAt(shapePath.v[shapePath._length - 1][0], shapePath.v[shapePath._length - 1][1],'o', shapePath._length - 1);
}
if (addedLength > shapeSegment.e) {
break;
}
if (i < len - 1) {
shapePath = shape_pool.newElement();
newShape = true;
shapes.push(shapePath);
segmentCount = 0;
}
}
return shapes;
};
ShapeModifiers.registerModifier('tm', TrimModifier);
function RoundCornersModifier(){}
extendPrototype([ShapeModifier],RoundCornersModifier);
RoundCornersModifier.prototype.initModifierProperties = function(elem,data){
this.getValue = this.processKeys;
this.rd = PropertyFactory.getProp(elem,data.r,0,null,this);
this._isAnimated = !!this.rd.effectsSequence.length;
};
RoundCornersModifier.prototype.processPath = function(path, round){
var cloned_path = shape_pool.newElement();
cloned_path.c = path.c;
var i, len = path._length;
var currentV,currentI,currentO,closerV, newV,newO,newI,distance,newPosPerc,index = 0;
var vX,vY,oX,oY,iX,iY;
for(i=0;i<len;i+=1){
currentV = path.v[i];
currentO = path.o[i];
currentI = path.i[i];
if(currentV[0]===currentO[0] && currentV[1]===currentO[1] && currentV[0]===currentI[0] && currentV[1]===currentI[1]){
if((i===0 || i === len - 1) && !path.c){
cloned_path.setTripleAt(currentV[0],currentV[1],currentO[0],currentO[1],currentI[0],currentI[1],index);
/*cloned_path.v[index] = currentV;
cloned_path.o[index] = currentO;
cloned_path.i[index] = currentI;*/
index += 1;
} else {
if(i===0){
closerV = path.v[len-1];
} else {
closerV = path.v[i-1];
}
distance = Math.sqrt(Math.pow(currentV[0]-closerV[0],2)+Math.pow(currentV[1]-closerV[1],2));
newPosPerc = distance ? Math.min(distance/2,round)/distance : 0;
vX = iX = currentV[0]+(closerV[0]-currentV[0])*newPosPerc;
vY = iY = currentV[1]-(currentV[1]-closerV[1])*newPosPerc;
oX = vX-(vX-currentV[0])*roundCorner;
oY = vY-(vY-currentV[1])*roundCorner;
cloned_path.setTripleAt(vX,vY,oX,oY,iX,iY,index);
index += 1;
if(i === len - 1){
closerV = path.v[0];
} else {
closerV = path.v[i+1];
}
distance = Math.sqrt(Math.pow(currentV[0]-closerV[0],2)+Math.pow(currentV[1]-closerV[1],2));
newPosPerc = distance ? Math.min(distance/2,round)/distance : 0;
vX = oX = currentV[0]+(closerV[0]-currentV[0])*newPosPerc;
vY = oY = currentV[1]+(closerV[1]-currentV[1])*newPosPerc;
iX = vX-(vX-currentV[0])*roundCorner;
iY = vY-(vY-currentV[1])*roundCorner;
cloned_path.setTripleAt(vX,vY,oX,oY,iX,iY,index);
index += 1;
}
} else {
cloned_path.setTripleAt(path.v[i][0],path.v[i][1],path.o[i][0],path.o[i][1],path.i[i][0],path.i[i][1],index);
index += 1;
}
}
return cloned_path;
};
RoundCornersModifier.prototype.processShapes = function(_isFirstFrame){
var shapePaths;
var i, len = this.shapes.length;
var j, jLen;
var rd = this.rd.v;
if(rd !== 0){
var shapeData, newPaths, localShapeCollection;
for(i=0;i<len;i+=1){
shapeData = this.shapes[i];
newPaths = shapeData.shape.paths;
localShapeCollection = shapeData.localShapeCollection;
if(!(!shapeData.shape._mdf && !this._mdf && !_isFirstFrame)){
localShapeCollection.releaseShapes();
shapeData.shape._mdf = true;
shapePaths = shapeData.shape.paths.shapes;
jLen = shapeData.shape.paths._length;
for(j=0;j<jLen;j+=1){
localShapeCollection.addShape(this.processPath(shapePaths[j],rd));
}
}
shapeData.shape.paths = shapeData.localShapeCollection;
}
}
if(!this.dynamicProperties.length){
this._mdf = false;
}
};
ShapeModifiers.registerModifier('rd',RoundCornersModifier);
function RepeaterModifier(){}
extendPrototype([ShapeModifier], RepeaterModifier);
RepeaterModifier.prototype.initModifierProperties = function(elem,data){
this.getValue = this.processKeys;
this.c = PropertyFactory.getProp(elem,data.c,0,null,this);
this.o = PropertyFactory.getProp(elem,data.o,0,null,this);
this.tr = TransformPropertyFactory.getTransformProperty(elem,data.tr,this);
this.data = data;
if(!this.dynamicProperties.length){
this.getValue(true);
}
this._isAnimated = !!this.dynamicProperties.length;
this.pMatrix = new Matrix();
this.rMatrix = new Matrix();
this.sMatrix = new Matrix();
this.tMatrix = new Matrix();
this.matrix = new Matrix();
};
RepeaterModifier.prototype.applyTransforms = function(pMatrix, rMatrix, sMatrix, transform, perc, inv){
var dir = inv ? -1 : 1;
var scaleX = transform.s.v[0] + (1 - transform.s.v[0]) * (1 - perc);
var scaleY = transform.s.v[1] + (1 - transform.s.v[1]) * (1 - perc);
pMatrix.translate(transform.p.v[0] * dir * perc, transform.p.v[1] * dir * perc, transform.p.v[2]);
rMatrix.translate(-transform.a.v[0], -transform.a.v[1], transform.a.v[2]);
rMatrix.rotate(-transform.r.v * dir * perc);
rMatrix.translate(transform.a.v[0], transform.a.v[1], transform.a.v[2]);
sMatrix.translate(-transform.a.v[0], -transform.a.v[1], transform.a.v[2]);
sMatrix.scale(inv ? 1/scaleX : scaleX, inv ? 1/scaleY : scaleY);
sMatrix.translate(transform.a.v[0], transform.a.v[1], transform.a.v[2]);
};
RepeaterModifier.prototype.init = function(elem, arr, pos, elemsData) {
this.elem = elem;
this.arr = arr;
this.pos = pos;
this.elemsData = elemsData;
this._currentCopies = 0;
this._elements = [];
this._groups = [];
this.frameId = -1;
this.initDynamicPropertyContainer(elem);
this.initModifierProperties(elem,arr[pos]);
var cont = 0;
while(pos>0){
pos -= 1;
//this._elements.unshift(arr.splice(pos,1)[0]);
this._elements.unshift(arr[pos]);
cont += 1;
}
if(this.dynamicProperties.length){
this.k = true;
}else{
this.getValue(true);
}
};
RepeaterModifier.prototype.resetElements = function(elements){
var i, len = elements.length;
for(i = 0; i < len; i += 1) {
elements[i]._processed = false;
if(elements[i].ty === 'gr'){
this.resetElements(elements[i].it);
}
}
};
RepeaterModifier.prototype.cloneElements = function(elements){
var i, len = elements.length;
var newElements = JSON.parse(JSON.stringify(elements));
this.resetElements(newElements);
return newElements;
};
RepeaterModifier.prototype.changeGroupRender = function(elements, renderFlag) {
var i, len = elements.length;
for(i = 0; i < len ; i += 1) {
elements[i]._render = renderFlag;
if(elements[i].ty === 'gr') {
this.changeGroupRender(elements[i].it, renderFlag);
}
}
};
RepeaterModifier.prototype.processShapes = function(_isFirstFrame) {
var items, itemsTransform, i, dir, cont;
if(this._mdf || _isFirstFrame){
var copies = Math.ceil(this.c.v);
if(this._groups.length < copies){
while(this._groups.length < copies){
var group = {
it:this.cloneElements(this._elements),
ty:'gr'
};
group.it.push({"a":{"a":0,"ix":1,"k":[0,0]},"nm":"Transform","o":{"a":0,"ix":7,"k":100},"p":{"a":0,"ix":2,"k":[0,0]},"r":{"a":1,"ix":6,"k":[{s:0,e:0,t:0},{s:0,e:0,t:1}]},"s":{"a":0,"ix":3,"k":[100,100]},"sa":{"a":0,"ix":5,"k":0},"sk":{"a":0,"ix":4,"k":0},"ty":"tr"});
this.arr.splice(0,0,group);
this._groups.splice(0,0,group);
this._currentCopies += 1;
}
this.elem.reloadShapes();
}
cont = 0;
var renderFlag;
for(i = 0; i <= this._groups.length - 1; i += 1){
renderFlag = cont < copies;
this._groups[i]._render = renderFlag;
this.changeGroupRender(this._groups[i].it, renderFlag);
cont += 1;
}
this._currentCopies = copies;
////
var offset = this.o.v;
var offsetModulo = offset%1;
var roundOffset = offset > 0 ? Math.floor(offset) : Math.ceil(offset);
var k;
var tMat = this.tr.v.props;
var pProps = this.pMatrix.props;
var rProps = this.rMatrix.props;
var sProps = this.sMatrix.props;
this.pMatrix.reset();
this.rMatrix.reset();
this.sMatrix.reset();
this.tMatrix.reset();
this.matrix.reset();
var iteration = 0;
if(offset > 0) {
while(iteration<roundOffset){
this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, 1, false);
iteration += 1;
}
if(offsetModulo){
this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, offsetModulo, false);
iteration += offsetModulo;
}
} else if(offset < 0) {
while(iteration>roundOffset){
this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, 1, true);
iteration -= 1;
}
if(offsetModulo){
this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, - offsetModulo, true);
iteration -= offsetModulo;
}
}
i = this.data.m === 1 ? 0 : this._currentCopies - 1;
dir = this.data.m === 1 ? 1 : -1;
cont = this._currentCopies;
var j, jLen;
while(cont){
items = this.elemsData[i].it;
itemsTransform = items[items.length - 1].transform.mProps.v.props;
jLen = itemsTransform.length;
items[items.length - 1].transform.mProps._mdf = true;
items[items.length - 1].transform.op._mdf = true;
if(iteration !== 0){
if((i !== 0 && dir === 1) || (i !== this._currentCopies - 1 && dir === -1)){
this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, 1, false);
}
this.matrix.transform(rProps[0],rProps[1],rProps[2],rProps[3],rProps[4],rProps[5],rProps[6],rProps[7],rProps[8],rProps[9],rProps[10],rProps[11],rProps[12],rProps[13],rProps[14],rProps[15]);
this.matrix.transform(sProps[0],sProps[1],sProps[2],sProps[3],sProps[4],sProps[5],sProps[6],sProps[7],sProps[8],sProps[9],sProps[10],sProps[11],sProps[12],sProps[13],sProps[14],sProps[15]);
this.matrix.transform(pProps[0],pProps[1],pProps[2],pProps[3],pProps[4],pProps[5],pProps[6],pProps[7],pProps[8],pProps[9],pProps[10],pProps[11],pProps[12],pProps[13],pProps[14],pProps[15]);
for(j=0;j<jLen;j+=1) {
itemsTransform[j] = this.matrix.props[j];
}
this.matrix.reset();
} else {
this.matrix.reset();
for(j=0;j<jLen;j+=1) {
itemsTransform[j] = this.matrix.props[j];
}
}
iteration += 1;
cont -= 1;
i += dir;
}
} else {
cont = this._currentCopies;
i = 0;
dir = 1;
while(cont){
items = this.elemsData[i].it;
itemsTransform = items[items.length - 1].transform.mProps.v.props;
items[items.length - 1].transform.mProps._mdf = false;
items[items.length - 1].transform.op._mdf = false;
cont -= 1;
i += dir;
}
}
};
RepeaterModifier.prototype.addShape = function(){};
ShapeModifiers.registerModifier('rp',RepeaterModifier);
function ShapeCollection(){
this._length = 0;
this._maxLength = 4;
this.shapes = createSizedArray(this._maxLength);
}
ShapeCollection.prototype.addShape = function(shapeData){
if(this._length === this._maxLength){
this.shapes = this.shapes.concat(createSizedArray(this._maxLength));
this._maxLength *= 2;
}
this.shapes[this._length] = shapeData;
this._length += 1;
};
ShapeCollection.prototype.releaseShapes = function(){
var i;
for(i = 0; i < this._length; i += 1) {
shape_pool.release(this.shapes[i]);
}
this._length = 0;
};
function DashProperty(elem, data, renderer) {
this.elem = elem;
this.frameId = -1;
this.dataProps = createSizedArray(data.length);
this.renderer = renderer;
this.k = false;
this.dashStr = '';
this.dashArray = createTypedArray('float32', data.length ? data.length - 1 : 0);
this.dashoffset = createTypedArray('float32', 1);
this.initDynamicPropertyContainer(elem);
var i, len = data.length || 0, prop;
for(i = 0; i < len; i += 1) {
prop = PropertyFactory.getProp(elem,data[i].v,0, 0, this);
this.k = prop.k || this.k;
this.dataProps[i] = {n:data[i].n,p:prop};
}
if(!this.k){
this.getValue(true);
}
this._isAnimated = this.k;
}
DashProperty.prototype.getValue = function(forceRender) {
if(this.elem.globalData.frameId === this.frameId && !forceRender){
return;
}
this.frameId = this.elem.globalData.frameId;
this.iterateDynamicProperties();
this._mdf = this._mdf || forceRender;
if (this._mdf) {
var i = 0, len = this.dataProps.length;
if(this.renderer === 'svg') {
this.dashStr = '';
}
for(i=0;i<len;i+=1){
if(this.dataProps[i].n != 'o'){
if(this.renderer === 'svg') {
this.dashStr += ' ' + this.dataProps[i].p.v;
}else{
this.dashArray[i] = this.dataProps[i].p.v;
}
}else{
this.dashoffset[0] = this.dataProps[i].p.v;
}
}
}
};
extendPrototype([DynamicPropertyContainer], DashProperty);
function GradientProperty(elem,data){
this.data = data;
this.c = createTypedArray('uint8c', data.p*4);
var cLength = data.k.k[0].s ? (data.k.k[0].s.length - data.p*4) : data.k.k.length - data.p*4;
this.o = createTypedArray('float32', cLength);
this._cmdf = false;
this._omdf = false;
this._collapsable = this.checkCollapsable();
this._hasOpacity = cLength;
this.initDynamicPropertyContainer(elem);
this.prop = PropertyFactory.getProp(elem,data.k,1,null,this);
this.k = this.prop.k;
this.getValue(true);
}
GradientProperty.prototype.comparePoints = function(values, points) {
var i = 0, len = this.o.length/2, diff;
while(i < len) {
diff = Math.abs(values[i*4] - values[points*4 + i*2]);
if(diff > 0.01){
return false;
}
i += 1;
}
return true;
};
GradientProperty.prototype.checkCollapsable = function() {
if (this.o.length/2 !== this.c.length/4) {
return false;
}
if (this.data.k.k[0].s) {
var i = 0, len = this.data.k.k.length;
while (i < len) {
if (!this.comparePoints(this.data.k.k[i].s, this.data.p)) {
return false;
}
i += 1;
}
} else if(!this.comparePoints(this.data.k.k, this.data.p)) {
return false;
}
return true;
};
GradientProperty.prototype.getValue = function(forceRender){
this.prop.getValue();
this._mdf = false;
this._cmdf = false;
this._omdf = false;
if(this.prop._mdf || forceRender){
var i, len = this.data.p*4;
var mult, val;
for(i=0;i<len;i+=1){
mult = i%4 === 0 ? 100 : 255;
val = Math.round(this.prop.v[i]*mult);
if(this.c[i] !== val){
this.c[i] = val;
this._cmdf = !forceRender;
}
}
if(this.o.length){
len = this.prop.v.length;
for(i=this.data.p*4;i<len;i+=1){
mult = i%2 === 0 ? 100 : 1;
val = i%2 === 0 ? Math.round(this.prop.v[i]*100):this.prop.v[i];
if(this.o[i-this.data.p*4] !== val){
this.o[i-this.data.p*4] = val;
this._omdf = !forceRender;
}
}
}
this._mdf = !forceRender;
}
};
extendPrototype([DynamicPropertyContainer], GradientProperty);
var buildShapeString = function(pathNodes, length, closed, mat) {
if(length === 0) {
return '';
}
var _o = pathNodes.o;
var _i = pathNodes.i;
var _v = pathNodes.v;
var i, shapeString = " M" + mat.applyToPointStringified(_v[0][0], _v[0][1]);
for(i = 1; i < length; i += 1) {
shapeString += " C" + mat.applyToPointStringified(_o[i - 1][0], _o[i - 1][1]) + " " + mat.applyToPointStringified(_i[i][0], _i[i][1]) + " " + mat.applyToPointStringified(_v[i][0], _v[i][1]);
}
if (closed && length) {
shapeString += " C" + mat.applyToPointStringified(_o[i - 1][0], _o[i - 1][1]) + " " + mat.applyToPointStringified(_i[0][0], _i[0][1]) + " " + mat.applyToPointStringified(_v[0][0], _v[0][1]);
shapeString += 'z';
}
return shapeString;
}
var ImagePreloader = (function(){
function imageLoaded(){
this.loadedAssets += 1;
if(this.loadedAssets === this.totalImages){
if(this.imagesLoadedCb) {
this.imagesLoadedCb(null);
}
}
}
function getAssetsPath(assetData){
var path = '';
if(this.assetsPath){
var imagePath = assetData.p;
if(imagePath.indexOf('images/') !== -1){
imagePath = imagePath.split('/')[1];
}
path = this.assetsPath + imagePath;
} else {
path = this.path;
path += assetData.u ? assetData.u : '';
path += assetData.p;
}
return path;
}
function loadImage(path){
var img = createTag('img');
img.addEventListener('load', imageLoaded.bind(this), false);
img.addEventListener('error', imageLoaded.bind(this), false);
img.src = path;
}
function loadAssets(assets, cb){
this.imagesLoadedCb = cb;
this.totalAssets = assets.length;
var i;
for(i=0;i<this.totalAssets;i+=1){
if(!assets[i].layers){
loadImage.bind(this)(getAssetsPath.bind(this)(assets[i]));
this.totalImages += 1;
}
}
}
function setPath(path){
this.path = path || '';
}
function setAssetsPath(path){
this.assetsPath = path || '';
}
function destroy() {
this.imagesLoadedCb = null;
}
return function ImagePreloader(){
this.loadAssets = loadAssets;
this.setAssetsPath = setAssetsPath;
this.setPath = setPath;
this.destroy = destroy;
this.assetsPath = '';
this.path = '';
this.totalAssets = 0;
this.totalImages = 0;
this.loadedAssets = 0;
this.imagesLoadedCb = null;
};
}());
var featureSupport = (function(){
var ob = {
maskType: true
};
if (/MSIE 10/i.test(navigator.userAgent) || /MSIE 9/i.test(navigator.userAgent) || /rv:11.0/i.test(navigator.userAgent) || /Edge\/\d./i.test(navigator.userAgent)) {
ob.maskType = false;
}
return ob;
}());
var filtersFactory = (function(){
var ob = {};
ob.createFilter = createFilter;
ob.createAlphaToLuminanceFilter = createAlphaToLuminanceFilter;
function createFilter(filId){
var fil = createNS('filter');
fil.setAttribute('id',filId);
fil.setAttribute('filterUnits','objectBoundingBox');
fil.setAttribute('x','0%');
fil.setAttribute('y','0%');
fil.setAttribute('width','100%');
fil.setAttribute('height','100%');
return fil;
}
function createAlphaToLuminanceFilter(){
var feColorMatrix = createNS('feColorMatrix');
feColorMatrix.setAttribute('type','matrix');
feColorMatrix.setAttribute('color-interpolation-filters','sRGB');
feColorMatrix.setAttribute('values','0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 1');
return feColorMatrix;
}
return ob;
}());
function TextAnimatorProperty(textData, renderType, elem){
this._isFirstFrame = true;
this._hasMaskedPath = false;
this._frameId = -1;
this._textData = textData;
this._renderType = renderType;
this._elem = elem;
this._animatorsData = createSizedArray(this._textData.a.length);
this._pathData = {};
this._moreOptions = {
alignment: {}
};
this.renderedLetters = [];
this.lettersChangedFlag = false;
this.initDynamicPropertyContainer(elem);
}
TextAnimatorProperty.prototype.searchProperties = function(){
var i, len = this._textData.a.length, animatorProps;
var getProp = PropertyFactory.getProp;
for(i=0;i<len;i+=1){
animatorProps = this._textData.a[i];
this._animatorsData[i] = new TextAnimatorDataProperty(this._elem, animatorProps, this);
}
if(this._textData.p && 'm' in this._textData.p){
this._pathData = {
f: getProp(this._elem,this._textData.p.f,0,0,this),
l: getProp(this._elem,this._textData.p.l,0,0,this),
r: this._textData.p.r,
m: this._elem.maskManager.getMaskProperty(this._textData.p.m)
};
this._hasMaskedPath = true;
} else {
this._hasMaskedPath = false;
}
this._moreOptions.alignment = getProp(this._elem,this._textData.m.a,1,0,this);
};
TextAnimatorProperty.prototype.getMeasures = function(documentData, lettersChangedFlag){
this.lettersChangedFlag = lettersChangedFlag;
if(!this._mdf && !this._isFirstFrame && !lettersChangedFlag && (!this._hasMaskedPath || !this._pathData.m._mdf)) {
return;
}
this._isFirstFrame = false;
var alignment = this._moreOptions.alignment.v;
var animators = this._animatorsData;
var textData = this._textData;
var matrixHelper = this.mHelper;
var renderType = this._renderType;
var renderedLettersCount = this.renderedLetters.length;
var data = this.data;
var xPos,yPos;
var i, len;
var letters = documentData.l, pathInfo, currentLength, currentPoint, segmentLength, flag, pointInd, segmentInd, prevPoint, points, segments, partialLength, totalLength, perc, tanAngle, mask;
if(this._hasMaskedPath) {
mask = this._pathData.m;
if(!this._pathData.n || this._pathData._mdf){
var paths = mask.v;
if(this._pathData.r){
paths = paths.reverse();
}
// TODO: release bezier data cached from previous pathInfo: this._pathData.pi
pathInfo = {
tLength: 0,
segments: []
};
len = paths._length - 1;
var pathData;
totalLength = 0;
for (i = 0; i < len; i += 1) {
pathData = {
s: paths.v[i],
e: paths.v[i + 1],
to: [paths.o[i][0] - paths.v[i][0], paths.o[i][1] - paths.v[i][1]],
ti: [paths.i[i + 1][0] - paths.v[i + 1][0], paths.i[i + 1][1] - paths.v[i + 1][1]]
};
bez.buildBezierData(pathData);
pathInfo.tLength += pathData.bezierData.segmentLength;
pathInfo.segments.push(pathData);
totalLength += pathData.bezierData.segmentLength;
}
i = len;
if (mask.v.c) {
pathData = {
s: paths.v[i],
e: paths.v[0],
to: [paths.o[i][0] - paths.v[i][0], paths.o[i][1] - paths.v[i][1]],
ti: [paths.i[0][0] - paths.v[0][0], paths.i[0][1] - paths.v[0][1]]
};
bez.buildBezierData(pathData);
pathInfo.tLength += pathData.bezierData.segmentLength;
pathInfo.segments.push(pathData);
totalLength += pathData.bezierData.segmentLength;
}
this._pathData.pi = pathInfo;
}
pathInfo = this._pathData.pi;
currentLength = this._pathData.f.v;
segmentInd = 0;
pointInd = 1;
segmentLength = 0;
flag = true;
segments = pathInfo.segments;
if (currentLength < 0 && mask.v.c) {
if (pathInfo.tLength < Math.abs(currentLength)) {
currentLength = -Math.abs(currentLength) % pathInfo.tLength;
}
segmentInd = segments.length - 1;
points = segments[segmentInd].bezierData.points;
pointInd = points.length - 1;
while (currentLength < 0) {
currentLength += points[pointInd].partialLength;
pointInd -= 1;
if (pointInd < 0) {
segmentInd -= 1;
points = segments[segmentInd].bezierData.points;
pointInd = points.length - 1;
}
}
}
points = segments[segmentInd].bezierData.points;
prevPoint = points[pointInd - 1];
currentPoint = points[pointInd];
partialLength = currentPoint.partialLength;
}
len = letters.length;
xPos = 0;
yPos = 0;
var yOff = documentData.finalSize * 1.2 * 0.714;
var firstLine = true;
var animatorProps, animatorSelector;
var j, jLen;
var letterValue;
jLen = animators.length;
var lastLetter;
var mult, ind = -1, offf, xPathPos, yPathPos;
var initPathPos = currentLength,initSegmentInd = segmentInd, initPointInd = pointInd, currentLine = -1;
var elemOpacity;
var sc,sw,fc,k;
var lineLength = 0;
var letterSw, letterSc, letterFc, letterM = '', letterP = this.defaultPropsArray, letterO;
//
if(documentData.j === 2 || documentData.j === 1) {
var animatorJustifyOffset = 0;
var animatorFirstCharOffset = 0;
var justifyOffsetMult = documentData.j === 2 ? -0.5 : -1;
var lastIndex = 0;
var isNewLine = true;
for (i = 0; i < len; i += 1) {
if (letters[i].n) {
if(animatorJustifyOffset) {
animatorJustifyOffset += animatorFirstCharOffset;
}
while (lastIndex < i) {
letters[lastIndex].animatorJustifyOffset = animatorJustifyOffset;
lastIndex += 1;
}
animatorJustifyOffset = 0;
isNewLine = true;
} else {
for (j = 0; j < jLen; j += 1) {
animatorProps = animators[j].a;
if (animatorProps.t.propType) {
if (isNewLine && documentData.j === 2) {
animatorFirstCharOffset += animatorProps.t.v * justifyOffsetMult;
}
animatorSelector = animators[j].s;
mult = animatorSelector.getMult(letters[i].anIndexes[j], textData.a[j].s.totalChars);
if (mult.length) {
animatorJustifyOffset += animatorProps.t.v*mult[0] * justifyOffsetMult;
} else {
animatorJustifyOffset += animatorProps.t.v*mult * justifyOffsetMult;
}
}
}
isNewLine = false;
}
}
if(animatorJustifyOffset) {
animatorJustifyOffset += animatorFirstCharOffset;
}
while(lastIndex < i) {
letters[lastIndex].animatorJustifyOffset = animatorJustifyOffset;
lastIndex += 1;
}
}
//
for( i = 0; i < len; i += 1) {
matrixHelper.reset();
elemOpacity = 1;
if(letters[i].n) {
xPos = 0;
yPos += documentData.yOffset;
yPos += firstLine ? 1 : 0;
currentLength = initPathPos ;
firstLine = false;
lineLength = 0;
if(this._hasMaskedPath) {
segmentInd = initSegmentInd;
pointInd = initPointInd;
points = segments[segmentInd].bezierData.points;
prevPoint = points[pointInd - 1];
currentPoint = points[pointInd];
partialLength = currentPoint.partialLength;
segmentLength = 0;
}
letterO = letterSw = letterFc = letterM = '';
letterP = this.defaultPropsArray;
}else{
if(this._hasMaskedPath) {
if(currentLine !== letters[i].line){
switch(documentData.j){
case 1:
currentLength += totalLength - documentData.lineWidths[letters[i].line];
break;
case 2:
currentLength += (totalLength - documentData.lineWidths[letters[i].line])/2;
break;
}
currentLine = letters[i].line;
}
if (ind !== letters[i].ind) {
if (letters[ind]) {
currentLength += letters[ind].extra;
}
currentLength += letters[i].an / 2;
ind = letters[i].ind;
}
currentLength += alignment[0] * letters[i].an / 200;
var animatorOffset = 0;
for (j = 0; j < jLen; j += 1) {
animatorProps = animators[j].a;
if (animatorProps.p.propType) {
animatorSelector = animators[j].s;
mult = animatorSelector.getMult(letters[i].anIndexes[j],textData.a[j].s.totalChars);
if(mult.length){
animatorOffset += animatorProps.p.v[0] * mult[0];
} else{
animatorOffset += animatorProps.p.v[0] * mult;
}
}
if (animatorProps.a.propType) {
animatorSelector = animators[j].s;
mult = animatorSelector.getMult(letters[i].anIndexes[j],textData.a[j].s.totalChars);
if(mult.length){
animatorOffset += animatorProps.a.v[0] * mult[0];
} else{
animatorOffset += animatorProps.a.v[0] * mult;
}
}
}
flag = true;
while (flag) {
if (segmentLength + partialLength >= currentLength + animatorOffset || !points) {
perc = (currentLength + animatorOffset - segmentLength) / currentPoint.partialLength;
xPathPos = prevPoint.point[0] + (currentPoint.point[0] - prevPoint.point[0]) * perc;
yPathPos = prevPoint.point[1] + (currentPoint.point[1] - prevPoint.point[1]) * perc;
matrixHelper.translate(-alignment[0]*letters[i].an/200, -(alignment[1] * yOff / 100));
flag = false;
} else if (points) {
segmentLength += currentPoint.partialLength;
pointInd += 1;
if (pointInd >= points.length) {
pointInd = 0;
segmentInd += 1;
if (!segments[segmentInd]) {
if (mask.v.c) {
pointInd = 0;
segmentInd = 0;
points = segments[segmentInd].bezierData.points;
} else {
segmentLength -= currentPoint.partialLength;
points = null;
}
} else {
points = segments[segmentInd].bezierData.points;
}
}
if (points) {
prevPoint = currentPoint;
currentPoint = points[pointInd];
partialLength = currentPoint.partialLength;
}
}
}
offf = letters[i].an / 2 - letters[i].add;
matrixHelper.translate(-offf, 0, 0);
} else {
offf = letters[i].an/2 - letters[i].add;
matrixHelper.translate(-offf,0,0);
// Grouping alignment
matrixHelper.translate(-alignment[0]*letters[i].an/200, -alignment[1]*yOff/100, 0);
}
lineLength += letters[i].l/2;
for(j=0;j<jLen;j+=1){
animatorProps = animators[j].a;
if (animatorProps.t.propType) {
animatorSelector = animators[j].s;
mult = animatorSelector.getMult(letters[i].anIndexes[j],textData.a[j].s.totalChars);
//This condition is to prevent applying tracking to first character in each line. Might be better to use a boolean "isNewLine"
if(xPos !== 0 || documentData.j !== 0) {
if(this._hasMaskedPath) {
if(mult.length) {
currentLength += animatorProps.t.v*mult[0];
} else {
currentLength += animatorProps.t.v*mult;
}
}else{
if(mult.length) {
xPos += animatorProps.t.v*mult[0];
} else {
xPos += animatorProps.t.v*mult;
}
}
}
}
}
lineLength += letters[i].l/2;
if(documentData.strokeWidthAnim) {
sw = documentData.sw || 0;
}
if(documentData.strokeColorAnim) {
if(documentData.sc){
sc = [documentData.sc[0], documentData.sc[1], documentData.sc[2]];
}else{
sc = [0,0,0];
}
}
if(documentData.fillColorAnim && documentData.fc) {
fc = [documentData.fc[0], documentData.fc[1], documentData.fc[2]];
}
for(j=0;j<jLen;j+=1){
animatorProps = animators[j].a;
if (animatorProps.a.propType) {
animatorSelector = animators[j].s;
mult = animatorSelector.getMult(letters[i].anIndexes[j],textData.a[j].s.totalChars);
if(mult.length){
matrixHelper.translate(-animatorProps.a.v[0]*mult[0], -animatorProps.a.v[1]*mult[1], animatorProps.a.v[2]*mult[2]);
} else {
matrixHelper.translate(-animatorProps.a.v[0]*mult, -animatorProps.a.v[1]*mult, animatorProps.a.v[2]*mult);
}
}
}
for(j=0;j<jLen;j+=1){
animatorProps = animators[j].a;
if (animatorProps.s.propType) {
animatorSelector = animators[j].s;
mult = animatorSelector.getMult(letters[i].anIndexes[j],textData.a[j].s.totalChars);
if(mult.length){
matrixHelper.scale(1+((animatorProps.s.v[0]-1)*mult[0]),1+((animatorProps.s.v[1]-1)*mult[1]),1);
} else {
matrixHelper.scale(1+((animatorProps.s.v[0]-1)*mult),1+((animatorProps.s.v[1]-1)*mult),1);
}
}
}
for(j=0;j<jLen;j+=1) {
animatorProps = animators[j].a;
animatorSelector = animators[j].s;
mult = animatorSelector.getMult(letters[i].anIndexes[j],textData.a[j].s.totalChars);
if (animatorProps.sk.propType) {
if(mult.length) {
matrixHelper.skewFromAxis(-animatorProps.sk.v * mult[0], animatorProps.sa.v * mult[1]);
} else {
matrixHelper.skewFromAxis(-animatorProps.sk.v * mult, animatorProps.sa.v * mult);
}
}
if (animatorProps.r.propType) {
if(mult.length) {
matrixHelper.rotateZ(-animatorProps.r.v * mult[2]);
} else {
matrixHelper.rotateZ(-animatorProps.r.v * mult);
}
}
if (animatorProps.ry.propType) {
if(mult.length) {
matrixHelper.rotateY(animatorProps.ry.v*mult[1]);
}else{
matrixHelper.rotateY(animatorProps.ry.v*mult);
}
}
if (animatorProps.rx.propType) {
if(mult.length) {
matrixHelper.rotateX(animatorProps.rx.v*mult[0]);
} else {
matrixHelper.rotateX(animatorProps.rx.v*mult);
}
}
if (animatorProps.o.propType) {
if(mult.length) {
elemOpacity += ((animatorProps.o.v)*mult[0] - elemOpacity)*mult[0];
} else {
elemOpacity += ((animatorProps.o.v)*mult - elemOpacity)*mult;
}
}
if (documentData.strokeWidthAnim && animatorProps.sw.propType) {
if(mult.length) {
sw += animatorProps.sw.v*mult[0];
} else {
sw += animatorProps.sw.v*mult;
}
}
if (documentData.strokeColorAnim && animatorProps.sc.propType) {
for(k=0;k<3;k+=1){
if(mult.length) {
sc[k] = sc[k] + (animatorProps.sc.v[k] - sc[k])*mult[0];
} else {
sc[k] = sc[k] + (animatorProps.sc.v[k] - sc[k])*mult;
}
}
}
if (documentData.fillColorAnim && documentData.fc) {
if(animatorProps.fc.propType){
for(k=0;k<3;k+=1){
if(mult.length) {
fc[k] = fc[k] + (animatorProps.fc.v[k] - fc[k])*mult[0];
} else {
fc[k] = fc[k] + (animatorProps.fc.v[k] - fc[k])*mult;
}
}
}
if(animatorProps.fh.propType){
if(mult.length) {
fc = addHueToRGB(fc,animatorProps.fh.v*mult[0]);
} else {
fc = addHueToRGB(fc,animatorProps.fh.v*mult);
}
}
if(animatorProps.fs.propType){
if(mult.length) {
fc = addSaturationToRGB(fc,animatorProps.fs.v*mult[0]);
} else {
fc = addSaturationToRGB(fc,animatorProps.fs.v*mult);
}
}
if(animatorProps.fb.propType){
if(mult.length) {
fc = addBrightnessToRGB(fc,animatorProps.fb.v*mult[0]);
} else {
fc = addBrightnessToRGB(fc,animatorProps.fb.v*mult);
}
}
}
}
for(j=0;j<jLen;j+=1){
animatorProps = animators[j].a;
if (animatorProps.p.propType) {
animatorSelector = animators[j].s;
mult = animatorSelector.getMult(letters[i].anIndexes[j],textData.a[j].s.totalChars);
if(this._hasMaskedPath) {
if(mult.length) {
matrixHelper.translate(0, animatorProps.p.v[1] * mult[0], -animatorProps.p.v[2] * mult[1]);
} else {
matrixHelper.translate(0, animatorProps.p.v[1] * mult, -animatorProps.p.v[2] * mult);
}
}else{
if(mult.length) {
matrixHelper.translate(animatorProps.p.v[0] * mult[0], animatorProps.p.v[1] * mult[1], -animatorProps.p.v[2] * mult[2]);
} else {
matrixHelper.translate(animatorProps.p.v[0] * mult, animatorProps.p.v[1] * mult, -animatorProps.p.v[2] * mult);
}
}
}
}
if(documentData.strokeWidthAnim){
letterSw = sw < 0 ? 0 : sw;
}
if(documentData.strokeColorAnim){
letterSc = 'rgb('+Math.round(sc[0]*255)+','+Math.round(sc[1]*255)+','+Math.round(sc[2]*255)+')';
}
if(documentData.fillColorAnim && documentData.fc){
letterFc = 'rgb('+Math.round(fc[0]*255)+','+Math.round(fc[1]*255)+','+Math.round(fc[2]*255)+')';
}
if(this._hasMaskedPath) {
matrixHelper.translate(0,-documentData.ls);
matrixHelper.translate(0, alignment[1]*yOff/100 + yPos,0);
if (textData.p.p) {
tanAngle = (currentPoint.point[1] - prevPoint.point[1]) / (currentPoint.point[0] - prevPoint.point[0]);
var rot = Math.atan(tanAngle) * 180 / Math.PI;
if (currentPoint.point[0] < prevPoint.point[0]) {
rot += 180;
}
matrixHelper.rotate(-rot * Math.PI / 180);
}
matrixHelper.translate(xPathPos, yPathPos, 0);
currentLength -= alignment[0]*letters[i].an/200;
if(letters[i+1] && ind !== letters[i+1].ind){
currentLength += letters[i].an / 2;
currentLength += documentData.tr/1000*documentData.finalSize;
}
}else{
matrixHelper.translate(xPos,yPos,0);
if(documentData.ps){
//matrixHelper.translate(documentData.ps[0],documentData.ps[1],0);
matrixHelper.translate(documentData.ps[0],documentData.ps[1] + documentData.ascent,0);
}
switch(documentData.j){
case 1:
matrixHelper.translate(letters[i].animatorJustifyOffset + documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[letters[i].line]),0,0);
break;
case 2:
matrixHelper.translate(letters[i].animatorJustifyOffset + documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[letters[i].line])/2,0,0);
break;
}
matrixHelper.translate(0,-documentData.ls);
matrixHelper.translate(offf,0,0);
matrixHelper.translate(alignment[0]*letters[i].an/200,alignment[1]*yOff/100,0);
xPos += letters[i].l + documentData.tr/1000*documentData.finalSize;
}
if(renderType === 'html'){
letterM = matrixHelper.toCSS();
}else if(renderType === 'svg'){
letterM = matrixHelper.to2dCSS();
}else{
letterP = [matrixHelper.props[0],matrixHelper.props[1],matrixHelper.props[2],matrixHelper.props[3],matrixHelper.props[4],matrixHelper.props[5],matrixHelper.props[6],matrixHelper.props[7],matrixHelper.props[8],matrixHelper.props[9],matrixHelper.props[10],matrixHelper.props[11],matrixHelper.props[12],matrixHelper.props[13],matrixHelper.props[14],matrixHelper.props[15]];
}
letterO = elemOpacity;
}
if(renderedLettersCount <= i) {
letterValue = new LetterProps(letterO,letterSw,letterSc,letterFc,letterM,letterP);
this.renderedLetters.push(letterValue);
renderedLettersCount += 1;
this.lettersChangedFlag = true;
} else {
letterValue = this.renderedLetters[i];
this.lettersChangedFlag = letterValue.update(letterO, letterSw, letterSc, letterFc, letterM, letterP) || this.lettersChangedFlag;
}
}
};
TextAnimatorProperty.prototype.getValue = function(){
if(this._elem.globalData.frameId === this._frameId){
return;
}
this._frameId = this._elem.globalData.frameId;
this.iterateDynamicProperties();
};
TextAnimatorProperty.prototype.mHelper = new Matrix();
TextAnimatorProperty.prototype.defaultPropsArray = [];
extendPrototype([DynamicPropertyContainer], TextAnimatorProperty);
function TextAnimatorDataProperty(elem, animatorProps, container) {
var defaultData = {propType:false};
var getProp = PropertyFactory.getProp;
var textAnimator_animatables = animatorProps.a;
this.a = {
r: textAnimator_animatables.r ? getProp(elem, textAnimator_animatables.r, 0, degToRads, container) : defaultData,
rx: textAnimator_animatables.rx ? getProp(elem, textAnimator_animatables.rx, 0, degToRads, container) : defaultData,
ry: textAnimator_animatables.ry ? getProp(elem, textAnimator_animatables.ry, 0, degToRads, container) : defaultData,
sk: textAnimator_animatables.sk ? getProp(elem, textAnimator_animatables.sk, 0, degToRads, container) : defaultData,
sa: textAnimator_animatables.sa ? getProp(elem, textAnimator_animatables.sa, 0, degToRads, container) : defaultData,
s: textAnimator_animatables.s ? getProp(elem, textAnimator_animatables.s, 1, 0.01, container) : defaultData,
a: textAnimator_animatables.a ? getProp(elem, textAnimator_animatables.a, 1, 0, container) : defaultData,
o: textAnimator_animatables.o ? getProp(elem, textAnimator_animatables.o, 0, 0.01, container) : defaultData,
p: textAnimator_animatables.p ? getProp(elem,textAnimator_animatables.p, 1, 0, container) : defaultData,
sw: textAnimator_animatables.sw ? getProp(elem, textAnimator_animatables.sw, 0, 0, container) : defaultData,
sc: textAnimator_animatables.sc ? getProp(elem, textAnimator_animatables.sc, 1, 0, container) : defaultData,
fc: textAnimator_animatables.fc ? getProp(elem, textAnimator_animatables.fc, 1, 0, container) : defaultData,
fh: textAnimator_animatables.fh ? getProp(elem, textAnimator_animatables.fh, 0, 0, container) : defaultData,
fs: textAnimator_animatables.fs ? getProp(elem, textAnimator_animatables.fs, 0, 0.01, container) : defaultData,
fb: textAnimator_animatables.fb ? getProp(elem, textAnimator_animatables.fb, 0, 0.01, container) : defaultData,
t: textAnimator_animatables.t ? getProp(elem, textAnimator_animatables.t, 0, 0, container) : defaultData
};
this.s = TextSelectorProp.getTextSelectorProp(elem,animatorProps.s, container);
this.s.t = animatorProps.s.t;
}
function LetterProps(o, sw, sc, fc, m, p){
this.o = o;
this.sw = sw;
this.sc = sc;
this.fc = fc;
this.m = m;
this.p = p;
this._mdf = {
o: true,
sw: !!sw,
sc: !!sc,
fc: !!fc,
m: true,
p: true
};
}
LetterProps.prototype.update = function(o, sw, sc, fc, m, p) {
this._mdf.o = false;
this._mdf.sw = false;
this._mdf.sc = false;
this._mdf.fc = false;
this._mdf.m = false;
this._mdf.p = false;
var updated = false;
if(this.o !== o) {
this.o = o;
this._mdf.o = true;
updated = true;
}
if(this.sw !== sw) {
this.sw = sw;
this._mdf.sw = true;
updated = true;
}
if(this.sc !== sc) {
this.sc = sc;
this._mdf.sc = true;
updated = true;
}
if(this.fc !== fc) {
this.fc = fc;
this._mdf.fc = true;
updated = true;
}
if(this.m !== m) {
this.m = m;
this._mdf.m = true;
updated = true;
}
if(p.length && (this.p[0] !== p[0] || this.p[1] !== p[1] || this.p[4] !== p[4] || this.p[5] !== p[5] || this.p[12] !== p[12] || this.p[13] !== p[13])) {
this.p = p;
this._mdf.p = true;
updated = true;
}
return updated;
};
function TextProperty(elem, data){
this._frameId = initialDefaultFrame;
this.pv = '';
this.v = '';
this.kf = false;
this._isFirstFrame = true;
this._mdf = false;
this.data = data;
this.elem = elem;
this.comp = this.elem.comp;
this.keysIndex = -1;
this.canResize = false;
this.minimumFontSize = 1;
this.effectsSequence = [];
this.currentData = {
ascent: 0,
boxWidth: this.defaultBoxWidth,
f: '',
fStyle: '',
fWeight: '',
fc: '',
j: '',
justifyOffset: '',
l: [],
lh: 0,
lineWidths: [],
ls: '',
of: '',
s: '',
sc: '',
sw: 0,
t: 0,
tr: 0,
sz:0,
ps:null,
fillColorAnim: false,
strokeColorAnim: false,
strokeWidthAnim: false,
yOffset: 0,
finalSize:0,
finalText:[],
finalLineHeight: 0,
__test: true
};
this.copyFromDocumentData(this.data.d.k[0].s);
if(!this.searchProperty()) {
this.completeTextData(this.currentData);
this.keysIndex = 0;
}
}
TextProperty.prototype.defaultBoxWidth = [0,0];
TextProperty.prototype.copyFromDocumentData = function(data) {
for(var s in data) {
this.currentData[s] = data[s];
}
}
TextProperty.prototype.setCurrentData = function(data, currentTextValue){
if(this.currentData !== data) {
if(!data.__complete) {
this.completeTextData(data);
}
this.copyFromDocumentData(data);
this.currentData.boxWidth = this.currentData.boxWidth || this.defaultBoxWidth;
this.currentData.fillColorAnim = data.fillColorAnim || this.currentData.fillColorAnim;
this.currentData.strokeColorAnim = data.strokeColorAnim || this.currentData.strokeColorAnim;
this.currentData.strokeWidthAnim = data.strokeWidthAnim || this.currentData.strokeWidthAnim;
this._mdf = true;
} else if(currentTextValue !== this.currentData.t) {
this._mdf = true;
this.completeTextData(data);
}
/*var currentData = this.currentData;
currentData.ascent = data.ascent;
currentData.boxWidth = data.boxWidth ? data.boxWidth : currentData.boxWidth;
currentData.f = data.f;
currentData.fStyle = data.fStyle;
currentData.fWeight = data.fWeight;
currentData.fc = data.fc;
currentData.j = data.j;
currentData.justifyOffset = data.justifyOffset;
currentData.l = data.l;
currentData.lh = data.lh;
currentData.lineWidths = data.lineWidths;
currentData.ls = data.ls;
currentData.of = data.of;
currentData.s = data.s;
currentData.sc = data.sc;
currentData.sw = data.sw;
currentData.sz = data.sz;
currentData.ps = data.ps;
currentData.t = data.t;
currentData.tr = data.tr;
currentData.fillColorAnim = data.fillColorAnim || currentData.fillColorAnim;
currentData.strokeColorAnim = data.strokeColorAnim || currentData.strokeColorAnim;
currentData.strokeWidthAnim = data.strokeWidthAnim || currentData.strokeWidthAnim;
currentData.yOffset = data.yOffset;
currentData.finalSize = data.finalSize;
currentData.finalLineHeight = data.finalLineHeight;
currentData.finalText = data.finalText;*/
};
TextProperty.prototype.searchProperty = function() {
return this.searchKeyframes();
};
TextProperty.prototype.searchKeyframes = function() {
this.kf = this.data.d.k.length > 1;
if(this.kf) {
this.addEffect(this.getKeyframeValue.bind(this));
}
return this.kf;
}
TextProperty.prototype.addEffect = function(effectFunction) {
this.effectsSequence.push(effectFunction);
this.elem.addDynamicProperty(this);
};
TextProperty.prototype.getValue = function(_finalValue) {
if((this.elem.globalData.frameId === this.frameId || !this.effectsSequence.length) && !_finalValue) {
return;
}
var currentTextValue = this.currentData.t;
if(this.lock) {
this.setCurrentData(this.currentData, currentTextValue);
return;
}
this.lock = true;
this._mdf = false;
var multipliedValue;
var i, len = this.effectsSequence.length;
var finalValue = _finalValue || this.currentData;
for(i = 0; i < len; i += 1) {
finalValue = this.effectsSequence[i](finalValue);
}
this.setCurrentData(finalValue, currentTextValue);
this.pv = this.v = this.currentData;
this.lock = false;
this.frameId = this.elem.globalData.frameId;
}
TextProperty.prototype.getKeyframeValue = function(currentValue) {
var textKeys = this.data.d.k, textDocumentData;
var frameNum = this.elem.comp.renderedFrame;
var i = 0, len = textKeys.length;
while(i <= len - 1) {
textDocumentData = textKeys[i].s;
if(i === len - 1 || textKeys[i+1].t > frameNum){
break;
}
i += 1;
}
if(this.keysIndex !== i) {
currentValue = textDocumentData;
this.keysIndex = i;
}
return currentValue;
};
TextProperty.prototype.buildFinalText = function(text) {
var combinedCharacters = FontManager.getCombinedCharacterCodes();
var charactersArray = [];
var i = 0, len = text.length;
while (i < len) {
if (combinedCharacters.indexOf(text.charCodeAt(i)) !== -1) {
charactersArray[charactersArray.length - 1] += text.charAt(i);
} else {
charactersArray.push(text.charAt(i));
}
i += 1;
}
return charactersArray;
}
TextProperty.prototype.completeTextData = function(documentData) {
documentData.__complete = true;
var fontManager = this.elem.globalData.fontManager;
var data = this.data;
var letters = [];
var i, len;
var newLineFlag, index = 0, val;
var anchorGrouping = data.m.g;
var currentSize = 0, currentPos = 0, currentLine = 0, lineWidths = [];
var lineWidth = 0;
var maxLineWidth = 0;
var j, jLen;
var fontData = fontManager.getFontByName(documentData.f);
var charData, cLength = 0;
var styles = fontData.fStyle ? fontData.fStyle.split(' ') : [];
var fWeight = 'normal', fStyle = 'normal';
len = styles.length;
var styleName;
for(i=0;i<len;i+=1){
styleName = styles[i].toLowerCase();
switch(styleName) {
case 'italic':
fStyle = 'italic';
break;
case 'bold':
fWeight = '700';
break;
case 'black':
fWeight = '900';
break;
case 'medium':
fWeight = '500';
break;
case 'regular':
case 'normal':
fWeight = '400';
break;
case 'light':
case 'thin':
fWeight = '200';
break;
}
}
documentData.fWeight = fontData.fWeight || fWeight;
documentData.fStyle = fStyle;
len = documentData.t.length;
documentData.finalSize = documentData.s;
documentData.finalText = this.buildFinalText(documentData.t);
documentData.finalLineHeight = documentData.lh;
var trackingOffset = documentData.tr/1000*documentData.finalSize;
if(documentData.sz){
var flag = true;
var boxWidth = documentData.sz[0];
var boxHeight = documentData.sz[1];
var currentHeight, finalText;
while(flag) {
finalText = this.buildFinalText(documentData.t);
currentHeight = 0;
lineWidth = 0;
len = finalText.length;
trackingOffset = documentData.tr/1000*documentData.finalSize;
var lastSpaceIndex = -1;
for(i=0;i<len;i+=1){
newLineFlag = false;
if(finalText[i] === ' '){
lastSpaceIndex = i;
}else if(finalText[i].charCodeAt(0) === 13){
lineWidth = 0;
newLineFlag = true;
currentHeight += documentData.finalLineHeight || documentData.finalSize*1.2;
}
if(fontManager.chars){
charData = fontManager.getCharData(finalText[i], fontData.fStyle, fontData.fFamily);
cLength = newLineFlag ? 0 : charData.w*documentData.finalSize/100;
}else{
//tCanvasHelper.font = documentData.s + 'px '+ fontData.fFamily;
cLength = fontManager.measureText(finalText[i], documentData.f, documentData.finalSize);
}
if(lineWidth + cLength > boxWidth && finalText[i] !== ' '){
if(lastSpaceIndex === -1){
len += 1;
} else {
i = lastSpaceIndex;
}
currentHeight += documentData.finalLineHeight || documentData.finalSize*1.2;
finalText.splice(i, lastSpaceIndex === i ? 1 : 0,"\r");
//finalText = finalText.substr(0,i) + "\r" + finalText.substr(i === lastSpaceIndex ? i + 1 : i);
lastSpaceIndex = -1;
lineWidth = 0;
}else {
lineWidth += cLength;
lineWidth += trackingOffset;
}
}
currentHeight += fontData.ascent*documentData.finalSize/100;
if(this.canResize && documentData.finalSize > this.minimumFontSize && boxHeight < currentHeight) {
documentData.finalSize -= 1;
documentData.finalLineHeight = documentData.finalSize * documentData.lh / documentData.s;
} else {
documentData.finalText = finalText;
len = documentData.finalText.length;
flag = false;
}
}
}
lineWidth = - trackingOffset;
cLength = 0;
var uncollapsedSpaces = 0;
var currentChar;
for (i = 0;i < len ;i += 1) {
newLineFlag = false;
currentChar = documentData.finalText[i];
if(currentChar === ' '){
val = '\u00A0';
}else if(currentChar.charCodeAt(0) === 13){
uncollapsedSpaces = 0;
lineWidths.push(lineWidth);
maxLineWidth = lineWidth > maxLineWidth ? lineWidth : maxLineWidth;
lineWidth = - 2 * trackingOffset;
val = '';
newLineFlag = true;
currentLine += 1;
}else{
val = documentData.finalText[i];
}
if(fontManager.chars){
charData = fontManager.getCharData(currentChar, fontData.fStyle, fontManager.getFontByName(documentData.f).fFamily);
cLength = newLineFlag ? 0 : charData.w*documentData.finalSize/100;
}else{
//var charWidth = fontManager.measureText(val, documentData.f, documentData.finalSize);
//tCanvasHelper.font = documentData.finalSize + 'px '+ fontManager.getFontByName(documentData.f).fFamily;
cLength = fontManager.measureText(val, documentData.f, documentData.finalSize);
}
//
if(currentChar === ' '){
uncollapsedSpaces += cLength + trackingOffset;
} else {
lineWidth += cLength + trackingOffset + uncollapsedSpaces;
uncollapsedSpaces = 0;
}
letters.push({l:cLength,an:cLength,add:currentSize,n:newLineFlag, anIndexes:[], val: val, line: currentLine, animatorJustifyOffset: 0});
if(anchorGrouping == 2){
currentSize += cLength;
if(val === '' || val === '\u00A0' || i === len - 1){
if(val === '' || val === '\u00A0'){
currentSize -= cLength;
}
while(currentPos<=i){
letters[currentPos].an = currentSize;
letters[currentPos].ind = index;
letters[currentPos].extra = cLength;
currentPos += 1;
}
index += 1;
currentSize = 0;
}
}else if(anchorGrouping == 3){
currentSize += cLength;
if(val === '' || i === len - 1){
if(val === ''){
currentSize -= cLength;
}
while(currentPos<=i){
letters[currentPos].an = currentSize;
letters[currentPos].ind = index;
letters[currentPos].extra = cLength;
currentPos += 1;
}
currentSize = 0;
index += 1;
}
}else{
letters[index].ind = index;
letters[index].extra = 0;
index += 1;
}
}
documentData.l = letters;
maxLineWidth = lineWidth > maxLineWidth ? lineWidth : maxLineWidth;
lineWidths.push(lineWidth);
if(documentData.sz){
documentData.boxWidth = documentData.sz[0];
documentData.justifyOffset = 0;
}else{
documentData.boxWidth = maxLineWidth;
switch(documentData.j){
case 1:
documentData.justifyOffset = - documentData.boxWidth;
break;
case 2:
documentData.justifyOffset = - documentData.boxWidth/2;
break;
default:
documentData.justifyOffset = 0;
}
}
documentData.lineWidths = lineWidths;
var animators = data.a, animatorData, letterData;
jLen = animators.length;
var based, ind, indexes = [];
for(j=0;j<jLen;j+=1){
animatorData = animators[j];
if(animatorData.a.sc){
documentData.strokeColorAnim = true;
}
if(animatorData.a.sw){
documentData.strokeWidthAnim = true;
}
if(animatorData.a.fc || animatorData.a.fh || animatorData.a.fs || animatorData.a.fb){
documentData.fillColorAnim = true;
}
ind = 0;
based = animatorData.s.b;
for(i=0;i<len;i+=1){
letterData = letters[i];
letterData.anIndexes[j] = ind;
if((based == 1 && letterData.val !== '') || (based == 2 && letterData.val !== '' && letterData.val !== '\u00A0') || (based == 3 && (letterData.n || letterData.val == '\u00A0' || i == len - 1)) || (based == 4 && (letterData.n || i == len - 1))){
if(animatorData.s.rn === 1){
indexes.push(ind);
}
ind += 1;
}
}
data.a[j].s.totalChars = ind;
var currentInd = -1, newInd;
if(animatorData.s.rn === 1){
for(i = 0; i < len; i += 1){
letterData = letters[i];
if(currentInd != letterData.anIndexes[j]){
currentInd = letterData.anIndexes[j];
newInd = indexes.splice(Math.floor(Math.random()*indexes.length),1)[0];
}
letterData.anIndexes[j] = newInd;
}
}
}
documentData.yOffset = documentData.finalLineHeight || documentData.finalSize*1.2;
documentData.ls = documentData.ls || 0;
documentData.ascent = fontData.ascent*documentData.finalSize/100;
};
TextProperty.prototype.updateDocumentData = function(newData, index) {
index = index === undefined
? this.keysIndex === -1
? 0
: this.keysIndex
: index;
var dData = this.data.d.k[index].s;
for(var s in newData) {
dData[s] = newData[s];
}
this.recalculate(index);
};
TextProperty.prototype.recalculate = function(index) {
var dData = this.data.d.k[index].s;
dData.__complete = false;
this.keysIndex = this.kf ? -1 : 0;
this._isFirstFrame = true;
this.getValue(dData);
}
TextProperty.prototype.canResizeFont = function(_canResize) {
this.canResize = _canResize;
this.recalculate(this.keysIndex);
};
TextProperty.prototype.setMinimumFontSize = function(_fontValue) {
this.minimumFontSize = Math.floor(_fontValue) || 1;
this.recalculate(this.keysIndex);
};
var TextSelectorProp = (function(){
var max = Math.max;
var min = Math.min;
var floor = Math.floor;
function TextSelectorProp(elem,data){
this._currentTextLength = -1;
this.k = false;
this.data = data;
this.elem = elem;
this.comp = elem.comp;
this.finalS = 0;
this.finalE = 0;
this.initDynamicPropertyContainer(elem);
this.s = PropertyFactory.getProp(elem,data.s || {k:0},0,0,this);
if('e' in data){
this.e = PropertyFactory.getProp(elem,data.e,0,0,this);
}else{
this.e = {v:100};
}
this.o = PropertyFactory.getProp(elem,data.o || {k:0},0,0,this);
this.xe = PropertyFactory.getProp(elem,data.xe || {k:0},0,0,this);
this.ne = PropertyFactory.getProp(elem,data.ne || {k:0},0,0,this);
this.a = PropertyFactory.getProp(elem,data.a,0,0.01,this);
if(!this.dynamicProperties.length){
this.getValue();
}
}
TextSelectorProp.prototype = {
getMult: function(ind) {
if(this._currentTextLength !== this.elem.textProperty.currentData.l.length) {
this.getValue();
}
//var easer = bez.getEasingCurve(this.ne.v/100,0,1-this.xe.v/100,1);
var easer = BezierFactory.getBezierEasing(this.ne.v/100,0,1-this.xe.v/100,1).get;
var mult = 0;
var s = this.finalS;
var e = this.finalE;
var type = this.data.sh;
if(type == 2){
if(e === s){
mult = ind >= e ? 1 : 0;
}else{
mult = max(0,min(0.5/(e-s) + (ind-s)/(e-s),1));
}
mult = easer(mult);
}else if(type == 3){
if(e === s){
mult = ind >= e ? 0 : 1;
}else{
mult = 1 - max(0,min(0.5/(e-s) + (ind-s)/(e-s),1));
}
mult = easer(mult);
}else if(type == 4){
if(e === s){
mult = 0;
}else{
mult = max(0,min(0.5/(e-s) + (ind-s)/(e-s),1));
if(mult<0.5){
mult *= 2;
}else{
mult = 1 - 2*(mult-0.5);
}
}
mult = easer(mult);
}else if(type == 5){
if(e === s){
mult = 0;
}else{
var tot = e - s;
/*ind += 0.5;
mult = -4/(tot*tot)*(ind*ind)+(4/tot)*ind;*/
ind = min(max(0,ind+0.5-s),e-s);
var x = -tot/2+ind;
var a = tot/2;
mult = Math.sqrt(1 - (x*x)/(a*a));
}
mult = easer(mult);
}else if(type == 6){
if(e === s){
mult = 0;
}else{
ind = min(max(0,ind+0.5-s),e-s);
mult = (1+(Math.cos((Math.PI+Math.PI*2*(ind)/(e-s)))))/2;
/*
ind = Math.min(Math.max(s,ind),e-1);
mult = (1+(Math.cos((Math.PI+Math.PI*2*(ind-s)/(e-1-s)))))/2;
mult = Math.max(mult,(1/(e-1-s))/(e-1-s));*/
}
mult = easer(mult);
}else {
if(ind >= floor(s)){
if(ind-s < 0){
mult = 1 - (s - ind);
}else{
mult = max(0,min(e-ind,1));
}
}
mult = easer(mult);
}
return mult*this.a.v;
},
getValue: function(newCharsFlag) {
this.iterateDynamicProperties();
this._mdf = newCharsFlag || this._mdf;
this._currentTextLength = this.elem.textProperty.currentData.l.length || 0;
if(newCharsFlag && this.data.r === 2) {
this.e.v = this._currentTextLength;
}
var divisor = this.data.r === 2 ? 1 : 100 / this._currentTextLength;
var o = this.o.v/divisor;
var s = this.s.v/divisor + o;
var e = (this.e.v/divisor) + o;
if(s>e){
var _s = s;
s = e;
e = _s;
}
this.finalS = s;
this.finalE = e;
}
}
extendPrototype([DynamicPropertyContainer], TextSelectorProp);
function getTextSelectorProp(elem, data,arr) {
return new TextSelectorProp(elem, data, arr);
}
return {
getTextSelectorProp: getTextSelectorProp
};
}());
var pool_factory = (function() {
return function(initialLength, _create, _release, _clone) {
var _length = 0;
var _maxLength = initialLength;
var pool = createSizedArray(_maxLength);
var ob = {
newElement: newElement,
release: release
};
function newElement(){
var element;
if(_length){
_length -= 1;
element = pool[_length];
} else {
element = _create();
}
return element;
}
function release(element) {
if(_length === _maxLength) {
pool = pooling.double(pool);
_maxLength = _maxLength*2;
}
if (_release) {
_release(element);
}
pool[_length] = element;
_length += 1;
}
function clone() {
var clonedElement = newElement();
return _clone(clonedElement);
}
return ob;
};
}());
var pooling = (function(){
function double(arr){
return arr.concat(createSizedArray(arr.length));
}
return {
double: double
};
}());
var point_pool = (function(){
function create() {
return createTypedArray('float32', 2);
}
return pool_factory(8, create);
}());
var shape_pool = (function(){
function create() {
return new ShapePath();
}
function release(shapePath) {
var len = shapePath._length, i;
for(i = 0; i < len; i += 1) {
point_pool.release(shapePath.v[i]);
point_pool.release(shapePath.i[i]);
point_pool.release(shapePath.o[i]);
shapePath.v[i] = null;
shapePath.i[i] = null;
shapePath.o[i] = null;
}
shapePath._length = 0;
shapePath.c = false;
}
function clone(shape) {
var cloned = factory.newElement();
var i, len = shape._length === undefined ? shape.v.length : shape._length;
cloned.setLength(len);
cloned.c = shape.c;
var pt;
for(i = 0; i < len; i += 1) {
cloned.setTripleAt(shape.v[i][0],shape.v[i][1],shape.o[i][0],shape.o[i][1],shape.i[i][0],shape.i[i][1], i);
}
return cloned;
}
var factory = pool_factory(4, create, release);
factory.clone = clone;
return factory;
}());
var shapeCollection_pool = (function(){
var ob = {
newShapeCollection: newShapeCollection,
release: release
};
var _length = 0;
var _maxLength = 4;
var pool = createSizedArray(_maxLength);
function newShapeCollection(){
var shapeCollection;
if(_length){
_length -= 1;
shapeCollection = pool[_length];
} else {
shapeCollection = new ShapeCollection();
}
return shapeCollection;
}
function release(shapeCollection) {
var i, len = shapeCollection._length;
for(i = 0; i < len; i += 1) {
shape_pool.release(shapeCollection.shapes[i]);
}
shapeCollection._length = 0;
if(_length === _maxLength) {
pool = pooling.double(pool);
_maxLength = _maxLength*2;
}
pool[_length] = shapeCollection;
_length += 1;
}
return ob;
}());
var segments_length_pool = (function(){
function create() {
return {
lengths: [],
totalLength: 0
};
}
function release(element) {
var i, len = element.lengths.length;
for(i=0;i<len;i+=1) {
bezier_length_pool.release(element.lengths[i]);
}
element.lengths.length = 0;
}
return pool_factory(8, create, release);
}());
var bezier_length_pool = (function(){
function create() {
return {
addedLength: 0,
percents: createTypedArray('float32', defaultCurveSegments),
lengths: createTypedArray('float32', defaultCurveSegments),
};
}
return pool_factory(8, create);
}());
function BaseRenderer(){}
BaseRenderer.prototype.checkLayers = function(num){
var i, len = this.layers.length, data;
this.completeLayers = true;
for (i = len - 1; i >= 0; i--) {
if (!this.elements[i]) {
data = this.layers[i];
if(data.ip - data.st <= (num - this.layers[i].st) && data.op - data.st > (num - this.layers[i].st))
{
this.buildItem(i);
}
}
this.completeLayers = this.elements[i] ? this.completeLayers:false;
}
this.checkPendingElements();
};
BaseRenderer.prototype.createItem = function(layer){
switch(layer.ty){
case 2:
return this.createImage(layer);
case 0:
return this.createComp(layer);
case 1:
return this.createSolid(layer);
case 3:
return this.createNull(layer);
case 4:
return this.createShape(layer);
case 5:
return this.createText(layer);
case 13:
return this.createCamera(layer);
}
return this.createNull(layer);
};
BaseRenderer.prototype.createCamera = function(){
throw new Error('You\'re using a 3d camera. Try the html renderer.');
};
BaseRenderer.prototype.buildAllItems = function(){
var i, len = this.layers.length;
for(i=0;i<len;i+=1){
this.buildItem(i);
}
this.checkPendingElements();
};
BaseRenderer.prototype.includeLayers = function(newLayers){
this.completeLayers = false;
var i, len = newLayers.length;
var j, jLen = this.layers.length;
for(i=0;i<len;i+=1){
j = 0;
while(j<jLen){
if(this.layers[j].id == newLayers[i].id){
this.layers[j] = newLayers[i];
break;
}
j += 1;
}
}
};
BaseRenderer.prototype.setProjectInterface = function(pInterface){
this.globalData.projectInterface = pInterface;
};
BaseRenderer.prototype.initItems = function(){
if(!this.globalData.progressiveLoad){
this.buildAllItems();
}
};
BaseRenderer.prototype.buildElementParenting = function(element, parentName, hierarchy) {
var elements = this.elements;
var layers = this.layers;
var i=0, len = layers.length;
while (i < len) {
if (layers[i].ind == parentName) {
if (!elements[i] || elements[i] === true) {
this.buildItem(i);
this.addPendingElement(element);
} else {
hierarchy.push(elements[i]);
elements[i].setAsParent();
if(layers[i].parent !== undefined) {
this.buildElementParenting(element, layers[i].parent, hierarchy);
} else {
element.setHierarchy(hierarchy);
}
}
}
i += 1;
}
};
BaseRenderer.prototype.addPendingElement = function(element){
this.pendingElements.push(element);
};
BaseRenderer.prototype.searchExtraCompositions = function(assets){
var i, len = assets.length;
for(i=0;i<len;i+=1){
if(assets[i].xt){
var comp = this.createComp(assets[i]);
comp.initExpressions();
this.globalData.projectInterface.registerComposition(comp);
}
}
};
function SVGRenderer(animationItem, config){
this.animationItem = animationItem;
this.layers = null;
this.renderedFrame = -1;
this.svgElement = createNS('svg');
var maskElement = createNS('g');
this.svgElement.appendChild(maskElement);
this.layerElement = maskElement;
var defs = createNS( 'defs');
this.svgElement.appendChild(defs);
this.renderConfig = {
preserveAspectRatio: (config && config.preserveAspectRatio) || 'xMidYMid meet',
progressiveLoad: (config && config.progressiveLoad) || false,
hideOnTransparent: (config && config.hideOnTransparent === false) ? false : true,
viewBoxOnly: (config && config.viewBoxOnly) || false,
viewBoxSize: (config && config.viewBoxSize) || false,
className: (config && config.className) || ''
};
this.globalData = {
_mdf: false,
frameNum: -1,
defs: defs,
frameId: 0,
compSize: {w:0,h:0},
renderConfig: this.renderConfig,
fontManager: new FontManager()
};
this.elements = [];
this.pendingElements = [];
this.destroyed = false;
}
extendPrototype([BaseRenderer],SVGRenderer);
SVGRenderer.prototype.createNull = function (data) {
return new NullElement(data,this.globalData,this);
};
SVGRenderer.prototype.createShape = function (data) {
return new SVGShapeElement(data,this.globalData,this);
};
SVGRenderer.prototype.createText = function (data) {
return new SVGTextElement(data,this.globalData,this);
};
SVGRenderer.prototype.createImage = function (data) {
return new IImageElement(data,this.globalData,this);
};
SVGRenderer.prototype.createComp = function (data) {
return new SVGCompElement(data,this.globalData,this);
};
SVGRenderer.prototype.createSolid = function (data) {
return new ISolidElement(data,this.globalData,this);
};
SVGRenderer.prototype.configAnimation = function(animData){
this.svgElement.setAttribute('xmlns','http://www.w3.org/2000/svg');
if(this.renderConfig.viewBoxSize) {
this.svgElement.setAttribute('viewBox',this.renderConfig.viewBoxSize);
} else {
this.svgElement.setAttribute('viewBox','0 0 '+animData.w+' '+animData.h);
}
if(!this.renderConfig.viewBoxOnly) {
this.svgElement.setAttribute('width',animData.w);
this.svgElement.setAttribute('height',animData.h);
this.svgElement.style.width = '100%';
this.svgElement.style.height = '100%';
this.svgElement.style.transform = 'translate3d(0,0,0)';
}
if(this.renderConfig.className) {
this.svgElement.setAttribute('class', this.renderConfig.className);
}
this.svgElement.setAttribute('preserveAspectRatio',this.renderConfig.preserveAspectRatio);
//this.layerElement.style.transform = 'translate3d(0,0,0)';
//this.layerElement.style.transformOrigin = this.layerElement.style.mozTransformOrigin = this.layerElement.style.webkitTransformOrigin = this.layerElement.style['-webkit-transform'] = "0px 0px 0px";
this.animationItem.wrapper.appendChild(this.svgElement);
//Mask animation
var defs = this.globalData.defs;
this.globalData.getAssetData = this.animationItem.getAssetData.bind(this.animationItem);
this.globalData.getAssetsPath = this.animationItem.getAssetsPath.bind(this.animationItem);
this.globalData.progressiveLoad = this.renderConfig.progressiveLoad;
this.globalData.nm = animData.nm;
this.globalData.compSize.w = animData.w;
this.globalData.compSize.h = animData.h;
this.globalData.frameRate = animData.fr;
this.data = animData;
var maskElement = createNS( 'clipPath');
var rect = createNS('rect');
rect.setAttribute('width',animData.w);
rect.setAttribute('height',animData.h);
rect.setAttribute('x',0);
rect.setAttribute('y',0);
var maskId = 'animationMask_'+randomString(10);
maskElement.setAttribute('id', maskId);
maskElement.appendChild(rect);
this.layerElement.setAttribute("clip-path", "url(" + locationHref + "#"+maskId+")");
defs.appendChild(maskElement);
this.layers = animData.layers;
this.globalData.fontManager.addChars(animData.chars);
this.globalData.fontManager.addFonts(animData.fonts,defs);
this.elements = createSizedArray(animData.layers.length);
};
SVGRenderer.prototype.destroy = function () {
this.animationItem.wrapper.innerHTML = '';
this.layerElement = null;
this.globalData.defs = null;
var i, len = this.layers ? this.layers.length : 0;
for (i = 0; i < len; i++) {
if(this.elements[i]){
this.elements[i].destroy();
}
}
this.elements.length = 0;
this.destroyed = true;
this.animationItem = null;
};
SVGRenderer.prototype.updateContainerSize = function () {
};
SVGRenderer.prototype.buildItem = function(pos){
var elements = this.elements;
if(elements[pos] || this.layers[pos].ty == 99){
return;
}
elements[pos] = true;
var element = this.createItem(this.layers[pos]);
elements[pos] = element;
if(expressionsPlugin){
if(this.layers[pos].ty === 0){
this.globalData.projectInterface.registerComposition(element);
}
element.initExpressions();
}
this.appendElementInPos(element,pos);
if(this.layers[pos].tt){
if(!this.elements[pos - 1] || this.elements[pos - 1] === true){
this.buildItem(pos - 1);
this.addPendingElement(element);
} else {
element.setMatte(elements[pos - 1].layerId);
}
}
};
SVGRenderer.prototype.checkPendingElements = function(){
while(this.pendingElements.length){
var element = this.pendingElements.pop();
element.checkParenting();
if(element.data.tt){
var i = 0, len = this.elements.length;
while(i<len){
if(this.elements[i] === element){
element.setMatte(this.elements[i - 1].layerId);
break;
}
i += 1;
}
}
}
};
SVGRenderer.prototype.renderFrame = function(num){
if(this.renderedFrame === num || this.destroyed){
return;
}
if(num === null){
num = this.renderedFrame;
}else{
this.renderedFrame = num;
}
// console.log('-------');
// console.log('FRAME ',num);
this.globalData.frameNum = num;
this.globalData.frameId += 1;
this.globalData.projectInterface.currentFrame = num;
this.globalData._mdf = false;
var i, len = this.layers.length;
if(!this.completeLayers){
this.checkLayers(num);
}
for (i = len - 1; i >= 0; i--) {
if(this.completeLayers || this.elements[i]){
this.elements[i].prepareFrame(num - this.layers[i].st);
}
}
if(this.globalData._mdf) {
for (i = 0; i < len; i += 1) {
if(this.completeLayers || this.elements[i]){
this.elements[i].renderFrame();
}
}
}
};
SVGRenderer.prototype.appendElementInPos = function(element, pos){
var newElement = element.getBaseElement();
if(!newElement){
return;
}
var i = 0;
var nextElement;
while(i<pos){
if(this.elements[i] && this.elements[i]!== true && this.elements[i].getBaseElement()){
nextElement = this.elements[i].getBaseElement();
}
i += 1;
}
if(nextElement){
this.layerElement.insertBefore(newElement, nextElement);
} else {
this.layerElement.appendChild(newElement);
}
};
SVGRenderer.prototype.hide = function(){
this.layerElement.style.display = 'none';
};
SVGRenderer.prototype.show = function(){
this.layerElement.style.display = 'block';
};
function MaskElement(data,element,globalData) {
this.data = data;
this.element = element;
this.globalData = globalData;
this.storedData = [];
this.masksProperties = this.data.masksProperties || [];
this.maskElement = null;
var defs = this.globalData.defs;
var i, len = this.masksProperties ? this.masksProperties.length : 0;
this.viewData = createSizedArray(len);
this.solidPath = '';
var path, properties = this.masksProperties;
var count = 0;
var currentMasks = [];
var j, jLen;
var layerId = randomString(10);
var rect, expansor, feMorph,x;
var maskType = 'clipPath', maskRef = 'clip-path';
for (i = 0; i < len; i++) {
if((properties[i].mode !== 'a' && properties[i].mode !== 'n')|| properties[i].inv || properties[i].o.k !== 100){
maskType = 'mask';
maskRef = 'mask';
}
if((properties[i].mode == 's' || properties[i].mode == 'i') && count === 0){
rect = createNS( 'rect');
rect.setAttribute('fill', '#ffffff');
rect.setAttribute('width', this.element.comp.data.w);
rect.setAttribute('height', this.element.comp.data.h);
currentMasks.push(rect);
} else {
rect = null;
}
path = createNS( 'path');
if(properties[i].mode == 'n') {
// TODO move this to a factory or to a constructor
this.viewData[i] = {
op: PropertyFactory.getProp(this.element,properties[i].o,0,0.01,this.element),
prop: ShapePropertyFactory.getShapeProp(this.element,properties[i],3),
elem: path,
lastPath: ''
};
defs.appendChild(path);
continue;
}
count += 1;
path.setAttribute('fill', properties[i].mode === 's' ? '#000000':'#ffffff');
path.setAttribute('clip-rule','nonzero');
var filterID;
if (properties[i].x.k !== 0) {
maskType = 'mask';
maskRef = 'mask';
x = PropertyFactory.getProp(this.element,properties[i].x,0,null,this.element);
filterID = 'fi_'+randomString(10);
expansor = createNS('filter');
expansor.setAttribute('id',filterID);
feMorph = createNS('feMorphology');
feMorph.setAttribute('operator','dilate');
feMorph.setAttribute('in','SourceGraphic');
feMorph.setAttribute('radius','0');
expansor.appendChild(feMorph);
defs.appendChild(expansor);
path.setAttribute('stroke', properties[i].mode === 's' ? '#000000':'#ffffff');
} else {
feMorph = null;
x = null;
}
// TODO move this to a factory or to a constructor
this.storedData[i] = {
elem: path,
x: x,
expan: feMorph,
lastPath: '',
lastOperator:'',
filterId:filterID,
lastRadius:0
};
if(properties[i].mode == 'i'){
jLen = currentMasks.length;
var g = createNS('g');
for(j=0;j<jLen;j+=1){
g.appendChild(currentMasks[j]);
}
var mask = createNS('mask');
mask.setAttribute('mask-type','alpha');
mask.setAttribute('id',layerId+'_'+count);
mask.appendChild(path);
defs.appendChild(mask);
g.setAttribute('mask','url(' + locationHref + '#'+layerId+'_'+count+')');
currentMasks.length = 0;
currentMasks.push(g);
}else{
currentMasks.push(path);
}
if(properties[i].inv && !this.solidPath){
this.solidPath = this.createLayerSolidPath();
}
// TODO move this to a factory or to a constructor
this.viewData[i] = {
elem: path,
lastPath: '',
op: PropertyFactory.getProp(this.element,properties[i].o,0,0.01,this.element),
prop:ShapePropertyFactory.getShapeProp(this.element,properties[i],3),
invRect: rect
};
if(!this.viewData[i].prop.k){
this.drawPath(properties[i],this.viewData[i].prop.v,this.viewData[i]);
}
}
this.maskElement = createNS( maskType);
len = currentMasks.length;
for(i=0;i<len;i+=1){
this.maskElement.appendChild(currentMasks[i]);
}
if(count > 0){
this.maskElement.setAttribute('id', layerId);
this.element.maskedElement.setAttribute(maskRef, "url(" + locationHref + "#" + layerId + ")");
defs.appendChild(this.maskElement);
}
if (this.viewData.length) {
this.element.addRenderableComponent(this);
}
}
MaskElement.prototype.getMaskProperty = function(pos){
return this.viewData[pos].prop;
};
MaskElement.prototype.renderFrame = function (isFirstFrame) {
var finalMat = this.element.finalTransform.mat;
var i, len = this.masksProperties.length;
for (i = 0; i < len; i++) {
if(this.viewData[i].prop._mdf || isFirstFrame){
this.drawPath(this.masksProperties[i],this.viewData[i].prop.v,this.viewData[i]);
}
if(this.viewData[i].op._mdf || isFirstFrame){
this.viewData[i].elem.setAttribute('fill-opacity',this.viewData[i].op.v);
}
if(this.masksProperties[i].mode !== 'n'){
if(this.viewData[i].invRect && (this.element.finalTransform.mProp._mdf || isFirstFrame)){
this.viewData[i].invRect.setAttribute('x', -finalMat.props[12]);
this.viewData[i].invRect.setAttribute('y', -finalMat.props[13]);
}
if(this.storedData[i].x && (this.storedData[i].x._mdf || isFirstFrame)){
var feMorph = this.storedData[i].expan;
if(this.storedData[i].x.v < 0){
if(this.storedData[i].lastOperator !== 'erode'){
this.storedData[i].lastOperator = 'erode';
this.storedData[i].elem.setAttribute('filter','url(' + locationHref + '#'+this.storedData[i].filterId+')');
}
feMorph.setAttribute('radius',-this.storedData[i].x.v);
}else{
if(this.storedData[i].lastOperator !== 'dilate'){
this.storedData[i].lastOperator = 'dilate';
this.storedData[i].elem.setAttribute('filter',null);
}
this.storedData[i].elem.setAttribute('stroke-width', this.storedData[i].x.v*2);
}
}
}
}
};
MaskElement.prototype.getMaskelement = function () {
return this.maskElement;
};
MaskElement.prototype.createLayerSolidPath = function(){
var path = 'M0,0 ';
path += ' h' + this.globalData.compSize.w ;
path += ' v' + this.globalData.compSize.h ;
path += ' h-' + this.globalData.compSize.w ;
path += ' v-' + this.globalData.compSize.h + ' ';
return path;
};
MaskElement.prototype.drawPath = function(pathData,pathNodes,viewData){
var pathString = " M"+pathNodes.v[0][0]+','+pathNodes.v[0][1];
var i, len;
len = pathNodes._length;
for(i=1;i<len;i+=1){
//pathString += " C"+pathNodes.o[i-1][0]+','+pathNodes.o[i-1][1] + " "+pathNodes.i[i][0]+','+pathNodes.i[i][1] + " "+pathNodes.v[i][0]+','+pathNodes.v[i][1];
pathString += " C"+pathNodes.o[i-1][0]+','+pathNodes.o[i-1][1] + " "+pathNodes.i[i][0]+','+pathNodes.i[i][1] + " "+pathNodes.v[i][0]+','+pathNodes.v[i][1];
}
//pathString += " C"+pathNodes.o[i-1][0]+','+pathNodes.o[i-1][1] + " "+pathNodes.i[0][0]+','+pathNodes.i[0][1] + " "+pathNodes.v[0][0]+','+pathNodes.v[0][1];
if(pathNodes.c && len > 1){
pathString += " C"+pathNodes.o[i-1][0]+','+pathNodes.o[i-1][1] + " "+pathNodes.i[0][0]+','+pathNodes.i[0][1] + " "+pathNodes.v[0][0]+','+pathNodes.v[0][1];
}
//pathNodes.__renderedString = pathString;
if(viewData.lastPath !== pathString){
var pathShapeValue = '';
if(viewData.elem){
if(pathNodes.c){
pathShapeValue = pathData.inv ? this.solidPath + pathString : pathString;
}
viewData.elem.setAttribute('d',pathShapeValue);
}
viewData.lastPath = pathString;
}
};
MaskElement.prototype.destroy = function(){
this.element = null;
this.globalData = null;
this.maskElement = null;
this.data = null;
this.masksProperties = null;
};
/**
* @file
* Handles AE's layer parenting property.
*
*/
function HierarchyElement(){}
HierarchyElement.prototype = {
/**
* @function
* Initializes hierarchy properties
*
*/
initHierarchy: function() {
//element's parent list
this.hierarchy = [];
//if element is parent of another layer _isParent will be true
this._isParent = false;
this.checkParenting();
},
/**
* @function
* Sets layer's hierarchy.
* @param {array} hierarch
* layer's parent list
*
*/
setHierarchy: function(hierarchy){
this.hierarchy = hierarchy;
},
/**
* @function
* Sets layer as parent.
*
*/
setAsParent: function() {
this._isParent = true;
},
/**
* @function
* Searches layer's parenting chain
*
*/
checkParenting: function(){
if (this.data.parent !== undefined){
this.comp.buildElementParenting(this, this.data.parent, []);
}
}
};
/**
* @file
* Handles element's layer frame update.
* Checks layer in point and out point
*
*/
function FrameElement(){}
FrameElement.prototype = {
/**
* @function
* Initializes frame related properties.
*
*/
initFrame: function(){
//set to true when inpoint is rendered
this._isFirstFrame = false;
//list of animated properties
this.dynamicProperties = [];
// If layer has been modified in current tick this will be true
this._mdf = false;
},
/**
* @function
* Calculates all dynamic values
*
* @param {number} num
* current frame number in Layer's time
* @param {boolean} isVisible
* if layers is currently in range
*
*/
prepareProperties: function(num, isVisible) {
var i, len = this.dynamicProperties.length;
for (i = 0;i < len; i += 1) {
if (isVisible || (this._isParent && this.dynamicProperties[i].propType === 'transform')) {
this.dynamicProperties[i].getValue();
if (this.dynamicProperties[i]._mdf) {
this.globalData._mdf = true;
this._mdf = true;
}
}
}
},
addDynamicProperty: function(prop) {
if(this.dynamicProperties.indexOf(prop) === -1) {
this.dynamicProperties.push(prop);
}
}
};
function TransformElement(){}
TransformElement.prototype = {
initTransform: function() {
this.finalTransform = {
mProp: this.data.ks ? TransformPropertyFactory.getTransformProperty(this, this.data.ks, this) : {o:0},
_matMdf: false,
_opMdf: false,
mat: new Matrix()
};
if (this.data.ao) {
this.finalTransform.mProp.autoOriented = true;
}
//TODO: check TYPE 11: Guided elements
if (this.data.ty !== 11) {
//this.createElements();
}
},
renderTransform: function() {
this.finalTransform._opMdf = this.finalTransform.mProp.o._mdf || this._isFirstFrame;
this.finalTransform._matMdf = this.finalTransform.mProp._mdf || this._isFirstFrame;
if (this.hierarchy) {
var mat;
var finalMat = this.finalTransform.mat;
var i = 0, len = this.hierarchy.length;
//Checking if any of the transformation matrices in the hierarchy chain has changed.
if (!this.finalTransform._matMdf) {
while (i < len) {
if (this.hierarchy[i].finalTransform.mProp._mdf) {
this.finalTransform._matMdf = true;
break;
}
i += 1;
}
}
if (this.finalTransform._matMdf) {
mat = this.finalTransform.mProp.v.props;
finalMat.cloneFromProps(mat);
for (i = 0; i < len; i += 1) {
mat = this.hierarchy[i].finalTransform.mProp.v.props;
finalMat.transform(mat[0], mat[1], mat[2], mat[3], mat[4], mat[5], mat[6], mat[7], mat[8], mat[9], mat[10], mat[11], mat[12], mat[13], mat[14], mat[15]);
}
}
}
},
globalToLocal: function(pt) {
var transforms = [];
transforms.push(this.finalTransform);
var flag = true;
var comp = this.comp;
while (flag) {
if (comp.finalTransform) {
if (comp.data.hasMask) {
transforms.splice(0, 0, comp.finalTransform);
}
comp = comp.comp;
} else {
flag = false;
}
}
var i, len = transforms.length,ptNew;
for (i = 0; i < len; i += 1) {
ptNew = transforms[i].mat.applyToPointArray(0, 0, 0);
//ptNew = transforms[i].mat.applyToPointArray(pt[0],pt[1],pt[2]);
pt = [pt[0] - ptNew[0], pt[1] - ptNew[1], 0];
}
return pt;
},
mHelper: new Matrix()
};
function RenderableElement(){
}
RenderableElement.prototype = {
initRenderable: function() {
//layer's visibility related to inpoint and outpoint. Rename isVisible to isInRange
this.isInRange = false;
//layer's display state
this.hidden = false;
// If layer's transparency equals 0, it can be hidden
this.isTransparent = false;
//list of animated components
this.renderableComponents = [];
},
addRenderableComponent: function(component) {
if(this.renderableComponents.indexOf(component) === -1) {
this.renderableComponents.push(component);
}
},
removeRenderableComponent: function(component) {
if(this.renderableComponents.indexOf(component) !== -1) {
this.renderableComponents.splice(this.renderableComponents.indexOf(component), 1);
}
},
prepareRenderableFrame: function(num) {
this.checkLayerLimits(num);
},
checkTransparency: function(){
if(this.finalTransform.mProp.o.v <= 0) {
if(!this.isTransparent && this.globalData.renderConfig.hideOnTransparent){
this.isTransparent = true;
this.hide();
}
} else if(this.isTransparent) {
this.isTransparent = false;
this.show();
}
},
/**
* @function
* Initializes frame related properties.
*
* @param {number} num
* current frame number in Layer's time
*
*/
checkLayerLimits: function(num) {
if(this.data.ip - this.data.st <= num && this.data.op - this.data.st > num)
{
if(this.isInRange !== true){
this.globalData._mdf = true;
this._mdf = true;
this.isInRange = true;
this.show();
}
} else {
if(this.isInRange !== false){
this.globalData._mdf = true;
this.isInRange = false;
this.hide();
}
}
},
renderRenderable: function() {
var i, len = this.renderableComponents.length;
for(i = 0; i < len; i += 1) {
this.renderableComponents[i].renderFrame(this._isFirstFrame);
}
/*this.maskManager.renderFrame(this.finalTransform.mat);
this.renderableEffectsManager.renderFrame(this._isFirstFrame);*/
},
sourceRectAtTime: function(){
return {
top:0,
left:0,
width:100,
height:100
};
},
getLayerSize: function(){
if(this.data.ty === 5){
return {w:this.data.textData.width,h:this.data.textData.height};
}else{
return {w:this.data.width,h:this.data.height};
}
}
};
function RenderableDOMElement() {}
(function(){
var _prototype = {
initElement: function(data,globalData,comp) {
this.initFrame();
this.initBaseData(data, globalData, comp);
this.initTransform(data, globalData, comp);
this.initHierarchy();
this.initRenderable();
this.initRendererElement();
this.createContainerElements();
this.addMasks();
this.createContent();
this.hide();
},
hide: function(){
if (!this.hidden && (!this.isInRange || this.isTransparent)) {
var elem = this.baseElement || this.layerElement;
elem.style.display = 'none';
this.hidden = true;
}
},
show: function(){
if (this.isInRange && !this.isTransparent){
if (!this.data.hd) {
var elem = this.baseElement || this.layerElement;
elem.style.display = 'block';
}
this.hidden = false;
this._isFirstFrame = true;
}
},
renderFrame: function() {
//If it is exported as hidden (data.hd === true) no need to render
//If it is not visible no need to render
if (this.data.hd || this.hidden) {
return;
}
this.renderTransform();
this.renderRenderable();
this.renderElement();
this.renderInnerContent();
if (this._isFirstFrame) {
this._isFirstFrame = false;
}
},
renderInnerContent: function() {},
prepareFrame: function(num) {
this._mdf = false;
this.prepareRenderableFrame(num);
this.prepareProperties(num, this.isInRange);
this.checkTransparency();
},
destroy: function(){
this.innerElem = null;
this.destroyBaseElement();
}
};
extendPrototype([RenderableElement, createProxyFunction(_prototype)], RenderableDOMElement);
}());
function ProcessedElement(element, position) {
this.elem = element;
this.pos = position;
}
function SVGStyleData(data, level) {
this.data = data;
this.type = data.ty;
this.d = '';
this.lvl = level;
this._mdf = false;
this.closed = false;
this.pElem = createNS('path');
this.msElem = null;
}
SVGStyleData.prototype.reset = function() {
this.d = '';
this._mdf = false;
};
function SVGShapeData(transformers, level, shape) {
this.caches = [];
this.styles = [];
this.transformers = transformers;
this.lStr = '';
this.sh = shape;
this.lvl = level;
//TODO find if there are some cases where _isAnimated can be false.
// For now, since shapes add up with other shapes. They have to be calculated every time.
// One way of finding out is checking if all styles associated to this shape depend only of this shape
this._isAnimated = !!shape.k;
// TODO: commenting this for now since all shapes are animated
var i = 0, len = transformers.length;
while(i < len) {
if(transformers[i].mProps.dynamicProperties.length) {
this._isAnimated = true;
break;
}
i += 1;
}
}
SVGShapeData.prototype.setAsAnimated = function() {
this._isAnimated = true;
}
function SVGTransformData(mProps, op, container) {
this.transform = {
mProps: mProps,
op: op,
container: container
};
this.elements = [];
this._isAnimated = this.transform.mProps.dynamicProperties.length || this.transform.op.effectsSequence.length;
}
function SVGStrokeStyleData(elem, data, styleOb){
this.initDynamicPropertyContainer(elem);
this.getValue = this.iterateDynamicProperties;
this.o = PropertyFactory.getProp(elem,data.o,0,0.01,this);
this.w = PropertyFactory.getProp(elem,data.w,0,null,this);
this.d = new DashProperty(elem,data.d||{},'svg',this);
this.c = PropertyFactory.getProp(elem,data.c,1,255,this);
this.style = styleOb;
this._isAnimated = !!this._isAnimated;
}
extendPrototype([DynamicPropertyContainer], SVGStrokeStyleData);
function SVGFillStyleData(elem, data, styleOb){
this.initDynamicPropertyContainer(elem);
this.getValue = this.iterateDynamicProperties;
this.o = PropertyFactory.getProp(elem,data.o,0,0.01,this);
this.c = PropertyFactory.getProp(elem,data.c,1,255,this);
this.style = styleOb;
}
extendPrototype([DynamicPropertyContainer], SVGFillStyleData);
function SVGGradientFillStyleData(elem, data, styleOb){
this.initDynamicPropertyContainer(elem);
this.getValue = this.iterateDynamicProperties;
this.initGradientData(elem, data, styleOb);
}
SVGGradientFillStyleData.prototype.initGradientData = function(elem, data, styleOb){
this.o = PropertyFactory.getProp(elem,data.o,0,0.01,this);
this.s = PropertyFactory.getProp(elem,data.s,1,null,this);
this.e = PropertyFactory.getProp(elem,data.e,1,null,this);
this.h = PropertyFactory.getProp(elem,data.h||{k:0},0,0.01,this);
this.a = PropertyFactory.getProp(elem,data.a||{k:0},0,degToRads,this);
this.g = new GradientProperty(elem,data.g,this);
this.style = styleOb;
this.stops = [];
this.setGradientData(styleOb.pElem, data);
this.setGradientOpacity(data, styleOb);
this._isAnimated = !!this._isAnimated;
};
SVGGradientFillStyleData.prototype.setGradientData = function(pathElement,data){
var gradientId = 'gr_'+randomString(10);
var gfill = createNS(data.t === 1 ? 'linearGradient' : 'radialGradient');
gfill.setAttribute('id',gradientId);
gfill.setAttribute('spreadMethod','pad');
gfill.setAttribute('gradientUnits','userSpaceOnUse');
var stops = [];
var stop, j, jLen;
jLen = data.g.p*4;
for(j=0;j<jLen;j+=4){
stop = createNS('stop');
gfill.appendChild(stop);
stops.push(stop);
}
pathElement.setAttribute( data.ty === 'gf' ? 'fill':'stroke','url(#'+gradientId+')');
this.gf = gfill;
this.cst = stops;
};
SVGGradientFillStyleData.prototype.setGradientOpacity = function(data, styleOb){
if(this.g._hasOpacity && !this.g._collapsable){
var stop, j, jLen;
var mask = createNS("mask");
var maskElement = createNS( 'path');
mask.appendChild(maskElement);
var opacityId = 'op_'+randomString(10);
var maskId = 'mk_'+randomString(10);
mask.setAttribute('id',maskId);
var opFill = createNS(data.t === 1 ? 'linearGradient' : 'radialGradient');
opFill.setAttribute('id',opacityId);
opFill.setAttribute('spreadMethod','pad');
opFill.setAttribute('gradientUnits','userSpaceOnUse');
jLen = data.g.k.k[0].s ? data.g.k.k[0].s.length : data.g.k.k.length;
var stops = this.stops;
for(j=data.g.p*4;j<jLen;j+=2){
stop = createNS('stop');
stop.setAttribute('stop-color','rgb(255,255,255)');
opFill.appendChild(stop);
stops.push(stop);
}
maskElement.setAttribute( data.ty === 'gf' ? 'fill':'stroke','url(#'+opacityId+')');
this.of = opFill;
this.ms = mask;
this.ost = stops;
this.maskId = maskId;
styleOb.msElem = maskElement;
}
};
extendPrototype([DynamicPropertyContainer], SVGGradientFillStyleData);
function SVGGradientStrokeStyleData(elem, data, styleOb){
this.initDynamicPropertyContainer(elem);
this.getValue = this.iterateDynamicProperties;
this.w = PropertyFactory.getProp(elem,data.w,0,null,this);
this.d = new DashProperty(elem,data.d||{},'svg',this);
this.initGradientData(elem, data, styleOb);
this._isAnimated = !!this._isAnimated;
}
extendPrototype([SVGGradientFillStyleData, DynamicPropertyContainer], SVGGradientStrokeStyleData);
function ShapeGroupData() {
this.it = [];
this.prevViewData = [];
this.gr = createNS('g');
}
var SVGElementsRenderer = (function() {
var _identityMatrix = new Matrix();
var _matrixHelper = new Matrix();
var ob = {
createRenderFunction: createRenderFunction
}
function createRenderFunction(data) {
var ty = data.ty;
switch(data.ty) {
case 'fl':
return renderFill;
case 'gf':
return renderGradient;
case 'gs':
return renderGradientStroke;
case 'st':
return renderStroke;
case 'sh':
case 'el':
case 'rc':
case 'sr':
return renderPath;
case 'tr':
return renderContentTransform;
}
}
function renderContentTransform(styleData, itemData, isFirstFrame) {
if(isFirstFrame || itemData.transform.op._mdf){
itemData.transform.container.setAttribute('opacity',itemData.transform.op.v);
}
if(isFirstFrame || itemData.transform.mProps._mdf){
itemData.transform.container.setAttribute('transform',itemData.transform.mProps.v.to2dCSS());
}
}
function renderPath(styleData, itemData, isFirstFrame) {
var j, jLen,pathStringTransformed,redraw,pathNodes,l, lLen = itemData.styles.length;
var lvl = itemData.lvl;
var paths, mat, props, iterations, k;
for(l=0;l<lLen;l+=1){
redraw = itemData.sh._mdf || isFirstFrame;
if(itemData.styles[l].lvl < lvl){
mat = _matrixHelper.reset();
iterations = lvl - itemData.styles[l].lvl;
k = itemData.transformers.length-1;
while(!redraw && iterations > 0) {
redraw = itemData.transformers[k].mProps._mdf || redraw;
iterations --;
k --;
}
if(redraw) {
iterations = lvl - itemData.styles[l].lvl;
k = itemData.transformers.length-1;
while(iterations > 0) {
props = itemData.transformers[k].mProps.v.props;
mat.transform(props[0],props[1],props[2],props[3],props[4],props[5],props[6],props[7],props[8],props[9],props[10],props[11],props[12],props[13],props[14],props[15]);
iterations --;
k --;
}
}
} else {
mat = _identityMatrix;
}
paths = itemData.sh.paths;
jLen = paths._length;
if(redraw){
pathStringTransformed = '';
for(j=0;j<jLen;j+=1){
pathNodes = paths.shapes[j];
if(pathNodes && pathNodes._length){
pathStringTransformed += buildShapeString(pathNodes, pathNodes._length, pathNodes.c, mat);
}
}
itemData.caches[l] = pathStringTransformed;
} else {
pathStringTransformed = itemData.caches[l];
}
itemData.styles[l].d += pathStringTransformed;
itemData.styles[l]._mdf = redraw || itemData.styles[l]._mdf;
}
}
function renderFill (styleData,itemData, isFirstFrame){
var styleElem = itemData.style;
if(itemData.c._mdf || isFirstFrame){
styleElem.pElem.setAttribute('fill','rgb('+bm_floor(itemData.c.v[0])+','+bm_floor(itemData.c.v[1])+','+bm_floor(itemData.c.v[2])+')');
}
if(itemData.o._mdf || isFirstFrame){
styleElem.pElem.setAttribute('fill-opacity',itemData.o.v);
}
};
function renderGradientStroke (styleData, itemData, isFirstFrame) {
renderGradient(styleData, itemData, isFirstFrame);
renderStroke(styleData, itemData, isFirstFrame);
}
function renderGradient(styleData, itemData, isFirstFrame) {
var gfill = itemData.gf;
var hasOpacity = itemData.g._hasOpacity;
var pt1 = itemData.s.v, pt2 = itemData.e.v;
if (itemData.o._mdf || isFirstFrame) {
var attr = styleData.ty === 'gf' ? 'fill-opacity' : 'stroke-opacity';
itemData.style.pElem.setAttribute(attr, itemData.o.v);
}
if (itemData.s._mdf || isFirstFrame) {
var attr1 = styleData.t === 1 ? 'x1' : 'cx';
var attr2 = attr1 === 'x1' ? 'y1' : 'cy';
gfill.setAttribute(attr1, pt1[0]);
gfill.setAttribute(attr2, pt1[1]);
if (hasOpacity && !itemData.g._collapsable) {
itemData.of.setAttribute(attr1, pt1[0]);
itemData.of.setAttribute(attr2, pt1[1]);
}
}
var stops, i, len, stop;
if (itemData.g._cmdf || isFirstFrame) {
stops = itemData.cst;
var cValues = itemData.g.c;
len = stops.length;
for (i = 0; i < len; i += 1){
stop = stops[i];
stop.setAttribute('offset', cValues[i * 4] + '%');
stop.setAttribute('stop-color','rgb('+ cValues[i * 4 + 1] + ',' + cValues[i * 4 + 2] + ','+cValues[i * 4 + 3] + ')');
}
}
if (hasOpacity && (itemData.g._omdf || isFirstFrame)) {
var oValues = itemData.g.o;
if(itemData.g._collapsable) {
stops = itemData.cst;
} else {
stops = itemData.ost;
}
len = stops.length;
for (i = 0; i < len; i += 1) {
stop = stops[i];
if(!itemData.g._collapsable) {
stop.setAttribute('offset', oValues[i * 2] + '%');
}
stop.setAttribute('stop-opacity', oValues[i * 2 + 1]);
}
}
if (styleData.t === 1) {
if (itemData.e._mdf || isFirstFrame) {
gfill.setAttribute('x2', pt2[0]);
gfill.setAttribute('y2', pt2[1]);
if (hasOpacity && !itemData.g._collapsable) {
itemData.of.setAttribute('x2', pt2[0]);
itemData.of.setAttribute('y2', pt2[1]);
}
}
} else {
var rad;
if (itemData.s._mdf || itemData.e._mdf || isFirstFrame) {
rad = Math.sqrt(Math.pow(pt1[0] - pt2[0], 2) + Math.pow(pt1[1] - pt2[1], 2));
gfill.setAttribute('r', rad);
if(hasOpacity && !itemData.g._collapsable){
itemData.of.setAttribute('r', rad);
}
}
if (itemData.e._mdf || itemData.h._mdf || itemData.a._mdf || isFirstFrame) {
if (!rad) {
rad = Math.sqrt(Math.pow(pt1[0] - pt2[0], 2) + Math.pow(pt1[1] - pt2[1], 2));
}
var ang = Math.atan2(pt2[1] - pt1[1], pt2[0] - pt1[0]);
var percent = itemData.h.v >= 1 ? 0.99 : itemData.h.v <= -1 ? -0.99: itemData.h.v;
var dist = rad * percent;
var x = Math.cos(ang + itemData.a.v) * dist + pt1[0];
var y = Math.sin(ang + itemData.a.v) * dist + pt1[1];
gfill.setAttribute('fx', x);
gfill.setAttribute('fy', y);
if (hasOpacity && !itemData.g._collapsable) {
itemData.of.setAttribute('fx', x);
itemData.of.setAttribute('fy', y);
}
}
//gfill.setAttribute('fy','200');
}
};
function renderStroke(styleData, itemData, isFirstFrame) {
var styleElem = itemData.style;
var d = itemData.d;
if (d && (d._mdf || isFirstFrame) && d.dashStr) {
styleElem.pElem.setAttribute('stroke-dasharray', d.dashStr);
styleElem.pElem.setAttribute('stroke-dashoffset', d.dashoffset[0]);
}
if(itemData.c && (itemData.c._mdf || isFirstFrame)){
styleElem.pElem.setAttribute('stroke','rgb(' + bm_floor(itemData.c.v[0]) + ',' + bm_floor(itemData.c.v[1]) + ',' + bm_floor(itemData.c.v[2]) + ')');
}
if(itemData.o._mdf || isFirstFrame){
styleElem.pElem.setAttribute('stroke-opacity', itemData.o.v);
}
if(itemData.w._mdf || isFirstFrame){
styleElem.pElem.setAttribute('stroke-width', itemData.w.v);
if(styleElem.msElem){
styleElem.msElem.setAttribute('stroke-width', itemData.w.v);
}
}
};
return ob;
}())
function BaseElement(){
}
BaseElement.prototype = {
checkMasks: function(){
if(!this.data.hasMask){
return false;
}
var i = 0, len = this.data.masksProperties.length;
while(i<len) {
if((this.data.masksProperties[i].mode !== 'n' && this.data.masksProperties[i].cl !== false)) {
return true;
}
i += 1;
}
return false;
},
initExpressions: function(){
this.layerInterface = LayerExpressionInterface(this);
if(this.data.hasMask && this.maskManager) {
this.layerInterface.registerMaskInterface(this.maskManager);
}
var effectsInterface = EffectsExpressionInterface.createEffectsInterface(this,this.layerInterface);
this.layerInterface.registerEffectsInterface(effectsInterface);
if(this.data.ty === 0 || this.data.xt){
this.compInterface = CompExpressionInterface(this);
} else if(this.data.ty === 4){
this.layerInterface.shapeInterface = ShapeExpressionInterface(this.shapesData,this.itemsData,this.layerInterface);
this.layerInterface.content = this.layerInterface.shapeInterface;
} else if(this.data.ty === 5){
this.layerInterface.textInterface = TextExpressionInterface(this);
this.layerInterface.text = this.layerInterface.textInterface;
}
},
blendModeEnums: {
1:'multiply',
2:'screen',
3:'overlay',
4:'darken',
5:'lighten',
6:'color-dodge',
7:'color-burn',
8:'hard-light',
9:'soft-light',
10:'difference',
11:'exclusion',
12:'hue',
13:'saturation',
14:'color',
15:'luminosity'
},
getBlendMode: function(){
return this.blendModeEnums[this.data.bm] || '';
},
setBlendMode: function(){
var blendModeValue = this.getBlendMode();
var elem = this.baseElement || this.layerElement;
elem.style['mix-blend-mode'] = blendModeValue;
},
initBaseData: function(data, globalData, comp){
this.globalData = globalData;
this.comp = comp;
this.data = data;
this.layerId = 'ly_'+randomString(10);
//Stretch factor for old animations missing this property.
if(!this.data.sr){
this.data.sr = 1;
}
// effects manager
this.effectsManager = new EffectsManager(this.data,this,this.dynamicProperties);
},
getType: function(){
return this.type;
}
}
function NullElement(data,globalData,comp){
this.initFrame();
this.initBaseData(data, globalData, comp);
this.initFrame();
this.initTransform(data, globalData, comp);
this.initHierarchy();
}
NullElement.prototype.prepareFrame = function(num) {
this.prepareProperties(num, true);
};
NullElement.prototype.renderFrame = function() {
};
NullElement.prototype.getBaseElement = function() {
return null;
};
NullElement.prototype.destroy = function() {
};
NullElement.prototype.sourceRectAtTime = function() {
};
NullElement.prototype.hide = function() {
};
extendPrototype([BaseElement,TransformElement,HierarchyElement,FrameElement], NullElement);
function SVGBaseElement(){
}
SVGBaseElement.prototype = {
initRendererElement: function() {
this.layerElement = createNS('g');
},
createContainerElements: function(){
this.matteElement = createNS('g');
this.transformedElement = this.layerElement;
this.maskedElement = this.layerElement;
this._sizeChanged = false;
var layerElementParent = null;
//If this layer acts as a mask for the following layer
var filId, fil, gg;
if (this.data.td) {
if (this.data.td == 3 || this.data.td == 1) {
var masker = createNS('mask');
masker.setAttribute('id', this.layerId);
masker.setAttribute('mask-type', this.data.td == 3 ? 'luminance' : 'alpha');
masker.appendChild(this.layerElement);
layerElementParent = masker;
this.globalData.defs.appendChild(masker);
// This is only for IE and Edge when mask if of type alpha
if (!featureSupport.maskType && this.data.td == 1) {
masker.setAttribute('mask-type', 'luminance');
filId = randomString(10);
fil = filtersFactory.createFilter(filId);
this.globalData.defs.appendChild(fil);
fil.appendChild(filtersFactory.createAlphaToLuminanceFilter());
gg = createNS('g');
gg.appendChild(this.layerElement);
layerElementParent = gg;
masker.appendChild(gg);
gg.setAttribute('filter','url(' + locationHref + '#' + filId + ')');
}
} else if(this.data.td == 2) {
var maskGroup = createNS('mask');
maskGroup.setAttribute('id', this.layerId);
maskGroup.setAttribute('mask-type','alpha');
var maskGrouper = createNS('g');
maskGroup.appendChild(maskGrouper);
filId = randomString(10);
fil = filtersFactory.createFilter(filId);
////
var feColorMatrix = createNS('feColorMatrix');
feColorMatrix.setAttribute('type', 'matrix');
feColorMatrix.setAttribute('color-interpolation-filters', 'sRGB');
feColorMatrix.setAttribute('values','1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 -1 1');
fil.appendChild(feColorMatrix);
////
/*var feCTr = createNS('feComponentTransfer');
feCTr.setAttribute('in','SourceGraphic');
fil.appendChild(feCTr);
var feFunc = createNS('feFuncA');
feFunc.setAttribute('type','table');
feFunc.setAttribute('tableValues','1.0 0.0');
feCTr.appendChild(feFunc);*/
this.globalData.defs.appendChild(fil);
var alphaRect = createNS('rect');
alphaRect.setAttribute('width', this.comp.data.w);
alphaRect.setAttribute('height', this.comp.data.h);
alphaRect.setAttribute('x','0');
alphaRect.setAttribute('y','0');
alphaRect.setAttribute('fill','#ffffff');
alphaRect.setAttribute('opacity','0');
maskGrouper.setAttribute('filter', 'url(' + locationHref + '#'+filId+')');
maskGrouper.appendChild(alphaRect);
maskGrouper.appendChild(this.layerElement);
layerElementParent = maskGrouper;
if (!featureSupport.maskType) {
maskGroup.setAttribute('mask-type', 'luminance');
fil.appendChild(filtersFactory.createAlphaToLuminanceFilter());
gg = createNS('g');
maskGrouper.appendChild(alphaRect);
gg.appendChild(this.layerElement);
layerElementParent = gg;
maskGrouper.appendChild(gg);
}
this.globalData.defs.appendChild(maskGroup);
}
} else if (this.data.tt) {
this.matteElement.appendChild(this.layerElement);
layerElementParent = this.matteElement;
this.baseElement = this.matteElement;
} else {
this.baseElement = this.layerElement;
}
if (this.data.ln) {
this.layerElement.setAttribute('id', this.data.ln);
}
if (this.data.cl) {
this.layerElement.setAttribute('class', this.data.cl);
}
//Clipping compositions to hide content that exceeds boundaries. If collapsed transformations is on, component should not be clipped
if (this.data.ty === 0 && !this.data.hd) {
var cp = createNS( 'clipPath');
var pt = createNS('path');
pt.setAttribute('d','M0,0 L' + this.data.w + ',0' + ' L' + this.data.w + ',' + this.data.h + ' L0,' + this.data.h + 'z');
var clipId = 'cp_'+randomString(8);
cp.setAttribute('id',clipId);
cp.appendChild(pt);
this.globalData.defs.appendChild(cp);
if (this.checkMasks()) {
var cpGroup = createNS('g');
cpGroup.setAttribute('clip-path','url(' + locationHref + '#'+clipId + ')');
cpGroup.appendChild(this.layerElement);
this.transformedElement = cpGroup;
if (layerElementParent) {
layerElementParent.appendChild(this.transformedElement);
} else {
this.baseElement = this.transformedElement;
}
} else {
this.layerElement.setAttribute('clip-path','url(' + locationHref + '#'+clipId+')');
}
}
if (this.data.bm !== 0) {
this.setBlendMode();
}
this.renderableEffectsManager = new SVGEffects(this);
},
renderElement: function() {
if (this.finalTransform._matMdf) {
this.transformedElement.setAttribute('transform', this.finalTransform.mat.to2dCSS());
}
if (this.finalTransform._opMdf) {
this.transformedElement.setAttribute('opacity', this.finalTransform.mProp.o.v);
}
},
destroyBaseElement: function() {
this.layerElement = null;
this.matteElement = null;
this.maskManager.destroy();
},
getBaseElement: function() {
if (this.data.hd) {
return null;
}
return this.baseElement;
},
addMasks: function() {
this.maskManager = new MaskElement(this.data, this, this.globalData);
},
setMatte: function(id) {
if (!this.matteElement) {
return;
}
this.matteElement.setAttribute("mask", "url(" + locationHref + "#" + id + ")");
}
};
function IShapeElement(){
}
IShapeElement.prototype = {
addShapeToModifiers: function(data) {
var i, len = this.shapeModifiers.length;
for(i=0;i<len;i+=1){
this.shapeModifiers[i].addShape(data);
}
},
isShapeInAnimatedModifiers: function(data) {
var i = 0, len = this.shapeModifiers.length;
while(i < len) {
if(this.shapeModifiers[i].isAnimatedWithShape(data)) {
return true;
}
}
return false;
},
renderModifiers: function() {
if(!this.shapeModifiers.length){
return;
}
var i, len = this.shapes.length;
for(i=0;i<len;i+=1){
this.shapes[i].sh.reset();
}
len = this.shapeModifiers.length;
for(i=len-1;i>=0;i-=1){
this.shapeModifiers[i].processShapes(this._isFirstFrame);
}
},
lcEnum: {
'1': 'butt',
'2': 'round',
'3': 'square'
},
ljEnum: {
'1': 'miter',
'2': 'round',
'3': 'butt'
},
searchProcessedElement: function(elem){
var elements = this.processedElements;
var i = 0, len = elements.length;
while(i < len){
if(elements[i].elem === elem){
return elements[i].pos;
}
i += 1;
}
return 0;
},
addProcessedElement: function(elem, pos){
var elements = this.processedElements;
var i = elements.length;
while(i){
i -= 1;
if(elements[i].elem === elem){
elements[i].pos = pos;
return;
}
}
elements.push(new ProcessedElement(elem, pos));
},
prepareFrame: function(num) {
this.prepareRenderableFrame(num);
this.prepareProperties(num, this.isInRange);
}
};
function ITextElement(){
}
ITextElement.prototype.initElement = function(data,globalData,comp){
this.lettersChangedFlag = true;
this.initFrame();
this.initBaseData(data, globalData, comp);
this.textProperty = new TextProperty(this, data.t, this.dynamicProperties);
this.textAnimator = new TextAnimatorProperty(data.t, this.renderType, this);
this.initTransform(data, globalData, comp);
this.initHierarchy();
this.initRenderable();
this.initRendererElement();
this.createContainerElements();
this.addMasks();
this.createContent();
this.hide();
this.textAnimator.searchProperties(this.dynamicProperties);
};
ITextElement.prototype.prepareFrame = function(num) {
this._mdf = false;
this.prepareRenderableFrame(num);
this.prepareProperties(num, this.isInRange);
if(this.textProperty._mdf || this.textProperty._isFirstFrame) {
this.buildNewText();
this.textProperty._isFirstFrame = false;
this.textProperty._mdf = false;
}
};
ITextElement.prototype.createPathShape = function(matrixHelper, shapes) {
var j,jLen = shapes.length;
var k, kLen, pathNodes;
var shapeStr = '';
for(j=0;j<jLen;j+=1){
pathNodes = shapes[j].ks.k;
shapeStr += buildShapeString(pathNodes, pathNodes.i.length, true, matrixHelper);
}
return shapeStr;
};
ITextElement.prototype.updateDocumentData = function(newData, index) {
this.textProperty.updateDocumentData(newData, index);
};
ITextElement.prototype.canResizeFont = function(_canResize) {
this.textProperty.canResizeFont(_canResize);
};
ITextElement.prototype.setMinimumFontSize = function(_fontSize) {
this.textProperty.setMinimumFontSize(_fontSize);
};
ITextElement.prototype.applyTextPropertiesToMatrix = function(documentData, matrixHelper, lineNumber, xPos, yPos) {
if(documentData.ps){
matrixHelper.translate(documentData.ps[0],documentData.ps[1] + documentData.ascent,0);
}
matrixHelper.translate(0,-documentData.ls,0);
switch(documentData.j){
case 1:
matrixHelper.translate(documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[lineNumber]),0,0);
break;
case 2:
matrixHelper.translate(documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[lineNumber] )/2,0,0);
break;
}
matrixHelper.translate(xPos, yPos, 0);
};
ITextElement.prototype.buildColor = function(colorData) {
return 'rgb(' + Math.round(colorData[0]*255) + ',' + Math.round(colorData[1]*255) + ',' + Math.round(colorData[2]*255) + ')';
};
ITextElement.prototype.emptyProp = new LetterProps();
ITextElement.prototype.destroy = function(){
};
function ICompElement(){}
extendPrototype([BaseElement, TransformElement, HierarchyElement, FrameElement, RenderableDOMElement], ICompElement);
ICompElement.prototype.initElement = function(data,globalData,comp) {
this.initFrame();
this.initBaseData(data, globalData, comp);
this.initTransform(data, globalData, comp);
this.initRenderable();
this.initHierarchy();
this.initRendererElement();
this.createContainerElements();
this.addMasks();
if(this.data.xt || !globalData.progressiveLoad){
this.buildAllItems();
}
this.hide();
};
/*ICompElement.prototype.hide = function(){
if(!this.hidden){
this.hideElement();
var i,len = this.elements.length;
for( i = 0; i < len; i+=1 ){
if(this.elements[i]){
this.elements[i].hide();
}
}
}
};*/
ICompElement.prototype.prepareFrame = function(num){
this._mdf = false;
this.prepareRenderableFrame(num);
this.prepareProperties(num, this.isInRange);
if(!this.isInRange && !this.data.xt){
return;
}
if (!this.tm._placeholder) {
var timeRemapped = this.tm.v;
if(timeRemapped === this.data.op){
timeRemapped = this.data.op - 1;
}
this.renderedFrame = timeRemapped;
} else {
this.renderedFrame = num/this.data.sr;
}
var i,len = this.elements.length;
if(!this.completeLayers){
this.checkLayers(this.renderedFrame);
}
for( i = 0; i < len; i+=1 ){
if(this.completeLayers || this.elements[i]){
this.elements[i].prepareFrame(this.renderedFrame - this.layers[i].st);
if(this.elements[i]._mdf) {
this._mdf = true;
}
}
}
};
ICompElement.prototype.renderInnerContent = function() {
var i,len = this.layers.length;
for( i = 0; i < len; i += 1 ){
if(this.completeLayers || this.elements[i]){
this.elements[i].renderFrame();
}
}
};
ICompElement.prototype.setElements = function(elems){
this.elements = elems;
};
ICompElement.prototype.getElements = function(){
return this.elements;
};
ICompElement.prototype.destroyElements = function(){
var i,len = this.layers.length;
for( i = 0; i < len; i+=1 ){
if(this.elements[i]){
this.elements[i].destroy();
}
}
};
ICompElement.prototype.destroy = function(){
this.destroyElements();
this.destroyBaseElement();
};
function IImageElement(data,globalData,comp){
this.assetData = globalData.getAssetData(data.refId);
this.initElement(data,globalData,comp);
}
extendPrototype([BaseElement,TransformElement,SVGBaseElement,HierarchyElement,FrameElement,RenderableDOMElement], IImageElement);
IImageElement.prototype.createContent = function(){
var assetPath = this.globalData.getAssetsPath(this.assetData);
this.innerElem = createNS('image');
this.innerElem.setAttribute('width',this.assetData.w+"px");
this.innerElem.setAttribute('height',this.assetData.h+"px");
this.innerElem.setAttribute('preserveAspectRatio','xMidYMid slice');
this.innerElem.setAttributeNS('http://www.w3.org/1999/xlink','href',assetPath);
this.layerElement.appendChild(this.innerElem);
};
function ISolidElement(data,globalData,comp){
this.initElement(data,globalData,comp);
}
extendPrototype([IImageElement], ISolidElement);
ISolidElement.prototype.createContent = function(){
var rect = createNS('rect');
////rect.style.width = this.data.sw;
////rect.style.height = this.data.sh;
////rect.style.fill = this.data.sc;
rect.setAttribute('width',this.data.sw);
rect.setAttribute('height',this.data.sh);
rect.setAttribute('fill',this.data.sc);
this.layerElement.appendChild(rect);
};
function SVGCompElement(data,globalData,comp){
this.layers = data.layers;
this.supports3d = true;
this.completeLayers = false;
this.pendingElements = [];
this.elements = this.layers ? createSizedArray(this.layers.length) : [];
//this.layerElement = createNS('g');
this.initElement(data,globalData,comp);
this.tm = data.tm ? PropertyFactory.getProp(this,data.tm,0,globalData.frameRate,this) : {_placeholder:true};
}
extendPrototype([SVGRenderer, ICompElement, SVGBaseElement], SVGCompElement);
function SVGTextElement(data,globalData,comp){
this.textSpans = [];
this.renderType = 'svg';
this.initElement(data,globalData,comp);
}
extendPrototype([BaseElement,TransformElement,SVGBaseElement,HierarchyElement,FrameElement,RenderableDOMElement,ITextElement], SVGTextElement);
SVGTextElement.prototype.createContent = function(){
if (this.data.singleShape && !this.globalData.fontManager.chars) {
this.textContainer = createNS('text');
}
};
SVGTextElement.prototype.buildTextContents = function(textArray) {
var i = 0, len = textArray.length;
var textContents = [], currentTextContent = '';
while (i < len) {
if(textArray[i] === String.fromCharCode(13)) {
textContents.push(currentTextContent);
currentTextContent = '';
} else {
currentTextContent += textArray[i];
}
i += 1;
}
textContents.push(currentTextContent);
return textContents;
}
SVGTextElement.prototype.buildNewText = function(){
var i, len;
var documentData = this.textProperty.currentData;
this.renderedLetters = createSizedArray(documentData ? documentData.l.length : 0);
if(documentData.fc) {
this.layerElement.setAttribute('fill', this.buildColor(documentData.fc));
}else{
this.layerElement.setAttribute('fill', 'rgba(0,0,0,0)');
}
if(documentData.sc){
this.layerElement.setAttribute('stroke', this.buildColor(documentData.sc));
this.layerElement.setAttribute('stroke-width', documentData.sw);
}
this.layerElement.setAttribute('font-size', documentData.finalSize);
var fontData = this.globalData.fontManager.getFontByName(documentData.f);
if(fontData.fClass){
this.layerElement.setAttribute('class',fontData.fClass);
} else {
this.layerElement.setAttribute('font-family', fontData.fFamily);
var fWeight = documentData.fWeight, fStyle = documentData.fStyle;
this.layerElement.setAttribute('font-style', fStyle);
this.layerElement.setAttribute('font-weight', fWeight);
}
var letters = documentData.l || [];
var usesGlyphs = this.globalData.fontManager.chars;
len = letters.length;
if(!len){
return;
}
var tSpan;
var matrixHelper = this.mHelper;
var shapes, shapeStr = '', singleShape = this.data.singleShape;
var xPos = 0, yPos = 0, firstLine = true;
var trackingOffset = documentData.tr/1000*documentData.finalSize;
if(singleShape && !usesGlyphs && !documentData.sz) {
var tElement = this.textContainer;
var justify = 'start';
switch(documentData.j) {
case 1:
justify = 'end';
break;
case 2:
justify = 'middle';
break;
}
tElement.setAttribute('text-anchor',justify);
tElement.setAttribute('letter-spacing',trackingOffset);
var textContent = this.buildTextContents(documentData.finalText);
len = textContent.length;
yPos = documentData.ps ? documentData.ps[1] + documentData.ascent : 0;
for ( i = 0; i < len; i += 1) {
tSpan = this.textSpans[i] || createNS('tspan');
tSpan.textContent = textContent[i];
tSpan.setAttribute('x', 0);
tSpan.setAttribute('y', yPos);
tSpan.style.display = 'inherit';
tElement.appendChild(tSpan);
this.textSpans[i] = tSpan;
yPos += documentData.finalLineHeight;
}
this.layerElement.appendChild(tElement);
} else {
var cachedSpansLength = this.textSpans.length;
var shapeData, charData;
for (i = 0; i < len; i += 1) {
if(!usesGlyphs || !singleShape || i === 0){
tSpan = cachedSpansLength > i ? this.textSpans[i] : createNS(usesGlyphs?'path':'text');
if (cachedSpansLength <= i) {
tSpan.setAttribute('stroke-linecap', 'butt');
tSpan.setAttribute('stroke-linejoin','round');
tSpan.setAttribute('stroke-miterlimit','4');
this.textSpans[i] = tSpan;
this.layerElement.appendChild(tSpan);
}
tSpan.style.display = 'inherit';
}
matrixHelper.reset();
matrixHelper.scale(documentData.finalSize / 100, documentData.finalSize / 100);
if (singleShape) {
if(letters[i].n) {
xPos = -trackingOffset;
yPos += documentData.yOffset;
yPos += firstLine ? 1 : 0;
firstLine = false;
}
this.applyTextPropertiesToMatrix(documentData, matrixHelper, letters[i].line, xPos, yPos);
xPos += letters[i].l || 0;
//xPos += letters[i].val === ' ' ? 0 : trackingOffset;
xPos += trackingOffset;
}
if(usesGlyphs) {
charData = this.globalData.fontManager.getCharData(documentData.finalText[i], fontData.fStyle, this.globalData.fontManager.getFontByName(documentData.f).fFamily);
shapeData = charData && charData.data || {};
shapes = shapeData.shapes ? shapeData.shapes[0].it : [];
if(!singleShape){
tSpan.setAttribute('d',this.createPathShape(matrixHelper,shapes));
} else {
shapeStr += this.createPathShape(matrixHelper,shapes);
}
} else {
if(singleShape) {
tSpan.setAttribute("transform", "translate(" + matrixHelper.props[12] + "," + matrixHelper.props[13] + ")");
}
tSpan.textContent = letters[i].val;
tSpan.setAttributeNS("http://www.w3.org/XML/1998/namespace", "xml:space","preserve");
}
//
}
if (singleShape) {
tSpan.setAttribute('d',shapeStr);
}
}
while (i < this.textSpans.length){
this.textSpans[i].style.display = 'none';
i += 1;
}
this._sizeChanged = true;
};
SVGTextElement.prototype.sourceRectAtTime = function(time){
this.prepareFrame(this.comp.renderedFrame - this.data.st);
this.renderInnerContent();
if(this._sizeChanged){
this._sizeChanged = false;
var textBox = this.layerElement.getBBox();
this.bbox = {
top: textBox.y,
left: textBox.x,
width: textBox.width,
height: textBox.height
};
}
return this.bbox;
};
SVGTextElement.prototype.renderInnerContent = function(){
if(!this.data.singleShape){
this.textAnimator.getMeasures(this.textProperty.currentData, this.lettersChangedFlag);
if(this.lettersChangedFlag || this.textAnimator.lettersChangedFlag){
this._sizeChanged = true;
var i,len;
var renderedLetters = this.textAnimator.renderedLetters;
var letters = this.textProperty.currentData.l;
len = letters.length;
var renderedLetter, textSpan;
for(i=0;i<len;i+=1){
if(letters[i].n){
continue;
}
renderedLetter = renderedLetters[i];
textSpan = this.textSpans[i];
if(renderedLetter._mdf.m) {
textSpan.setAttribute('transform',renderedLetter.m);
}
if(renderedLetter._mdf.o) {
textSpan.setAttribute('opacity',renderedLetter.o);
}
if(renderedLetter._mdf.sw){
textSpan.setAttribute('stroke-width',renderedLetter.sw);
}
if(renderedLetter._mdf.sc){
textSpan.setAttribute('stroke',renderedLetter.sc);
}
if(renderedLetter._mdf.fc){
textSpan.setAttribute('fill',renderedLetter.fc);
}
}
}
}
};
function SVGShapeElement(data,globalData,comp){
//List of drawable elements
this.shapes = [];
// Full shape data
this.shapesData = data.shapes;
//List of styles that will be applied to shapes
this.stylesList = [];
//List of modifiers that will be applied to shapes
this.shapeModifiers = [];
//List of items in shape tree
this.itemsData = [];
//List of items in previous shape tree
this.processedElements = [];
// List of animated components
this.animatedContents = [];
this.initElement(data,globalData,comp);
//Moving any property that doesn't get too much access after initialization because of v8 way of handling more than 10 properties.
// List of elements that have been created
this.prevViewData = [];
//Moving any property that doesn't get too much access after initialization because of v8 way of handling more than 10 properties.
}
extendPrototype([BaseElement,TransformElement,SVGBaseElement,IShapeElement,HierarchyElement,FrameElement,RenderableDOMElement], SVGShapeElement);
SVGShapeElement.prototype.initSecondaryElement = function() {
};
SVGShapeElement.prototype.identityMatrix = new Matrix();
SVGShapeElement.prototype.buildExpressionInterface = function(){};
SVGShapeElement.prototype.createContent = function(){
this.searchShapes(this.shapesData,this.itemsData,this.prevViewData,this.layerElement, 0, [], true);
this.filterUniqueShapes();
};
/*
This method searches for multiple shapes that affect a single element and one of them is animated
*/
SVGShapeElement.prototype.filterUniqueShapes = function(){
var i, len = this.shapes.length, shape;
var j, jLen = this.stylesList.length;
var style, count = 0;
var tempShapes = [];
var areAnimated = false;
for(j = 0; j < jLen; j += 1) {
style = this.stylesList[j];
areAnimated = false;
tempShapes.length = 0;
for(i = 0; i < len; i += 1) {
shape = this.shapes[i];
if(shape.styles.indexOf(style) !== -1) {
tempShapes.push(shape);
areAnimated = shape._isAnimated || areAnimated;
}
}
if(tempShapes.length > 1 && areAnimated) {
this.setShapesAsAnimated(tempShapes);
}
}
}
SVGShapeElement.prototype.setShapesAsAnimated = function(shapes){
var i, len = shapes.length;
for(i = 0; i < len; i += 1) {
shapes[i].setAsAnimated();
}
}
SVGShapeElement.prototype.createStyleElement = function(data, level){
//TODO: prevent drawing of hidden styles
var elementData;
var styleOb = new SVGStyleData(data, level);
var pathElement = styleOb.pElem;
if(data.ty === 'st') {
elementData = new SVGStrokeStyleData(this, data, styleOb);
} else if(data.ty === 'fl') {
elementData = new SVGFillStyleData(this, data, styleOb);
} else if(data.ty === 'gf' || data.ty === 'gs') {
var gradientConstructor = data.ty === 'gf' ? SVGGradientFillStyleData : SVGGradientStrokeStyleData;
elementData = new gradientConstructor(this, data, styleOb);
this.globalData.defs.appendChild(elementData.gf);
if (elementData.maskId) {
this.globalData.defs.appendChild(elementData.ms);
this.globalData.defs.appendChild(elementData.of);
pathElement.setAttribute('mask','url(#' + elementData.maskId + ')');
}
}
if(data.ty === 'st' || data.ty === 'gs') {
pathElement.setAttribute('stroke-linecap', this.lcEnum[data.lc] || 'round');
pathElement.setAttribute('stroke-linejoin',this.ljEnum[data.lj] || 'round');
pathElement.setAttribute('fill-opacity','0');
if(data.lj === 1) {
pathElement.setAttribute('stroke-miterlimit',data.ml);
}
}
if(data.r === 2) {
pathElement.setAttribute('fill-rule', 'evenodd');
}
if(data.ln){
pathElement.setAttribute('id',data.ln);
}
if(data.cl){
pathElement.setAttribute('class',data.cl);
}
this.stylesList.push(styleOb);
this.addToAnimatedContents(data, elementData);
return elementData;
};
SVGShapeElement.prototype.createGroupElement = function(data) {
var elementData = new ShapeGroupData();
if(data.ln){
elementData.gr.setAttribute('id',data.ln);
}
return elementData;
};
SVGShapeElement.prototype.createTransformElement = function(data, container) {
var transformProperty = TransformPropertyFactory.getTransformProperty(this,data,this);
var elementData = new SVGTransformData(transformProperty, transformProperty.o, container);
this.addToAnimatedContents(data, elementData);
return elementData;
};
SVGShapeElement.prototype.createShapeElement = function(data, ownTransformers, level) {
var ty = 4;
if(data.ty === 'rc'){
ty = 5;
}else if(data.ty === 'el'){
ty = 6;
}else if(data.ty === 'sr'){
ty = 7;
}
var shapeProperty = ShapePropertyFactory.getShapeProp(this,data,ty,this);
var elementData = new SVGShapeData(ownTransformers, level, shapeProperty);
this.shapes.push(elementData);
this.addShapeToModifiers(elementData);
this.addToAnimatedContents(data, elementData);
return elementData;
};
SVGShapeElement.prototype.addToAnimatedContents = function(data, element) {
var i = 0, len = this.animatedContents.length;
while(i < len) {
if(this.animatedContents[i].element === element) {
return;
}
i += 1;
}
this.animatedContents.push({
fn: SVGElementsRenderer.createRenderFunction(data),
element: element,
data: data
});
};
SVGShapeElement.prototype.setElementStyles = function(elementData){
var arr = elementData.styles;
var j, jLen = this.stylesList.length;
for (j = 0; j < jLen; j += 1) {
if (!this.stylesList[j].closed) {
arr.push(this.stylesList[j]);
}
}
};
SVGShapeElement.prototype.reloadShapes = function(){
this._isFirstFrame = true;
var i, len = this.itemsData.length;
for( i = 0; i < len; i += 1) {
this.prevViewData[i] = this.itemsData[i];
}
this.searchShapes(this.shapesData,this.itemsData,this.prevViewData,this.layerElement, 0, [], true);
this.filterUniqueShapes();
len = this.dynamicProperties.length;
for(i = 0; i < len; i += 1) {
this.dynamicProperties[i].getValue();
}
this.renderModifiers();
};
SVGShapeElement.prototype.searchShapes = function(arr,itemsData,prevViewData,container, level, transformers, render){
var ownTransformers = [].concat(transformers);
var i, len = arr.length - 1;
var j, jLen;
var ownStyles = [], ownModifiers = [], styleOb, currentTransform, modifier, processedPos;
for(i=len;i>=0;i-=1){
processedPos = this.searchProcessedElement(arr[i]);
if(!processedPos){
arr[i]._render = render;
} else {
itemsData[i] = prevViewData[processedPos - 1];
}
if(arr[i].ty == 'fl' || arr[i].ty == 'st' || arr[i].ty == 'gf' || arr[i].ty == 'gs'){
if(!processedPos){
itemsData[i] = this.createStyleElement(arr[i], level);
} else {
itemsData[i].style.closed = false;
}
if(arr[i]._render){
container.appendChild(itemsData[i].style.pElem);
}
ownStyles.push(itemsData[i].style);
}else if(arr[i].ty == 'gr'){
if(!processedPos){
itemsData[i] = this.createGroupElement(arr[i]);
} else {
jLen = itemsData[i].it.length;
for(j=0;j<jLen;j+=1){
itemsData[i].prevViewData[j] = itemsData[i].it[j];
}
}
this.searchShapes(arr[i].it,itemsData[i].it,itemsData[i].prevViewData,itemsData[i].gr, level + 1, ownTransformers, render);
if(arr[i]._render){
container.appendChild(itemsData[i].gr);
}
}else if(arr[i].ty == 'tr'){
if(!processedPos){
itemsData[i] = this.createTransformElement(arr[i], container);
}
currentTransform = itemsData[i].transform;
ownTransformers.push(currentTransform);
}else if(arr[i].ty == 'sh' || arr[i].ty == 'rc' || arr[i].ty == 'el' || arr[i].ty == 'sr'){
if(!processedPos){
itemsData[i] = this.createShapeElement(arr[i], ownTransformers, level);
}
this.setElementStyles(itemsData[i]);
}else if(arr[i].ty == 'tm' || arr[i].ty == 'rd' || arr[i].ty == 'ms'){
if(!processedPos){
modifier = ShapeModifiers.getModifier(arr[i].ty);
modifier.init(this,arr[i]);
itemsData[i] = modifier;
this.shapeModifiers.push(modifier);
} else {
modifier = itemsData[i];
modifier.closed = false;
}
ownModifiers.push(modifier);
}else if(arr[i].ty == 'rp'){
if(!processedPos){
modifier = ShapeModifiers.getModifier(arr[i].ty);
itemsData[i] = modifier;
modifier.init(this,arr,i,itemsData);
this.shapeModifiers.push(modifier);
render = false;
}else{
modifier = itemsData[i];
modifier.closed = true;
}
ownModifiers.push(modifier);
}
this.addProcessedElement(arr[i], i + 1);
}
len = ownStyles.length;
for(i=0;i<len;i+=1){
ownStyles[i].closed = true;
}
len = ownModifiers.length;
for(i=0;i<len;i+=1){
ownModifiers[i].closed = true;
}
};
SVGShapeElement.prototype.renderInnerContent = function() {
this.renderModifiers();
var i, len = this.stylesList.length;
for(i=0;i<len;i+=1){
this.stylesList[i].reset();
}
this.renderShape();
for (i = 0; i < len; i += 1) {
if (this.stylesList[i]._mdf || this._isFirstFrame) {
if(this.stylesList[i].msElem){
this.stylesList[i].msElem.setAttribute('d', this.stylesList[i].d);
//Adding M0 0 fixes same mask bug on all browsers
this.stylesList[i].d = 'M0 0' + this.stylesList[i].d;
}
this.stylesList[i].pElem.setAttribute('d', this.stylesList[i].d || 'M0 0');
}
}
};
SVGShapeElement.prototype.renderShape = function() {
var i, len = this.animatedContents.length;
var animatedContent;
for(i = 0; i < len; i += 1) {
animatedContent = this.animatedContents[i];
if(this._isFirstFrame || animatedContent.element._isAnimated) {
animatedContent.fn(animatedContent.data, animatedContent.element, this._isFirstFrame);
}
}
}
SVGShapeElement.prototype.destroy = function(){
this.destroyBaseElement();
this.shapeData = null;
this.itemsData = null;
};
function SVGTintFilter(filter, filterManager){
this.filterManager = filterManager;
var feColorMatrix = createNS('feColorMatrix');
feColorMatrix.setAttribute('type','matrix');
feColorMatrix.setAttribute('color-interpolation-filters','linearRGB');
feColorMatrix.setAttribute('values','0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0');
feColorMatrix.setAttribute('result','f1');
filter.appendChild(feColorMatrix);
feColorMatrix = createNS('feColorMatrix');
feColorMatrix.setAttribute('type','matrix');
feColorMatrix.setAttribute('color-interpolation-filters','sRGB');
feColorMatrix.setAttribute('values','1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0');
feColorMatrix.setAttribute('result','f2');
filter.appendChild(feColorMatrix);
this.matrixFilter = feColorMatrix;
if(filterManager.effectElements[2].p.v !== 100 || filterManager.effectElements[2].p.k){
var feMerge = createNS('feMerge');
filter.appendChild(feMerge);
var feMergeNode;
feMergeNode = createNS('feMergeNode');
feMergeNode.setAttribute('in','SourceGraphic');
feMerge.appendChild(feMergeNode);
feMergeNode = createNS('feMergeNode');
feMergeNode.setAttribute('in','f2');
feMerge.appendChild(feMergeNode);
}
}
SVGTintFilter.prototype.renderFrame = function(forceRender){
if(forceRender || this.filterManager._mdf){
var colorBlack = this.filterManager.effectElements[0].p.v;
var colorWhite = this.filterManager.effectElements[1].p.v;
var opacity = this.filterManager.effectElements[2].p.v/100;
this.matrixFilter.setAttribute('values',(colorWhite[0]- colorBlack[0])+' 0 0 0 '+ colorBlack[0] +' '+ (colorWhite[1]- colorBlack[1]) +' 0 0 0 '+ colorBlack[1] +' '+ (colorWhite[2]- colorBlack[2]) +' 0 0 0 '+ colorBlack[2] +' 0 0 0 ' + opacity + ' 0');
}
};
function SVGFillFilter(filter, filterManager){
this.filterManager = filterManager;
var feColorMatrix = createNS('feColorMatrix');
feColorMatrix.setAttribute('type','matrix');
feColorMatrix.setAttribute('color-interpolation-filters','sRGB');
feColorMatrix.setAttribute('values','1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0');
filter.appendChild(feColorMatrix);
this.matrixFilter = feColorMatrix;
}
SVGFillFilter.prototype.renderFrame = function(forceRender){
if(forceRender || this.filterManager._mdf){
var color = this.filterManager.effectElements[2].p.v;
var opacity = this.filterManager.effectElements[6].p.v;
this.matrixFilter.setAttribute('values','0 0 0 0 '+color[0]+' 0 0 0 0 '+color[1]+' 0 0 0 0 '+color[2]+' 0 0 0 '+opacity+' 0');
}
};
function SVGStrokeEffect(elem, filterManager){
this.initialized = false;
this.filterManager = filterManager;
this.elem = elem;
this.paths = [];
}
SVGStrokeEffect.prototype.initialize = function(){
var elemChildren = this.elem.layerElement.children || this.elem.layerElement.childNodes;
var path,groupPath, i, len;
if(this.filterManager.effectElements[1].p.v === 1){
len = this.elem.maskManager.masksProperties.length;
i = 0;
} else {
i = this.filterManager.effectElements[0].p.v - 1;
len = i + 1;
}
groupPath = createNS('g');
groupPath.setAttribute('fill','none');
groupPath.setAttribute('stroke-linecap','round');
groupPath.setAttribute('stroke-dashoffset',1);
for(i;i<len;i+=1){
path = createNS('path');
groupPath.appendChild(path);
this.paths.push({p:path,m:i});
}
if(this.filterManager.effectElements[10].p.v === 3){
var mask = createNS('mask');
var id = 'stms_' + randomString(10);
mask.setAttribute('id',id);
mask.setAttribute('mask-type','alpha');
mask.appendChild(groupPath);
this.elem.globalData.defs.appendChild(mask);
var g = createNS('g');
g.setAttribute('mask','url(' + locationHref + '#'+id+')');
if(elemChildren[0]){
g.appendChild(elemChildren[0]);
}
this.elem.layerElement.appendChild(g);
this.masker = mask;
groupPath.setAttribute('stroke','#fff');
} else if(this.filterManager.effectElements[10].p.v === 1 || this.filterManager.effectElements[10].p.v === 2){
if(this.filterManager.effectElements[10].p.v === 2){
elemChildren = this.elem.layerElement.children || this.elem.layerElement.childNodes;
while(elemChildren.length){
this.elem.layerElement.removeChild(elemChildren[0]);
}
}
this.elem.layerElement.appendChild(groupPath);
this.elem.layerElement.removeAttribute('mask');
groupPath.setAttribute('stroke','#fff');
}
this.initialized = true;
this.pathMasker = groupPath;
};
SVGStrokeEffect.prototype.renderFrame = function(forceRender){
if(!this.initialized){
this.initialize();
}
var i, len = this.paths.length;
var mask, path;
for(i=0;i<len;i+=1){
if(this.paths[i].m === -1) {
continue;
}
mask = this.elem.maskManager.viewData[this.paths[i].m];
path = this.paths[i].p;
if(forceRender || this.filterManager._mdf || mask.prop._mdf){
path.setAttribute('d',mask.lastPath);
}
if(forceRender || this.filterManager.effectElements[9].p._mdf || this.filterManager.effectElements[4].p._mdf || this.filterManager.effectElements[7].p._mdf || this.filterManager.effectElements[8].p._mdf || mask.prop._mdf){
var dasharrayValue;
if(this.filterManager.effectElements[7].p.v !== 0 || this.filterManager.effectElements[8].p.v !== 100){
var s = Math.min(this.filterManager.effectElements[7].p.v,this.filterManager.effectElements[8].p.v)/100;
var e = Math.max(this.filterManager.effectElements[7].p.v,this.filterManager.effectElements[8].p.v)/100;
var l = path.getTotalLength();
dasharrayValue = '0 0 0 ' + l*s + ' ';
var lineLength = l*(e-s);
var segment = 1+this.filterManager.effectElements[4].p.v*2*this.filterManager.effectElements[9].p.v/100;
var units = Math.floor(lineLength/segment);
var j;
for(j=0;j<units;j+=1){
dasharrayValue += '1 ' + this.filterManager.effectElements[4].p.v*2*this.filterManager.effectElements[9].p.v/100 + ' ';
}
dasharrayValue += '0 ' + l*10 + ' 0 0';
} else {
dasharrayValue = '1 ' + this.filterManager.effectElements[4].p.v*2*this.filterManager.effectElements[9].p.v/100;
}
path.setAttribute('stroke-dasharray',dasharrayValue);
}
}
if(forceRender || this.filterManager.effectElements[4].p._mdf){
this.pathMasker.setAttribute('stroke-width',this.filterManager.effectElements[4].p.v*2);
}
if(forceRender || this.filterManager.effectElements[6].p._mdf){
this.pathMasker.setAttribute('opacity',this.filterManager.effectElements[6].p.v);
}
if(this.filterManager.effectElements[10].p.v === 1 || this.filterManager.effectElements[10].p.v === 2){
if(forceRender || this.filterManager.effectElements[3].p._mdf){
var color = this.filterManager.effectElements[3].p.v;
this.pathMasker.setAttribute('stroke','rgb('+bm_floor(color[0]*255)+','+bm_floor(color[1]*255)+','+bm_floor(color[2]*255)+')');
}
}
};
function SVGTritoneFilter(filter, filterManager){
this.filterManager = filterManager;
var feColorMatrix = createNS('feColorMatrix');
feColorMatrix.setAttribute('type','matrix');
feColorMatrix.setAttribute('color-interpolation-filters','linearRGB');
feColorMatrix.setAttribute('values','0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0');
feColorMatrix.setAttribute('result','f1');
filter.appendChild(feColorMatrix);
var feComponentTransfer = createNS('feComponentTransfer');
feComponentTransfer.setAttribute('color-interpolation-filters','sRGB');
filter.appendChild(feComponentTransfer);
this.matrixFilter = feComponentTransfer;
var feFuncR = createNS('feFuncR');
feFuncR.setAttribute('type','table');
feComponentTransfer.appendChild(feFuncR);
this.feFuncR = feFuncR;
var feFuncG = createNS('feFuncG');
feFuncG.setAttribute('type','table');
feComponentTransfer.appendChild(feFuncG);
this.feFuncG = feFuncG;
var feFuncB = createNS('feFuncB');
feFuncB.setAttribute('type','table');
feComponentTransfer.appendChild(feFuncB);
this.feFuncB = feFuncB;
}
SVGTritoneFilter.prototype.renderFrame = function(forceRender){
if(forceRender || this.filterManager._mdf){
var color1 = this.filterManager.effectElements[0].p.v;
var color2 = this.filterManager.effectElements[1].p.v;
var color3 = this.filterManager.effectElements[2].p.v;
var tableR = color3[0] + ' ' + color2[0] + ' ' + color1[0];
var tableG = color3[1] + ' ' + color2[1] + ' ' + color1[1];
var tableB = color3[2] + ' ' + color2[2] + ' ' + color1[2];
this.feFuncR.setAttribute('tableValues', tableR);
this.feFuncG.setAttribute('tableValues', tableG);
this.feFuncB.setAttribute('tableValues', tableB);
//var opacity = this.filterManager.effectElements[2].p.v/100;
//this.matrixFilter.setAttribute('values',(colorWhite[0]- colorBlack[0])+' 0 0 0 '+ colorBlack[0] +' '+ (colorWhite[1]- colorBlack[1]) +' 0 0 0 '+ colorBlack[1] +' '+ (colorWhite[2]- colorBlack[2]) +' 0 0 0 '+ colorBlack[2] +' 0 0 0 ' + opacity + ' 0');
}
};
function SVGProLevelsFilter(filter, filterManager){
this.filterManager = filterManager;
var effectElements = this.filterManager.effectElements;
var feComponentTransfer = createNS('feComponentTransfer');
var feFuncR, feFuncG, feFuncB;
if(effectElements[10].p.k || effectElements[10].p.v !== 0 || effectElements[11].p.k || effectElements[11].p.v !== 1 || effectElements[12].p.k || effectElements[12].p.v !== 1 || effectElements[13].p.k || effectElements[13].p.v !== 0 || effectElements[14].p.k || effectElements[14].p.v !== 1){
this.feFuncR = this.createFeFunc('feFuncR', feComponentTransfer);
}
if(effectElements[17].p.k || effectElements[17].p.v !== 0 || effectElements[18].p.k || effectElements[18].p.v !== 1 || effectElements[19].p.k || effectElements[19].p.v !== 1 || effectElements[20].p.k || effectElements[20].p.v !== 0 || effectElements[21].p.k || effectElements[21].p.v !== 1){
this.feFuncG = this.createFeFunc('feFuncG', feComponentTransfer);
}
if(effectElements[24].p.k || effectElements[24].p.v !== 0 || effectElements[25].p.k || effectElements[25].p.v !== 1 || effectElements[26].p.k || effectElements[26].p.v !== 1 || effectElements[27].p.k || effectElements[27].p.v !== 0 || effectElements[28].p.k || effectElements[28].p.v !== 1){
this.feFuncB = this.createFeFunc('feFuncB', feComponentTransfer);
}
if(effectElements[31].p.k || effectElements[31].p.v !== 0 || effectElements[32].p.k || effectElements[32].p.v !== 1 || effectElements[33].p.k || effectElements[33].p.v !== 1 || effectElements[34].p.k || effectElements[34].p.v !== 0 || effectElements[35].p.k || effectElements[35].p.v !== 1){
this.feFuncA = this.createFeFunc('feFuncA', feComponentTransfer);
}
if(this.feFuncR || this.feFuncG || this.feFuncB || this.feFuncA){
feComponentTransfer.setAttribute('color-interpolation-filters','sRGB');
filter.appendChild(feComponentTransfer);
feComponentTransfer = createNS('feComponentTransfer');
}
if(effectElements[3].p.k || effectElements[3].p.v !== 0 || effectElements[4].p.k || effectElements[4].p.v !== 1 || effectElements[5].p.k || effectElements[5].p.v !== 1 || effectElements[6].p.k || effectElements[6].p.v !== 0 || effectElements[7].p.k || effectElements[7].p.v !== 1){
feComponentTransfer.setAttribute('color-interpolation-filters','sRGB');
filter.appendChild(feComponentTransfer);
this.feFuncRComposed = this.createFeFunc('feFuncR', feComponentTransfer);
this.feFuncGComposed = this.createFeFunc('feFuncG', feComponentTransfer);
this.feFuncBComposed = this.createFeFunc('feFuncB', feComponentTransfer);
}
}
SVGProLevelsFilter.prototype.createFeFunc = function(type, feComponentTransfer) {
var feFunc = createNS(type);
feFunc.setAttribute('type','table');
feComponentTransfer.appendChild(feFunc);
return feFunc;
};
SVGProLevelsFilter.prototype.getTableValue = function(inputBlack, inputWhite, gamma, outputBlack, outputWhite) {
var cnt = 0;
var segments = 256;
var perc;
var min = Math.min(inputBlack, inputWhite);
var max = Math.max(inputBlack, inputWhite);
var table = Array.call(null,{length:segments});
var colorValue;
var pos = 0;
var outputDelta = outputWhite - outputBlack;
var inputDelta = inputWhite - inputBlack;
while(cnt <= 256) {
perc = cnt/256;
if(perc <= min){
colorValue = inputDelta < 0 ? outputWhite : outputBlack;
} else if(perc >= max){
colorValue = inputDelta < 0 ? outputBlack : outputWhite;
} else {
colorValue = (outputBlack + outputDelta * Math.pow((perc - inputBlack) / inputDelta, 1 / gamma));
}
table[pos++] = colorValue;
cnt += 256/(segments-1);
}
return table.join(' ');
};
SVGProLevelsFilter.prototype.renderFrame = function(forceRender){
if(forceRender || this.filterManager._mdf){
var val, cnt, perc, bezier;
var effectElements = this.filterManager.effectElements;
if(this.feFuncRComposed && (forceRender || effectElements[3].p._mdf || effectElements[4].p._mdf || effectElements[5].p._mdf || effectElements[6].p._mdf || effectElements[7].p._mdf)){
val = this.getTableValue(effectElements[3].p.v,effectElements[4].p.v,effectElements[5].p.v,effectElements[6].p.v,effectElements[7].p.v);
this.feFuncRComposed.setAttribute('tableValues',val);
this.feFuncGComposed.setAttribute('tableValues',val);
this.feFuncBComposed.setAttribute('tableValues',val);
}
if(this.feFuncR && (forceRender || effectElements[10].p._mdf || effectElements[11].p._mdf || effectElements[12].p._mdf || effectElements[13].p._mdf || effectElements[14].p._mdf)){
val = this.getTableValue(effectElements[10].p.v,effectElements[11].p.v,effectElements[12].p.v,effectElements[13].p.v,effectElements[14].p.v);
this.feFuncR.setAttribute('tableValues',val);
}
if(this.feFuncG && (forceRender || effectElements[17].p._mdf || effectElements[18].p._mdf || effectElements[19].p._mdf || effectElements[20].p._mdf || effectElements[21].p._mdf)){
val = this.getTableValue(effectElements[17].p.v,effectElements[18].p.v,effectElements[19].p.v,effectElements[20].p.v,effectElements[21].p.v);
this.feFuncG.setAttribute('tableValues',val);
}
if(this.feFuncB && (forceRender || effectElements[24].p._mdf || effectElements[25].p._mdf || effectElements[26].p._mdf || effectElements[27].p._mdf || effectElements[28].p._mdf)){
val = this.getTableValue(effectElements[24].p.v,effectElements[25].p.v,effectElements[26].p.v,effectElements[27].p.v,effectElements[28].p.v);
this.feFuncB.setAttribute('tableValues',val);
}
if(this.feFuncA && (forceRender || effectElements[31].p._mdf || effectElements[32].p._mdf || effectElements[33].p._mdf || effectElements[34].p._mdf || effectElements[35].p._mdf)){
val = this.getTableValue(effectElements[31].p.v,effectElements[32].p.v,effectElements[33].p.v,effectElements[34].p.v,effectElements[35].p.v);
this.feFuncA.setAttribute('tableValues',val);
}
}
};
function SVGDropShadowEffect(filter, filterManager){
filter.setAttribute('x','-100%');
filter.setAttribute('y','-100%');
filter.setAttribute('width','400%');
filter.setAttribute('height','400%');
this.filterManager = filterManager;
var feGaussianBlur = createNS('feGaussianBlur');
feGaussianBlur.setAttribute('in','SourceAlpha');
feGaussianBlur.setAttribute('result','drop_shadow_1');
feGaussianBlur.setAttribute('stdDeviation','0');
this.feGaussianBlur = feGaussianBlur;
filter.appendChild(feGaussianBlur);
var feOffset = createNS('feOffset');
feOffset.setAttribute('dx','25');
feOffset.setAttribute('dy','0');
feOffset.setAttribute('in','drop_shadow_1');
feOffset.setAttribute('result','drop_shadow_2');
this.feOffset = feOffset;
filter.appendChild(feOffset);
var feFlood = createNS('feFlood');
feFlood.setAttribute('flood-color','#00ff00');
feFlood.setAttribute('flood-opacity','1');
feFlood.setAttribute('result','drop_shadow_3');
this.feFlood = feFlood;
filter.appendChild(feFlood);
var feComposite = createNS('feComposite');
feComposite.setAttribute('in','drop_shadow_3');
feComposite.setAttribute('in2','drop_shadow_2');
feComposite.setAttribute('operator','in');
feComposite.setAttribute('result','drop_shadow_4');
filter.appendChild(feComposite);
var feMerge = createNS('feMerge');
filter.appendChild(feMerge);
var feMergeNode;
feMergeNode = createNS('feMergeNode');
feMerge.appendChild(feMergeNode);
feMergeNode = createNS('feMergeNode');
feMergeNode.setAttribute('in','SourceGraphic');
this.feMergeNode = feMergeNode;
this.feMerge = feMerge;
this.originalNodeAdded = false;
feMerge.appendChild(feMergeNode);
}
SVGDropShadowEffect.prototype.renderFrame = function(forceRender){
if(forceRender || this.filterManager._mdf){
if(forceRender || this.filterManager.effectElements[4].p._mdf){
this.feGaussianBlur.setAttribute('stdDeviation', this.filterManager.effectElements[4].p.v / 4);
}
if(forceRender || this.filterManager.effectElements[0].p._mdf){
var col = this.filterManager.effectElements[0].p.v;
this.feFlood.setAttribute('flood-color',rgbToHex(Math.round(col[0]*255),Math.round(col[1]*255),Math.round(col[2]*255)));
}
if(forceRender || this.filterManager.effectElements[1].p._mdf){
this.feFlood.setAttribute('flood-opacity',this.filterManager.effectElements[1].p.v/255);
}
if(forceRender || this.filterManager.effectElements[2].p._mdf || this.filterManager.effectElements[3].p._mdf){
var distance = this.filterManager.effectElements[3].p.v;
var angle = (this.filterManager.effectElements[2].p.v - 90) * degToRads;
var x = distance * Math.cos(angle);
var y = distance * Math.sin(angle);
this.feOffset.setAttribute('dx', x);
this.feOffset.setAttribute('dy', y);
}
/*if(forceRender || this.filterManager.effectElements[5].p._mdf){
if(this.filterManager.effectElements[5].p.v === 1 && this.originalNodeAdded) {
this.feMerge.removeChild(this.feMergeNode);
this.originalNodeAdded = false;
} else if(this.filterManager.effectElements[5].p.v === 0 && !this.originalNodeAdded) {
this.feMerge.appendChild(this.feMergeNode);
this.originalNodeAdded = true;
}
}*/
}
};
var _svgMatteSymbols = [];
var _svgMatteMaskCounter = 0;
function SVGMatte3Effect(filterElem, filterManager, elem){
this.initialized = false;
this.filterManager = filterManager;
this.filterElem = filterElem;
this.elem = elem;
elem.matteElement = createNS('g');
elem.matteElement.appendChild(elem.layerElement);
elem.matteElement.appendChild(elem.transformedElement);
elem.baseElement = elem.matteElement;
}
SVGMatte3Effect.prototype.findSymbol = function(mask) {
var i = 0, len = _svgMatteSymbols.length;
while(i < len) {
if(_svgMatteSymbols[i] === mask) {
return _svgMatteSymbols[i];
}
i += 1;
}
return null;
};
SVGMatte3Effect.prototype.replaceInParent = function(mask, symbolId) {
var parentNode = mask.layerElement.parentNode;
if(!parentNode) {
return;
}
var children = parentNode.children;
var i = 0, len = children.length;
while (i < len) {
if (children[i] === mask.layerElement) {
break;
}
i += 1;
}
var nextChild;
if (i <= len - 2) {
nextChild = children[i + 1];
}
var useElem = createNS('use');
useElem.setAttribute('href', '#' + symbolId);
if(nextChild) {
parentNode.insertBefore(useElem, nextChild);
} else {
parentNode.appendChild(useElem);
}
};
SVGMatte3Effect.prototype.setElementAsMask = function(elem, mask) {
if(!this.findSymbol(mask)) {
var symbolId = 'matte_' + randomString(5) + '_' + _svgMatteMaskCounter++;
var masker = createNS('mask');
masker.setAttribute('id', mask.layerId);
masker.setAttribute('mask-type', 'alpha');
_svgMatteSymbols.push(mask);
var defs = elem.globalData.defs;
defs.appendChild(masker);
var symbol = createNS('symbol');
symbol.setAttribute('id', symbolId);
this.replaceInParent(mask, symbolId);
symbol.appendChild(mask.layerElement);
defs.appendChild(symbol);
var useElem = createNS('use');
useElem.setAttribute('href', '#' + symbolId);
masker.appendChild(useElem);
mask.data.hd = false;
mask.show();
}
elem.setMatte(mask.layerId);
};
SVGMatte3Effect.prototype.initialize = function() {
var ind = this.filterManager.effectElements[0].p.v;
var i = 0, len = this.elem.comp.elements.length;
while (i < len) {
if (this.elem.comp.elements[i].data.ind === ind) {
this.setElementAsMask(this.elem, this.elem.comp.elements[i]);
}
i += 1;
}
this.initialized = true;
};
SVGMatte3Effect.prototype.renderFrame = function() {
if(!this.initialized) {
this.initialize();
}
};
function SVGEffects(elem){
var i, len = elem.data.ef ? elem.data.ef.length : 0;
var filId = randomString(10);
var fil = filtersFactory.createFilter(filId);
var count = 0;
this.filters = [];
var filterManager;
for(i=0;i<len;i+=1){
filterManager = null;
if(elem.data.ef[i].ty === 20){
count += 1;
filterManager = new SVGTintFilter(fil, elem.effectsManager.effectElements[i]);
}else if(elem.data.ef[i].ty === 21){
count += 1;
filterManager = new SVGFillFilter(fil, elem.effectsManager.effectElements[i]);
}else if(elem.data.ef[i].ty === 22){
filterManager = new SVGStrokeEffect(elem, elem.effectsManager.effectElements[i]);
}else if(elem.data.ef[i].ty === 23){
count += 1;
filterManager = new SVGTritoneFilter(fil, elem.effectsManager.effectElements[i]);
}else if(elem.data.ef[i].ty === 24){
count += 1;
filterManager = new SVGProLevelsFilter(fil, elem.effectsManager.effectElements[i]);
}else if(elem.data.ef[i].ty === 25){
count += 1;
filterManager = new SVGDropShadowEffect(fil, elem.effectsManager.effectElements[i]);
}else if(elem.data.ef[i].ty === 28){
//count += 1;
filterManager = new SVGMatte3Effect(fil, elem.effectsManager.effectElements[i], elem);
}
if(filterManager) {
this.filters.push(filterManager);
}
}
if(count){
elem.globalData.defs.appendChild(fil);
elem.layerElement.setAttribute('filter','url(' + locationHref + '#'+filId+')');
}
if (this.filters.length) {
elem.addRenderableComponent(this);
}
}
SVGEffects.prototype.renderFrame = function(_isFirstFrame){
var i, len = this.filters.length;
for(i=0;i<len;i+=1){
this.filters[i].renderFrame(_isFirstFrame);
}
};
var animationManager = (function(){
var moduleOb = {};
var registeredAnimations = [];
var initTime = 0;
var len = 0;
var idled = true;
var playingAnimationsNum = 0;
var _stopped = true;
function removeElement(ev){
var i = 0;
var animItem = ev.target;
while(i<len) {
if (registeredAnimations[i].animation === animItem) {
registeredAnimations.splice(i, 1);
i -= 1;
len -= 1;
if(!animItem.isPaused){
subtractPlayingCount();
}
}
i += 1;
}
}
function registerAnimation(element, animationData){
if(!element){
return null;
}
var i=0;
while(i<len){
if(registeredAnimations[i].elem == element && registeredAnimations[i].elem !== null ){
return registeredAnimations[i].animation;
}
i+=1;
}
var animItem = new AnimationItem();
setupAnimation(animItem, element);
animItem.setData(element, animationData);
return animItem;
}
function addPlayingCount(){
playingAnimationsNum += 1;
activate();
}
function subtractPlayingCount(){
playingAnimationsNum -= 1;
if(playingAnimationsNum === 0){
idled = true;
}
}
function setupAnimation(animItem, element){
animItem.addEventListener('destroy',removeElement);
animItem.addEventListener('_active',addPlayingCount);
animItem.addEventListener('_idle',subtractPlayingCount);
registeredAnimations.push({elem: element,animation:animItem});
len += 1;
}
function loadAnimation(params){
var animItem = new AnimationItem();
setupAnimation(animItem, null);
animItem.setParams(params);
return animItem;
}
function setSpeed(val,animation){
var i;
for(i=0;i<len;i+=1){
registeredAnimations[i].animation.setSpeed(val, animation);
}
}
function setDirection(val, animation){
var i;
for(i=0;i<len;i+=1){
registeredAnimations[i].animation.setDirection(val, animation);
}
}
function play(animation){
var i;
for(i=0;i<len;i+=1){
registeredAnimations[i].animation.play(animation);
}
}
function resume(nowTime) {
var elapsedTime = nowTime - initTime;
var i;
for(i=0;i<len;i+=1){
registeredAnimations[i].animation.advanceTime(elapsedTime);
}
initTime = nowTime;
if(!idled) {
window.requestAnimationFrame(resume);
} else {
_stopped = true;
}
}
function first(nowTime){
initTime = nowTime;
window.requestAnimationFrame(resume);
}
function pause(animation) {
var i;
for(i=0;i<len;i+=1){
registeredAnimations[i].animation.pause(animation);
}
}
function goToAndStop(value,isFrame,animation) {
var i;
for(i=0;i<len;i+=1){
registeredAnimations[i].animation.goToAndStop(value,isFrame,animation);
}
}
function stop(animation) {
var i;
for(i=0;i<len;i+=1){
registeredAnimations[i].animation.stop(animation);
}
}
function togglePause(animation) {
var i;
for(i=0;i<len;i+=1){
registeredAnimations[i].animation.togglePause(animation);
}
}
function destroy(animation) {
var i;
for(i=(len-1);i>=0;i-=1){
registeredAnimations[i].animation.destroy(animation);
}
}
function searchAnimations(animationData, standalone, renderer){
var animElements = [].concat([].slice.call(document.getElementsByClassName('lottie')),
[].slice.call(document.getElementsByClassName('bodymovin')));
var i, len = animElements.length;
for(i=0;i<len;i+=1){
if(renderer){
animElements[i].setAttribute('data-bm-type',renderer);
}
registerAnimation(animElements[i], animationData);
}
if(standalone && len === 0){
if(!renderer){
renderer = 'svg';
}
var body = document.getElementsByTagName('body')[0];
body.innerHTML = '';
var div = createTag('div');
div.style.width = '100%';
div.style.height = '100%';
div.setAttribute('data-bm-type',renderer);
body.appendChild(div);
registerAnimation(div, animationData);
}
}
function resize(){
var i;
for(i=0;i<len;i+=1){
registeredAnimations[i].animation.resize();
}
}
/*function start(){
window.requestAnimationFrame(first);
}*/
function activate(){
if(idled){
idled = false;
if(_stopped) {
window.requestAnimationFrame(first);
_stopped = false;
}
}
}
//start();
//setTimeout(start,0);
moduleOb.registerAnimation = registerAnimation;
moduleOb.loadAnimation = loadAnimation;
moduleOb.setSpeed = setSpeed;
moduleOb.setDirection = setDirection;
moduleOb.play = play;
moduleOb.pause = pause;
moduleOb.stop = stop;
moduleOb.togglePause = togglePause;
moduleOb.searchAnimations = searchAnimations;
moduleOb.resize = resize;
//moduleOb.start = start;
moduleOb.goToAndStop = goToAndStop;
moduleOb.destroy = destroy;
return moduleOb;
}());
var AnimationItem = function () {
this._cbs = [];
this.name = '';
this.path = '';
this.isLoaded = false;
this.currentFrame = 0;
this.currentRawFrame = 0;
this.totalFrames = 0;
this.frameRate = 0;
this.frameMult = 0;
this.playSpeed = 1;
this.playDirection = 1;
this.pendingElements = 0;
this.playCount = 0;
this.animationData = {};
this.layers = [];
this.assets = [];
this.isPaused = true;
this.autoplay = false;
this.loop = true;
this.renderer = null;
this.animationID = randomString(10);
this.assetsPath = '';
this.timeCompleted = 0;
this.segmentPos = 0;
this.subframeEnabled = subframeEnabled;
this.segments = [];
this._idle = true;
this.projectInterface = ProjectInterface();
};
extendPrototype([BaseEvent], AnimationItem);
AnimationItem.prototype.setParams = function(params) {
var self = this;
if(params.context){
this.context = params.context;
}
if(params.wrapper || params.container){
this.wrapper = params.wrapper || params.container;
}
var animType = params.animType ? params.animType : params.renderer ? params.renderer : 'svg';
switch(animType){
case 'canvas':
this.renderer = new CanvasRenderer(this, params.rendererSettings);
break;
case 'svg':
this.renderer = new SVGRenderer(this, params.rendererSettings);
break;
default:
this.renderer = new HybridRenderer(this, params.rendererSettings);
break;
}
this.renderer.setProjectInterface(this.projectInterface);
this.animType = animType;
if(params.loop === '' || params.loop === null){
}else if(params.loop === false){
this.loop = false;
}else if(params.loop === true){
this.loop = true;
}else{
this.loop = parseInt(params.loop);
}
this.autoplay = 'autoplay' in params ? params.autoplay : true;
this.name = params.name ? params.name : '';
this.autoloadSegments = params.hasOwnProperty('autoloadSegments') ? params.autoloadSegments : true;
this.assetsPath = params.assetsPath;
if(params.animationData){
self.configAnimation(params.animationData);
}else if(params.path){
if(params.path.substr(-4) != 'json'){
if (params.path.substr(-1, 1) != '/') {
params.path += '/';
}
params.path += 'data.json';
}
var xhr = new XMLHttpRequest();
if(params.path.lastIndexOf('\\') != -1){
this.path = params.path.substr(0,params.path.lastIndexOf('\\')+1);
}else{
this.path = params.path.substr(0,params.path.lastIndexOf('/')+1);
}
this.fileName = params.path.substr(params.path.lastIndexOf('/')+1);
this.fileName = this.fileName.substr(0,this.fileName.lastIndexOf('.json'));
xhr.open('GET', params.path, true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if(xhr.status == 200){
self.configAnimation(JSON.parse(xhr.responseText));
}else{
try{
var response = JSON.parse(xhr.responseText);
self.configAnimation(response);
}catch(err){
}
}
}
};
}
};
AnimationItem.prototype.setData = function (wrapper, animationData) {
var params = {
wrapper: wrapper,
animationData: animationData ? (typeof animationData === "object") ? animationData : JSON.parse(animationData) : null
};
var wrapperAttributes = wrapper.attributes;
params.path = wrapperAttributes.getNamedItem('data-animation-path') ? wrapperAttributes.getNamedItem('data-animation-path').value : wrapperAttributes.getNamedItem('data-bm-path') ? wrapperAttributes.getNamedItem('data-bm-path').value : wrapperAttributes.getNamedItem('bm-path') ? wrapperAttributes.getNamedItem('bm-path').value : '';
params.animType = wrapperAttributes.getNamedItem('data-anim-type') ? wrapperAttributes.getNamedItem('data-anim-type').value : wrapperAttributes.getNamedItem('data-bm-type') ? wrapperAttributes.getNamedItem('data-bm-type').value : wrapperAttributes.getNamedItem('bm-type') ? wrapperAttributes.getNamedItem('bm-type').value : wrapperAttributes.getNamedItem('data-bm-renderer') ? wrapperAttributes.getNamedItem('data-bm-renderer').value : wrapperAttributes.getNamedItem('bm-renderer') ? wrapperAttributes.getNamedItem('bm-renderer').value : 'canvas';
var loop = wrapperAttributes.getNamedItem('data-anim-loop') ? wrapperAttributes.getNamedItem('data-anim-loop').value : wrapperAttributes.getNamedItem('data-bm-loop') ? wrapperAttributes.getNamedItem('data-bm-loop').value : wrapperAttributes.getNamedItem('bm-loop') ? wrapperAttributes.getNamedItem('bm-loop').value : '';
if(loop === ''){
}else if(loop === 'false'){
params.loop = false;
}else if(loop === 'true'){
params.loop = true;
}else{
params.loop = parseInt(loop);
}
var autoplay = wrapperAttributes.getNamedItem('data-anim-autoplay') ? wrapperAttributes.getNamedItem('data-anim-autoplay').value : wrapperAttributes.getNamedItem('data-bm-autoplay') ? wrapperAttributes.getNamedItem('data-bm-autoplay').value : wrapperAttributes.getNamedItem('bm-autoplay') ? wrapperAttributes.getNamedItem('bm-autoplay').value : true;
params.autoplay = autoplay !== "false";
params.name = wrapperAttributes.getNamedItem('data-name') ? wrapperAttributes.getNamedItem('data-name').value : wrapperAttributes.getNamedItem('data-bm-name') ? wrapperAttributes.getNamedItem('data-bm-name').value : wrapperAttributes.getNamedItem('bm-name') ? wrapperAttributes.getNamedItem('bm-name').value : '';
var prerender = wrapperAttributes.getNamedItem('data-anim-prerender') ? wrapperAttributes.getNamedItem('data-anim-prerender').value : wrapperAttributes.getNamedItem('data-bm-prerender') ? wrapperAttributes.getNamedItem('data-bm-prerender').value : wrapperAttributes.getNamedItem('bm-prerender') ? wrapperAttributes.getNamedItem('bm-prerender').value : '';
if(prerender === 'false'){
params.prerender = false;
}
this.setParams(params);
};
AnimationItem.prototype.includeLayers = function(data) {
if(data.op > this.animationData.op){
this.animationData.op = data.op;
this.totalFrames = Math.floor(data.op - this.animationData.ip);
this.animationData.tf = this.totalFrames;
}
var layers = this.animationData.layers;
var i, len = layers.length;
var newLayers = data.layers;
var j, jLen = newLayers.length;
for(j=0;j<jLen;j+=1){
i = 0;
while(i<len){
if(layers[i].id == newLayers[j].id){
layers[i] = newLayers[j];
break;
}
i += 1;
}
}
if(data.chars || data.fonts){
this.renderer.globalData.fontManager.addChars(data.chars);
this.renderer.globalData.fontManager.addFonts(data.fonts, this.renderer.globalData.defs);
}
if(data.assets){
len = data.assets.length;
for(i = 0; i < len; i += 1){
this.animationData.assets.push(data.assets[i]);
}
}
//this.totalFrames = 50;
//this.animationData.tf = 50;
this.animationData.__complete = false;
dataManager.completeData(this.animationData,this.renderer.globalData.fontManager);
this.renderer.includeLayers(data.layers);
if(expressionsPlugin){
expressionsPlugin.initExpressions(this);
}
this.renderer.renderFrame(-1);
this.loadNextSegment();
};
AnimationItem.prototype.loadNextSegment = function() {
var segments = this.animationData.segments;
if(!segments || segments.length === 0 || !this.autoloadSegments){
this.trigger('data_ready');
this.timeCompleted = this.animationData.tf;
return;
}
var segment = segments.shift();
this.timeCompleted = segment.time * this.frameRate;
var xhr = new XMLHttpRequest();
var self = this;
var segmentPath = this.path+this.fileName+'_' + this.segmentPos + '.json';
this.segmentPos += 1;
xhr.open('GET', segmentPath, true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if(xhr.status == 200){
self.includeLayers(JSON.parse(xhr.responseText));
}else{
try{
var response = JSON.parse(xhr.responseText);
self.includeLayers(response);
}catch(err){
}
}
}
};
};
AnimationItem.prototype.loadSegments = function() {
var segments = this.animationData.segments;
if(!segments) {
this.timeCompleted = this.animationData.tf;
}
this.loadNextSegment();
};
AnimationItem.prototype.configAnimation = function (animData) {
var _this = this;
if(this.renderer && this.renderer.destroyed){
return;
}
this.animationData = animData;
this.totalFrames = Math.floor(this.animationData.op - this.animationData.ip);
this.animationData.tf = this.totalFrames;
this.renderer.configAnimation(animData);
if(!animData.assets){
animData.assets = [];
}
if(animData.comps) {
animData.assets = animData.assets.concat(animData.comps);
animData.comps = null;
}
this.renderer.searchExtraCompositions(animData.assets);
this.layers = this.animationData.layers;
this.assets = this.animationData.assets;
this.frameRate = this.animationData.fr;
this.firstFrame = Math.round(this.animationData.ip);
this.frameMult = this.animationData.fr / 1000;
this.trigger('config_ready');
this.imagePreloader = new ImagePreloader();
this.imagePreloader.setAssetsPath(this.assetsPath);
this.imagePreloader.setPath(this.path);
this.imagePreloader.loadAssets(animData.assets, function(err) {
if(!err) {
_this.trigger('loaded_images');
}
});
this.loadSegments();
this.updaFrameModifier();
if(this.renderer.globalData.fontManager){
this.waitForFontsLoaded();
}else{
dataManager.completeData(this.animationData,this.renderer.globalData.fontManager);
this.checkLoaded();
}
};
AnimationItem.prototype.waitForFontsLoaded = (function(){
function checkFontsLoaded(){
if(this.renderer.globalData.fontManager.loaded){
dataManager.completeData(this.animationData,this.renderer.globalData.fontManager);
//this.renderer.buildItems(this.animationData.layers);
this.checkLoaded();
}else{
setTimeout(checkFontsLoaded.bind(this),20);
}
}
return function(){
checkFontsLoaded.bind(this)();
};
}());
AnimationItem.prototype.addPendingElement = function () {
this.pendingElements += 1;
};
AnimationItem.prototype.elementLoaded = function () {
this.pendingElements--;
this.checkLoaded();
};
AnimationItem.prototype.checkLoaded = function () {
if (this.pendingElements === 0) {
if(expressionsPlugin){
expressionsPlugin.initExpressions(this);
}
this.renderer.initItems();
setTimeout(function(){
this.trigger('DOMLoaded');
}.bind(this),0);
this.isLoaded = true;
this.gotoFrame();
if(this.autoplay){
this.play();
}
}
};
AnimationItem.prototype.resize = function () {
this.renderer.updateContainerSize();
};
AnimationItem.prototype.setSubframe = function(flag){
this.subframeEnabled = flag ? true : false;
};
AnimationItem.prototype.gotoFrame = function () {
this.currentFrame = this.subframeEnabled ? this.currentRawFrame : ~~this.currentRawFrame;
if(this.timeCompleted !== this.totalFrames && this.currentFrame > this.timeCompleted){
this.currentFrame = this.timeCompleted;
}
this.trigger('enterFrame');
this.renderFrame();
};
AnimationItem.prototype.renderFrame = function () {
if(this.isLoaded === false){
return;
}
this.renderer.renderFrame(this.currentFrame + this.firstFrame);
};
AnimationItem.prototype.play = function (name) {
if(name && this.name != name){
return;
}
if(this.isPaused === true){
this.isPaused = false;
if(this._idle){
this._idle = false;
this.trigger('_active');
}
}
};
AnimationItem.prototype.pause = function (name) {
if(name && this.name != name){
return;
}
if(this.isPaused === false){
this.isPaused = true;
this._idle = true;
this.trigger('_idle');
}
};
AnimationItem.prototype.togglePause = function (name) {
if(name && this.name != name){
return;
}
if(this.isPaused === true){
this.play();
}else{
this.pause();
}
};
AnimationItem.prototype.stop = function (name) {
if(name && this.name != name){
return;
}
this.pause();
this.playCount = 0;
this.setCurrentRawFrameValue(0);
};
AnimationItem.prototype.goToAndStop = function (value, isFrame, name) {
if(name && this.name != name){
return;
}
if(isFrame){
this.setCurrentRawFrameValue(value);
}else{
this.setCurrentRawFrameValue(value * this.frameModifier);
}
this.pause();
};
AnimationItem.prototype.goToAndPlay = function (value, isFrame, name) {
this.goToAndStop(value, isFrame, name);
this.play();
};
AnimationItem.prototype.advanceTime = function (value) {
if (this.isPaused === true || this.isLoaded === false) {
return;
}
var nextValue = this.currentRawFrame + value * this.frameModifier;
var _isComplete = false;
// Checking if nextValue > totalFrames - 1 for addressing non looping and looping animations.
// If animation won't loop, it should stop at totalFrames - 1. If it will loop it should complete the last frame and then loop.
if (nextValue >= this.totalFrames - 1 && this.frameModifier > 0) {
if (!this.loop || this.playCount === this.loop) {
if (!this.checkSegments(nextValue % this.totalFrames)) {
_isComplete = true;
nextValue = this.totalFrames - 1;
}
} else if (nextValue >= this.totalFrames) {
this.playCount += 1;
if (!this.checkSegments(nextValue % this.totalFrames)) {
this.setCurrentRawFrameValue(nextValue % this.totalFrames);
this.trigger('loopComplete');
}
} else {
this.setCurrentRawFrameValue(nextValue);
}
} else if(nextValue < 0) {
if (!this.checkSegments(nextValue % this.totalFrames)) {
if (this.loop && !(this.playCount-- <= 0 && this.loop !== true)) {
this.setCurrentRawFrameValue(this.totalFrames + (nextValue % this.totalFrames));
this.trigger('loopComplete');
} else {
_isComplete = true;
nextValue = 0;
}
}
} else {
this.setCurrentRawFrameValue(nextValue);
}
if (_isComplete) {
this.setCurrentRawFrameValue(nextValue);
this.pause();
this.trigger('complete');
}
};
AnimationItem.prototype.adjustSegment = function(arr, offset){
this.playCount = 0;
if(arr[1] < arr[0]){
if(this.frameModifier > 0){
if(this.playSpeed < 0){
this.setSpeed(-this.playSpeed);
} else {
this.setDirection(-1);
}
}
this.timeCompleted = this.totalFrames = arr[0] - arr[1];
this.firstFrame = arr[1];
this.setCurrentRawFrameValue(this.totalFrames - 0.001 - offset);
} else if(arr[1] > arr[0]){
if(this.frameModifier < 0){
if(this.playSpeed < 0){
this.setSpeed(-this.playSpeed);
} else {
this.setDirection(1);
}
}
this.timeCompleted = this.totalFrames = arr[1] - arr[0];
this.firstFrame = arr[0];
this.setCurrentRawFrameValue(0.001 + offset);
}
this.trigger('segmentStart');
};
AnimationItem.prototype.setSegment = function (init,end) {
var pendingFrame = -1;
if(this.isPaused) {
if (this.currentRawFrame + this.firstFrame < init) {
pendingFrame = init;
} else if (this.currentRawFrame + this.firstFrame > end) {
pendingFrame = end - init;
}
}
this.firstFrame = init;
this.timeCompleted = this.totalFrames = end - init;
if(pendingFrame !== -1) {
this.goToAndStop(pendingFrame,true);
}
};
AnimationItem.prototype.playSegments = function (arr,forceFlag) {
if(typeof arr[0] === 'object'){
var i, len = arr.length;
for(i=0;i<len;i+=1){
this.segments.push(arr[i]);
}
}else{
this.segments.push(arr);
}
if(forceFlag){
this.checkSegments(0);
}
if(this.isPaused){
this.play();
}
};
AnimationItem.prototype.resetSegments = function (forceFlag) {
this.segments.length = 0;
this.segments.push([this.animationData.ip,this.animationData.op]);
//this.segments.push([this.animationData.ip*this.frameRate,Math.floor(this.animationData.op - this.animationData.ip+this.animationData.ip*this.frameRate)]);
if(forceFlag){
this.checkSegments(0);
}
};
AnimationItem.prototype.checkSegments = function(offset){
if(this.segments.length) {
this.adjustSegment(this.segments.shift(), offset);
return true;
}
return false;
};
AnimationItem.prototype.remove = function (name) {
if(name && this.name != name){
return;
}
this.renderer.destroy();
};
AnimationItem.prototype.destroy = function (name) {
if((name && this.name != name) || (this.renderer && this.renderer.destroyed)){
return;
}
this.renderer.destroy();
this.trigger('destroy');
this._cbs = null;
this.onEnterFrame = this.onLoopComplete = this.onComplete = this.onSegmentStart = this.onDestroy = null;
this.renderer = null;
};
AnimationItem.prototype.setCurrentRawFrameValue = function(value){
this.currentRawFrame = value;
this.gotoFrame();
};
AnimationItem.prototype.setSpeed = function (val) {
this.playSpeed = val;
this.updaFrameModifier();
};
AnimationItem.prototype.setDirection = function (val) {
this.playDirection = val < 0 ? -1 : 1;
this.updaFrameModifier();
};
AnimationItem.prototype.updaFrameModifier = function () {
this.frameModifier = this.frameMult * this.playSpeed * this.playDirection;
};
AnimationItem.prototype.getPath = function () {
return this.path;
};
AnimationItem.prototype.getAssetsPath = function (assetData) {
var path = '';
if(this.assetsPath){
var imagePath = assetData.p;
if(imagePath.indexOf('images/') !== -1){
imagePath = imagePath.split('/')[1];
}
path = this.assetsPath + imagePath;
} else {
path = this.path;
path += assetData.u ? assetData.u : '';
path += assetData.p;
}
return path;
};
AnimationItem.prototype.getAssetData = function (id) {
var i = 0, len = this.assets.length;
while (i < len) {
if(id == this.assets[i].id){
return this.assets[i];
}
i += 1;
}
};
AnimationItem.prototype.hide = function () {
this.renderer.hide();
};
AnimationItem.prototype.show = function () {
this.renderer.show();
};
AnimationItem.prototype.getAssets = function () {
return this.assets;
};
AnimationItem.prototype.getDuration = function (isFrame) {
return isFrame ? this.totalFrames : this.totalFrames / this.frameRate;
};
AnimationItem.prototype.trigger = function(name){
if(this._cbs && this._cbs[name]){
switch(name){
case 'enterFrame':
this.triggerEvent(name,new BMEnterFrameEvent(name,this.currentFrame,this.totalFrames,this.frameMult));
break;
case 'loopComplete':
this.triggerEvent(name,new BMCompleteLoopEvent(name,this.loop,this.playCount,this.frameMult));
break;
case 'complete':
this.triggerEvent(name,new BMCompleteEvent(name,this.frameMult));
break;
case 'segmentStart':
this.triggerEvent(name,new BMSegmentStartEvent(name,this.firstFrame,this.totalFrames));
break;
case 'destroy':
this.triggerEvent(name,new BMDestroyEvent(name,this));
break;
default:
this.triggerEvent(name);
}
}
if(name === 'enterFrame' && this.onEnterFrame){
this.onEnterFrame.call(this,new BMEnterFrameEvent(name,this.currentFrame,this.totalFrames,this.frameMult));
}
if(name === 'loopComplete' && this.onLoopComplete){
this.onLoopComplete.call(this,new BMCompleteLoopEvent(name,this.loop,this.playCount,this.frameMult));
}
if(name === 'complete' && this.onComplete){
this.onComplete.call(this,new BMCompleteEvent(name,this.frameMult));
}
if(name === 'segmentStart' && this.onSegmentStart){
this.onSegmentStart.call(this,new BMSegmentStartEvent(name,this.firstFrame,this.totalFrames));
}
if(name === 'destroy' && this.onDestroy){
this.onDestroy.call(this,new BMDestroyEvent(name,this));
}
};
function EffectsManager(){}
function CanvasRenderer(animationItem, config){
this.animationItem = animationItem;
this.renderConfig = {
clearCanvas: (config && config.clearCanvas !== undefined) ? config.clearCanvas : true,
context: (config && config.context) || null,
progressiveLoad: (config && config.progressiveLoad) || false,
preserveAspectRatio: (config && config.preserveAspectRatio) || 'xMidYMid meet',
className: (config && config.className) || ''
};
this.renderConfig.dpr = (config && config.dpr) || 1;
if (this.animationItem.wrapper) {
this.renderConfig.dpr = (config && config.dpr) || window.devicePixelRatio || 1;
}
this.renderedFrame = -1;
this.globalData = {
frameNum: -1,
_mdf: false,
renderConfig: this.renderConfig,
currentGlobalAlpha: -1
};
var i, len = 15;
this.contextData = new CVContextData();
this.elements = [];
this.pendingElements = [];
this.transformMat = new Matrix();
this.completeLayers = false;
}
extendPrototype([BaseRenderer],CanvasRenderer);
CanvasRenderer.prototype.createShape = function (data) {
return new CVShapeElement(data, this.globalData, this);
};
CanvasRenderer.prototype.createText = function (data) {
return new CVTextElement(data, this.globalData, this);
};
CanvasRenderer.prototype.createImage = function (data) {
return new CVImageElement(data, this.globalData, this);
};
CanvasRenderer.prototype.createComp = function (data) {
return new CVCompElement(data, this.globalData, this);
};
CanvasRenderer.prototype.createSolid = function (data) {
return new CVSolidElement(data, this.globalData, this);
};
CanvasRenderer.prototype.createNull = SVGRenderer.prototype.createNull;
CanvasRenderer.prototype.ctxTransform = function(props){
if(props[0] === 1 && props[1] === 0 && props[4] === 0 && props[5] === 1 && props[12] === 0 && props[13] === 0){
return;
}
if(!this.renderConfig.clearCanvas){
this.canvasContext.transform(props[0],props[1],props[4],props[5],props[12],props[13]);
return;
}
this.transformMat.cloneFromProps(props);
var cProps = this.contextData.cTr.props;
this.transformMat.transform(cProps[0],cProps[1],cProps[2],cProps[3],cProps[4],cProps[5],cProps[6],cProps[7],cProps[8],cProps[9],cProps[10],cProps[11],cProps[12],cProps[13],cProps[14],cProps[15]);
//this.contextData.cTr.transform(props[0],props[1],props[2],props[3],props[4],props[5],props[6],props[7],props[8],props[9],props[10],props[11],props[12],props[13],props[14],props[15]);
this.contextData.cTr.cloneFromProps(this.transformMat.props);
var trProps = this.contextData.cTr.props;
this.canvasContext.setTransform(trProps[0],trProps[1],trProps[4],trProps[5],trProps[12],trProps[13]);
};
CanvasRenderer.prototype.ctxOpacity = function(op){
/*if(op === 1){
return;
}*/
if(!this.renderConfig.clearCanvas){
this.canvasContext.globalAlpha *= op < 0 ? 0 : op;
this.globalData.currentGlobalAlpha = this.contextData.cO;
return;
}
this.contextData.cO *= op < 0 ? 0 : op;
if(this.globalData.currentGlobalAlpha !== this.contextData.cO) {
this.canvasContext.globalAlpha = this.contextData.cO;
this.globalData.currentGlobalAlpha = this.contextData.cO;
}
};
CanvasRenderer.prototype.reset = function(){
if(!this.renderConfig.clearCanvas){
this.canvasContext.restore();
return;
}
this.contextData.reset();
};
CanvasRenderer.prototype.save = function(actionFlag){
if(!this.renderConfig.clearCanvas){
this.canvasContext.save();
return;
}
if(actionFlag){
this.canvasContext.save();
}
var props = this.contextData.cTr.props;
if(this.contextData._length <= this.contextData.cArrPos) {
this.contextData.duplicate();
}
var i, arr = this.contextData.saved[this.contextData.cArrPos];
for (i = 0; i < 16; i += 1) {
arr[i] = props[i];
}
this.contextData.savedOp[this.contextData.cArrPos] = this.contextData.cO;
this.contextData.cArrPos += 1;
};
CanvasRenderer.prototype.restore = function(actionFlag){
if(!this.renderConfig.clearCanvas){
this.canvasContext.restore();
return;
}
if(actionFlag){
this.canvasContext.restore();
this.globalData.blendMode = 'source-over';
}
this.contextData.cArrPos -= 1;
var popped = this.contextData.saved[this.contextData.cArrPos];
var i,arr = this.contextData.cTr.props;
for(i=0;i<16;i+=1){
arr[i] = popped[i];
}
this.canvasContext.setTransform(popped[0],popped[1],popped[4],popped[5],popped[12],popped[13]);
popped = this.contextData.savedOp[this.contextData.cArrPos];
this.contextData.cO = popped;
if(this.globalData.currentGlobalAlpha !== popped) {
this.canvasContext.globalAlpha = popped;
this.globalData.currentGlobalAlpha = popped;
}
};
CanvasRenderer.prototype.configAnimation = function(animData){
if(this.animationItem.wrapper){
this.animationItem.container = createTag('canvas');
this.animationItem.container.style.width = '100%';
this.animationItem.container.style.height = '100%';
//this.animationItem.container.style.transform = 'translate3d(0,0,0)';
//this.animationItem.container.style.webkitTransform = 'translate3d(0,0,0)';
this.animationItem.container.style.transformOrigin = this.animationItem.container.style.mozTransformOrigin = this.animationItem.container.style.webkitTransformOrigin = this.animationItem.container.style['-webkit-transform'] = "0px 0px 0px";
this.animationItem.wrapper.appendChild(this.animationItem.container);
this.canvasContext = this.animationItem.container.getContext('2d');
if(this.renderConfig.className) {
this.animationItem.container.setAttribute('class', this.renderConfig.className);
}
}else{
this.canvasContext = this.renderConfig.context;
}
this.data = animData;
this.globalData.canvasContext = this.canvasContext;
this.globalData.renderer = this;
this.globalData.isDashed = false;
this.globalData.totalFrames = Math.floor(animData.tf);
this.globalData.compWidth = animData.w;
this.globalData.compHeight = animData.h;
this.globalData.frameRate = animData.fr;
this.globalData.frameId = 0;
this.globalData.compSize = {
w: animData.w,
h: animData.h
};
this.globalData.progressiveLoad = this.renderConfig.progressiveLoad;
this.layers = animData.layers;
this.transformCanvas = {
w: animData.w,
h:animData.h,
sx:0,
sy:0,
tx:0,
ty:0
};
this.globalData.fontManager = new FontManager();
this.globalData.fontManager.addChars(animData.chars);
this.globalData.fontManager.addFonts(animData.fonts,document.body);
this.globalData.getAssetData = this.animationItem.getAssetData.bind(this.animationItem);
this.globalData.getAssetsPath = this.animationItem.getAssetsPath.bind(this.animationItem);
this.globalData.elementLoaded = this.animationItem.elementLoaded.bind(this.animationItem);
this.globalData.addPendingElement = this.animationItem.addPendingElement.bind(this.animationItem);
this.globalData.transformCanvas = this.transformCanvas;
this.elements = createSizedArray(animData.layers.length);
this.updateContainerSize();
};
CanvasRenderer.prototype.updateContainerSize = function () {
this.reset();
var elementWidth,elementHeight;
if(this.animationItem.wrapper && this.animationItem.container){
elementWidth = this.animationItem.wrapper.offsetWidth;
elementHeight = this.animationItem.wrapper.offsetHeight;
this.animationItem.container.setAttribute('width',elementWidth * this.renderConfig.dpr );
this.animationItem.container.setAttribute('height',elementHeight * this.renderConfig.dpr);
}else{
elementWidth = this.canvasContext.canvas.width * this.renderConfig.dpr;
elementHeight = this.canvasContext.canvas.height * this.renderConfig.dpr;
}
var elementRel,animationRel;
if(this.renderConfig.preserveAspectRatio.indexOf('meet') !== -1 || this.renderConfig.preserveAspectRatio.indexOf('slice') !== -1){
var par = this.renderConfig.preserveAspectRatio.split(' ');
var fillType = par[1] || 'meet';
var pos = par[0] || 'xMidYMid';
var xPos = pos.substr(0,4);
var yPos = pos.substr(4);
elementRel = elementWidth/elementHeight;
animationRel = this.transformCanvas.w/this.transformCanvas.h;
if(animationRel>elementRel && fillType === 'meet' || animationRel<elementRel && fillType === 'slice'){
this.transformCanvas.sx = elementWidth/(this.transformCanvas.w/this.renderConfig.dpr);
this.transformCanvas.sy = elementWidth/(this.transformCanvas.w/this.renderConfig.dpr);
}else{
this.transformCanvas.sx = elementHeight/(this.transformCanvas.h / this.renderConfig.dpr);
this.transformCanvas.sy = elementHeight/(this.transformCanvas.h / this.renderConfig.dpr);
}
if(xPos === 'xMid' && ((animationRel<elementRel && fillType==='meet') || (animationRel>elementRel && fillType === 'slice'))){
this.transformCanvas.tx = (elementWidth-this.transformCanvas.w*(elementHeight/this.transformCanvas.h))/2*this.renderConfig.dpr;
} else if(xPos === 'xMax' && ((animationRel<elementRel && fillType==='meet') || (animationRel>elementRel && fillType === 'slice'))){
this.transformCanvas.tx = (elementWidth-this.transformCanvas.w*(elementHeight/this.transformCanvas.h))*this.renderConfig.dpr;
} else {
this.transformCanvas.tx = 0;
}
if(yPos === 'YMid' && ((animationRel>elementRel && fillType==='meet') || (animationRel<elementRel && fillType === 'slice'))){
this.transformCanvas.ty = ((elementHeight-this.transformCanvas.h*(elementWidth/this.transformCanvas.w))/2)*this.renderConfig.dpr;
} else if(yPos === 'YMax' && ((animationRel>elementRel && fillType==='meet') || (animationRel<elementRel && fillType === 'slice'))){
this.transformCanvas.ty = ((elementHeight-this.transformCanvas.h*(elementWidth/this.transformCanvas.w)))*this.renderConfig.dpr;
} else {
this.transformCanvas.ty = 0;
}
}else if(this.renderConfig.preserveAspectRatio == 'none'){
this.transformCanvas.sx = elementWidth/(this.transformCanvas.w/this.renderConfig.dpr);
this.transformCanvas.sy = elementHeight/(this.transformCanvas.h/this.renderConfig.dpr);
this.transformCanvas.tx = 0;
this.transformCanvas.ty = 0;
}else{
this.transformCanvas.sx = this.renderConfig.dpr;
this.transformCanvas.sy = this.renderConfig.dpr;
this.transformCanvas.tx = 0;
this.transformCanvas.ty = 0;
}
this.transformCanvas.props = [this.transformCanvas.sx,0,0,0,0,this.transformCanvas.sy,0,0,0,0,1,0,this.transformCanvas.tx,this.transformCanvas.ty,0,1];
/*var i, len = this.elements.length;
for(i=0;i<len;i+=1){
if(this.elements[i] && this.elements[i].data.ty === 0){
this.elements[i].resize(this.globalData.transformCanvas);
}
}*/
this.ctxTransform(this.transformCanvas.props);
this.canvasContext.beginPath();
this.canvasContext.rect(0,0,this.transformCanvas.w,this.transformCanvas.h);
this.canvasContext.closePath();
this.canvasContext.clip();
};
CanvasRenderer.prototype.destroy = function () {
if(this.renderConfig.clearCanvas) {
this.animationItem.wrapper.innerHTML = '';
}
var i, len = this.layers ? this.layers.length : 0;
for (i = len - 1; i >= 0; i-=1) {
if(this.elements[i]) {
this.elements[i].destroy();
}
}
this.elements.length = 0;
this.globalData.canvasContext = null;
this.animationItem.container = null;
this.destroyed = true;
};
CanvasRenderer.prototype.renderFrame = function(num){
if((this.renderedFrame == num && this.renderConfig.clearCanvas === true) || this.destroyed || num === -1){
return;
}
this.renderedFrame = num;
this.globalData.frameNum = num - this.animationItem._isFirstFrame;
this.globalData.frameId += 1;
this.globalData._mdf = false;
this.globalData.projectInterface.currentFrame = num;
// console.log('--------');
// console.log('NEW: ',num);
var i, len = this.layers.length;
if(!this.completeLayers){
this.checkLayers(num);
}
for (i = 0; i < len; i++) {
if(this.completeLayers || this.elements[i]){
this.elements[i].prepareFrame(num - this.layers[i].st);
}
}
if(this.globalData._mdf) {
if(this.renderConfig.clearCanvas === true){
this.canvasContext.clearRect(0, 0, this.transformCanvas.w, this.transformCanvas.h);
}else{
this.save();
}
for (i = len - 1; i >= 0; i-=1) {
if(this.completeLayers || this.elements[i]){
this.elements[i].renderFrame();
}
}
if(this.renderConfig.clearCanvas !== true){
this.restore();
}
}
};
CanvasRenderer.prototype.buildItem = function(pos){
var elements = this.elements;
if(elements[pos] || this.layers[pos].ty == 99){
return;
}
var element = this.createItem(this.layers[pos], this,this.globalData);
elements[pos] = element;
element.initExpressions();
/*if(this.layers[pos].ty === 0){
element.resize(this.globalData.transformCanvas);
}*/
};
CanvasRenderer.prototype.checkPendingElements = function(){
while(this.pendingElements.length){
var element = this.pendingElements.pop();
element.checkParenting();
}
};
CanvasRenderer.prototype.hide = function(){
this.animationItem.container.style.display = 'none';
};
CanvasRenderer.prototype.show = function(){
this.animationItem.container.style.display = 'block';
};
function HybridRenderer(animationItem, config){
this.animationItem = animationItem;
this.layers = null;
this.renderedFrame = -1;
this.renderConfig = {
className: (config && config.className) || '',
hideOnTransparent: (config && config.hideOnTransparent === false) ? false : true
};
this.globalData = {
_mdf: false,
frameNum: -1,
renderConfig: this.renderConfig
};
this.pendingElements = [];
this.elements = [];
this.threeDElements = [];
this.destroyed = false;
this.camera = null;
this.supports3d = true;
}
extendPrototype([BaseRenderer],HybridRenderer);
HybridRenderer.prototype.buildItem = SVGRenderer.prototype.buildItem;
HybridRenderer.prototype.checkPendingElements = function(){
while(this.pendingElements.length){
var element = this.pendingElements.pop();
element.checkParenting();
}
};
HybridRenderer.prototype.appendElementInPos = function(element, pos){
var newDOMElement = element.getBaseElement();
if(!newDOMElement){
return;
}
var layer = this.layers[pos];
if(!layer.ddd || !this.supports3d){
if(this.threeDElements) {
this.addTo3dContainer(newDOMElement,pos);
} else {
var i = 0;
var nextDOMElement, nextLayer, tmpDOMElement;
while(i<pos){
if(this.elements[i] && this.elements[i]!== true && this.elements[i].getBaseElement){
nextLayer = this.elements[i];
tmpDOMElement = this.layers[i].ddd ? this.getThreeDContainerByPos(i) : nextLayer.getBaseElement();
nextDOMElement = tmpDOMElement || nextDOMElement;
}
i += 1;
}
if(nextDOMElement){
if(!layer.ddd || !this.supports3d){
this.layerElement.insertBefore(newDOMElement, nextDOMElement);
}
} else {
if(!layer.ddd || !this.supports3d){
this.layerElement.appendChild(newDOMElement);
}
}
}
} else {
this.addTo3dContainer(newDOMElement,pos);
}
};
HybridRenderer.prototype.createShape = function (data) {
if(!this.supports3d){
return new SVGShapeElement(data, this.globalData, this);
}
return new HShapeElement(data, this.globalData, this);
};
HybridRenderer.prototype.createText = function (data) {
if(!this.supports3d){
return new SVGTextElement(data, this.globalData, this);
}
return new HTextElement(data, this.globalData, this);
};
HybridRenderer.prototype.createCamera = function (data) {
this.camera = new HCameraElement(data, this.globalData, this);
return this.camera;
};
HybridRenderer.prototype.createImage = function (data) {
if(!this.supports3d){
return new IImageElement(data, this.globalData, this);
}
return new HImageElement(data, this.globalData, this);
};
HybridRenderer.prototype.createComp = function (data) {
if(!this.supports3d){
return new SVGCompElement(data, this.globalData, this);
}
return new HCompElement(data, this.globalData, this);
};
HybridRenderer.prototype.createSolid = function (data) {
if(!this.supports3d){
return new ISolidElement(data, this.globalData, this);
}
return new HSolidElement(data, this.globalData, this);
};
HybridRenderer.prototype.createNull = SVGRenderer.prototype.createNull;
HybridRenderer.prototype.getThreeDContainerByPos = function(pos){
var i = 0, len = this.threeDElements.length;
while(i<len) {
if(this.threeDElements[i].startPos <= pos && this.threeDElements[i].endPos >= pos) {
return this.threeDElements[i].perspectiveElem;
}
i += 1;
}
};
HybridRenderer.prototype.createThreeDContainer = function(pos, type){
var perspectiveElem = createTag('div');
styleDiv(perspectiveElem);
var container = createTag('div');
styleDiv(container);
if(type === '3d') {
perspectiveElem.style.width = this.globalData.compSize.w+'px';
perspectiveElem.style.height = this.globalData.compSize.h+'px';
perspectiveElem.style.transformOrigin = perspectiveElem.style.mozTransformOrigin = perspectiveElem.style.webkitTransformOrigin = "50% 50%";
container.style.transform = container.style.webkitTransform = 'matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)';
}
perspectiveElem.appendChild(container);
//this.resizerElem.appendChild(perspectiveElem);
var threeDContainerData = {
container:container,
perspectiveElem:perspectiveElem,
startPos: pos,
endPos: pos,
type: type
};
this.threeDElements.push(threeDContainerData);
return threeDContainerData;
};
HybridRenderer.prototype.build3dContainers = function(){
var i, len = this.layers.length;
var lastThreeDContainerData;
var currentContainer = '';
for(i=0;i<len;i+=1){
if(this.layers[i].ddd && this.layers[i].ty !== 3){
if(currentContainer !== '3d'){
currentContainer = '3d';
lastThreeDContainerData = this.createThreeDContainer(i,'3d');
}
lastThreeDContainerData.endPos = Math.max(lastThreeDContainerData.endPos,i);
} else {
if(currentContainer !== '2d'){
currentContainer = '2d';
lastThreeDContainerData = this.createThreeDContainer(i,'2d');
}
lastThreeDContainerData.endPos = Math.max(lastThreeDContainerData.endPos,i);
}
}
len = this.threeDElements.length;
for(i = len - 1; i >= 0; i --) {
this.resizerElem.appendChild(this.threeDElements[i].perspectiveElem);
}
};
HybridRenderer.prototype.addTo3dContainer = function(elem,pos){
var i = 0, len = this.threeDElements.length;
while(i<len){
if(pos <= this.threeDElements[i].endPos){
var j = this.threeDElements[i].startPos;
var nextElement;
while(j<pos){
if(this.elements[j] && this.elements[j].getBaseElement){
nextElement = this.elements[j].getBaseElement();
}
j += 1;
}
if(nextElement){
this.threeDElements[i].container.insertBefore(elem, nextElement);
} else {
this.threeDElements[i].container.appendChild(elem);
}
break;
}
i += 1;
}
};
HybridRenderer.prototype.configAnimation = function(animData){
var resizerElem = createTag('div');
var wrapper = this.animationItem.wrapper;
resizerElem.style.width = animData.w+'px';
resizerElem.style.height = animData.h+'px';
this.resizerElem = resizerElem;
styleDiv(resizerElem);
resizerElem.style.transformStyle = resizerElem.style.webkitTransformStyle = resizerElem.style.mozTransformStyle = "flat";
if(this.renderConfig.className) {
resizerElem.setAttribute('class', this.renderConfig.className);
}
wrapper.appendChild(resizerElem);
resizerElem.style.overflow = 'hidden';
var svg = createNS('svg');
svg.setAttribute('width','1');
svg.setAttribute('height','1');
styleDiv(svg);
this.resizerElem.appendChild(svg);
var defs = createNS('defs');
svg.appendChild(defs);
this.globalData.defs = defs;
this.data = animData;
//Mask animation
this.globalData.getAssetData = this.animationItem.getAssetData.bind(this.animationItem);
this.globalData.getAssetsPath = this.animationItem.getAssetsPath.bind(this.animationItem);
this.globalData.elementLoaded = this.animationItem.elementLoaded.bind(this.animationItem);
this.globalData.frameId = 0;
this.globalData.compSize = {
w: animData.w,
h: animData.h
};
this.globalData.frameRate = animData.fr;
this.layers = animData.layers;
this.globalData.fontManager = new FontManager();
this.globalData.fontManager.addChars(animData.chars);
this.globalData.fontManager.addFonts(animData.fonts,svg);
this.layerElement = this.resizerElem;
this.build3dContainers();
this.updateContainerSize();
};
HybridRenderer.prototype.destroy = function () {
this.animationItem.wrapper.innerHTML = '';
this.animationItem.container = null;
this.globalData.defs = null;
var i, len = this.layers ? this.layers.length : 0;
for (i = 0; i < len; i++) {
this.elements[i].destroy();
}
this.elements.length = 0;
this.destroyed = true;
this.animationItem = null;
};
HybridRenderer.prototype.updateContainerSize = function () {
var elementWidth = this.animationItem.wrapper.offsetWidth;
var elementHeight = this.animationItem.wrapper.offsetHeight;
var elementRel = elementWidth/elementHeight;
var animationRel = this.globalData.compSize.w/this.globalData.compSize.h;
var sx,sy,tx,ty;
if(animationRel>elementRel){
sx = elementWidth/(this.globalData.compSize.w);
sy = elementWidth/(this.globalData.compSize.w);
tx = 0;
ty = ((elementHeight-this.globalData.compSize.h*(elementWidth/this.globalData.compSize.w))/2);
}else{
sx = elementHeight/(this.globalData.compSize.h);
sy = elementHeight/(this.globalData.compSize.h);
tx = (elementWidth-this.globalData.compSize.w*(elementHeight/this.globalData.compSize.h))/2;
ty = 0;
}
this.resizerElem.style.transform = this.resizerElem.style.webkitTransform = 'matrix3d(' + sx + ',0,0,0,0,'+sy+',0,0,0,0,1,0,'+tx+','+ty+',0,1)';
};
HybridRenderer.prototype.renderFrame = SVGRenderer.prototype.renderFrame;
HybridRenderer.prototype.hide = function(){
this.resizerElem.style.display = 'none';
};
HybridRenderer.prototype.show = function(){
this.resizerElem.style.display = 'block';
};
HybridRenderer.prototype.initItems = function(){
this.buildAllItems();
if(this.camera){
this.camera.setup();
} else {
var cWidth = this.globalData.compSize.w;
var cHeight = this.globalData.compSize.h;
var i, len = this.threeDElements.length;
for(i=0;i<len;i+=1){
this.threeDElements[i].perspectiveElem.style.perspective = this.threeDElements[i].perspectiveElem.style.webkitPerspective = Math.sqrt(Math.pow(cWidth,2) + Math.pow(cHeight,2)) + 'px';
}
}
};
HybridRenderer.prototype.searchExtraCompositions = function(assets){
var i, len = assets.length;
var floatingContainer = createTag('div');
for(i=0;i<len;i+=1){
if(assets[i].xt){
var comp = this.createComp(assets[i],floatingContainer,this.globalData.comp,null);
comp.initExpressions();
this.globalData.projectInterface.registerComposition(comp);
}
}
};
function CVShapeData(element, data) {
this.nodes = [];
this.trNodes = [];
this.tr = [0,0,0,0,0,0];
var ty = 4;
if(data.ty == 'rc'){
ty = 5;
}else if(data.ty == 'el'){
ty = 6;
}else if(data.ty == 'sr'){
ty = 7;
}
this.sh = ShapePropertyFactory.getShapeProp(element,data,ty,element);
this.st = false;
this.fl = false;
}
CVShapeData.prototype.setAsAnimated = SVGShapeData.prototype.setAsAnimated;
function CVContextData() {
this.saved = [];
this.cArrPos = 0;
this.cTr = new Matrix();
this.cO = 1;
var i, len = 15;
this.savedOp = createTypedArray('float32', len);
for(i=0;i<len;i+=1){
this.saved[i] = createTypedArray('float32', 16);
}
this._length = len;
}
CVContextData.prototype.duplicate = function() {
var newLength = this._length * 2;
var currentSavedOp = this.savedOp;
this.savedOp = createTypedArray('float32', newLength);
this.savedOp.set(currentSavedOp);
var i = 0;
for(i = this._length; i < newLength; i += 1) {
this.saved[i] = createTypedArray('float32', 16);
}
this._length = newLength;
};
CVContextData.prototype.reset = function() {
this.cArrPos = 0;
this.cTr.reset();
this.cO = 1;
};
function CVBaseElement(){
}
CVBaseElement.prototype = {
createElements: function(){},
initRendererElement: function(){},
createContainerElements: function(){
this.canvasContext = this.globalData.canvasContext;
this.renderableEffectsManager = new CVEffects(this);
},
createContent: function(){},
setBlendMode: function(){
var globalData = this.globalData;
if(globalData.blendMode !== this.data.bm) {
globalData.blendMode = this.data.bm;
var blendModeValue = this.getBlendMode();
globalData.canvasContext.globalCompositeOperation = blendModeValue;
}
},
addMasks: function(){
this.maskManager = new CVMaskElement(this.data, this);
},
hideElement: function(){
if (!this.hidden && (!this.isInRange || this.isTransparent)) {
this.hidden = true;
}
},
showElement: function(){
if (this.isInRange && !this.isTransparent){
this.hidden = false;
this._isFirstFrame = true;
this.maskManager._isFirstFrame = true;
}
},
renderFrame: function() {
if (this.hidden) {
return;
}
this.renderTransform();
this.renderRenderable();
this.setBlendMode();
this.globalData.renderer.save();
this.globalData.renderer.ctxTransform(this.finalTransform.mat.props);
this.globalData.renderer.ctxOpacity(this.finalTransform.mProp.o.v);
this.renderInnerContent();
this.globalData.renderer.restore();
if(this.maskManager.hasMasks) {
this.globalData.renderer.restore(true);
}
if (this._isFirstFrame) {
this._isFirstFrame = false;
}
},
destroy: function(){
this.canvasContext = null;
this.data = null;
this.globalData = null;
this.maskManager.destroy();
},
mHelper: new Matrix()
};
CVBaseElement.prototype.hide = CVBaseElement.prototype.hideElement;
CVBaseElement.prototype.show = CVBaseElement.prototype.showElement;
function CVImageElement(data, globalData, comp){
this.failed = false;
this.img = new Image();
this.assetData = globalData.getAssetData(data.refId);
this.initElement(data,globalData,comp);
this.globalData.addPendingElement();
}
extendPrototype([BaseElement, TransformElement, CVBaseElement, HierarchyElement, FrameElement, RenderableElement], CVImageElement);
CVImageElement.prototype.initElement = SVGShapeElement.prototype.initElement;
CVImageElement.prototype.prepareFrame = IImageElement.prototype.prepareFrame;
CVImageElement.prototype.imageLoaded = function() {
this.globalData.elementLoaded();
if(this.assetData.w !== this.img.width || this.assetData.h !== this.img.height){
var canvas = createTag('canvas');
canvas.width = this.assetData.w;
canvas.height = this.assetData.h;
var ctx = canvas.getContext('2d');
var imgW = this.img.width;
var imgH = this.img.height;
var imgRel = imgW / imgH;
var canvasRel = this.assetData.w/this.assetData.h;
var widthCrop, heightCrop;
if(imgRel>canvasRel){
heightCrop = imgH;
widthCrop = heightCrop*canvasRel;
} else {
widthCrop = imgW;
heightCrop = widthCrop/canvasRel;
}
ctx.drawImage(this.img,(imgW-widthCrop)/2,(imgH-heightCrop)/2,widthCrop,heightCrop,0,0,this.assetData.w,this.assetData.h);
this.img = canvas;
}
};
CVImageElement.prototype.imageFailed = function() {
this.failed = true;
this.globalData.elementLoaded();
};
CVImageElement.prototype.createContent = function(){
var img = this.img;
img.addEventListener('load', this.imageLoaded.bind(this), false);
img.addEventListener('error', this.imageFailed.bind(this), false);
var assetPath = this.globalData.getAssetsPath(this.assetData);
img.src = assetPath;
};
CVImageElement.prototype.renderInnerContent = function(parentMatrix){
if (this.failed) {
return;
}
this.canvasContext.drawImage(this.img, 0, 0);
};
CVImageElement.prototype.destroy = function(){
this.img = null;
};
function CVCompElement(data, globalData, comp) {
this.completeLayers = false;
this.layers = data.layers;
this.pendingElements = [];
this.elements = createSizedArray(this.layers.length);
this.initElement(data, globalData, comp);
this.tm = data.tm ? PropertyFactory.getProp(this,data.tm,0,globalData.frameRate, this) : {_placeholder:true};
}
extendPrototype([CanvasRenderer, ICompElement, CVBaseElement], CVCompElement);
CVCompElement.prototype.renderInnerContent = function() {
var i,len = this.layers.length;
for( i = len - 1; i >= 0; i -= 1 ){
if(this.completeLayers || this.elements[i]){
this.elements[i].renderFrame();
}
}
};
CVCompElement.prototype.destroy = function(){
var i,len = this.layers.length;
for( i = len - 1; i >= 0; i -= 1 ){
if(this.elements[i]) {
this.elements[i].destroy();
}
}
this.layers = null;
this.elements = null;
};
function CVMaskElement(data,element){
this.data = data;
this.element = element;
this.masksProperties = this.data.masksProperties || [];
this.viewData = createSizedArray(this.masksProperties.length);
var i, len = this.masksProperties.length, hasMasks = false;
for (i = 0; i < len; i++) {
if(this.masksProperties[i].mode !== 'n'){
hasMasks = true;
}
this.viewData[i] = ShapePropertyFactory.getShapeProp(this.element,this.masksProperties[i],3);
}
this.hasMasks = hasMasks;
if(hasMasks) {
this.element.addRenderableComponent(this);
}
}
CVMaskElement.prototype.renderFrame = function () {
if(!this.hasMasks){
return;
}
var transform = this.element.finalTransform.mat;
var ctx = this.element.canvasContext;
var i, len = this.masksProperties.length;
var pt,pts,data;
ctx.beginPath();
for (i = 0; i < len; i++) {
if(this.masksProperties[i].mode !== 'n'){
if (this.masksProperties[i].inv) {
ctx.moveTo(0, 0);
ctx.lineTo(this.element.globalData.compWidth, 0);
ctx.lineTo(this.element.globalData.compWidth, this.element.globalData.compHeight);
ctx.lineTo(0, this.element.globalData.compHeight);
ctx.lineTo(0, 0);
}
data = this.viewData[i].v;
pt = transform.applyToPointArray(data.v[0][0],data.v[0][1],0);
ctx.moveTo(pt[0], pt[1]);
var j, jLen = data._length;
for (j = 1; j < jLen; j++) {
pts = transform.applyToTriplePoints(data.o[j - 1], data.i[j], data.v[j]);
ctx.bezierCurveTo(pts[0], pts[1], pts[2], pts[3], pts[4], pts[5]);
}
pts = transform.applyToTriplePoints(data.o[j - 1], data.i[0], data.v[0]);
ctx.bezierCurveTo(pts[0], pts[1], pts[2], pts[3], pts[4], pts[5]);
}
}
this.element.globalData.renderer.save(true);
ctx.clip();
};
CVMaskElement.prototype.getMaskProperty = MaskElement.prototype.getMaskProperty;
CVMaskElement.prototype.destroy = function(){
this.element = null;
};
function CVShapeElement(data, globalData, comp) {
this.shapes = [];
this.shapesData = data.shapes;
this.stylesList = [];
this.itemsData = [];
this.prevViewData = [];
this.shapeModifiers = [];
this.processedElements = [];
this.initElement(data, globalData, comp);
}
extendPrototype([BaseElement,TransformElement,CVBaseElement,IShapeElement,HierarchyElement,FrameElement,RenderableElement], CVShapeElement);
CVShapeElement.prototype.initElement = RenderableDOMElement.prototype.initElement;
CVShapeElement.prototype.transformHelper = {opacity:1,mat:new Matrix(),_matMdf:false,_opMdf:false};
CVShapeElement.prototype.dashResetter = [];
CVShapeElement.prototype.createContent = function(){
this.searchShapes(this.shapesData,this.itemsData,this.prevViewData, true);
};
CVShapeElement.prototype.createStyleElement = function(data){
var styleElem = {
data: data,
type: data.ty,
elements: []
};
var elementData = {};
if(data.ty == 'fl' || data.ty == 'st'){
elementData.c = PropertyFactory.getProp(this,data.c,1,255,this);
if(!elementData.c.k){
styleElem.co = 'rgb('+bm_floor(elementData.c.v[0])+','+bm_floor(elementData.c.v[1])+','+bm_floor(elementData.c.v[2])+')';
}
}
elementData.o = PropertyFactory.getProp(this,data.o,0,0.01,this);
if(data.ty == 'st') {
styleElem.lc = this.lcEnum[data.lc] || 'round';
styleElem.lj = this.ljEnum[data.lj] || 'round';
if(data.lj == 1) {
styleElem.ml = data.ml;
}
elementData.w = PropertyFactory.getProp(this,data.w,0,null,this);
if(!elementData.w.k){
styleElem.wi = elementData.w.v;
}
if(data.d){
var d = new DashProperty(this,data.d,'canvas');
elementData.d = d;
if(!elementData.d.k){
styleElem.da = elementData.d.dashArray;
styleElem.do = elementData.d.dashoffset[0];
}
}
} else {
styleElem.r = data.r === 2 ? 'evenodd' : 'nonzero';
}
this.stylesList.push(styleElem);
elementData.style = styleElem;
return elementData;
};
CVShapeElement.prototype.createGroupElement = function(data) {
var elementData = {
it: [],
prevViewData: []
};
return elementData;
};
CVShapeElement.prototype.createTransformElement = function(data) {
var elementData = {
transform : {
mat: new Matrix(),
opacity: 1,
_matMdf:false,
_opMdf:false,
op: PropertyFactory.getProp(this,data.o,0,0.01,this),
mProps: TransformPropertyFactory.getTransformProperty(this,data,this)
},
elements: []
};
return elementData;
};
CVShapeElement.prototype.createShapeElement = function(data) {
var elementData = new CVShapeData(this, data);
this.shapes.push(elementData);
this.addShapeToModifiers(elementData);
var j, jLen = this.stylesList.length;
var hasStrokes = false, hasFills = false;
for(j=0;j<jLen;j+=1){
if(!this.stylesList[j].closed){
this.stylesList[j].elements.push(elementData);
if(this.stylesList[j].type === 'st'){
hasStrokes = true;
}else{
hasFills = true;
}
}
}
elementData.st = hasStrokes;
elementData.fl = hasFills;
return elementData;
};
CVShapeElement.prototype.reloadShapes = function(){
this._isFirstFrame = true;
var i, len = this.itemsData.length;
for(i=0;i<len;i+=1){
this.prevViewData[i] = this.itemsData[i];
}
this.searchShapes(this.shapesData,this.itemsData,this.prevViewData, true);
len = this.dynamicProperties.length;
for(i=0;i<len;i+=1){
this.dynamicProperties[i].getValue();
}
this.renderModifiers();
};
CVShapeElement.prototype.searchShapes = function(arr,itemsData, prevViewData, render){
var i, len = arr.length - 1;
var j, jLen;
var ownArrays = [], ownModifiers = [], processedPos, modifier;
for(i=len;i>=0;i-=1){
processedPos = this.searchProcessedElement(arr[i]);
if(!processedPos){
arr[i]._render = render;
} else {
itemsData[i] = prevViewData[processedPos - 1];
}
if(arr[i].ty == 'fl' || arr[i].ty == 'st'){
if(!processedPos){
itemsData[i] = this.createStyleElement(arr[i]);
} else {
itemsData[i].style.closed = false;
}
ownArrays.push(itemsData[i].style);
}else if(arr[i].ty == 'gr'){
if(!processedPos){
itemsData[i] = this.createGroupElement(arr[i]);
} else {
jLen = itemsData[i].it.length;
for(j=0;j<jLen;j+=1){
itemsData[i].prevViewData[j] = itemsData[i].it[j];
}
}
this.searchShapes(arr[i].it,itemsData[i].it,itemsData[i].prevViewData, render);
}else if(arr[i].ty == 'tr'){
if(!processedPos){
itemsData[i] = this.createTransformElement(arr[i]);
}
}else if(arr[i].ty == 'sh' || arr[i].ty == 'rc' || arr[i].ty == 'el' || arr[i].ty == 'sr'){
if(!processedPos){
itemsData[i] = this.createShapeElement(arr[i]);
}
}else if(arr[i].ty == 'tm' || arr[i].ty == 'rd'){
if(!processedPos){
modifier = ShapeModifiers.getModifier(arr[i].ty);
modifier.init(this,arr[i]);
itemsData[i] = modifier;
this.shapeModifiers.push(modifier);
} else {
modifier = itemsData[i];
modifier.closed = false;
}
ownModifiers.push(modifier);
} else if(arr[i].ty == 'rp'){
if(!processedPos){
modifier = ShapeModifiers.getModifier(arr[i].ty);
itemsData[i] = modifier;
modifier.init(this,arr,i,itemsData);
this.shapeModifiers.push(modifier);
render = false;
}else{
modifier = itemsData[i];
modifier.closed = true;
}
ownModifiers.push(modifier);
}
this.addProcessedElement(arr[i], i + 1);
}
len = ownArrays.length;
for(i=0;i<len;i+=1){
ownArrays[i].closed = true;
}
len = ownModifiers.length;
for(i=0;i<len;i+=1){
ownModifiers[i].closed = true;
}
};
CVShapeElement.prototype.renderInnerContent = function() {
this.transformHelper.mat.reset();
this.transformHelper.opacity = 1;
this.transformHelper._matMdf = false;
this.transformHelper._opMdf = false;
this.renderModifiers();
this.renderShape(this.transformHelper,this.shapesData,this.itemsData,true);
};
CVShapeElement.prototype.renderShapeTransform = function(parentTransform, groupTransform) {
var props, groupMatrix;
if(parentTransform._opMdf || groupTransform.op._mdf || this._isFirstFrame) {
groupTransform.opacity = parentTransform.opacity;
groupTransform.opacity *= groupTransform.op.v;
groupTransform._opMdf = true;
}
if(parentTransform._matMdf || groupTransform.mProps._mdf || this._isFirstFrame) {
groupMatrix = groupTransform.mat;
groupMatrix.cloneFromProps(groupTransform.mProps.v.props);
groupTransform._matMdf = true;
props = parentTransform.mat.props;
groupMatrix.transform(props[0],props[1],props[2],props[3],props[4],props[5],props[6],props[7],props[8],props[9],props[10],props[11],props[12],props[13],props[14],props[15]);
}
};
CVShapeElement.prototype.drawLayer = function() {
var i, len = this.stylesList.length;
var j, jLen, k, kLen,elems,nodes, renderer = this.globalData.renderer, ctx = this.globalData.canvasContext, type, currentStyle;
for(i=0;i<len;i+=1){
currentStyle = this.stylesList[i];
type = currentStyle.type;
if((type === 'st' && currentStyle.wi === 0) || !currentStyle.data._render || currentStyle.coOp === 0){
continue;
}
renderer.save();
elems = currentStyle.elements;
if(type === 'st'){
ctx.strokeStyle = currentStyle.co;
ctx.lineWidth = currentStyle.wi;
ctx.lineCap = currentStyle.lc;
ctx.lineJoin = currentStyle.lj;
ctx.miterLimit = currentStyle.ml || 0;
}else{
ctx.fillStyle = currentStyle.co;
}
renderer.ctxOpacity(currentStyle.coOp);
if(this.globalData.currentGlobalAlpha !== 0) {
if(type !== 'st'){
ctx.beginPath();
}
jLen = elems.length;
for(j=0;j<jLen;j+=1){
if(type === 'st'){
ctx.beginPath();
if(currentStyle.da){
ctx.setLineDash(currentStyle.da);
ctx.lineDashOffset = currentStyle.do;
this.globalData.isDashed = true;
}else if(this.globalData.isDashed){
ctx.setLineDash(this.dashResetter);
this.globalData.isDashed = false;
}
}
nodes = elems[j].trNodes;
kLen = nodes.length;
for(k=0;k<kLen;k+=1){
if(nodes[k].t == 'm'){
ctx.moveTo(nodes[k].p[0],nodes[k].p[1]);
}else if(nodes[k].t == 'c'){
ctx.bezierCurveTo(nodes[k].pts[0],nodes[k].pts[1],nodes[k].pts[2],nodes[k].pts[3],nodes[k].pts[4],nodes[k].pts[5]);
}else{
ctx.closePath();
}
}
if(type === 'st'){
ctx.stroke();
}
}
if(type !== 'st'){
ctx.fill(currentStyle.r);
}
}
renderer.restore();
}
};
CVShapeElement.prototype.renderShape = function(parentTransform,items,data,isMain){
var i, len = items.length - 1;
var groupTransform;
groupTransform = parentTransform;
for(i=len;i>=0;i-=1){
if(items[i].ty == 'tr'){
groupTransform = data[i].transform;
this.renderShapeTransform(parentTransform, groupTransform);
}else if(items[i].ty == 'sh' || items[i].ty == 'el' || items[i].ty == 'rc' || items[i].ty == 'sr'){
this.renderPath(items[i],data[i],groupTransform);
}else if(items[i].ty == 'fl'){
this.renderFill(items[i],data[i],groupTransform);
}else if(items[i].ty == 'st'){
this.renderStroke(items[i],data[i],groupTransform);
}else if(items[i].ty == 'gr'){
this.renderShape(groupTransform,items[i].it,data[i].it);
}else if(items[i].ty == 'tm'){
//
}
}
if(isMain){
this.drawLayer();
}
};
CVShapeElement.prototype.renderPath = function(pathData,itemData,groupTransform){
var len, i, j,jLen;
var redraw = groupTransform._matMdf || itemData.sh._mdf || this._isFirstFrame;
if(redraw) {
var paths = itemData.sh.paths, groupTransformMat = groupTransform.mat;
jLen = pathData._render === false ? 0 : paths._length;
var pathStringTransformed = itemData.trNodes;
pathStringTransformed.length = 0;
for(j=0;j<jLen;j+=1){
var pathNodes = paths.shapes[j];
if(pathNodes && pathNodes.v){
len = pathNodes._length;
for (i = 1; i < len; i += 1) {
if (i == 1) {
pathStringTransformed.push({
t: 'm',
p: groupTransformMat.applyToPointArray(pathNodes.v[0][0], pathNodes.v[0][1], 0)
});
}
pathStringTransformed.push({
t: 'c',
pts: groupTransformMat.applyToTriplePoints(pathNodes.o[i - 1], pathNodes.i[i], pathNodes.v[i])
});
}
if (len == 1) {
pathStringTransformed.push({
t: 'm',
p: groupTransformMat.applyToPointArray(pathNodes.v[0][0], pathNodes.v[0][1], 0)
});
}
if (pathNodes.c && len) {
pathStringTransformed.push({
t: 'c',
pts: groupTransformMat.applyToTriplePoints(pathNodes.o[i - 1], pathNodes.i[0], pathNodes.v[0])
});
pathStringTransformed.push({
t: 'z'
});
}
itemData.lStr = pathStringTransformed;
}
}
if (itemData.st) {
for (i = 0; i < 16; i += 1) {
itemData.tr[i] = groupTransform.mat.props[i];
}
}
itemData.trNodes = pathStringTransformed;
}
};
CVShapeElement.prototype.renderFill = function(styleData,itemData, groupTransform){
var styleElem = itemData.style;
if(itemData.c._mdf || this._isFirstFrame){
styleElem.co = 'rgb('+bm_floor(itemData.c.v[0])+','+bm_floor(itemData.c.v[1])+','+bm_floor(itemData.c.v[2])+')';
}
if(itemData.o._mdf || groupTransform._opMdf || this._isFirstFrame){
styleElem.coOp = itemData.o.v*groupTransform.opacity;
}
};
CVShapeElement.prototype.renderStroke = function(styleData,itemData, groupTransform){
var styleElem = itemData.style;
var d = itemData.d;
if(d && (d._mdf || this._isFirstFrame)){
styleElem.da = d.dashArray;
styleElem.do = d.dashoffset[0];
}
if(itemData.c._mdf || this._isFirstFrame){
styleElem.co = 'rgb('+bm_floor(itemData.c.v[0])+','+bm_floor(itemData.c.v[1])+','+bm_floor(itemData.c.v[2])+')';
}
if(itemData.o._mdf || groupTransform._opMdf || this._isFirstFrame){
styleElem.coOp = itemData.o.v*groupTransform.opacity;
}
if(itemData.w._mdf || this._isFirstFrame){
styleElem.wi = itemData.w.v;
}
};
CVShapeElement.prototype.destroy = function(){
this.shapesData = null;
this.globalData = null;
this.canvasContext = null;
this.stylesList.length = 0;
this.itemsData.length = 0;
};
function CVSolidElement(data, globalData, comp) {
this.initElement(data,globalData,comp);
}
extendPrototype([BaseElement, TransformElement, CVBaseElement, HierarchyElement, FrameElement, RenderableElement], CVSolidElement);
CVSolidElement.prototype.initElement = SVGShapeElement.prototype.initElement;
CVSolidElement.prototype.prepareFrame = IImageElement.prototype.prepareFrame;
CVSolidElement.prototype.renderInnerContent = function() {
var ctx = this.canvasContext;
ctx.fillStyle = this.data.sc;
ctx.fillRect(0, 0, this.data.sw, this.data.sh);
//
};
function CVTextElement(data, globalData, comp){
this.textSpans = [];
this.yOffset = 0;
this.fillColorAnim = false;
this.strokeColorAnim = false;
this.strokeWidthAnim = false;
this.stroke = false;
this.fill = false;
this.justifyOffset = 0;
this.currentRender = null;
this.renderType = 'canvas';
this.values = {
fill: 'rgba(0,0,0,0)',
stroke: 'rgba(0,0,0,0)',
sWidth: 0,
fValue: ''
};
this.initElement(data,globalData,comp);
}
extendPrototype([BaseElement,TransformElement,CVBaseElement,HierarchyElement,FrameElement,RenderableElement,ITextElement], CVTextElement);
CVTextElement.prototype.tHelper = createTag('canvas').getContext('2d');
CVTextElement.prototype.buildNewText = function(){
var documentData = this.textProperty.currentData;
this.renderedLetters = createSizedArray(documentData.l ? documentData.l.length : 0);
var hasFill = false;
if(documentData.fc) {
hasFill = true;
this.values.fill = this.buildColor(documentData.fc);
}else{
this.values.fill = 'rgba(0,0,0,0)';
}
this.fill = hasFill;
var hasStroke = false;
if(documentData.sc){
hasStroke = true;
this.values.stroke = this.buildColor(documentData.sc);
this.values.sWidth = documentData.sw;
}
var fontData = this.globalData.fontManager.getFontByName(documentData.f);
var i, len;
var letters = documentData.l;
var matrixHelper = this.mHelper;
this.stroke = hasStroke;
this.values.fValue = documentData.finalSize + 'px '+ this.globalData.fontManager.getFontByName(documentData.f).fFamily;
len = documentData.finalText.length;
//this.tHelper.font = this.values.fValue;
var charData, shapeData, k, kLen, shapes, j, jLen, pathNodes, commands, pathArr, singleShape = this.data.singleShape;
var trackingOffset = documentData.tr/1000*documentData.finalSize;
var xPos = 0, yPos = 0, firstLine = true;
var cnt = 0;
for (i = 0; i < len; i += 1) {
charData = this.globalData.fontManager.getCharData(documentData.finalText[i], fontData.fStyle, this.globalData.fontManager.getFontByName(documentData.f).fFamily);
shapeData = charData && charData.data || {};
matrixHelper.reset();
if(singleShape && letters[i].n) {
xPos = -trackingOffset;
yPos += documentData.yOffset;
yPos += firstLine ? 1 : 0;
firstLine = false;
}
shapes = shapeData.shapes ? shapeData.shapes[0].it : [];
jLen = shapes.length;
matrixHelper.scale(documentData.finalSize/100,documentData.finalSize/100);
if(singleShape){
this.applyTextPropertiesToMatrix(documentData, matrixHelper, letters[i].line, xPos, yPos);
}
commands = createSizedArray(jLen);
for(j=0;j<jLen;j+=1){
kLen = shapes[j].ks.k.i.length;
pathNodes = shapes[j].ks.k;
pathArr = [];
for(k=1;k<kLen;k+=1){
if(k==1){
pathArr.push(matrixHelper.applyToX(pathNodes.v[0][0],pathNodes.v[0][1],0),matrixHelper.applyToY(pathNodes.v[0][0],pathNodes.v[0][1],0));
}
pathArr.push(matrixHelper.applyToX(pathNodes.o[k-1][0],pathNodes.o[k-1][1],0),matrixHelper.applyToY(pathNodes.o[k-1][0],pathNodes.o[k-1][1],0),matrixHelper.applyToX(pathNodes.i[k][0],pathNodes.i[k][1],0),matrixHelper.applyToY(pathNodes.i[k][0],pathNodes.i[k][1],0),matrixHelper.applyToX(pathNodes.v[k][0],pathNodes.v[k][1],0),matrixHelper.applyToY(pathNodes.v[k][0],pathNodes.v[k][1],0));
}
pathArr.push(matrixHelper.applyToX(pathNodes.o[k-1][0],pathNodes.o[k-1][1],0),matrixHelper.applyToY(pathNodes.o[k-1][0],pathNodes.o[k-1][1],0),matrixHelper.applyToX(pathNodes.i[0][0],pathNodes.i[0][1],0),matrixHelper.applyToY(pathNodes.i[0][0],pathNodes.i[0][1],0),matrixHelper.applyToX(pathNodes.v[0][0],pathNodes.v[0][1],0),matrixHelper.applyToY(pathNodes.v[0][0],pathNodes.v[0][1],0));
commands[j] = pathArr;
}
if(singleShape){
xPos += letters[i].l;
xPos += trackingOffset;
}
if(this.textSpans[cnt]){
this.textSpans[cnt].elem = commands;
} else {
this.textSpans[cnt] = {elem: commands};
}
cnt +=1;
}
};
CVTextElement.prototype.renderInnerContent = function(){
var ctx = this.canvasContext;
var finalMat = this.finalTransform.mat.props;
ctx.font = this.values.fValue;
ctx.lineCap = 'butt';
ctx.lineJoin = 'miter';
ctx.miterLimit = 4;
if(!this.data.singleShape){
this.textAnimator.getMeasures(this.textProperty.currentData, this.lettersChangedFlag);
}
var i,len, j, jLen, k, kLen;
var renderedLetters = this.textAnimator.renderedLetters;
var letters = this.textProperty.currentData.l;
len = letters.length;
var renderedLetter;
var lastFill = null, lastStroke = null, lastStrokeW = null, commands, pathArr;
for(i=0;i<len;i+=1){
if(letters[i].n){
continue;
}
renderedLetter = renderedLetters[i];
if(renderedLetter){
this.globalData.renderer.save();
this.globalData.renderer.ctxTransform(renderedLetter.p);
this.globalData.renderer.ctxOpacity(renderedLetter.o);
}
if(this.fill){
if(renderedLetter && renderedLetter.fc){
if(lastFill !== renderedLetter.fc){
lastFill = renderedLetter.fc;
ctx.fillStyle = renderedLetter.fc;
}
}else if(lastFill !== this.values.fill){
lastFill = this.values.fill;
ctx.fillStyle = this.values.fill;
}
commands = this.textSpans[i].elem;
jLen = commands.length;
this.globalData.canvasContext.beginPath();
for(j=0;j<jLen;j+=1) {
pathArr = commands[j];
kLen = pathArr.length;
this.globalData.canvasContext.moveTo(pathArr[0], pathArr[1]);
for (k = 2; k < kLen; k += 6) {
this.globalData.canvasContext.bezierCurveTo(pathArr[k], pathArr[k + 1], pathArr[k + 2], pathArr[k + 3], pathArr[k + 4], pathArr[k + 5]);
}
}
this.globalData.canvasContext.closePath();
this.globalData.canvasContext.fill();
///ctx.fillText(this.textSpans[i].val,0,0);
}
if(this.stroke){
if(renderedLetter && renderedLetter.sw){
if(lastStrokeW !== renderedLetter.sw){
lastStrokeW = renderedLetter.sw;
ctx.lineWidth = renderedLetter.sw;
}
}else if(lastStrokeW !== this.values.sWidth){
lastStrokeW = this.values.sWidth;
ctx.lineWidth = this.values.sWidth;
}
if(renderedLetter && renderedLetter.sc){
if(lastStroke !== renderedLetter.sc){
lastStroke = renderedLetter.sc;
ctx.strokeStyle = renderedLetter.sc;
}
}else if(lastStroke !== this.values.stroke){
lastStroke = this.values.stroke;
ctx.strokeStyle = this.values.stroke;
}
commands = this.textSpans[i].elem;
jLen = commands.length;
this.globalData.canvasContext.beginPath();
for(j=0;j<jLen;j+=1) {
pathArr = commands[j];
kLen = pathArr.length;
this.globalData.canvasContext.moveTo(pathArr[0], pathArr[1]);
for (k = 2; k < kLen; k += 6) {
this.globalData.canvasContext.bezierCurveTo(pathArr[k], pathArr[k + 1], pathArr[k + 2], pathArr[k + 3], pathArr[k + 4], pathArr[k + 5]);
}
}
this.globalData.canvasContext.closePath();
this.globalData.canvasContext.stroke();
///ctx.strokeText(letters[i].val,0,0);
}
if(renderedLetter) {
this.globalData.renderer.restore();
}
}
/*if(this.data.hasMask){
this.globalData.renderer.restore(true);
}*/
};
function CVEffects() {
}
CVEffects.prototype.renderFrame = function(){};
function HBaseElement(data,globalData,comp){}
HBaseElement.prototype = {
checkBlendMode: function(){},
initRendererElement: function(){
this.baseElement = createTag(this.data.tg || 'div');
if(this.data.hasMask) {
this.svgElement = createNS('svg');
this.layerElement = createNS('g');
this.maskedElement = this.layerElement;
this.svgElement.appendChild(this.layerElement);
this.baseElement.appendChild(this.svgElement);
} else {
this.layerElement = this.baseElement;
}
styleDiv(this.baseElement);
},
createContainerElements: function(){
this.renderableEffectsManager = new CVEffects(this);
this.transformedElement = this.baseElement;
this.maskedElement = this.layerElement;
if (this.data.ln) {
this.layerElement.setAttribute('id',this.data.ln);
}
if (this.data.cl) {
this.layerElement.setAttribute('class', this.data.cl);
}
if (this.data.bm !== 0) {
this.setBlendMode();
}
},
renderElement: function() {
if(this.finalTransform._matMdf){
this.transformedElement.style.transform = this.transformedElement.style.webkitTransform = this.finalTransform.mat.toCSS();
}
if(this.finalTransform._opMdf){
this.transformedElement.style.opacity = this.finalTransform.mProp.o.v;
}
},
renderFrame: function() {
//If it is exported as hidden (data.hd === true) no need to render
//If it is not visible no need to render
if (this.data.hd || this.hidden) {
return;
}
this.renderTransform();
this.renderRenderable();
this.renderElement();
this.renderInnerContent();
if (this._isFirstFrame) {
this._isFirstFrame = false;
}
},
destroy: function(){
this.layerElement = null;
this.transformedElement = null;
if(this.matteElement) {
this.matteElement = null;
}
if(this.maskManager) {
this.maskManager.destroy();
this.maskManager = null;
}
},
addMasks: function(){
this.maskManager = new MaskElement(this.data, this, this.globalData);
},
setMatte: function(){}
};
HBaseElement.prototype.getBaseElement = SVGBaseElement.prototype.getBaseElement;
HBaseElement.prototype.destroyBaseElement = HBaseElement.prototype.destroy;
HBaseElement.prototype.buildElementParenting = HybridRenderer.prototype.buildElementParenting;
function HSolidElement(data,globalData,comp){
this.initElement(data,globalData,comp);
}
extendPrototype([BaseElement,TransformElement,HBaseElement,HierarchyElement,FrameElement,RenderableDOMElement], HSolidElement);
HSolidElement.prototype.createContent = function(){
var rect;
if(this.data.hasMask){
rect = createNS('rect');
rect.setAttribute('width',this.data.sw);
rect.setAttribute('height',this.data.sh);
rect.setAttribute('fill',this.data.sc);
this.svgElement.setAttribute('width',this.data.sw);
this.svgElement.setAttribute('height',this.data.sh);
} else {
rect = createTag('div');
rect.style.width = this.data.sw + 'px';
rect.style.height = this.data.sh + 'px';
rect.style.backgroundColor = this.data.sc;
}
this.layerElement.appendChild(rect);
};
function HCompElement(data,globalData,comp){
this.layers = data.layers;
this.supports3d = !data.hasMask;
this.completeLayers = false;
this.pendingElements = [];
this.elements = this.layers ? createSizedArray(this.layers.length) : [];
this.initElement(data,globalData,comp);
this.tm = data.tm ? PropertyFactory.getProp(this,data.tm,0,globalData.frameRate,this) : {_placeholder:true};
}
extendPrototype([HybridRenderer, ICompElement, HBaseElement], HCompElement);
HCompElement.prototype._createBaseContainerElements = HCompElement.prototype.createContainerElements;
HCompElement.prototype.createContainerElements = function(){
this._createBaseContainerElements();
//divElement.style.clip = 'rect(0px, '+this.data.w+'px, '+this.data.h+'px, 0px)';
if(this.data.hasMask){
this.svgElement.setAttribute('width',this.data.w);
this.svgElement.setAttribute('height',this.data.h);
this.transformedElement = this.baseElement;
} else {
this.transformedElement = this.layerElement;
}
};
HCompElement.prototype.addTo3dContainer = function(elem,pos) {
var j = 0;
var nextElement;
while(j<pos){
if(this.elements[j] && this.elements[j].getBaseElement){
nextElement = this.elements[j].getBaseElement();
}
j += 1;
}
if(nextElement){
this.layerElement.insertBefore(elem, nextElement);
} else {
this.layerElement.appendChild(elem);
}
}
function HShapeElement(data,globalData,comp){
//List of drawable elements
this.shapes = [];
// Full shape data
this.shapesData = data.shapes;
//List of styles that will be applied to shapes
this.stylesList = [];
//List of modifiers that will be applied to shapes
this.shapeModifiers = [];
//List of items in shape tree
this.itemsData = [];
//List of items in previous shape tree
this.processedElements = [];
// List of animated components
this.animatedContents = [];
this.shapesContainer = createNS('g');
this.initElement(data,globalData,comp);
//Moving any property that doesn't get too much access after initialization because of v8 way of handling more than 10 properties.
// List of elements that have been created
this.prevViewData = [];
this.currentBBox = {
x:999999,
y: -999999,
h: 0,
w: 0
};
}
extendPrototype([BaseElement,TransformElement,HSolidElement,SVGShapeElement,HBaseElement,HierarchyElement,FrameElement,RenderableElement], HShapeElement);
HShapeElement.prototype._renderShapeFrame = HShapeElement.prototype.renderInnerContent;
HShapeElement.prototype.createContent = function(){
var cont;
this.baseElement.style.fontSize = 0;
if (this.data.hasMask) {
this.layerElement.appendChild(this.shapesContainer);
cont = this.svgElement;
} else {
cont = createNS('svg');
var size = this.comp.data ? this.comp.data : this.globalData.compSize;
cont.setAttribute('width',size.w);
cont.setAttribute('height',size.h);
cont.appendChild(this.shapesContainer);
this.layerElement.appendChild(cont);
}
this.searchShapes(this.shapesData,this.itemsData,this.prevViewData,this.shapesContainer,0, [], true);
this.filterUniqueShapes();
this.shapeCont = cont;
};
HShapeElement.prototype.getTransformedPoint = function(transformers, point) {
var i, len = transformers.length;
for(i = 0; i < len; i += 1) {
point = transformers[i].mProps.v.applyToPointArray(point[0], point[1], 0);
}
return point;
}
HShapeElement.prototype.calculateShapeBoundingBox = function(item, boundingBox) {
var shape = item.sh.v;
var transformers = item.transformers;
var i, len = shape._length, vPoint, oPoint, nextIPoint, nextVPoint, bounds;
if (len <= 1) {
return;
}
for (i = 0; i < len - 1; i += 1) {
vPoint = this.getTransformedPoint(transformers, shape.v[i]);
oPoint = this.getTransformedPoint(transformers, shape.o[i]);
nextIPoint = this.getTransformedPoint(transformers, shape.i[i + 1]);
nextVPoint = this.getTransformedPoint(transformers, shape.v[i + 1]);
this.checkBounds(vPoint, oPoint, nextIPoint, nextVPoint, boundingBox);
}
if(shape.c) {
vPoint = this.getTransformedPoint(transformers, shape.v[i]);
oPoint = this.getTransformedPoint(transformers, shape.o[i]);
nextIPoint = this.getTransformedPoint(transformers, shape.i[0]);
nextVPoint = this.getTransformedPoint(transformers, shape.v[0]);
this.checkBounds(vPoint, oPoint, nextIPoint, nextVPoint, boundingBox);
}
}
HShapeElement.prototype.checkBounds = function(vPoint, oPoint, nextIPoint, nextVPoint, boundingBox) {
this.getBoundsOfCurve(vPoint, oPoint, nextIPoint, nextVPoint);
var bounds = this.shapeBoundingBox;
boundingBox.x = bm_min(bounds.left, boundingBox.x);
boundingBox.xMax = bm_max(bounds.right, boundingBox.xMax);
boundingBox.y = bm_min(bounds.top, boundingBox.y);
boundingBox.yMax = bm_max(bounds.bottom, boundingBox.yMax);
}
HShapeElement.prototype.shapeBoundingBox = {
left:0,
right:0,
top:0,
bottom:0,
}
HShapeElement.prototype.tempBoundingBox = {
x:0,
xMax:0,
y:0,
yMax:0,
width:0,
height:0
}
HShapeElement.prototype.getBoundsOfCurve = function(p0, p1, p2, p3) {
var bounds = [[p0[0],p3[0]], [p0[1],p3[1]]];
for (var a, b, c, t, b2ac, t1, t2, i = 0; i < 2; ++i) {
b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i];
a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i];
c = 3 * p1[i] - 3 * p0[i];
b = b | 0;
a = a | 0;
c = c | 0;
if (a === 0) {
if (b === 0) {
continue;
}
t = -c / b;
if (0 < t && t < 1) {
bounds[i].push(this.calculateF(t,p0,p1,p2,p3,i));
}
continue;
}
b2ac = b * b - 4 * c * a;
if (b2ac < 0) {
continue;
}
t1 = (-b + bm_sqrt(b2ac))/(2 * a);
if (0 < t1 && t1 < 1) bounds[i].push(this.calculateF(t1,p0,p1,p2,p3,i));
t2 = (-b - bm_sqrt(b2ac))/(2 * a);
if (0 < t2 && t2 < 1) bounds[i].push(this.calculateF(t2,p0,p1,p2,p3,i));
}
this.shapeBoundingBox.left = bm_min.apply(null, bounds[0]);
this.shapeBoundingBox.top = bm_min.apply(null, bounds[1]);
this.shapeBoundingBox.right = bm_max.apply(null, bounds[0]);
this.shapeBoundingBox.bottom = bm_max.apply(null, bounds[1]);
};
HShapeElement.prototype.calculateF = function(t, p0, p1, p2, p3, i) {
return bm_pow(1-t, 3) * p0[i]
+ 3 * bm_pow(1-t, 2) * t * p1[i]
+ 3 * (1-t) * bm_pow(t, 2) * p2[i]
+ bm_pow(t, 3) * p3[i];
}
HShapeElement.prototype.calculateBoundingBox = function(itemsData, boundingBox) {
var i, len = itemsData.length, path;
for(i = 0; i < len; i += 1) {
if(itemsData[i] && itemsData[i].sh) {
this.calculateShapeBoundingBox(itemsData[i], boundingBox)
} else if(itemsData[i] && itemsData[i].it) {
this.calculateBoundingBox(itemsData[i].it, boundingBox)
}
}
}
HShapeElement.prototype.currentBoxContains = function(box) {
return this.currentBBox.x <= box.x
&& this.currentBBox.y <= box.y
&& this.currentBBox.width + this.currentBBox.x >= box.x + box.width
&& this.currentBBox.height + this.currentBBox.y >= box.y + box.height
}
HShapeElement.prototype.renderInnerContent = function() {
this._renderShapeFrame();
if(!this.hidden && (this._isFirstFrame || this._mdf)) {
var tempBoundingBox = this.tempBoundingBox;
var max = 999999;
tempBoundingBox.x = max;
tempBoundingBox.xMax = -max;
tempBoundingBox.y = max;
tempBoundingBox.yMax = -max;
this.calculateBoundingBox(this.itemsData, tempBoundingBox);
tempBoundingBox.width = tempBoundingBox.xMax < tempBoundingBox.x ? 0 : tempBoundingBox.xMax - tempBoundingBox.x;
tempBoundingBox.height = tempBoundingBox.yMax < tempBoundingBox.y ? 0 : tempBoundingBox.yMax - tempBoundingBox.y;
//var tempBoundingBox = this.shapeCont.getBBox();
if(this.currentBoxContains(tempBoundingBox)) {
return;
}
var changed = false;
if(this.currentBBox.w !== tempBoundingBox.width){
this.currentBBox.w = tempBoundingBox.width;
this.shapeCont.setAttribute('width',tempBoundingBox.width);
changed = true;
}
if(this.currentBBox.h !== tempBoundingBox.height){
this.currentBBox.h = tempBoundingBox.height;
this.shapeCont.setAttribute('height',tempBoundingBox.height);
changed = true;
}
if(changed || this.currentBBox.x !== tempBoundingBox.x || this.currentBBox.y !== tempBoundingBox.y){
this.currentBBox.w = tempBoundingBox.width;
this.currentBBox.h = tempBoundingBox.height;
this.currentBBox.x = tempBoundingBox.x;
this.currentBBox.y = tempBoundingBox.y;
this.shapeCont.setAttribute('viewBox',this.currentBBox.x+' '+this.currentBBox.y+' '+this.currentBBox.w+' '+this.currentBBox.h);
this.shapeCont.style.transform = this.shapeCont.style.webkitTransform = 'translate(' + this.currentBBox.x + 'px,' + this.currentBBox.y + 'px)';
}
}
};
function HTextElement(data,globalData,comp){
this.textSpans = [];
this.textPaths = [];
this.currentBBox = {
x:999999,
y: -999999,
h: 0,
w: 0
};
this.renderType = 'svg';
this.isMasked = false;
this.initElement(data,globalData,comp);
}
extendPrototype([BaseElement,TransformElement,HBaseElement,HierarchyElement,FrameElement,RenderableDOMElement,ITextElement], HTextElement);
HTextElement.prototype.createContent = function(){
this.isMasked = this.checkMasks();
if(this.isMasked){
this.renderType = 'svg';
this.compW = this.comp.data.w;
this.compH = this.comp.data.h;
this.svgElement.setAttribute('width',this.compW);
this.svgElement.setAttribute('height',this.compH);
var g = createNS('g');
this.maskedElement.appendChild(g);
this.innerElem = g;
} else {
this.renderType = 'html';
this.innerElem = this.layerElement;
}
this.checkParenting();
};
HTextElement.prototype.buildNewText = function(){
var documentData = this.textProperty.currentData;
this.renderedLetters = createSizedArray(documentData.l ? documentData.l.length : 0);
var innerElemStyle = this.innerElem.style;
innerElemStyle.color = innerElemStyle.fill = documentData.fc ? this.buildColor(documentData.fc) : 'rgba(0,0,0,0)';
if(documentData.sc){
innerElemStyle.stroke = this.buildColor(documentData.sc);
innerElemStyle.strokeWidth = documentData.sw+'px';
}
var fontData = this.globalData.fontManager.getFontByName(documentData.f);
if(!this.globalData.fontManager.chars){
innerElemStyle.fontSize = documentData.finalSize+'px';
innerElemStyle.lineHeight = documentData.finalSize+'px';
if(fontData.fClass){
this.innerElem.className = fontData.fClass;
} else {
innerElemStyle.fontFamily = fontData.fFamily;
var fWeight = documentData.fWeight, fStyle = documentData.fStyle;
innerElemStyle.fontStyle = fStyle;
innerElemStyle.fontWeight = fWeight;
}
}
var i, len;
var letters = documentData.l;
len = letters.length;
var tSpan,tParent,tCont;
var matrixHelper = this.mHelper;
var shapes, shapeStr = '';
var cnt = 0;
for (i = 0;i < len ;i += 1) {
if(this.globalData.fontManager.chars){
if(!this.textPaths[cnt]){
tSpan = createNS('path');
tSpan.setAttribute('stroke-linecap', 'butt');
tSpan.setAttribute('stroke-linejoin','round');
tSpan.setAttribute('stroke-miterlimit','4');
} else {
tSpan = this.textPaths[cnt];
}
if(!this.isMasked){
if(this.textSpans[cnt]){
tParent = this.textSpans[cnt];
tCont = tParent.children[0];
} else {
tParent = createTag('div');
tCont = createNS('svg');
tCont.appendChild(tSpan);
styleDiv(tParent);
}
}
}else{
if(!this.isMasked){
if(this.textSpans[cnt]){
tParent = this.textSpans[cnt];
tSpan = this.textPaths[cnt];
} else {
tParent = createTag('span');
styleDiv(tParent);
tSpan = createTag('span');
styleDiv(tSpan);
tParent.appendChild(tSpan);
}
} else {
tSpan = this.textPaths[cnt] ? this.textPaths[cnt] : createNS('text');
}
}
//tSpan.setAttribute('visibility', 'hidden');
if(this.globalData.fontManager.chars){
var charData = this.globalData.fontManager.getCharData(documentData.finalText[i], fontData.fStyle, this.globalData.fontManager.getFontByName(documentData.f).fFamily);
var shapeData;
if(charData){
shapeData = charData.data;
} else {
shapeData = null;
}
matrixHelper.reset();
if(shapeData && shapeData.shapes){
shapes = shapeData.shapes[0].it;
matrixHelper.scale(documentData.finalSize/100,documentData.finalSize/100);
shapeStr = this.createPathShape(matrixHelper,shapes);
tSpan.setAttribute('d',shapeStr);
}
if(!this.isMasked){
this.innerElem.appendChild(tParent);
if(shapeData && shapeData.shapes){
//document.body.appendChild is needed to get exact measure of shape
document.body.appendChild(tCont);
var boundingBox = tCont.getBBox();
tCont.setAttribute('width',boundingBox.width + 2);
tCont.setAttribute('height',boundingBox.height + 2);
tCont.setAttribute('viewBox',(boundingBox.x-1)+' '+ (boundingBox.y-1)+' '+ (boundingBox.width+2)+' '+ (boundingBox.height+2));
tCont.style.transform = tCont.style.webkitTransform = 'translate(' + (boundingBox.x-1) + 'px,' + (boundingBox.y-1) + 'px)';
letters[i].yOffset = boundingBox.y-1;
} else{
tCont.setAttribute('width',1);
tCont.setAttribute('height',1);
}
tParent.appendChild(tCont);
}else{
this.innerElem.appendChild(tSpan);
}
}else{
tSpan.textContent = letters[i].val;
tSpan.setAttributeNS("http://www.w3.org/XML/1998/namespace", "xml:space","preserve");
if(!this.isMasked){
this.innerElem.appendChild(tParent);
//
tSpan.style.transform = tSpan.style.webkitTransform = 'translate3d(0,'+ -documentData.finalSize/1.2+'px,0)';
} else {
this.innerElem.appendChild(tSpan);
}
}
//
if(!this.isMasked){
this.textSpans[cnt] = tParent;
}else{
this.textSpans[cnt] = tSpan;
}
this.textSpans[cnt].style.display = 'block';
this.textPaths[cnt] = tSpan;
cnt += 1;
}
while(cnt < this.textSpans.length){
this.textSpans[cnt].style.display = 'none';
cnt += 1;
}
};
HTextElement.prototype.renderInnerContent = function() {
if(this.data.singleShape){
if(!this._isFirstFrame && !this.lettersChangedFlag){
return;
} else {
// Todo Benchmark if using this is better than getBBox
if(this.isMasked && this.finalTransform._matMdf){
this.svgElement.setAttribute('viewBox',-this.finalTransform.mProp.p.v[0]+' '+ -this.finalTransform.mProp.p.v[1]+' '+this.compW+' '+this.compH);
this.svgElement.style.transform = this.svgElement.style.webkitTransform = 'translate(' + -this.finalTransform.mProp.p.v[0] + 'px,' + -this.finalTransform.mProp.p.v[1] + 'px)';
}
}
}
this.textAnimator.getMeasures(this.textProperty.currentData, this.lettersChangedFlag);
if(!this.lettersChangedFlag && !this.textAnimator.lettersChangedFlag){
return;
}
var i,len, count = 0;
var renderedLetters = this.textAnimator.renderedLetters;
var letters = this.textProperty.currentData.l;
len = letters.length;
var renderedLetter, textSpan, textPath;
for(i=0;i<len;i+=1){
if(letters[i].n){
count += 1;
continue;
}
textSpan = this.textSpans[i];
textPath = this.textPaths[i];
renderedLetter = renderedLetters[count];
count += 1;
if(renderedLetter._mdf.m) {
if(!this.isMasked){
textSpan.style.transform = textSpan.style.webkitTransform = renderedLetter.m;
}else{
textSpan.setAttribute('transform',renderedLetter.m);
}
}
////textSpan.setAttribute('opacity',renderedLetter.o);
textSpan.style.opacity = renderedLetter.o;
if(renderedLetter.sw && renderedLetter._mdf.sw){
textPath.setAttribute('stroke-width',renderedLetter.sw);
}
if(renderedLetter.sc && renderedLetter._mdf.sc){
textPath.setAttribute('stroke',renderedLetter.sc);
}
if(renderedLetter.fc && renderedLetter._mdf.fc){
textPath.setAttribute('fill',renderedLetter.fc);
textPath.style.color = renderedLetter.fc;
}
}
if(this.innerElem.getBBox && !this.hidden && (this._isFirstFrame || this._mdf)){
var boundingBox = this.innerElem.getBBox();
if(this.currentBBox.w !== boundingBox.width){
this.currentBBox.w = boundingBox.width;
this.svgElement.setAttribute('width',boundingBox.width);
}
if(this.currentBBox.h !== boundingBox.height){
this.currentBBox.h = boundingBox.height;
this.svgElement.setAttribute('height',boundingBox.height);
}
var margin = 1;
if(this.currentBBox.w !== (boundingBox.width + margin*2) || this.currentBBox.h !== (boundingBox.height + margin*2) || this.currentBBox.x !== (boundingBox.x - margin) || this.currentBBox.y !== (boundingBox.y - margin)){
this.currentBBox.w = boundingBox.width + margin*2;
this.currentBBox.h = boundingBox.height + margin*2;
this.currentBBox.x = boundingBox.x - margin;
this.currentBBox.y = boundingBox.y - margin;
this.svgElement.setAttribute('viewBox',this.currentBBox.x+' '+this.currentBBox.y+' '+this.currentBBox.w+' '+this.currentBBox.h);
this.svgElement.style.transform = this.svgElement.style.webkitTransform = 'translate(' + this.currentBBox.x + 'px,' + this.currentBBox.y + 'px)';
}
}
};
function HImageElement(data,globalData,comp){
this.assetData = globalData.getAssetData(data.refId);
this.initElement(data,globalData,comp);
}
extendPrototype([BaseElement,TransformElement,HBaseElement,HSolidElement,HierarchyElement,FrameElement,RenderableElement], HImageElement);
HImageElement.prototype.createContent = function(){
var assetPath = this.globalData.getAssetsPath(this.assetData);
var img = new Image();
if(this.data.hasMask){
this.imageElem = createNS('image');
this.imageElem.setAttribute('width',this.assetData.w+"px");
this.imageElem.setAttribute('height',this.assetData.h+"px");
this.imageElem.setAttributeNS('http://www.w3.org/1999/xlink','href',assetPath);
this.layerElement.appendChild(this.imageElem);
this.baseElement.setAttribute('width',this.assetData.w);
this.baseElement.setAttribute('height',this.assetData.h);
} else {
this.layerElement.appendChild(img);
}
img.src = assetPath;
if(this.data.ln){
this.baseElement.setAttribute('id',this.data.ln);
}
};
function HCameraElement(data,globalData,comp){
this.initFrame();
this.initBaseData(data,globalData,comp);
this.initHierarchy();
var getProp = PropertyFactory.getProp;
this.pe = getProp(this,data.pe,0,0,this);
if(data.ks.p.s){
this.px = getProp(this,data.ks.p.x,1,0,this);
this.py = getProp(this,data.ks.p.y,1,0,this);
this.pz = getProp(this,data.ks.p.z,1,0,this);
}else{
this.p = getProp(this,data.ks.p,1,0,this);
}
if(data.ks.a){
this.a = getProp(this,data.ks.a,1,0,this);
}
if(data.ks.or.k.length && data.ks.or.k[0].to){
var i,len = data.ks.or.k.length;
for(i=0;i<len;i+=1){
data.ks.or.k[i].to = null;
data.ks.or.k[i].ti = null;
}
}
this.or = getProp(this,data.ks.or,1,degToRads,this);
this.or.sh = true;
this.rx = getProp(this,data.ks.rx,0,degToRads,this);
this.ry = getProp(this,data.ks.ry,0,degToRads,this);
this.rz = getProp(this,data.ks.rz,0,degToRads,this);
this.mat = new Matrix();
this._prevMat = new Matrix();
this._isFirstFrame = true;
}
extendPrototype([BaseElement, FrameElement, HierarchyElement], HCameraElement);
HCameraElement.prototype.setup = function() {
var i, len = this.comp.threeDElements.length, comp;
for(i=0;i<len;i+=1){
//[perspectiveElem,container]
comp = this.comp.threeDElements[i];
if(comp.type === '3d') {
comp.perspectiveElem.style.perspective = comp.perspectiveElem.style.webkitPerspective = this.pe.v+'px';
comp.container.style.transformOrigin = comp.container.style.mozTransformOrigin = comp.container.style.webkitTransformOrigin = "0px 0px 0px";
comp.perspectiveElem.style.transform = comp.perspectiveElem.style.webkitTransform = 'matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)';
}
}
};
HCameraElement.prototype.createElements = function(){
};
HCameraElement.prototype.hide = function(){
};
HCameraElement.prototype.renderFrame = function(){
var _mdf = this._isFirstFrame;
var i, len;
if(this.hierarchy){
len = this.hierarchy.length;
for(i=0;i<len;i+=1){
_mdf = this.hierarchy[i].finalTransform.mProp._mdf || _mdf;
}
}
if(_mdf || (this.p && this.p._mdf) || (this.px && (this.px._mdf || this.py._mdf || this.pz._mdf)) || this.rx._mdf || this.ry._mdf || this.rz._mdf || this.or._mdf || (this.a && this.a._mdf)) {
this.mat.reset();
if(this.hierarchy){
var mat;
len = this.hierarchy.length - 1;
for (i = len; i >= 0; i -= 1) {
/*mat = this.hierarchy[i].finalTransform.mProp.v.props;
console.log(mat)
this.mat.transform(-mat[0],-mat[1],-mat[2],-mat[3],-mat[4],-mat[5],-mat[6],-mat[7],-mat[8],-mat[9],-mat[10],-mat[11],-mat[12],-mat[13],-mat[14],mat[15]);
console.log(this.mat.props)*/
var mTransf = this.hierarchy[i].finalTransform.mProp;
this.mat.translate(-mTransf.p.v[0],-mTransf.p.v[1],mTransf.p.v[2]);
this.mat.rotateX(-mTransf.rx.v).rotateY(-mTransf.ry.v).rotateZ(mTransf.rz.v);
this.mat.scale(1/mTransf.s.v[0],1/mTransf.s.v[1],1/mTransf.s.v[2]);
this.mat.translate(mTransf.a.v[0],mTransf.a.v[1],mTransf.a.v[2]);
}
}
if(this.p){
this.mat.translate(-this.p.v[0],-this.p.v[1],this.p.v[2]);
}else{
this.mat.translate(-this.px.v,-this.py.v,this.pz.v);
}
if(this.a){
var diffVector = [this.p.v[0]-this.a.v[0],this.p.v[1]-this.a.v[1],this.p.v[2]-this.a.v[2]];
var mag = Math.sqrt(Math.pow(diffVector[0],2)+Math.pow(diffVector[1],2)+Math.pow(diffVector[2],2));
//var lookDir = getNormalizedPoint(getDiffVector(this.a.v,this.p.v));
var lookDir = [diffVector[0]/mag,diffVector[1]/mag,diffVector[2]/mag];
var lookLengthOnXZ = Math.sqrt( lookDir[2]*lookDir[2] + lookDir[0]*lookDir[0] );
var m_rotationX = (Math.atan2( lookDir[1], lookLengthOnXZ ));
var m_rotationY = (Math.atan2( lookDir[0], -lookDir[2]));
this.mat.rotateY(m_rotationY).rotateX(-m_rotationX);
}
this.mat.rotateX(-this.rx.v).rotateY(-this.ry.v).rotateZ(this.rz.v);
this.mat.rotateX(-this.or.v[0]).rotateY(-this.or.v[1]).rotateZ(this.or.v[2]);
this.mat.translate(this.globalData.compSize.w/2,this.globalData.compSize.h/2,0);
this.mat.translate(0,0,this.pe.v);
if(!this._prevMat.equals(this.mat) && this.comp.threeDElements) {
len = this.comp.threeDElements.length;
var comp;
for(i=0;i<len;i+=1){
comp = this.comp.threeDElements[i];
if(comp.type === '3d') {
comp.container.style.transform = comp.container.style.webkitTransform = this.mat.toCSS();
}
}
this.mat.clone(this._prevMat);
}
}
this._isFirstFrame = false;
};
HCameraElement.prototype.prepareFrame = function(num) {
this.prepareProperties(num, true);
};
HCameraElement.prototype.destroy = function(){
};
HCameraElement.prototype.initExpressions = function(){};
HCameraElement.prototype.getBaseElement = function(){return null;};
function HEffects() {
}
HEffects.prototype.renderFrame = function(){};
var Expressions = (function(){
var ob = {};
ob.initExpressions = initExpressions;
function initExpressions(animation){
animation.renderer.compInterface = CompExpressionInterface(animation.renderer);
animation.renderer.globalData.projectInterface.registerComposition(animation.renderer);
}
return ob;
}());
expressionsPlugin = Expressions;
var ExpressionManager = (function(){
'use strict';
var ob = {};
var Math = BMMath;
var window = null;
var document = null;
function duplicatePropertyValue(value, mult) {
mult = mult || 1;
if (typeof value === 'number' || value instanceof Number) {
return value * mult;
} else if(value.i) {
return shape_pool.clone(value);
} else {
var arr = createTypedArray('float32', value.length);
var i, len = value.length;
for (i = 0; i < len; i += 1) {
arr[i] = value[i] * mult;
}
return arr;
}
}
function isTypeOfArray(arr) {
return arr.constructor === Array || arr.constructor === Float32Array;
}
function isNumerable(tOfV, v) {
return tOfV === 'number' || tOfV === 'boolean' || tOfV === 'string' || v instanceof Number;
}
function $bm_neg(a){
var tOfA = typeof a;
if(tOfA === 'number' || tOfA === 'boolean' || a instanceof Number ){
return -a;
}
if(isTypeOfArray(a)){
var i, lenA = a.length;
var retArr = [];
for(i=0;i<lenA;i+=1){
retArr[i] = -a[i];
}
return retArr;
}
}
function sum(a,b) {
var tOfA = typeof a;
var tOfB = typeof b;
if(tOfA === 'string' || tOfB === 'string'){
return a + b;
}
if(isNumerable(tOfA, a) && isNumerable(tOfB, b)) {
return a + b;
}
if(isTypeOfArray(a) && isNumerable(tOfB, b)){
a = a.slice(0);
a[0] = a[0] + b;
return a;
}
if(isNumerable(tOfA, a) && isTypeOfArray(b)){
b = b.slice(0);
b[0] = a + b[0];
return b;
}
if(isTypeOfArray(a) && isTypeOfArray(b)){
var i = 0, lenA = a.length, lenB = b.length;
var retArr = [];
while(i<lenA || i < lenB){
if((typeof a[i] === 'number' || a[i] instanceof Number) && (typeof b[i] === 'number' || b[i] instanceof Number)){
retArr[i] = a[i] + b[i];
}else{
retArr[i] = b[i] === undefined ? a[i] : a[i] || b[i];
}
i += 1;
}
return retArr;
}
return 0;
}
var add = sum;
function sub(a,b) {
var tOfA = typeof a;
var tOfB = typeof b;
if(isNumerable(tOfA, a) && isNumerable(tOfB, b)) {
if(tOfA === 'string') {
a = parseInt(a);
}
if(tOfB === 'string') {
b = parseInt(b);
}
return a - b;
}
if( isTypeOfArray(a) && isNumerable(tOfB, b)){
a = a.slice(0);
a[0] = a[0] - b;
return a;
}
if(isNumerable(tOfA, a) && isTypeOfArray(b)){
b = b.slice(0);
b[0] = a - b[0];
return b;
}
if(isTypeOfArray(a) && isTypeOfArray(b)){
var i = 0, lenA = a.length, lenB = b.length;
var retArr = [];
while(i<lenA || i < lenB){
if((typeof a[i] === 'number' || a[i] instanceof Number) && (typeof b[i] === 'number' || b[i] instanceof Number)){
retArr[i] = a[i] - b[i];
}else{
retArr[i] = b[i] === undefined ? a[i] : a[i] || b[i];
}
i += 1;
}
return retArr;
}
return 0;
}
function mul(a,b) {
var tOfA = typeof a;
var tOfB = typeof b;
var arr;
if(isNumerable(tOfA, a) && isNumerable(tOfB, b)) {
return a * b;
}
var i, len;
if(isTypeOfArray(a) && isNumerable(tOfB, b)){
len = a.length;
arr = createTypedArray('float32', len);
for(i=0;i<len;i+=1){
arr[i] = a[i] * b;
}
return arr;
}
if(isNumerable(tOfA, a) && isTypeOfArray(b)){
len = b.length;
arr = createTypedArray('float32', len);
for(i=0;i<len;i+=1){
arr[i] = a * b[i];
}
return arr;
}
return 0;
}
function div(a,b) {
var tOfA = typeof a;
var tOfB = typeof b;
var arr;
if(isNumerable(tOfA, a) && isNumerable(tOfB, b)) {
return a / b;
}
var i, len;
if(isTypeOfArray(a) && isNumerable(tOfB, b)){
len = a.length;
arr = createTypedArray('float32', len);
for(i=0;i<len;i+=1){
arr[i] = a[i] / b;
}
return arr;
}
if(isNumerable(tOfA, a) && isTypeOfArray(b)){
len = b.length;
arr = createTypedArray('float32', len);
for(i=0;i<len;i+=1){
arr[i] = a / b[i];
}
return arr;
}
return 0;
}
function mod(a,b) {
if(typeof a === 'string') {
a = parseInt(a);
}
if(typeof b === 'string') {
b = parseInt(b);
}
return a % b;
}
function clamp(num, min, max) {
if(min > max){
var mm = max;
max = min;
min = mm;
}
return Math.min(Math.max(num, min), max);
}
function radiansToDegrees(val) {
return val/degToRads;
}
var radians_to_degrees = radiansToDegrees;
function degreesToRadians(val) {
return val*degToRads;
}
var degrees_to_radians = radiansToDegrees;
var helperLengthArray = [0,0,0,0,0,0];
function length(arr1, arr2) {
if (typeof arr1 === 'number' || arr1 instanceof Number) {
arr2 = arr2 || 0;
return Math.abs(arr1 - arr2);
}
if(!arr2) {
arr2 = helperLengthArray;
}
var i, len = Math.min(arr1.length, arr2.length);
var addedLength = 0;
for (i = 0; i < len; i += 1) {
addedLength += Math.pow(arr2[i] - arr1[i], 2);
}
return Math.sqrt(addedLength);
}
function normalize(vec) {
return div(vec, length(vec));
}
function rgbToHsl(val) {
var r = val[0]; var g = val[1]; var b = val[2];
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, l = (max + min) / 2;
if(max == min){
h = s = 0; // achromatic
}else{
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch(max){
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return [h, s, l,val[3]];
}
function hue2rgb(p, q, t){
if(t < 0) t += 1;
if(t > 1) t -= 1;
if(t < 1/6) return p + (q - p) * 6 * t;
if(t < 1/2) return q;
if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}
function hslToRgb(val){
var h = val[0];
var s = val[1];
var l = val[2];
var r, g, b;
if(s === 0){
r = g = b = l; // achromatic
}else{
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return [r, g , b, val[3]];
}
function linear(t, tMin, tMax, value1, value2){
if(value1 === undefined || value2 === undefined){
return linear(t,0,1,tMin,tMax);
}
if(t <= tMin) {
return value1;
}else if(t >= tMax){
return value2;
}
var perc = tMax === tMin ? 0 : (t-tMin)/(tMax-tMin);
if(!value1.length){
return value1 + (value2-value1)*perc;
}
var i, len = value1.length;
var arr = createTypedArray('float32', len);
for(i=0;i<len;i+=1){
arr[i] = value1[i] + (value2[i]-value1[i])*perc;
}
return arr;
}
function random(min,max){
if(max === undefined){
if(min === undefined){
min = 0;
max = 1;
} else {
max = min;
min = undefined;
}
}
if(max.length){
var i, len = max.length;
if(!min){
min = createTypedArray('float32', len);
}
var arr = createTypedArray('float32', len);
var rnd = BMMath.random();
for(i=0;i<len;i+=1){
arr[i] = min[i] + rnd*(max[i]-min[i]);
}
return arr;
}
if(min === undefined){
min = 0;
}
var rndm = BMMath.random();
return min + rndm*(max-min);
}
function createPath(points, inTangents, outTangents, closed) {
var i, len = points.length;
var path = shape_pool.newElement();
path.setPathData(!!closed, len);
var arrPlaceholder = [0,0], inVertexPoint, outVertexPoint;
for(i = 0; i < len; i += 1) {
inVertexPoint = inTangents ? inTangents[i] : arrPlaceholder;
outVertexPoint = outTangents ? outTangents[i] : arrPlaceholder;
path.setTripleAt(points[i][0],points[i][1],outVertexPoint[0] + points[i][0],outVertexPoint[1] + points[i][1],inVertexPoint[0] + points[i][0],inVertexPoint[1] + points[i][1],i,true);
}
return path;
}
function initiateExpression(elem,data,property){
var val = data.x;
var needsVelocity = /velocity(?![\w\d])/.test(val);
var _needsRandom = val.indexOf('random') !== -1;
var elemType = elem.data.ty;
var transform,content,effect;
var thisProperty = property;
elem.comp.frameDuration = 1/elem.comp.globalData.frameRate;
var inPoint = elem.data.ip/elem.comp.globalData.frameRate;
var outPoint = elem.data.op/elem.comp.globalData.frameRate;
var width = elem.data.sw ? elem.data.sw : 0;
var height = elem.data.sh ? elem.data.sh : 0;
var loopIn, loop_in, loopOut, loop_out;
var toWorld,fromWorld,fromComp,fromCompToSurface,anchorPoint,thisLayer,thisComp,mask,valueAtTime,velocityAtTime;
var scoped_bm_rt;
var expression_function = eval('[function _expression_function(){' + val+';scoped_bm_rt=$bm_rt}' + ']')[0];
var numKeys = property.kf ? data.k.length : 0;
var wiggle = function wiggle(freq,amp){
var i,j, len = this.pv.length ? this.pv.length : 1;
var addedAmps = createTypedArray('float32', len);
freq = 5;
var iterations = Math.floor(time*freq);
i = 0;
j = 0;
while(i<iterations){
//var rnd = BMMath.random();
for(j=0;j<len;j+=1){
addedAmps[j] += -amp + amp*2*BMMath.random();
//addedAmps[j] += -amp + amp*2*rnd;
}
i += 1;
}
//var rnd2 = BMMath.random();
var periods = time*freq;
var perc = periods - Math.floor(periods);
var arr = createTypedArray('float32', len);
if(len>1){
for(j=0;j<len;j+=1){
arr[j] = this.pv[j] + addedAmps[j] + (-amp + amp*2*BMMath.random())*perc;
//arr[j] = this.pv[j] + addedAmps[j] + (-amp + amp*2*rnd)*perc;
//arr[i] = this.pv[i] + addedAmp + amp1*perc + amp2*(1-perc);
}
return arr;
} else {
return this.pv + addedAmps[0] + (-amp + amp*2*BMMath.random())*perc;
}
}.bind(this);
if(thisProperty.loopIn) {
loopIn = thisProperty.loopIn.bind(thisProperty);
loop_in = loopIn;
}
if(thisProperty.loopOut) {
loopOut = thisProperty.loopOut.bind(thisProperty);
loop_out = loopOut;
}
function loopInDuration(type,duration){
return loopIn(type,duration,true);
}
function loopOutDuration(type,duration){
return loopOut(type,duration,true);
}
if(this.getValueAtTime) {
valueAtTime = this.getValueAtTime.bind(this);
}
if(this.getVelocityAtTime) {
velocityAtTime = this.getVelocityAtTime.bind(this);
}
var comp = elem.comp.globalData.projectInterface.bind(elem.comp.globalData.projectInterface);
function lookAt(elem1,elem2){
var fVec = [elem2[0]-elem1[0],elem2[1]-elem1[1],elem2[2]-elem1[2]];
var pitch = Math.atan2(fVec[0],Math.sqrt(fVec[1]*fVec[1]+fVec[2]*fVec[2]))/degToRads;
var yaw = -Math.atan2(fVec[1],fVec[2])/degToRads;
return [yaw,pitch,0];
}
function easeOut(t, tMin, tMax, val1, val2){
if(val1 === undefined){
val1 = tMin;
val2 = tMax;
} else {
t = (t - tMin) / (tMax - tMin);
}
return -(val2-val1) * t*(t-2) + val1;
}
function easeIn(t, tMin, tMax, val1, val2){
if(val1 === undefined){
val1 = tMin;
val2 = tMax;
} else {
t = (t - tMin) / (tMax - tMin);
}
return (val2-val1)*t*t + val1;
}
function nearestKey(time){
var i, len = data.k.length,index,keyTime;
if(!data.k.length || typeof(data.k[0]) === 'number'){
index = 0;
keyTime = 0;
} else {
index = -1;
time *= elem.comp.globalData.frameRate;
if (time < data.k[0].t) {
index = 1;
keyTime = data.k[0].t;
} else {
for(i=0;i<len-1;i+=1){
if(time === data.k[i].t){
index = i + 1;
keyTime = data.k[i].t;
break;
}else if(time>data.k[i].t && time<data.k[i+1].t){
if(time-data.k[i].t > data.k[i+1].t - time){
index = i + 2;
keyTime = data.k[i+1].t;
} else {
index = i + 1;
keyTime = data.k[i].t;
}
break;
}
}
if(index === -1){
index = i + 1;
keyTime = data.k[i].t;
}
}
}
var ob = {};
ob.index = index;
ob.time = keyTime/elem.comp.globalData.frameRate;
return ob;
}
function key(ind){
var ob, i, len;
if(!data.k.length || typeof(data.k[0]) === 'number'){
throw new Error('The property has no keyframe at index ' + ind);
}
ind -= 1;
ob = {
time: data.k[ind].t/elem.comp.globalData.frameRate
};
var arr;
if(ind === data.k.length - 1 && !data.k[ind].h){
arr = data.k[ind-1].e;
}else{
arr = data.k[ind].s;
}
len = arr.length;
for(i=0;i<len;i+=1){
ob[i] = arr[i];
}
return ob;
}
function framesToTime(frames, fps) {
if (!fps) {
fps = elem.comp.globalData.frameRate;
}
return frames / fps;
}
function timeToFrames(t, fps) {
if (!t && t !== 0) {
t = time;
}
if (!fps) {
fps = elem.comp.globalData.frameRate;
}
return t * fps;
}
function seedRandom(seed){
BMMath.seedrandom(randSeed + seed);
}
function sourceRectAtTime() {
return elem.sourceRectAtTime();
}
var time, velocity, value, textIndex, textTotal, selectorValue;
var index = elem.data.ind;
var hasParent = !!(elem.hierarchy && elem.hierarchy.length);
var parent;
var randSeed = Math.floor(Math.random()*1000000);
function executeExpression(_value) {
value = _value;
if (_needsRandom) {
seedRandom(randSeed);
}
if (this.frameExpressionId === elem.globalData.frameId && this.propType !== 'textSelector') {
return value;
}
if(this.propType === 'textSelector'){
textIndex = this.textIndex;
textTotal = this.textTotal;
selectorValue = this.selectorValue;
}
if (!thisLayer) {
thisLayer = elem.layerInterface;
thisComp = elem.comp.compInterface;
toWorld = thisLayer.toWorld.bind(thisLayer);
fromWorld = thisLayer.fromWorld.bind(thisLayer);
fromComp = thisLayer.fromComp.bind(thisLayer);
mask = thisLayer.mask ? thisLayer.mask.bind(thisLayer) : null;
fromCompToSurface = fromComp;
}
if (!transform) {
transform = elem.layerInterface("ADBE Transform Group");
anchorPoint = transform.anchorPoint;
}
if (elemType === 4 && !content) {
content = thisLayer("ADBE Root Vectors Group");
}
if (!effect) {
effect = thisLayer(4);
}
hasParent = !!(elem.hierarchy && elem.hierarchy.length);
if (hasParent && !parent) {
parent = elem.hierarchy[0].layerInterface;
}
time = this.comp.renderedFrame/this.comp.globalData.frameRate;
if (needsVelocity) {
velocity = velocityAtTime(time);
}
expression_function();
this.frameExpressionId = elem.globalData.frameId;
//TODO: Check if it's possible to return on ShapeInterface the .v value
if (scoped_bm_rt.propType === "shape") {
scoped_bm_rt = shape_pool.clone(scoped_bm_rt.v);
}
return scoped_bm_rt;
}
return executeExpression;
}
ob.initiateExpression = initiateExpression;
return ob;
}());
(function addPropertyDecorator() {
function getStaticValueAtTime() {
return this.pv;
}
function loopOut(type,duration,durationFlag){
if(!this.k || !this.keyframes){
return this.pv;
}
type = type ? type.toLowerCase() : '';
var currentFrame = this.comp.renderedFrame;
var keyframes = this.keyframes;
var lastKeyFrame = keyframes[keyframes.length - 1].t;
if(currentFrame<=lastKeyFrame){
return this.pv;
}else{
var cycleDuration, firstKeyFrame;
if(!durationFlag){
if(!duration || duration > keyframes.length - 1){
duration = keyframes.length - 1;
}
firstKeyFrame = keyframes[keyframes.length - 1 - duration].t;
cycleDuration = lastKeyFrame - firstKeyFrame;
} else {
if(!duration){
cycleDuration = Math.max(0,lastKeyFrame - this.elem.data.ip);
} else {
cycleDuration = Math.abs(lastKeyFrame - elem.comp.globalData.frameRate*duration);
}
firstKeyFrame = lastKeyFrame - cycleDuration;
}
var i, len, ret;
if(type === 'pingpong') {
var iterations = Math.floor((currentFrame - firstKeyFrame)/cycleDuration);
if(iterations % 2 !== 0){
return this.getValueAtTime(((cycleDuration - (currentFrame - firstKeyFrame) % cycleDuration + firstKeyFrame)) / this.comp.globalData.frameRate, 0);
}
} else if(type === 'offset'){
var initV = this.getValueAtTime(firstKeyFrame / this.comp.globalData.frameRate, 0);
var endV = this.getValueAtTime(lastKeyFrame / this.comp.globalData.frameRate, 0);
var current = this.getValueAtTime(((currentFrame - firstKeyFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0);
var repeats = Math.floor((currentFrame - firstKeyFrame)/cycleDuration);
if(this.pv.length){
ret = new Array(initV.length);
len = ret.length;
for(i=0;i<len;i+=1){
ret[i] = (endV[i]-initV[i])*repeats + current[i];
}
return ret;
}
return (endV-initV)*repeats + current;
} else if(type === 'continue'){
var lastValue = this.getValueAtTime(lastKeyFrame / this.comp.globalData.frameRate, 0);
var nextLastValue = this.getValueAtTime((lastKeyFrame - 0.001) / this.comp.globalData.frameRate, 0);
if(this.pv.length){
ret = new Array(lastValue.length);
len = ret.length;
for(i=0;i<len;i+=1){
ret[i] = lastValue[i] + (lastValue[i]-nextLastValue[i])*((currentFrame - lastKeyFrame)/ this.comp.globalData.frameRate)/0.0005;
}
return ret;
}
return lastValue + (lastValue-nextLastValue)*(((currentFrame - lastKeyFrame))/0.001);
}
return this.getValueAtTime((((currentFrame - firstKeyFrame) % cycleDuration + firstKeyFrame)) / this.comp.globalData.frameRate, 0);
}
}
function loopIn(type,duration, durationFlag) {
if(!this.k){
return this.pv;
}
type = type ? type.toLowerCase() : '';
var currentFrame = this.comp.renderedFrame;
var keyframes = this.keyframes;
var firstKeyFrame = keyframes[0].t;
if(currentFrame>=firstKeyFrame){
return this.pv;
}else{
var cycleDuration, lastKeyFrame;
if(!durationFlag){
if(!duration || duration > keyframes.length - 1){
duration = keyframes.length - 1;
}
lastKeyFrame = keyframes[duration].t;
cycleDuration = lastKeyFrame - firstKeyFrame;
} else {
if(!duration){
cycleDuration = Math.max(0,this.elem.data.op - firstKeyFrame);
} else {
cycleDuration = Math.abs(elem.comp.globalData.frameRate*duration);
}
lastKeyFrame = firstKeyFrame + cycleDuration;
}
var i, len, ret;
if(type === 'pingpong') {
var iterations = Math.floor((firstKeyFrame - currentFrame)/cycleDuration);
if(iterations % 2 === 0){
return this.getValueAtTime((((firstKeyFrame - currentFrame)%cycleDuration + firstKeyFrame)) / this.comp.globalData.frameRate, 0);
}
} else if(type === 'offset'){
var initV = this.getValueAtTime(firstKeyFrame / this.comp.globalData.frameRate, 0);
var endV = this.getValueAtTime(lastKeyFrame / this.comp.globalData.frameRate, 0);
var current = this.getValueAtTime((cycleDuration - (firstKeyFrame - currentFrame)%cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0);
var repeats = Math.floor((firstKeyFrame - currentFrame)/cycleDuration)+1;
if(this.pv.length){
ret = new Array(initV.length);
len = ret.length;
for(i=0;i<len;i+=1){
ret[i] = current[i]-(endV[i]-initV[i])*repeats;
}
return ret;
}
return current-(endV-initV)*repeats;
} else if(type === 'continue'){
var firstValue = this.getValueAtTime(firstKeyFrame / this.comp.globalData.frameRate, 0);
var nextFirstValue = this.getValueAtTime((firstKeyFrame + 0.001) / this.comp.globalData.frameRate, 0);
if(this.pv.length){
ret = new Array(firstValue.length);
len = ret.length;
for(i=0;i<len;i+=1){
ret[i] = firstValue[i] + (firstValue[i]-nextFirstValue[i])*(firstKeyFrame - currentFrame)/0.001;
}
return ret;
}
return firstValue + (firstValue-nextFirstValue)*(firstKeyFrame - currentFrame)/0.001;
}
return this.getValueAtTime(((cycleDuration - (firstKeyFrame - currentFrame) % cycleDuration + firstKeyFrame)) / this.comp.globalData.frameRate, 0);
}
}
function getValueAtTime(frameNum) {
if(frameNum !== this._cachingAtTime.lastFrame) {
frameNum *= this.elem.globalData.frameRate;
frameNum -= this.offsetTime;
this._cachingAtTime.lastIndex = this._cachingAtTime.lastFrame < frameNum ? this._cachingAtTime.lastIndex : 0;
this._cachingAtTime.value = this.interpolateValue(frameNum, this._cachingAtTime);
this._cachingAtTime.lastFrame = frameNum;
}
return this._cachingAtTime.value;
}
function getVelocityAtTime(frameNum) {
if(this.vel !== undefined){
return this.vel;
}
var delta = -0.01;
//frameNum += this.elem.data.st;
var v1 = this.getValueAtTime(frameNum);
var v2 = this.getValueAtTime(frameNum + delta);
var velocity;
if(v1.length){
velocity = createTypedArray('float32', v1.length);
var i;
for(i=0;i<v1.length;i+=1){
//removing frameRate
//if needed, don't add it here
//velocity[i] = this.elem.globalData.frameRate*((v2[i] - v1[i])/delta);
velocity[i] = (v2[i] - v1[i])/delta;
}
} else {
velocity = (v2 - v1)/delta;
}
return velocity;
}
function setGroupProperty(propertyGroup){
this.propertyGroup = propertyGroup;
}
function searchExpressions(elem,data,prop){
if(data.x){
prop.k = true;
prop.x = true;
prop.initiateExpression = ExpressionManager.initiateExpression;
prop.effectsSequence.push(prop.initiateExpression(elem,data,prop).bind(prop));
}
}
function getTransformValueAtTime(time) {
console.warn('Transform at time not supported');
}
function getTransformStaticValueAtTime(time) {
}
var TextExpressionSelectorProp = (function(){
function getValueProxy(index,total){
this.textIndex = index+1;
this.textTotal = total;
this.getValue();
return this.v;
}
return function TextExpressionSelectorProp(elem,data){
this.pv = 1;
this.comp = elem.comp;
this.elem = elem;
this.mult = 0.01;
this.propType = 'textSelector';
this.textTotal = data.totalChars;
this.selectorValue = 100;
this.lastValue = [1,1,1];
searchExpressions.bind(this)(elem,data,this);
this.getMult = getValueProxy;
this.getVelocityAtTime = getVelocityAtTime;
if(this.kf){
this.getValueAtTime = getValueAtTime.bind(this);
} else {
this.getValueAtTime = getStaticValueAtTime.bind(this);
}
this.setGroupProperty = setGroupProperty;
};
}());
var getTransformProperty = TransformPropertyFactory.getTransformProperty;
TransformPropertyFactory.getTransformProperty = function(elem, data, container) {
var prop = getTransformProperty(elem, data, container);
if(prop.dynamicProperties.length) {
prop.getValueAtTime = getTransformValueAtTime.bind(prop);
} else {
prop.getValueAtTime = getTransformStaticValueAtTime.bind(prop);
}
prop.setGroupProperty = setGroupProperty;
return prop;
};
var propertyGetProp = PropertyFactory.getProp;
PropertyFactory.getProp = function(elem,data,type, mult, container){
var prop = propertyGetProp(elem,data,type, mult, container);
//prop.getVelocityAtTime = getVelocityAtTime;
//prop.loopOut = loopOut;
//prop.loopIn = loopIn;
if(prop.kf){
prop.getValueAtTime = getValueAtTime.bind(prop);
} else {
prop.getValueAtTime = getStaticValueAtTime.bind(prop);
}
prop.setGroupProperty = setGroupProperty;
prop.loopOut = loopOut;
prop.loopIn = loopIn;
prop.getVelocityAtTime = getVelocityAtTime;
prop.numKeys = data.a === 1 ? data.k.length : 0;
prop.propertyIndex = data.ix;
var value = 0;
if(type !== 0) {
value = createTypedArray('float32', data.a === 1 ? data.k[0].s.length : data.k.length);
}
prop._cachingAtTime = {
lastFrame: initialDefaultFrame,
lastIndex: 0,
value: value
};
searchExpressions(elem,data,prop);
if(prop.k){
container.addDynamicProperty(prop);
}
return prop;
};
function getShapeValueAtTime(frameNum) {
//For now this caching object is created only when needed instead of creating it when the shape is initialized.
if (!this._cachingAtTime) {
this._cachingAtTime = {
shapeValue: shape_pool.clone(this.pv),
lastIndex: 0,
lastTime: initialDefaultFrame
};
}
if(frameNum !== this._cachingAtTime.lastTime) {
this._cachingAtTime.lastTime = frameNum;
frameNum *= this.elem.globalData.frameRate;
this.interpolateShape(frameNum, this._cachingAtTime.shapeValue, this._cachingAtTime);
}
return this._cachingAtTime.shapeValue;
}
var ShapePropertyConstructorFunction = ShapePropertyFactory.getConstructorFunction();
var KeyframedShapePropertyConstructorFunction = ShapePropertyFactory.getKeyframedConstructorFunction();
function ShapeExpressions(){}
ShapeExpressions.prototype = {
vertices: function(prop, time){
var shapePath = this.v;
if(time !== undefined) {
shapePath = this.getValueAtTime(time, 0);
}
var i, len = shapePath._length;
var vertices = shapePath[prop];
var points = shapePath.v;
var arr = createSizedArray(len);
for(i = 0; i < len; i += 1) {
if(prop === 'i' || prop === 'o') {
arr[i] = [vertices[i][0] - points[i][0], vertices[i][1] - points[i][1]];
} else {
arr[i] = [vertices[i][0], vertices[i][1]];
}
}
return arr;
},
points: function(time){
return this.vertices('v', time);
},
inTangents: function(time){
return this.vertices('i', time);
},
outTangents: function(time){
return this.vertices('o', time);
},
isClosed: function(){
return this.v.c;
},
pointOnPath: function(perc, time){
var shapePath = this.v;
if(time !== undefined) {
shapePath = this.getValueAtTime(time, 0);
}
if(!this._segmentsLength) {
this._segmentsLength = bez.getSegmentsLength(shapePath);
}
var segmentsLength = this._segmentsLength;
var lengths = segmentsLength.lengths;
var lengthPos = segmentsLength.totalLength * perc;
var i = 0, len = lengths.length;
var j = 0, jLen;
var accumulatedLength = 0, pt;
while(i < len) {
if(accumulatedLength + lengths[i].addedLength > lengthPos) {
var initIndex = i;
var endIndex = (shapePath.c && i === len - 1) ? 0 : i + 1;
var segmentPerc = (lengthPos - accumulatedLength)/lengths[i].addedLength;
pt = bez.getPointInSegment(shapePath.v[initIndex], shapePath.v[endIndex], shapePath.o[initIndex], shapePath.i[endIndex], segmentPerc, lengths[i]);
break;
} else {
accumulatedLength += lengths[i].addedLength;
}
i += 1;
}
if(!pt){
pt = shapePath.c ? [shapePath.v[0][0],shapePath.v[0][1]]:[shapePath.v[shapePath._length-1][0],shapePath.v[shapePath._length-1][1]];
}
return pt;
},
vectorOnPath: function(perc, time, vectorType){
//perc doesn't use triple equality because it can be a Number object as well as a primitive.
perc = perc == 1 ? this.v.c ? 0 : 0.999 : perc;
var pt1 = this.pointOnPath(perc, time);
var pt2 = this.pointOnPath(perc + 0.001, time);
var xLength = pt2[0] - pt1[0];
var yLength = pt2[1] - pt1[1];
var magnitude = Math.sqrt(Math.pow(xLength,2) + Math.pow(yLength,2));
var unitVector = vectorType === 'tangent' ? [xLength/magnitude, yLength/magnitude] : [-yLength/magnitude, xLength/magnitude];
return unitVector;
},
tangentOnPath: function(perc, time){
return this.vectorOnPath(perc, time, 'tangent');
},
normalOnPath: function(perc, time){
return this.vectorOnPath(perc, time, 'normal');
},
setGroupProperty: setGroupProperty,
getValueAtTime: getStaticValueAtTime
};
extendPrototype([ShapeExpressions], ShapePropertyConstructorFunction);
extendPrototype([ShapeExpressions], KeyframedShapePropertyConstructorFunction);
KeyframedShapePropertyConstructorFunction.prototype.getValueAtTime = getShapeValueAtTime;
KeyframedShapePropertyConstructorFunction.prototype.initiateExpression = ExpressionManager.initiateExpression;
var propertyGetShapeProp = ShapePropertyFactory.getShapeProp;
ShapePropertyFactory.getShapeProp = function(elem,data,type, arr, trims){
var prop = propertyGetShapeProp(elem,data,type, arr, trims);
prop.propertyIndex = data.ix;
prop.lock = false;
if(type === 3){
searchExpressions(elem,data.pt,prop);
} else if(type === 4){
searchExpressions(elem,data.ks,prop);
}
if(prop.k){
elem.addDynamicProperty(prop);
}
return prop;
};
var propertyGetTextProp = TextSelectorProp.getTextSelectorProp;
TextSelectorProp.getTextSelectorProp = function(elem, data,arr){
if(data.t === 1){
return new TextExpressionSelectorProp(elem, data,arr);
} else {
return propertyGetTextProp(elem,data,arr);
}
};
}());
(function addDecorator() {
function searchExpressions(){
if(this.data.d.x){
this.calculateExpression = ExpressionManager.initiateExpression.bind(this)(this.elem,this.data.d,this);
this.addEffect(this.getExpressionValue.bind(this));
return true;
}
}
TextProperty.prototype.getExpressionValue = function(currentValue) {
var newValue = this.calculateExpression(currentValue.t);
currentValue.t = newValue;
return currentValue;
}
TextProperty.prototype.searchProperty = function(){
var isKeyframed = this.searchKeyframes();
var hasExpressions = this.searchExpressions();
this.kf = isKeyframed || hasExpressions;
return this.kf;
};
TextProperty.prototype.searchExpressions = searchExpressions;
}());
var ShapeExpressionInterface = (function(){
function iterateElements(shapes,view, propertyGroup){
var arr = [];
var i, len = shapes ? shapes.length : 0;
for(i=0;i<len;i+=1){
if(shapes[i].ty == 'gr'){
arr.push(groupInterfaceFactory(shapes[i],view[i],propertyGroup));
}else if(shapes[i].ty == 'fl'){
arr.push(fillInterfaceFactory(shapes[i],view[i],propertyGroup));
}else if(shapes[i].ty == 'st'){
arr.push(strokeInterfaceFactory(shapes[i],view[i],propertyGroup));
}else if(shapes[i].ty == 'tm'){
arr.push(trimInterfaceFactory(shapes[i],view[i],propertyGroup));
}else if(shapes[i].ty == 'tr'){
//arr.push(transformInterfaceFactory(shapes[i],view[i],propertyGroup));
}else if(shapes[i].ty == 'el'){
arr.push(ellipseInterfaceFactory(shapes[i],view[i],propertyGroup));
}else if(shapes[i].ty == 'sr'){
arr.push(starInterfaceFactory(shapes[i],view[i],propertyGroup));
} else if(shapes[i].ty == 'sh'){
arr.push(pathInterfaceFactory(shapes[i],view[i],propertyGroup));
} else if(shapes[i].ty == 'rc'){
arr.push(rectInterfaceFactory(shapes[i],view[i],propertyGroup));
} else if(shapes[i].ty == 'rd'){
arr.push(roundedInterfaceFactory(shapes[i],view[i],propertyGroup));
} else if(shapes[i].ty == 'rp'){
arr.push(repeaterInterfaceFactory(shapes[i],view[i],propertyGroup));
}
}
return arr;
}
function contentsInterfaceFactory(shape,view, propertyGroup){
var interfaces;
var interfaceFunction = function _interfaceFunction(value){
var i = 0, len = interfaces.length;
while(i<len){
if(interfaces[i]._name === value || interfaces[i].mn === value || interfaces[i].propertyIndex === value || interfaces[i].ix === value || interfaces[i].ind === value){
return interfaces[i];
}
i+=1;
}
if(typeof value === 'number'){
return interfaces[value-1];
}
};
interfaceFunction.propertyGroup = function(val){
if(val === 1){
return interfaceFunction;
} else{
return propertyGroup(val-1);
}
};
interfaces = iterateElements(shape.it, view.it, interfaceFunction.propertyGroup);
interfaceFunction.numProperties = interfaces.length;
interfaceFunction.propertyIndex = shape.cix;
interfaceFunction._name = shape.nm;
return interfaceFunction;
}
function groupInterfaceFactory(shape,view, propertyGroup){
var interfaceFunction = function _interfaceFunction(value){
switch(value){
case 'ADBE Vectors Group':
case 'Contents':
case 2:
return interfaceFunction.content;
//Not necessary for now. Keeping them here in case a new case appears
//case 'ADBE Vector Transform Group':
//case 3:
default:
return interfaceFunction.transform;
}
};
interfaceFunction.propertyGroup = function(val){
if(val === 1){
return interfaceFunction;
} else{
return propertyGroup(val-1);
}
};
var content = contentsInterfaceFactory(shape,view,interfaceFunction.propertyGroup);
var transformInterface = transformInterfaceFactory(shape.it[shape.it.length - 1],view.it[view.it.length - 1],interfaceFunction.propertyGroup);
interfaceFunction.content = content;
interfaceFunction.transform = transformInterface;
Object.defineProperty(interfaceFunction, '_name', {
get: function(){
return shape.nm;
}
});
//interfaceFunction.content = interfaceFunction;
interfaceFunction.numProperties = shape.np;
interfaceFunction.propertyIndex = shape.ix;
interfaceFunction.nm = shape.nm;
interfaceFunction.mn = shape.mn;
return interfaceFunction;
}
function fillInterfaceFactory(shape,view,propertyGroup){
function interfaceFunction(val){
if(val === 'Color' || val === 'color'){
return interfaceFunction.color;
} else if(val === 'Opacity' || val === 'opacity'){
return interfaceFunction.opacity;
}
}
Object.defineProperties(interfaceFunction, {
'color': {
get: function() {
return ExpressionValue(view.c, 1 / view.c.mult, 'color');
}
},
'opacity': {
get: function() {
return ExpressionValue(view.o, 100);
}
},
'_name': { value: shape.nm },
'mn': { value: shape.mn }
});
view.c.setGroupProperty(propertyGroup);
view.o.setGroupProperty(propertyGroup);
return interfaceFunction;
}
function strokeInterfaceFactory(shape,view,propertyGroup){
function _propertyGroup(val){
if(val === 1){
return ob;
} else{
return propertyGroup(val-1);
}
}
function _dashPropertyGroup(val){
if(val === 1){
return dashOb;
} else{
return _propertyGroup(val-1);
}
}
function addPropertyToDashOb(i) {
Object.defineProperty(dashOb, shape.d[i].nm, {
get: function(){
return ExpressionValue(view.d.dataProps[i].p);
}
});
}
var i, len = shape.d ? shape.d.length : 0;
var dashOb = {};
for (i = 0; i < len; i += 1) {
addPropertyToDashOb(i);
view.d.dataProps[i].p.setGroupProperty(_dashPropertyGroup);
}
function interfaceFunction(val){
if(val === 'Color' || val === 'color'){
return interfaceFunction.color;
} else if(val === 'Opacity' || val === 'opacity'){
return interfaceFunction.opacity;
} else if(val === 'Stroke Width' || val === 'stroke width'){
return interfaceFunction.strokeWidth;
}
}
Object.defineProperties(interfaceFunction, {
'color': {
get: function() {
return ExpressionValue(view.c, 1 / view.c.mult, 'color');
}
},
'opacity': {
get: function() {
return ExpressionValue(view.o, 100);
}
},
'strokeWidth': {
get: function() {
return ExpressionValue(view.w);
}
},
'dash': {
get: function() {
return dashOb;
}
},
'_name': { value: shape.nm },
'mn': { value: shape.mn }
});
view.c.setGroupProperty(_propertyGroup);
view.o.setGroupProperty(_propertyGroup);
view.w.setGroupProperty(_propertyGroup);
return interfaceFunction;
}
function trimInterfaceFactory(shape,view,propertyGroup){
function _propertyGroup(val){
if(val == 1){
return interfaceFunction;
} else {
return propertyGroup(--val);
}
}
interfaceFunction.propertyIndex = shape.ix;
view.s.setGroupProperty(_propertyGroup);
view.e.setGroupProperty(_propertyGroup);
view.o.setGroupProperty(_propertyGroup);
function interfaceFunction(val){
if(val === shape.e.ix || val === 'End' || val === 'end'){
return interfaceFunction.end;
}
if(val === shape.s.ix){
return interfaceFunction.start;
}
if(val === shape.o.ix){
return interfaceFunction.offset;
}
}
interfaceFunction.propertyIndex = shape.ix;
Object.defineProperties(interfaceFunction, {
'start': {
get: function() {
return ExpressionValue(view.s, 1 / view.s.mult);
}
},
'end': {
get: function() {
return ExpressionValue(view.e, 1 / view.e.mult);
}
},
'offset': {
get: function() {
return ExpressionValue(view.o);
}
},
'_name': { value: shape.nm }
});
interfaceFunction.mn = shape.mn;
return interfaceFunction;
}
function transformInterfaceFactory(shape,view,propertyGroup){
function _propertyGroup(val){
if(val == 1){
return interfaceFunction;
} else {
return propertyGroup(--val);
}
}
view.transform.mProps.o.setGroupProperty(_propertyGroup);
view.transform.mProps.p.setGroupProperty(_propertyGroup);
view.transform.mProps.a.setGroupProperty(_propertyGroup);
view.transform.mProps.s.setGroupProperty(_propertyGroup);
view.transform.mProps.r.setGroupProperty(_propertyGroup);
if(view.transform.mProps.sk){
view.transform.mProps.sk.setGroupProperty(_propertyGroup);
view.transform.mProps.sa.setGroupProperty(_propertyGroup);
}
view.transform.op.setGroupProperty(_propertyGroup);
function interfaceFunction(value){
if(shape.a.ix === value || value === 'Anchor Point'){
return interfaceFunction.anchorPoint;
}
if(shape.o.ix === value || value === 'Opacity'){
return interfaceFunction.opacity;
}
if(shape.p.ix === value || value === 'Position'){
return interfaceFunction.position;
}
if(shape.r.ix === value || value === 'Rotation' || value === 'ADBE Vector Rotation'){
return interfaceFunction.rotation;
}
if(shape.s.ix === value || value === 'Scale'){
return interfaceFunction.scale;
}
if(shape.sk && shape.sk.ix === value || value === 'Skew'){
return interfaceFunction.skew;
}
if(shape.sa && shape.sa.ix === value || value === 'Skew Axis'){
return interfaceFunction.skewAxis;
}
}
Object.defineProperties(interfaceFunction, {
'opacity': {
get: function(){
return ExpressionValue(view.transform.mProps.o, 1/view.transform.mProps.o.mult);
}
},
'position': {
get: function(){
return ExpressionValue(view.transform.mProps.p);
}
},
'anchorPoint': {
get: function(){
return ExpressionValue(view.transform.mProps.a);
}
},
'scale': {
get: function(){
return ExpressionValue(view.transform.mProps.s, 1 / view.transform.mProps.s.mult);
}
},
'rotation': {
get: function(){
return ExpressionValue(view.transform.mProps.r, 1 / view.transform.mProps.r.mult);
}
},
'skew': {
get: function(){
return ExpressionValue(view.transform.mProps.sk);
}
},
'skewAxis': {
get: function(){
return ExpressionValue(view.transform.mProps.sa);
}
},
'_name': { value: shape.nm }
});
interfaceFunction.ty = 'tr';
interfaceFunction.mn = shape.mn;
return interfaceFunction;
}
function ellipseInterfaceFactory(shape,view,propertyGroup){
function _propertyGroup(val){
if(val == 1){
return interfaceFunction;
} else {
return propertyGroup(--val);
}
}
interfaceFunction.propertyIndex = shape.ix;
var prop = view.sh.ty === 'tm' ? view.sh.prop : view.sh;
prop.s.setGroupProperty(_propertyGroup);
prop.p.setGroupProperty(_propertyGroup);
function interfaceFunction(value){
if(shape.p.ix === value){
return interfaceFunction.position;
}
if(shape.s.ix === value){
return interfaceFunction.size;
}
}
Object.defineProperties(interfaceFunction, {
'size': {
get: function(){
return ExpressionValue(prop.s);
}
},
'position': {
get: function(){
return ExpressionValue(prop.p);
}
},
'_name': { value: shape.nm }
});
interfaceFunction.mn = shape.mn;
return interfaceFunction;
}
function starInterfaceFactory(shape,view,propertyGroup){
function _propertyGroup(val){
if(val == 1){
return interfaceFunction;
} else {
return propertyGroup(--val);
}
}
var prop = view.sh.ty === 'tm' ? view.sh.prop : view.sh;
interfaceFunction.propertyIndex = shape.ix;
prop.or.setGroupProperty(_propertyGroup);
prop.os.setGroupProperty(_propertyGroup);
prop.pt.setGroupProperty(_propertyGroup);
prop.p.setGroupProperty(_propertyGroup);
prop.r.setGroupProperty(_propertyGroup);
if(shape.ir){
prop.ir.setGroupProperty(_propertyGroup);
prop.is.setGroupProperty(_propertyGroup);
}
function interfaceFunction(value){
if(shape.p.ix === value){
return interfaceFunction.position;
}
if(shape.r.ix === value){
return interfaceFunction.rotation;
}
if(shape.pt.ix === value){
return interfaceFunction.points;
}
if(shape.or.ix === value || 'ADBE Vector Star Outer Radius' === value){
return interfaceFunction.outerRadius;
}
if(shape.os.ix === value){
return interfaceFunction.outerRoundness;
}
if(shape.ir && (shape.ir.ix === value || 'ADBE Vector Star Inner Radius' === value)){
return interfaceFunction.innerRadius;
}
if(shape.is && shape.is.ix === value){
return interfaceFunction.innerRoundness;
}
}
Object.defineProperties(interfaceFunction, {
'position': {
get: function() {
return ExpressionValue(prop.p);
}
},
'rotation': {
get: function() {
return ExpressionValue(prop.r, 1 / prop.r.mult);
}
},
'points': {
get: function() {
return ExpressionValue(prop.pt);
}
},
'outerRadius': {
get: function() {
return ExpressionValue(prop.or);
}
},
'outerRoundness': {
get: function(){
return ExpressionValue(prop.os);
}
},
'innerRadius': {
get: function(){
if(!prop.ir){
return 0;
}
return ExpressionValue(prop.ir);
}
},
'innerRoundness': {
get: function(){
if(!prop.is){
return 0;
}
return ExpressionValue(prop.is, 1 / prop.is.mult);
}
},
'_name': { value: shape.nm }
});
interfaceFunction.mn = shape.mn;
return interfaceFunction;
}
function rectInterfaceFactory(shape,view,propertyGroup){
function _propertyGroup(val){
if(val == 1){
return interfaceFunction;
} else {
return propertyGroup(--val);
}
}
var prop = view.sh.ty === 'tm' ? view.sh.prop : view.sh;
interfaceFunction.propertyIndex = shape.ix;
prop.p.setGroupProperty(_propertyGroup);
prop.s.setGroupProperty(_propertyGroup);
prop.r.setGroupProperty(_propertyGroup);
function interfaceFunction(value){
if(shape.p.ix === value){
return interfaceFunction.position;
}
if(shape.r.ix === value){
return interfaceFunction.roundness;
}
if(shape.s.ix === value || value === 'Size' || value === 'ADBE Vector Rect Size'){
return interfaceFunction.size;
}
}
Object.defineProperties(interfaceFunction, {
'position': {
get: function(){
return ExpressionValue(prop.p);
}
},
'roundness': {
get: function(){
return ExpressionValue(prop.r);
}
},
'size': {
get: function(){
return ExpressionValue(prop.s);
}
},
'_name': { value: shape.nm }
});
interfaceFunction.mn = shape.mn;
return interfaceFunction;
}
function roundedInterfaceFactory(shape,view,propertyGroup){
function _propertyGroup(val){
if(val == 1){
return interfaceFunction;
} else {
return propertyGroup(--val);
}
}
var prop = view;
interfaceFunction.propertyIndex = shape.ix;
prop.rd.setGroupProperty(_propertyGroup);
function interfaceFunction(value){
if(shape.r.ix === value || 'Round Corners 1' === value){
return interfaceFunction.radius;
}
}
Object.defineProperties(interfaceFunction, {
'radius': {
get: function() {
return ExpressionValue(prop.rd);
}
},
'_name': { value: shape.nm }
});
interfaceFunction.mn = shape.mn;
return interfaceFunction;
}
function repeaterInterfaceFactory(shape,view,propertyGroup){
function _propertyGroup(val){
if(val == 1){
return interfaceFunction;
} else {
return propertyGroup(--val);
}
}
var prop = view;
interfaceFunction.propertyIndex = shape.ix;
prop.c.setGroupProperty(_propertyGroup);
prop.o.setGroupProperty(_propertyGroup);
function interfaceFunction(value){
if(shape.c.ix === value || 'Copies' === value){
return interfaceFunction.copies;
} else if(shape.o.ix === value || 'Offset' === value){
return interfaceFunction.offset;
}
}
Object.defineProperties(interfaceFunction, {
'copies': {
get: function(){
return ExpressionValue(prop.c);
}
},
'offset': {
get: function(){
return ExpressionValue(prop.o);
}
},
'_name': { value: shape.nm }
});
interfaceFunction.mn = shape.mn;
return interfaceFunction;
}
function pathInterfaceFactory(shape,view,propertyGroup){
var prop = view.sh;
function _propertyGroup(val){
if(val == 1){
return interfaceFunction;
} else {
return propertyGroup(--val);
}
}
prop.setGroupProperty(_propertyGroup);
function interfaceFunction(val){
if(val === 'Shape' || val === 'shape' || val === 'Path' || val === 'path' || val === 'ADBE Vector Shape' || val === 2){
return interfaceFunction.path;
}
}
Object.defineProperties(interfaceFunction, {
'path': {
get: function(){
if(prop.k){
prop.getValue();
}
return prop;
}
},
'shape': {
get: function(){
if(prop.k){
prop.getValue();
}
return prop;
}
},
'_name': { value: shape.nm },
'ix': { value: shape.ix },
'mn': { value: shape.mn }
});
return interfaceFunction;
}
return function(shapes,view,propertyGroup) {
var interfaces;
function _interfaceFunction(value){
if(typeof value === 'number'){
return interfaces[value-1];
} else {
var i = 0, len = interfaces.length;
while(i<len){
if(interfaces[i]._name === value){
return interfaces[i];
}
i+=1;
}
}
}
_interfaceFunction.propertyGroup = propertyGroup;
interfaces = iterateElements(shapes, view, _interfaceFunction);
return _interfaceFunction;
};
}());
var TextExpressionInterface = (function(){
return function(elem){
var _prevValue, _sourceText;
function _thisLayerFunction(){
}
Object.defineProperty(_thisLayerFunction, "sourceText", {
get: function(){
var stringValue = elem.textProperty.currentData.t;
if(stringValue !== _prevValue) {
elem.textProperty.currentData.t = _prevValue;
_sourceText = new String(stringValue);
//If stringValue is an empty string, eval returns undefined, so it has to be returned as a String primitive
_sourceText.value = stringValue ? stringValue : new String(stringValue);
}
return _sourceText;
}
});
return _thisLayerFunction;
};
}());
var LayerExpressionInterface = (function (){
function toWorld(arr, time){
var toWorldMat = new Matrix();
toWorldMat.reset();
var transformMat;
if(time) {
//Todo implement value at time on transform properties
//transformMat = this._elem.finalTransform.mProp.getValueAtTime(time);
transformMat = this._elem.finalTransform.mProp;
} else {
transformMat = this._elem.finalTransform.mProp;
}
transformMat.applyToMatrix(toWorldMat);
if(this._elem.hierarchy && this._elem.hierarchy.length){
var i, len = this._elem.hierarchy.length;
for(i=0;i<len;i+=1){
this._elem.hierarchy[i].finalTransform.mProp.applyToMatrix(toWorldMat);
}
return toWorldMat.applyToPointArray(arr[0],arr[1],arr[2]||0);
}
return toWorldMat.applyToPointArray(arr[0],arr[1],arr[2]||0);
}
function fromWorld(arr, time){
var toWorldMat = new Matrix();
toWorldMat.reset();
var transformMat;
if(time) {
//Todo implement value at time on transform properties
//transformMat = this._elem.finalTransform.mProp.getValueAtTime(time);
transformMat = this._elem.finalTransform.mProp;
} else {
transformMat = this._elem.finalTransform.mProp;
}
transformMat.applyToMatrix(toWorldMat);
if(this._elem.hierarchy && this._elem.hierarchy.length){
var i, len = this._elem.hierarchy.length;
for(i=0;i<len;i+=1){
this._elem.hierarchy[i].finalTransform.mProp.applyToMatrix(toWorldMat);
}
return toWorldMat.inversePoint(arr);
}
return toWorldMat.inversePoint(arr);
}
function fromComp(arr){
var toWorldMat = new Matrix();
toWorldMat.reset();
this._elem.finalTransform.mProp.applyToMatrix(toWorldMat);
if(this._elem.hierarchy && this._elem.hierarchy.length){
var i, len = this._elem.hierarchy.length;
for(i=0;i<len;i+=1){
this._elem.hierarchy[i].finalTransform.mProp.applyToMatrix(toWorldMat);
}
return toWorldMat.inversePoint(arr);
}
return toWorldMat.inversePoint(arr);
}
return function(elem){
var transformInterface;
function _registerMaskInterface(maskManager){
_thisLayerFunction.mask = new MaskManagerInterface(maskManager, elem);
}
function _registerEffectsInterface(effects){
_thisLayerFunction.effect = effects;
}
function _thisLayerFunction(name){
switch(name){
case "ADBE Root Vectors Group":
case "Contents":
case 2:
return _thisLayerFunction.shapeInterface;
case 1:
case 6:
case "Transform":
case "transform":
case "ADBE Transform Group":
return transformInterface;
case 4:
case "ADBE Effect Parade":
return _thisLayerFunction.effect;
}
}
_thisLayerFunction.toWorld = toWorld;
_thisLayerFunction.fromWorld = fromWorld;
_thisLayerFunction.toComp = toWorld;
_thisLayerFunction.fromComp = fromComp;
_thisLayerFunction.sourceRectAtTime = elem.sourceRectAtTime.bind(elem);
_thisLayerFunction._elem = elem;
transformInterface = TransformExpressionInterface(elem.finalTransform.mProp);
var anchorPointDescriptor = getDescriptor(transformInterface, 'anchorPoint');
Object.defineProperties(_thisLayerFunction,{
hasParent: {
get: function(){
return elem.hierarchy.length;
}
},
parent: {
get: function(){
return elem.hierarchy[0].layerInterface;
}
},
rotation: getDescriptor(transformInterface, 'rotation'),
scale: getDescriptor(transformInterface, 'scale'),
position: getDescriptor(transformInterface, 'position'),
opacity: getDescriptor(transformInterface, 'opacity'),
anchorPoint: anchorPointDescriptor,
anchor_point: anchorPointDescriptor,
transform: {
get: function () {
return transformInterface;
}
},
active: {
get: function(){
return elem.isInRange;
}
}
});
_thisLayerFunction.startTime = elem.data.st;
_thisLayerFunction.index = elem.data.ind;
_thisLayerFunction.source = elem.data.refId;
_thisLayerFunction.height = elem.data.ty === 0 ? elem.data.h : 100;
_thisLayerFunction.width = elem.data.ty === 0 ? elem.data.w : 100;
_thisLayerFunction.registerMaskInterface = _registerMaskInterface;
_thisLayerFunction.registerEffectsInterface = _registerEffectsInterface;
return _thisLayerFunction;
};
}());
var CompExpressionInterface = (function (){
return function(comp){
function _thisLayerFunction(name){
var i=0, len = comp.layers.length;
while(i<len){
if(comp.layers[i].nm === name || comp.layers[i].ind === name){
return comp.elements[i].layerInterface;
}
i += 1;
}
return {active:false};
}
Object.defineProperty(_thisLayerFunction, "_name", { value:comp.data.nm });
_thisLayerFunction.layer = _thisLayerFunction;
_thisLayerFunction.pixelAspect = 1;
_thisLayerFunction.height = comp.globalData.compSize.h;
_thisLayerFunction.width = comp.globalData.compSize.w;
_thisLayerFunction.pixelAspect = 1;
_thisLayerFunction.frameDuration = 1/comp.globalData.frameRate;
return _thisLayerFunction;
};
}());
var TransformExpressionInterface = (function (){
return function(transform){
function _thisFunction(name){
switch(name){
case "scale":
case "Scale":
case "ADBE Scale":
case 6:
return _thisFunction.scale;
case "rotation":
case "Rotation":
case "ADBE Rotation":
case "ADBE Rotate Z":
case 10:
return _thisFunction.rotation;
case "ADBE Rotate X":
return _thisFunction.xRotation;
case "ADBE Rotate Y":
return _thisFunction.yRotation;
case "position":
case "Position":
case "ADBE Position":
case 2:
return _thisFunction.position;
case 'ADBE Position_0':
return _thisFunction.xPosition;
case 'ADBE Position_1':
return _thisFunction.yPosition;
case 'ADBE Position_2':
return _thisFunction.zPosition;
case "anchorPoint":
case "AnchorPoint":
case "Anchor Point":
case "ADBE AnchorPoint":
case 1:
return _thisFunction.anchorPoint;
case "opacity":
case "Opacity":
case 11:
return _thisFunction.opacity;
}
}
Object.defineProperty(_thisFunction, "rotation", {
get: function(){
if(transform.r) {
return ExpressionValue(transform.r, 1/degToRads);
} else {
return ExpressionValue(transform.rz, 1/degToRads);
}
}
});
Object.defineProperty(_thisFunction, "xRotation", {
get: function(){
return ExpressionValue(transform.rx, 1/degToRads);
}
});
Object.defineProperty(_thisFunction, "yRotation", {
get: function(){
return ExpressionValue(transform.ry, 1/degToRads);
}
});
Object.defineProperty(_thisFunction, "scale", {
get: function () {
return ExpressionValue(transform.s, 100);
}
});
Object.defineProperty(_thisFunction, "position", {
get: function () {
if(transform.p) {
return ExpressionValue(transform.p);
} else {
return [transform.px.v, transform.py.v, transform.pz ? transform.pz.v : 0];
}
}
});
Object.defineProperty(_thisFunction, "xPosition", {
get: function () {
return ExpressionValue(transform.px);
}
});
Object.defineProperty(_thisFunction, "yPosition", {
get: function () {
return ExpressionValue(transform.py);
}
});
Object.defineProperty(_thisFunction, "zPosition", {
get: function () {
return ExpressionValue(transform.pz);
}
});
Object.defineProperty(_thisFunction, "anchorPoint", {
get: function () {
return ExpressionValue(transform.a);
}
});
Object.defineProperty(_thisFunction, "opacity", {
get: function () {
return ExpressionValue(transform.o, 100);
}
});
Object.defineProperty(_thisFunction, "skew", {
get: function () {
return ExpressionValue(transform.sk);
}
});
Object.defineProperty(_thisFunction, "skewAxis", {
get: function () {
return ExpressionValue(transform.sa);
}
});
Object.defineProperty(_thisFunction, "orientation", {
get: function () {
return ExpressionValue(transform.or);
}
});
return _thisFunction;
};
}());
var ProjectInterface = (function (){
function registerComposition(comp){
this.compositions.push(comp);
}
return function(){
function _thisProjectFunction(name){
var i = 0, len = this.compositions.length;
while(i<len){
if(this.compositions[i].data && this.compositions[i].data.nm === name){
if(this.compositions[i].prepareFrame) {
this.compositions[i].prepareFrame(this.compositions[i].data.xt ? this.currentFrame : this.compositions[i].renderedFrame);
}
return this.compositions[i].compInterface;
}
i+=1;
}
}
_thisProjectFunction.compositions = [];
_thisProjectFunction.currentFrame = 0;
_thisProjectFunction.registerComposition = registerComposition;
return _thisProjectFunction;
};
}());
var EffectsExpressionInterface = (function (){
var ob = {
createEffectsInterface: createEffectsInterface
};
function createEffectsInterface(elem, propertyGroup){
if(elem.effectsManager){
var effectElements = [];
var effectsData = elem.data.ef;
var i, len = elem.effectsManager.effectElements.length;
for(i=0;i<len;i+=1){
effectElements.push(createGroupInterface(effectsData[i],elem.effectsManager.effectElements[i],propertyGroup,elem));
}
return function(name){
var effects = elem.data.ef, i = 0, len = effects.length;
while(i<len) {
if(name === effects[i].nm || name === effects[i].mn || name === effects[i].ix){
return effectElements[i];
}
i += 1;
}
};
}
}
function createGroupInterface(data,elements, propertyGroup, elem){
var effectElements = [];
var i, len = data.ef.length;
for(i=0;i<len;i+=1){
if(data.ef[i].ty === 5){
effectElements.push(createGroupInterface(data.ef[i],elements.effectElements[i],elements.effectElements[i].propertyGroup, elem));
} else {
effectElements.push(createValueInterface(elements.effectElements[i],data.ef[i].ty, elem, _propertyGroup));
}
}
function _propertyGroup(val) {
if(val === 1){
return groupInterface;
} else{
return propertyGroup(val-1);
}
}
var groupInterface = function(name){
var effects = data.ef, i = 0, len = effects.length;
while(i<len) {
if(name === effects[i].nm || name === effects[i].mn || name === effects[i].ix){
if(effects[i].ty === 5){
return effectElements[i];
} else {
return effectElements[i]();
}
}
i += 1;
}
return effectElements[0]();
};
groupInterface.propertyGroup = _propertyGroup;
if(data.mn === 'ADBE Color Control'){
Object.defineProperty(groupInterface, 'color', {
get: function(){
return effectElements[0]();
}
});
}
Object.defineProperty(groupInterface, 'numProperties', {
get: function(){
return data.np;
}
});
groupInterface.active = data.en !== 0;
return groupInterface;
}
function createValueInterface(element, type, elem, propertyGroup){
function interfaceFunction(){
if(type === 10){
return elem.comp.compInterface(element.p.v);
}
return ExpressionValue(element.p);
}
if(element.p.setGroupProperty) {
element.p.setGroupProperty(propertyGroup);
}
return interfaceFunction;
}
return ob;
}());
var MaskManagerInterface = (function(){
function MaskInterface(mask, data){
this._mask = mask;
this._data = data;
}
Object.defineProperty(MaskInterface.prototype, 'maskPath', {
get: function(){
if(this._mask.prop.k){
this._mask.prop.getValue();
}
return this._mask.prop;
}
});
var MaskManager = function(maskManager, elem){
var _maskManager = maskManager;
var _elem = elem;
var _masksInterfaces = createSizedArray(maskManager.viewData.length);
var i, len = maskManager.viewData.length;
for(i = 0; i < len; i += 1) {
_masksInterfaces[i] = new MaskInterface(maskManager.viewData[i], maskManager.masksProperties[i]);
}
var maskFunction = function(name){
i = 0;
while(i<len){
if(maskManager.masksProperties[i].nm === name){
return _masksInterfaces[i];
}
i += 1;
}
};
return maskFunction;
};
return MaskManager;
}());
var ExpressionValue = (function() {
return function(elementProp, mult, type) {
mult = mult || 1;
var expressionValue, arrayValue;
if (elementProp.k) {
elementProp.getValue();
}
var i, len, arrValue, val;
if (type) {
if(type === 'color') {
len = 4;
expressionValue = createTypedArray('float32', len);
arrValue = createTypedArray('float32', len);
for (i = 0; i < len; i += 1) {
expressionValue[i] = arrValue[i] = (i < 3) ? elementProp.v[i] * mult : 1;
}
expressionValue.value = arrValue;
}
} else if (elementProp.propType === 'unidimensional'){
val = elementProp.v * mult;
expressionValue = new Number(val);
expressionValue.value = val;
} else {
len = elementProp.pv.length;
expressionValue = createTypedArray('float32', len);
arrValue = createTypedArray('float32', len);
for (i = 0; i < len; i += 1) {
expressionValue[i] = arrValue[i] = elementProp.v[i] * mult;
}
expressionValue.value = arrValue;
}
expressionValue.numKeys = elementProp.keyframes ? elementProp.keyframes.length : 0;
expressionValue.key = function(pos) {
if (!expressionValue.numKeys) {
return 0;
} else {
return elementProp.keyframes[pos-1].t;
}
};
expressionValue.valueAtTime = elementProp.getValueAtTime;
expressionValue.propertyGroup = elementProp.propertyGroup;
return expressionValue;
};
}());
function SliderEffect(data,elem, container){
this.p = PropertyFactory.getProp(elem,data.v,0,0,container);
}
function AngleEffect(data,elem, container){
this.p = PropertyFactory.getProp(elem,data.v,0,0,container);
}
function ColorEffect(data,elem, container){
this.p = PropertyFactory.getProp(elem,data.v,1,0,container);
}
function PointEffect(data,elem, container){
this.p = PropertyFactory.getProp(elem,data.v,1,0,container);
}
function LayerIndexEffect(data,elem, container){
this.p = PropertyFactory.getProp(elem,data.v,0,0,container);
}
function MaskIndexEffect(data,elem, container){
this.p = PropertyFactory.getProp(elem,data.v,0,0,container);
}
function CheckboxEffect(data,elem, container){
this.p = PropertyFactory.getProp(elem,data.v,0,0,container);
}
function NoValueEffect(){
this.p = {};
}
function EffectsManager(data,element){
var effects = data.ef || [];
this.effectElements = [];
var i,len = effects.length;
var effectItem;
for(i=0;i<len;i++) {
effectItem = new GroupEffect(effects[i],element);
this.effectElements.push(effectItem);
}
}
function GroupEffect(data,element){
this.init(data,element);
}
extendPrototype([DynamicPropertyContainer], GroupEffect);
GroupEffect.prototype.getValue = GroupEffect.prototype.iterateDynamicProperties;
GroupEffect.prototype.init = function(data,element){
this.data = data;
this.effectElements = [];
this.initDynamicPropertyContainer(element);
var i, len = this.data.ef.length;
var eff, effects = this.data.ef;
for(i=0;i<len;i+=1){
eff = null;
switch(effects[i].ty){
case 0:
eff = new SliderEffect(effects[i],element,this);
break;
case 1:
eff = new AngleEffect(effects[i],element,this);
break;
case 2:
eff = new ColorEffect(effects[i],element,this);
break;
case 3:
eff = new PointEffect(effects[i],element,this);
break;
case 4:
case 7:
eff = new CheckboxEffect(effects[i],element,this);
break;
case 10:
eff = new LayerIndexEffect(effects[i],element,this);
break;
case 11:
eff = new MaskIndexEffect(effects[i],element,this);
break;
case 5:
eff = new EffectsManager(effects[i],element,this);
break;
//case 6:
default:
eff = new NoValueEffect(effects[i],element,this);
break;
}
if(eff) {
this.effectElements.push(eff);
}
}
};
var lottiejs = {};
function setLocationHref (href) {
locationHref = href;
}
function play(animation){
animationManager.play(animation);
}
function pause(animation) {
animationManager.pause(animation);
}
function togglePause(animation) {
animationManager.togglePause(animation);
}
function setSpeed(value, animation) {
animationManager.setSpeed(value, animation);
}
function setDirection(value, animation) {
animationManager.setDirection(value, animation);
}
function stop(animation) {
animationManager.stop(animation);
}
function searchAnimations() {
if (standalone === true) {
animationManager.searchAnimations(animationData, standalone, renderer);
} else {
animationManager.searchAnimations();
}
}
function registerAnimation(elem) {
return animationManager.registerAnimation(elem);
}
function resize() {
animationManager.resize();
}
/*function start() {
animationManager.start();
}*/
function goToAndStop(val, isFrame, animation) {
animationManager.goToAndStop(val, isFrame, animation);
}
function setSubframeRendering(flag) {
subframeEnabled = flag;
}
function loadAnimation(params) {
if (standalone === true) {
params.animationData = JSON.parse(animationData);
}
return animationManager.loadAnimation(params);
}
function destroy(animation) {
return animationManager.destroy(animation);
}
function setQuality(value) {
if (typeof value === 'string') {
switch (value) {
case 'high':
defaultCurveSegments = 200;
break;
case 'medium':
defaultCurveSegments = 50;
break;
case 'low':
defaultCurveSegments = 10;
break;
}
} else if (!isNaN(value) && value > 1) {
defaultCurveSegments = value;
}
if (defaultCurveSegments >= 50) {
roundValues(false);
} else {
roundValues(true);
}
}
function inBrowser() {
return typeof navigator !== 'undefined';
}
function installPlugin(type, plugin) {
if (type === 'expressions') {
expressionsPlugin = plugin;
}
}
function getFactory(name) {
switch (name) {
case "propertyFactory":
return PropertyFactory;
case "shapePropertyFactory":
return ShapePropertyFactory;
case "matrix":
return Matrix;
}
}
lottiejs.play = play;
lottiejs.pause = pause;
lottiejs.setLocationHref = setLocationHref;
lottiejs.togglePause = togglePause;
lottiejs.setSpeed = setSpeed;
lottiejs.setDirection = setDirection;
lottiejs.stop = stop;
lottiejs.searchAnimations = searchAnimations;
lottiejs.registerAnimation = registerAnimation;
lottiejs.loadAnimation = loadAnimation;
lottiejs.setSubframeRendering = setSubframeRendering;
lottiejs.resize = resize;
//lottiejs.start = start;
lottiejs.goToAndStop = goToAndStop;
lottiejs.destroy = destroy;
lottiejs.setQuality = setQuality;
lottiejs.inBrowser = inBrowser;
lottiejs.installPlugin = installPlugin;
lottiejs.__getFactory = getFactory;
lottiejs.version = '5.1.11';
function checkReady() {
if (document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
searchAnimations();
}
}
function getQueryVariable(variable) {
var vars = queryString.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
}
var standalone = '__[STANDALONE]__';
var animationData = '__[ANIMATIONDATA]__';
var renderer = '';
if (standalone) {
var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index] || {
src: ''
};
var queryString = myScript.src.replace(/^[^\?]+\??/, '');
renderer = getQueryVariable('renderer');
}
var readyStateCheckInterval = setInterval(checkReady, 100);
return lottiejs;
})); |
var IFCObj=function(){var a={statusChange:null,ySandboxFrame:null,findSandboxFrame:function(){frames&&frames.ifc_frame?(_dumpy(1,1,"MAIN: looking for bridge from 'ifc_frame'"),a.ySandboxFrame=frames.ifc_frame.contentWindow||frames.ifc_frame.contentDocument||frames.ifc_frame):(_dumpy(1,1,"MAIN: looking for bridge from 'ifc_frame'"),a.ySandboxFrame=$frameByName("ifc_frame").contentWindow||$frameByName("ifc_frame").contentDocument||$frameByName("ifc_frame"),"undefined"==typeof a.ySandboxFrame&&opener&&
opener.ifc_frame&&(_dumpy(1,1,"MAIN: looking for bridge from 'opener'"),a.ySandboxFrame=opener.ifc_frame.contentWindow||opener.ifc_frame.contentDocument||frames.ifc_frame));return a},ifcMsgCounter:0,ifcMsgQueue:[],receiveMessage:function(b){_dumpy(1,1,"MAIN: receiveMessage() from "+b.origin);if("object"==typeof b&&void 0!==b.data.s&&void 0!==b.data.a){var c=b.data.s+"."+b.data.a;_dumpy(1,1,"MAIN: {0} ({1})".format(c,b.origin));switch(c){case "yeapf.offline":case "yeapf.online":"function"==typeof a.statusChange&&
a.statusChange(b.data.a);break;case "yeapf.getConnParams":_dumpy(1,1,"MAIN: getConnParams");a.getConnParams(function(a){b.source.postMessage({s:"yeapf",a:"connParams",limits:{connParams:a}},"*")});break;case "yeapf.dataPleaded":if(c=a.ifcMsgQueue[b.data.callbackId]){if("function"==typeof c.aCallbackFunction)c.aCallbackFunction(200,0,b.data.data);else if("string"==typeof c.aCallbackFunction){var d=c.aCallbackFunction.split("."),e=null,e=1==d.length?window[c.aCallbackFunction]:window[d[0]][d[1]];"function"==
typeof e&&e(b.data.data)}delete a.ifcMsgQueue[b.data.callbackId]}}}},getConnParams:function(b){chrome&&chrome.storage&&chrome.storage.local.get("connParams",function(a){a=a.connParams;b(a)})},setConnParams:function(b,c,d,e){var f={server:b,user:c,password:d,terminalID:e};chrome.storage.local.set({connParams:f},function(){a.ySandboxFrame.postMessage({s:"yeapf",a:"connParams",limits:{connParams:f}},"*")})},plead:function(b,c,d,e){_dumpy(1,1,"MAIN: preparing to plead ("+b+","+c+")");if("function"==typeof e||
"undefined"==typeof e||"string"==typeof e)if("undefined"===typeof a.ySandboxFrame&&(_dump("MAIN: looking for 'ifc_frame' iframe"),a.findSandboxFrame()),a.ySandboxFrame){var f=a.ifcMsgCounter++;d={s:"yeapf",a:"plead",context:{s:b,a:c,limits:d,queueId:f}};a.ifcMsgQueue[f]={aCallbackFunction:e};_dumpy(1,1,"MAIN: pleading("+b+","+c+")");_dumpy(1,1,JSON.stringify(d));a.ySandboxFrame.postMessage(d,"*")}else _dumpy(1,1,"MAIN: you need a sandboxed iframe called ifc_frame");else _dumpy(1,1,"MAIN: you need to define a callback function")}};
return a.findSandboxFrame()},ifc;addOnLoadManager(function(){ifc||(ifc=IFCObj());window.addEventListener("message",ifc.receiveMessage,!1)});
|
module.exports={A:{A:{"2":"K D G E A B gB"},B:{"2":"1 C d J M H I"},C:{"2":"0 1 2 3 5 6 7 8 9 dB EB F N K D G E A B C d J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z GB AB CB DB XB WB"},D:{"2":"0 1 2 3 5 6 7 8 9 F N K D G E A B C d J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z GB AB CB DB QB iB KB IB LB MB NB OB"},E:{"2":"4 F N K D G E A B C PB HB RB SB TB UB VB p YB"},F:{"2":"0 4 5 E B C J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z ZB aB bB cB p BB eB"},G:{"2":"G HB fB FB hB JB jB kB lB mB nB oB pB qB rB sB"},H:{"2":"tB"},I:{"2":"3 EB F uB vB wB xB FB yB zB"},J:{"2":"D A"},K:{"2":"4 A B C L p BB"},L:{"2":"IB"},M:{"2":"2"},N:{"2":"A B"},O:{"2":"0B"},P:{"2":"F 1B 2B 3B 4B"},Q:{"2":"5B"},R:{"2":"6B"}},B:5,C:":has() CSS relational pseudo-class"};
|
require("requirish")._(module);
var factories = require("lib/misc/factories");
var ObjWithIntegerId_Schema = {
id: factories.next_available_id(),
name: "ObjWithIntegerId",
fields: [
{name: "title", fieldType: "UAString"},
{
name: "requestHandle", fieldType: "IntegerId"
}
]
};
exports.ObjWithIntegerId_Schema = ObjWithIntegerId_Schema;
|
'use strict'
const Bignumber = require('bignumber.js')
exports.MT = {
POS_INT: 0,
NEG_INT: 1,
BYTE_STRING: 2,
UTF8_STRING: 3,
ARRAY: 4,
MAP: 5,
TAG: 6,
SIMPLE_FLOAT: 7
}
exports.TAG = {
DATE_STRING: 0,
DATE_EPOCH: 1,
POS_BIGINT: 2,
NEG_BIGINT: 3,
DECIMAL_FRAC: 4,
BIGFLOAT: 5,
BASE64URL_EXPECTED: 21,
BASE64_EXPECTED: 22,
BASE16_EXPECTED: 23,
CBOR: 24,
URI: 32,
BASE64URL: 33,
BASE64: 34,
REGEXP: 35,
MIME: 36
}
exports.NUMBYTES = {
ZERO: 0,
ONE: 24,
TWO: 25,
FOUR: 26,
EIGHT: 27,
INDEFINITE: 31
}
exports.SIMPLE = {
FALSE: 20,
TRUE: 21,
NULL: 22,
UNDEFINED: 23
}
exports.SYMS = {
NULL: Symbol('null'),
UNDEFINED: Symbol('undef'),
PARENT: Symbol('parent'),
BREAK: Symbol('break'),
STREAM: Symbol('stream')
}
exports.SHIFT32 = Math.pow(2, 32)
exports.SHIFT16 = Math.pow(2, 16)
exports.MAX_SAFE_HIGH = 0x1fffff
exports.NEG_ONE = new Bignumber(-1)
exports.TEN = new Bignumber(10)
exports.TWO = new Bignumber(2)
exports.PARENT = {
ARRAY: 0,
OBJECT: 1,
MAP: 2,
TAG: 3,
BYTE_STRING: 4,
UTF8_STRING: 5
}
|
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { refType } from '@material-ui/utils';
import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled';
import experimentalStyled from '../styles/experimentalStyled';
import useControlled from '../utils/useControlled';
import useFormControl from '../FormControl/useFormControl';
import IconButton from '../IconButton';
import { getSwitchBaseUtilityClass } from './switchBaseClasses';
const useUtilityClasses = styleProps => {
const {
classes,
checked,
disabled
} = styleProps;
const slots = {
root: ['root', checked && 'checked', disabled && 'disabled'],
input: ['input']
};
return composeClasses(slots, getSwitchBaseUtilityClass, classes);
};
const SwitchBaseRoot = experimentalStyled(IconButton, {}, {
name: 'PrivateSwitchBase',
slot: 'Root'
})({
/* Styles applied to the root element. */
padding: 9
});
const SwitchBaseInput = experimentalStyled('input', {}, {
name: 'PrivateSwitchBase',
slot: 'Input'
})({
/* Styles applied to the internal input element. */
cursor: 'inherit',
position: 'absolute',
opacity: 0,
width: '100%',
height: '100%',
top: 0,
left: 0,
margin: 0,
padding: 0,
zIndex: 1
});
/**
* @ignore - internal component.
*/
const SwitchBase = /*#__PURE__*/React.forwardRef(function SwitchBase(props, ref) {
const {
autoFocus,
checked: checkedProp,
checkedIcon,
className,
defaultChecked,
disabled: disabledProp,
icon,
id,
inputProps,
inputRef,
name,
onBlur,
onChange,
onFocus,
readOnly,
required,
tabIndex,
type,
value
} = props,
other = _objectWithoutPropertiesLoose(props, ["autoFocus", "checked", "checkedIcon", "className", "defaultChecked", "disabled", "icon", "id", "inputProps", "inputRef", "name", "onBlur", "onChange", "onFocus", "readOnly", "required", "tabIndex", "type", "value"]);
const [checked, setCheckedState] = useControlled({
controlled: checkedProp,
default: Boolean(defaultChecked),
name: 'SwitchBase',
state: 'checked'
});
const muiFormControl = useFormControl();
const handleFocus = event => {
if (onFocus) {
onFocus(event);
}
if (muiFormControl && muiFormControl.onFocus) {
muiFormControl.onFocus(event);
}
};
const handleBlur = event => {
if (onBlur) {
onBlur(event);
}
if (muiFormControl && muiFormControl.onBlur) {
muiFormControl.onBlur(event);
}
};
const handleInputChange = event => {
// Workaround for https://github.com/facebook/react/issues/9023
if (event.nativeEvent.defaultPrevented) {
return;
}
const newChecked = event.target.checked;
setCheckedState(newChecked);
if (onChange) {
// TODO v5: remove the second argument.
onChange(event, newChecked);
}
};
let disabled = disabledProp;
if (muiFormControl) {
if (typeof disabled === 'undefined') {
disabled = muiFormControl.disabled;
}
}
const hasLabelFor = type === 'checkbox' || type === 'radio';
const styleProps = _extends({}, props, {
checked,
disabled
});
const classes = useUtilityClasses(styleProps);
return /*#__PURE__*/React.createElement(SwitchBaseRoot, _extends({
component: "span",
className: clsx(classes.root, className),
disabled: disabled,
tabIndex: null,
role: undefined,
onFocus: handleFocus,
onBlur: handleBlur,
styleProps: styleProps,
ref: ref
}, other), /*#__PURE__*/React.createElement(SwitchBaseInput, _extends({
autoFocus: autoFocus,
checked: checkedProp,
defaultChecked: defaultChecked,
className: classes.input,
disabled: disabled,
id: hasLabelFor && id,
name: name,
onChange: handleInputChange,
readOnly: readOnly,
ref: inputRef,
required: required,
styleProps: styleProps,
tabIndex: tabIndex,
type: type,
value: value
}, inputProps)), checked ? checkedIcon : icon);
}); // NB: If changed, please update Checkbox, Switch and Radio
// so that the API documentation is updated.
process.env.NODE_ENV !== "production" ? SwitchBase.propTypes = {
/**
* If `true`, the `input` element is focused during the first mount.
*/
autoFocus: PropTypes.bool,
/**
* If `true`, the component is checked.
*/
checked: PropTypes.bool,
/**
* The icon to display when the component is checked.
*/
checkedIcon: PropTypes.node.isRequired,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* @ignore
*/
defaultChecked: PropTypes.bool,
/**
* If `true`, the component is disabled.
*/
disabled: PropTypes.bool,
/**
* The icon to display when the component is unchecked.
*/
icon: PropTypes.node.isRequired,
/**
* The id of the `input` element.
*/
id: PropTypes.string,
/**
* [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
*/
inputProps: PropTypes.object,
/**
* Pass a ref to the `input` element.
*/
inputRef: refType,
/*
* @ignore
*/
name: PropTypes.string,
/**
* @ignore
*/
onBlur: PropTypes.func,
/**
* Callback fired when the state is changed.
*
* @param {object} event The event source of the callback.
* You can pull out the new checked state by accessing `event.target.checked` (boolean).
*/
onChange: PropTypes.func,
/**
* @ignore
*/
onFocus: PropTypes.func,
/**
* It prevents the user from changing the value of the field
* (not from interacting with the field).
*/
readOnly: PropTypes.bool,
/**
* If `true`, the `input` element is required.
*/
required: PropTypes.bool,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.object,
/**
* @ignore
*/
tabIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* The input component prop `type`.
*/
type: PropTypes.string.isRequired,
/**
* The value of the component.
*/
value: PropTypes.any
} : void 0;
export default SwitchBase; |
import * as CounterState from './CounterState';
import * as NavigationState from '../../modules/navigation/NavigationState';
import React, {PropTypes} from 'react';
import {
StyleSheet,
TouchableOpacity,
Image,
Text,
View
} from 'react-native';
const CounterView = React.createClass({
propTypes: {
counter: PropTypes.number.isRequired,
userName: PropTypes.string,
userProfilePhoto: PropTypes.string,
loading: PropTypes.bool.isRequired,
dispatch: PropTypes.func.isRequired
},
increment() {
this.props.dispatch(CounterState.increment());
},
reset() {
this.props.dispatch(CounterState.reset());
},
random() {
this.props.dispatch(CounterState.random());
},
bored() {
this.props.dispatch(NavigationState.pushRoute({
key: 'Color',
title: 'Color Screen'
}));
},
renderUserInfo() {
if (!this.props.userName) {
return null;
}
return (
<View style={styles.userContainer}>
<Image
style={styles.userProfilePhoto}
source={{
uri: this.props.userProfilePhoto,
width: 80,
height: 80
}}
/>
<Text style={styles.linkButton}>
Welcome, {this.props.userName}!
</Text>
</View>
);
},
render() {
const loadingStyle = this.props.loading
? {backgroundColor: '#eee'}
: null;
return (
<View style={styles.container}>
{this.renderUserInfo()}
<TouchableOpacity
onPress={this.increment}
style={[styles.counterButton, loadingStyle]}>
<Text style={styles.counter}>
{this.props.counter}
</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.reset}>
<Text style={styles.linkButton}>
Reset
</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.random}>
<Text style={styles.linkButton}>
Random
</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.bored} accessible={true}>
<Text style={styles.linkButton}>
{'I\'m bored!'}
</Text>
</TouchableOpacity>
</View>
);
}
});
const circle = {
borderWidth: 0,
borderRadius: 40,
width: 80,
height: 80
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white'
},
userContainer: {
justifyContent: 'center',
alignItems: 'center'
},
userProfilePhoto: {
...circle,
alignSelf: 'center'
},
counterButton: {
...circle,
backgroundColor: 'green',
alignItems: 'center',
justifyContent: 'center',
margin: 20
},
counter: {
color: 'white',
fontSize: 20,
textAlign: 'center'
},
welcome: {
textAlign: 'center',
color: 'black',
marginBottom: 5,
padding: 5
},
linkButton: {
textAlign: 'center',
color: '#CCCCCC',
marginBottom: 10,
padding: 5
}
});
export default CounterView;
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function _helperPluginUtils() {
const data = require("@babel/helper-plugin-utils");
_helperPluginUtils = function () {
return data;
};
return data;
}
function _core() {
const data = require("@babel/core");
_core = function () {
return data;
};
return data;
}
var _default = (0, _helperPluginUtils().declare)(api => {
api.assertVersion(7);
return {
name: "transform-typeof-symbol",
visitor: {
Scope({
scope
}) {
if (!scope.getBinding("Symbol")) {
return;
}
scope.rename("Symbol");
},
UnaryExpression(path) {
const {
node,
parent
} = path;
if (node.operator !== "typeof") return;
if (path.parentPath.isBinaryExpression() && _core().types.EQUALITY_BINARY_OPERATORS.indexOf(parent.operator) >= 0) {
const opposite = path.getOpposite();
if (opposite.isLiteral() && opposite.node.value !== "symbol" && opposite.node.value !== "object") {
return;
}
}
const helper = this.addHelper("typeof");
const isUnderHelper = path.findParent(path => {
return path.isVariableDeclarator() && path.node.id === helper || path.isFunctionDeclaration() && path.node.id && path.node.id.name === helper.name;
});
if (isUnderHelper) {
return;
}
const call = _core().types.callExpression(helper, [node.argument]);
const arg = path.get("argument");
if (arg.isIdentifier() && !path.scope.hasBinding(arg.node.name, true)) {
const unary = _core().types.unaryExpression("typeof", _core().types.cloneNode(node.argument));
path.replaceWith(_core().types.conditionalExpression(_core().types.binaryExpression("===", unary, _core().types.stringLiteral("undefined")), _core().types.stringLiteral("undefined"), call));
} else {
path.replaceWith(call);
}
}
}
};
});
exports.default = _default; |
var name = "First Emblem of Grendaline";
var collection_type = 0;
var is_secret = 0;
var desc = "Got your first Grendaline Emblem";
var status_text = "Lo, meek one. For granting me the dues I so richly deserve, I have granted you 1000 favor points. And now I guess I will grant you this Emblem of Grendaline. Lo!";
var last_published = 1323915606;
var is_shareworthy = 0;
var url = "first-emblem-of-grendaline";
var category = "giants";
var url_swf = "\/c2.glitch.bz\/achievements\/2011-05-09\/first_grendaline_emblem_1304983707.swf";
var url_img_180 = "\/c2.glitch.bz\/achievements\/2011-05-09\/first_grendaline_emblem_1304983707_180.png";
var url_img_60 = "\/c2.glitch.bz\/achievements\/2011-05-09\/first_grendaline_emblem_1304983707_60.png";
var url_img_40 = "\/c2.glitch.bz\/achievements\/2011-05-09\/first_grendaline_emblem_1304983707_40.png";
function on_apply(pc){
}
var conditions = {
162 : {
type : "counter",
group : "emblems_acquired",
label : "grendaline",
value : "1"
},
};
function onComplete(pc){ // generated from rewards
var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0;
multiplier += pc.imagination_get_achievement_modifier();
if (/completist/i.exec(this.name)) {
var level = pc.stats_get_level();
if (level > 4) {
multiplier *= (pc.stats_get_level()/4);
}
}
pc.stats_add_xp(round_to_5(75 * multiplier), true);
pc.createItemFromFamiliar("emblem_grendaline", 1);
if(pc.buffs_has('gift_of_gab')) {
pc.buffs_remove('gift_of_gab');
}
else if(pc.buffs_has('silvertongue')) {
pc.buffs_remove('silvertongue');
}
}
var rewards = {
"xp" : 75,
"items" : {
"0" : {
"class_id" : "emblem_grendaline",
"label" : "Emblem of Grendaline",
"count" : "1"
}
}
};
// generated ok (NO DATE)
|
//jshint strict: false
module.exports = function(config) {
config.set({
basePath: './app',
frameworks: ['jasmine'],
files: [
'lib/jquery.min.js',
'lib/angular.min.js',
'lib/angular-route.min.js',
'lib/angular-mocks.js',
'lib/firebase.js',
'lib/angularfire.min.js',
'js/*.js',
'unit_tests/*.js'
],
exclude: [
'js/grayscale.js',
'js/grayscale.min.js',
'js/eventDetilTemp.js',
'js/fblogin.js',
'js/memberDetail.js',
'js/memberDetail_linked.js',
'js/memberDetailTemp.js',
'js/memberDisplay.js',
'js/teamDetailTemp.js',
'js/teamDisplay.js',
'js/index.js'
],
preprocessors: {
'js/site.js' : ['coverage'],
//'js/index.js' : ['coverage'],
'js/admin.js' : ['coverage'],
'js/team.js' : ['coverage'],
'js/member.js' : ['coverage']
},
reporters: ['progress', 'coverage'],
coverageReporter: {
type: 'html',
dir: 'coverage/',
subdir: '.'
},
port: 8080,
colors: true,
browsers: ['Chrome'],
singleRun: true,
plugins: [
'karma-chrome-launcher',
'karma-jasmine',
'karma-coverage'
]
});
};
|
define(['mobs', 'items', 'npcs', 'warrior', 'chest'], function(Mobs, Items, NPCs, Warrior, Chest) {
var EntityFactory = {};
EntityFactory.createEntity = function(kind, id, name) {
if(!kind) {
log.error("kind is undefined", true);
return;
}
if(!_.isFunction(EntityFactory.builders[kind])) {
throw Error(kind + " is not a valid Entity type");
}
return EntityFactory.builders[kind](id, name);
};
//===== mobs ======
EntityFactory.builders = [];
EntityFactory.builders[Types.Entities.WARRIOR] = function(id, name) {
return new Warrior(id, name);
};
EntityFactory.builders[Types.Entities.RAT] = function(id) {
return new Mobs.Rat(id);
};
EntityFactory.builders[Types.Entities.SKELETON] = function(id) {
return new Mobs.Skeleton(id);
};
EntityFactory.builders[Types.Entities.SKELETON2] = function(id) {
return new Mobs.Skeleton2(id);
};
EntityFactory.builders[Types.Entities.SPECTRE] = function(id) {
return new Mobs.Spectre(id);
};
EntityFactory.builders[Types.Entities.DEATHKNIGHT] = function(id) {
return new Mobs.Deathknight(id);
};
EntityFactory.builders[Types.Entities.GOBLIN] = function(id) {
return new Mobs.Goblin(id);
};
EntityFactory.builders[Types.Entities.OGRE] = function(id) {
return new Mobs.Ogre(id);
};
EntityFactory.builders[Types.Entities.CRAB] = function(id) {
return new Mobs.Crab(id);
};
EntityFactory.builders[Types.Entities.SNAKE] = function(id) {
return new Mobs.Snake(id);
};
EntityFactory.builders[Types.Entities.EYE] = function(id) {
return new Mobs.Eye(id);
};
EntityFactory.builders[Types.Entities.BAT] = function(id) {
return new Mobs.Bat(id);
};
EntityFactory.builders[Types.Entities.WIZARD] = function(id) {
return new Mobs.Wizard(id);
};
EntityFactory.builders[Types.Entities.BOSS] = function(id) {
return new Mobs.Boss(id);
};
//===== items ======
EntityFactory.builders[Types.Entities.SWORD2] = function(id) {
return new Items.Sword2(id);
};
EntityFactory.builders[Types.Entities.AXE] = function(id) {
return new Items.Axe(id);
};
EntityFactory.builders[Types.Entities.REDSWORD] = function(id) {
return new Items.RedSword(id);
};
EntityFactory.builders[Types.Entities.BLUESWORD] = function(id) {
return new Items.BlueSword(id);
};
EntityFactory.builders[Types.Entities.GOLDENSWORD] = function(id) {
return new Items.GoldenSword(id);
};
EntityFactory.builders[Types.Entities.MORNINGSTAR] = function(id) {
return new Items.MorningStar(id);
};
EntityFactory.builders[Types.Entities.MAILARMOR] = function(id) {
return new Items.MailArmor(id);
};
EntityFactory.builders[Types.Entities.LEATHERARMOR] = function(id) {
return new Items.LeatherArmor(id);
};
EntityFactory.builders[Types.Entities.PLATEARMOR] = function(id) {
return new Items.PlateArmor(id);
};
EntityFactory.builders[Types.Entities.REDARMOR] = function(id) {
return new Items.RedArmor(id);
};
EntityFactory.builders[Types.Entities.GOLDENARMOR] = function(id) {
return new Items.GoldenArmor(id);
};
EntityFactory.builders[Types.Entities.FLASK] = function(id) {
return new Items.Flask(id);
};
EntityFactory.builders[Types.Entities.FIREPOTION] = function(id) {
return new Items.FirePotion(id);
};
EntityFactory.builders[Types.Entities.BURGER] = function(id) {
return new Items.Burger(id);
};
EntityFactory.builders[Types.Entities.CAKE] = function(id) {
return new Items.Cake(id);
};
EntityFactory.builders[Types.Entities.CHEST] = function(id) {
return new Chest(id);
};
//====== NPCs ======
EntityFactory.builders[Types.Entities.GUARD] = function(id) {
return new NPCs.Guard(id);
};
EntityFactory.builders[Types.Entities.KING] = function(id) {
return new NPCs.King(id);
};
EntityFactory.builders[Types.Entities.VILLAGEGIRL] = function(id) {
return new NPCs.VillageGirl(id);
};
EntityFactory.builders[Types.Entities.VILLAGER] = function(id) {
return new NPCs.Villager(id);
};
EntityFactory.builders[Types.Entities.CODER] = function(id) {
return new NPCs.Coder(id);
};
EntityFactory.builders[Types.Entities.AGENT] = function(id) {
return new NPCs.Agent(id);
};
EntityFactory.builders[Types.Entities.RICK] = function(id) {
return new NPCs.Rick(id);
};
EntityFactory.builders[Types.Entities.SCIENTIST] = function(id) {
return new NPCs.Scientist(id);
};
EntityFactory.builders[Types.Entities.NYAN] = function(id) {
return new NPCs.Nyan(id);
};
EntityFactory.builders[Types.Entities.PRIEST] = function(id) {
return new NPCs.Priest(id);
};
EntityFactory.builders[Types.Entities.SORCERER] = function(id) {
return new NPCs.Sorcerer(id);
};
EntityFactory.builders[Types.Entities.OCTOCAT] = function(id) {
return new NPCs.Octocat(id);
};
EntityFactory.builders[Types.Entities.BEACHNPC] = function(id) {
return new NPCs.BeachNpc(id);
};
EntityFactory.builders[Types.Entities.FORESTNPC] = function(id) {
return new NPCs.ForestNpc(id);
};
EntityFactory.builders[Types.Entities.DESERTNPC] = function(id) {
return new NPCs.DesertNpc(id);
};
EntityFactory.builders[Types.Entities.LAVANPC] = function(id) {
return new NPCs.LavaNpc(id);
};
return EntityFactory;
});
|
var name = "Order of the Hoarder";
var collection_type = 0;
var is_secret = 0;
var desc = "Crafted 211 Storage Display Boxes";
var status_text = "With your 211 magnificently crafted Storage Display Boxes, you have truly joined - if not founded - the Order of the Hoarder. Take your commemorative badge, and display it with pride.";
var last_published = 1348802180;
var is_shareworthy = 1;
var url = "order-of-the-hoarder";
var category = "furniture";
var url_swf = "\/c2.glitch.bz\/achievements\/2012-06-14\/order_of_the_hoarder_1339718440.swf";
var url_img_180 = "\/c2.glitch.bz\/achievements\/2012-06-14\/order_of_the_hoarder_1339718440_180.png";
var url_img_60 = "\/c2.glitch.bz\/achievements\/2012-06-14\/order_of_the_hoarder_1339718440_60.png";
var url_img_40 = "\/c2.glitch.bz\/achievements\/2012-06-14\/order_of_the_hoarder_1339718440_40.png";
function on_apply(pc){
}
var conditions = {
705 : {
type : "counter",
group : "making_known_recipe",
label : "255",
value : "211"
},
};
function onComplete(pc){ // generated from rewards
var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0;
multiplier += pc.imagination_get_achievement_modifier();
if (/completist/i.exec(this.name)) {
var level = pc.stats_get_level();
if (level > 4) {
multiplier *= (pc.stats_get_level()/4);
}
}
pc.stats_add_xp(round_to_5(1000 * multiplier), true);
pc.stats_add_favor_points("alph", round_to_5(200 * multiplier));
if(pc.buffs_has('gift_of_gab')) {
pc.buffs_remove('gift_of_gab');
}
else if(pc.buffs_has('silvertongue')) {
pc.buffs_remove('silvertongue');
}
}
var rewards = {
"xp" : 1000,
"favor" : {
"giant" : "alph",
"points" : 200
}
};
// generated ok (NO DATE)
|
var parser = require('../index.js');
var expect = require('expect.js');
var helpers = require('./helpers.js');
var encode = parser.encode;
var decode = parser.decode;
var BlobBuilder = global.BlobBuilder || global.WebKitBlobBuilder || global.MSBlobBuilder || global.MozBlobBuilder;
describe('parser', function() {
it('encodes a Blob', function() {
var data;
if (BlobBuilder) {
var bb = new BlobBuilder();
bb.append(new ArrayBuffer(2));
data = bb.getBlob();
} else {
data = new Blob([new ArrayBuffer(2)]);
}
var packet = {
type: parser.BINARY_EVENT,
data: data,
id: 0,
nsp: '/'
};
helpers.test_bin(packet);
});
it('encodes an Blob deep in JSON', function() {
var data;
if (BlobBuilder) {
var bb = new BlobBuilder();
bb.append(new ArrayBuffer(2));
data = bb.getBlob();
} else {
data = new Blob([new ArrayBuffer(2)]);
}
var packet = {
type: parser.BINARY_EVENT,
data: {a: 'hi', b: { why: data }, c: 'bye'},
id: 999,
nsp: '/deep'
};
helpers.test_bin(packet);
});
it('encodes a binary ack with a blob', function() {
var data;
if (BlobBuilder) {
var bb = new BlobBuilder();
bb.append(new ArrayBuffer(2));
data = bb.getBlob();
} else {
data = new Blob([new ArrayBuffer(2)]);
}
var packet = {
type: parser.BINARY_ACK,
data: {a: 'hi ack', b: { why: data }, c: 'bye ack'},
id: 999,
nsp: '/deep'
};
helpers.test_bin(packet);
})
});
|
/**
@module ember
@submodule ember-runtime
*/
// ..........................................................
// HELPERS
//
import Ember from 'ember-metal/core'; // ES6TODO: Ember.A
import symbol from 'ember-metal/symbol';
import { get } from 'ember-metal/property_get';
import {
computed,
cacheFor
} from 'ember-metal/computed';
import isNone from 'ember-metal/is_none';
import Enumerable from 'ember-runtime/mixins/enumerable';
import { Mixin } from 'ember-metal/mixin';
import {
propertyWillChange,
propertyDidChange
} from 'ember-metal/property_events';
import {
addListener,
removeListener,
sendEvent,
hasListeners
} from 'ember-metal/events';
import { meta as metaFor } from 'ember-metal/meta';
import { markObjectAsDirty } from 'ember-metal/tags';
import EachProxy from 'ember-runtime/system/each_proxy';
import { deprecate } from 'ember-metal/debug';
import isEnabled from 'ember-metal/features';
function arrayObserversHelper(obj, target, opts, operation, notify) {
let willChange = (opts && opts.willChange) || 'arrayWillChange';
let didChange = (opts && opts.didChange) || 'arrayDidChange';
let hasObservers = get(obj, 'hasArrayObservers');
if (hasObservers === notify) {
propertyWillChange(obj, 'hasArrayObservers');
}
operation(obj, '@array:before', target, willChange);
operation(obj, '@array:change', target, didChange);
if (hasObservers === notify) {
propertyDidChange(obj, 'hasArrayObservers');
}
return obj;
}
export function addArrayObserver(array, target, opts) {
return arrayObserversHelper(array, target, opts, addListener, false);
}
export function removeArrayObserver(array, target, opts) {
return arrayObserversHelper(array, target, opts, removeListener, true);
}
export function objectAt(content, idx) {
if (content.objectAt) {
return content.objectAt(idx);
}
return content[idx];
}
export function arrayContentWillChange(array, startIdx, removeAmt, addAmt) {
let removing, lim;
// if no args are passed assume everything changes
if (startIdx === undefined) {
startIdx = 0;
removeAmt = addAmt = -1;
} else {
if (removeAmt === undefined) {
removeAmt = -1;
}
if (addAmt === undefined) {
addAmt = -1;
}
}
if (array.__each) {
array.__each.arrayWillChange(array, startIdx, removeAmt, addAmt);
}
sendEvent(array, '@array:before', [array, startIdx, removeAmt, addAmt]);
if (startIdx >= 0 && removeAmt >= 0 && get(array, 'hasEnumerableObservers')) {
removing = [];
lim = startIdx + removeAmt;
for (let idx = startIdx; idx < lim; idx++) {
removing.push(objectAt(array, idx));
}
} else {
removing = removeAmt;
}
array.enumerableContentWillChange(removing, addAmt);
return array;
}
export function arrayContentDidChange(array, startIdx, removeAmt, addAmt) {
markObjectAsDirty(metaFor(array));
// if no args are passed assume everything changes
if (startIdx === undefined) {
startIdx = 0;
removeAmt = addAmt = -1;
} else {
if (removeAmt === undefined) {
removeAmt = -1;
}
if (addAmt === undefined) {
addAmt = -1;
}
}
let adding;
if (startIdx >= 0 && addAmt >= 0 && get(array, 'hasEnumerableObservers')) {
adding = [];
let lim = startIdx + addAmt;
for (let idx = startIdx; idx < lim; idx++) {
adding.push(objectAt(array, idx));
}
} else {
adding = addAmt;
}
array.enumerableContentDidChange(removeAmt, adding);
if (array.__each) {
array.__each.arrayDidChange(array, startIdx, removeAmt, addAmt);
}
sendEvent(array, '@array:change', [array, startIdx, removeAmt, addAmt]);
let length = get(array, 'length');
let cachedFirst = cacheFor(array, 'firstObject');
let cachedLast = cacheFor(array, 'lastObject');
if (objectAt(array, 0) !== cachedFirst) {
propertyWillChange(array, 'firstObject');
propertyDidChange(array, 'firstObject');
}
if (objectAt(array, length - 1) !== cachedLast) {
propertyWillChange(array, 'lastObject');
propertyDidChange(array, 'lastObject');
}
return array;
}
const EMBER_ARRAY = symbol('EMBER_ARRAY');
export function isEmberArray(obj) {
return obj && !!obj[EMBER_ARRAY];
}
// ..........................................................
// ARRAY
//
/**
This mixin implements Observer-friendly Array-like behavior. It is not a
concrete implementation, but it can be used up by other classes that want
to appear like arrays.
For example, ArrayProxy is a concrete classes that can
be instantiated to implement array-like behavior. Both of these classes use
the Array Mixin by way of the MutableArray mixin, which allows observable
changes to be made to the underlying array.
Unlike `Ember.Enumerable,` this mixin defines methods specifically for
collections that provide index-ordered access to their contents. When you
are designing code that needs to accept any kind of Array-like object, you
should use these methods instead of Array primitives because these will
properly notify observers of changes to the array.
Although these methods are efficient, they do add a layer of indirection to
your application so it is a good idea to use them only when you need the
flexibility of using both true JavaScript arrays and "virtual" arrays such
as controllers and collections.
You can use the methods defined in this module to access and modify array
contents in a KVO-friendly way. You can also be notified whenever the
membership of an array changes by using `.observes('myArray.[]')`.
To support `Ember.Array` in your own class, you must override two
primitives to use it: `length()` and `objectAt()`.
Note that the Ember.Array mixin also incorporates the `Ember.Enumerable`
mixin. All `Ember.Array`-like objects are also enumerable.
@class Array
@namespace Ember
@uses Ember.Enumerable
@since Ember 0.9.0
@public
*/
const ArrayMixin = Mixin.create(Enumerable, {
[EMBER_ARRAY]: true,
/**
__Required.__ You must implement this method to apply this mixin.
Your array must support the `length` property. Your replace methods should
set this property whenever it changes.
@property {Number} length
@public
*/
length: null,
/**
Returns the object at the given `index`. If the given `index` is negative
or is greater or equal than the array length, returns `undefined`.
This is one of the primitives you must implement to support `Ember.Array`.
If your object supports retrieving the value of an array item using `get()`
(i.e. `myArray.get(0)`), then you do not need to implement this method
yourself.
```javascript
let arr = ['a', 'b', 'c', 'd'];
arr.objectAt(0); // 'a'
arr.objectAt(3); // 'd'
arr.objectAt(-1); // undefined
arr.objectAt(4); // undefined
arr.objectAt(5); // undefined
```
@method objectAt
@param {Number} idx The index of the item to return.
@return {*} item at index or undefined
@public
*/
objectAt(idx) {
if (idx < 0 || idx >= get(this, 'length')) {
return undefined;
}
return get(this, idx);
},
/**
This returns the objects at the specified indexes, using `objectAt`.
```javascript
let arr = ['a', 'b', 'c', 'd'];
arr.objectsAt([0, 1, 2]); // ['a', 'b', 'c']
arr.objectsAt([2, 3, 4]); // ['c', 'd', undefined]
```
@method objectsAt
@param {Array} indexes An array of indexes of items to return.
@return {Array}
@public
*/
objectsAt(indexes) {
return indexes.map(idx => objectAt(this, idx));
},
// overrides Ember.Enumerable version
nextObject(idx) {
return objectAt(this, idx);
},
/**
This is the handler for the special array content property. If you get
this property, it will return this. If you set this property to a new
array, it will replace the current content.
This property overrides the default property defined in `Ember.Enumerable`.
@property []
@return this
@public
*/
'[]': computed({
get(key) {
return this;
},
set(key, value) {
this.replace(0, get(this, 'length'), value);
return this;
}
}),
firstObject: computed(function() {
return objectAt(this, 0);
}).readOnly(),
lastObject: computed(function() {
return objectAt(this, get(this, 'length') - 1);
}).readOnly(),
// optimized version from Enumerable
contains(obj) {
if (isEnabled('ember-runtime-enumerable-includes')) {
deprecate(
'`Enumerable#contains` is deprecated, use `Enumerable#includes` instead.',
false,
{ id: 'ember-runtime.enumerable-contains', until: '3.0.0', url: 'http://emberjs.com/deprecations/v2.x#toc_enumerable-contains' }
);
}
return this.indexOf(obj) >= 0;
},
// Add any extra methods to Ember.Array that are native to the built-in Array.
/**
Returns a new array that is a slice of the receiver. This implementation
uses the observable array methods to retrieve the objects for the new
slice.
```javascript
let arr = ['red', 'green', 'blue'];
arr.slice(0); // ['red', 'green', 'blue']
arr.slice(0, 2); // ['red', 'green']
arr.slice(1, 100); // ['green', 'blue']
```
@method slice
@param {Number} beginIndex (Optional) index to begin slicing from.
@param {Number} endIndex (Optional) index to end the slice at (but not included).
@return {Array} New array with specified slice
@public
*/
slice(beginIndex, endIndex) {
let ret = Ember.A();
let length = get(this, 'length');
if (isNone(beginIndex)) {
beginIndex = 0;
}
if (isNone(endIndex) || (endIndex > length)) {
endIndex = length;
}
if (beginIndex < 0) {
beginIndex = length + beginIndex;
}
if (endIndex < 0) {
endIndex = length + endIndex;
}
while (beginIndex < endIndex) {
ret[ret.length] = objectAt(this, beginIndex++);
}
return ret;
},
/**
Returns the index of the given object's first occurrence.
If no `startAt` argument is given, the starting location to
search is 0. If it's negative, will count backward from
the end of the array. Returns -1 if no match is found.
```javascript
let arr = ['a', 'b', 'c', 'd', 'a'];
arr.indexOf('a'); // 0
arr.indexOf('z'); // -1
arr.indexOf('a', 2); // 4
arr.indexOf('a', -1); // 4
arr.indexOf('b', 3); // -1
arr.indexOf('a', 100); // -1
```
@method indexOf
@param {Object} object the item to search for
@param {Number} startAt optional starting location to search, default 0
@return {Number} index or -1 if not found
@public
*/
indexOf(object, startAt) {
let len = get(this, 'length');
if (startAt === undefined) {
startAt = 0;
}
if (startAt < 0) {
startAt += len;
}
for (let idx = startAt; idx < len; idx++) {
if (objectAt(this, idx) === object) {
return idx;
}
}
return -1;
},
/**
Returns the index of the given object's last occurrence.
If no `startAt` argument is given, the search starts from
the last position. If it's negative, will count backward
from the end of the array. Returns -1 if no match is found.
```javascript
let arr = ['a', 'b', 'c', 'd', 'a'];
arr.lastIndexOf('a'); // 4
arr.lastIndexOf('z'); // -1
arr.lastIndexOf('a', 2); // 0
arr.lastIndexOf('a', -1); // 4
arr.lastIndexOf('b', 3); // 1
arr.lastIndexOf('a', 100); // 4
```
@method lastIndexOf
@param {Object} object the item to search for
@param {Number} startAt optional starting location to search, default 0
@return {Number} index or -1 if not found
@public
*/
lastIndexOf(object, startAt) {
let len = get(this, 'length');
if (startAt === undefined || startAt >= len) {
startAt = len - 1;
}
if (startAt < 0) {
startAt += len;
}
for (let idx = startAt; idx >= 0; idx--) {
if (objectAt(this, idx) === object) {
return idx;
}
}
return -1;
},
// ..........................................................
// ARRAY OBSERVERS
//
/**
Adds an array observer to the receiving array. The array observer object
normally must implement two methods:
* `arrayWillChange(observedObj, start, removeCount, addCount)` - This method will be
called just before the array is modified.
* `arrayDidChange(observedObj, start, removeCount, addCount)` - This method will be
called just after the array is modified.
Both callbacks will be passed the observed object, starting index of the
change as well as a count of the items to be removed and added. You can use
these callbacks to optionally inspect the array during the change, clear
caches, or do any other bookkeeping necessary.
In addition to passing a target, you can also include an options hash
which you can use to override the method names that will be invoked on the
target.
@method addArrayObserver
@param {Object} target The observer object.
@param {Object} opts Optional hash of configuration options including
`willChange` and `didChange` option.
@return {Ember.Array} receiver
@public
*/
addArrayObserver(target, opts) {
return addArrayObserver(this, target, opts);
},
/**
Removes an array observer from the object if the observer is current
registered. Calling this method multiple times with the same object will
have no effect.
@method removeArrayObserver
@param {Object} target The object observing the array.
@param {Object} opts Optional hash of configuration options including
`willChange` and `didChange` option.
@return {Ember.Array} receiver
@public
*/
removeArrayObserver(target, opts) {
return removeArrayObserver(this, target, opts);
},
/**
Becomes true whenever the array currently has observers watching changes
on the array.
@property {Boolean} hasArrayObservers
@public
*/
hasArrayObservers: computed(function() {
return hasListeners(this, '@array:change') || hasListeners(this, '@array:before');
}),
/**
If you are implementing an object that supports `Ember.Array`, call this
method just before the array content changes to notify any observers and
invalidate any related properties. Pass the starting index of the change
as well as a delta of the amounts to change.
@method arrayContentWillChange
@param {Number} startIdx The starting index in the array that will change.
@param {Number} removeAmt The number of items that will be removed. If you
pass `null` assumes 0
@param {Number} addAmt The number of items that will be added. If you
pass `null` assumes 0.
@return {Ember.Array} receiver
@public
*/
arrayContentWillChange(startIdx, removeAmt, addAmt) {
return arrayContentWillChange(this, startIdx, removeAmt, addAmt);
},
/**
If you are implementing an object that supports `Ember.Array`, call this
method just after the array content changes to notify any observers and
invalidate any related properties. Pass the starting index of the change
as well as a delta of the amounts to change.
@method arrayContentDidChange
@param {Number} startIdx The starting index in the array that did change.
@param {Number} removeAmt The number of items that were removed. If you
pass `null` assumes 0
@param {Number} addAmt The number of items that were added. If you
pass `null` assumes 0.
@return {Ember.Array} receiver
@public
*/
arrayContentDidChange(startIdx, removeAmt, addAmt) {
return arrayContentDidChange(this, startIdx, removeAmt, addAmt);
},
/**
Returns a special object that can be used to observe individual properties
on the array. Just get an equivalent property on this object and it will
return an enumerable that maps automatically to the named key on the
member objects.
`@each` should only be used in a non-terminal context. Example:
```javascript
myMethod: computed('posts.@each.author', function(){
...
});
```
If you merely want to watch for the array being changed, like an object being
replaced, added or removed, use `[]` instead of `@each`.
```javascript
myMethod: computed('posts.[]', function(){
...
});
```
@property @each
@public
*/
'@each': computed(function() {
// TODO use Symbol or add to meta
if (!this.__each) {
this.__each = new EachProxy(this);
}
return this.__each;
}).volatile()
});
if (isEnabled('ember-runtime-enumerable-includes')) {
ArrayMixin.reopen({
/**
Returns `true` if the passed object can be found in the array.
This method is a Polyfill for ES 2016 Array.includes.
If no `startAt` argument is given, the starting location to
search is 0. If it's negative, searches from the index of
`this.length + startAt` by asc.
```javascript
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(3, 2); // true
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true
[1, 2, 3].includes(1, -1); // false
[1, 2, 3].includes(1, -4); // true
[1, 2, NaN].includes(NaN); // true
```
@method includes
@param {Object} obj The object to search for.
@param {Number} startAt optional starting location to search, default 0
@return {Boolean} `true` if object is found in the array.
@public
*/
includes(obj, startAt) {
let len = get(this, 'length');
if (startAt === undefined) {
startAt = 0;
}
if (startAt < 0) {
startAt += len;
}
for (let idx = startAt; idx < len; idx++) {
let currentObj = objectAt(this, idx);
// SameValueZero comparison (NaN !== NaN)
if (obj === currentObj || (obj !== obj && currentObj !== currentObj)) {
return true;
}
}
return false;
}
});
}
export default ArrayMixin;
|
/**
* Link to list
*
* Usage:
* <ma-list-button entity="entity" size="xs"></ma-list-button>
*/
function maListButtonDirective($state) {
return {
restrict: 'E',
scope: {
entity: '&',
entityName: '@',
size: '@',
label: '@',
},
link: function (scope, element, attrs) {
scope.gotoList = () => {
var entityName = scope.entity() ? scope.entity().name() : attrs.entityName;
var params = entityName == $state.params.entity ? $state.params : {};
params.entity = entityName;
$state.go($state.get('list'), params);
}
scope.label = scope.label || 'List';
},
template:
` <a class="btn btn-default" ng-class="size ? \'btn-\' + size : \'\'" ng-click="gotoList()">
<span class="glyphicon glyphicon-list" aria-hidden="true"></span> <span class="hidden-xs">{{ ::label }}</span>
</a>`
};
}
maListButtonDirective.$inject = ['$state'];
module.exports = maListButtonDirective;
|
/* globals WebAppHashing */
import less from 'less';
import Autoprefixer from 'less-plugin-autoprefix';
import crypto from 'crypto';
const logger = new Logger('rocketchat:theme', {
methods: {
stop_rendering: {
type: 'info'
}
}
});
WebApp.rawConnectHandlers.use(function(req, res, next) {
const path = req.url.split('?')[0];
const prefix = __meteor_runtime_config__.ROOT_URL_PATH_PREFIX || '';
if (path === `${ prefix }/__cordova/theme.css` || path === `${ prefix }/theme.css`) {
const css = RocketChat.theme.getCss();
const hash = crypto.createHash('sha1').update(css).digest('hex');
res.setHeader('Content-Type', 'text/css; charset=UTF-8');
res.setHeader('ETag', `"${ hash }"`);
res.write(css);
return res.end();
} else {
return next();
}
});
const calculateClientHash = WebAppHashing.calculateClientHash;
WebAppHashing.calculateClientHash = function(manifest, includeFilter, runtimeConfigOverride) {
const css = RocketChat.theme.getCss();
if (css.trim() !== '') {
const hash = crypto.createHash('sha1').update(css).digest('hex');
let themeManifestItem = _.find(manifest, function(item) {
return item.path === 'app/theme.css';
});
if (themeManifestItem == null) {
themeManifestItem = {};
manifest.push(themeManifestItem);
}
themeManifestItem.path = 'app/theme.css';
themeManifestItem.type = 'css';
themeManifestItem.cacheable = true;
themeManifestItem.where = 'client';
themeManifestItem.url = `/theme.css?${ hash }`;
themeManifestItem.size = css.length;
themeManifestItem.hash = hash;
}
return calculateClientHash.call(this, manifest, includeFilter, runtimeConfigOverride);
};
RocketChat.theme = new class {
constructor() {
this.variables = {};
this.packageCallbacks = [];
this.files = ['server/colors.less'];
this.customCSS = '';
RocketChat.settings.add('css', '');
RocketChat.settings.addGroup('Layout');
RocketChat.settings.onload('css', Meteor.bindEnvironment((key, value, initialLoad) => {
if (!initialLoad) {
Meteor.startup(function() {
process.emit('message', {
refresh: 'client'
});
});
}
}));
this.compileDelayed = _.debounce(Meteor.bindEnvironment(this.compile.bind(this)), 100);
Meteor.startup(() => {
RocketChat.settings.onAfterInitialLoad(() => {
RocketChat.settings.get(/^theme-./, Meteor.bindEnvironment((key, value) => {
if (key === 'theme-custom-css' && value != null) {
this.customCSS = value;
} else {
const name = key.replace(/^theme-[a-z]+-/, '');
if (this.variables[name] != null) {
this.variables[name].value = value;
}
}
this.compileDelayed();
}));
});
});
}
compile() {
let content = [this.getVariablesAsLess()];
content.push(...this.files.map((name) => Assets.getText(name)));
content.push(...this.packageCallbacks.map(name => name()));
content.push(this.customCSS);
content = content.join('\n');
const options = {
compress: true,
plugins: [new Autoprefixer()]
};
const start = Date.now();
return less.render(content, options, function(err, data) {
logger.stop_rendering(Date.now() - start);
if (err != null) {
return console.log(err);
}
RocketChat.settings.updateById('css', data.css);
return Meteor.startup(function() {
return Meteor.setTimeout(function() {
return process.emit('message', {
refresh: 'client'
});
}, 200);
});
});
}
addVariable(type, name, value, section, persist = true, editor, allowedTypes) {
this.variables[name] = {
type,
value
};
if (persist) {
const config = {
group: 'Layout',
type,
editor: editor || type,
section,
'public': false,
allowedTypes
};
return RocketChat.settings.add(`theme-${ type }-${ name }`, value, config);
}
}
addPublicColor(name, value, section, editor = 'color') {
return this.addVariable('color', name, value, section, true, editor, ['color', 'expression']);
}
addPublicFont(name, value) {
return this.addVariable('font', name, value, 'Fonts', true);
}
getVariablesAsObject() {
return Object.keys(this.variables).reduce((obj, name) => {
obj[name] = this.variables[name].value;
return obj;
}, {});
}
getVariablesAsLess() {
return Object.keys(this.variables).map((name) => {
const variable = this.variables[name];
return `@${ name }: ${ variable.value };`;
}).join('\n');
}
addPackageAsset(cb) {
this.packageCallbacks.push(cb);
return this.compileDelayed();
}
getCss() {
return RocketChat.settings.get('css') || '';
}
};
|
/* eslint quote-props: ["error", "as-needed"] */
import React, { Component, PropTypes } from 'react';
import { findDOMNode } from 'react-dom';
import { css } from 'glamor';
import { FormInput, Glyph, GlyphButton } from '../../../elemental';
import theme from '../../../../theme';
class EditFormHeaderSearch extends Component {
constructor () {
super();
this.focusField = this.focusField.bind(this);
this.state = { focused: false };
}
focusField () {
this.setState({ focused: true }, () => {
findDOMNode(this.refs.target).focus();
});
}
render () {
const { focused } = this.state;
const {
onChange,
onKeyUp,
value,
...props
} = this.props;
return focused ? (
<div className={css(classes.wrapper)}>
<Glyph
cssStyles={classes.glyph}
color={theme.color.gray40}
name="search"
data-e2e-search-icon
/>
<FormInput
cssStyles={classes.input}
name="search"
onBlur={() => this.setState({ focused: false })}
onChange={onChange}
onKeyUp={onKeyUp}
placeholder="Search"
ref="target"
type="search"
value={value}
{...props}
/>
</div>
) : (
<GlyphButton
color="primary"
glyph="search"
glyphStyle={{ marginRight: '0.4em' }}
onClick={this.focusField}
onFocus={this.focusField}
position="left"
variant="link"
style={{ paddingLeft: '0.7em' }}
data-e2e-search-icon
>
Search
</GlyphButton>
);
}
};
// For props "glyph", "glyphColor", and "glyphSize":
// prop type validation will occur within the Glyph component, no need to
// duplicate, just pass it through.
EditFormHeaderSearch.propTypes = {
onChange: PropTypes.func.isRequired,
value: PropTypes.string,
};
const classes = {
wrapper: {
display: 'inline-block',
position: 'relative',
verticalAlign: 'middle',
},
// input
input: {
paddingLeft: '2.2em',
// opacity: 0,
transition: 'all 240ms',
width: 100,
':focus': {
// opacity: 1,
width: 240,
},
},
// glyph
glyph: {
alignItems: 'center',
display: 'flex',
height: '100%',
justifyContent: 'center',
position: 'absolute',
width: '2.2em',
},
};
module.exports = EditFormHeaderSearch;
// Search
// ------------------------------
// .EditForm__header__search {
// display: inline-block;
// margin-left: 1em;
// }
// .EditForm__header__search-field {
// margin-bottom: 0;
//
// .IconField__icon {
// color: @app-primary;
// }
// }
//
// // make the input appear as a button link until focused
// .EditForm__header__search-input {
// // override elemental's transition to catch the width or it looks weird
// .transition( all 0.15s ease-in-out );
// .placeholder(@link-color);
// background: transparent;
// border-color: transparent;
// box-shadow: none;
// display: inline-block;
//
// // set the width to only be as long as if it were a button initially
// // this is updated on focus to a more comfortable typing length
// width: 100px;
//
// // decorate the input as a link
// &:hover {
// .placeholder(@link-hover-color);
// border-color: transparent;
// cursor: pointer;
//
// // handle placeholder text
// &::-moz-placeholder { text-decoration: underline; }
// &:-ms-input-placeholder { text-decoration: underline; }
// &::-webkit-input-placeholder { text-decoration: underline; }
//
// + .IconField__icon {
// color: @link-hover-color;
// }
// }
//
// // return the input to it's natural appearance on focus
// &:focus {
// .placeholder(@input-placeholder-color);
// background: white;
// border-color: @input-border-color-focus;
// box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 0 3px fade(@input-border-color-focus, 10%);
// cursor: auto;
// outline: 0;
// width: 240px;
//
// // handle placeholder text
// &::-moz-placeholder { text-decoration: none; }
// &:-ms-input-placeholder { text-decoration: none; }
// &::-webkit-input-placeholder { text-decoration: none; }
//
// + .IconField__icon {
// color: @input-placeholder-color;
// }
// }
// }
// // hide the search field on small devices
// @media (max-width: 480px) {
// .EditForm__header__search {
// display: none;
// }
// }
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: >
Result of boolean conversion from nonempty string value (length is not
zero) is true; from empty String (length is zero) is false
es5id: 9.2_A5_T4
description: Any nonempty string convert to Boolean by implicit transformation
---*/
// CHECK#1
if (!(" ") !== false) {
$ERROR('#1: !(" ") === false. Actual: ' + (!(" ")));
}
// CHECK#2
if (!("Nonempty String") !== false) {
$ERROR('#2: !("Nonempty String") === false. Actual: ' + (!("Nonempty String")));
}
|
var parent = require('../../stable/string/replace-all');
module.exports = parent;
|
var isCanvasSupportsStreamCapturing = false;
var isVideoSupportsStreamCapturing = false;
['captureStream', 'mozCaptureStream', 'webkitCaptureStream'].forEach(function(item) {
// asdf
if(item in document.createElement('canvas')) {
isCanvasSupportsStreamCapturing = true;
}
if(item in document.createElement('video')) {
isVideoSupportsStreamCapturing = true;
}
});
|
var searchData=
[
['filter',['filter',['../interface_chipmunk_multi_grab.html#aa494a368c4c817b4613555ad15a2ac70',1,'ChipmunkMultiGrab::filter()'],['../interface_chipmunk_shape.html#ac7feb7912cc5469386b60d57c6fc37c8',1,'ChipmunkShape::filter()']]],
['flags',['flags',['../structcp_space_debug_draw_options.html#a1b4b5128c4b70e3642f49ad71d49159f',1,'cpSpaceDebugDrawOptions']]],
['force',['force',['../interface_chipmunk_body.html#a128612d069fac7a00478e2d5b3f0340c',1,'ChipmunkBody']]],
['friction',['friction',['../interface_chipmunk_shape.html#ac161b9d079be6c15166a7e94232eb296',1,'ChipmunkShape']]]
];
|
/// Copyright (c) 2009 Microsoft Corporation
///
/// Redistribution and use in source and binary forms, with or without modification, are permitted provided
/// that the following conditions are met:
/// * Redistributions of source code must retain the above copyright notice, this list of conditions and
/// the following disclaimer.
/// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
/// the following disclaimer in the documentation and/or other materials provided with the distribution.
/// * Neither the name of Microsoft nor the names of its contributors may be used to
/// endorse or promote products derived from this software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
/// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
/// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
/// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
/// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
/// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
/// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*
Step 4 of defineProperty calls the [[DefineOwnProperty]] internal method
of O to define the property. Step 7b of [[DefineOwnProperty]] rejects if
current.[[Enumerable]] and desc.[[Enumerable]] are the boolean negations
of each other.
*/
ES5Harness.registerTest( {
id: "15.2.3.6-4-10",
path: "TestCases/chapter15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-10.js",
description: "Object.defineProperty throws TypeError when changing [[Enumerable]] from false to true on non-configurable accessor properties",
test: function testcase() {
var o = {};
// create an accessor property; all other attributes default to false.
// dummy getter
var getter = function () { return 1; }
var d1 = { get: getter, enumerable: false, configurable: false };
Object.defineProperty(o, "foo", d1);
// now, setting enumerable to true should fail, since [[Configurable]]
// on the original property will be false.
var desc = { get: getter, enumerable: true };
try {
Object.defineProperty(o, "foo", desc);
}
catch (e) {
if (e instanceof TypeError) {
// the property should remain unchanged.
var d2 = Object.getOwnPropertyDescriptor(o, "foo");
if (d2.get === getter &&
d2.enumerable === false &&
d2.configurable === false) {
return true;
}
}
}
},
precondition: function prereq() {
return fnExists(Object.defineProperty) && fnExists(Object.getOwnPropertyDescriptor);
}
});
|
var _ = require('../util')
var Cache = require('../cache')
var templateCache = new Cache(1000)
var idSelectorCache = new Cache(1000)
var map = {
_default: [0, '', ''],
legend: [1, '<fieldset>', '</fieldset>'],
tr: [2, '<table><tbody>', '</tbody></table>'],
col: [
2,
'<table><tbody></tbody><colgroup>',
'</colgroup></table>'
]
}
map.td =
map.th = [
3,
'<table><tbody><tr>',
'</tr></tbody></table>'
]
map.option =
map.optgroup = [
1,
'<select multiple="multiple">',
'</select>'
]
map.thead =
map.tbody =
map.colgroup =
map.caption =
map.tfoot = [1, '<table>', '</table>']
map.g =
map.defs =
map.symbol =
map.use =
map.image =
map.text =
map.circle =
map.ellipse =
map.line =
map.path =
map.polygon =
map.polyline =
map.rect = [
1,
'<svg ' +
'xmlns="http://www.w3.org/2000/svg" ' +
'xmlns:xlink="http://www.w3.org/1999/xlink" ' +
'xmlns:ev="http://www.w3.org/2001/xml-events"' +
'version="1.1">',
'</svg>'
]
/**
* Check if a node is a supported template node with a
* DocumentFragment content.
*
* @param {Node} node
* @return {Boolean}
*/
function isRealTemplate (node) {
return _.isTemplate(node) &&
node.content instanceof DocumentFragment
}
var tagRE = /<([\w:]+)/
var entityRE = /&\w+;|&#\d+;|&#x[\dA-F]+;/
/**
* Convert a string template to a DocumentFragment.
* Determines correct wrapping by tag types. Wrapping
* strategy found in jQuery & component/domify.
*
* @param {String} templateString
* @return {DocumentFragment}
*/
function stringToFragment (templateString) {
// try a cache hit first
var hit = templateCache.get(templateString)
if (hit) {
return hit
}
var frag = document.createDocumentFragment()
var tagMatch = templateString.match(tagRE)
var entityMatch = entityRE.test(templateString)
if (!tagMatch && !entityMatch) {
// text only, return a single text node.
frag.appendChild(
document.createTextNode(templateString)
)
} else {
var tag = tagMatch && tagMatch[1]
var wrap = map[tag] || map._default
var depth = wrap[0]
var prefix = wrap[1]
var suffix = wrap[2]
var node = document.createElement('div')
node.innerHTML = prefix + templateString.trim() + suffix
while (depth--) {
node = node.lastChild
}
var child
/* eslint-disable no-cond-assign */
while (child = node.firstChild) {
/* eslint-enable no-cond-assign */
frag.appendChild(child)
}
}
templateCache.put(templateString, frag)
return frag
}
/**
* Convert a template node to a DocumentFragment.
*
* @param {Node} node
* @return {DocumentFragment}
*/
function nodeToFragment (node) {
// if its a template tag and the browser supports it,
// its content is already a document fragment.
if (isRealTemplate(node)) {
_.trimNode(node.content)
return node.content
}
// script template
if (node.tagName === 'SCRIPT') {
return stringToFragment(node.textContent)
}
// normal node, clone it to avoid mutating the original
var clone = exports.clone(node)
var frag = document.createDocumentFragment()
var child
/* eslint-disable no-cond-assign */
while (child = clone.firstChild) {
/* eslint-enable no-cond-assign */
frag.appendChild(child)
}
_.trimNode(frag)
return frag
}
// Test for the presence of the Safari template cloning bug
// https://bugs.webkit.org/show_bug.cgi?id=137755
var hasBrokenTemplate = _.inBrowser
? (function () {
var a = document.createElement('div')
a.innerHTML = '<template>1</template>'
return !a.cloneNode(true).firstChild.innerHTML
})()
: false
// Test for IE10/11 textarea placeholder clone bug
var hasTextareaCloneBug = _.inBrowser
? (function () {
var t = document.createElement('textarea')
t.placeholder = 't'
return t.cloneNode(true).value === 't'
})()
: false
/**
* 1. Deal with Safari cloning nested <template> bug by
* manually cloning all template instances.
* 2. Deal with IE10/11 textarea placeholder bug by setting
* the correct value after cloning.
*
* @param {Element|DocumentFragment} node
* @return {Element|DocumentFragment}
*/
exports.clone = function (node) {
if (!node.querySelectorAll) {
return node.cloneNode()
}
var res = node.cloneNode(true)
var i, original, cloned
/* istanbul ignore if */
if (hasBrokenTemplate) {
var clone = res
if (isRealTemplate(node)) {
node = node.content
clone = res.content
}
original = node.querySelectorAll('template')
if (original.length) {
cloned = clone.querySelectorAll('template')
i = cloned.length
while (i--) {
cloned[i].parentNode.replaceChild(
exports.clone(original[i]),
cloned[i]
)
}
}
}
/* istanbul ignore if */
if (hasTextareaCloneBug) {
if (node.tagName === 'TEXTAREA') {
res.value = node.value
} else {
original = node.querySelectorAll('textarea')
if (original.length) {
cloned = res.querySelectorAll('textarea')
i = cloned.length
while (i--) {
cloned[i].value = original[i].value
}
}
}
}
return res
}
/**
* Process the template option and normalizes it into a
* a DocumentFragment that can be used as a partial or a
* instance template.
*
* @param {*} template
* Possible values include:
* - DocumentFragment object
* - Node object of type Template
* - id selector: '#some-template-id'
* - template string: '<div><span>{{msg}}</span></div>'
* @param {Boolean} clone
* @param {Boolean} noSelector
* @return {DocumentFragment|undefined}
*/
exports.parse = function (template, clone, noSelector) {
var node, frag
// if the template is already a document fragment,
// do nothing
if (template instanceof DocumentFragment) {
_.trimNode(template)
return clone
? exports.clone(template)
: template
}
if (typeof template === 'string') {
// id selector
if (!noSelector && template.charAt(0) === '#') {
// id selector can be cached too
frag = idSelectorCache.get(template)
if (!frag) {
node = document.getElementById(template.slice(1))
if (node) {
frag = nodeToFragment(node)
// save selector to cache
idSelectorCache.put(template, frag)
}
}
} else {
// normal string template
frag = stringToFragment(template)
}
} else if (template.nodeType) {
// a direct node
frag = nodeToFragment(template)
}
return frag && clone
? exports.clone(frag)
: frag
}
|
/**
* (c) 2009-2020 Sebastian Bochann
*
* Price indicator for Highcharts
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*/
'use strict';
import H from '../Core/Globals.js';
import U from '../Core/Utilities.js';
var addEvent = U.addEvent, isArray = U.isArray, merge = U.merge;
/**
* The line marks the last price from visible range of points.
*
* @sample {highstock} stock/indicators/last-visible-price
* Last visible price
*
* @declare Highcharts.SeriesLastVisiblePriceOptionsObject
* @product highstock
* @requires modules/price-indicator
* @apioption plotOptions.series.lastVisiblePrice
*/
/**
* Enable or disable the indicator.
*
* @type {boolean}
* @product highstock
* @default true
* @apioption plotOptions.series.lastVisiblePrice.enabled
*/
/**
* @declare Highcharts.SeriesLastVisiblePriceLabelOptionsObject
* @apioption plotOptions.series.lastVisiblePrice.label
*/
/**
* Enable or disable the label.
*
* @type {boolean}
* @product highstock
* @default true
* @apioption plotOptions.series.lastVisiblePrice.label.enabled
*
*/
/**
* The line marks the last price from all points.
*
* @sample {highstock} stock/indicators/last-price
* Last price
*
* @declare Highcharts.SeriesLastPriceOptionsObject
* @product highstock
* @requires modules/price-indicator
* @apioption plotOptions.series.lastPrice
*/
/**
* Enable or disable the indicator.
*
* @type {boolean}
* @product highstock
* @default true
* @apioption plotOptions.series.lastPrice.enabled
*/
/**
* The color of the line of last price.
*
* @type {string}
* @product highstock
* @default red
* @apioption plotOptions.series.lastPrice.color
*
*/
/* eslint-disable no-invalid-this */
addEvent(H.Series, 'afterRender', function () {
var serie = this, seriesOptions = serie.options, pointRange = seriesOptions.pointRange, lastVisiblePrice = seriesOptions.lastVisiblePrice, lastPrice = seriesOptions.lastPrice;
if ((lastVisiblePrice || lastPrice) &&
seriesOptions.id !== 'highcharts-navigator-series') {
var xAxis = serie.xAxis, yAxis = serie.yAxis, origOptions = yAxis.crosshair, origGraphic = yAxis.cross, origLabel = yAxis.crossLabel, points = serie.points, yLength = serie.yData.length, pLength = points.length, x = serie.xData[serie.xData.length - 1], y = serie.yData[yLength - 1], lastPoint, yValue, crop;
if (lastPrice && lastPrice.enabled) {
yAxis.crosshair = yAxis.options.crosshair = seriesOptions.lastPrice;
yAxis.cross = serie.lastPrice;
yValue = isArray(y) ? y[3] : y;
yAxis.drawCrosshair(null, ({
x: x,
y: yValue,
plotX: xAxis.toPixels(x, true),
plotY: yAxis.toPixels(yValue, true)
}));
// Save price
if (serie.yAxis.cross) {
serie.lastPrice = serie.yAxis.cross;
serie.lastPrice.y = yValue;
}
}
if (lastVisiblePrice &&
lastVisiblePrice.enabled &&
pLength > 0) {
crop = (points[pLength - 1].x === x) || pointRange === null ? 1 : 2;
yAxis.crosshair = yAxis.options.crosshair = merge({
color: 'transparent'
}, seriesOptions.lastVisiblePrice);
yAxis.cross = serie.lastVisiblePrice;
lastPoint = points[pLength - crop];
if (serie.crossLabel) {
serie.crossLabel.destroy();
// Set to undefined to avoid collision with
// the yAxis crosshair #11480
delete yAxis.crossLabel;
}
// Save price
yAxis.drawCrosshair(null, lastPoint);
if (yAxis.cross) {
serie.lastVisiblePrice = yAxis.cross;
if (typeof lastPoint.y === 'number') {
serie.lastVisiblePrice.y = lastPoint.y;
}
}
serie.crossLabel = yAxis.crossLabel;
}
// Restore crosshair:
yAxis.crosshair = origOptions;
yAxis.cross = origGraphic;
yAxis.crossLabel = origLabel;
}
});
|
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import Chart from './Chart/Chart.js';
import U from './Utilities.js';
var find = U.find, isArray = U.isArray, isObject = U.isObject, merge = U.merge, objectEach = U.objectEach, pick = U.pick, splat = U.splat, uniqueKey = U.uniqueKey;
/**
* A callback function to gain complete control on when the responsive rule
* applies.
*
* @callback Highcharts.ResponsiveCallbackFunction
*
* @param {Highcharts.Chart} this
* Chart context.
*
* @return {boolean}
* Return `true` if it applies.
*/
/**
* Allows setting a set of rules to apply for different screen or chart
* sizes. Each rule specifies additional chart options.
*
* @sample {highstock} stock/demo/responsive/
* Stock chart
* @sample highcharts/responsive/axis/
* Axis
* @sample highcharts/responsive/legend/
* Legend
* @sample highcharts/responsive/classname/
* Class name
*
* @since 5.0.0
* @apioption responsive
*/
/**
* A set of rules for responsive settings. The rules are executed from
* the top down.
*
* @sample {highcharts} highcharts/responsive/axis/
* Axis changes
* @sample {highstock} highcharts/responsive/axis/
* Axis changes
* @sample {highmaps} highcharts/responsive/axis/
* Axis changes
*
* @type {Array<*>}
* @since 5.0.0
* @apioption responsive.rules
*/
/**
* A full set of chart options to apply as overrides to the general
* chart options. The chart options are applied when the given rule
* is active.
*
* A special case is configuration objects that take arrays, for example
* [xAxis](#xAxis), [yAxis](#yAxis) or [series](#series). For these
* collections, an `id` option is used to map the new option set to
* an existing object. If an existing object of the same id is not found,
* the item of the same indexupdated. So for example, setting `chartOptions`
* with two series items without an `id`, will cause the existing chart's
* two series to be updated with respective options.
*
* @sample {highstock} stock/demo/responsive/
* Stock chart
* @sample highcharts/responsive/axis/
* Axis
* @sample highcharts/responsive/legend/
* Legend
* @sample highcharts/responsive/classname/
* Class name
*
* @type {Highcharts.Options}
* @since 5.0.0
* @apioption responsive.rules.chartOptions
*/
/**
* Under which conditions the rule applies.
*
* @since 5.0.0
* @apioption responsive.rules.condition
*/
/**
* A callback function to gain complete control on when the responsive
* rule applies. Return `true` if it applies. This opens for checking
* against other metrics than the chart size, for example the document
* size or other elements.
*
* @type {Highcharts.ResponsiveCallbackFunction}
* @since 5.0.0
* @context Highcharts.Chart
* @apioption responsive.rules.condition.callback
*/
/**
* The responsive rule applies if the chart height is less than this.
*
* @type {number}
* @since 5.0.0
* @apioption responsive.rules.condition.maxHeight
*/
/**
* The responsive rule applies if the chart width is less than this.
*
* @sample highcharts/responsive/axis/
* Max width is 500
*
* @type {number}
* @since 5.0.0
* @apioption responsive.rules.condition.maxWidth
*/
/**
* The responsive rule applies if the chart height is greater than this.
*
* @type {number}
* @default 0
* @since 5.0.0
* @apioption responsive.rules.condition.minHeight
*/
/**
* The responsive rule applies if the chart width is greater than this.
*
* @type {number}
* @default 0
* @since 5.0.0
* @apioption responsive.rules.condition.minWidth
*/
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* Update the chart based on the current chart/document size and options for
* responsiveness.
*
* @private
* @function Highcharts.Chart#setResponsive
* @param {boolean} [redraw=true]
* @param {boolean} [reset=false]
* Reset by un-applying all rules. Chart.update resets all rules before applying
* updated options.
*/
Chart.prototype.setResponsive = function (redraw, reset) {
var options = this.options.responsive, ruleIds = [], currentResponsive = this.currentResponsive, currentRuleIds, undoOptions;
if (!reset && options && options.rules) {
options.rules.forEach(function (rule) {
if (typeof rule._id === 'undefined') {
rule._id = uniqueKey();
}
this.matchResponsiveRule(rule, ruleIds /* , redraw */);
}, this);
}
// Merge matching rules
var mergedOptions = merge.apply(0, ruleIds.map(function (ruleId) {
return find(options.rules, function (rule) {
return rule._id === ruleId;
}).chartOptions;
}));
mergedOptions.isResponsiveOptions = true;
// Stringified key for the rules that currently apply.
ruleIds = (ruleIds.toString() || void 0);
currentRuleIds = currentResponsive && currentResponsive.ruleIds;
// Changes in what rules apply
if (ruleIds !== currentRuleIds) {
// Undo previous rules. Before we apply a new set of rules, we need to
// roll back completely to base options (#6291).
if (currentResponsive) {
this.update(currentResponsive.undoOptions, redraw, true);
}
if (ruleIds) {
// Get undo-options for matching rules
undoOptions = this.currentOptions(mergedOptions);
undoOptions.isResponsiveOptions = true;
this.currentResponsive = {
ruleIds: ruleIds,
mergedOptions: mergedOptions,
undoOptions: undoOptions
};
this.update(mergedOptions, redraw, true);
}
else {
this.currentResponsive = void 0;
}
}
};
/**
* Handle a single responsiveness rule.
*
* @private
* @function Highcharts.Chart#matchResponsiveRule
* @param {Highcharts.ResponsiveRulesOptions} rule
* @param {Array<string>} matches
*/
Chart.prototype.matchResponsiveRule = function (rule, matches) {
var condition = rule.condition, fn = condition.callback || function () {
return (this.chartWidth <= pick(condition.maxWidth, Number.MAX_VALUE) &&
this.chartHeight <=
pick(condition.maxHeight, Number.MAX_VALUE) &&
this.chartWidth >= pick(condition.minWidth, 0) &&
this.chartHeight >= pick(condition.minHeight, 0));
};
if (fn.call(this)) {
matches.push(rule._id);
}
};
/**
* Get the current values for a given set of options. Used before we update
* the chart with a new responsiveness rule.
*
* @todo Restore axis options (by id?). The matching of items in collections
* bears resemblance to the oneToOne matching in Chart.update. Probably we can
* refactor out that matching and reuse it in both functions.
*
* @private
* @function Highcharts.Chart#currentOptions
* @param {Highcharts.Options} options
* @return {Highcharts.Options}
*/
Chart.prototype.currentOptions = function (options) {
var chart = this, ret = {};
/**
* Recurse over a set of options and its current values,
* and store the current values in the ret object.
*/
function getCurrent(options, curr, ret, depth) {
var i;
objectEach(options, function (val, key) {
if (!depth &&
chart.collectionsWithUpdate.indexOf(key) > -1) {
val = splat(val);
ret[key] = [];
// Iterate over collections like series, xAxis or yAxis and map
// the items by index.
for (i = 0; i < Math.max(val.length, curr[key].length); i++) {
// Item exists in current data (#6347)
if (curr[key][i]) {
// If the item is missing from the new data, we need to
// save the whole config structure. Like when
// responsively updating from a dual axis layout to a
// single axis and back (#13544).
if (val[i] === void 0) {
ret[key][i] = curr[key][i];
// Otherwise, proceed
}
else {
ret[key][i] = {};
getCurrent(val[i], curr[key][i], ret[key][i], depth + 1);
}
}
}
}
else if (isObject(val)) {
ret[key] = isArray(val) ? [] : {};
getCurrent(val, curr[key] || {}, ret[key], depth + 1);
}
else if (typeof curr[key] === 'undefined') { // #10286
ret[key] = null;
}
else {
ret[key] = curr[key];
}
});
}
getCurrent(options, this.options, ret, 0);
return ret;
};
|
;(function(win){
var store = {},
doc = win.document,
localStorageName = 'localStorage',
namespace = '__storejs__',
storage
store.disabled = false
store.set = function(key, value) {}
store.get = function(key) {}
store.remove = function(key) {}
store.clear = function() {}
store.transact = function(key, defaultVal, transactionFn) {
var val = store.get(key)
if (transactionFn == null) {
transactionFn = defaultVal
defaultVal = null
}
if (typeof val == 'undefined') { val = defaultVal || {} }
transactionFn(val)
store.set(key, val)
}
store.getAll = function() {}
store.serialize = function(value) {
return JSON.stringify(value)
}
store.deserialize = function(value) {
if (typeof value != 'string') { return undefined }
try { return JSON.parse(value) }
catch(e) { return value || undefined }
}
// Functions to encapsulate questionable FireFox 3.6.13 behavior
// when about.config::dom.storage.enabled === false
// See https://github.com/marcuswestin/store.js/issues#issue/13
function isLocalStorageNameSupported() {
try { return (localStorageName in win && win[localStorageName]) }
catch(err) { return false }
}
if (isLocalStorageNameSupported()) {
storage = win[localStorageName]
store.set = function(key, val) {
if (val === undefined) { return store.remove(key) }
storage.setItem(key, store.serialize(val))
return val
}
store.get = function(key) { return store.deserialize(storage.getItem(key)) }
store.remove = function(key) { storage.removeItem(key) }
store.clear = function() { storage.clear() }
store.getAll = function() {
var ret = {}
for (var i=0; i<storage.length; ++i) {
var key = storage.key(i)
ret[key] = store.get(key)
}
return ret
}
} else if (doc.documentElement.addBehavior) {
var storageOwner,
storageContainer
// Since #userData storage applies only to specific paths, we need to
// somehow link our data to a specific path. We choose /favicon.ico
// as a pretty safe option, since all browsers already make a request to
// this URL anyway and being a 404 will not hurt us here. We wrap an
// iframe pointing to the favicon in an ActiveXObject(htmlfile) object
// (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx)
// since the iframe access rules appear to allow direct access and
// manipulation of the document element, even for a 404 page. This
// document can be used instead of the current document (which would
// have been limited to the current path) to perform #userData storage.
try {
storageContainer = new ActiveXObject('htmlfile')
storageContainer.open()
storageContainer.write('<s' + 'cript>document.w=window</s' + 'cript><iframe src="/favicon.ico"></iframe>')
storageContainer.close()
storageOwner = storageContainer.w.frames[0].document
storage = storageOwner.createElement('div')
} catch(e) {
// somehow ActiveXObject instantiation failed (perhaps some special
// security settings or otherwse), fall back to per-path storage
storage = doc.createElement('div')
storageOwner = doc.body
}
function withIEStorage(storeFunction) {
return function() {
var args = Array.prototype.slice.call(arguments, 0)
args.unshift(storage)
// See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx
// and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx
storageOwner.appendChild(storage)
storage.addBehavior('#default#userData')
storage.load(localStorageName)
var result = storeFunction.apply(store, args)
storageOwner.removeChild(storage)
return result
}
}
// In IE7, keys may not contain special chars. See all of https://github.com/marcuswestin/store.js/issues/40
var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g")
function ieKeyFix(key) {
return key.replace(forbiddenCharsRegex, '___')
}
store.set = withIEStorage(function(storage, key, val) {
key = ieKeyFix(key)
if (val === undefined) { return store.remove(key) }
storage.setAttribute(key, store.serialize(val))
storage.save(localStorageName)
return val
})
store.get = withIEStorage(function(storage, key) {
key = ieKeyFix(key)
return store.deserialize(storage.getAttribute(key))
})
store.remove = withIEStorage(function(storage, key) {
key = ieKeyFix(key)
storage.removeAttribute(key)
storage.save(localStorageName)
})
store.clear = withIEStorage(function(storage) {
var attributes = storage.XMLDocument.documentElement.attributes
storage.load(localStorageName)
for (var i=0, attr; attr=attributes[i]; i++) {
storage.removeAttribute(attr.name)
}
storage.save(localStorageName)
})
store.getAll = withIEStorage(function(storage) {
var attributes = storage.XMLDocument.documentElement.attributes
var ret = {}
for (var i=0, attr; attr=attributes[i]; ++i) {
var key = ieKeyFix(attr.name)
ret[attr.name] = store.deserialize(storage.getAttribute(key))
}
return ret
})
}
try {
store.set(namespace, namespace)
if (store.get(namespace) != namespace) { store.disabled = true }
store.remove(namespace)
} catch(e) {
store.disabled = true
}
store.enabled = !store.disabled
if (typeof module != 'undefined' && module.exports) { module.exports = store }
else if (typeof define === 'function' && define.amd) { define(store) }
else { win.store = store }
})(this.window || global);
|
var BookListItem = React.createClass({
handleClick: function(event) {
console.log('an item is clicked', this.props.book)
this.props.onListItemClicked(this.props.book.id)
},
render: function() {
var book = this.props.book
return (
<div className="book row" >
<div className="bookTitle six columns" onClick={this.handleClick}>
<b> {book.title} </b>
</div>
</div>
)
}
}) |
/*
* Pass a function to whenReady() and it will be invoked (as a method of the
* document) when the document is parsed and ready for manipulation. Registered
* functions are triggered by the first DOMContentLoaded, readystatechange, or
* load event that occurs. Once the document is ready and all functions have
* been invoked, any functions passed to whenReady() will be invoked
* immediately.
*/
var whenReady = (function() { // This function returns the whenReady() function
var funcs = []; // The functions to run when we get an event
var ready = false; // Switches to true when the handler is triggered
// The event handler invoked when the document becomes ready
function handler(e) {
// If we've already run once, just return
if (ready) return;
// If this was a readystatechange event where the state changed to
// something other than "complete", then we're not ready yet
if (e.type === "readystatechange" && document.readyState !== "complete")
return;
// Run all registered functions.
// Note that we look up funcs.length each time, in case calling
// one of these functions causes more functions to be registered.
for(var i = 0; i < funcs.length; i++)
funcs[i].call(document);
// Now set the ready flag to true and forget the functions
ready = true;
funcs = null;
}
// Register the handler for any event we might receive
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", handler, false);
document.addEventListener("readystatechange", handler, false);
window.addEventListener("load", handler, false);
}
else if (document.attachEvent) {
document.attachEvent("onreadystatechange", handler);
window.attachEvent("onload", handler);
}
// Return the whenReady function
return function whenReady(f) {
if (ready) f.call(document); // If already ready, just run it
else funcs.push(f); // Otherwise, queue it for later.
}
}());
|
module.exports = require('./NativeSafeComponent');
|
/**
* @file 支持的命令列表
* @author mengke01(kekee000@gmail.com)
*/
define(
function (require) {
var lang = require('common/lang');
var support = {};
lang.extend(support, require('./shape'));
lang.extend(support, require('./transform'));
lang.extend(support, require('./align'));
lang.extend(support, require('./join'));
lang.extend(support, require('./referenceline'));
lang.extend(support, require('./editor'));
return support;
}
);
|
Meteor.methods({
doesArticleExist: function(slug) {
return Article.first({
slug: slug
})
},
isItArchy: function() {
if (Meteor.user()) {
if (Meteor.user().admin == 1) {
return true;
}
}
return false;
}
});
Article._collection.allow({
insert: function() {
return Meteor.call('isItArchy')
},
update: function() {
return Meteor.call('isItArchy')
},
remove: function() {
return Meteor.call('isItArchy')
}
});
Changelog.allow({
insert: function() {
return Meteor.call('isItArchy')
},
update: function() {
return Meteor.call('isItArchy')
},
remove: function() {
return Meteor.call('isItArchy')
}
});
|
'use strict';
module.exports = jsonpRequest;
var errors = require('../errors');
var JSONPCounter = 0;
function jsonpRequest(url, opts, cb) {
if (opts.method !== 'GET') {
cb(new Error('Method ' + opts.method + ' ' + url + ' is not supported by JSONP.'));
return;
}
opts.debug('JSONP: start');
var cbCalled = false;
var timedOut = false;
JSONPCounter += 1;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
var cbName = 'algoliaJSONP_' + JSONPCounter;
var done = false;
window[cbName] = function(data) {
removeGlobals();
if (timedOut) {
opts.debug('JSONP: Late answer, ignoring');
return;
}
cbCalled = true;
clean();
cb(null, {
body: data/* ,
// We do not send the statusCode, there's no statusCode in JSONP, it will be
// computed using data.status && data.message like with XDR
statusCode*/
});
};
// add callback by hand
url += '&callback=' + cbName;
// add body params manually
if (opts.jsonBody && opts.jsonBody.params) {
url += '&' + opts.jsonBody.params;
}
var ontimeout = setTimeout(timeout, opts.timeouts.complete);
// script onreadystatechange needed only for
// <= IE8
// https://github.com/angular/angular.js/issues/4523
script.onreadystatechange = readystatechange;
script.onload = success;
script.onerror = error;
script.async = true;
script.defer = true;
script.src = url;
head.appendChild(script);
function success() {
opts.debug('JSONP: success');
if (done || timedOut) {
return;
}
done = true;
// script loaded but did not call the fn => script loading error
if (!cbCalled) {
opts.debug('JSONP: Fail. Script loaded but did not call the callback');
clean();
cb(new errors.JSONPScriptFail());
}
}
function readystatechange() {
if (this.readyState === 'loaded' || this.readyState === 'complete') {
success();
}
}
function clean() {
clearTimeout(ontimeout);
script.onload = null;
script.onreadystatechange = null;
script.onerror = null;
head.removeChild(script);
}
function removeGlobals() {
try {
delete window[cbName];
delete window[cbName + '_loaded'];
} catch (e) {
window[cbName] = window[cbName + '_loaded'] = undefined;
}
}
function timeout() {
opts.debug('JSONP: Script timeout');
timedOut = true;
clean();
cb(new errors.RequestTimeout());
}
function error() {
opts.debug('JSONP: Script error');
if (done || timedOut) {
return;
}
clean();
cb(new errors.JSONPScriptError());
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:584e77eaff3bcc18c7dbe5c416bbd5f9ac05b2ae37928f292cdf7994cda86a4d
size 1437
|
ko.bindingHandlers['text'] = {
'update': function (element, valueAccessor) {
ko.utils.setTextContent(element, valueAccessor());
}
};
ko.virtualElements.allowedBindings['text'] = true;
|
describe('<md-toolbar>', function() {
var pageScope, element, controller;
var $rootScope, $timeout;
beforeEach(function() {
module('material.components.toolbar', function($controllerProvider) {
$controllerProvider.register('MockController', function() {});
});
});
beforeEach(inject(function(_$rootScope_, _$timeout_) {
$rootScope = _$rootScope_;
$timeout = _$timeout_;
}));
it('with scrollShrink, it should shrink scrollbar when going to bottom', inject(function($compile, $rootScope, $mdConstant, mdToolbarDirective, $$rAF) {
var parent = angular.element('<div>');
var toolbar = angular.element('<md-toolbar>');
var contentEl = angular.element('<div>');
// Make content and toolbar siblings
parent.append(toolbar).append(contentEl);
//Prop will be used for offsetHeight, give a fake offsetHeight
spyOn(toolbar, 'prop').and.callFake(function() {
return 100;
});
// Fake the css function so we can read css values properly,
// no matter which browser the tests are being run on.
// (IE, firefox, chrome all give different results when reading element.style)
var toolbarCss = {};
spyOn(toolbar, 'css').and.callFake(function(k, v) {
toolbarCss[k] = v;
});
var contentCss = {};
spyOn(contentEl, 'css').and.callFake(function(properties, value) {
if (angular.isObject(properties)) {
for (k in properties) {
if (properties.hasOwnProperty(k)) {
contentCss[k] = properties[k];
}
}
} else {
contentCss[properties] = value;
}
});
// Manually link so we can give our own elements with spies on them
mdToolbarDirective[0].link($rootScope, toolbar, {
mdScrollShrink: true,
mdShrinkSpeedFactor: 1,
$observe: function() {}
});
$rootScope.$apply();
$rootScope.$broadcast('$mdContentLoaded', contentEl);
$$rAF.flush();
//Expect everything to be in its proper initial state.
expect(toolbarCss[$mdConstant.CSS.TRANSFORM]).toEqual('translate3d(0,0px,0)');
expect(contentCss['margin-top']).toEqual('-100px');
expect(contentCss['margin-bottom']).toEqual('-100px');
expect(contentCss[$mdConstant.CSS.TRANSFORM]).toEqual('translate3d(0,100px,0)');
// Fake scroll to the bottom
contentEl.triggerHandler({
type: 'scroll',
target: {scrollTop: 500}
});
$$rAF.flush();
expect(toolbarCss[$mdConstant.CSS.TRANSFORM]).toEqual('translate3d(0,-100px,0)');
expect(contentCss[$mdConstant.CSS.TRANSFORM]).toEqual('translate3d(0,0px,0)');
// Fake scroll back to the top
contentEl.triggerHandler({
type: 'scroll',
target: {scrollTop: 0}
});
$$rAF.flush();
expect(toolbarCss[$mdConstant.CSS.TRANSFORM]).toEqual('translate3d(0,0px,0)');
expect(contentCss[$mdConstant.CSS.TRANSFORM]).toEqual('translate3d(0,100px,0)');
}));
it('works without ng-if', inject(function() {
build(
'<div>' +
' <md-toolbar md-scroll-shrink="true"></md-toolbar>' +
' <md-content></md-content>' +
'</div>'
);
expect(element.find('md-content').attr('scroll-shrink')).toEqual('true');
}));
it('works with ng-if', inject(function() {
build(
'<div>' +
' <md-toolbar md-scroll-shrink="true" ng-if="shouldShowToolbar"></md-toolbar>' +
' <md-content></md-content>' +
'</div>'
);
// It starts out undefined
expect(element.find('md-content').attr('scroll-shrink')).toEqual(undefined);
// Change the ng-if to add the toolbar which then injects a scrollShrink
// on the mdContent
pageScope.$apply('shouldShowToolbar = true');
expect(element.find('md-content').attr('scroll-shrink')).toEqual('true');
// Change the ng-if to remove the toolbar
pageScope.$apply('shouldShowToolbar = false');
expect(element.find('md-toolbar').length).toBe(0);
}));
it('works with ng-show', inject(function($$rAF, $timeout) {
var template =
'<div layout="column" style="height: 600px;">' +
' <md-toolbar md-scroll-shrink="true" ng-show="shouldShowToolbar">test</md-toolbar>' +
' <md-content flex><div style="height: 5000px;"></div></md-content>' +
'</div>';
// Build/append the element
build(template);
document.body.appendChild(element[0]);
// Flushing to get the actual height of toolbar
$$rAF.flush();
//
// Initial tests
//
var toolbarStyles = getComputedStyle(element.find('md-toolbar')[0]);
var contentStyles = getComputedStyle(element.find('md-content')[0]);
// Should start out hidden because we have not set shouldShowToolbar
expect(toolbarStyles.display).toBeTruthy();
expect(toolbarStyles.display).toEqual('none');
// Expect the content to have a zero margin top
expect(contentStyles.marginTop).toBeTruthy();
expect(contentStyles.marginTop).toEqual('0px');
//
// After showing toolbar tests
//
// Show the toolbar and ensure it is visible
pageScope.$apply('shouldShowToolbar = true');
pageScope.$digest();
$timeout.flush();
toolbarStyles = getComputedStyle(element.find('md-toolbar')[0]);
contentStyles = getComputedStyle(element.find('md-content')[0]);
// Expect the toolbar to be visible
expect(toolbarStyles.display).toBeTruthy();
expect(toolbarStyles.display).not.toEqual('none');
// Expect the content to have a non-zero margin top (because updateToolbarHeight() was called)
expect(contentStyles.marginTop).toBeTruthy();
expect(contentStyles.marginTop).not.toEqual('0px');
// Remove the element
document.body.removeChild(element[0]);
}));
it('works with ng-hide', inject(function($$rAF, $timeout) {
var template =
'<div layout="column" style="height: 600px;">' +
' <md-toolbar md-scroll-shrink="true" ng-hide="shouldNotShowToolbar">test</md-toolbar>' +
' <md-content flex><div style="height: 5000px;"></div></md-content>' +
'</div>';
// Build/append the element
build(template);
document.body.appendChild(element[0]);
// Flushing to get the actual height of toolbar
$$rAF.flush();
//
// Initial tests
//
var toolbarStyles = getComputedStyle(element.find('md-toolbar')[0]);
var contentStyles = getComputedStyle(element.find('md-content')[0]);
// Should start out visible because we have not set shouldNotShowToolbar
expect(toolbarStyles.display).toBeTruthy();
expect(toolbarStyles.display).not.toEqual('none');
// Expect the content to have a non-zero margin top
expect(contentStyles.marginTop).toBeTruthy();
expect(contentStyles.marginTop).not.toEqual('0px');
//
// After showing toolbar tests
//
// Show the toolbar and ensure it is hidden
pageScope.$apply('shouldNotShowToolbar = true');
pageScope.$digest();
$timeout.flush();
toolbarStyles = getComputedStyle(element.find('md-toolbar')[0]);
contentStyles = getComputedStyle(element.find('md-content')[0]);
// Expect the toolbar to be hidden
expect(toolbarStyles.display).toBeTruthy();
expect(toolbarStyles.display).toEqual('none');
// Expect the content to have a zero margin top (because updateToolbarHeight() was called)
expect(contentStyles.marginTop).toBeTruthy();
expect(contentStyles.marginTop).toEqual('0px');
// Remove the element
document.body.removeChild(element[0]);
}));
// The toolbar is like a container component, so we want to make sure it works with ng-controller
it('works with ng-controller', inject(function($exceptionHandler) {
build(
'<div>' +
' <md-toolbar md-scroll-shrink ng-controller="MockController"></md-toolbar>' +
' <md-content></md-content>' +
'</div>'
);
// Expect no errors
expect($exceptionHandler.errors).toEqual([]);
}));
it('should have `._md` class indicator', inject(function() {
build(
'<div>' +
' <md-toolbar></md-toolbar>' +
' <md-content></md-content>' +
'</div>'
);
expect(element.find('md-toolbar').hasClass('_md')).toBe(true);
}));
it('disables scroll shrink when the attribute is not provided', inject(function() {
build(
'<div>' +
' <md-toolbar></md-toolbar>' +
' <md-content></md-content>' +
'</div>'
);
expect(element.find('md-content').attr('scroll-shrink')).toEqual(undefined);
}));
it('enables scroll shrink when the attribute has no value', function() {
build(
'<div>' +
' <md-toolbar md-scroll-shrink></md-toolbar>' +
' <md-content></md-content>' +
'</div>'
);
expect(element.find('md-content').attr('scroll-shrink')).toEqual('true');
});
it('disables scroll shrink if the expression evaluates to false', function() {
var pageScope = $rootScope.$new();
// Set the value to false
pageScope.$apply('someValue = false');
// Build the element
build(
// Pass our template
'<div>' +
' <md-toolbar md-scroll-shrink="someValue"></md-toolbar>' +
' <md-content></md-content>' +
'</div>',
// Pass our custom pageScope
pageScope
);
// Check that scroll shrink is disabled
expect(element.find('md-content').attr('scroll-shrink')).toEqual('false');
});
function build(template, scope) {
inject(function($compile) {
if (scope) {
pageScope = scope
} else {
pageScope = $rootScope.$new();
}
element = $compile(template)(pageScope);
controller = element.controller('mdToolbar');
pageScope.$apply();
$timeout.flush();
});
}
});
|
run_spec(__dirname, ["html"]);
run_spec(__dirname, ["html"], { printWidth: 1 });
run_spec(__dirname, ["html"], { printWidth: Number.POSITIVE_INFINITY });
run_spec(__dirname, ["html"], { htmlWhitespaceSensitivity: "strict" });
run_spec(__dirname, ["html"], { htmlWhitespaceSensitivity: "ignore" });
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { APP_BASE_HREF, HashLocationStrategy, LOCATION_INITIALIZED, Location, LocationStrategy, PathLocationStrategy, PlatformLocation } from '@angular/common';
import { ANALYZE_FOR_ENTRY_COMPONENTS, APP_BOOTSTRAP_LISTENER, APP_INITIALIZER, ApplicationRef, Compiler, Inject, Injectable, Injector, NgModule, NgModuleFactoryLoader, NgProbeToken, OpaqueToken, Optional, SkipSelf, SystemJsNgModuleLoader } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { of } from 'rxjs/observable/of';
import { RouterLink, RouterLinkWithHref } from './directives/router_link';
import { RouterLinkActive } from './directives/router_link_active';
import { RouterOutlet } from './directives/router_outlet';
import { getDOM } from './private_import_platform-browser';
import { RouteReuseStrategy } from './route_reuse_strategy';
import { Router } from './router';
import { ROUTES } from './router_config_loader';
import { RouterOutletMap } from './router_outlet_map';
import { NoPreloading, PreloadAllModules, PreloadingStrategy, RouterPreloader } from './router_preloader';
import { ActivatedRoute } from './router_state';
import { UrlHandlingStrategy } from './url_handling_strategy';
import { DefaultUrlSerializer, UrlSerializer } from './url_tree';
import { flatten } from './utils/collection';
/**
* @whatItDoes Contains a list of directives
* @stable
*/
var /** @type {?} */ ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, RouterLinkActive];
/**
* @whatItDoes Is used in DI to configure the router.
* @stable
*/
export var /** @type {?} */ ROUTER_CONFIGURATION = new OpaqueToken('ROUTER_CONFIGURATION');
/**
* @docsNotRequired
*/
export var /** @type {?} */ ROUTER_FORROOT_GUARD = new OpaqueToken('ROUTER_FORROOT_GUARD');
export var /** @type {?} */ ROUTER_PROVIDERS = [
Location,
{ provide: UrlSerializer, useClass: DefaultUrlSerializer },
{
provide: Router,
useFactory: setupRouter,
deps: [
ApplicationRef, UrlSerializer, RouterOutletMap, Location, Injector, NgModuleFactoryLoader,
Compiler, ROUTES, ROUTER_CONFIGURATION, [UrlHandlingStrategy, new Optional()],
[RouteReuseStrategy, new Optional()]
]
},
RouterOutletMap,
{ provide: ActivatedRoute, useFactory: rootRoute, deps: [Router] },
{ provide: NgModuleFactoryLoader, useClass: SystemJsNgModuleLoader },
RouterPreloader,
NoPreloading,
PreloadAllModules,
{ provide: ROUTER_CONFIGURATION, useValue: { enableTracing: false } },
];
/**
* @return {?}
*/
export function routerNgProbeToken() {
return new NgProbeToken('Router', Router);
}
/**
* \@whatItDoes Adds router directives and providers.
*
* \@howToUse
*
* RouterModule can be imported multiple times: once per lazily-loaded bundle.
* Since the router deals with a global shared resource--location, we cannot have
* more than one router service active.
*
* That is why there are two ways to create the module: `RouterModule.forRoot` and
* `RouterModule.forChild`.
*
* * `forRoot` creates a module that contains all the directives, the given routes, and the router
* service itself.
* * `forChild` creates a module that contains all the directives and the given routes, but does not
* include the router service.
*
* When registered at the root, the module should be used as follows
*
* ```
* \@NgModule({
* imports: [RouterModule.forRoot(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* For submodules and lazy loaded submodules the module should be used as follows:
*
* ```
* \@NgModule({
* imports: [RouterModule.forChild(ROUTES)]
* })
* class MyNgModule {}
* ```
*
* \@description
*
* Managing state transitions is one of the hardest parts of building applications. This is
* especially true on the web, where you also need to ensure that the state is reflected in the URL.
* In addition, we often want to split applications into multiple bundles and load them on demand.
* Doing this transparently is not trivial.
*
* The Angular router solves these problems. Using the router, you can declaratively specify
* application states, manage state transitions while taking care of the URL, and load bundles on
* demand.
*
* [Read this developer guide](https://angular.io/docs/ts/latest/guide/router.html) to get an
* overview of how the router should be used.
*
* \@stable
*/
export var RouterModule = (function () {
/**
* @param {?} guard
*/
function RouterModule(guard) {
}
/**
* Creates a module with all the router providers and directives. It also optionally sets up an
* application listener to perform an initial navigation.
*
* Options:
* * `enableTracing` makes the router log all its internal events to the console.
* * `useHash` enables the location strategy that uses the URL fragment instead of the history
* API.
* * `initialNavigation` disables the initial navigation.
* * `errorHandler` provides a custom error handler.
* @param {?} routes
* @param {?=} config
* @return {?}
*/
RouterModule.forRoot = function (routes, config) {
return {
ngModule: RouterModule,
providers: [
ROUTER_PROVIDERS,
provideRoutes(routes),
{
provide: ROUTER_FORROOT_GUARD,
useFactory: provideForRootGuard,
deps: [[Router, new Optional(), new SkipSelf()]]
},
{ provide: ROUTER_CONFIGURATION, useValue: config ? config : {} },
{
provide: LocationStrategy,
useFactory: provideLocationStrategy,
deps: [
PlatformLocation, [new Inject(APP_BASE_HREF), new Optional()], ROUTER_CONFIGURATION
]
},
{
provide: PreloadingStrategy,
useExisting: config && config.preloadingStrategy ? config.preloadingStrategy :
NoPreloading
},
{ provide: NgProbeToken, multi: true, useFactory: routerNgProbeToken },
provideRouterInitializer(),
],
};
};
/**
* Creates a module with all the router directives and a provider registering routes.
* @param {?} routes
* @return {?}
*/
RouterModule.forChild = function (routes) {
return { ngModule: RouterModule, providers: [provideRoutes(routes)] };
};
RouterModule.decorators = [
{ type: NgModule, args: [{ declarations: ROUTER_DIRECTIVES, exports: ROUTER_DIRECTIVES },] },
];
/** @nocollapse */
RouterModule.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: Optional }, { type: Inject, args: [ROUTER_FORROOT_GUARD,] },] },
]; };
return RouterModule;
}());
function RouterModule_tsickle_Closure_declarations() {
/** @type {?} */
RouterModule.decorators;
/**
* @nocollapse
* @type {?}
*/
RouterModule.ctorParameters;
}
/**
* @param {?} platformLocationStrategy
* @param {?} baseHref
* @param {?=} options
* @return {?}
*/
export function provideLocationStrategy(platformLocationStrategy, baseHref, options) {
if (options === void 0) { options = {}; }
return options.useHash ? new HashLocationStrategy(platformLocationStrategy, baseHref) :
new PathLocationStrategy(platformLocationStrategy, baseHref);
}
/**
* @param {?} router
* @return {?}
*/
export function provideForRootGuard(router) {
if (router) {
throw new Error("RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.");
}
return 'guarded';
}
/**
* \@whatItDoes Registers routes.
*
* \@howToUse
*
* ```
* \@NgModule({
* imports: [RouterModule.forChild(ROUTES)],
* providers: [provideRoutes(EXTRA_ROUTES)]
* })
* class MyNgModule {}
* ```
*
* \@stable
* @param {?} routes
* @return {?}
*/
export function provideRoutes(routes) {
return [
{ provide: ANALYZE_FOR_ENTRY_COMPONENTS, multi: true, useValue: routes },
{ provide: ROUTES, multi: true, useValue: routes },
];
}
/**
* @param {?} ref
* @param {?} urlSerializer
* @param {?} outletMap
* @param {?} location
* @param {?} injector
* @param {?} loader
* @param {?} compiler
* @param {?} config
* @param {?=} opts
* @param {?=} urlHandlingStrategy
* @param {?=} routeReuseStrategy
* @return {?}
*/
export function setupRouter(ref, urlSerializer, outletMap, location, injector, loader, compiler, config, opts, urlHandlingStrategy, routeReuseStrategy) {
if (opts === void 0) { opts = {}; }
var /** @type {?} */ router = new Router(null, urlSerializer, outletMap, location, injector, loader, compiler, flatten(config));
if (urlHandlingStrategy) {
router.urlHandlingStrategy = urlHandlingStrategy;
}
if (routeReuseStrategy) {
router.routeReuseStrategy = routeReuseStrategy;
}
if (opts.errorHandler) {
router.errorHandler = opts.errorHandler;
}
if (opts.enableTracing) {
var /** @type {?} */ dom_1 = getDOM();
router.events.subscribe(function (e) {
dom_1.logGroup("Router Event: " + ((e.constructor)).name);
dom_1.log(e.toString());
dom_1.log(e);
dom_1.logGroupEnd();
});
}
return router;
}
/**
* @param {?} router
* @return {?}
*/
export function rootRoute(router) {
return router.routerState.root;
}
/**
* To initialize the router properly we need to do in two steps:
*
* We need to start the navigation in a APP_INITIALIZER to block the bootstrap if
* a resolver or a guards executes asynchronously. Second, we need to actually run
* activation in a BOOTSTRAP_LISTENER. We utilize the afterPreactivation
* hook provided by the router to do that.
*
* The router navigation starts, reaches the point when preactivation is done, and then
* pauses. It waits for the hook to be resolved. We then resolve it only in a bootstrap listener.
*/
export var RouterInitializer = (function () {
/**
* @param {?} injector
*/
function RouterInitializer(injector) {
this.injector = injector;
this.resultOfPreactivationDone = new Subject();
}
/**
* @return {?}
*/
RouterInitializer.prototype.appInitializer = function () {
var _this = this;
var /** @type {?} */ p = this.injector.get(LOCATION_INITIALIZED, Promise.resolve(null));
return p.then(function () {
var /** @type {?} */ resolve = null;
var /** @type {?} */ res = new Promise(function (r) { return resolve = r; });
var /** @type {?} */ router = _this.injector.get(Router);
var /** @type {?} */ opts = _this.injector.get(ROUTER_CONFIGURATION);
if (opts.initialNavigation === false) {
router.setUpLocationChangeListener();
}
else {
router.hooks.afterPreactivation = function () {
// only the initial navigation should be delayed
if (!_this.initNavigation) {
_this.initNavigation = true;
resolve(true);
return _this.resultOfPreactivationDone;
}
else {
return of(null);
}
};
router.initialNavigation();
}
return res;
});
};
/**
* @param {?} bootstrappedComponentRef
* @return {?}
*/
RouterInitializer.prototype.bootstrapListener = function (bootstrappedComponentRef) {
var /** @type {?} */ ref = this.injector.get(ApplicationRef);
if (bootstrappedComponentRef !== ref.components[0]) {
return;
}
var /** @type {?} */ preloader = this.injector.get(RouterPreloader);
preloader.setUpPreloading();
var /** @type {?} */ router = this.injector.get(Router);
router.resetRootComponentType(ref.componentTypes[0]);
this.resultOfPreactivationDone.next(null);
this.resultOfPreactivationDone.complete();
};
RouterInitializer.decorators = [
{ type: Injectable },
];
/** @nocollapse */
RouterInitializer.ctorParameters = function () { return [
{ type: Injector, },
]; };
return RouterInitializer;
}());
function RouterInitializer_tsickle_Closure_declarations() {
/** @type {?} */
RouterInitializer.decorators;
/**
* @nocollapse
* @type {?}
*/
RouterInitializer.ctorParameters;
/** @type {?} */
RouterInitializer.prototype.initNavigation;
/** @type {?} */
RouterInitializer.prototype.resultOfPreactivationDone;
/** @type {?} */
RouterInitializer.prototype.injector;
}
/**
* @param {?} r
* @return {?}
*/
export function getAppInitializer(r) {
return r.appInitializer.bind(r);
}
/**
* @param {?} r
* @return {?}
*/
export function getBootstrapListener(r) {
return r.bootstrapListener.bind(r);
}
/**
* A token for the router initializer that will be called after the app is bootstrapped.
*
* @experimental
*/
export var /** @type {?} */ ROUTER_INITIALIZER = new OpaqueToken('Router Initializer');
/**
* @return {?}
*/
export function provideRouterInitializer() {
return [
RouterInitializer,
{
provide: APP_INITIALIZER,
multi: true,
useFactory: getAppInitializer,
deps: [RouterInitializer]
},
{ provide: ROUTER_INITIALIZER, useFactory: getBootstrapListener, deps: [RouterInitializer] },
{ provide: APP_BOOTSTRAP_LISTENER, multi: true, useExisting: ROUTER_INITIALIZER },
];
}
//# sourceMappingURL=router_module.js.map |
'use strict';
var bodyParser = require('body-parser');
var config = require('./config');
var errorhandler = require('errorhandler');
var express = require('express');
var historyApiFallback = require('connect-history-api-fallback');
var log4js = require('log4js');
var methodOverride = require('method-override');
var morgan = require('morgan');
var serveStatic = require('serve-static');
var app = module.exports = express();
var serveDirectory = 'client';
// all environments
app.set('port', config.application.port);
// Logs requests to the console
app.use(morgan('combined'));
// Parses form data and makes this form data available through the request
// object: req.body
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// This middleware allows simulation of DELETE and other HTTP request types.
app.use(methodOverride());
// we deactivate all caches. Really stupid idea in general, but hey, this is
// a workshop and it needs to be simple :-)
app.use(function cacheDeactivation (req, res, next) {
res.header('Cache-Control', 'no-cache');
next();
});
// provide a fallback for the history API, i.e. change the requested URL
var fallbackLogger = log4js.getLogger('historyApiFallback');
historyApiFallback.setLogger(fallbackLogger.trace.bind(fallbackLogger));
app.use(historyApiFallback);
// all requests, that are not handled by static or historyApiFallback
// are handled by the following routing mechanism.
var routes = require('./routes')();
app.get('/movies', routes.movies.getMovies);
app.post('/movies', routes.movies.addMovie);
app.get('/movies/:id', routes.movies.getMovie);
app.put('/movies/:id', routes.movies.updateMovie);
// delete is a reserved word
app['delete']('/movies/:id', routes.movies.deleteMovie);
// Serve static files
app.use(serveStatic(serveDirectory));
// development only => extra error handling
if (process.env.NODE_ENV === 'development') {
console.log('app is in dev mode');
app.use(errorhandler());
}
|
/**
* @file Contains all dynamic functionality needed on post and term pages.
*
* @output wp-admin/js/post.js
*/
/* global ajaxurl, wpAjax, postboxes, pagenow, tinymce, alert, deleteUserSetting, ClipboardJS */
/* global theList:true, theExtraList:true, getUserSetting, setUserSetting, commentReply, commentsBox */
/* global WPSetThumbnailHTML, wptitlehint */
// Backward compatibility: prevent fatal errors.
window.makeSlugeditClickable = window.editPermalink = function(){};
// Make sure the wp object exists.
window.wp = window.wp || {};
( function( $ ) {
var titleHasFocus = false,
__ = wp.i18n.__;
/**
* Control loading of comments on the post and term edit pages.
*
* @type {{st: number, get: commentsBox.get, load: commentsBox.load}}
*
* @namespace commentsBox
*/
window.commentsBox = {
// Comment offset to use when fetching new comments.
st : 0,
/**
* Fetch comments using Ajax and display them in the box.
*
* @memberof commentsBox
*
* @param {number} total Total number of comments for this post.
* @param {number} num Optional. Number of comments to fetch, defaults to 20.
* @return {boolean} Always returns false.
*/
get : function(total, num) {
var st = this.st, data;
if ( ! num )
num = 20;
this.st += num;
this.total = total;
$( '#commentsdiv .spinner' ).addClass( 'is-active' );
data = {
'action' : 'get-comments',
'mode' : 'single',
'_ajax_nonce' : $('#add_comment_nonce').val(),
'p' : $('#post_ID').val(),
'start' : st,
'number' : num
};
$.post(
ajaxurl,
data,
function(r) {
r = wpAjax.parseAjaxResponse(r);
$('#commentsdiv .widefat').show();
$( '#commentsdiv .spinner' ).removeClass( 'is-active' );
if ( 'object' == typeof r && r.responses[0] ) {
$('#the-comment-list').append( r.responses[0].data );
theList = theExtraList = null;
$( 'a[className*=\':\']' ).unbind();
// If the offset is over the total number of comments we cannot fetch any more, so hide the button.
if ( commentsBox.st > commentsBox.total )
$('#show-comments').hide();
else
$('#show-comments').show().children('a').text( __( 'Show more comments' ) );
return;
} else if ( 1 == r ) {
$('#show-comments').text( __( 'No more comments found.' ) );
return;
}
$('#the-comment-list').append('<tr><td colspan="2">'+wpAjax.broken+'</td></tr>');
}
);
return false;
},
/**
* Load the next batch of comments.
*
* @memberof commentsBox
*
* @param {number} total Total number of comments to load.
*/
load: function(total){
this.st = jQuery('#the-comment-list tr.comment:visible').length;
this.get(total);
}
};
/**
* Overwrite the content of the Featured Image postbox
*
* @param {string} html New HTML to be displayed in the content area of the postbox.
*
* @global
*/
window.WPSetThumbnailHTML = function(html){
$('.inside', '#postimagediv').html(html);
};
/**
* Set the Image ID of the Featured Image
*
* @param {number} id The post_id of the image to use as Featured Image.
*
* @global
*/
window.WPSetThumbnailID = function(id){
var field = $('input[value="_thumbnail_id"]', '#list-table');
if ( field.length > 0 ) {
$('#meta\\[' + field.attr('id').match(/[0-9]+/) + '\\]\\[value\\]').text(id);
}
};
/**
* Remove the Featured Image
*
* @param {string} nonce Nonce to use in the request.
*
* @global
*/
window.WPRemoveThumbnail = function(nonce){
$.post(ajaxurl, {
action: 'set-post-thumbnail', post_id: $( '#post_ID' ).val(), thumbnail_id: -1, _ajax_nonce: nonce, cookie: encodeURIComponent( document.cookie )
},
/**
* Handle server response
*
* @param {string} str Response, will be '0' when an error occurred otherwise contains link to add Featured Image.
*/
function(str){
if ( str == '0' ) {
alert( __( 'Could not set that as the thumbnail image. Try a different attachment.' ) );
} else {
WPSetThumbnailHTML(str);
}
}
);
};
/**
* Heartbeat locks.
*
* Used to lock editing of an object by only one user at a time.
*
* When the user does not send a heartbeat in a heartbeat-time
* the user is no longer editing and another user can start editing.
*/
$(document).on( 'heartbeat-send.refresh-lock', function( e, data ) {
var lock = $('#active_post_lock').val(),
post_id = $('#post_ID').val(),
send = {};
if ( ! post_id || ! $('#post-lock-dialog').length )
return;
send.post_id = post_id;
if ( lock )
send.lock = lock;
data['wp-refresh-post-lock'] = send;
}).on( 'heartbeat-tick.refresh-lock', function( e, data ) {
// Post locks: update the lock string or show the dialog if somebody has taken over editing.
var received, wrap, avatar;
if ( data['wp-refresh-post-lock'] ) {
received = data['wp-refresh-post-lock'];
if ( received.lock_error ) {
// Show "editing taken over" message.
wrap = $('#post-lock-dialog');
if ( wrap.length && ! wrap.is(':visible') ) {
if ( wp.autosave ) {
// Save the latest changes and disable.
$(document).one( 'heartbeat-tick', function() {
wp.autosave.server.suspend();
wrap.removeClass('saving').addClass('saved');
$(window).off( 'beforeunload.edit-post' );
});
wrap.addClass('saving');
wp.autosave.server.triggerSave();
}
if ( received.lock_error.avatar_src ) {
avatar = $( '<img />', {
'class': 'avatar avatar-64 photo',
width: 64,
height: 64,
alt: '',
src: received.lock_error.avatar_src,
srcset: received.lock_error.avatar_src_2x ? received.lock_error.avatar_src_2x + ' 2x' : undefined
} );
wrap.find('div.post-locked-avatar').empty().append( avatar );
}
wrap.show().find('.currently-editing').text( received.lock_error.text );
wrap.find('.wp-tab-first').focus();
}
} else if ( received.new_lock ) {
$('#active_post_lock').val( received.new_lock );
}
}
}).on( 'before-autosave.update-post-slug', function() {
titleHasFocus = document.activeElement && document.activeElement.id === 'title';
}).on( 'after-autosave.update-post-slug', function() {
/*
* Create slug area only if not already there
* and the title field was not focused (user was not typing a title) when autosave ran.
*/
if ( ! $('#edit-slug-box > *').length && ! titleHasFocus ) {
$.post( ajaxurl, {
action: 'sample-permalink',
post_id: $('#post_ID').val(),
new_title: $('#title').val(),
samplepermalinknonce: $('#samplepermalinknonce').val()
},
function( data ) {
if ( data != '-1' ) {
$('#edit-slug-box').html(data);
}
}
);
}
});
}(jQuery));
/**
* Heartbeat refresh nonces.
*/
(function($) {
var check, timeout;
/**
* Only allow to check for nonce refresh every 30 seconds.
*/
function schedule() {
check = false;
window.clearTimeout( timeout );
timeout = window.setTimeout( function(){ check = true; }, 300000 );
}
$(document).on( 'heartbeat-send.wp-refresh-nonces', function( e, data ) {
var post_id,
$authCheck = $('#wp-auth-check-wrap');
if ( check || ( $authCheck.length && ! $authCheck.hasClass( 'hidden' ) ) ) {
if ( ( post_id = $('#post_ID').val() ) && $('#_wpnonce').val() ) {
data['wp-refresh-post-nonces'] = {
post_id: post_id
};
}
}
}).on( 'heartbeat-tick.wp-refresh-nonces', function( e, data ) {
var nonces = data['wp-refresh-post-nonces'];
if ( nonces ) {
schedule();
if ( nonces.replace ) {
$.each( nonces.replace, function( selector, value ) {
$( '#' + selector ).val( value );
});
}
if ( nonces.heartbeatNonce )
window.heartbeatSettings.nonce = nonces.heartbeatNonce;
}
}).ready( function() {
schedule();
});
}(jQuery));
/**
* All post and postbox controls and functionality.
*/
jQuery(document).ready( function($) {
var stamp, visibility, $submitButtons, updateVisibility, updateText,
$textarea = $('#content'),
$document = $(document),
postId = $('#post_ID').val() || 0,
$submitpost = $('#submitpost'),
releaseLock = true,
$postVisibilitySelect = $('#post-visibility-select'),
$timestampdiv = $('#timestampdiv'),
$postStatusSelect = $('#post-status-select'),
isMac = window.navigator.platform ? window.navigator.platform.indexOf( 'Mac' ) !== -1 : false,
copyAttachmentURLClipboard = new ClipboardJS( '.copy-attachment-url.edit-media' ),
copyAttachmentURLSuccessTimeout,
__ = wp.i18n.__, _x = wp.i18n._x;
postboxes.add_postbox_toggles(pagenow);
/*
* Clear the window name. Otherwise if this is a former preview window where the user navigated to edit another post,
* and the first post is still being edited, clicking Preview there will use this window to show the preview.
*/
window.name = '';
// Post locks: contain focus inside the dialog. If the dialog is shown, focus the first item.
$('#post-lock-dialog .notification-dialog').on( 'keydown', function(e) {
// Don't do anything when [Tab] is pressed.
if ( e.which != 9 )
return;
var target = $(e.target);
// [Shift] + [Tab] on first tab cycles back to last tab.
if ( target.hasClass('wp-tab-first') && e.shiftKey ) {
$(this).find('.wp-tab-last').focus();
e.preventDefault();
// [Tab] on last tab cycles back to first tab.
} else if ( target.hasClass('wp-tab-last') && ! e.shiftKey ) {
$(this).find('.wp-tab-first').focus();
e.preventDefault();
}
}).filter(':visible').find('.wp-tab-first').focus();
// Set the heartbeat interval to 15 seconds if post lock dialogs are enabled.
if ( wp.heartbeat && $('#post-lock-dialog').length ) {
wp.heartbeat.interval( 15 );
}
// The form is being submitted by the user.
$submitButtons = $submitpost.find( ':submit, a.submitdelete, #post-preview' ).on( 'click.edit-post', function( event ) {
var $button = $(this);
if ( $button.hasClass('disabled') ) {
event.preventDefault();
return;
}
if ( $button.hasClass('submitdelete') || $button.is( '#post-preview' ) ) {
return;
}
// The form submission can be blocked from JS or by using HTML 5.0 validation on some fields.
// Run this only on an actual 'submit'.
$('form#post').off( 'submit.edit-post' ).on( 'submit.edit-post', function( event ) {
if ( event.isDefaultPrevented() ) {
return;
}
// Stop auto save.
if ( wp.autosave ) {
wp.autosave.server.suspend();
}
if ( typeof commentReply !== 'undefined' ) {
/*
* Warn the user they have an unsaved comment before submitting
* the post data for update.
*/
if ( ! commentReply.discardCommentChanges() ) {
return false;
}
/*
* Close the comment edit/reply form if open to stop the form
* action from interfering with the post's form action.
*/
commentReply.close();
}
releaseLock = false;
$(window).off( 'beforeunload.edit-post' );
$submitButtons.addClass( 'disabled' );
if ( $button.attr('id') === 'publish' ) {
$submitpost.find( '#major-publishing-actions .spinner' ).addClass( 'is-active' );
} else {
$submitpost.find( '#minor-publishing .spinner' ).addClass( 'is-active' );
}
});
});
// Submit the form saving a draft or an autosave, and show a preview in a new tab.
$('#post-preview').on( 'click.post-preview', function( event ) {
var $this = $(this),
$form = $('form#post'),
$previewField = $('input#wp-preview'),
target = $this.attr('target') || 'wp-preview',
ua = navigator.userAgent.toLowerCase();
event.preventDefault();
if ( $this.hasClass('disabled') ) {
return;
}
if ( wp.autosave ) {
wp.autosave.server.tempBlockSave();
}
$previewField.val('dopreview');
$form.attr( 'target', target ).submit().attr( 'target', '' );
// Workaround for WebKit bug preventing a form submitting twice to the same action.
// https://bugs.webkit.org/show_bug.cgi?id=28633
if ( ua.indexOf('safari') !== -1 && ua.indexOf('chrome') === -1 ) {
$form.attr( 'action', function( index, value ) {
return value + '?t=' + ( new Date() ).getTime();
});
}
$previewField.val('');
});
// This code is meant to allow tabbing from Title to Post content.
$('#title').on( 'keydown.editor-focus', function( event ) {
var editor;
if ( event.keyCode === 9 && ! event.ctrlKey && ! event.altKey && ! event.shiftKey ) {
editor = typeof tinymce != 'undefined' && tinymce.get('content');
if ( editor && ! editor.isHidden() ) {
editor.focus();
} else if ( $textarea.length ) {
$textarea.focus();
} else {
return;
}
event.preventDefault();
}
});
// Auto save new posts after a title is typed.
if ( $( '#auto_draft' ).val() ) {
$( '#title' ).blur( function() {
var cancel;
if ( ! this.value || $('#edit-slug-box > *').length ) {
return;
}
// Cancel the auto save when the blur was triggered by the user submitting the form.
$('form#post').one( 'submit', function() {
cancel = true;
});
window.setTimeout( function() {
if ( ! cancel && wp.autosave ) {
wp.autosave.server.triggerSave();
}
}, 200 );
});
}
$document.on( 'autosave-disable-buttons.edit-post', function() {
$submitButtons.addClass( 'disabled' );
}).on( 'autosave-enable-buttons.edit-post', function() {
if ( ! wp.heartbeat || ! wp.heartbeat.hasConnectionError() ) {
$submitButtons.removeClass( 'disabled' );
}
}).on( 'before-autosave.edit-post', function() {
$( '.autosave-message' ).text( __( 'Saving Draft…' ) );
}).on( 'after-autosave.edit-post', function( event, data ) {
$( '.autosave-message' ).text( data.message );
if ( $( document.body ).hasClass( 'post-new-php' ) ) {
$( '.submitbox .submitdelete' ).show();
}
});
/*
* When the user is trying to load another page, or reloads current page
* show a confirmation dialog when there are unsaved changes.
*/
$(window).on( 'beforeunload.edit-post', function() {
var editor = typeof tinymce !== 'undefined' && tinymce.get('content');
if ( ( editor && ! editor.isHidden() && editor.isDirty() ) ||
( wp.autosave && wp.autosave.server.postChanged() ) ) {
return __( 'The changes you made will be lost if you navigate away from this page.' );
}
}).on( 'unload.edit-post', function( event ) {
if ( ! releaseLock ) {
return;
}
/*
* Unload is triggered (by hand) on removing the Thickbox iframe.
* Make sure we process only the main document unload.
*/
if ( event.target && event.target.nodeName != '#document' ) {
return;
}
var postID = $('#post_ID').val();
var postLock = $('#active_post_lock').val();
if ( ! postID || ! postLock ) {
return;
}
var data = {
action: 'wp-remove-post-lock',
_wpnonce: $('#_wpnonce').val(),
post_ID: postID,
active_post_lock: postLock
};
if ( window.FormData && window.navigator.sendBeacon ) {
var formData = new window.FormData();
$.each( data, function( key, value ) {
formData.append( key, value );
});
if ( window.navigator.sendBeacon( ajaxurl, formData ) ) {
return;
}
}
// Fall back to a synchronous POST request.
// See https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon
$.post({
async: false,
data: data,
url: ajaxurl
});
});
// Multiple taxonomies.
if ( $('#tagsdiv-post_tag').length ) {
window.tagBox && window.tagBox.init();
} else {
$('.meta-box-sortables').children('div.postbox').each(function(){
if ( this.id.indexOf('tagsdiv-') === 0 ) {
window.tagBox && window.tagBox.init();
return false;
}
});
}
// Handle categories.
$('.categorydiv').each( function(){
var this_id = $(this).attr('id'), catAddBefore, catAddAfter, taxonomyParts, taxonomy, settingName;
taxonomyParts = this_id.split('-');
taxonomyParts.shift();
taxonomy = taxonomyParts.join('-');
settingName = taxonomy + '_tab';
if ( taxonomy == 'category' ) {
settingName = 'cats';
}
// @todo Move to jQuery 1.3+, support for multiple hierarchical taxonomies, see wp-lists.js.
$('a', '#' + taxonomy + '-tabs').click( function( e ) {
e.preventDefault();
var t = $(this).attr('href');
$(this).parent().addClass('tabs').siblings('li').removeClass('tabs');
$('#' + taxonomy + '-tabs').siblings('.tabs-panel').hide();
$(t).show();
if ( '#' + taxonomy + '-all' == t ) {
deleteUserSetting( settingName );
} else {
setUserSetting( settingName, 'pop' );
}
});
if ( getUserSetting( settingName ) )
$('a[href="#' + taxonomy + '-pop"]', '#' + taxonomy + '-tabs').click();
// Add category button controls.
$('#new' + taxonomy).one( 'focus', function() {
$( this ).val( '' ).removeClass( 'form-input-tip' );
});
// On [Enter] submit the taxonomy.
$('#new' + taxonomy).keypress( function(event){
if( 13 === event.keyCode ) {
event.preventDefault();
$('#' + taxonomy + '-add-submit').click();
}
});
// After submitting a new taxonomy, re-focus the input field.
$('#' + taxonomy + '-add-submit').click( function() {
$('#new' + taxonomy).focus();
});
/**
* Before adding a new taxonomy, disable submit button.
*
* @param {Object} s Taxonomy object which will be added.
*
* @return {Object}
*/
catAddBefore = function( s ) {
if ( !$('#new'+taxonomy).val() ) {
return false;
}
s.data += '&' + $( ':checked', '#'+taxonomy+'checklist' ).serialize();
$( '#' + taxonomy + '-add-submit' ).prop( 'disabled', true );
return s;
};
/**
* Re-enable submit button after a taxonomy has been added.
*
* Re-enable submit button.
* If the taxonomy has a parent place the taxonomy underneath the parent.
*
* @param {Object} r Response.
* @param {Object} s Taxonomy data.
*
* @return {void}
*/
catAddAfter = function( r, s ) {
var sup, drop = $('#new'+taxonomy+'_parent');
$( '#' + taxonomy + '-add-submit' ).prop( 'disabled', false );
if ( 'undefined' != s.parsed.responses[0] && (sup = s.parsed.responses[0].supplemental.newcat_parent) ) {
drop.before(sup);
drop.remove();
}
};
$('#' + taxonomy + 'checklist').wpList({
alt: '',
response: taxonomy + '-ajax-response',
addBefore: catAddBefore,
addAfter: catAddAfter
});
// Add new taxonomy button toggles input form visibility.
$('#' + taxonomy + '-add-toggle').click( function( e ) {
e.preventDefault();
$('#' + taxonomy + '-adder').toggleClass( 'wp-hidden-children' );
$('a[href="#' + taxonomy + '-all"]', '#' + taxonomy + '-tabs').click();
$('#new'+taxonomy).focus();
});
// Sync checked items between "All {taxonomy}" and "Most used" lists.
$('#' + taxonomy + 'checklist, #' + taxonomy + 'checklist-pop').on( 'click', 'li.popular-category > label input[type="checkbox"]', function() {
var t = $(this), c = t.is(':checked'), id = t.val();
if ( id && t.parents('#taxonomy-'+taxonomy).length )
$('#in-' + taxonomy + '-' + id + ', #in-popular-' + taxonomy + '-' + id).prop( 'checked', c );
});
}); // End cats.
// Custom Fields postbox.
if ( $('#postcustom').length ) {
$( '#the-list' ).wpList( {
/**
* Add current post_ID to request to fetch custom fields
*
* @ignore
*
* @param {Object} s Request object.
*
* @return {Object} Data modified with post_ID attached.
*/
addBefore: function( s ) {
s.data += '&post_id=' + $('#post_ID').val();
return s;
},
/**
* Show the listing of custom fields after fetching.
*
* @ignore
*/
addAfter: function() {
$('table#list-table').show();
}
});
}
/*
* Publish Post box (#submitdiv)
*/
if ( $('#submitdiv').length ) {
stamp = $('#timestamp').html();
visibility = $('#post-visibility-display').html();
/**
* When the visibility of a post changes sub-options should be shown or hidden.
*
* @ignore
*
* @return {void}
*/
updateVisibility = function() {
// Show sticky for public posts.
if ( $postVisibilitySelect.find('input:radio:checked').val() != 'public' ) {
$('#sticky').prop('checked', false);
$('#sticky-span').hide();
} else {
$('#sticky-span').show();
}
// Show password input field for password protected post.
if ( $postVisibilitySelect.find('input:radio:checked').val() != 'password' ) {
$('#password-span').hide();
} else {
$('#password-span').show();
}
};
/**
* Make sure all labels represent the current settings.
*
* @ignore
*
* @return {boolean} False when an invalid timestamp has been selected, otherwise True.
*/
updateText = function() {
if ( ! $timestampdiv.length )
return true;
var attemptedDate, originalDate, currentDate, publishOn, postStatus = $('#post_status'),
optPublish = $('option[value="publish"]', postStatus), aa = $('#aa').val(),
mm = $('#mm').val(), jj = $('#jj').val(), hh = $('#hh').val(), mn = $('#mn').val();
attemptedDate = new Date( aa, mm - 1, jj, hh, mn );
originalDate = new Date( $('#hidden_aa').val(), $('#hidden_mm').val() -1, $('#hidden_jj').val(), $('#hidden_hh').val(), $('#hidden_mn').val() );
currentDate = new Date( $('#cur_aa').val(), $('#cur_mm').val() -1, $('#cur_jj').val(), $('#cur_hh').val(), $('#cur_mn').val() );
// Catch unexpected date problems.
if ( attemptedDate.getFullYear() != aa || (1 + attemptedDate.getMonth()) != mm || attemptedDate.getDate() != jj || attemptedDate.getMinutes() != mn ) {
$timestampdiv.find('.timestamp-wrap').addClass('form-invalid');
return false;
} else {
$timestampdiv.find('.timestamp-wrap').removeClass('form-invalid');
}
// Determine what the publish should be depending on the date and post status.
if ( attemptedDate > currentDate && $('#original_post_status').val() != 'future' ) {
publishOn = __( 'Schedule for:' );
$('#publish').val( _x( 'Schedule', 'post action/button label' ) );
} else if ( attemptedDate <= currentDate && $('#original_post_status').val() != 'publish' ) {
publishOn = __( 'Publish on:' );
$('#publish').val( __( 'Publish' ) );
} else {
publishOn = __( 'Published on:' );
$('#publish').val( __( 'Update' ) );
}
// If the date is the same, set it to trigger update events.
if ( originalDate.toUTCString() == attemptedDate.toUTCString() ) {
// Re-set to the current value.
$('#timestamp').html(stamp);
} else {
$('#timestamp').html(
'\n' + publishOn + ' <b>' +
// translators: 1: Month, 2: Day, 3: Year, 4: Hour, 5: Minute.
__( '%1$s %2$s, %3$s at %4$s:%5$s' )
.replace( '%1$s', $( 'option[value="' + mm + '"]', '#mm' ).attr( 'data-text' ) )
.replace( '%2$s', parseInt( jj, 10 ) )
.replace( '%3$s', aa )
.replace( '%4$s', ( '00' + hh ).slice( -2 ) )
.replace( '%5$s', ( '00' + mn ).slice( -2 ) ) +
'</b> '
);
}
// Add "privately published" to post status when applies.
if ( $postVisibilitySelect.find('input:radio:checked').val() == 'private' ) {
$('#publish').val( __( 'Update' ) );
if ( 0 === optPublish.length ) {
postStatus.append('<option value="publish">' + __( 'Privately Published' ) + '</option>');
} else {
optPublish.html( __( 'Privately Published' ) );
}
$('option[value="publish"]', postStatus).prop('selected', true);
$('#misc-publishing-actions .edit-post-status').hide();
} else {
if ( $('#original_post_status').val() == 'future' || $('#original_post_status').val() == 'draft' ) {
if ( optPublish.length ) {
optPublish.remove();
postStatus.val($('#hidden_post_status').val());
}
} else {
optPublish.html( __( 'Published' ) );
}
if ( postStatus.is(':hidden') )
$('#misc-publishing-actions .edit-post-status').show();
}
// Update "Status:" to currently selected status.
$('#post-status-display').text(
// Remove any potential tags from post status text.
wp.sanitize.stripTagsAndEncodeText( $('option:selected', postStatus).text() )
);
// Show or hide the "Save Draft" button.
if ( $('option:selected', postStatus).val() == 'private' || $('option:selected', postStatus).val() == 'publish' ) {
$('#save-post').hide();
} else {
$('#save-post').show();
if ( $('option:selected', postStatus).val() == 'pending' ) {
$('#save-post').show().val( __( 'Save as Pending' ) );
} else {
$('#save-post').show().val( __( 'Save Draft' ) );
}
}
return true;
};
// Show the visibility options and hide the toggle button when opened.
$( '#visibility .edit-visibility').click( function( e ) {
e.preventDefault();
if ( $postVisibilitySelect.is(':hidden') ) {
updateVisibility();
$postVisibilitySelect.slideDown( 'fast', function() {
$postVisibilitySelect.find( 'input[type="radio"]' ).first().focus();
} );
$(this).hide();
}
});
// Cancel visibility selection area and hide it from view.
$postVisibilitySelect.find('.cancel-post-visibility').click( function( event ) {
$postVisibilitySelect.slideUp('fast');
$('#visibility-radio-' + $('#hidden-post-visibility').val()).prop('checked', true);
$('#post_password').val($('#hidden-post-password').val());
$('#sticky').prop('checked', $('#hidden-post-sticky').prop('checked'));
$('#post-visibility-display').html(visibility);
$('#visibility .edit-visibility').show().focus();
updateText();
event.preventDefault();
});
// Set the selected visibility as current.
$postVisibilitySelect.find('.save-post-visibility').click( function( event ) { // Crazyhorse - multiple OK cancels.
var visibilityLabel = '', selectedVisibility = $postVisibilitySelect.find('input:radio:checked').val();
$postVisibilitySelect.slideUp('fast');
$('#visibility .edit-visibility').show().focus();
updateText();
if ( 'public' !== selectedVisibility ) {
$('#sticky').prop('checked', false);
}
switch ( selectedVisibility ) {
case 'public':
visibilityLabel = $( '#sticky' ).prop( 'checked' ) ? __( 'Public, Sticky' ) : __( 'Public' );
break;
case 'private':
visibilityLabel = __( 'Private' );
break;
case 'password':
visibilityLabel = __( 'Password Protected' );
break;
}
$('#post-visibility-display').text( visibilityLabel );
event.preventDefault();
});
// When the selection changes, update labels.
$postVisibilitySelect.find('input:radio').change( function() {
updateVisibility();
});
// Edit publish time click.
$timestampdiv.siblings('a.edit-timestamp').click( function( event ) {
if ( $timestampdiv.is( ':hidden' ) ) {
$timestampdiv.slideDown( 'fast', function() {
$( 'input, select', $timestampdiv.find( '.timestamp-wrap' ) ).first().focus();
} );
$(this).hide();
}
event.preventDefault();
});
// Cancel editing the publish time and hide the settings.
$timestampdiv.find('.cancel-timestamp').click( function( event ) {
$timestampdiv.slideUp('fast').siblings('a.edit-timestamp').show().focus();
$('#mm').val($('#hidden_mm').val());
$('#jj').val($('#hidden_jj').val());
$('#aa').val($('#hidden_aa').val());
$('#hh').val($('#hidden_hh').val());
$('#mn').val($('#hidden_mn').val());
updateText();
event.preventDefault();
});
// Save the changed timestamp.
$timestampdiv.find('.save-timestamp').click( function( event ) { // Crazyhorse - multiple OK cancels.
if ( updateText() ) {
$timestampdiv.slideUp('fast');
$timestampdiv.siblings('a.edit-timestamp').show().focus();
}
event.preventDefault();
});
// Cancel submit when an invalid timestamp has been selected.
$('#post').on( 'submit', function( event ) {
if ( ! updateText() ) {
event.preventDefault();
$timestampdiv.show();
if ( wp.autosave ) {
wp.autosave.enableButtons();
}
$( '#publishing-action .spinner' ).removeClass( 'is-active' );
}
});
// Post Status edit click.
$postStatusSelect.siblings('a.edit-post-status').click( function( event ) {
if ( $postStatusSelect.is( ':hidden' ) ) {
$postStatusSelect.slideDown( 'fast', function() {
$postStatusSelect.find('select').focus();
} );
$(this).hide();
}
event.preventDefault();
});
// Save the Post Status changes and hide the options.
$postStatusSelect.find('.save-post-status').click( function( event ) {
$postStatusSelect.slideUp( 'fast' ).siblings( 'a.edit-post-status' ).show().focus();
updateText();
event.preventDefault();
});
// Cancel Post Status editing and hide the options.
$postStatusSelect.find('.cancel-post-status').click( function( event ) {
$postStatusSelect.slideUp( 'fast' ).siblings( 'a.edit-post-status' ).show().focus();
$('#post_status').val( $('#hidden_post_status').val() );
updateText();
event.preventDefault();
});
}
/**
* Handle the editing of the post_name. Create the required HTML elements and
* update the changes via Ajax.
*
* @global
*
* @return {void}
*/
function editPermalink() {
var i, slug_value,
$el, revert_e,
c = 0,
real_slug = $('#post_name'),
revert_slug = real_slug.val(),
permalink = $( '#sample-permalink' ),
permalinkOrig = permalink.html(),
permalinkInner = $( '#sample-permalink a' ).html(),
buttons = $('#edit-slug-buttons'),
buttonsOrig = buttons.html(),
full = $('#editable-post-name-full');
// Deal with Twemoji in the post-name.
full.find( 'img' ).replaceWith( function() { return this.alt; } );
full = full.html();
permalink.html( permalinkInner );
// Save current content to revert to when cancelling.
$el = $( '#editable-post-name' );
revert_e = $el.html();
buttons.html( '<button type="button" class="save button button-small">' + __( 'OK' ) + '</button> <button type="button" class="cancel button-link">' + __( 'Cancel' ) + '</button>' );
// Save permalink changes.
buttons.children( '.save' ).click( function() {
var new_slug = $el.children( 'input' ).val();
if ( new_slug == $('#editable-post-name-full').text() ) {
buttons.children('.cancel').click();
return;
}
$.post(
ajaxurl,
{
action: 'sample-permalink',
post_id: postId,
new_slug: new_slug,
new_title: $('#title').val(),
samplepermalinknonce: $('#samplepermalinknonce').val()
},
function(data) {
var box = $('#edit-slug-box');
box.html(data);
if (box.hasClass('hidden')) {
box.fadeIn('fast', function () {
box.removeClass('hidden');
});
}
buttons.html(buttonsOrig);
permalink.html(permalinkOrig);
real_slug.val(new_slug);
$( '.edit-slug' ).focus();
wp.a11y.speak( __( 'Permalink saved' ) );
}
);
});
// Cancel editing of permalink.
buttons.children( '.cancel' ).click( function() {
$('#view-post-btn').show();
$el.html(revert_e);
buttons.html(buttonsOrig);
permalink.html(permalinkOrig);
real_slug.val(revert_slug);
$( '.edit-slug' ).focus();
});
// If more than 1/4th of 'full' is '%', make it empty.
for ( i = 0; i < full.length; ++i ) {
if ( '%' == full.charAt(i) )
c++;
}
slug_value = ( c > full.length / 4 ) ? '' : full;
$el.html( '<input type="text" id="new-post-slug" value="' + slug_value + '" autocomplete="off" />' ).children( 'input' ).keydown( function( e ) {
var key = e.which;
// On [Enter], just save the new slug, don't save the post.
if ( 13 === key ) {
e.preventDefault();
buttons.children( '.save' ).click();
}
// On [Esc] cancel the editing.
if ( 27 === key ) {
buttons.children( '.cancel' ).click();
}
} ).keyup( function() {
real_slug.val( this.value );
}).focus();
}
$( '#titlediv' ).on( 'click', '.edit-slug', function() {
editPermalink();
});
/**
* Adds screen reader text to the title label when needed.
*
* Use the 'screen-reader-text' class to emulate a placeholder attribute
* and hide the label when entering a value.
*
* @param {string} id Optional. HTML ID to add the screen reader helper text to.
*
* @global
*
* @return {void}
*/
window.wptitlehint = function( id ) {
id = id || 'title';
var title = $( '#' + id ), titleprompt = $( '#' + id + '-prompt-text' );
if ( '' === title.val() ) {
titleprompt.removeClass( 'screen-reader-text' );
}
title.on( 'input', function() {
if ( '' === this.value ) {
titleprompt.removeClass( 'screen-reader-text' );
return;
}
titleprompt.addClass( 'screen-reader-text' );
} );
};
wptitlehint();
// Resize the WYSIWYG and plain text editors.
( function() {
var editor, offset, mce,
$handle = $('#post-status-info'),
$postdivrich = $('#postdivrich');
// If there are no textareas or we are on a touch device, we can't do anything.
if ( ! $textarea.length || 'ontouchstart' in window ) {
// Hide the resize handle.
$('#content-resize-handle').hide();
return;
}
/**
* Handle drag event.
*
* @param {Object} event Event containing details about the drag.
*/
function dragging( event ) {
if ( $postdivrich.hasClass( 'wp-editor-expand' ) ) {
return;
}
if ( mce ) {
editor.theme.resizeTo( null, offset + event.pageY );
} else {
$textarea.height( Math.max( 50, offset + event.pageY ) );
}
event.preventDefault();
}
/**
* When the dragging stopped make sure we return focus and do a sanity check on the height.
*/
function endDrag() {
var height, toolbarHeight;
if ( $postdivrich.hasClass( 'wp-editor-expand' ) ) {
return;
}
if ( mce ) {
editor.focus();
toolbarHeight = parseInt( $( '#wp-content-editor-container .mce-toolbar-grp' ).height(), 10 );
if ( toolbarHeight < 10 || toolbarHeight > 200 ) {
toolbarHeight = 30;
}
height = parseInt( $('#content_ifr').css('height'), 10 ) + toolbarHeight - 28;
} else {
$textarea.focus();
height = parseInt( $textarea.css('height'), 10 );
}
$document.off( '.wp-editor-resize' );
// Sanity check: normalize height to stay within acceptable ranges.
if ( height && height > 50 && height < 5000 ) {
setUserSetting( 'ed_size', height );
}
}
$handle.on( 'mousedown.wp-editor-resize', function( event ) {
if ( typeof tinymce !== 'undefined' ) {
editor = tinymce.get('content');
}
if ( editor && ! editor.isHidden() ) {
mce = true;
offset = $('#content_ifr').height() - event.pageY;
} else {
mce = false;
offset = $textarea.height() - event.pageY;
$textarea.blur();
}
$document.on( 'mousemove.wp-editor-resize', dragging )
.on( 'mouseup.wp-editor-resize mouseleave.wp-editor-resize', endDrag );
event.preventDefault();
}).on( 'mouseup.wp-editor-resize', endDrag );
})();
// TinyMCE specific handling of Post Format changes to reflect in the editor.
if ( typeof tinymce !== 'undefined' ) {
// When changing post formats, change the editor body class.
$( '#post-formats-select input.post-format' ).on( 'change.set-editor-class', function() {
var editor, body, format = this.id;
if ( format && $( this ).prop( 'checked' ) && ( editor = tinymce.get( 'content' ) ) ) {
body = editor.getBody();
body.className = body.className.replace( /\bpost-format-[^ ]+/, '' );
editor.dom.addClass( body, format == 'post-format-0' ? 'post-format-standard' : format );
$( document ).trigger( 'editor-classchange' );
}
});
// When changing page template, change the editor body class.
$( '#page_template' ).on( 'change.set-editor-class', function() {
var editor, body, pageTemplate = $( this ).val() || '';
pageTemplate = pageTemplate.substr( pageTemplate.lastIndexOf( '/' ) + 1, pageTemplate.length )
.replace( /\.php$/, '' )
.replace( /\./g, '-' );
if ( pageTemplate && ( editor = tinymce.get( 'content' ) ) ) {
body = editor.getBody();
body.className = body.className.replace( /\bpage-template-[^ ]+/, '' );
editor.dom.addClass( body, 'page-template-' + pageTemplate );
$( document ).trigger( 'editor-classchange' );
}
});
}
// Save on pressing [Ctrl]/[Command] + [S] in the Text editor.
$textarea.on( 'keydown.wp-autosave', function( event ) {
// Key [S] has code 83.
if ( event.which === 83 ) {
if ( event.shiftKey || event.altKey || ( isMac && ( ! event.metaKey || event.ctrlKey ) ) || ( ! isMac && ! event.ctrlKey ) ) {
return;
}
wp.autosave && wp.autosave.server.triggerSave();
event.preventDefault();
}
});
// If the last status was auto-draft and the save is triggered, edit the current URL.
if ( $( '#original_post_status' ).val() === 'auto-draft' && window.history.replaceState ) {
var location;
$( '#publish' ).on( 'click', function() {
location = window.location.href;
location += ( location.indexOf( '?' ) !== -1 ) ? '&' : '?';
location += 'wp-post-new-reload=true';
window.history.replaceState( null, null, location );
});
}
/**
* Copies the attachment URL in the Edit Media page to the clipboard.
*
* @since 5.5.0
*
* @param {MouseEvent} event A click event.
*
* @return {void}
*/
copyAttachmentURLClipboard.on( 'success', function( event ) {
var triggerElement = $( event.trigger ),
successElement = $( '.success', triggerElement.closest( '.copy-to-clipboard-container' ) );
// Clear the selection and move focus back to the trigger.
event.clearSelection();
// Handle ClipboardJS focus bug, see https://github.com/zenorocha/clipboard.js/issues/680
triggerElement.focus();
// Show success visual feedback.
clearTimeout( copyAttachmentURLSuccessTimeout );
successElement.removeClass( 'hidden' );
// Hide success visual feedback after 3 seconds since last success.
copyAttachmentURLSuccessTimeout = setTimeout( function() {
successElement.addClass( 'hidden' );
}, 3000 );
// Handle success audible feedback.
wp.a11y.speak( __( 'The file URL has been copied to your clipboard' ) );
} );
} );
/**
* TinyMCE word count display
*/
( function( $, counter ) {
$( function() {
var $content = $( '#content' ),
$count = $( '#wp-word-count' ).find( '.word-count' ),
prevCount = 0,
contentEditor;
/**
* Get the word count from TinyMCE and display it
*/
function update() {
var text, count;
if ( ! contentEditor || contentEditor.isHidden() ) {
text = $content.val();
} else {
text = contentEditor.getContent( { format: 'raw' } );
}
count = counter.count( text );
if ( count !== prevCount ) {
$count.text( count );
}
prevCount = count;
}
/**
* Bind the word count update triggers.
*
* When a node change in the main TinyMCE editor has been triggered.
* When a key has been released in the plain text content editor.
*/
$( document ).on( 'tinymce-editor-init', function( event, editor ) {
if ( editor.id !== 'content' ) {
return;
}
contentEditor = editor;
editor.on( 'nodechange keyup', _.debounce( update, 1000 ) );
} );
$content.on( 'input keyup', _.debounce( update, 1000 ) );
update();
} );
} )( jQuery, new wp.utils.WordCounter() );
|
import Transaction from '../../transaction';
import inherits from 'inherits';
const debug = require('debug')('knex:tx')
import * as helpers from '../../helpers';
import { assign, isUndefined } from 'lodash'
function Transaction_MySQL2() {
Transaction.apply(this, arguments)
}
inherits(Transaction_MySQL2, Transaction)
assign(Transaction_MySQL2.prototype, {
query(conn, sql, status, value) {
const t = this
const q = this.trxClient.query(conn, sql)
.catch(err => err.code === 'ER_SP_DOES_NOT_EXIST', function() {
helpers.warn(
'Transaction was implicitly committed, do not mix transactions and' +
'DDL with MySQL (#805)'
)
})
.catch(function(err) {
status = 2
value = err
t._completed = true
debug('%s error running transaction query', t.txid)
})
.tap(function() {
if (status === 1) t._resolver(value)
if (status === 2) {
if(isUndefined(value)) {
value = new Error(`Transaction rejected with non-error: ${value}`)
}
t._rejecter(value)
}
})
if (status === 1 || status === 2) {
t._completed = true
}
return q;
}
})
export default Transaction_MySQL2
|
// { "framework": "Vue" }
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ function(module, exports, __webpack_require__) {
var __vue_exports__, __vue_options__
var __vue_styles__ = []
/* styles */
__vue_styles__.push(__webpack_require__(541)
)
/* script */
__vue_exports__ = __webpack_require__(542)
/* template */
var __vue_template__ = __webpack_require__(555)
__vue_options__ = __vue_exports__ = __vue_exports__ || {}
if (
typeof __vue_exports__.default === "object" ||
typeof __vue_exports__.default === "function"
) {
if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")}
__vue_options__ = __vue_exports__ = __vue_exports__.default
}
if (typeof __vue_options__ === "function") {
__vue_options__ = __vue_options__.options
}
__vue_options__.__file = "/Users/bobning/work/source/weex_fork/examples/vue/style/index.vue"
__vue_options__.render = __vue_template__.render
__vue_options__.staticRenderFns = __vue_template__.staticRenderFns
__vue_options__.style = __vue_options__.style || {}
__vue_styles__.forEach(function (module) {
for (var name in module) {
__vue_options__.style[name] = module[name]
}
})
module.exports = __vue_exports__
module.exports.el = 'true'
new Vue(module.exports)
/***/ },
/***/ 381:
/***/ function(module, exports, __webpack_require__) {
var __vue_exports__, __vue_options__
var __vue_styles__ = []
/* styles */
__vue_styles__.push(__webpack_require__(382)
)
/* script */
__vue_exports__ = __webpack_require__(383)
/* template */
var __vue_template__ = __webpack_require__(384)
__vue_options__ = __vue_exports__ = __vue_exports__ || {}
if (
typeof __vue_exports__.default === "object" ||
typeof __vue_exports__.default === "function"
) {
if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")}
__vue_options__ = __vue_exports__ = __vue_exports__.default
}
if (typeof __vue_options__ === "function") {
__vue_options__ = __vue_options__.options
}
__vue_options__.__file = "/Users/bobning/work/source/weex_fork/examples/vue/include/panel.vue"
__vue_options__.render = __vue_template__.render
__vue_options__.staticRenderFns = __vue_template__.staticRenderFns
__vue_options__.style = __vue_options__.style || {}
__vue_styles__.forEach(function (module) {
for (var name in module) {
__vue_options__.style[name] = module[name]
}
})
module.exports = __vue_exports__
/***/ },
/***/ 382:
/***/ function(module, exports) {
module.exports = {
"panel": {
"marginBottom": 20,
"backgroundColor": "#ffffff",
"borderColor": "#dddddd",
"borderWidth": 1
},
"panel-primary": {
"borderColor": "rgb(40,96,144)"
},
"panel-success": {
"borderColor": "rgb(76,174,76)"
},
"panel-info": {
"borderColor": "rgb(70,184,218)"
},
"panel-warning": {
"borderColor": "rgb(238,162,54)"
},
"panel-danger": {
"borderColor": "rgb(212,63,58)"
},
"panel-header": {
"backgroundColor": "#f5f5f5",
"fontSize": 40,
"color": "#333333"
},
"panel-header-primary": {
"backgroundColor": "rgb(40,96,144)",
"color": "#ffffff"
},
"panel-header-success": {
"backgroundColor": "rgb(92,184,92)",
"color": "#ffffff"
},
"panel-header-info": {
"backgroundColor": "rgb(91,192,222)",
"color": "#ffffff"
},
"panel-header-warning": {
"backgroundColor": "rgb(240,173,78)",
"color": "#ffffff"
},
"panel-header-danger": {
"backgroundColor": "rgb(217,83,79)",
"color": "#ffffff"
}
}
/***/ },
/***/ 383:
/***/ function(module, exports) {
'use strict';
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
module.exports = {
props: {
type: { default: 'default' },
title: { default: '' },
paddingBody: { default: 20 },
paddingHead: { default: 20 },
dataClass: { default: '' }, // FIXME transfer class
border: { default: 0 }
}
};
/***/ },
/***/ 384:
/***/ function(module, exports) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _h('div', {
class: ['panel', 'panel-' + _vm.type],
style: {
borderWidth: _vm.border
}
}, [_h('text', {
class: ['panel-header', 'panel-header-' + _vm.type],
style: {
paddingTop: _vm.paddingHead,
paddingBottom: _vm.paddingHead,
paddingLeft: _vm.paddingHead * 1.5,
paddingRight: _vm.paddingHead * 1.5
}
}, [_vm._s(_vm.title)]), _h('div', {
class: ['panel-body', 'panel-body-' + _vm.type],
style: {
paddingTop: _vm.paddingBody,
paddingBottom: _vm.paddingBody,
paddingLeft: _vm.paddingBody * 1.5,
paddingRight: _vm.paddingBody * 1.5
}
}, [_vm._t("default")])])
},staticRenderFns: []}
module.exports.render._withStripped = true
/***/ },
/***/ 391:
/***/ function(module, exports, __webpack_require__) {
var __vue_exports__, __vue_options__
var __vue_styles__ = []
/* styles */
__vue_styles__.push(__webpack_require__(392)
)
/* script */
__vue_exports__ = __webpack_require__(393)
/* template */
var __vue_template__ = __webpack_require__(394)
__vue_options__ = __vue_exports__ = __vue_exports__ || {}
if (
typeof __vue_exports__.default === "object" ||
typeof __vue_exports__.default === "function"
) {
if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")}
__vue_options__ = __vue_exports__ = __vue_exports__.default
}
if (typeof __vue_options__ === "function") {
__vue_options__ = __vue_options__.options
}
__vue_options__.__file = "/Users/bobning/work/source/weex_fork/examples/vue/include/tip.vue"
__vue_options__.render = __vue_template__.render
__vue_options__.staticRenderFns = __vue_template__.staticRenderFns
__vue_options__.style = __vue_options__.style || {}
__vue_styles__.forEach(function (module) {
for (var name in module) {
__vue_options__.style[name] = module[name]
}
})
module.exports = __vue_exports__
/***/ },
/***/ 392:
/***/ function(module, exports) {
module.exports = {
"tip": {
"paddingLeft": 36,
"paddingRight": 36,
"paddingTop": 36,
"paddingBottom": 36,
"borderRadius": 10
},
"tip-txt": {
"fontSize": 28
},
"tip-success": {
"backgroundColor": "#dff0d8",
"borderColor": "#d6e9c6"
},
"tip-txt-success": {
"color": "#3c763d"
},
"tip-info": {
"backgroundColor": "#d9edf7",
"borderColor": "#bce8f1"
},
"tip-txt-info": {
"color": "#31708f"
},
"tip-warning": {
"backgroundColor": "#fcf8e3",
"borderColor": "#faebcc"
},
"tip-txt-warning": {
"color": "#8a6d3b"
},
"tip-danger": {
"backgroundColor": "#f2dede",
"borderColor": "#ebccd1"
},
"tip-txt-danger": {
"color": "#a94442"
}
}
/***/ },
/***/ 393:
/***/ function(module, exports) {
'use strict';
//
//
//
//
//
//
//
module.exports = {
props: {
type: { default: 'success' },
value: { default: '' }
}
};
/***/ },
/***/ 394:
/***/ function(module, exports) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _h('div', {
class: ['tip', 'tip-' + _vm.type]
}, [_h('text', {
class: ['tip-txt', 'tip-txt-' + _vm.type]
}, [_vm._s(_vm.value)])])
},staticRenderFns: []}
module.exports.render._withStripped = true
/***/ },
/***/ 541:
/***/ function(module, exports) {
module.exports = {
"bg-item": {
"width": 690,
"marginBottom": 10
}
}
/***/ },
/***/ 542:
/***/ function(module, exports, __webpack_require__) {
'use strict';
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
module.exports = {
components: {
panel: __webpack_require__(381),
styleBox: __webpack_require__(543),
styleFlex: __webpack_require__(551),
styleItem: __webpack_require__(546)
}
};
/***/ },
/***/ 543:
/***/ function(module, exports, __webpack_require__) {
var __vue_exports__, __vue_options__
var __vue_styles__ = []
/* styles */
__vue_styles__.push(__webpack_require__(544)
)
/* script */
__vue_exports__ = __webpack_require__(545)
/* template */
var __vue_template__ = __webpack_require__(550)
__vue_options__ = __vue_exports__ = __vue_exports__ || {}
if (
typeof __vue_exports__.default === "object" ||
typeof __vue_exports__.default === "function"
) {
if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")}
__vue_options__ = __vue_exports__ = __vue_exports__.default
}
if (typeof __vue_options__ === "function") {
__vue_options__ = __vue_options__.options
}
__vue_options__.__file = "/Users/bobning/work/source/weex_fork/examples/vue/style/style-box.vue"
__vue_options__.render = __vue_template__.render
__vue_options__.staticRenderFns = __vue_template__.staticRenderFns
__vue_options__.style = __vue_options__.style || {}
__vue_styles__.forEach(function (module) {
for (var name in module) {
__vue_options__.style[name] = module[name]
}
})
module.exports = __vue_exports__
/***/ },
/***/ 544:
/***/ function(module, exports) {
module.exports = {
"box": {
"backgroundColor": "#f5f5f5",
"width": 260,
"height": 260,
"paddingLeft": 40,
"paddingTop": 40,
"paddingRight": 40,
"paddingBottom": 40,
"marginLeft": 40,
"marginTop": 40,
"marginRight": 40,
"marginBottom": 40,
"borderWidth": 40,
"borderColor": "#333333",
"borderStyle": "solid"
}
}
/***/ },
/***/ 545:
/***/ function(module, exports, __webpack_require__) {
'use strict';
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
module.exports = {
components: {
panel: __webpack_require__(381),
tip: __webpack_require__(391),
styleItem: __webpack_require__(546)
}
};
/***/ },
/***/ 546:
/***/ function(module, exports, __webpack_require__) {
var __vue_exports__, __vue_options__
var __vue_styles__ = []
/* styles */
__vue_styles__.push(__webpack_require__(547)
)
/* script */
__vue_exports__ = __webpack_require__(548)
/* template */
var __vue_template__ = __webpack_require__(549)
__vue_options__ = __vue_exports__ = __vue_exports__ || {}
if (
typeof __vue_exports__.default === "object" ||
typeof __vue_exports__.default === "function"
) {
if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")}
__vue_options__ = __vue_exports__ = __vue_exports__.default
}
if (typeof __vue_options__ === "function") {
__vue_options__ = __vue_options__.options
}
__vue_options__.__file = "/Users/bobning/work/source/weex_fork/examples/vue/style/style-item.vue"
__vue_options__.render = __vue_template__.render
__vue_options__.staticRenderFns = __vue_template__.staticRenderFns
__vue_options__.style = __vue_options__.style || {}
__vue_styles__.forEach(function (module) {
for (var name in module) {
__vue_options__.style[name] = module[name]
}
})
module.exports = __vue_exports__
/***/ },
/***/ 547:
/***/ function(module, exports) {
module.exports = {
"item": {
"marginRight": 10,
"width": 160,
"height": 75,
"paddingLeft": 8,
"paddingRight": 8,
"paddingTop": 8,
"paddingBottom": 8
},
"txt": {
"color": "#eeeeee"
}
}
/***/ },
/***/ 548:
/***/ function(module, exports) {
'use strict';
//
//
//
//
//
//
//
module.exports = {
props: {
value: { default: '' },
type: { default: '0' } // 0, 1
},
computed: {
bgColor: function bgColor() {
return this.type == '1' ? '#7BA3A8' : '#BEAD92';
}
}
};
/***/ },
/***/ 549:
/***/ function(module, exports) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _h('text', {
staticClass: ["item", "txt"],
style: {
backgroundColor: _vm.bgColor
},
attrs: {
"value": _vm.value
}
})
},staticRenderFns: []}
module.exports.render._withStripped = true
/***/ },
/***/ 550:
/***/ function(module, exports) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _h('div', [_h('panel', {
attrs: {
"title": "Box Model",
"padding-body": "0",
"type": "primary"
}
}, [_h('text', {
staticClass: ["box"]
}, ["Box"])]), _h('panel', {
attrs: {
"title": "border",
"type": "primary"
}
}, [_h('panel', {
attrs: {
"title": "border-width",
"type": ""
}
}, [_h('div', {
staticStyle: {
flexDirection: "row"
}
}, [_h('style-item', {
staticStyle: {
borderStyle: "solid",
borderWidth: "2px",
borderColor: "#333"
},
attrs: {
"value": ""
}
}), _h('style-item', {
staticStyle: {
borderStyle: "solid",
borderWidth: "10px",
borderColor: "#333"
},
attrs: {
"value": ""
}
}), _h('style-item', {
staticStyle: {
borderStyle: "solid",
borderLeftWidth: "4px",
borderColor: "#333"
},
attrs: {
"value": ""
}
}), _h('style-item', {
staticStyle: {
borderStyle: "solid",
borderBottomWidth: "4px",
borderColor: "#333"
},
attrs: {
"value": ""
}
})])]), _h('panel', {
attrs: {
"title": "border-color",
"type": ""
}
}, [_h('div', {
staticStyle: {
flexDirection: "row"
}
}, [_h('style-item', {
staticStyle: {
borderStyle: "solid",
borderWidth: "4px",
borderColor: "#333"
},
attrs: {
"value": ""
}
}), _h('style-item', {
staticStyle: {
borderStyle: "solid",
borderWidth: "4px",
borderColor: "#ddd"
},
attrs: {
"value": ""
}
}), _h('style-item', {
staticStyle: {
borderStyle: "solid",
borderWidth: "4px",
borderColor: "red"
},
attrs: {
"value": ""
}
})])]), _h('panel', {
attrs: {
"title": "border-style",
"type": ""
}
}, [_h('tip', {
staticStyle: {
marginBottom: "10px"
},
attrs: {
"type": "warning",
"value": "just support four edges"
}
}), _h('div', {
staticStyle: {
flexDirection: "row"
}
}, [_h('style-item', {
staticStyle: {
borderStyle: "solid",
borderWidth: "4px",
borderColor: "#333"
},
attrs: {
"value": ""
}
}), _h('style-item', {
staticStyle: {
borderStyle: "dashed",
borderWidth: "4px",
borderColor: "#333"
},
attrs: {
"value": "",
"type": ""
}
}), _h('style-item', {
staticStyle: {
borderStyle: "dotted",
borderWidth: "4px",
borderColor: "#333"
},
attrs: {
"value": ""
}
})])]), _h('panel', {
attrs: {
"title": "border-radius",
"type": ""
}
}, [_h('div', {
staticStyle: {
flexDirection: "row"
}
}, [_h('style-item', {
staticStyle: {
width: "75px",
borderRadius: "38px"
},
attrs: {
"value": ""
}
}), _h('style-item', {
staticStyle: {
borderRadius: "20px"
},
attrs: {
"value": ""
}
}), _h('style-item', {
staticStyle: {
borderTopLeftRadius: "20px",
borderTopRightRadius: "20px"
},
attrs: {
"value": ""
}
}), _h('style-item', {
staticStyle: {
borderBottomLeftRadius: "20px",
borderBottomRightRadius: "20px"
},
attrs: {
"value": ""
}
})])])])])
},staticRenderFns: []}
module.exports.render._withStripped = true
/***/ },
/***/ 551:
/***/ function(module, exports, __webpack_require__) {
var __vue_exports__, __vue_options__
var __vue_styles__ = []
/* styles */
__vue_styles__.push(__webpack_require__(552)
)
/* script */
__vue_exports__ = __webpack_require__(553)
/* template */
var __vue_template__ = __webpack_require__(554)
__vue_options__ = __vue_exports__ = __vue_exports__ || {}
if (
typeof __vue_exports__.default === "object" ||
typeof __vue_exports__.default === "function"
) {
if (Object.keys(__vue_exports__).some(function (key) { return key !== "default" && key !== "__esModule" })) {console.error("named exports are not supported in *.vue files.")}
__vue_options__ = __vue_exports__ = __vue_exports__.default
}
if (typeof __vue_options__ === "function") {
__vue_options__ = __vue_options__.options
}
__vue_options__.__file = "/Users/bobning/work/source/weex_fork/examples/vue/style/style-flex.vue"
__vue_options__.render = __vue_template__.render
__vue_options__.staticRenderFns = __vue_template__.staticRenderFns
__vue_options__.style = __vue_options__.style || {}
__vue_styles__.forEach(function (module) {
for (var name in module) {
__vue_options__.style[name] = module[name]
}
})
module.exports = __vue_exports__
/***/ },
/***/ 552:
/***/ function(module, exports) {
module.exports = {
"row": {
"flexDirection": "row",
"marginBottom": 10
},
"row-align": {
"height": 160,
"borderWidth": 3,
"borderColor": "#dddddd",
"borderStyle": "solid"
}
}
/***/ },
/***/ 553:
/***/ function(module, exports, __webpack_require__) {
'use strict';
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
module.exports = {
components: {
panel: __webpack_require__(381),
styleItem: __webpack_require__(546)
}
};
/***/ },
/***/ 554:
/***/ function(module, exports) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _h('div', [_h('panel', {
attrs: {
"title": "flex-direction",
"type": "primary"
}
}, [_h('div', {
staticClass: ["row"],
staticStyle: {
flexDirection: "row"
}
}, [_h('style-item', {
staticStyle: {
marginRight: "0"
},
attrs: {
"value": "row"
}
}), _h('style-item', {
attrs: {
"type": "1"
}
})]), _h('div', {
staticClass: ["row"],
staticStyle: {
flexDirection: "column"
}
}, [_h('style-item', {
attrs: {
"value": "column"
}
}), _h('style-item', {
attrs: {
"type": "1"
}
})])]), _h('panel', {
attrs: {
"title": "justify-content",
"type": "primary"
}
}, [_h('div', {
staticClass: ["row"],
staticStyle: {
justifyContent: "flex-start"
}
}, [_h('style-item', {
staticStyle: {
marginRight: "0"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0"
},
attrs: {
"type": "1"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0"
}
})]), _h('div', {
staticClass: ["row"],
staticStyle: {
justifyContent: "flex-end"
}
}, [_h('style-item', {
staticStyle: {
marginRight: "0"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0"
},
attrs: {
"type": "1"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0"
}
})]), _h('div', {
staticClass: ["row"],
staticStyle: {
justifyContent: "center"
}
}, [_h('style-item', {
staticStyle: {
marginRight: "0"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0"
},
attrs: {
"type": "1"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0"
}
})]), _h('div', {
staticClass: ["row"],
staticStyle: {
justifyContent: "space-between"
}
}, [_h('style-item', {
staticStyle: {
marginRight: "0"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0"
},
attrs: {
"type": "1"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0"
}
})])]), _h('panel', {
attrs: {
"title": "align-items",
"type": "primary"
}
}, [_h('div', {
staticClass: ["row", "row-align"],
staticStyle: {
alignItems: "flex-start"
}
}, [_h('style-item', {
staticStyle: {
marginRight: "0"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0"
},
attrs: {
"type": "1"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0"
}
})]), _h('div', {
staticClass: ["row", "row-align"],
staticStyle: {
alignItems: "flex-end"
}
}, [_h('style-item', {
staticStyle: {
marginRight: "0"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0"
},
attrs: {
"type": "1"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0"
}
})]), _h('div', {
staticClass: ["row", "row-align"],
staticStyle: {
alignItems: "center"
}
}, [_h('style-item', {
staticStyle: {
marginRight: "0"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0"
},
attrs: {
"type": "1"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0"
}
})]), _h('div', {
staticClass: ["row", "row-align"],
staticStyle: {
alignItems: "stretch"
}
}, [_h('style-item', {
staticStyle: {
marginRight: "0"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0"
},
attrs: {
"type": "1"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0"
}
})])]), _h('panel', {
attrs: {
"title": "flex",
"type": "primary"
}
}, [_h('div', {
staticClass: ["row"],
staticStyle: {
alignItems: "flex-start"
}
}, [_h('style-item', {
staticStyle: {
marginRight: "0"
},
attrs: {
"value": "no flex"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0"
},
attrs: {
"value": "no flex",
"type": "1"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0"
},
attrs: {
"value": "no flex"
}
})]), _h('div', {
staticClass: ["row"],
staticStyle: {
alignItems: "flex-start"
}
}, [_h('style-item', {
staticStyle: {
marginRight: "0"
},
attrs: {
"value": "no flex"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0",
flex: "1"
},
attrs: {
"type": "1",
"value": "flex:1"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0",
flex: "2"
},
attrs: {
"value": "flex:2"
}
})]), _h('div', {
staticClass: ["row"],
staticStyle: {
alignItems: "flex-start"
}
}, [_h('style-item', {
staticStyle: {
marginRight: "0",
flex: "1"
},
attrs: {
"value": "flex:1"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0",
flex: "1"
},
attrs: {
"type": "1",
"value": "flex:1"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0",
flex: "1"
},
attrs: {
"value": "flex:1"
}
})]), _h('div', {
staticClass: ["row"],
staticStyle: {
alignItems: "flex-start"
}
}, [_h('style-item', {
staticStyle: {
marginRight: "0",
flex: "1"
},
attrs: {
"value": "flex:1"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0",
flex: "2"
},
attrs: {
"type": "1",
"value": "flex:2"
}
}), _h('style-item', {
staticStyle: {
marginRight: "0",
flex: "3"
},
attrs: {
"value": "flex:3"
}
})])]), _h('panel', {
attrs: {
"title": "flex-wrap",
"type": "primary"
}
}, [_h('div', {
staticClass: ["row"],
staticStyle: {
flexWrap: "wrap",
backgroundColor: "grey",
padding: "10"
}
}, [_h('style-item', {
attrs: {
"value": "1:wrap"
}
}), _h('style-item', {
attrs: {
"value": "2:wrap"
}
}), _h('style-item', {
attrs: {
"value": "3:wrap"
}
}), _h('style-item', {
attrs: {
"value": "4:wrap"
}
}), _h('style-item', {
attrs: {
"value": "5:wrap"
}
}), _h('style-item', {
attrs: {
"value": "6:wrap"
}
})]), _h('div', {
staticClass: ["row"],
staticStyle: {
flexWrap: "nowrap",
backgroundColor: "grey",
padding: "10"
}
}, [_h('style-item', {
attrs: {
"value": "1:nowrap"
}
}), _h('style-item', {
attrs: {
"value": "2:nowrap"
}
}), _h('style-item', {
attrs: {
"value": "3:nowrap"
}
}), _h('style-item', {
attrs: {
"value": "4:nowrap"
}
}), _h('style-item', {
attrs: {
"value": "5:nowrap"
}
}), _h('style-item', {
attrs: {
"value": "6:nowrap"
}
})])])])
},staticRenderFns: []}
module.exports.render._withStripped = true
/***/ },
/***/ 555:
/***/ function(module, exports) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _h('scroller', [_h('style-box'), _h('style-flex'), _h('panel', {
attrs: {
"title": "opacity",
"type": "primary"
}
}, [_h('div', {
staticStyle: {
flexDirection: "row"
}
}, [_h('style-item', {
staticStyle: {
opacity: "1"
},
attrs: {
"value": "1"
}
}), _h('style-item', {
staticStyle: {
opacity: "0.9"
},
attrs: {
"value": "0.9"
}
}), _h('style-item', {
staticStyle: {
opacity: "0.5"
},
attrs: {
"value": "0.5"
}
}), _h('style-item', {
staticStyle: {
opacity: "0.2"
},
attrs: {
"value": "0.2"
}
})])]), _h('panel', {
attrs: {
"title": "background-color",
"type": "primary"
}
}, [_h('div', [_h('style-item', {
staticClass: ["bg-item"],
staticStyle: {
backgroundColor: "#333"
},
attrs: {
"value": "#333"
}
}), _h('style-item', {
staticClass: ["bg-item"],
staticStyle: {
backgroundColor: "#333333"
},
attrs: {
"value": "#333333"
}
}), _h('style-item', {
staticClass: ["bg-item"],
staticStyle: {
backgroundColor: "rgb(238, 162, 54)"
},
attrs: {
"value": "rgb()"
}
}), _h('style-item', {
staticClass: ["bg-item"],
staticStyle: {
backgroundColor: "rgba(238, 162, 54, 0.5)"
},
attrs: {
"value": "rgba()"
}
}), _h('style-item', {
staticClass: ["bg-item"],
staticStyle: {
backgroundColor: "red"
},
attrs: {
"value": "red"
}
})])])])
},staticRenderFns: []}
module.exports.render._withStripped = true
/***/ }
/******/ }); |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: Operator x >>> y uses [[Default Value]]
es5id: 11.7.3_A2.2_T1
description: If Type(value) is Object, evaluate ToPrimitive(value, Number)
---*/
//CHECK#1
if ({valueOf: function() {return -4}} >>> 1 !== 2147483646) {
$ERROR('#1: {valueOf: function() {return -4}} >>> 1 === 2147483646. Actual: ' + ({valueOf: function() {return -4}} >>> 1));
}
//CHECK#2
if ({valueOf: function() {return -4}, toString: function() {return 0}} >>> 1 !== 2147483646) {
$ERROR('#2: {valueOf: function() {return -4}, toString: function() {return 0}} >>> 1 === 2147483646. Actual: ' + ({valueOf: function() {return -4}, toString: function() {return 0}} >>> 1));
}
//CHECK#3
if ({valueOf: function() {return -4}, toString: function() {return {}}} >>> 1 !== 2147483646) {
$ERROR('#3: {valueOf: function() {return -4}, toString: function() {return {}}} >>> 1 === 2147483646. Actual: ' + ({valueOf: function() {return -4}, toString: function() {return {}}} >>> 1));
}
//CHECK#4
try {
if ({valueOf: function() {return -4}, toString: function() {throw "error"}} >>> 1 !== 2147483646) {
$ERROR('#4.1: {valueOf: function() {return -4}, toString: function() {throw "error"}} >>> 1 === 2147483646. Actual: ' + ({valueOf: function() {return -4}, toString: function() {throw "error"}} >>> 1));
}
}
catch (e) {
if (e === "error") {
$ERROR('#4.2: {valueOf: function() {return -4}, toString: function() {throw "error"}} >>> 1 not throw "error"');
} else {
$ERROR('#4.3: {valueOf: function() {return -4}, toString: function() {throw "error"}} >>> 1 not throw Error. Actual: ' + (e));
}
}
//CHECK#5
if (-4 >>> {toString: function() {return 1}} !== 2147483646) {
$ERROR('#5: -4 >>> {toString: function() {return 1}} === 2147483646. Actual: ' + (-4 >>> {toString: function() {return 1}}));
}
//CHECK#6
if (-4 >>> {valueOf: function() {return {}}, toString: function() {return 1}} !== 2147483646) {
$ERROR('#6: -4 >>> {valueOf: function() {return {}}, toString: function() {return 1}} === 2147483646. Actual: ' + (-4 >>> {valueOf: function() {return {}}, toString: function() {return 1}}));
}
//CHECK#7
try {
-4 >>> {valueOf: function() {throw "error"}, toString: function() {return 1}};
$ERROR('#7.1: -4 >>> {valueOf: function() {throw "error"}, toString: function() {return 1}} throw "error". Actual: ' + (-4 >>> {valueOf: function() {throw "error"}, toString: function() {return 1}}));
}
catch (e) {
if (e !== "error") {
$ERROR('#7.2: -4 >>> {valueOf: function() {throw "error"}, toString: function() {return 1}} throw "error". Actual: ' + (e));
}
}
//CHECK#8
try {
-4 >>> {valueOf: function() {return {}}, toString: function() {return {}}};
$ERROR('#8.1: -4 >>> {valueOf: function() {return {}}, toString: function() {return {}}} throw TypeError. Actual: ' + (e));
}
catch (e) {
if ((e instanceof TypeError) !== true) {
$ERROR('#8.2: -4 >>> {valueOf: function() {return {}}, toString: function() {return {}}} throw TypeError. Actual: ' + (e));
}
}
|
var code = `var foo = 1;
if (x) {
const bar = 1;
}`;
var innerScope = true;
var res = transform(code, {
plugins: opts.plugins.concat([
function (b) {
var t = b.types;
return {
visitor: {
Scope: {
exit: function(path) {
if (innerScope) {
expect(Object.keys(path.scope.bindings)).toHaveLength(0);
innerScope = false;
return;
}
expect(Object.keys(path.scope.bindings)).toHaveLength(2);
}
}
}
}
}
]),
});
var expected = `var foo = 1;
if (x) {
var bar = 1;
}`;
expect(res.code).toBe(expected);
|
/****************************************************************************
The MIT License (MIT)
Copyright (c) 2013 Apigee Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
'use strict';
var _ = require('underscore');
var DEFAULT_TTL = 300;
var EM = require('events').EventEmitter;
var eventEmitter = new EM();
eventEmitter.setMaxListeners(100);
function Cache(Spi, name, options) {
if (!options && _.isObject(name)) { // allow name to be passed as part of options
options = name;
name = options.name;
delete(options.name);
}
this.name = name;
this.options = _.extend({}, options) || {};
this.options.ttl = this.options.ttl ? convertNumber(this.options.ttl, 'ttl') : DEFAULT_TTL;
this.cache = new Spi(name, this.options);
}
module.exports = Cache;
// Set the text encoding for values retrieved from the cache. The value will be returned as a string
// in the specified encoding. If this function is never called, then values will always be returned as buffers.
Cache.prototype.setEncoding = function(encoding) {
this.options.encoding = encoding;
};
// Retrieve an element from cache if present and set it using the provided populate function if not.
// This method will also handle the "thundering herd" issue by coordinating waiting for already in-progress getSet()
// requests and population for the same key.
// The populate (key, callback) function must invoke its callback(error, reply) function on completion. If there is an
// error, it must be passed as the first parameter (otherwise undefined or null). Assuming no error, the second
// parameter is the value passed to the cache.
// The options parameter contains any options to be passed as a part of the cache set() function.
// The callback (error, reply, fromCache) function will be called after all processing has completed. It is called
// immediately (fromCache == true) if the cache contains the item. Otherwise, it will be called once the
// populate function has completed.
// If "setEncoding" was previously called on this cache, then the value will be returned as a string
// in the specified encoding. Otherwise, a Buffer will be returned.
// key, populate, and callback are required. options is optional.
Cache.prototype.getSet = function(key, populate, options, callback) {
validateKey(key);
if (!callback) { callback = options; options = {}; }
if (typeof populate !== 'function') { throw new Error('populate must be a function'); }
if (typeof callback !== 'function') { throw new Error('callback must be a function'); }
var self = this;
this.get(key, function(err, reply) {
if (err || reply) { return callback(err, reply, true); }
var event = self.name + key;
if (EM.listenerCount(eventEmitter, event) === 0) {
eventEmitter.once(event, function(err, reply) {
callback(err, reply, false); // special case for the populate (fromCache == false)
});
} else {
eventEmitter.once(event, callback);
return;
}
populate(key, function(err, reply) {
if (err || !reply) { return eventEmitter.emit(event, err, reply); }
self.set(key, reply, options, function(err) {
if (reply && options.encoding) {
reply = reply.toString(options.encoding);
}
eventEmitter.emit(event, err, reply, true);
});
});
});
};
// Retrieve the element from cache and return as the second argument to "callback". (First argument is
// the error, or undefined if there is no error). It is an error to call this with no callback.
// If "setEncoding" was previously called on this cache, then the value will be returned as a string
// in the specified encoding. Otherwise, a Buffer will be returned.
Cache.prototype.get = function(key, callback) {
validateKey(key);
if (!callback) {
throw new Error('callback is required');
}
if (typeof callback !== 'function') {
throw new Error('callback must be a function');
}
var options = this.options;
this.cache.get(key, function(err, reply) {
if (reply && options.encoding) {
reply = reply.toString(options.encoding);
}
callback(err, reply);
});
};
// Set "value" in the cache under "key". "options" is optional and implementation-dependent.
// If callback is supplied, call it when the set is complete, passing the error as the first
// argument if there is one. If "value" is a string, then it will be converted to a buffer
// using the encoding field set in "options" or "utf8" otherwise.
Cache.prototype.set = function(key, v, o, c) {
validateKey(key);
var callback;
var options;
if (!o) {
options = {};
} else if (typeof o === 'function') {
options = {};
callback = o;
} else {
if (c && typeof c !== 'function') {
throw new Error('callback must be a function');
}
options = o;
callback = c;
}
try {
var value = convertValue(v, options.encoding);
} catch (err) {
return callback(err);
}
options.ttl = options.ttl ? convertNumber(options.ttl, 'ttl') : this.options.ttl;
this.cache.set(key, value, options, callback);
};
// Remove "key" from the cache. If callback is supplied, call it when delete is complete with
// the error as the first element.
Cache.prototype.delete = function(key, callback) {
validateKey(key);
this.cache.delete(key, callback);
};
// Clear the entire cache. If callback is supplied, call it when delete is complete with
// the error as the first element.
Cache.prototype.clear = function(callback) {
this.cache.clear(callback);
};
Cache.prototype.connectMiddleware = function(options) {
var mw = require('./cache-connect');
return new mw(this, options);
};
Cache.prototype.expressMiddleware = Cache.prototype.connectMiddleware;
Cache.prototype.argoMiddleware = function(options) {
var mw = require('./cache-argo');
return new mw(this, options);
};
function validateKey(key) {
if (!key) {
throw new Error('key is required');
}
if (typeof key !== 'string') {
throw new Error('key must be a string');
}
}
function convertValue(value, encoding) {
if (typeof value === 'string') {
return new Buffer(value, encoding);
} else if (value instanceof Buffer) {
return value;
} else {
throw new Error('value must be a string or a Buffer');
}
}
function convertNumber(value, name) {
if (typeof value === 'string') {
return parseInt(value, 10);
} else if (typeof value === 'number') {
return value;
} else {
throw new Error(name + ' must be a string or a number');
}
}
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
/* jshint latedef:false */
/* jshint forin:false */
/* jshint noempty:false */
'use strict';
var msRestAzure = require('ms-rest-azure');
exports.BaseResource = msRestAzure.BaseResource;
exports.CloudError = msRestAzure.CloudError;
exports.Product = require('./product');
exports.ProductProperties = require('./productProperties');
exports.OperationResult = require('./operationResult');
exports.PagingGetMultiplePagesOptions = require('./pagingGetMultiplePagesOptions');
exports.PagingGetOdataMultiplePagesOptions = require('./pagingGetOdataMultiplePagesOptions');
exports.PagingGetMultiplePagesWithOffsetOptions = require('./pagingGetMultiplePagesWithOffsetOptions');
exports.PagingGetMultiplePagesWithOffsetNextOptions = require('./pagingGetMultiplePagesWithOffsetNextOptions');
exports.ProductResult = require('./productResult');
exports.OdataProductResult = require('./odataProductResult');
|
/*! jQuery UI - v1.10.4 - 2014-05-12
* http://jqueryui.com
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(t){t.datepicker.regional["fr-CH"]={closeText:"Fermer",prevText:"<Préc",nextText:"Suiv>",currentText:"Courant",monthNames:["janvier","février","mars","avril","mai","juin","juillet","août","septembre","octobre","novembre","décembre"],monthNamesShort:["janv.","févr.","mars","avril","mai","juin","juil.","août","sept.","oct.","nov.","déc."],dayNames:["dimanche","lundi","mardi","mercredi","jeudi","vendredi","samedi"],dayNamesShort:["dim.","lun.","mar.","mer.","jeu.","ven.","sam."],dayNamesMin:["D","L","M","M","J","V","S"],weekHeader:"Sm",dateFormat:"dd.mm.yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},t.datepicker.setDefaults(t.datepicker.regional["fr-CH"])}); |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'templates', 'hi', {
button: 'टॅम्प्लेट',
emptyListMsg: '(कोई टॅम्प्लेट डिफ़ाइन नहीं किया गया है)',
insertOption: 'मूल शब्दों को बदलें',
options: 'Template Options', // MISSING
selectPromptMsg: 'ऍडिटर में ओपन करने हेतु टॅम्प्लेट चुनें(वर्तमान कन्टॅन्ट सेव नहीं होंगे):',
title: 'कन्टेन्ट टॅम्प्लेट'
});
|
var five = require("../lib/johnny-five.js"),
board, photoresistor;
board = new five.Board();
board.on("ready", function() {
// Create a new `photoresistor` hardware instance.
photoresistor = new five.Sensor({
pin: "A2",
freq: 250
});
// Inject the `sensor` hardware into
// the Repl instance's context;
// allows direct command line access
board.repl.inject({
pot: photoresistor
});
// "data" get the current reading from the photoresistor
photoresistor.on("data", function() {
console.log( this.value );
});
});
// References
//
// http://nakkaya.com/2009/10/29/connecting-a-photoresistor-to-an-arduino/
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Platform
* @flow
*/
'use strict';
const Platform = {
OS: 'ios',
get Version() {
const constants = require('NativeModules').IOSConstants;
return constants ? constants.osVersion : '';
},
get isTVOS() {
const constants = require('NativeModules').IOSConstants;
return constants ? (constants.interfaceIdiom === 'tv') : false;
},
select: (obj: Object) => obj.ios,
};
module.exports = Platform;
|
'use strict';
/**
* Module dependencies.
*/
var fs = require('fs'),
http = require('http'),
https = require('https'),
express = require('express'),
socketio = require('socket.io'),
morgan = require('morgan'),
bodyParser = require('body-parser'),
session = require('express-session'),
compress = require('compression'),
methodOverride = require('method-override'),
cookieParser = require('cookie-parser'),
helmet = require('helmet'),
passport = require('passport'),
mongoStore = require('connect-mongo')({
session: session
}),
flash = require('connect-flash'),
config = require('./config'),
consolidate = require('consolidate'),
path = require('path');
module.exports = function(db) {
// Initialize express app
var app = express();
// Globbing model files
config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) {
require(path.resolve(modelPath));
});
// Setting application local variables
app.locals.title = config.app.title;
app.locals.description = config.app.description;
app.locals.keywords = config.app.keywords;
app.locals.facebookAppId = config.facebook.clientID;
app.locals.jsFiles = config.getJavaScriptAssets();
app.locals.cssFiles = config.getCSSAssets();
// Passing the request url to environment locals
app.use(function(req, res, next) {
res.locals.url = req.protocol + '://' + req.headers.host + req.url;
next();
});
// Should be placed before express.static
app.use(compress({
filter: function(req, res) {
return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
},
level: 9
}));
// Showing stack errors
app.set('showStackError', true);
// Set swig as the template engine
app.engine('server.view.html', consolidate[config.templateEngine]);
// Set views path and view engine
app.set('view engine', 'server.view.html');
app.set('views', './app/views');
// Environment dependent middleware
if (process.env.NODE_ENV === 'development') {
// Enable logger (morgan)
app.use(morgan('dev'));
// Disable views cache
app.set('view cache', false);
} else if (process.env.NODE_ENV === 'production') {
app.locals.cache = 'memory';
}
// Request body parsing middleware should be above methodOverride
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
// CookieParser should be above session
app.use(cookieParser());
// Express MongoDB session storage
app.use(session({
saveUninitialized: true,
resave: true,
secret: config.sessionSecret,
store: new mongoStore({
db: db.connection.db,
collection: config.sessionCollection
})
}));
// use passport session
app.use(passport.initialize());
app.use(passport.session());
// connect flash for flash messages
app.use(flash());
// Use helmet to secure Express headers
app.use(helmet.xframe());
app.use(helmet.xssFilter());
app.use(helmet.nosniff());
app.use(helmet.ienoopen());
app.disable('x-powered-by');
// Setting the app router and static folder
app.use(express.static(path.resolve('./public')));
// Globbing routing files
config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
require(path.resolve(routePath))(app);
});
// Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
app.use(function(err, req, res, next) {
// If the error object doesn't exists
if (!err) return next();
// Log it
console.error(err.stack);
// Error page
res.status(500).render('500', {
error: err.stack
});
});
// Assume 404 since no middleware responded
app.use(function(req, res) {
res.status(404).render('404', {
url: req.originalUrl,
error: 'Not Found'
});
});
if (process.env.NODE_ENV === 'secure') {
// Log SSL usage
console.log('Securely using https protocol');
// Load SSL key and certificate
var privateKey = fs.readFileSync('./config/sslcerts/key.pem', 'utf8');
var certificate = fs.readFileSync('./config/sslcerts/cert.pem', 'utf8');
// Create HTTPS Server
var httpsServer = https.createServer({
key: privateKey,
cert: certificate
}, app);
// Return HTTPS server instance
return httpsServer;
}
// Use Socket.io
var server = http.createServer(app);
var io = socketio.listen(server);
app.set('socketio', io);
app.set('server', server);
// Return Express server instance
return app;
}; |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'colordialog', 'zh', {
clear: 'Clear', // MISSING
highlight: 'Highlight', // MISSING
options: 'Color Options', // MISSING
selected: 'Selected Color', // MISSING
title: 'Select color' // MISSING
});
|
'use strict';
var assert = require('assert');
var fs = require('fs');
var os = require('os');
var asar = require('../lib/asar');
var compDirs = require('./util/compareDirectories');
describe('api', function() {
it('should create archive from directory', function(done) {
asar.createPackage('test/input/packthis/', 'tmp/packthis-api.asar', function (error) {
var actual = fs.readFileSync('tmp/packthis-api.asar', 'utf8');
var expected = fs.readFileSync('test/expected/packthis.asar', 'utf8');
done(assert.equal(actual, expected));
});
});
it('should list files/dirs in archive', function() {
var actual = asar.listPackage('test/input/extractthis.asar').join('\n');
var expected = fs.readFileSync('test/expected/extractthis-filelist.txt', 'utf8');
// on windows replace slashes with backslashes and crlf with lf
if ('win32' === os.platform())
expected = expected.replace(/\//g, '\\').replace(/\r\n/g, '\n');
return assert.equal(actual, expected);
});
it('should extract a text file from archive', function() {
var actual = asar.extractFile('test/input/extractthis.asar', 'dir1/file1.txt').toString('utf8');
var expected = fs.readFileSync('test/expected/extractthis/dir1/file1.txt', 'utf8');
// on windows replace crlf with lf
if ('win32' === os.platform())
expected = expected.replace(/\r\n/g, '\n');
return assert.equal(actual, expected);
});
it('should extract a binary file from archive', function() {
var actual = asar.extractFile('test/input/extractthis.asar', 'dir2/file2.png');
var expected = fs.readFileSync('test/expected/extractthis/dir2/file2.png', 'utf8');
return assert.equal(actual, expected);
});
it('should extract a binary file from archive with unpacked files', function() {
var actual = asar.extractFile('test/input/extractthis-unpack.asar', 'dir2/file2.png');
var expected = fs.readFileSync('test/expected/extractthis/dir2/file2.png', 'utf8');
return assert.equal(actual, expected);
});
it('should extract an archive', function(done) {
asar.extractAll('test/input/extractthis.asar','tmp/extractthis-api/');
compDirs('tmp/extractthis-api/', 'test/expected/extractthis', done);
});
it('should extract an archive with unpacked files', function(done) {
asar.extractAll('test/input/extractthis-unpack.asar','tmp/extractthis-unpack-api/');
compDirs('tmp/extractthis-api/', 'test/expected/extractthis', done);
});
});
|
(function () {
TaxonomyTranslation.models.Term = Backbone.Model.extend({
idAttribute: "term_taxonomy_id",
defaults: function () {
return {
name: false,
trid: false,
term_taxonomy_id: false,
language_code: false,
slug: false,
parent: false,
correctedParent: false,
description: false,
level: 0,
correctedLevel: 0,
source_language_code: false,
meta_data: false
};
},
save: function (name, slug, description, meta_data) {
var self = this;
slug = slug ? slug : '';
description = description ? description : '';
if (name) {
jQuery.ajax({
url: ajaxurl,
type: "POST",
data: {
action: 'wpml_save_term',
name: name,
slug: slug,
_icl_nonce: labels.wpml_save_term_nonce,
description: description,
trid: self.get("trid"),
term_language_code: self.get("language_code"),
taxonomy: TaxonomyTranslation.classes.taxonomy.get("taxonomy"),
meta_data: meta_data,
force_hierarchical_sync: true
},
success: function (response) {
var newTermData = response.data;
if (newTermData.language_code && newTermData.trid && newTermData.slug && newTermData.term_taxonomy_id) {
self.set(newTermData);
self.trigger("translationSaved");
WPML_Translate_taxonomy.callbacks.fire('wpml_tt_save_term_translation', TaxonomyTranslation.classes.taxonomy.get("taxonomy"));
} else {
self.trigger("saveFailed");
}
return self;
},
error: function(){
self.trigger("saveFailed");
return self;
}
});
}
},
isOriginal: function() {
return this.get( 'source_language_code' ) === null;
},
getNameSlugAndDescription: function () {
var self = this;
var term = {};
term.slug = self.getSlug();
term.description = self.get("description");
if ( ! term.description ) {
term.description = "";
}
term.name = self.get("name");
if ( ! term.name) {
term.name = "";
}
return term;
},
getSlug: function () {
var self = this;
var slug = self.get("slug");
if (!slug) {
slug = "";
}
slug = decodeURIComponent(slug);
return slug;
},
getMetaData: function() {
return this.get('meta_data');
}
});
})(TaxonomyTranslation);
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'toolbar', 'nb', {
toolbarCollapse: 'Skjul verktøylinje',
toolbarExpand: 'Vis verktøylinje',
toolbarGroups: {
document: 'Dokument',
clipboard: 'Utklippstavle/Angre',
editing: 'Redigering',
forms: 'Skjema',
basicstyles: 'Basisstiler',
paragraph: 'Avsnitt',
links: 'Lenker',
insert: 'Innsetting',
styles: 'Stiler',
colors: 'Farger',
tools: 'Verktøy'
},
toolbars: 'Verktøylinjer for editor'
});
|
'use strict';
var isPromise = require('../../is-promise')
, deferred = require('../../deferred');
module.exports = function (t) {
var x = {}, y = {}, e = new Error();
return {
Limit: function (a) {
a.deep(t([x, 34, 'raz'], 2), [x, 34]);
},
Extend: function (a) {
a.deep(t([x, 34, 'raz'], 5), [x, 34, 'raz', undefined, undefined]);
},
"Promise arguments": {
Resolved: {
"": function (a) {
a.deep(t([x, deferred(y), 'dwa', deferred(null)]),
[x, y, 'dwa', null]);
},
Error: function (a) {
var p = deferred(e);
a(t([x, p, 'dwa', deferred(null)]), p);
}
},
Unresolved: {
"": function (a) {
var py = deferred(), px = deferred(), p;
p = t([x, py.promise, 'dwa', px.promise]);
a(isPromise(p), true, "Promise");
p.done(function (args) {
a.deep(args, [x, y, 'dwa', x]);
}, a.never);
py.resolve(y);
px.resolve(x);
},
Error: function (a) {
var py = deferred(), px = deferred(), p;
p = t([x, py.promise, 'dwa', px.promise]);
a(isPromise(p), true, "Promise");
p.done(a.never, function (err) {
a(err, e);
});
py.resolve(y);
px.reject(e);
}
}
}
};
};
|
define(['./underscore', './_baseIteratee', './iteratee'], function (underscore, _baseIteratee, iteratee) {
// The function we call internally to generate a callback. It invokes
// `_.iteratee` if overridden, otherwise `baseIteratee`.
function cb(value, context, argCount) {
if (underscore.iteratee !== iteratee) return underscore.iteratee(value, context);
return _baseIteratee(value, context, argCount);
}
return cb;
});
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react'), require('glamor')) :
typeof define === 'function' && define.amd ? define(['react', 'glamor'], factory) :
(global.glamorous = factory(global.React,global.Glamor));
}(this, (function (React,glamor) { 'use strict';
React = React && React.hasOwnProperty('default') ? React['default'] : React;
var CHANNEL = '__glamorous__'; /* istanbul ignore next */
var isPreact = false;
var _PropTypes = void 0;
/* istanbul ignore next */
if (isPreact) {
if (!React.PropTypes) {
_PropTypes = function PropTypes() {
return _PropTypes;
};
['array', 'bool', 'func', 'number', 'object', 'string', 'symbol', 'any', 'arrayOf', 'element', 'instanceOf', 'node', 'objectOf', 'oneOf', 'oneOfType', 'shape', 'exact'].forEach(function (type) {
_PropTypes[type] = _PropTypes;
});
}
// copied from preact-compat
/* eslint-disable no-eq-null, eqeqeq, consistent-return */
if (!React.Children) {
var Children = {
map: function map(children, fn, ctx) {
if (children == null) {
return null;
}
children = Children.toArray(children);
if (ctx && ctx !== children) {
fn = fn.bind(ctx);
}
return children.map(fn);
},
forEach: function forEach(children, fn, ctx) {
if (children == null) {
return null;
}
children = Children.toArray(children);
if (ctx && ctx !== children) {
fn = fn.bind(ctx);
}
children.forEach(fn);
},
count: function count(children) {
return children && children.length || 0;
},
only: function only(children) {
children = Children.toArray(children);
if (children.length !== 1) {
throw new Error('Children.only() expects only one child.');
}
return children[0];
},
toArray: function toArray(children) {
if (children == null) {
return [];
}
return [].concat(children);
}
};
React.Children = Children;
}
/* eslint-enable no-eq-null, eqeqeq, consistent-return */
} else if (parseFloat(React.version.slice(0, 4)) >= 15.5) {
/* istanbul ignore next */
try {
_PropTypes = (typeof window !== 'undefined' ? window : global).PropTypes;
/* istanbul ignore next */
} catch (error) {
// ignore
}
}
/* istanbul ignore next */
_PropTypes = _PropTypes || React.PropTypes;
/*
eslint
import/no-mutable-exports:0,
import/prefer-default-export:0,
react/no-deprecated:0
*/
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
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 inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var objectWithoutProperties = function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
function generateWarningMessage(Comp) {
var componentName = Comp.displayName || Comp.name || 'FunctionComponent';
// eslint-disable-next-line max-len
return 'glamorous warning: Expected component called "' + componentName + '" which uses withTheme to be within a ThemeProvider but none was found.';
}
function withTheme(ComponentToTheme) {
var _defaultContextTypes;
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref$noWarn = _ref.noWarn,
noWarn = _ref$noWarn === undefined ? false : _ref$noWarn,
_ref$createElement = _ref.createElement,
createElement = _ref$createElement === undefined ? true : _ref$createElement;
var ThemedComponent = function (_React$Component) {
inherits(ThemedComponent, _React$Component);
function ThemedComponent() {
var _temp, _this, _ret;
classCallCheck(this, ThemedComponent);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.warned = noWarn, _this.state = { theme: {} }, _this.setTheme = function (theme) {
return _this.setState({ theme: theme });
}, _temp), possibleConstructorReturn(_this, _ret);
}
// eslint-disable-next-line complexity
ThemedComponent.prototype.componentWillMount = function componentWillMount() {
if (!this.context[CHANNEL]) {
if ('development' !== 'production' && !this.warned) {
this.warned = true;
// eslint-disable-next-line no-console
console.warn(generateWarningMessage(ComponentToTheme));
}
}
var theme = this.props.theme;
if (this.context[CHANNEL]) {
// if a theme is provided via props,
// it takes precedence over context
this.setTheme(theme ? theme : this.context[CHANNEL].getState());
} else {
this.setTheme(theme || {});
}
};
ThemedComponent.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (this.props.theme !== nextProps.theme) {
this.setTheme(nextProps.theme);
}
};
ThemedComponent.prototype.componentDidMount = function componentDidMount() {
if (this.context[CHANNEL] && !this.props.theme) {
// subscribe to future theme changes
this.subscriptionId = this.context[CHANNEL].subscribe(this.setTheme);
}
};
ThemedComponent.prototype.componentWillUnmount = function componentWillUnmount() {
// cleanup subscription
this.subscriptionId && this.context[CHANNEL].unsubscribe(this.subscriptionId);
};
ThemedComponent.prototype.render = function render() {
if (createElement) {
return React.createElement(ComponentToTheme, _extends({}, this.props, this.state));
} else {
// this allows us to effectively use the GlamorousComponent
// as our `render` method without going through lifecycle hooks.
// Also allows us to forward the context in the scenario where
// a user wants to add more context.
// eslint-disable-next-line babel/new-cap
return ComponentToTheme.call(this, _extends({}, this.props, this.state), this.context);
}
};
return ThemedComponent;
}(React.Component);
ThemedComponent.propTypes = {
theme: _PropTypes.object
};
var defaultContextTypes = (_defaultContextTypes = {}, _defaultContextTypes[CHANNEL] = _PropTypes.object, _defaultContextTypes);
var userDefinedContextTypes = null;
// configure the contextTypes to be settable by the user,
// however also retaining the glamorous channel.
Object.defineProperty(ThemedComponent, 'contextTypes', {
enumerable: true,
configurable: true,
set: function set$$1(value) {
userDefinedContextTypes = value;
},
get: function get$$1() {
// if the user has provided a contextTypes definition,
// merge the default context types with the provided ones.
if (userDefinedContextTypes) {
return _extends({}, defaultContextTypes, userDefinedContextTypes);
}
return defaultContextTypes;
}
});
return ThemedComponent;
}
/**
* This function takes a className string and gets all the
* associated glamor styles. It's used to merge glamor styles
* from a className to make sure that specificity is not
* a problem when passing a className to a component.
* @param {String} [className=''] the className string
* @return {Object} { glamorStyles, glamorlessClassName }
* - glamorStyles is an array of all the glamor styles objects
* - glamorlessClassName is the rest of the className string
* without the glamor classNames
*/
function extractGlamorStyles(className) {
var glamorlessClassName = [];
var glamorStyles = [];
className.toString().split(' ').forEach(function (name) {
if (name.indexOf('css-') === 0) {
var style = buildGlamorSrcFromClassName(name);
glamorStyles.push(style);
} else {
glamorlessClassName.push(name);
}
});
return { glamorlessClassName: glamorlessClassName, glamorStyles: glamorStyles };
}
/** Glamor's css function returns an object with the shape
*
* {
* [`data-css-${hash}`]: '',
* toString() { return `css-${hash}` }
* }
*
* Whenever glamor's build function encounters an object with
* this shape it just pulls the resulting styles from the cache.
*
* note: the toString method is not needed to qualify the shape
**/
function buildGlamorSrcFromClassName(className) {
var _ref;
return _ref = {}, _ref['data-' + className] = '', _ref;
}
function getGlamorClassName(_ref2) {
var styles = _ref2.styles,
props = _ref2.props,
cssOverrides = _ref2.cssOverrides,
cssProp = _ref2.cssProp,
context = _ref2.context,
displayName = _ref2.displayName;
var _handleStyles = handleStyles([].concat(styles, [props.className, cssOverrides, cssProp]), props, context),
mappedArgs = _handleStyles.mappedArgs,
nonGlamorClassNames = _handleStyles.nonGlamorClassNames;
// eslint-disable-next-line max-len
var devRules = { label: displayName };
var glamorClassName = glamor.css.apply(undefined, [devRules].concat(mappedArgs)).toString();
var extras = nonGlamorClassNames.join(' ').trim();
return (glamorClassName + ' ' + extras).trim();
}
// this next function is on a "hot" code-path
// so it's pretty complex to make sure it's fast.
// eslint-disable-next-line complexity
function handleStyles(styles, props, context) {
var current = void 0;
var mappedArgs = [];
var nonGlamorClassNames = [];
for (var i = 0; i < styles.length; i++) {
current = styles[i];
while (typeof current === 'function') {
current = current(props, context);
}
if (typeof current === 'string') {
var _extractGlamorStyles = extractGlamorStyles(current),
glamorStyles = _extractGlamorStyles.glamorStyles,
glamorlessClassName = _extractGlamorStyles.glamorlessClassName;
mappedArgs.push.apply(mappedArgs, glamorStyles);
nonGlamorClassNames.push.apply(nonGlamorClassNames, glamorlessClassName);
} else if (Array.isArray(current)) {
var recursed = handleStyles(current, props, context);
mappedArgs.push.apply(mappedArgs, recursed.mappedArgs);
nonGlamorClassNames.push.apply(nonGlamorClassNames, recursed.nonGlamorClassNames);
} else {
mappedArgs.push(current);
}
}
return { mappedArgs: mappedArgs, nonGlamorClassNames: nonGlamorClassNames };
}
/*
* This is a relatively small abstraction that's ripe for open sourcing.
* Documentation is in the README.md
*/
function createGlamorous(splitProps) {
return glamorous;
/**
* This is the main export and the function that people
* interact with most directly.
*
* It accepts a component which can be a string or
* a React Component and returns
* a "glamorousComponentFactory"
* @param {String|ReactComponent} comp the component to render
* @param {Object} options helpful info for the GlamorousComponents
* @return {Function} the glamorousComponentFactory
*/
function glamorous(comp) {
var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var rootEl = config.rootEl,
displayName = config.displayName,
shouldClassNameUpdate = config.shouldClassNameUpdate,
_config$filterProps = config.filterProps,
filterProps = _config$filterProps === undefined ? [] : _config$filterProps,
_config$forwardProps = config.forwardProps,
forwardProps = _config$forwardProps === undefined ? [] : _config$forwardProps,
_config$propsAreCssOv = config.propsAreCssOverrides,
propsAreCssOverrides = _config$propsAreCssOv === undefined ? comp.propsAreCssOverrides : _config$propsAreCssOv,
basePropsToApply = config.withProps;
Object.assign(glamorousComponentFactory, { withConfig: withConfig });
return glamorousComponentFactory;
function withConfig(newConfig) {
return glamorous(comp, _extends({}, config, newConfig));
}
/**
* This returns a React Component that renders the comp (closure)
* with a className based on the given glamor styles object(s)
* @param {...Object|Function} styles the styles to create with glamor.
* If any of these are functions, they are invoked with the component
* props and the return value is used.
* @return {ReactComponent} the ReactComponent function
*/
function glamorousComponentFactory() {
for (var _len = arguments.length, styles = Array(_len), _key = 0; _key < _len; _key++) {
styles[_key] = arguments[_key];
}
/**
* This is a component which will render the comp (closure)
* with the glamorous styles (closure). Forwards any valid
* props to the underlying component.
*/
var GlamorousComponent = withTheme(function (props, context) {
props = getPropsToApply(GlamorousComponent.propsToApply, {}, props, context);
var updateClassName = shouldUpdate(props, context, this.previous);
if (shouldClassNameUpdate) {
this.previous = { props: props, context: context };
}
var _splitProps = splitProps(props, GlamorousComponent),
toForward = _splitProps.toForward,
cssOverrides = _splitProps.cssOverrides,
cssProp = _splitProps.cssProp;
// create className to apply
this.className = updateClassName ? getGlamorClassName({
styles: GlamorousComponent.styles,
props: props,
cssOverrides: cssOverrides,
cssProp: cssProp,
context: context,
displayName: GlamorousComponent.displayName
}) : this.className;
return React.createElement(GlamorousComponent.comp, _extends({
// if innerRef is forwarded we don't want to apply it here
ref: 'innerRef' in toForward ? undefined : props.innerRef
}, toForward, {
className: this.className
}));
}, { noWarn: true, createElement: false });
GlamorousComponent.propTypes = {
// className accepts an object due to glamor's css function
// returning an object with a toString method that gives the className
className: _PropTypes.oneOfType([_PropTypes.string, _PropTypes.object]),
cssOverrides: _PropTypes.object,
innerRef: _PropTypes.func,
glam: _PropTypes.object
};
function shouldUpdate(props, context, previous) {
// exiting early so components which do not use this
// optimization are not penalized by hanging onto
// references to previous props and context
if (!shouldClassNameUpdate) {
return true;
}
var update = true;
if (previous) {
if (!shouldClassNameUpdate(previous.props, props, previous.context, context)) {
update = false;
}
}
return update;
}
Object.assign(GlamorousComponent, getGlamorousComponentMetadata({
comp: comp,
styles: styles,
rootEl: rootEl,
filterProps: filterProps,
forwardProps: forwardProps,
displayName: displayName,
propsToApply: basePropsToApply
}), {
isGlamorousComponent: true,
propsAreCssOverrides: propsAreCssOverrides,
withComponent: function (newComp) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var fwp = GlamorousComponent.forwardProps,
flp = GlamorousComponent.filterProps,
componentProperties = objectWithoutProperties(GlamorousComponent, ['forwardProps', 'filterProps']);
return glamorous(_extends({}, componentProperties, {
comp: newComp,
rootEl: getRootEl(newComp)
}), _extends({
// allows the forwardProps and filterProps to be overridden
forwardProps: fwp,
filterProps: flp
}, options))();
},
withProps: function () {
for (var _len2 = arguments.length, propsToApply = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
propsToApply[_key2] = arguments[_key2];
}
return glamorous(GlamorousComponent, { withProps: propsToApply })();
},
withConfig: withConfig
});
return GlamorousComponent;
}
}
function getGlamorousComponentMetadata(_ref) {
var comp = _ref.comp,
styles = _ref.styles,
rootEl = _ref.rootEl,
filterProps = _ref.filterProps,
forwardProps = _ref.forwardProps,
displayName = _ref.displayName,
basePropsToApply = _ref.propsToApply;
var componentsComp = comp.comp ? comp.comp : comp;
var propsToApply = comp.propsToApply ? [].concat(comp.propsToApply, arrayify(basePropsToApply)) : arrayify(basePropsToApply);
return {
// join styles together (for anyone doing: glamorous(glamorous.a({}), {}))
styles: when(comp.styles, styles),
// keep track of the ultimate rootEl to render (we never
// actually render anything but
// the base component, even when people wrap a glamorous
// component in glamorous
comp: componentsComp,
rootEl: rootEl || getRootEl(comp),
// join forwardProps and filterProps
// (for anyone doing: glamorous(glamorous.a({}), {}))
forwardProps: when(comp.forwardProps, forwardProps),
filterProps: when(comp.filterProps, filterProps),
// set the displayName to something that's slightly more
// helpful than `GlamorousComponent` :)
displayName: displayName || 'glamorous(' + getDisplayName(comp) + ')',
// these are props that should be applied to the component at render time
propsToApply: propsToApply
};
}
}
/**
* reduces the propsToApply given to a single props object
* @param {Array} propsToApply an array of propsToApply objects:
* - object
* - array of propsToApply items
* - function that accepts the accumulated props and the context
* @param {Object} accumulator an object to apply props onto
* @param {Object} props the props that should ultimately take precedence
* @param {*} context the context object
* @return {Object} the reduced props
*/
function getPropsToApply(propsToApply, accumulator, props, context) {
// using forEach rather than reduce here because the reduce solution
// effectively did the same thing because we manipulate the `accumulator`
propsToApply.forEach(function (propsToApplyItem) {
if (typeof propsToApplyItem === 'function') {
return Object.assign(accumulator, propsToApplyItem(Object.assign({}, accumulator, props), context));
} else if (Array.isArray(propsToApplyItem)) {
return Object.assign(accumulator, getPropsToApply(propsToApplyItem, accumulator, props, context));
}
return Object.assign(accumulator, propsToApplyItem);
});
// props wins
return Object.assign(accumulator, props);
}
function arrayify() {
var x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
return Array.isArray(x) ? x : [x];
}
function when(comp, prop) {
return comp ? comp.concat(prop) : prop;
}
function getRootEl(comp) {
return comp.rootEl ? comp.rootEl : comp.comp || comp;
}
function getDisplayName(comp) {
return typeof comp === 'string' ? comp : comp.displayName || comp.name || 'unknown';
}
/* eslint no-unused-vars:0 */
function splitProps(_ref, _ref2) {
var forwardProps = _ref2.forwardProps;
var cssProp = _ref.css,
innerRef = _ref.innerRef,
theme = _ref.theme,
className = _ref.className,
glam = _ref.glam,
rest = objectWithoutProperties(_ref, ['css', 'innerRef', 'theme', 'className', 'glam']);
// forward innerRef if user wishes to do so
if (innerRef !== undefined && forwardProps.indexOf('innerRef') !== -1) {
rest.innerRef = innerRef;
}
return { toForward: rest, cssProp: cssProp };
}
var glamorous = createGlamorous(splitProps);
return glamorous;
})));
//# sourceMappingURL=glamorous.umd.tiny.js.map
|
/**
*
* @authors Your Name (you@example.org)
* @date 2015-10-30 14:50:51
* @version $Id$
*/
$(function(){
dropdown.init();
}); |
/* *
* (c) 2010-2019 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
import H from './Globals.js';
import './Utilities.js';
var Axis = H.Axis,
getMagnitude = H.getMagnitude,
normalizeTickInterval = H.normalizeTickInterval,
timeUnits = H.timeUnits;
/**
* Set the tick positions to a time unit that makes sense, for example
* on the first of each month or on every Monday. Return an array
* with the time positions. Used in datetime axes as well as for grouping
* data on a datetime axis.
*
* @private
* @function Highcharts.Axis#getTimeTicks
*
* @param {*} normalizedInterval
* The interval in axis values (ms) and thecount
*
* @param {number} min
* The minimum in axis values
*
* @param {number} max
* The maximum in axis values
*
* @param {number} startOfWeek
*
* @return {number}
*/
Axis.prototype.getTimeTicks = function () {
return this.chart.time.getTimeTicks.apply(this.chart.time, arguments);
};
/**
* Get a normalized tick interval for dates. Returns a configuration object with
* unit range (interval), count and name. Used to prepare data for getTimeTicks.
* Previously this logic was part of getTimeTicks, but as getTimeTicks now runs
* of segments in stock charts, the normalizing logic was extracted in order to
* prevent it for running over again for each segment having the same interval.
* #662, #697.
*
* @private
* @function Highcharts.Axis#normalizeTimeTickInterval
*
* @param {number} tickInterval
*
* @param {Array<Array<number|string>>} [unitsOption]
*
* @return {*}
*/
Axis.prototype.normalizeTimeTickInterval = function (
tickInterval,
unitsOption
) {
var units = unitsOption || [[
'millisecond', // unit name
[1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples
], [
'second',
[1, 2, 5, 10, 15, 30]
], [
'minute',
[1, 2, 5, 10, 15, 30]
], [
'hour',
[1, 2, 3, 4, 6, 8, 12]
], [
'day',
[1, 2]
], [
'week',
[1, 2]
], [
'month',
[1, 2, 3, 4, 6]
], [
'year',
null
]],
unit = units[units.length - 1], // default unit is years
interval = timeUnits[unit[0]],
multiples = unit[1],
count,
i;
// loop through the units to find the one that best fits the tickInterval
for (i = 0; i < units.length; i++) {
unit = units[i];
interval = timeUnits[unit[0]];
multiples = unit[1];
if (units[i + 1]) {
// lessThan is in the middle between the highest multiple and the
// next unit.
var lessThan = (interval * multiples[multiples.length - 1] +
timeUnits[units[i + 1][0]]) / 2;
// break and keep the current unit
if (tickInterval <= lessThan) {
break;
}
}
}
// prevent 2.5 years intervals, though 25, 250 etc. are allowed
if (interval === timeUnits.year && tickInterval < 5 * interval) {
multiples = [1, 2, 5];
}
// get the count
count = normalizeTickInterval(
tickInterval / interval,
multiples,
unit[0] === 'year' ?
Math.max(getMagnitude(tickInterval / interval), 1) : // #1913, #2360
1
);
return {
unitRange: interval,
count: count,
unitName: unit[0]
};
};
|
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Undo/Redo system for saving shapshot for document modification
* and other recordable changes.
*/
(function()
{
CKEDITOR.plugins.add( 'undo',
{
requires : [ 'selection', 'wysiwygarea' ],
init : function( editor )
{
var undoManager = new UndoManager( editor );
var undoCommand = editor.addCommand( 'undo',
{
exec : function()
{
if ( undoManager.undo() )
{
editor.selectionChange();
this.fire( 'afterUndo' );
}
},
state : CKEDITOR.TRISTATE_DISABLED,
canUndo : false
});
var redoCommand = editor.addCommand( 'redo',
{
exec : function()
{
if ( undoManager.redo() )
{
editor.selectionChange();
this.fire( 'afterRedo' );
}
},
state : CKEDITOR.TRISTATE_DISABLED,
canUndo : false
});
undoManager.onChange = function()
{
undoCommand.setState( undoManager.undoable() ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED );
redoCommand.setState( undoManager.redoable() ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED );
};
function recordCommand( event )
{
// If the command hasn't been marked to not support undo.
if ( undoManager.enabled && event.data.command.canUndo !== false )
undoManager.save();
}
// We'll save snapshots before and after executing a command.
editor.on( 'beforeCommandExec', recordCommand );
editor.on( 'afterCommandExec', recordCommand );
// Save snapshots before doing custom changes.
editor.on( 'saveSnapshot', function( evt )
{
undoManager.save( evt.data && evt.data.contentOnly );
});
// Registering keydown on every document recreation.(#3844)
editor.on( 'contentDom', function()
{
editor.document.on( 'keydown', function( event )
{
// Do not capture CTRL hotkeys.
if ( !event.data.$.ctrlKey && !event.data.$.metaKey )
undoManager.type( event );
});
});
// Always save an undo snapshot - the previous mode might have
// changed editor contents.
editor.on( 'beforeModeUnload', function()
{
editor.mode == 'wysiwyg' && undoManager.save( true );
});
// Make the undo manager available only in wysiwyg mode.
editor.on( 'mode', function()
{
undoManager.enabled = editor.readOnly ? false : editor.mode == 'wysiwyg';
undoManager.onChange();
});
editor.ui.addButton( 'Undo',
{
label : editor.lang.undo,
command : 'undo'
});
editor.ui.addButton( 'Redo',
{
label : editor.lang.redo,
command : 'redo'
});
editor.resetUndo = function()
{
// Reset the undo stack.
undoManager.reset();
// Create the first image.
editor.fire( 'saveSnapshot' );
};
/**
* Amend the top of undo stack (last undo image) with the current DOM changes.
* @name CKEDITOR.editor#updateUndo
* @example
* function()
* {
* editor.fire( 'saveSnapshot' );
* editor.document.body.append(...);
* // Make new changes following the last undo snapshot part of it.
* editor.fire( 'updateSnapshot' );
* ...
* }
*/
editor.on( 'updateSnapshot', function()
{
if ( undoManager.currentImage )
undoManager.update();
});
}
});
CKEDITOR.plugins.undo = {};
/**
* Undo snapshot which represents the current document status.
* @name CKEDITOR.plugins.undo.Image
* @param editor The editor instance on which the image is created.
*/
var Image = CKEDITOR.plugins.undo.Image = function( editor )
{
this.editor = editor;
editor.fire( 'beforeUndoImage' );
var contents = editor.getSnapshot(),
selection = contents && editor.getSelection();
// In IE, we need to remove the expando attributes.
CKEDITOR.env.ie && contents && ( contents = contents.replace( /\s+data-cke-expando=".*?"/g, '' ) );
this.contents = contents;
this.bookmarks = selection && selection.createBookmarks2( true );
editor.fire( 'afterUndoImage' );
};
// Attributes that browser may changing them when setting via innerHTML.
var protectedAttrs = /\b(?:href|src|name)="[^"]*?"/gi;
Image.prototype =
{
equals : function( otherImage, contentOnly )
{
var thisContents = this.contents,
otherContents = otherImage.contents;
// For IE6/7 : Comparing only the protected attribute values but not the original ones.(#4522)
if ( CKEDITOR.env.ie && ( CKEDITOR.env.ie7Compat || CKEDITOR.env.ie6Compat ) )
{
thisContents = thisContents.replace( protectedAttrs, '' );
otherContents = otherContents.replace( protectedAttrs, '' );
}
if ( thisContents != otherContents )
return false;
if ( contentOnly )
return true;
var bookmarksA = this.bookmarks,
bookmarksB = otherImage.bookmarks;
if ( bookmarksA || bookmarksB )
{
if ( !bookmarksA || !bookmarksB || bookmarksA.length != bookmarksB.length )
return false;
for ( var i = 0 ; i < bookmarksA.length ; i++ )
{
var bookmarkA = bookmarksA[ i ],
bookmarkB = bookmarksB[ i ];
if (
bookmarkA.startOffset != bookmarkB.startOffset ||
bookmarkA.endOffset != bookmarkB.endOffset ||
!CKEDITOR.tools.arrayCompare( bookmarkA.start, bookmarkB.start ) ||
!CKEDITOR.tools.arrayCompare( bookmarkA.end, bookmarkB.end ) )
{
return false;
}
}
}
return true;
}
};
/**
* @constructor Main logic for Redo/Undo feature.
*/
function UndoManager( editor )
{
this.editor = editor;
// Reset the undo stack.
this.reset();
}
var editingKeyCodes = { /*Backspace*/ 8:1, /*Delete*/ 46:1 },
modifierKeyCodes = { /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1 },
navigationKeyCodes = { 37:1, 38:1, 39:1, 40:1 }; // Arrows: L, T, R, B
UndoManager.prototype =
{
/**
* Process undo system regard keystrikes.
* @param {CKEDITOR.dom.event} event
*/
type : function( event )
{
var keystroke = event && event.data.getKey(),
isModifierKey = keystroke in modifierKeyCodes,
isEditingKey = keystroke in editingKeyCodes,
wasEditingKey = this.lastKeystroke in editingKeyCodes,
sameAsLastEditingKey = isEditingKey && keystroke == this.lastKeystroke,
// Keystrokes which navigation through contents.
isReset = keystroke in navigationKeyCodes,
wasReset = this.lastKeystroke in navigationKeyCodes,
// Keystrokes which just introduce new contents.
isContent = ( !isEditingKey && !isReset ),
// Create undo snap for every different modifier key.
modifierSnapshot = ( isEditingKey && !sameAsLastEditingKey ),
// Create undo snap on the following cases:
// 1. Just start to type .
// 2. Typing some content after a modifier.
// 3. Typing some content after make a visible selection.
startedTyping = !( isModifierKey || this.typing )
|| ( isContent && ( wasEditingKey || wasReset ) );
if ( startedTyping || modifierSnapshot )
{
var beforeTypeImage = new Image( this.editor ),
beforeTypeCount = this.snapshots.length;
// Use setTimeout, so we give the necessary time to the
// browser to insert the character into the DOM.
CKEDITOR.tools.setTimeout( function()
{
var currentSnapshot = this.editor.getSnapshot();
// In IE, we need to remove the expando attributes.
if ( CKEDITOR.env.ie )
currentSnapshot = currentSnapshot.replace( /\s+data-cke-expando=".*?"/g, '' );
// If changes have taken place, while not been captured yet (#8459),
// compensate the snapshot.
if ( beforeTypeImage.contents != currentSnapshot &&
beforeTypeCount == this.snapshots.length )
{
// It's safe to now indicate typing state.
this.typing = true;
// This's a special save, with specified snapshot
// and without auto 'fireChange'.
if ( !this.save( false, beforeTypeImage, false ) )
// Drop future snapshots.
this.snapshots.splice( this.index + 1, this.snapshots.length - this.index - 1 );
this.hasUndo = true;
this.hasRedo = false;
this.typesCount = 1;
this.modifiersCount = 1;
this.onChange();
}
},
0, this
);
}
this.lastKeystroke = keystroke;
// Create undo snap after typed too much (over 25 times).
if ( isEditingKey )
{
this.typesCount = 0;
this.modifiersCount++;
if ( this.modifiersCount > 25 )
{
this.save( false, null, false );
this.modifiersCount = 1;
}
}
else if ( !isReset )
{
this.modifiersCount = 0;
this.typesCount++;
if ( this.typesCount > 25 )
{
this.save( false, null, false );
this.typesCount = 1;
}
}
},
reset : function() // Reset the undo stack.
{
/**
* Remember last pressed key.
*/
this.lastKeystroke = 0;
/**
* Stack for all the undo and redo snapshots, they're always created/removed
* in consistency.
*/
this.snapshots = [];
/**
* Current snapshot history index.
*/
this.index = -1;
this.limit = this.editor.config.undoStackSize || 20;
this.currentImage = null;
this.hasUndo = false;
this.hasRedo = false;
this.resetType();
},
/**
* Reset all states about typing.
* @see UndoManager.type
*/
resetType : function()
{
this.typing = false;
delete this.lastKeystroke;
this.typesCount = 0;
this.modifiersCount = 0;
},
fireChange : function()
{
this.hasUndo = !!this.getNextImage( true );
this.hasRedo = !!this.getNextImage( false );
// Reset typing
this.resetType();
this.onChange();
},
/**
* Save a snapshot of document image for later retrieve.
*/
save : function( onContentOnly, image, autoFireChange )
{
var snapshots = this.snapshots;
// Get a content image.
if ( !image )
image = new Image( this.editor );
// Do nothing if it was not possible to retrieve an image.
if ( image.contents === false )
return false;
// Check if this is a duplicate. In such case, do nothing.
if ( this.currentImage && image.equals( this.currentImage, onContentOnly ) )
return false;
// Drop future snapshots.
snapshots.splice( this.index + 1, snapshots.length - this.index - 1 );
// If we have reached the limit, remove the oldest one.
if ( snapshots.length == this.limit )
snapshots.shift();
// Add the new image, updating the current index.
this.index = snapshots.push( image ) - 1;
this.currentImage = image;
if ( autoFireChange !== false )
this.fireChange();
return true;
},
restoreImage : function( image )
{
// Bring editor focused to restore selection.
var editor = this.editor,
sel;
if ( image.bookmarks )
{
editor.focus();
// Retrieve the selection beforehand. (#8324)
sel = editor.getSelection();
}
this.editor.loadSnapshot( image.contents );
if ( image.bookmarks )
sel.selectBookmarks( image.bookmarks );
else if ( CKEDITOR.env.ie )
{
// IE BUG: If I don't set the selection to *somewhere* after setting
// document contents, then IE would create an empty paragraph at the bottom
// the next time the document is modified.
var $range = this.editor.document.getBody().$.createTextRange();
$range.collapse( true );
$range.select();
}
this.index = image.index;
// Update current image with the actual editor
// content, since actualy content may differ from
// the original snapshot due to dom change. (#4622)
this.update();
this.fireChange();
},
// Get the closest available image.
getNextImage : function( isUndo )
{
var snapshots = this.snapshots,
currentImage = this.currentImage,
image, i;
if ( currentImage )
{
if ( isUndo )
{
for ( i = this.index - 1 ; i >= 0 ; i-- )
{
image = snapshots[ i ];
if ( !currentImage.equals( image, true ) )
{
image.index = i;
return image;
}
}
}
else
{
for ( i = this.index + 1 ; i < snapshots.length ; i++ )
{
image = snapshots[ i ];
if ( !currentImage.equals( image, true ) )
{
image.index = i;
return image;
}
}
}
}
return null;
},
/**
* Check the current redo state.
* @return {Boolean} Whether the document has previous state to
* retrieve.
*/
redoable : function()
{
return this.enabled && this.hasRedo;
},
/**
* Check the current undo state.
* @return {Boolean} Whether the document has future state to restore.
*/
undoable : function()
{
return this.enabled && this.hasUndo;
},
/**
* Perform undo on current index.
*/
undo : function()
{
if ( this.undoable() )
{
this.save( true );
var image = this.getNextImage( true );
if ( image )
return this.restoreImage( image ), true;
}
return false;
},
/**
* Perform redo on current index.
*/
redo : function()
{
if ( this.redoable() )
{
// Try to save. If no changes have been made, the redo stack
// will not change, so it will still be redoable.
this.save( true );
// If instead we had changes, we can't redo anymore.
if ( this.redoable() )
{
var image = this.getNextImage( false );
if ( image )
return this.restoreImage( image ), true;
}
}
return false;
},
/**
* Update the last snapshot of the undo stack with the current editor content.
*/
update : function()
{
this.snapshots.splice( this.index, 1, ( this.currentImage = new Image( this.editor ) ) );
}
};
})();
/**
* The number of undo steps to be saved. The higher this setting value the more
* memory is used for it.
* @name CKEDITOR.config.undoStackSize
* @type Number
* @default 20
* @example
* config.undoStackSize = 50;
*/
/**
* Fired when the editor is about to save an undo snapshot. This event can be
* fired by plugins and customizations to make the editor saving undo snapshots.
* @name CKEDITOR.editor#saveSnapshot
* @event
*/
/**
* Fired before an undo image is to be taken. An undo image represents the
* editor state at some point. It's saved into an undo store, so the editor is
* able to recover the editor state on undo and redo operations.
* @name CKEDITOR.editor#beforeUndoImage
* @since 3.5.3
* @see CKEDITOR.editor#afterUndoImage
* @event
*/
/**
* Fired after an undo image is taken. An undo image represents the
* editor state at some point. It's saved into an undo store, so the editor is
* able to recover the editor state on undo and redo operations.
* @name CKEDITOR.editor#afterUndoImage
* @since 3.5.3
* @see CKEDITOR.editor#beforeUndoImage
* @event
*/
|
/**
* @jsx React.DOM
*/
var _ = require('lodash');
var React = require('react/addons');
var Loader = require('../../common/loader.js');
var DataTable = require('./data_table.js');
var KeenViz = require('./keen_viz.js');
var ExplorerUtils = require('../../../utils/ExplorerUtils');
var FormatUtils = require('../../../utils/FormatUtils');
var Chart = React.createClass({
// ***********************
// Content building
// ***********************
buildVizContent: function() {
var model = this.props.model;
if (!model.result && model.result !== 0) {
return (
<div ref="notice" className="big-notice">
<div className="alert alert-info">
{'Let\'s go exploring!'}
</div>
</div>
);
}
if (!ExplorerUtils.resultCanBeVisualized(model)) {
return (
<div ref="notice" className="big-notice">
<div className="alert alert-danger">
<span className="icon glyphicon glyphicon-info-sign error"></span>
Your query returned no results.
</div>
</div>
);
}
if (ExplorerUtils.resultCanBeVisualized(model)) {
return this.buildViz();
} else {
this.props.dataviz.destroy();
}
},
buildViz: function() {
var chartContent;
var msgContent;
var analysisType = this.props.model.query.analysis_type;
var wrapClasses = analysisType + '-viz';
if (ExplorerUtils.isJSONViz(this.props.model)) {
var content = FormatUtils.prettyPrintJSON({
result: this.props.model.result
});
chartContent = (
<textarea ref='jsonViz' className="json-view" value={content} readOnly />
);
} else if (ExplorerUtils.isTableViz(this.props.model)) {
chartContent = (
<DataTable data={this.props.model.result}/>
);
} else {
chartContent = (
<KeenViz model={this.props.model} dataviz={this.props.dataviz} />
);
}
return (
<div className={wrapClasses}>
{chartContent}
</div>
);
},
// ***********************
// Lifecycle hooks
// ***********************
render: function() {
var vizContent = this.buildVizContent();
return (
<div className="chart-area">
<Loader visible={this.props.model.loading} />
{vizContent}
</div>
);
}
});
module.exports = Chart;
|
/******
* Comment Canvas Core For HTML5 VideoPlayers
* Author : Jim Chen
* Licensing : MIT License
******/
Array.prototype.remove = function(obj){
for(var a = 0; a < this.length;a++)
if(this[a] == obj){
this.splice(a,1);
break;
}
};
Array.prototype.bsearch = function(what,how){
if(this.length == 0) return 0;
if(how(what,this[0]) < 0) return 0;
if(how(what,this[this.length - 1]) >=0) return this.length;
var low =0;
var i = 0;
var count = 0;
var high = this.length - 1;
while(low<=high){
i = Math.floor((high + low + 1)/2);
count++;
if(how(what,this[i-1])>=0 && how(what,this[i])<0){
return i;
}else if(how(what,this[i-1])<0){
high = i-1;
}else if(how(what,this[i])>=0){
low = i;
}else
console.error('Program Error');
if(count > 1500) console.error('Too many run cycles.');
}
return -1;
};
Array.prototype.binsert = function(what,how){
this.splice(this.bsearch(what,how),0,what);
};
function CommentCore(stage){
function Comment(data){
this.position = {x:0,y:0};
this.width = 0;
this.height = 0;
this.parent = null;
this.ttl = 4000;
this.dur = 4000;
this.data = data;
this.canvas = document.createElement('canvas');
var context = this.canvas.getContext('2d');
context.font = "bold " + data.size + "px " + data.font;
context.fillStyle = data.color;
context.strokeStyle = "#000000";
context.globalAlpha = data.alpha;
context.textBaseline = "top";
this.width = context.measureText(data.text).width;
//Measure the height
this.height = data.size;
context.strokeText(data.text,0,0);
context.fillText(data.text,0,0);
};
Comment.prototype.draw = function(){
var ctx = this.parent.getContext("2d");
if((this.data.mode == 4 || this.data.mode == 5 || this.data.mode == 7) && this.data.alphaFrom != null && this.data.alphaTo != null){
ctx.globalAlpha = (this.data.alphaFrom - this.data.alphaTo) * (this.ttl/this.dur) + this.data.alphaTo;
}
//Border problem
if(this.data.border == true){
ctx.strokeStyle="#00ffff";
ctx.strokeRect(this.position.x,this.position.y,this.width,this.height);
ctx.strokeRect(this.position.x-0.5,this.position.y-0.5,this.width+1,this.height+1);
ctx.strokeStyle="#000000";
}
ctx.drawImage(this.canvas,this.position.x,this.position.y);
ctx.globalAlpha = 1;//Reset
};
//End comment Definition
function TimeKeeper(tick){
var _timer = 0;
var _lastTick = 0;
this.interval = tick;
this.isRunning = false;
this.refobj = null;//Reference Object
this.onTick = function(){
var elapsed = new Date().getTime() - _lastTick;
_lastTick = new Date().getTime();
if(this.onTimer != null)
this.onTimer(elapsed,this.refobj);
};
this.start = function(){
if(this.isRunning)
return;
_lastTick = new Date().getTime();
var _self = this;
_timer = window.setInterval(function(){_self.onTick();},this.interval);
this.isRunning = true;
};
this.stop = function(){
window.clearInterval(_timer);
_timer = 0;
this.isRunning = false;
}
}
//End TimeKeeper
function CommentManager(stage){
this.stage = stage;
this.scaleFactor = 1;
this.time = new TimeKeeper(10);
this.timeline = [];//Timeline is filled with Pre-Rendered Comment Data
this.runline = [];
this.position = 0;
this.filter = null;
this.csa = {
scroll: new CommentSpaceAllocator(0,0),
top:new TopCommentSpaceAllocator(0,0),
bottom:new BottomCommentSpaceAllocator(0,0),
reverse:new ReverseCommentSpaceAllocator(0,0),
scrollbtm:new BottomScrollCommentSpaceAllocator(0,0)
};
var cmObj = this;
this.time.refobj = cmObj;
this.time.onTimer = function(elapsed,ref){
ref.render(elapsed);
};
//End
this.setBounds();
};
CommentManager.prototype.start = function(){
this.time.start();
};
CommentManager.prototype.stop = function(){
this.time.stop();
};
CommentManager.prototype.setBounds = function(){
for(var comAlloc in this.csa){
this.csa[comAlloc].setBounds(this.stage.width,this.stage.height);
}
};
CommentManager.prototype.render = function (timePassed){
if(this.runline.length > 0)
this.stage.getContext('2d').clearRect(0,0,this.stage.width,this.stage.height);//Clear
for(var i=0;i<this.runline.length;i++){
var cmt = this.runline[i];
cmt.ttl -= timePassed;
if(cmt.data.mode == 1 || cmt.data.mode == 2){
cmt.position.x = (cmt.ttl / (cmt.dur * this.scaleFactor)) * (this.stage.width + cmt.width) - cmt.width;
}else if(cmt.data.mode == 6){
cmt.position.x = (1 - cmt.ttl / cmt.dur) * (this.stage.width + cmt.width) - cmt.width;
}else if(cmt.data.mode == 7 && cmt.data.movable){
cmt.position.y = ((cmt.data.toY - cmt.data.y) * (Math.min(Math.max(cmt.dur - cmt.data.moveDelay - cmt.ttl,0),cmt.data.moveDuration) / cmt.data.moveDuration) + parseInt(cmt.data.y));
cmt.position.x = ((cmt.data.toX - cmt.data.x) * (Math.min(Math.max(cmt.dur - cmt.data.moveDelay - cmt.ttl,0),cmt.data.moveDuration) / cmt.data.moveDuration) + parseInt(cmt.data.x));
}
/*if(cmObj.filter != null){
cmt = cmObj.filter.runtimeFilter(cmt);
}*/
if(cmt.ttl <= 0){
this.runline.remove(cmt);//remove the comment
this.finish(cmt);
}else{
cmt.draw();
}
}
};
CommentManager.prototype.seek = function (time){
this.position = this.timeline.bsearch(time,function(a,b){
if(a < b.stime) return -1
else if(a > b.stime) return 1;
else return 0;
});
};
CommentManager.prototype.sendComment = function(data){
var cmt = new Comment(data);
cmt.parent = this.stage;
switch(cmt.data.mode){
default:
case 1:{this.csa.scroll.add(cmt);}break;
case 2:{this.csa.scrollbtm.add(cmt);}break;
case 4:{this.csa.bottom.add(cmt);}break;
case 5:{this.csa.top.add(cmt);}break;
case 6:{this.csa.reverse.add(cmt);}break;
}
this.runline.push(cmt);
};
CommentManager.prototype.finish = function(cmt){
switch(cmt.data.mode){
default:
case 1:{this.csa.scroll.remove(cmt);}break;
case 2:{this.csa.scrollbtm.remove(cmt);}break;
case 4:{this.csa.bottom.remove(cmt);}break;
case 5:{this.csa.top.remove(cmt);}break;
case 6:{this.csa.reverse.remove(cmt);}break;
case 7:break;
}
};
//Do the core stuff now
this.cm = new CommentManager(stage);
}
|
/** @jsx React.DOM */
var assert = require('chai').assert;
var _ = require('lodash');
var sinon = require('sinon');
var FilterValueFields = require('../../../../client/js/app/components/common/filter_value_fields.js');
var Geo = require('../../../../client/js/app/components/common/geo.js');
var Datepicker = require('../../../../client/js/app/components/common/datepicker.js');
var Select = require('../../../../client/js/app/components/common/select.js');
var ProjectUtils = require('../../../../client/js/app/utils/ProjectUtils');
var React = require('react/addons');
var TestUtils = React.addons.TestUtils;
var TestHelpers = require('../../../support/TestHelpers');
describe('components/common/filter_value_fields', function() {
beforeEach(function() {
this.project = TestHelpers.createProject();
this.model = TestHelpers.createExplorerModel();;
this.model.event_collection = 'click';
this.filter = {
property_name: 'propOne',
operator: 'eq',
property_value: 'abc',
coercion_type: 'String'
};
this.index = 0;
this.component = TestUtils.renderIntoDocument(<FilterValueFields model={this.model} filter={this.filter} project={this.project} index={this.index} />);
});
describe('setup', function() {
it('is of the right type', function() {
assert.isTrue(TestUtils.isCompositeComponentWithType(this.component, FilterValueFields));
});
describe('Datetime', function() {
beforeEach(function(){
this.component.props.filter.coercion_type = 'Datetime';
this.component.forceUpdate();
});
it('has a Datetime component', function(){
assert.lengthOf(TestUtils.scryRenderedComponentsWithType(this.component, Datepicker), 1);
});
});
describe('Boolean', function() {
beforeEach(function(){
this.component.props.filter.coercion_type = 'Boolean';
this.component.forceUpdate();
});
it('has a Select component', function(){
assert.lengthOf(TestUtils.scryRenderedComponentsWithType(this.component, Select), 2);
});
it('has no input tags', function(){
assert.lengthOf(TestUtils.scryRenderedDOMComponentsWithTag(this.component, 'input'), 0);
});
});
describe('Null', function () {
beforeEach(function () {
this.component.props.filter.coercion_type = 'Null';
this.component.forceUpdate();
assert.lengthOf(TestUtils.scryRenderedDOMComponentsWithTag(this.component, 'input'), 1);
});
it('has a readonly input', function () {
var input = TestUtils.scryRenderedDOMComponentsWithTag(this.component, 'input')[0];
assert.isTrue(input.props.readOnly);
});
it('the input value has a placeholder of \'null\'', function () {
var input = TestUtils.scryRenderedDOMComponentsWithTag(this.component, 'input')[0];
assert.equal(input.props.placeholder, 'Null');
});
});
describe('Geo', function () {
beforeEach(function () {
this.component.props.filter = {
property_name: 'geoProp',
coercion_type: 'Geo',
operator: 'within',
property_value: {
coordinates: [],
max_distance_miles: null
}
};
sinon.stub(ProjectUtils, 'getPropertyType');
this.component.forceUpdate();
});
afterEach(function () {
ProjectUtils.getPropertyType.restore();
});
it('has a Geo component', function(){
assert.lengthOf(TestUtils.scryRenderedComponentsWithType(this.component, Geo), 1);
});
it('has 3 inputs for geo-location query data', function(){
assert.lengthOf(TestUtils.scryRenderedDOMComponentsWithTag(this.component, 'input'), 3);
});
});
describe('not Boolean or Datetime or Null', function() {
beforeEach(function(){
this.component.props.filter.coercion_type = 'String';
this.component.forceUpdate();
});
it('does not have a Datetime component', function(){
assert.lengthOf(TestUtils.scryRenderedComponentsWithType(this.component, Datepicker), 0);
});
it('has one input', function(){
assert.lengthOf(TestUtils.scryRenderedDOMComponentsWithTag(this.component, 'input'), 1);
});
it('has one select', function(){
assert.lengthOf(TestUtils.scryRenderedComponentsWithType(this.component, Select), 1);
});
});
describe('available coercion types', function () {
describe('when property type is not geo', function () {
it('has all the coercion types', function () {
var defaultCoercionOptions = ['String', 'Number', 'Null', 'List', 'Boolean', 'Datetime']
this.component.props.filter.property_name = 'stringProp';
this.component.forceUpdate();
var coercionTypeSelect = TestUtils.scryRenderedDOMComponentsWithTag(this.component, 'select')[0].getDOMNode();
var coercionOptions = _.map(coercionTypeSelect.childNodes, function(node){
return node.value;
});
coercionOptions = _.compact(coercionOptions);
assert.sameMembers(defaultCoercionOptions, coercionOptions);
});
});
});
describe('available property value options when Boolean', function () {
it('is true or false', function () {
this.component.props.filter = { operator: 'exists', coercion_type: 'Boolean' };
this.component.forceUpdate()
var boolPropValueSelect = this.component.refs['boolean-value-set'].getDOMNode().lastChild
var boolPropValueSelectOptions = _.map(boolPropValueSelect.childNodes, function(node){
return node.value;
});
propertyValueOptions = _.compact(boolPropValueSelectOptions);
assert.sameMembers(propertyValueOptions, ['true', 'false']);
});
});
});
}); |
/* @flow */
"use strict"
const hasInterpolation = require("../utils/hasInterpolation")
/**
* Check whether a value is standard
*/
module.exports = function (value/*: string*/)/*: boolean*/ {
// SCSS variable
if (value[0] === "$") {
return false
}
// Less variable
if (value[0] === "@") {
return false
}
// SCSS or Less interpolation
if (hasInterpolation(value)) {
return false
}
return true
}
|
/**
* jQuery Unveil2
* A very lightweight jQuery plugin to lazy load images
* Based on https://github.com/luis-almeida/unveil
*
* Licensed under the MIT license.
* Copyright 2015 Joram van den Boezem
* https://github.com/hongaar/unveil2
*/
/*global
console, window
*/
(function ($) {
"use strict";
// "unveil" as a variable to save some bytes
var unveilString = 'unveil',
images = $(),
initialized = false;
$.fn.unveil = function (opts) {
opts = opts || {};
console.log('Called unveil on', this.length, 'elements with the following options:', opts);
// Initialize variables
var $window = $(window),
$container = opts.container || $window,
placeholder = opts.placeholder || 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
offset = opts.offset || 0,
height = $window.height(),
breakpoints = opts.breakpoints || [],
retina = window.devicePixelRatio > 1;
// Sort sizes array, arrange highest minWidth to front of array
breakpoints.sort(function (a, b) {
return b.minWidth - a.minWidth;
});
// Read and reset the src attribute first, to prevent loading
// of original images
this.each(function () {
var $this = $(this),
elmPlaceholder = $this.data('src-placeholder') || placeholder;
// Add element to global array
images = $(images).add(this);
// If this element has been called before,
// don't set placeholder now to prevent FOUI (Flash Of Ustyled Image)
if (!$this.data(unveilString)) {
// Set the unveil flag
$this.data(unveilString, true);
// Set data-src if not set
if (!$this.data('src')) {
$this.data('src', $this.prop('src'));
}
// Set placeholder
$this
.one('load', function () {
$(this).addClass(unveilString + '-placeholder');
unveil();
})
.prop('src', '')
.prop('src', elmPlaceholder);
}
});
console.log('Images now in collection', images.length);
// This triggers an image source to be set on the target,
// based on window width and presence of retina screen
this.one(unveilString, function () {
/*jslint plusplus: true */
var i, $this = $(this), windowWidth = $window.width(),
attrib = 'src', targetSrc, defaultSrc, retinaSrc;
// Determine attribute to extract source from
for (i = 0; i < breakpoints.length; i++) {
var dataAttrib = breakpoints[i].attribute.replace(/^data-/, '');
if (windowWidth >= breakpoints[i].minWidth && $this.data(dataAttrib)) {
attrib = dataAttrib;
break;
}
}
// Extract source
defaultSrc = retinaSrc = $this.data(attrib);
// Do we have a retina source?
if (defaultSrc && defaultSrc.indexOf("|") !== -1) {
retinaSrc = defaultSrc.split("|")[1];
defaultSrc = defaultSrc.split("|")[0];
}
// Change attribute on image
if (defaultSrc) {
targetSrc = (retina && retinaSrc) ? retinaSrc : defaultSrc;
console.log('Unveiling image', {
attribute: attrib,
retina: retina,
defaultSrc: defaultSrc,
retinaSrc: retinaSrc,
targetSrc: targetSrc
});
// Change classes
classLoading($this);
// Set new source
$this.prop("src", targetSrc);
// When new source has loaded, do stuff
$this.one('load', function () {
// Change classes
classLoaded($this);
// Fire up the callback if it's a function
if (typeof opts.loaded === "function") {
opts.loaded.call(this);
}
// Loading the image may have modified page layout,
// so unveil again
unveil();
});
// If the image has instantly loaded, change classes now
if (this.complete) {
classLoaded($this);
}
}
});
// Functions below
function classLoading($elm) {
$elm.addClass(unveilString + '-loading');
}
function classLoaded($elm) {
$elm.removeClass(unveilString + '-placeholder ' + unveilString + '-loading');
$elm.addClass(unveilString + '-loaded');
}
function inview() {
/* jshint validthis: true */
var $this = $(this);
if ($this.is(":hidden")) {
return;
}
var viewportTop = $window.scrollTop(),
viewportEnd = viewportTop + height,
containerTop = $container !== $window ? viewportTop - $container.offset().top : 0,
elementTop = $this.offset().top + containerTop,
elementEnd = elementTop + $this.height();
return elementEnd >= viewportTop - offset && elementTop <= viewportEnd + offset;
}
function unveil() {
console.log('Unveiling');
var batch = images.filter(inview);
batch.trigger(unveilString);
images = images.not(batch);
if (batch.length) {
console.log('New images in view', batch.length, ', leaves', images.length, 'in collection');
}
}
function resize() {
height = $window.height();
unveil();
}
function throttle(callback) {
var wait = false; // Initially, we're not waiting
return function () { // We return a throttled function
if (!wait) { // If we're not waiting
wait = true; // Prevent future invocations
setTimeout(function () { // After a period of time
callback(); // Execute users function
wait = false; // And allow future invocations
}, opts.throttle || 0);
}
};
}
// Bind global listeners
if (!initialized) {
$container.on({
'resize.unveil': throttle(resize),
'scroll.unveil': throttle(unveil),
'lookup.unveil': unveil
});
}
// Wait a little bit for the placeholder to be set, so the src attribute
// is not empty (which will mark the image as hidden)
setTimeout(unveil, 0);
initialized = true;
return this;
};
})(window.jQuery || window.Zepto); |
require("chai").should();
var Repos = require('../../../app/collections/repos');
describe('Repos', function() {
it('should have a default url if params.user is not specified', function() {
var repos = new Repos();
repos.url().should.equal('/repositories');
});
it('should have a unique url if params.user is specified', function() {
var repos = new Repos();
repos.params.user = 'someusername';
repos.url().should.equal('/users/:user/repos');
});
});
|
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/** cc.Layer is a subclass of cc.Node that implements the TouchEventsDelegate protocol.<br/>
* All features from cc.Node are valid, plus the bake feature: Baked layer can cache a static layer to improve performance
* @class
* @extends cc.Node
*/
cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{
_className: "Layer",
/**
* <p>Constructor of cc.Layer, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.</p>
*/
ctor: function () {
var nodep = cc.Node.prototype;
nodep.ctor.call(this);
this._ignoreAnchorPointForPosition = true;
nodep.setAnchorPoint.call(this, 0.5, 0.5);
nodep.setContentSize.call(this, cc.winSize);
},
/**
* Initialization of the layer, please do not call this function by yourself, you should pass the parameters to constructor to initialize a layer
*/
init: function(){
var _t = this;
_t._ignoreAnchorPointForPosition = true;
_t.setAnchorPoint(0.5, 0.5);
_t.setContentSize(cc.winSize);
_t._cascadeColorEnabled = false;
_t._cascadeOpacityEnabled = false;
return true;
},
/**
* Sets the layer to cache all of children to a bake sprite, and draw itself by bake sprite. recommend using it in UI.<br/>
* This is useful only in html5 engine
* @function
* @see cc.Layer#unbake
*/
bake: function(){
this._renderCmd.bake();
},
/**
* Cancel the layer to cache all of children to a bake sprite.<br/>
* This is useful only in html5 engine
* @function
* @see cc.Layer#bake
*/
unbake: function(){
this._renderCmd.unbake();
},
/**
* Determines if the layer is baked.
* @function
* @returns {boolean}
* @see cc.Layer#bake and cc.Layer#unbake
*/
isBaked: function(){
return this._renderCmd._isBaked;
},
addChild: function(child, localZOrder, tag){
cc.Node.prototype.addChild.call(this, child, localZOrder, tag);
this._renderCmd._bakeForAddChild(child);
},
_createRenderCmd: function(){
if (cc._renderType === cc._RENDER_TYPE_CANVAS)
return new cc.Layer.CanvasRenderCmd(this);
else
return new cc.Layer.WebGLRenderCmd(this);
}
});
/**
* Creates a layer
* @deprecated since v3.0, please use the new construction instead
* @see cc.Layer
* @return {cc.Layer|Null}
*/
cc.Layer.create = function () {
return new cc.Layer();
};
/**
* <p>
* CCLayerColor is a subclass of CCLayer that implements the CCRGBAProtocol protocol. <br/>
* All features from CCLayer are valid, plus the following new features: <br/>
* - opacity <br/>
* - RGB colors </p>
* @class
* @extends cc.Layer
*
* @param {cc.Color} [color=] The color of the layer
* @param {Number} [width=] The width of the layer
* @param {Number} [height=] The height of the layer
*
* @example
* // Example
* //Create a yellow color layer as background
* var yellowBackground = new cc.LayerColor(cc.color(255,255,0,255));
* //If you didn't pass in width and height, it defaults to the same size as the canvas
*
* //create a yellow box, 200 by 200 in size
* var yellowBox = new cc.LayerColor(cc.color(255,255,0,255), 200, 200);
*/
cc.LayerColor = cc.Layer.extend(/** @lends cc.LayerColor# */{
_blendFunc: null,
_className: "LayerColor",
/**
* Returns the blend function
* @return {cc.BlendFunc}
*/
getBlendFunc: function () {
return this._blendFunc;
},
/**
* Changes width and height
* @deprecated since v3.0 please use setContentSize instead
* @see cc.Node#setContentSize
* @param {Number} w width
* @param {Number} h height
*/
changeWidthAndHeight: function (w, h) {
this.width = w;
this.height = h;
},
/**
* Changes width in Points
* @deprecated since v3.0 please use setContentSize instead
* @see cc.Node#setContentSize
* @param {Number} w width
*/
changeWidth: function (w) {
this.width = w;
},
/**
* change height in Points
* @deprecated since v3.0 please use setContentSize instead
* @see cc.Node#setContentSize
* @param {Number} h height
*/
changeHeight: function (h) {
this.height = h;
},
setOpacityModifyRGB: function (value) {
},
isOpacityModifyRGB: function () {
return false;
},
/**
* Constructor of cc.LayerColor
* @function
* @param {cc.Color} [color=]
* @param {Number} [width=]
* @param {Number} [height=]
*/
ctor: function(color, width, height){
cc.Layer.prototype.ctor.call(this);
this._blendFunc = new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA);
cc.LayerColor.prototype.init.call(this, color, width, height);
},
/**
* Initialization of the layer, please do not call this function by yourself, you should pass the parameters to constructor to initialize a layer
* @param {cc.Color} [color=]
* @param {Number} [width=]
* @param {Number} [height=]
* @return {Boolean}
*/
init: function (color, width, height) {
if (cc._renderType !== cc._RENDER_TYPE_CANVAS)
this.shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_COLOR);
var winSize = cc.director.getWinSize();
color = color || cc.color(0, 0, 0, 255);
width = width === undefined ? winSize.width : width;
height = height === undefined ? winSize.height : height;
var locRealColor = this._realColor;
locRealColor.r = color.r;
locRealColor.g = color.g;
locRealColor.b = color.b;
this._realOpacity = color.a;
this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty|cc.Node._dirtyFlags.opacityDirty);
cc.LayerColor.prototype.setContentSize.call(this, width, height);
return true;
},
/**
* Sets the blend func, you can pass either a cc.BlendFunc object or source and destination value separately
* @param {Number|cc.BlendFunc} src
* @param {Number} [dst]
*/
setBlendFunc: function (src, dst) {
var locBlendFunc = this._blendFunc;
if (dst === undefined) {
locBlendFunc.src = src.src;
locBlendFunc.dst = src.dst;
} else {
locBlendFunc.src = src;
locBlendFunc.dst = dst;
}
this._renderCmd.updateBlendFunc(locBlendFunc);
},
_setWidth: function(width){
cc.Node.prototype._setWidth.call(this, width);
this._renderCmd._updateSquareVerticesWidth(width);
},
_setHeight: function(height){
cc.Node.prototype._setHeight.call(this, height);
this._renderCmd._updateSquareVerticesHeight(height);
},
setContentSize: function(size, height){
cc.Layer.prototype.setContentSize.call(this, size, height);
this._renderCmd._updateSquareVertices(size, height);
},
_createRenderCmd: function(){
if (cc._renderType === cc._RENDER_TYPE_CANVAS)
return new cc.LayerColor.CanvasRenderCmd(this);
else
return new cc.LayerColor.WebGLRenderCmd(this);
}
});
/**
* Creates a cc.Layer with color, width and height in Points
* @deprecated since v3.0 please use the new construction instead
* @see cc.LayerColor
* @param {cc.Color} color
* @param {Number|Null} [width=]
* @param {Number|Null} [height=]
* @return {cc.LayerColor}
*/
cc.LayerColor.create = function (color, width, height) {
return new cc.LayerColor(color, width, height);
};
//LayerColor - Getter Setter
(function(){
var proto = cc.LayerColor.prototype;
cc.defineGetterSetter(proto, "width", proto._getWidth, proto._setWidth);
cc.defineGetterSetter(proto, "height", proto._getHeight, proto._setHeight);
})();
/**
* <p>
* CCLayerGradient is a subclass of cc.LayerColor that draws gradients across the background.<br/>
*<br/>
* All features from cc.LayerColor are valid, plus the following new features:<br/>
* <ul><li>direction</li>
* <li>final color</li>
* <li>interpolation mode</li></ul>
* <br/>
* Color is interpolated between the startColor and endColor along the given<br/>
* vector (starting at the origin, ending at the terminus). If no vector is<br/>
* supplied, it defaults to (0, -1) -- a fade from top to bottom.<br/>
* <br/>
* If 'compressedInterpolation' is disabled, you will not see either the start or end color for<br/>
* non-cardinal vectors; a smooth gradient implying both end points will be still<br/>
* be drawn, however.<br/>
*<br/>
* If 'compressedInterpolation' is enabled (default mode) you will see both the start and end colors of the gradient.
* </p>
* @class
* @extends cc.LayerColor
*
* @param {cc.Color} start Starting color
* @param {cc.Color} end Ending color
* @param {cc.Point} [v=cc.p(0, -1)] A vector defines the gradient direction, default direction is from top to bottom
*
* @property {cc.Color} startColor - Start color of the color gradient
* @property {cc.Color} endColor - End color of the color gradient
* @property {Number} startOpacity - Start opacity of the color gradient
* @property {Number} endOpacity - End opacity of the color gradient
* @property {Number} vector - Direction vector of the color gradient
* @property {Number} compressedInterpolation - Indicate whether or not the interpolation will be compressed
*/
cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{
_endColor: null,
_startOpacity: 255,
_endOpacity: 255,
_alongVector: null,
_compressedInterpolation: false,
_className: "LayerGradient",
_colorStops: [],
/**
* Constructor of cc.LayerGradient
* @param {cc.Color} start
* @param {cc.Color} end
* @param {cc.Point} [v=cc.p(0, -1)]
* @param {Array|Null} stops
*
* @example Using ColorStops argument:
* //startColor & endColor are for default and backward compatibility
* var layerGradient = new cc.LayerGradient(cc.color.RED, new cc.Color(255,0,0,0), cc.p(0, -1),
* [{p:0, color: cc.color.RED},
* {p:.5, color: new cc.Color(0,0,0,0)},
* {p:1, color: cc.color.RED}]);
* //where p = A value between 0.0 and 1.0 that represents the position between start and end in a gradient
*
*/
ctor: function (start, end, v, stops) {
cc.LayerColor.prototype.ctor.call(this);
this._endColor = cc.color(0, 0, 0, 255);
this._alongVector = cc.p(0, -1);
this._startOpacity = 255;
this._endOpacity = 255;
if(stops && stops instanceof Array){
this._colorStops = stops;
stops.splice(0, 0, {p:0, color: start || cc.color.BLACK});
stops.push({p:1, color: end || cc.color.BLACK});
} else
this._colorStops = [{p:0, color: start || cc.color.BLACK}, {p:1, color: end || cc.color.BLACK}];
cc.LayerGradient.prototype.init.call(this, start, end, v, stops);
},
/**
* Initialization of the layer, please do not call this function by yourself, you should pass the parameters to constructor to initialize a layer
* @param {cc.Color} start starting color
* @param {cc.Color} end
* @param {cc.Point|Null} v
* @param {Array|Null} stops
* @return {Boolean}
*/
init: function (start, end, v, stops) {
start = start || cc.color(0, 0, 0, 255);
end = end || cc.color(0, 0, 0, 255);
v = v || cc.p(0, -1);
var _t = this;
// Initializes the CCLayer with a gradient between start and end in the direction of v.
var locEndColor = _t._endColor;
_t._startOpacity = start.a;
locEndColor.r = end.r;
locEndColor.g = end.g;
locEndColor.b = end.b;
_t._endOpacity = end.a;
_t._alongVector = v;
_t._compressedInterpolation = true;
cc.LayerColor.prototype.init.call(_t, cc.color(start.r, start.g, start.b, 255));
this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty|cc.Node._dirtyFlags.opacityDirty|cc.Node._dirtyFlags.gradientDirty);
return true;
},
/**
* Sets the untransformed size of the LayerGradient.
* @param {cc.Size|Number} size The untransformed size of the LayerGradient or The untransformed size's width of the LayerGradient.
* @param {Number} [height] The untransformed size's height of the LayerGradient.
*/
setContentSize: function (size, height) {
cc.LayerColor.prototype.setContentSize.call(this, size, height);
this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.gradientDirty);
},
_setWidth: function (width) {
cc.LayerColor.prototype._setWidth.call(this, width);
this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.gradientDirty);
},
_setHeight: function (height) {
cc.LayerColor.prototype._setHeight.call(this, height);
this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.gradientDirty);
},
/**
* Returns the starting color
* @return {cc.Color}
*/
getStartColor: function () {
return cc.color(this._realColor);
},
/**
* Sets the starting color
* @param {cc.Color} color
* @example
* // Example
* myGradientLayer.setStartColor(cc.color(255,0,0));
* //set the starting gradient to red
*/
setStartColor: function (color) {
this.color = color;
//update the color stops
var stops = this._colorStops;
if(stops && stops.length > 0){
var selColor = stops[0].color;
selColor.r = color.r;
selColor.g = color.g;
selColor.b = color.b;
}
},
/**
* Sets the end gradient color
* @param {cc.Color} color
* @example
* // Example
* myGradientLayer.setEndColor(cc.color(255,0,0));
* //set the ending gradient to red
*/
setEndColor: function (color) {
var locColor = this._endColor;
locColor.r = color.r;
locColor.g = color.g;
locColor.b = color.b;
//update the color stops
var stops = this._colorStops;
if(stops && stops.length > 0){
var selColor = stops[stops.length -1].color;
selColor.r = color.r;
selColor.g = color.g;
selColor.b = color.b;
}
this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty);
},
/**
* Returns the end color
* @return {cc.Color}
*/
getEndColor: function () {
return cc.color(this._endColor);
},
/**
* Sets starting gradient opacity
* @param {Number} o from 0 to 255, 0 is transparent
*/
setStartOpacity: function (o) {
this._startOpacity = o;
//update the color stops
var stops = this._colorStops;
if(stops && stops.length > 0)
stops[0].color.a = o;
this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.opacityDirty);
},
/**
* Returns the starting gradient opacity
* @return {Number}
*/
getStartOpacity: function () {
return this._startOpacity;
},
/**
* Sets the end gradient opacity
* @param {Number} o
*/
setEndOpacity: function (o) {
this._endOpacity = o;
var stops = this._colorStops;
if(stops && stops.length > 0)
stops[stops.length -1].color.a = o;
this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.opacityDirty);
},
/**
* Returns the end gradient opacity
* @return {Number}
*/
getEndOpacity: function () {
return this._endOpacity;
},
/**
* Sets the direction vector of the gradient
* @param {cc.Point} Var
*/
setVector: function (Var) {
this._alongVector.x = Var.x;
this._alongVector.y = Var.y;
this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.gradientDirty);
},
/**
* Returns the direction vector of the gradient
* @return {cc.Point}
*/
getVector: function () {
return cc.p(this._alongVector.x, this._alongVector.y);
},
/**
* Returns whether compressed interpolation is enabled
* @return {Boolean}
*/
isCompressedInterpolation: function () {
return this._compressedInterpolation;
},
/**
* Sets whether compressed interpolation is enabled
* @param {Boolean} compress
*/
setCompressedInterpolation: function (compress) {
this._compressedInterpolation = compress;
this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.gradientDirty);
},
/**
* Return an array of Object representing a colorStop for the gradient, if no stops was specified
* start & endColor will be provided as default values
* @example
* [{p: 0, color: cc.color.RED},{p: 1, color: cc.color.RED},...]
* @returns {Array}
*/
getColorStops: function(){
return this._colorStops;
},
/**
* Set the colorStops to create the gradient using multiple point & color
*
* @param colorStops
*
* @example
* //startColor & endColor are for default and backward compatibility
* var layerGradient = new cc.LayerGradient(cc.color.RED, new cc.Color(255,0,0,0), cc.p(0, -1));
* layerGradient.setColorStops([{p:0, color: cc.color.RED},
* {p:.5, color: new cc.Color(0,0,0,0)},
* {p:1, color: cc.color.RED}]);
* //where p = A value between 0.0 and 1.0 that represents the position between start and end in a gradient
*
*/
setColorStops: function(colorStops){
this._colorStops = colorStops;
//todo need update the start color and end color
this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty|cc.Node._dirtyFlags.opacityDirty|cc.Node._dirtyFlags.gradientDirty);
},
_createRenderCmd: function(){
if (cc._renderType === cc._RENDER_TYPE_CANVAS)
return new cc.LayerGradient.CanvasRenderCmd(this);
else
return new cc.LayerGradient.WebGLRenderCmd(this);
}
});
/**
* Creates a gradient layer
* @deprecated since v3.0, please use the new construction instead
* @see cc.layerGradient
* @param {cc.Color} start starting color
* @param {cc.Color} end ending color
* @param {cc.Point|Null} v
* @param {Array|NULL} stops
* @return {cc.LayerGradient}
*/
cc.LayerGradient.create = function (start, end, v, stops) {
return new cc.LayerGradient(start, end, v, stops);
};
//LayerGradient - Getter Setter
(function(){
var proto = cc.LayerGradient.prototype;
// Extended properties
/** @expose */
proto.startColor;
cc.defineGetterSetter(proto, "startColor", proto.getStartColor, proto.setStartColor);
/** @expose */
proto.endColor;
cc.defineGetterSetter(proto, "endColor", proto.getEndColor, proto.setEndColor);
/** @expose */
proto.startOpacity;
cc.defineGetterSetter(proto, "startOpacity", proto.getStartOpacity, proto.setStartOpacity);
/** @expose */
proto.endOpacity;
cc.defineGetterSetter(proto, "endOpacity", proto.getEndOpacity, proto.setEndOpacity);
/** @expose */
proto.vector;
cc.defineGetterSetter(proto, "vector", proto.getVector, proto.setVector);
/** @expose */
proto.colorStops;
cc.defineGetterSetter(proto, "colorStops", proto.getColorStops, proto.setColorStops);
})();
/**
* CCMultipleLayer is a CCLayer with the ability to multiplex it's children.<br/>
* Features:<br/>
* <ul><li>- It supports one or more children</li>
* <li>- Only one children will be active a time</li></ul>
* @class
* @extends cc.Layer
* @param {Array} layers an array of cc.Layer
* @example
* // Example
* var multiLayer = new cc.LayerMultiple(layer1, layer2, layer3);//any number of layers
*/
cc.LayerMultiplex = cc.Layer.extend(/** @lends cc.LayerMultiplex# */{
_enabledLayer: 0,
_layers: null,
_className: "LayerMultiplex",
/**
* Constructor of cc.LayerMultiplex
* @param {Array} layers an array of cc.Layer
*/
ctor: function (layers) {
cc.Layer.prototype.ctor.call(this);
if (layers instanceof Array)
cc.LayerMultiplex.prototype.initWithLayers.call(this, layers);
else
cc.LayerMultiplex.prototype.initWithLayers.call(this, Array.prototype.slice.call(arguments));
},
/**
* Initialization of the layer multiplex, please do not call this function by yourself, you should pass the parameters to constructor to initialize a layer multiplex
* @param {Array} layers an array of cc.Layer
* @return {Boolean}
*/
initWithLayers: function (layers) {
if ((layers.length > 0) && (layers[layers.length - 1] == null))
cc.log(cc._LogInfos.LayerMultiplex_initWithLayers);
this._layers = layers;
this._enabledLayer = 0;
this.addChild(this._layers[this._enabledLayer]);
return true;
},
/**
* Switches to a certain layer indexed by n.<br/>
* The current (old) layer will be removed from it's parent with 'cleanup:YES'.
* @param {Number} n the layer index to switch to
*/
switchTo: function (n) {
if (n >= this._layers.length) {
cc.log(cc._LogInfos.LayerMultiplex_switchTo);
return;
}
this.removeChild(this._layers[this._enabledLayer], true);
this._enabledLayer = n;
this.addChild(this._layers[n]);
},
/**
* Release the current layer and switches to another layer indexed by n.<br/>
* The current (old) layer will be removed from it's parent with 'cleanup:YES'.
* @param {Number} n the layer index to switch to
*/
switchToAndReleaseMe: function (n) {
if (n >= this._layers.length) {
cc.log(cc._LogInfos.LayerMultiplex_switchToAndReleaseMe);
return;
}
this.removeChild(this._layers[this._enabledLayer], true);
//[layers replaceObjectAtIndex:_enabledLayer withObject:[NSNull null]];
this._layers[this._enabledLayer] = null;
this._enabledLayer = n;
this.addChild(this._layers[n]);
},
/**
* Add a layer to the multiplex layers list
* @param {cc.Layer} layer
*/
addLayer: function (layer) {
if (!layer) {
cc.log(cc._LogInfos.LayerMultiplex_addLayer);
return;
}
this._layers.push(layer);
}
});
/**
* Creates a cc.LayerMultiplex with one or more layers using a variable argument list.
* @deprecated since v3.0, please use new construction instead
* @see cc.LayerMultiplex
* @return {cc.LayerMultiplex|Null}
*/
cc.LayerMultiplex.create = function (/*Multiple Arguments*/) {
return new cc.LayerMultiplex(Array.prototype.slice.call(arguments));
}; |
module configurationModule from 'torii/configuration';
var configuration = configurationModule.default,
configurable = configurationModule.configurable;
var originalConfiguration = configuration.test,
Testable = Ember.Object.extend({
configNamespace: 'test',
required: configurable('apiKey'),
defaulted: configurable('scope', 'email'),
defaultedFunctionValue: 'found-via-get',
defaultedFunction: configurable('redirectUri', function(){
return this.get('defaultedFunctionValue');
}),
}),
testable;
module('Configuration - Unit', {
setup: function(){
testable = new Testable();
},
teardown: function(){
configuration.test = originalConfiguration;
Ember.run(testable, 'destroy');
}
});
test("it should throw when reading a value not defaulted", function(){
var threw = false, message;
try {
testable.get('required');
} catch (e) {
threw = true;
message = e.message;
}
ok(threw, 'read threw');
ok(/Expected configuration value test.apiKey/.test(message), 'did not have proper error: '+message);
});
test("it should read values", function(){
configuration.test = {apiKey: 'item val'};
var value = testable.get('required');
equal(value, 'item val');
});
test("it should read default values", function(){
var value = testable.get('defaulted');
equal(value, 'email');
});
test("it should override default values", function(){
configuration.test = {scope: 'baz'};
var value = testable.get('defaulted');
equal(value, 'baz');
});
test("it read default values from a function", function(){
var value = testable.get('defaultedFunction');
equal(value, 'found-via-get');
});
/* window.ENV is set in index.html */
test("it will read off of window.ENV.torii", function(){
ok(configuration.didLoadFromEnv,
'configuration read from window.ENV.torii');
});
|
import propsToAriaRole from"./propsToAriaRole";var roleComponents={article:"article",banner:"header",complementary:"aside",contentinfo:"footer",form:"form",link:"a",list:"ul",listitem:"li",main:"main",navigation:"nav",region:"section"},emptyObject={},propsToAccessibilityComponent=function(o){if(void 0===o&&(o=emptyObject),"label"===o.accessibilityRole)return"label";var e=propsToAriaRole(o);return e?"heading"===e?"h"+(o["aria-level"]||1):roleComponents[e]:void 0};export default propsToAccessibilityComponent; |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getOutlinedInputUtilityClass = getOutlinedInputUtilityClass;
exports.default = void 0;
var _unstyled = require("@material-ui/unstyled");
function getOutlinedInputUtilityClass(slot) {
return (0, _unstyled.generateUtilityClass)('MuiOutlinedInput', slot);
}
const outlinedInputClasses = (0, _unstyled.generateUtilityClasses)('MuiOutlinedInput', ['root', 'colorSecondary', 'focused', 'disabled', 'adornedStart', 'adornedEnd', 'error', 'sizeSmall', 'multiline', 'notchedOutline', 'input', 'inputSizeSmall', 'inputMultiline', 'inputAdornedStart', 'inputAdornedEnd']);
var _default = outlinedInputClasses;
exports.default = _default; |
(function() {
// Default to the local version.
var path = '../libs/jquery/jquery.js';
// Get any jquery=___ param from the query string.
var jqversion = location.search.match(/[?&]jquery=(.*?)(?=&|$)/);
// If a version was specified, use that version from code.jquery.com.
if (jqversion) {
path = 'http://code.jquery.com/jquery-' + jqversion[1] + '.js';
}
// This is the only time I'll ever use document.write, I promise!
document.write('<script src="' + path + '"></script>');
}());
|
'use strict';
/* global describe, it, beforeEach */
var helper = require('../testHelpers/jsdomHelper');
helper();
var unexpected = require('unexpected');
var unexpectedDom = require('unexpected-dom');
var unexpectedSinon = require('unexpected-sinon');
var sinon = require('sinon');
var expect = unexpected
.clone()
.installPlugin(unexpectedSinon)
.installPlugin(unexpectedDom);
var React = require('react');
var ReactDOM = require('react-dom');
var TestUtils = require('react-addons-test-utils');
var OPTION = { label: 'TEST-LABEL', value: 'TEST-VALUE' };
var Value = require('../src/Value');
describe('Value component', function() {
var props;
var value;
beforeEach(function() {
props = {
value: OPTION,
onRemove: sinon.spy()
};
value = TestUtils.renderIntoDocument(<Value {...props}>{OPTION.label}</Value>);
});
it('requests its own removal when the remove icon is clicked', function() {
var selectItemIcon = TestUtils.findRenderedDOMComponentWithClass(value, 'Select-value-icon');
TestUtils.Simulate.mouseDown(selectItemIcon);
expect(props.onRemove, 'was called');
});
it('requests its own removal when the remove icon is touched', function() {
var selectItemIcon = TestUtils.findRenderedDOMComponentWithClass(value, 'Select-value-icon');
TestUtils.Simulate.touchStart(selectItemIcon);
TestUtils.Simulate.touchEnd(selectItemIcon);
expect(props.onRemove, 'was called');
});
it('ignores its own removal when the remove icon is touched and dragged', function() {
var selectItemIcon = TestUtils.findRenderedDOMComponentWithClass(value, 'Select-value-icon');
TestUtils.Simulate.touchStart(selectItemIcon);
TestUtils.Simulate.touchMove(selectItemIcon);
TestUtils.Simulate.touchEnd(selectItemIcon);
expect(props.onRemove, 'was not called');
});
describe('without a custom click handler', function() {
it('presents the given label', function() {
var selectItemLabel = TestUtils.findRenderedDOMComponentWithClass(value, 'Select-value-label');
expect(ReactDOM.findDOMNode(selectItemLabel), 'to have text', OPTION.label);
});
});
describe('with a custom click handler', function() {
var valueLabel;
beforeEach(function() {
props = {
value: OPTION,
onRemove: sinon.spy(),
onClick: sinon.spy(),
};
value = TestUtils.renderIntoDocument(<Value {...props}>{OPTION.label}</Value>);
valueLabel = TestUtils.findRenderedDOMComponentWithClass(value, 'Select-value-label');
});
it('presents the given label', function() {
expect(ReactDOM.findDOMNode(valueLabel), 'to have text', OPTION.label);
});
it('calls a custom callback when the anchor is clicked', function() {
TestUtils.Simulate.mouseDown(valueLabel);
expect(props.onClick, 'was called');
});
it('calls a custom callback when the anchor is touched', function() {
TestUtils.Simulate.touchEnd(valueLabel);
expect(props.onClick, 'was called');
});
});
});
|
/*
jQuery Tags Input Plugin 1.3.3
Copyright (c) 2011 XOXCO, Inc
Documentation for this plugin lives here:
http://xoxco.com/clickable/jquery-tags-input
Licensed under the MIT license:
http://www.opensource.org/licenses/mit-license.php
ben@xoxco.com
*/
(function($) {
var delimiter = new Array();
var tags_callbacks = new Array();
$.fn.doAutosize = function(o){
var minWidth = $(this).data('minwidth'),
maxWidth = $(this).data('maxwidth'),
val = '',
input = $(this),
testSubject = $('#'+$(this).data('tester_id'));
if (val === (val = input.val())) {return;}
// Enter new content into testSubject
var escaped = val.replace(/&/g, '&').replace(/\s/g,' ').replace(/</g, '<').replace(/>/g, '>');
testSubject.html(escaped);
// Calculate new width + whether to change
var testerWidth = testSubject.width(),
newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth,
currentWidth = input.width(),
isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth)
|| (newWidth > minWidth && newWidth < maxWidth);
// Animate width
if (isValidWidthChange) {
input.width(newWidth);
}
};
$.fn.resetAutosize = function(options){
// alert(JSON.stringify(options));
var minWidth = $(this).data('minwidth') || options.minInputWidth || $(this).width(),
maxWidth = $(this).data('maxwidth') || options.maxInputWidth || ($(this).closest('.tagsinput').width() - options.inputPadding),
val = '',
input = $(this),
testSubject = $('<tester/>').css({
position: 'absolute',
top: -9999,
left: -9999,
width: 'auto',
fontSize: input.css('fontSize'),
fontFamily: input.css('fontFamily'),
fontWeight: input.css('fontWeight'),
letterSpacing: input.css('letterSpacing'),
whiteSpace: 'nowrap'
}),
testerId = $(this).attr('id')+'_autosize_tester';
if(! $('#'+testerId).length > 0){
testSubject.attr('id', testerId);
testSubject.appendTo('body');
}
input.data('minwidth', minWidth);
input.data('maxwidth', maxWidth);
input.data('tester_id', testerId);
input.css('width', minWidth);
};
$.fn.addTag = function(value,options) {
options = jQuery.extend({focus:false,callback:true},options);
this.each(function() {
var id = $(this).attr('id');
var tagslist = $(this).val().split(delimiter[id]);
if (tagslist[0] == '') {
tagslist = new Array();
}
value = jQuery.trim(value);
if (options.unique) {
var skipTag = $(this).tagExist(value);
if(skipTag == true) {
//Marks fake input as not_valid to let styling it
$('#'+id+'_tag').addClass('not_valid');
}
} else {
var skipTag = false;
}
if (value !='' && skipTag != true) {
$('<span>').addClass('tag').append(
$('<span>').text(value).append(' '),
$('<a class="tagsinput-remove-link icon-remove">', {
href : '#',
title : 'Remove tag',
text : ''
}).click(function () {
return $('#' + id).removeTag(escape(value));
})
).insertBefore('#' + id + '_addTag');
tagslist.push(value);
$('#'+id+'_tag').val('');
if (options.focus) {
$('#'+id+'_tag').focus();
} else {
$('#'+id+'_tag').blur();
}
$.fn.tagsInput.updateTagsField(this,tagslist);
if (options.callback && tags_callbacks[id] && tags_callbacks[id]['onAddTag']) {
var f = tags_callbacks[id]['onAddTag'];
f.call(this, value);
}
if(tags_callbacks[id] && tags_callbacks[id]['onChange'])
{
var i = tagslist.length;
var f = tags_callbacks[id]['onChange'];
f.call(this, $(this), tagslist[i-1]);
}
}
});
return false;
};
$.fn.removeTag = function(value) {
value = unescape(value);
this.each(function() {
var id = $(this).attr('id');
var old = $(this).val().split(delimiter[id]);
$('#'+id+'_tagsinput .tag').remove();
str = '';
for (i=0; i< old.length; i++) {
if (old[i]!=value) {
str = str + delimiter[id] +old[i];
}
}
$.fn.tagsInput.importTags(this,str);
if (tags_callbacks[id] && tags_callbacks[id]['onRemoveTag']) {
var f = tags_callbacks[id]['onRemoveTag'];
f.call(this, value);
}
});
return false;
};
$.fn.tagExist = function(val) {
var id = $(this).attr('id');
var tagslist = $(this).val().split(delimiter[id]);
return (jQuery.inArray(val, tagslist) >= 0); //true when tag exists, false when not
};
// clear all existing tags and import new ones from a string
$.fn.importTags = function(str) {
id = $(this).attr('id');
$('#'+id+'_tagsinput .tag').remove();
$.fn.tagsInput.importTags(this,str);
}
$.fn.tagsInput = function(options) {
var settings = jQuery.extend({
interactive:true,
defaultText:'',
minChars:0,
width:'',
height:'',
autocomplete: {selectFirst: false },
'hide':true,
'delimiter':',',
'unique':true,
removeWithBackspace:true,
placeholderColor:'#666666',
autosize: true,
comfortZone: 20,
inputPadding: 6*2
},options);
this.each(function() {
if (settings.hide) {
$(this).hide();
}
var id = $(this).attr('id');
if (!id || delimiter[$(this).attr('id')]) {
id = $(this).attr('id', 'tags' + new Date().getTime()).attr('id');
}
var data = jQuery.extend({
pid:id,
real_input: '#'+id,
holder: '#'+id+'_tagsinput',
input_wrapper: '#'+id+'_addTag',
fake_input: '#'+id+'_tag'
},settings);
delimiter[id] = data.delimiter;
if (settings.onAddTag || settings.onRemoveTag || settings.onChange) {
tags_callbacks[id] = new Array();
tags_callbacks[id]['onAddTag'] = settings.onAddTag;
tags_callbacks[id]['onRemoveTag'] = settings.onRemoveTag;
tags_callbacks[id]['onChange'] = settings.onChange;
}
var markup = '<div id="'+id+'_tagsinput" class="tagsinput"><div class="tagsinput-add-container" id="'+id+'_addTag"><div class="tagsinput-add icon-plus"></div>';
if (settings.interactive) {
markup = markup + '<input id="'+id+'_tag" value="" data-default="'+settings.defaultText+'" />';
}
markup = markup + '</div></div>';
$(markup).insertAfter(this);
$(data.holder).css('width',settings.width);
$(data.holder).css('min-height',settings.height);
$(data.holder).css('height','100%');
if ($(data.real_input).val()!='') {
$.fn.tagsInput.importTags($(data.real_input),$(data.real_input).val());
}
if (settings.interactive) {
$(data.fake_input).val($(data.fake_input).attr('data-default'));
$(data.fake_input).css('color',settings.placeholderColor);
$(data.fake_input).resetAutosize(settings);
$(data.holder).bind('click',data,function(event) {
$(event.data.fake_input).focus();
});
$(data.fake_input).bind('focus',data,function(event) {
if ($(event.data.fake_input).val()==$(event.data.fake_input).attr('data-default')) {
$(event.data.fake_input).val('');
}
$(event.data.fake_input).css('color','#000000');
});
if (settings.autocomplete_url != undefined) {
autocomplete_options = {source: settings.autocomplete_url};
for (attrname in settings.autocomplete) {
autocomplete_options[attrname] = settings.autocomplete[attrname];
}
if (jQuery.Autocompleter !== undefined) {
$(data.fake_input).autocomplete(settings.autocomplete_url, settings.autocomplete);
$(data.fake_input).bind('result',data,function(event,data,formatted) {
if (data) {
$('#'+id).addTag(data[0] + "",{focus:true,unique:(settings.unique)});
}
});
} else if (jQuery.ui.autocomplete !== undefined) {
$(data.fake_input).autocomplete(autocomplete_options);
$(data.fake_input).bind('autocompleteselect',data,function(event,ui) {
$(event.data.real_input).addTag(ui.item.value,{focus:true,unique:(settings.unique)});
return false;
});
}
} else {
// if a user tabs out of the field, create a new tag
// this is only available if autocomplete is not used.
$(data.fake_input).bind('blur',data,function(event) {
var d = $(this).attr('data-default');
if ($(event.data.fake_input).val()!='' && $(event.data.fake_input).val()!=d) {
if( (event.data.minChars <= $(event.data.fake_input).val().length) && (!event.data.maxChars || (event.data.maxChars >= $(event.data.fake_input).val().length)) )
$(event.data.real_input).addTag($(event.data.fake_input).val(),{focus:true,unique:(settings.unique)});
} else {
$(event.data.fake_input).val($(event.data.fake_input).attr('data-default'));
$(event.data.fake_input).css('color',settings.placeholderColor);
}
return false;
});
}
// if user types a comma, create a new tag
$(data.fake_input).bind('keypress',data,function(event) {
if (event.which==event.data.delimiter.charCodeAt(0) || event.which==13 ) {
event.preventDefault();
if( (event.data.minChars <= $(event.data.fake_input).val().length) && (!event.data.maxChars || (event.data.maxChars >= $(event.data.fake_input).val().length)) )
$(event.data.real_input).addTag($(event.data.fake_input).val(),{focus:true,unique:(settings.unique)});
$(event.data.fake_input).resetAutosize(settings);
return false;
} else if (event.data.autosize) {
$(event.data.fake_input).doAutosize(settings);
}
});
//Delete last tag on backspace
data.removeWithBackspace && $(data.fake_input).bind('keydown', function(event)
{
if(event.keyCode == 8 && $(this).val() == '')
{
event.preventDefault();
var last_tag = $(this).closest('.tagsinput').find('.tag:last').text();
var id = $(this).attr('id').replace(/_tag$/, '');
last_tag = last_tag.replace(/[\s\u00a0]+x$/, '');
$('#' + id).removeTag(escape(last_tag));
$(this).trigger('focus');
}
});
$(data.fake_input).blur();
//Removes the not_valid class when user changes the value of the fake input
if(data.unique) {
$(data.fake_input).keydown(function(event){
if(event.keyCode == 8 || String.fromCharCode(event.which).match(/\w+|[áéíóúÁÉÍÓÚñÑ,/]+/)) {
$(this).removeClass('not_valid');
}
});
}
} // if settings.interactive
});
return this;
};
$.fn.tagsInput.updateTagsField = function(obj,tagslist) {
var id = $(obj).attr('id');
$(obj).val(tagslist.join(delimiter[id]));
};
$.fn.tagsInput.importTags = function(obj,val) {
$(obj).val('');
var id = $(obj).attr('id');
var tags = val.split(delimiter[id]);
for (i=0; i<tags.length; i++) {
$(obj).addTag(tags[i],{focus:false,callback:false});
}
if(tags_callbacks[id] && tags_callbacks[id]['onChange'])
{
var f = tags_callbacks[id]['onChange'];
f.call(obj, obj, tags[i]);
}
};
})(jQuery);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.