code
stringlengths
2
1.05M
Capybara = { nextIndex: 0, nodes: {}, attachedFiles: [], keyModifiersStack: [], invoke: function () { try { if (CapybaraInvocation.functionName == "leftClick") { var args = CapybaraInvocation.arguments; var leftClickOptions = this["verifiedClickPosition"].apply(this, args); leftClickOptions["keys"] = JSON.parse(args[1]); offset = JSON.parse(args[2]); if (offset && offset.x && offset.y){ leftClickOptions["absoluteX"] = leftClickOptions["absoluteLeft"] + offset.x; leftClickOptions["absoluteY"] = leftClickOptions["absoluteTop"] + offset.y; } return leftClickOptions; } else { return this[CapybaraInvocation.functionName].apply(this, CapybaraInvocation.arguments); } } catch (e) { CapybaraInvocation.error = e; } }, findXpath: function (xpath) { return this.findXpathRelativeTo(document, xpath); }, findCss: function (selector) { return this.findCssRelativeTo(document, selector); }, findXpathWithin: function (index, xpath) { return this.findXpathRelativeTo(this.getNode(index), xpath); }, findCssWithin: function (index, selector) { return this.findCssRelativeTo(this.getNode(index), selector); }, findXpathRelativeTo: function (reference, xpath) { var iterator = document.evaluate(xpath, reference, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null); var node; var results = []; while (node = iterator.iterateNext()) { results.push(this.registerNode(node)); } return results.join(","); }, findCssRelativeTo: function (reference, selector) { var elements = reference.querySelectorAll(selector); var results = []; for (var i = 0; i < elements.length; i++) { results.push(this.registerNode(elements[i])); } return results.join(","); }, isAttached: function(index) { return this.nodes[index] && document.evaluate("ancestor-or-self::html", this.nodes[index], null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue != null; }, getNode: function(index) { if (CapybaraInvocation.allowUnattached || this.isAttached(index)) { return this.nodes[index]; } else { throw new Capybara.NodeNotAttachedError(index); } }, text: function (index) { var node = this.getNode(index); var type = node instanceof HTMLFormElement ? 'form' : (node.type || node.tagName).toLowerCase(); if (!this.isNodeVisible(node)) { return ''; } else if (type == "textarea") { return node.innerHTML; } else { visible_text = node.innerText; return typeof visible_text === "string" ? visible_text : node.textContent; } }, allText: function (index) { var node = this.getNode(index); return node.textContent; }, attribute: function (index, name) { var node = this.getNode(index); if (node.hasAttribute(name)) { return node.getAttribute(name); } return void 0; }, property: function (index, name) { var node = this.getNode(index); return node[name]; }, hasAttribute: function(index, name) { return this.getNode(index).hasAttribute(name); }, path: function(index) { return this.pathForNode(this.getNode(index)); }, pathForNode: function(node) { return "/" + this.getXPathNode(node).join("/"); }, getXPathNode: function(node, path) { path = path || []; if (node.parentNode) { path = this.getXPathNode(node.parentNode, path); } var first = node; while (first.previousSibling) first = first.previousSibling; var count = 0; var index = 0; var iter = first; while (iter) { if (iter.nodeType == 1 && iter.nodeName == node.nodeName) count++; if (iter.isSameNode(node)) index = count; iter = iter.nextSibling; continue; } if (node.nodeType == 1) path.push(node.nodeName.toLowerCase() + (node.id ? "[@id='"+node.id+"']" : count > 1 ? "["+index+"]" : '')); return path; }, tagName: function(index) { return this.getNode(index).tagName.toLowerCase(); }, submit: function(index) { return this.getNode(index).submit(); }, expectNodeAtPosition: function(node, pos) { var nodeAtPosition = document.elementFromPoint(pos.relativeX, pos.relativeY); var overlappingPath; if (nodeAtPosition) overlappingPath = this.pathForNode(nodeAtPosition) if (!this.isNodeOrChildAtPosition(node, pos, nodeAtPosition)) throw new Capybara.ClickFailed( this.pathForNode(node), overlappingPath, pos ); }, isNodeOrChildAtPosition: function(expectedNode, pos, currentNode) { if (currentNode == expectedNode) { return CapybaraInvocation.clickTest( expectedNode, pos.absoluteX, pos.absoluteY ); } else if (currentNode) { return this.isNodeOrChildAtPosition( expectedNode, pos, currentNode.parentNode ); } else { return false; } }, clickPosition: function(node) { if(node.namespaceURI == 'http://www.w3.org/2000/svg') { var rect = node.getBoundingClientRect(); if (rect.width > 0 && rect.height > 0) return CapybaraInvocation.clickPosition(node, rect.left, rect.top, rect.width, rect.height); } else { var rects = node.getClientRects(); var rect; for (var i = 0; i < rects.length; i++) { rect = rects[i]; if (rect.width > 0 && rect.height > 0) return CapybaraInvocation.clickPosition(node, rect.left, rect.top, rect.width, rect.height); } } var visible = this.isNodeVisible(node); throw new Capybara.UnpositionedElement(this.pathForNode(node), visible); }, verifiedClickPosition: function (index) { var node = this.getNode(index); node.scrollIntoViewIfNeeded(); var pos = this.clickPosition(node); CapybaraInvocation.hover(pos.relativeX, pos.relativeY); this.expectNodeAtPosition(node, pos); return pos; }, click: function (index, action, keys, offset) { var pos = this.verifiedClickPosition(index); keys = keys ? JSON.parse(keys) : []; offset = offset ? JSON.parse(offset) : {}; if (offset && (offset.x != null) && (offset.y != null)){ action(pos.absoluteLeft + offset.x, pos.absoluteTop + offset.y, keys); } else { action(pos.absoluteX, pos.absoluteY, keys); } }, leftClick: function (index, keys, offset) { this.click(index, CapybaraInvocation.leftClick, keys, offset); }, doubleClick: function(index, keys, offset) { this.click(index, CapybaraInvocation.leftClick, keys, offset); this.click(index, CapybaraInvocation.doubleClick, keys, offset); }, rightClick: function(index, keys, offset) { this.click(index, CapybaraInvocation.rightClick, keys, offset); }, hover: function (index) { var node = this.getNode(index); node.scrollIntoViewIfNeeded(); var pos = this.clickPosition(node); CapybaraInvocation.hover(pos.absoluteX, pos.absoluteY); }, trigger: function (index, eventName) { this.triggerOnNode(this.getNode(index), eventName); }, triggerOnNode: function(node, eventName) { var eventObject = document.createEvent("HTMLEvents"); eventObject.initEvent(eventName, true, true); node.dispatchEvent(eventObject); }, visible: function (index) { return this.isNodeVisible(this.getNode(index)); }, isNodeVisible: function(node) { var style = node.ownerDocument.defaultView.getComputedStyle(node, null); // Only check computed visibility style on current node since it // will inherit from nearest ancestor with a setting and overrides // any farther ancestors if (style.getPropertyValue('visibility') == 'hidden' || style.getPropertyValue('display') == 'none') return false; // Must check CSS display setting for all ancestors while (node = node.parentElement) { style = node.ownerDocument.defaultView.getComputedStyle(node, null); if (style.getPropertyValue('display') == 'none' ) return false; } return true; }, selected: function (index) { return this.getNode(index).selected; }, value: function(index) { return this.getNode(index).value; }, getInnerHTML: function(index) { return this.getNode(index).innerHTML; }, setInnerHTML: function(index, value) { this.getNode(index).innerHTML = value; return true; }, sendKeys: function (elem_index, json_keys) { var idx, length, keys; keys = JSON.parse(json_keys); length = keys.length; if (length) { this.focus(elem_index); } for (idx = 0; idx < length; idx++) { this._sendKeys(keys[idx]); } }, _sendKeys: function(keys) { if (typeof keys == "string") { var str_len = keys.length; var str_idx; for (str_idx = 0; str_idx < str_len; str_idx++) { CapybaraInvocation.keypress(keys[str_idx]); } } else if (Array.isArray(keys)) { this.keyModifiersStack.push([]); var idx; for (idx = 0; idx < keys.length; idx++) { this._sendKeys(keys[idx]); } var mods = this.keyModifiersStack.pop(); while (mods.length) { CapybaraInvocation.namedKeyup(mods.pop().key); } } else { key = keys.key; if (["Shift", "Control", "Alt", "Meta"].indexOf(key) > -1){ CapybaraInvocation.namedKeydown(key); this.keyModifiersStack[this.keyModifiersStack.length-1].push(keys); } else { CapybaraInvocation.namedKeypress(key, keys.modifier); } } }, set: function (index, value) { var length, maxLength, node, strindex, textTypes, type; node = this.getNode(index); type = (node.type || node.tagName).toLowerCase(); textTypes = ["email", "number", "password", "search", "tel", "text", "textarea", "url"]; if (textTypes.indexOf(type) != -1) { maxLength = this.attribute(index, "maxlength"); if (maxLength && value.length > maxLength) { length = maxLength; } else { length = value.length; } if (!node.readOnly) { this.focus(index); node.value = ""; for (strindex = 0; strindex < length; strindex++) { CapybaraInvocation.keypress(value[strindex]); } if (value === "") { this.trigger(index, "change"); } } } else if (type === "checkbox" || type === "radio") { if (node.checked != (value === "true")) { this.leftClick(index); } } else if (type === "file") { this.attachedFiles = Array.prototype.slice.call(arguments, 1); this.leftClick(index); } else if (this.isContentEditable(node)) { var content = document.createTextNode(value); node.innerHTML = ''; node.appendChild(content); } else { node.value = value; } }, isContentEditable: function(node) { if (node.contentEditable == 'true') { return true; } else if (node.contentEditable == 'false') { return false; } else if (node.contentEditable == 'inherit') { return this.isContentEditable(node.parentNode); } }, focus: function(index) { this.getNode(index).focus(); }, focus_frame: function(index) { var elem = this.getNode(index); if (elem === document.activeElement) { elem.blur(); } elem.focus(); }, selectOption: function(index){ this._setOption(index, true); }, unselectOption: function(index){ this._setOption(index, false); }, _setOption: function(index, state) { var optionNode = this.getNode(index); var selectNode = optionNode.parentNode; if (selectNode.tagName == "OPTGROUP") selectNode = selectNode.parentNode; if (optionNode.disabled) return; if ((!selectNode.multiple) && (!state)) return; // click on select list this.triggerOnNode(selectNode, 'mousedown'); selectNode.focus(); this.triggerOnNode(selectNode, 'input'); // select/deselect option from list if (optionNode.selected != state){ optionNode.selected = state; this.triggerOnNode(selectNode, 'change'); } this.triggerOnNode(selectNode, 'mouseup'); this.triggerOnNode(selectNode, 'click'); }, centerPosition: function(element) { this.reflow(element); var rect = element.getBoundingClientRect(); var position = { x: rect.width / 2, y: rect.height / 2 }; do { position.x += element.offsetLeft; position.y += element.offsetTop; } while ((element = element.offsetParent)); position.x = Math.floor(position.x); position.y = Math.floor(position.y); return position; }, reflow: function(element, force) { if (force || element.offsetWidth === 0) { var prop, oldStyle = {}, newStyle = {position: "absolute", visibility : "hidden", display: "block" }; for (prop in newStyle) { oldStyle[prop] = element.style[prop]; element.style[prop] = newStyle[prop]; } // force reflow element.offsetWidth; element.offsetHeight; for (prop in oldStyle) element.style[prop] = oldStyle[prop]; } }, dragTo: function (index, targetIndex) { var element = this.getNode(index), target = this.getNode(targetIndex); var position = this.centerPosition(element); var options = { clientX: position.x, clientY: position.y }; var mouseTrigger = function(eventName, options) { var eventObject = document.createEvent("MouseEvents"); eventObject.initMouseEvent(eventName, true, true, window, 0, 0, 0, options.clientX || 0, options.clientY || 0, false, false, false, false, 0, null); element.dispatchEvent(eventObject); }; mouseTrigger('mousedown', options); options.clientX += 1; options.clientY += 1; mouseTrigger('mousemove', options); position = this.centerPosition(target); options = { clientX: position.x, clientY: position.y }; mouseTrigger('mousemove', options); mouseTrigger('mouseup', options); }, registerNode: function(node) { this.nextIndex++; this.nodes[this.nextIndex] = node; return this.nextIndex; }, equals: function(index, targetIndex) { return this.getNode(index) === this.getNode(targetIndex); }, _visitedObjects: [], wrapResult: function(arg) { if (this._visitedObjects.indexOf(arg) >= 0) { return '(cyclic structure)'; } if (arg instanceof NodeList) { arg = Array.prototype.slice.call(arg, 0); } if (Array.isArray(arg)) { for(var _j = 0; _j < arg.length; _j++) { arg[_j] = this.wrapResult(arg[_j]); } } else if (arg && arg.nodeType == 1 && arg.tagName) { return {'element-581e-422e-8be1-884c4e116226': this.registerNode(arg)}; } else if (arg === null) { return undefined; } else if (arg instanceof Date){ return arg; } else if ( typeof arg == 'object' ) { this._visitedObjects.push(arg); var result = {}; for(var _k in arg){ result[_k] = this.wrapResult(arg[_k]); } this._visitedObjects.pop(); return result; } return arg; } }; Capybara.ClickFailed = function(expectedPath, actualPath, position) { this.name = 'Capybara.ClickFailed'; this.message = 'Failed to click element ' + expectedPath; if (actualPath) this.message += ' because of overlapping element ' + actualPath; if (position) this.message += ' at position ' + position["absoluteX"] + ', ' + position["absoluteY"]; else this.message += ' at unknown position'; this.message += "; \nA screenshot of the page at the time of the failure has been written to " + CapybaraInvocation.render(); }; Capybara.ClickFailed.prototype = new Error(); Capybara.ClickFailed.prototype.constructor = Capybara.ClickFailed; Capybara.UnpositionedElement = function(path, visible) { this.name = 'Capybara.ClickFailed'; this.message = 'Failed to find position for element ' + path; if (!visible) this.message += ' because it is not visible'; }; Capybara.UnpositionedElement.prototype = new Error(); Capybara.UnpositionedElement.prototype.constructor = Capybara.UnpositionedElement; Capybara.NodeNotAttachedError = function(index) { this.name = 'Capybara.NodeNotAttachedError'; this.message = 'Element at ' + index + ' no longer present in the DOM'; }; Capybara.NodeNotAttachedError.prototype = new Error(); Capybara.NodeNotAttachedError.prototype.constructor = Capybara.NodeNotAttachedError;
import express from 'express'; import bodyParser from 'body-parser'; import path from 'path'; const app = express(); // allow cross-origin requests app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); // configure app to use bodyParser() // this will let us get the data from a POST app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // REGISTER OUR ROUTES // public-facing application route app.use(express.static(path.resolve(__dirname, '../build'))); app.use('/', require('./public/main')); // all of our API routes will prefixed with /api app.use('/api', require('./api/companies')); app.use('/api', require('./api/roles')); export default app;
'use strict'; module.exports = lastContainedIndex; function lastContainedIndex(maxIndex, indexesArray) { while (indexesArray.indexOf(maxIndex) === -1) { maxIndex--; } return maxIndex; }
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* * Copyright (C) 2013, 2014 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ WebInspector.DashboardManager = (function (_WebInspector$Object) { _inherits(DashboardManager, _WebInspector$Object); function DashboardManager() { _classCallCheck(this, DashboardManager); _get(Object.getPrototypeOf(DashboardManager.prototype), "constructor", this).call(this); this._dashboards = {}; this._dashboards["default"] = new WebInspector.DefaultDashboard(); this._dashboards["debugger"] = new WebInspector.DebuggerDashboard(); this._dashboards.replay = new WebInspector.ReplayDashboard(); } _createClass(DashboardManager, [{ key: "dashboards", get: function get() { return this._dashboards; } }]); return DashboardManager; })(WebInspector.Object);
version https://git-lfs.github.com/spec/v1 oid sha256:295eaea121e63329af0104e60bdf15ec28f4bef432c5845f73b0ceaa64e098bc size 38825
angular.module('app.services',['services-users', 'services-posts']) .service('dbPath', function($location){ if($location.$$host==='localhost'){ this.path= $location.$$protocol+'://'+$location.$$host+':'+$location.$$port; }else{ this.path=$location.$$protocol+'://'+$location.$$host; } }) .service('getSettings',function($http, $rootScope){ this.init=function(){ return $http.get('/site'); }; }) .service('getMenuItems',function($http, dbPath){ this.init=function(){return $http.get(dbPath.path+'/posts?{"isMenuItem":true,"$fields":{"slug":1,"title":1}}'); }; }) .service('menuOrderList', function(){ return function(){ var arr=[]; for(var i=-10; i<11; i++){ var idx=i; arr.push({"value":i, "name":i}); } return arr; }; }) .service('stopScroll', function($window){ this.init=function(){ $(window).scroll(function(){ $window.scrollTo(0,0); $(window).off('scroll'); }); }; }) .service('getMedia', function($http, dbPath){ this.init=function(){ return $http.get(dbPath.path+'/media'); }; }) ;
$(function () { var RELOAD = 5000, TIMEOUT = 2000, SHIFT = 20, PERCISION = 2; var SERIES = {}; var table = $('#containers').DataTable({ "ajax": "/api/ps", "columns": [ { "title": "Container ID", "data": "Id" }, { "title": "Image", "data": "Image" }, { "title": "Command", "data": "Command" }, { "title": "Created", "data": "Created" }, { "title": "Status", "data": "Status" }, { "title": "Ports", "data": "Ports[0].PublicPort" }, { "title": "Names", "data": "Names" } ], "aoColumnDefs": [{ "aTargets": [ 0 ], "mRender": function (data, type, full) { return data.slice(0, 12); } }], "fnInitComplete": function (settings) { if (settings.json) { for (var i = 0; i < settings.json.data.length; i++) { var hash = settings.json.data[i].Id.slice(0, 12); SERIES[hash] = chart.addSeries({ name: settings.json.data[i].Names[0] }); } updateCharts(); setInterval(updateCharts, TIMEOUT); } }, "fnDrawCallback": function(settings) { if (settings.json) { for (var i = 0; i < settings.json.data.length; i++) { console.log(settings.json.data[i].Id); } } } }); setTimeout(function () { table.ajax.reload(null, false); }, RELOAD); function getStats(hash) { $.getJSON('/api/curated/' + hash, function (data) { var series = SERIES[hash], shift = series.data.length > SHIFT; series.addPoint(parseFloat(data.cpu_percent.toFixed(PERCISION)), true, shift); }); } function updateCharts() { for (var hash in SERIES) { getStats(hash); } } var chart = new Highcharts.Chart({ chart: { renderTo: 'charts' }, credits: { enabled: false }, title: { text : 'CPU %' }, exporting: { enabled: false } }); });
import { Mongo } from 'meteor/mongo'; RocketChat.Migrations.add({ version: 42, up() { const files = RocketChat.__migration_assets_files = new Mongo.Collection('assets.files'); const chunks = RocketChat.__migration_assets_chunks = new Mongo.Collection('assets.chunks'); const list = { 'favicon.ico': 'favicon_ico', 'favicon.svg': 'favicon', 'favicon_64.png': 'favicon_64', 'favicon_96.png': 'favicon_96', 'favicon_128.png': 'favicon_128', 'favicon_192.png': 'favicon_192', 'favicon_256.png': 'favicon_256', }; for (const from of Object.keys(list)) { const to = list[from]; const query = { _id: to, }; if (!files.findOne(query)) { const oldFile = files.findOne({ _id: from, }); if (oldFile) { const extension = RocketChat.Assets.mime.extension(oldFile.contentType); RocketChat.settings.removeById(`Assets_${ from }`); RocketChat.settings.updateById(`Assets_${ to }`, { url: `/assets/${ to }.${ extension }`, defaultUrl: RocketChat.Assets.assets[to].defaultUrl, }); oldFile._id = to; oldFile.filename = to; files.insert(oldFile); files.remove({ _id: from, }); chunks.update({ files_id: from, }, { $set: { files_id: to, }, }, { multi: true, }); } } } }, });
(function() { var locations = angular.module("locations", [ ], function($interpolateProvider) { $interpolateProvider.startSymbol('[['); $interpolateProvider.endSymbol(']]'); }); locations.controller("LocationsController", [ '$http', function($http) { var locations = this; locations.list = []; $http.get("/locations").success(function(data) { locations.list = data; }); }]); })();
version https://git-lfs.github.com/spec/v1 oid sha256:bc18c14cf7bdcb08a36e0ef050472c62cbdd2047f2ea2999cab1249399b24d91 size 2895
describe('Filter', function() { let Filter = require('../../validators/filter'); let attribute = 'notFiltered'; it('Filter', (done) => { let value = ' Test '; let model = {}; model[attribute] = value; let errors = {}; let validator = new Filter(attribute, { model, errors, filter: value => value.trim(), }); validator .validate() .then(res => { expect(res).toBe(value.trim()); done(); }) .catch(err => {}); }); });
'use strict';var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var di_1 = require('angular2/di'); var PipeBinding = (function (_super) { __extends(PipeBinding, _super); function PipeBinding(name, key, factory, dependencies) { _super.call(this, key, factory, dependencies); this.name = name; } PipeBinding.createFromType = function (type, metadata) { var binding = new di_1.Binding(type, { toClass: type }); var rb = binding.resolve(); return new PipeBinding(metadata.name, rb.key, rb.factory, rb.dependencies); }; return PipeBinding; })(di_1.ResolvedBinding); exports.PipeBinding = PipeBinding; //# sourceMappingURL=pipe_binding.js.map
"use strict"; var React = require('react/addons') var TestUtils = React.addons.TestUtils var proxyquire = require('proxyquire') require('../../test/setup') var envStub = {} var configStub = {common: {'host': '127.0.0.1', 'port': 3000, 'apiBasePath': '/api'}} var Global = proxyquire('../../src/common/Global', { './utils/env': envStub, 'config': configStub } ) describe('Global component', () => { var globalElement before('renders components and locates elements', () => { var components = TestUtils.renderIntoDocument( < Global / > ) var globalComponent = TestUtils.findRenderedDOMComponentWithTag( components, 'span' ) globalElement = globalComponent.getDOMNode() }) it('should render in the document', () => { expect(globalElement).to.exist }) context('when run in the client', () => { before(() => { envStub.CLIENT = true envStub.SERVER = false }) context('getConfig method', () => { it('should return the config set in the global window', () => { global.window.__CONFIG__ = {'test': 'test'} expect(Global.getConfig()).to.equal(global.window.__CONFIG__) }) it('should throw an exception when no config is set in the global window', () => { global.window.__CONFIG__ = undefined expect(Global.getConfig).to.throw(Error) }) }) context('getBaseUrl method', () => { it('should return the base URL to be used in a client environment', () => { global.window.__CONFIG__ = {'port': 3000, 'apiBasePath': '/api'} expect(Global.getBaseUrl()).to.equal('') }) }) context('getApiBaseUrl method', () => { it('should return the api base URL to be used in a client environment', () => { global.window.__CONFIG__ = {'common': {'port': 3000, 'apiBasePath': '/api'}} expect(Global.getApiBaseUrl()).to.equal('/api') }) }) context('getCookie method', () => { it('should return the cookie which name has been specified as a parameter', () => { global.window.document.cookie = 'accessToken=O1lbi7zyBbrrWDMWmbhgsbuJWIihU9hdfkSNqBEzfcisTtqmGcSwk3cZib0k1xrn;' expect(Global.getCookie('accessToken')).to.equal('O1lbi7zyBbrrWDMWmbhgsbuJWIihU9hdfkSNqBEzfcisTtqmGcSwk3cZib0k1xrn') }) }) context('getSessionApiBaseUrl method', () => { it('should return the session api base URL to be used in a client environment', () => { global.window.document.cookie = 'accessToken=O1lbi7zyBbrrWDMWmbhgsbuJWIihU9hdfkSNqBEzfcisTtqmGcSwk3cZib0k1xrn;' global.window.__CONFIG__ = {'common': {'port': 3000, 'apiBasePath': '/api'}, 'client': {'injectSessionIdInURL': true}} expect(Global.getSessionApiBaseUrl()).to.equal('/api/session/O1lbi7zyBbrrWDMWmbhgsbuJWIihU9hdfkSNqBEzfcisTtqmGcSwk3cZib0k1xrn') }) }) context('getAccessToken method', () => { it('should return the cookie accessToken', () => { global.window.document.cookie = 'accessToken=O1lbi7zyBbrrWDMWmbhgsbuJWIihU9hdfkSNqBEzfcisTtqmGcSwk3cZib0k1xrn;' expect(Global.getAccessToken('O1lbi7zyBbrrWDMWmbhgsbuJWIihU9hdfkSNqBEzfcisTtqmGcSwk3cZib0k1xrn')).to.equal('O1lbi7zyBbrrWDMWmbhgsbuJWIihU9hdfkSNqBEzfcisTtqmGcSwk3cZib0k1xrn') }) }) }) context('when run in the server', () => { before(() => { envStub.CLIENT = false envStub.SERVER = true }) context('getConfig method', () => { it('should return the config from the server', () => { expect(Global.getConfig()).to.equal(configStub) }) }) context('getBaseUrl method', () => { it('should return the base URL to be used in a server environment', () => { expect(Global.getBaseUrl()).to.equal("http://127.0.0.1:3000") }) }) context('getApiBaseUrl method', () => { it('should return the api base URL to be used in a server environment', () => { expect(Global.getApiBaseUrl()).to.equal("http://127.0.0.1:3000/api") }) }) context('getCookie method', () => { it('should an exception when executed in a server environment', () => { expect(Global.getCookie).to.throw(Error) }) }) context('getSessionApiBaseUrl method', () => { it('should return the session api base URL to be used in a server environment', () => { expect(Global.getSessionApiBaseUrl('O1lbi7zyBbrrWDMWmbhgsbuJWIihU9hdfkSNqBEzfcisTtqmGcSwk3cZib0k1xrn')).to.equal('http://127.0.0.1:3000/api/session/O1lbi7zyBbrrWDMWmbhgsbuJWIihU9hdfkSNqBEzfcisTtqmGcSwk3cZib0k1xrn') }) }) context('getAccessToken method', () => { it('should return the given accessToken instead of asking for cookie', () => { expect(Global.getAccessToken('O1lbi7zyBbrrWDMWmbhgsbuJWIihU9hdfkSNqBEzfcisTtqmGcSwk3cZib0k1xrn')).to.equal('O1lbi7zyBbrrWDMWmbhgsbuJWIihU9hdfkSNqBEzfcisTtqmGcSwk3cZib0k1xrn') }) }) }) });
/** * author:oppoffice * date:2017.1 */ ;(function(){ function getFileName(file){ return file.replace(/.*(\/|\\)/, ""); } function getExt(str){ return /\.[^\.]+$/.exec(str); } function addEvent(el,type,fn){ if(typeof el ==='undefined' || el.nodeType!==1){ return; } if(window.addEventListener){ el.addEventListener(type,fn,false); }else if(window.attachEvent){ el.attachEvent("on"+type,fn); }else{ el["on"+type]=fn; } } var toElement=(function(){ return function(sdoc){ var div=document.createElement('div'), newNode=null; div.innerHTML=sdoc; newNode=div.childNodes[0]; div=null; return newNode; } })(); function trim(s){ return s && s.replace(/(^\s*)|(\s+$)/,''); } function noop(){} function toJSON(s){ s=trim(s); if(s && s[0]==='{' && s[s.length-1]==='}'){ if(typeof JSON!=='undefined' && typeof JSON.parse==='function'){ return JSON.parse(s); }else { try { return window.eval('('+s+')'); } catch (error) { return s; } } }else{ return s; } } function AjaxUpload(options){ var me=this; me._input=null; me._iframe=null; me._form=null; me.disabled=false; me.settings={ btn:null, action:'upload.php', name:'file', onClick:noop, onChange:noop, onSubmit:noop, onComplete:noop, submitText:'上传中...' }; for(var i in options){ me.settings[i]=options[i]; } if(me.settings.btn==null){ return; } me.init(); } AjaxUpload.prototype={ init:function(){ var me=this; me.createInput(); me.createIframe(); me.createForm(); }, createInput:function(){ var me=this; var w=me.settings.btn.offsetWidth; var h=me.settings.btn.offsetHeight; me._input=toElement('<input type="file" name="'+me.settings.name+'" style="position:absolute;left:0;top:0;z-index:100;width:'+w+'px;height:'+h+'px;line-height:'+h+'px;opacity:0;filter:alpha(opacity=0)";overflow:hidden;/>'); addEvent(me._input,'change',function(ev){ if(me.disabled)return; var ext=getExt(me._input.value||""); if(!(me.settings.onChange.call(me,this,ext)==false)){ me.submit(me._input,ext); } }); addEvent(me._input,'click',function(ev){ me.settings.onClick.call(me); }); }, createIframe:function(){ var me=this; me._iframe=toElement('<iframe id="iframeUpload" name="iframeUpload" src="javascript:false;" style="display:none;"></iframe>'); me.settings.btn.appendChild(me._iframe); }, createForm:function(){ var me=this; me._form=toElement('<form action="'+me.settings.action+'" method="POST" enctype="multipart/form-data" target="iframeUpload"></form>'); me._form.appendChild(me._input); me.settings.btn.appendChild(me._form); }, submit:function(obj,ext){ var me=this; addEvent(me._iframe,'load',function(){ var doc=this.contentDocument||window.frames['iframeUpload'].document, sdoc=doc.body.childNodes[0].innerHTML || doc.body.innerHTML, code=sdoc[0]!='{'?-400:200; var obj=code==200?toJSON(sdoc):sdoc; me.settings.onComplete.call(me,obj,code ,ext); me.destory(); }); if(!(me.settings.onSubmit.call(me,obj,ext)==false)){ me._form.submit(); } }, destory:function(){ var me=this; me.diabled=false; me.settings.btn.removeChild(me._form); me.settings.btn.removeChild(me._iframe); me.createInput(); me.createIframe(); me.createForm(); } } AjaxUpload.upload=(function(){ var au=null; return function(options){ return au===null?(au=new AjaxUpload(options)):au; } })(); if(typeof define === 'function' && typeof define.amd =='object' && define.amd){ define(function(){ return AjaxUpload; }); }else if(typeof module !=='undefined' && module.exports){ module.exports=AjaxUpload.upload; module.exports.AjaxUpload=AjaxUpload; }else{ window.AjaxUpload=AjaxUpload; } })();
/*! * lv.emotions v1.0.0 * Criado para utilizar emoticons em suas páginas web * https://github.com/LucasViniciusPereira * License : MIT * Author : Lucas Vinicius Pereira (http://lucasvinicius.eti.br/) */ (function ($) { $.fn.emotions = function (options) { // Definição dos valores padrões var arrayEmotions = { "0": "Undefined", "1": "o:)", "2": ":3", "3": "o.O", "4": ":'(", "5": "3:)", "6": ":(", "7": ":O", "8": "88)", "9": ":D", "10": "s2", "11": "<3", "12": "-_^", "13": ":*", "14": ":v", "15": ":}~", "16": "´x_x´", "17": "8|", "18": ":p", "19": ":/", "20": "&gt:Z", "21": ";[" }; var nameEmotions = ["undefined", "angel", "smiling", "confused", "cry", "devil", "frown", "wonder", "gratters", "grin", "love", "heart", "boredom", "kiss", "shame", "funny", "squint", "sunglasses", "tongue", "unsure", "sleep", "nervous"]; var defaults = { 'path': 'img-emotions/', 'extension': '.gif', 'campoMensagemID': '#txtMensagem', 'btnEnviaMensagemID': '#btnEnviarMensagem', 'listaEmotionsView': '#lista-emotions', 'exibeMensagemView': '#showHere', 'elementoRetorno': "p" }; // Geração das settings do seu plugin var settings = $.extend({}, defaults, options); /* * Monta a lista de emotions para o usuário clicar no emotion */ $.fn.montaListaEmotionView = function () { var lista = ""; $.each(nameEmotions, function (key, value) { if (value != 'undefined') lista = lista + "<a onclick='$(this).recuperarEmotion(" + key + ")'>" + $(this).montaImagemEmotion(value) + '</a>'; }); $(settings.listaEmotionsView).prepend(lista); }; /* * Ao clicar no emotion ele recupera em qual elemento foi clicado * keyEmotion => index do emotion */ $.fn.recuperarEmotion = function (keyEmotion) { $.each(arrayEmotions, function (key, value) { if (parseInt(key) == keyEmotion) element = value; }); $(settings.campoMensagemID).val($(settings.campoMensagemID).val() + ' ' + element + ' '); }; /* * Monta a imagem do emotion e retorna o html *_name => Qual o nome do arquivo da imagem */ $.fn.montaImagemEmotion = function (_name) { return "<img class='img-emotion' src='" + settings.path + _name + settings.extension + "' />"; } /* * Retorna a mensagem com os emotion *message => Parametro da mensagem */ $.fn.retornaMensagemEmotion = function (message) { //Remove os espaços e separa em array textoDigitado = message.trimLeft().trimRight().toString().split(" "); textoCompleto = ""; //Substitui o carecter digitado pelo emotion for (i = 0; i < textoDigitado.length; i++) { $.each(arrayEmotions, function (key, value) { if (textoDigitado[i] == value) { textoDigitado[i] = $(this).montaImagemEmotion(nameEmotions[key]); } }); } //Imprime todo o texto digitado $.each(textoDigitado, function (key, value) { textoCompleto = textoCompleto + ' ' + value; }); return textoCompleto; } //Init method $(this).montaListaEmotionView(); }; })(jQuery);
GAME.setConsts({ E_MAXVEL : 0.1, B_MAXVEL : 0.1, S_PLAYER : [[-0.5, -0.5], [0.5, -0.5], [0.5, 0.5], [-0.5, 0.5]], S_BULLET : [[0, .5], [-.3, 0.15], [-.3, -.3], [.3, -.3], [.3, 0.15]], E_TYPE_ENEMY : 0, E_TYPE_PLAYER : 1, E_TYPE_BULLET : 2, REPULSION_CONST : 3 / 30, WALL_REPULSION_CONST : 3 / 30, }); GAME.Entity = (function() { function newEntity(x, y, shape, type) { return { x : GAME.defaultTo(x, 5), y : GAME.defaultTo(y, 5), xvel : 0, yvel : 0, angle : 0, accel : 1/30, maxSpeed : GAME.E_MAXVEL, entityType : type, path : [], shape : cloneShape(shape) } } function newEnemy(x, y, shape) { return newEntity(x, y, shape, GAME.E_TYPE_ENEMY); } function newPlayer(x, y, shape) { return newEntity(x, y, shape, GAME.E_TYPE_PLAYER); } function newBullet(x, y, shape) { var bullet = newEntity(x, y, shape, GAME.E_TYPE_BULLET); bullet.path.push([bullet.x, bullet.y]); return bullet; } function cloneShape(shape) { var newShape = []; for (var i = 0; i < shape.length; i++) { newShape.push([shape[i][0], shape[i][1]]); } return newShape; } function step(ent) { var TIME_FACTOR = 0.08; ent.x += ent.xvel * GAME.frames[GAME.frames.length-1]*TIME_FACTOR; ent.y += ent.yvel * GAME.frames[GAME.frames.length-1]*TIME_FACTOR; return ent; } function move(ent, dx, dy) { var acl = Math.sqrt(dx * dx + dy * dy); ent.xvel *= 0.8; ent.yvel *= 0.8; if (acl != 0) { dx /= acl; dy /= acl; dx *= ent.accel; dy *= ent.accel; } ent.xvel += dx; ent.yvel += dy; var spd = Math.sqrt(ent.xvel*ent.xvel + ent.yvel*ent.yvel); if (spd > ent.maxSpeed) { ent.xvel /= spd; ent.yvel /= spd; ent.xvel *= ent.maxSpeed; ent.yvel *= ent.maxSpeed; } ent.x += ent.xvel; ent.y += ent.yvel; return ent; } function dist(ent1, ent2) { var dx = ent1.x - ent2.x; var dy = ent1.y - ent2.y; return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2)); } function shoot(ent) { bullet = GAME.Entity.newBullet(ent.x, ent.y, GAME.S_BULLET); bullet.angle = ent.angle; bullet.xvel = GAME.B_MAXVEL * Math.cos(ent.angle); bullet.yvel = GAME.B_MAXVEL * Math.sin(ent.angle); GAME.bullets.push(bullet); return bullet; } function detectCollisions(ent) { var entities = GAME.entities, CONST = GAME.REPULSION_CONST; for (var i=0; i < entities.length; i++) { if (entities[i] == ent) continue; var d = dist(entities[i], ent), dx = entities[i].x - ent.x, dy = entities[i].y - ent.y, angleToEnt = Math.atan2(dy, dx); if (d < 5) { if (ent.entityType == GAME.E_TYPE_BULLET) { entities.splice(i, 1); GAME.kills++; } else { ent.xvel -= Math.cos(angleToEnt) * CONST; ent.yvel -= Math.sin(angleToEnt) * CONST; entities[i].xvel += Math.cos(angleToEnt) * CONST; entities[i].yvel += Math.sin(angleToEnt) * CONST; } } } var tilex = Math.floor(ent.x / GAME.TILE_SCALE), tiley = Math.floor(ent.y / GAME.TILE_SCALE), wallCollided = false; for (var i = -1; i <= 1; i++) { for (var j = -1; j <= 1; j++) { wallCollided |= detectWallCollision(ent, tilex+j, tiley+i); } } if (wallCollided) { ent.path.push([ent.x, ent.y]); } return wallCollided; } function detectWallCollision(ent, tilex, tiley) { var CONST = GAME.WALL_REPULSION_CONST, width = GAME.current_level.size.width, height = GAME.current_level.size.height; if (tilex < 0 || width <= tilex || tiley < 0 || height < tiley) return; if (GAME.current_level.tilemap[tilex][tiley] == GAME.FLOOR_TILE) return; var tx = (tilex + 0.5) * GAME.TILE_SCALE, ty = (tiley + 0.5) * GAME.TILE_SCALE, d = Math.sqrt(Math.pow(tx-ent.x, 2) + Math.pow(ty-ent.y, 2)), dx = tx - ent.x, dy = ty - ent.y, angleToEnt = Math.atan2(dy, dx); var collision = true; if (d < 5) { collision = false; if (ent.entityType == GAME.E_TYPE_BULLET) { if (tilex != Math.floor(ent.x / GAME.TILE_SCALE)) ent.xvel *= -1; if (tiley != Math.floor(ent.y / GAME.TILE_SCALE)) ent.yvel *= -1; } else { ent.xvel -= Math.cos(angleToEnt) * CONST; ent.yvel -= Math.sin(angleToEnt) * CONST; } } return collision; } function speedOf(entity) { return Math.sqrt(Math.pow(entity.xvel, 2) + Math.pow(entity.yvel, 2)); } return { detectCollisions : detectCollisions, step : step, move : move, dist : dist, shoot : shoot, newEntity : newEntity, newEnemy : newEnemy, newPlayer : newPlayer, newBullet : newBullet, speedOf : speedOf, } })();
$(document).ready(function() { // put all your jQuery goodness in here. var filmstrip = $("#filmstrip-holder"); var animating = false; //create the automatic animation function startTimer(){ filmstrip.everyTime(6000, "slider", function() { scrollLeft(true); }); } function scrollLeft(looping){ //stop the timer if(looping === true){ //nothing }else{ filmstrip.stopTime("slider"); $("#fs-pause").addClass("play"); } if(!animating){ animating = true; $("#filmstrip-controls p").fadeOut(600, function(){ var newtext = $("#filmstrip-images li:eq(1) span").text(); $(this).text(newtext); $(this).fadeIn(600); }); var first = $("#filmstrip-images li:first"); $("#filmstrip-images").animate({"marginLeft":"-" + first.width() + "px"}, 3000, function(){ //clone the element so we can add it to the end var clone = $("#filmstrip-images li:first").clone(); //remove the element $("#filmstrip-images li:first").remove(); //set the margin left $("#filmstrip-images").css("marginLeft", "0px"); //append the cloned element to the end $("#filmstrip-images").append(clone); //set the animating to false animating = false; }); } return false; } function scrollRight(){ //stop the timer filmstrip.stopTime("slider"); $("#fs-pause").addClass("play"); if(!animating){ animating = true; $("#filmstrip-controls p").fadeOut(600, function(){ var newtext = $("#filmstrip-images li:eq(" + ($("#filmstrip-images").size() - 1) + ") span").text(); $(this).text(newtext); $(this).fadeIn(600); }); //set the margin left to the negative value $("#filmstrip-images").css("marginLeft", "-" + filmstrip.width() + "px"); //clone the last in the dive var clone = $("#filmstrip-images li:last").clone(); //remove the element $("#filmstrip-images li:last").remove(); //prepend the cloned element to the begining so it looks right $("#filmstrip-images").prepend(clone); //animate it back to 0p $("#filmstrip-images").animate({"marginLeft":"0px"}, 1200, function(){ //set the animating to false animating = false; //replace cufon }); } return false; } function scrollPause(){ if ($(this).hasClass("play")){ startTimer(); //do a scroll on play out of good faith scrollLeft(true); //remove the play class $("#fs-pause").removeClass("play"); }else{ filmstrip.stopTime("slider"); //remove the play class $("#fs-pause").addClass("play"); } return false; } $("#fs-forward").click(scrollLeft); $("#fs-back").click(scrollRight); $("#fs-pause").click(scrollPause); startTimer(); });
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M8 17h8v-.24L8.34 9.1C8.12 9.68 8 10.32 8 11v6zm4-10.5c-.19 0-.37.03-.55.06L16 11.1V11c0-2.48-1.51-4.5-4-4.5z" opacity=".3" /><path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2zm0-15.5c2.49 0 4 2.02 4 4.5v.1l2 2V11c0-3.07-1.63-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68c-.24.06-.47.15-.69.23l1.64 1.64c.18-.02.36-.05.55-.05zM5.41 3.35L4 4.76l2.81 2.81C6.29 8.57 6 9.74 6 11v5l-2 2v1h14.24l1.74 1.74 1.41-1.41L5.41 3.35zM16 17H8v-6c0-.68.12-1.32.34-1.9L16 16.76V17z" /></React.Fragment> , 'NotificationsOffTwoTone');
/** * @Author: Zhang Yingya(hzzhangyingya) <zyy> * @Date: 2016-07-20T16:59:19+08:00 * @Email: zyy7259@gmail.com * @Last modified by: zyy * @Last modified time: 2016-07-20T17:09:40+08:00 */ var argv = require('yargs').argv if (argv.ships > 3 && argv.distance < 53.5) { console.log('Plunder more riffiwobbles!') } else { console.log('Retreat from the xupptumblers') } /* node options.js node options.js --ships=4 --distance=22 node options.js --ships 12 --distance 98.7 */
import request from 'superagent' import { EventEmitter } from 'events' export default class SlackData extends EventEmitter { constructor ({ token, interval, org: host }){ super() this.host = host this.token = token this.interval = interval this.ready = false this.org = {} this.users = {} this.channelsByName = {} this.init() this.fetch() } init (){ request .get(`https://${this.host}.slack.com/api/channels.list`) .query({ token: this.token }) .end((err, res) => { (res.body.channels || []).forEach(channel => { this.channelsByName[channel.name] = channel }) }) request .get(`https://${this.host}.slack.com/api/team.info`) .query({ token: this.token }) .end((err, res) => { let team = res.body.team this.org.name = team.name if (!team.icon.image_default) { this.org.logo = team.icon.image_132 } }) } fetch (){ request .get(`https://${this.host}.slack.com/api/users.list`) .query({ token: this.token, presence: 1 }) .end((err, res) => { this.onres(err, res) }) this.emit('fetch') } getChannelId (name){ let channel = this.channelsByName[name] return channel ? channel.id: null } retry (){ let interval = this.interval * 2 setTimeout(this.fetch.bind(this), interval) this.emit('retry') } onres (err, res){ if (err) { this.emit('error', err) return this.retry() } let users = res.body.members if (!users) { let err = new Error(`Invalid Slack response: ${res.status}`) this.emit('error', err) return this.retry() } // remove slackbot and bots from users // slackbot is not a bot, go figure! users = users.filter(x => { return x.id != 'USLACKBOT' && !x.is_bot && !x.deleted }) let total = users.length let active = users.filter(user => { return 'active' === user.presence }).length if (this.users) { if (total != this.users.total) { this.emit('change', 'total', total) } if (active != this.users.active) { this.emit('change', 'active', active) } } this.users.total = total this.users.active = active if (!this.ready) { this.ready = true this.emit('ready') } setTimeout(this.fetch.bind(this), this.interval) this.emit('data') } }
var winston = require('winston'); var MemoryStorage = module.exports = function(options, verbosity) { // default configuration options = options || {}; verbosity = verbosity || 'info'; this.config = {capacity: 1000}; // update configuration and defaults for (var k in options) { this.config[k] = options[k]; } // configure the log this.log = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ colorize: true, timestamp: true, level: verbosity }) ] }); // recalculate new ideal capacity (unless alternate and valid ideal has been specified) if (!(options.ideal && this.config.ideal <= (this.config.capacity * 0.9))) { this.config.ideal = this.config.capacity * 0.9; } if (this.config.ideal < (this.config.capacity * 0.1)) { this.config.ideal = this.config.capacity * 0.1; } // init stock this.clear(); this.log.info("New memory storage created"); this.log.info("Configuration: capacity=" + this.config.capacity + ", ideal=" + this.config.ideal); } // remove all cached resources MemoryStorage.prototype.clear = function() { this.currentStock = {}; return this.stockCount = 0; }; // retrieve a specific resource MemoryStorage.prototype.get = function(key, callback) { callback(null, this.currentStock[key]); }; // save a specific resource MemoryStorage.prototype.put = function(resource, callback) { if (!(this.currentStock[resource.options.key] != null)) { this.stockCount++; this.cleanUp(); } this.currentStock[resource.options.key] = resource; // support for optional callback if (callback) { callback(null, resource); } // allow chaining, mostly for testing return this; }; // you guessed it! removed a specific item MemoryStorage.prototype.remove = function(key) { if (this.currentStock[key]) { delete this.currentStock[key]; return this.stockCount--; } }; // removes items from storage if over capacity MemoryStorage.prototype.cleanUp = function() { // check if we are over capacity if (this.stockCount > this.config.capacity) { this.log.warn("We're over capacity " + this.stockCount + " / " + this.config.ideal + ". Time to clean up the pantry memory storage"); var now = new Date() , expired = []; // used for efficiency to prevent possibly looping through a second time // remove spoiled items for (var key in this.currentStock) { resource = this.currentStock[key]; if (resource.spoilsOn < now) { this.log.verbose("Spoiled " + key); this.remove(key); } else if (resource.bestBefore < now) { expired.push(key); } } if (this.stockCount > this.config.capacity) { // still over capacity. let's toss out some expired times to make room for (var i = 0, len = expired.length; i < len; i++) { key = expired[i]; this.log.info("Expired " + key); this.remove(key); if (this.stockCount <= this.config.ideal) { break; } } } if (this.stockCount > this.config.capacity) { // we have more stuff than we can handle. time to toss some good stuff out // TODO: likely want to be smarter about which good items we toss // but without significant overhead for (key in this.currentStock) { resource = this.currentStock[key]; this.log.warn("Tossed " + key); this.remove(key); if (this.stockCount <= this.config.ideal) { break; } } } this.log.info("Cleanup complete. Currently have " + this.stockCount + " items in stock"); } };
// EventEmitter service for injection angular.module('EventEmitter', []) .factory('EventEmitter', ['$window', function ($window) { return $window.EventEmitter } ]);
version https://git-lfs.github.com/spec/v1 oid sha256:ba252e1698dee26f1488778f51f2307a30a1ee639d55cd4e98d7d1e101e70f81 size 9415
var globals = require("./globals"); var gl = globals.gl; /* Create a new Tensor with the given shape and data, and upload the resulting texture to the GPU. */ function Tensor(shape, data){ if(shape.length != 2) throw new Error("Only Tensor of order two (matrix) is supported right now."); var M = shape[0], N = shape[1]; this.texture = gl.createDataTexture(M, N, data); this.shape = [M, N]; this[Symbol.toStringTag] = 'Tensor'; } module.exports = Tensor; /* delete the GPU resident texture */ Tensor.prototype.delete = function(){ gl.context.deleteTexture(this.texture); this.texture = null; this.shape = null; }; /* Extract the data from GPU memory and return as a Float32Array, optionally keeping the data in GPU memory. */ Tensor.prototype.transfer = function(keep){ var M = this.shape[0], N = this.shape[1], out, result; // create output texture out = gl.createOutputTexture(M, N); // float extraction gl.encode(M, N, this.texture, out); result = new Float32Array(gl.readData(M, N)); // clean up gl.context.deleteTexture(out); if(!keep){ this.delete(); } return result; }; Tensor.prototype.reshape = function(shape, keep){ var M = this.shape[0], N = this.shape[1], M_out = shape[0], N_out = shape[1]; // create new texture to hold tranpose var t0 = new Tensor(shape, null); // invoke shader gl.reshape(M, N, M_out, N_out, this.texture, t0.texture); if(!keep){ this.delete(); } return t0; }; Tensor.prototype.transpose = function(keep){ var M = this.shape[0], N = this.shape[1]; // create new texture to hold tranpose var tT = new Tensor([N, M], null); // invoke shader gl.transpose(M, N, this.texture, tT.texture); if(!keep){ this.delete(); } return tT; }; Tensor.prototype.split = function(stride, keep){ var M = this.shape[0], N = this.shape[1]; if(N % 2 !== 0) throw new Error("row count must be multiple of two."); // create new texture to hold tranpose var t0 = new Tensor([M, N/2], null), t1 = new Tensor([M, N/2], null); gl.submatrix(N, M, N/2, stride, 0, this.texture, t0.texture); gl.submatrix(N, M, N/2, stride, 1, this.texture, t1.texture); if(!keep){ this.delete(); } return [t0, t1]; } Tensor.combine = function(t0, t1, stride, keep){ var M = t0.shape[0], N = t0.shape[1]; if(t0.shape[1] !== t1.shape[1] || t0.shape[0] !== t1.shape[0]) throw new Error("row and column counts must be equal."); if(stride % 4 !== 0) throw new Error("stride must be a multiple of four"); // create new texture to hold tranpose var t2 = new Tensor([M, N * 2], null); gl.combine(M, N, stride, t0.texture, t1.texture, t2.texture); if(!keep){ t0.delete(); t1.delete(); } return t2; }
import React from 'react'; import Tracking from 'tracking'; import findIndex from '../helpers/index'; export default class Video extends React.Component { constructor() { super(); } componentDidMount() { this.createVideo(); } createVideo() { navigator.mediaDevices.getUserMedia({ audio: false, video: true }) .then((stream) => { const video = document.querySelector('#video'); video.src = window.URL.createObjectURL(stream); video.onloadedmetadata = function(e) { video.play(); }; }) .catch((err) => { console.log(err.name + ": " + err.message); }); } render() { return ( <video id="video" height="600" width="1400"></video> ) } }
//! logs/app.js //! listen to nmea message events, write them to disk, and enable //! downloading of log archives //! version : 0.1 //! homegrownmarine.com var path = require('path'); var util = require('util'); var fs = require('fs'); var async = require('async'); var _ = require('lodash'); var moment = require('moment'); var express = require('express'); var archiver = require('archiver'); var winston = require('winston'); var handlebars = require('handlebars'); exports.load = function(server, boatData, settings) { var dataDir = settings.get("logs:dataDir"); var currentStreamTime = null; var currentStream = null; //cache current write stream, and append to it function getStreamForTime(time) { time = time.startOf('hour'); if (!time.isSame(currentStreamTime)) { //if our stream is changing, end old stream if ( currentStream ) currentStream.end(); currentStreamTime = time; currentStream = fs.createWriteStream(path.join(dataDir, time.format('YYMMDDHH')+'.txt'), { flags: 'a'}) } return currentStream; } // do logging if ( settings.get("logs:log") !== false ) { boatData.on('nmea', function(message) { getStreamForTime(moment()) .write(message+'\r\n'); }); } // log interface var indexTemplate = null; fs.readFile(path.join(__dirname,'templates/index.html'), {encoding:'utf8'}, function(err, data) { if (err) { winston.error('logs: error loading template', err); return; } indexTemplate = handlebars.compile(data); }); //enable log downloading server.use('/logs', express.static(path.join(__dirname, 'zips/'))); // list log files, grouped by day server.get('/logs/', function(req, res) { if ( !indexTemplate ) { res.send(); return; } fs.readdir(dataDir, function(err, files) { if (err) { winston.error('logs: error reading log dir', err); return; } var logs = _(files) .filter(function(filename) { return filename.match(/\d{8}\./); }) .map(function(filename) { return filename.substring(0,6); }) .sort() .uniq() .reverse() .map(function(filename) { return { filename: filename, date: moment(filename, "YYMMDD").format("MMM D, YYYY") }; }) .valueOf(); res.send( indexTemplate({log_days:logs}) ); }); }); //TODO: way to reprocess a partial day //archive day's logs into zip file server.get('/logs/ready/:day', function(req, res) { var day = req.params.day; var zipFile = path.join(__dirname, '/zips/', day + '.zip'); if ( fs.existsSync(zipFile) ) { res.send({'status':'ready', 'location': '/logs/'+day+'.zip'}); } else if ( fs.existsSync(zipFile+'.tmp') ) { //TODO: restart if not actively writing. res.send({'status':'archiving'}); } else { // TODO: child process var hourlyLogs = _.filter(fs.readdirSync(dataDir), function(filename) { return filename.substring(0,6) === day; }); var output = fs.createWriteStream(zipFile+'.tmp'); var archive = archiver('zip'); archive.on('end', function() { output.end(); }); output.on('finish', function() { // rename temp file, archive can now be downloaded fs.rename(__dirname + '/zips/' + day + '.zip.tmp', __dirname + '/zips/' + day + '.zip', function(err){ if (err) winston.error('Error renaming zip file.', err); }); }); archive.pipe(output); // add each file to the archive async.each(hourlyLogs, function(file, callback) { archive.append(fs.createReadStream(path.join(dataDir, file)), { name: file }); callback(null); }, function(err) { if (!err) archive.finalize(); }); res.send({'status':'archiving'}); } }); return {url:'/logs/', title:'Download Logs', priority: 100}; };
// pages/posts/posts.js var postData = require("../../data/posts_data.js"); Page({ data: { condition: true, }, onItemTap: function (event) { // console.log("onItemTap" + event.currentTarget.dataset.postid); wx.navigateTo({ url: 'posts-detail/posts-detail?id=' + event.currentTarget.dataset.postid, success: function (res) { // success }, fail: function () { // fail }, complete: function () { // complete } }) }, onSwiperItemTap: function (event) { wx.navigateTo({ url: 'posts-detail/posts-detail?id=' + event.currentTarget.dataset.postid, success: function (res) { // success }, fail: function () { // fail }, complete: function () { // complete } }) }, onSwiperTap: function (event) { wx.navigateTo({ url: 'posts-detail/posts-detail?id=' + event.target.dataset.postid, success: function (res) { // success }, fail: function () { // fail }, complete: function () { // complete } }) }, procss: function () { console.log("process"); }, onLoad: function (options) { // 页面初始化 options为页面跳转所带来的参数 console.log("postdata: " + postData.postDataList); // this.data.posts_key = postData.localData; this.setData({ posts_key: postData.postDataList }); }, onReady: function () { // 页面渲染完成 }, onShow: function () { // 页面显示 }, onHide: function () { // 页面隐藏 }, onUnload: function () { // 页面关闭 } })
import React from 'react'; import { ResultList } from 'components'; import { connect } from 'react-redux'; import { voteResultRequest } from 'actions/vote'; class VoteResult extends React.Component { componentDidMount() { this.props.voteResultRequest().then( () => { //console.log(this.props.resultData); } ); } render() { const dummyData = [ { "id": 3, "title": "트랜센던스 (Transcendence)", "year": "2014", "directorName": "윌리 피스터", "posterUrl": "http://cfile119.uf.daum.net/image/243A7A4752BB8C5C377EEF", "voteCount": 2, "votePer": 0.4 }, { "id": 1, "title": "루시 (Lucy)", "year": "2014", "directorName": "뤽 베송", "posterUrl": "http://cfile17.uf.daum.net/image/2458B3375382F287111B8F", "voteCount": 2, "votePer": 0.4 }, { "id": 2, "title": "엑스 마키나 (Ex Machina)", "year": "2015", "directorName": "알렉스 갈린드", "posterUrl": "http://cfile116.uf.daum.net/image/227AFF4E5486B719247C67", "voteCount": 0, "votePer": 0.0 } ]; return( <div> <ResultList data={this.props.resultData}/> </div> ); } } const mapStateToProps = (state) => { return { resultData : state.result.data } } const mapDispatchToProps = (dispatch) => { return { voteResultRequest : () => { return dispatch(voteResultRequest()); } } } export default connect(mapStateToProps, mapDispatchToProps)(VoteResult);
"use strict"; const { markEvalScopes, isMarked: isEvalScopesMarked, hasEval, } = require("babel-helper-mark-eval-scopes"); module.exports = ({ types: t, traverse }) => { const hop = Object.prototype.hasOwnProperty; class Mangler { constructor(charset, program, { blacklist = {}, keepFnName = false, eval: _eval = false, topLevel = false, keepClassName = false, } = {}) { this.charset = charset; this.program = program; this.blacklist = blacklist; this.keepFnName = keepFnName; this.keepClassName = keepClassName; this.eval = _eval; this.topLevel = topLevel; this.unsafeScopes = new Set; this.visitedScopes = new Set; this.referencesToUpdate = new Map; } run() { this.cleanup(); this.collect(); this.charset.sort(); this.mangle(); } cleanup() { traverse.clearCache(); this.program.scope.crawl(); } isBlacklist(name) { return hop.call(this.blacklist, name); } markUnsafeScopes(scope) { let evalScope = scope; do { this.unsafeScopes.add(evalScope); } while (evalScope = evalScope.parent); } collect() { const mangler = this; if (!isEvalScopesMarked(mangler.program.scope)) { markEvalScopes(mangler.program); } if (this.charset.shouldConsider) { const collectVisitor = { Identifier(path) { const { node } = path; if ((path.parentPath.isMemberExpression({ property: node })) || (path.parentPath.isObjectProperty({ key: node })) ) { mangler.charset.consider(node.name); } }, Literal({ node }) { mangler.charset.consider(String(node.value)); } }; mangler.program.traverse(collectVisitor); } } mangle() { const mangler = this; this.program.traverse({ Scopable(path) { const {scope} = path; if (!mangler.eval && hasEval(scope)) return; if (mangler.visitedScopes.has(scope)) return; mangler.visitedScopes.add(scope); function hasOwnBinding(name) { if (scope.parent !== mangler.program.scope) { return scope.hasOwnBinding(name); } return mangler.program.scope.hasOwnBinding(name) || scope.hasOwnBinding(name); } let i = 0; function getNext() { return mangler.charset.getIdentifier(i++); } // This is useful when we have vars of single character // => var a, ...z, A, ...Z, $, _; // to // => var aa, a, b ,c; // instead of // => var aa, ab, ...; // TODO: // Re-enable after enabling this feature // This doesn't work right now as we are concentrating // on performance improvements // function resetNext() { // i = 0; // } const bindings = scope.getAllBindings(); const names = Object.keys(bindings); for (let i = 0; i < names.length; i++) { const oldName = names[i]; const binding = bindings[oldName]; const isTopLevel = mangler.program.scope.bindings[oldName] === binding; if ( // already renamed bindings binding.renamed // arguments || oldName === "arguments" // globals || (mangler.topLevel ? false : isTopLevel) // other scope bindings || !hasOwnBinding(oldName) // labels || binding.path.isLabeledStatement() // blacklisted || mangler.isBlacklist(oldName) // function names || (mangler.keepFnName ? isFunction(binding.path) : false) // class names || (mangler.keepClassName ? isClass(binding.path) : false) ) { continue; } let next; do { next = getNext(); } while ( !t.isValidIdentifier(next) || hop.call(bindings, next) || scope.hasGlobal(next) || scope.hasReference(next) ); // TODO: // re-enable this - check above // resetNext(); mangler.rename(scope, oldName, next); if (isTopLevel) { mangler.rename(mangler.program.scope, oldName, next); } // mark the binding as renamed binding.renamed = true; } } }); // TODO: // re-enable // check above // this.updateReferences(); } rename(scope, oldName, newName) { const binding = scope.getBinding(oldName); // rename at the declaration level binding.identifier.name = newName; const {bindings} = scope; bindings[newName] = binding; delete bindings[oldName]; // update all constant violations & redeclarations const violations = binding.constantViolations; for (let i = 0; i < violations.length; i++) { if (violations[i].isLabeledStatement()) continue; const bindings = violations[i].getBindingIdentifiers(); Object .keys(bindings) .map((b) => { bindings[b].name = newName; }); } // update all referenced places const refs = binding.referencePaths; for (let i = 0; i < refs.length; i++) { const path = refs[i]; const {node} = path; if (!path.isIdentifier()) { // Ideally, this should not happen // it happens in these places now - // case 1: Export Statements // This is a bug in babel // https://github.com/babel/babel/pull/3629 // case 2: Replacements in other plugins // eg: https://github.com/babel/babili/issues/122 // replacement in dce from `x` to `!x` gives referencePath as `!x` path.traverse({ ReferencedIdentifier(refPath) { if (refPath.node.name === oldName && refPath.scope === scope) { refPath.node.name = newName; } } }); } else if (!isLabelIdentifier(path)) { node.name = newName; } } } } return { name: "minify-mangle-names", visitor: { Program(path) { // If the source code is small then we're going to assume that the user // is running on this on single files before bundling. Therefore we // need to achieve as much determinisim and we will not do any frequency // sorting on the character set. Currently the number is pretty arbitrary. const shouldConsiderSource = path.getSource().length > 70000; const charset = new Charset(shouldConsiderSource); const mangler = new Mangler(charset, path, this.opts); mangler.run(); }, }, }; }; const CHARSET = ("abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ$_").split(""); class Charset { constructor(shouldConsider) { this.shouldConsider = shouldConsider; this.chars = CHARSET.slice(); this.frequency = {}; this.chars.forEach((c) => { this.frequency[c] = 0; }); this.finalized = false; } consider(str) { if (!this.shouldConsider) { return; } str.split("").forEach((c) => { if (this.frequency[c] != null) { this.frequency[c]++; } }); } sort() { if (this.shouldConsider) { this.chars = this.chars.sort( (a, b) => this.frequency[b] - this.frequency[a] ); } this.finalized = true; } getIdentifier(num) { if (!this.finalized) { throw new Error("Should sort first"); } let ret = ""; num++; do { num--; ret += this.chars[num % this.chars.length]; num = Math.floor(num / this.chars.length); } while (num > 0); return ret; } } // for keepFnName function isFunction(path) { return path.isFunctionExpression() || path.isFunctionDeclaration(); } // for keepClassName function isClass(path) { return path.isClassExpression() || path.isClassDeclaration(); } function isLabelIdentifier(path) { const {node} = path; return path.parentPath.isLabeledStatement({ label: node }) || path.parentPath.isBreakStatement({ label: node }) || path.parentPath.isContinueStatement({ label: node }); }
import moment from 'moment'; import _ from 'lodash'; const sorts = { createDateOldestToNewest({ createdAt: a }, { createdAt: b }) { return moment(a).isAfter(b); }, createDateNewestToOldest({ createdAt: a }, { createdAt: b }) { return moment(a).isBefore(b); }, startDateOldestToNewest({ startDate: a }, { startDate: b }) { return moment(a).isAfter(b); }, startDateNewestToOldest({ startDate: a }, { startDate: b }) { return moment(a).isBefore(b); }, latestDeadline({ endDate: a }, { endDate: b }) { return moment(a).isAfter(b); }, earliestDeadline({ endDate: a }, { endDate: b }) { return moment(a).isBefore(b); }, }; export const getDefaultOptionValue = () => 'earliestDeadline'; export const sortOptions = _.keys(sorts) .map(option => ({ value: option, label: _.startCase(option), }), ); export const sort = (data, key) => { if (key) { return data.sort(sorts[key]); } return data; };
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var session = require('express-session') var routes = require('./routes/index'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use(session({ secret: 'zookeeper_web', resave: false, saveUninitialized: true })); app.use('/', routes); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); app.listen(3000,function(){ console.log('app is running'); }) module.exports = app;
// flow-typed signature: 268c848364eeda2427a142849237d02b // flow-typed version: <<STUB>>/redux-logger_v^3.0.1/flow_v0.40.0 /** * This is an autogenerated libdef stub for: * * 'redux-logger' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'redux-logger' { declare module.exports: any; /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ } declare module 'redux-logger/dist/index' { declare module.exports: any; } declare module 'redux-logger/dist/index.min' { declare module.exports: any; } declare module 'redux-logger/lib/core' { declare module.exports: any; } declare module 'redux-logger/lib/defaults' { declare module.exports: any; } declare module 'redux-logger/lib/diff' { declare module.exports: any; } declare module 'redux-logger/lib/helpers' { declare module.exports: any; } declare module 'redux-logger/lib/index' { declare module.exports: any; } declare module 'redux-logger/src/core' { declare module.exports: any; } declare module 'redux-logger/src/defaults' { declare module.exports: any; } declare module 'redux-logger/src/diff' { declare module.exports: any; } declare module 'redux-logger/src/helpers' { declare module.exports: any; } declare module 'redux-logger/src/index' { declare module.exports: any; // Filename aliases } declare module 'redux-logger/dist/index.js' { declare module.exports: $Exports<'redux-logger/dist/index'>; } declare module 'redux-logger/dist/index.min.js' { declare module.exports: $Exports<'redux-logger/dist/index.min'>; } declare module 'redux-logger/lib/core.js' { declare module.exports: $Exports<'redux-logger/lib/core'>; } declare module 'redux-logger/lib/defaults.js' { declare module.exports: $Exports<'redux-logger/lib/defaults'>; } declare module 'redux-logger/lib/diff.js' { declare module.exports: $Exports<'redux-logger/lib/diff'>; } declare module 'redux-logger/lib/helpers.js' { declare module.exports: $Exports<'redux-logger/lib/helpers'>; } declare module 'redux-logger/lib/index.js' { declare module.exports: $Exports<'redux-logger/lib/index'>; } declare module 'redux-logger/src/core.js' { declare module.exports: $Exports<'redux-logger/src/core'>; } declare module 'redux-logger/src/defaults.js' { declare module.exports: $Exports<'redux-logger/src/defaults'>; } declare module 'redux-logger/src/diff.js' { declare module.exports: $Exports<'redux-logger/src/diff'>; } declare module 'redux-logger/src/helpers.js' { declare module.exports: $Exports<'redux-logger/src/helpers'>; } declare module 'redux-logger/src/index.js' { declare module.exports: $Exports<'redux-logger/src/index'>; }
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { setupIntl } from 'ember-intl/test-support'; import { render, click } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; module('Integration | Component | new objective', function (hooks) { setupRenderingTest(hooks); setupIntl(hooks, 'en-us'); test('it renders', async function (assert) { this.set('cancel', () => {}); await render(hbs`<NewObjective @cancel={{this.cancel}} />`); const content = this.element.textContent.trim(); assert.ok(content.includes('New Objective')); assert.ok(content.includes('Description')); }); test('errors do not show up initially', async function (assert) { assert.expect(1); this.set('cancel', () => { assert.ok(false); //shouldn't be called }); await render(hbs`<NewObjective @cancel={{this.cancel}} />`); assert.dom('.validation-error-message').doesNotExist(); }); test('errors show up', async function (assert) { assert.expect(2); this.set('cancel', () => { assert.ok(false); //shouldn't be called }); await render(hbs`<NewObjective @cancel={{this.cancel}} />`); await click('.done'); assert.dom('.validation-error-message').exists(); assert.dom('.validation-error-message').includesText('blank'); }); });
/** * @fileoverview Translation for `validateLineBreaks` (JSCS) to ESLint * @author Breno Lima de Freitas <https://breno.io> * @copyright 2016 Breno Lima de Freitas. All rights reserved. * See LICENSE file in root directory for full license. */ 'use strict' //------------------------------------------------------------------------------ // Rule Translation Definition //------------------------------------------------------------------------------ module.exports = { name: 'linebreak-style', truthy: function(__current__, value) { var sys = (value === 'CLRF') ? 'windows' : 'unix' return [2, sys] } };
#! /usr/bin/env node var parseJS = require("../lib/parse-js"); var sys = require("sys"); // write debug in a very straightforward manner var debug = function(){ sys.log(Array.prototype.slice.call(arguments).join(', ')); }; ParserTestSuite(function(i, input, desc){ try { parseJS.parse(input); debug("ok " + i + ": " + desc); } catch(e){ debug("FAIL " + i + " " + desc + " (" + e + ")"); } }); function ParserTestSuite(callback){ var inps = [ ["var abc;", "Regular variable statement w/o assignment"], ["var abc = 5;", "Regular variable statement with assignment"], ["/* */;", "Multiline comment"], ['/** **/;', 'Double star multiline comment'], ["var f = function(){;};", "Function expression in var assignment"], ['hi; // moo\n;', 'single line comment'], ['var varwithfunction;', 'Dont match keywords as substrings'], // difference between `var withsomevar` and `"str"` (local search and lits) ['a + b;', 'addition'], ["'a';", 'single string literal'], ["'a\\n';", 'single string literal with escaped return'], ['"a";', 'double string literal'], ['"a\\n";', 'double string literal with escaped return'], ['"var";', 'string is a keyword'], ['"variable";', 'string starts with a keyword'], ['"somevariable";', 'string contains a keyword'], ['"somevar";', 'string ends with a keyword'], ['500;', 'int literal'], ['500.;', 'float literal w/o decimals'], ['500.432;', 'float literal with decimals'], ['.432432;', 'float literal w/o int'], ['(a,b,c);', 'parens and comma'], ['[1,2,abc];', 'array literal'], ['var o = {a:1};', 'object literal unquoted key'], ['var o = {"b":2};', 'object literal quoted key'], // opening curly may not be at the start of a statement... ['var o = {c:c};', 'object literal keyname is identifier'], ['var o = {a:1,"b":2,c:c};', 'object literal combinations'], ['var x;\nvar y;', 'two lines'], ['var x;\nfunction n(){; }', 'function def'], ['var x;\nfunction n(abc){; }', 'function def with arg'], ['var x;\nfunction n(abc, def){ ;}', 'function def with args'], ['function n(){ "hello"; }', 'function def with body'], ['/a/;', 'regex literal'], ['/a/b;', 'regex literal with flag'], ['/a/ / /b/;', 'regex div regex'], ['a/b/c;', 'triple division looks like regex'], ['+function(){/regex/;};', 'regex at start of function body'], // http://code.google.com/p/es-lab/source/browse/trunk/tests/parser/parsertests.js?r=86 // http://code.google.com/p/es-lab/source/browse/trunk/tests/parser/parsertests.js?r=430 // first tests for the lexer, should also parse as program (when you append a semi) // comments ['//foo!@#^&$1234\nbar;', 'single line comment'], ['/* abcd!@#@$* { } && null*/;', 'single line multi line comment'], ['/*foo\nbar*/;','multi line comment'], ['/*x*x*/;','multi line comment with *'], ['/**/;','empty comment'], // identifiers ["x;",'1 identifier'], ["_x;",'2 identifier'], ["xyz;",'3 identifier'], ["$x;",'4 identifier'], ["x$;",'5 identifier'], ["_;",'6 identifier'], ["x5;",'7 identifier'], ["x_y;",'8 identifier'], ["x+5;",'9 identifier'], ["xyz123;",'10 identifier'], ["x1y1z1;",'11 identifier'], ["foo\\u00D8bar;",'12 identifier unicode escape'], //["foo�bar;",'13 identifier unicode embedded (might fail)'], // numbers ["5;", '1 number'], ["5.5;", '2 number'], ["0;", '3 number'], ["0.0;", '4 number'], ["0.001;", '5 number'], ["1.e2;", '6 number'], ["1.e-2;", '7 number'], ["1.E2;", '8 number'], ["1.E-2;", '9 number'], [".5;", '10 number'], [".5e3;", '11 number'], [".5e-3;", '12 number'], ["0.5e3;", '13 number'], ["55;", '14 number'], ["123;", '15 number'], ["55.55;", '16 number'], ["55.55e10;", '17 number'], ["123.456;", '18 number'], ["1+e;", '20 number'], ["0x01;", '22 number'], ["0XCAFE;", '23 number'], ["0x12345678;", '24 number'], ["0x1234ABCD;", '25 number'], ["0x0001;", '26 number'], // strings ["\"foo\";", '1 string'], ["\'foo\';", '2 string'], ["\"x\";", '3 string'], ["\'\';", '4 string'], ["\"foo\\tbar\";", '5 string'], ["\"!@#$%^&*()_+{}[]\";", '6 string'], ["\"/*test*/\";", '7 string'], ["\"//test\";", '8 string'], ["\"\\\\\";", '9 string'], ["\"\\u0001\";", '10 string'], ["\"\\uFEFF\";", '11 string'], ["\"\\u10002\";", '12 string'], ["\"\\x55\";", '13 string'], ["\"\\x55a\";", '14 string'], ["\"a\\\\nb\";", '15 string'], ['";"', '16 string: semi in a string'], ['"a\\\nb";', '17 string: line terminator escape'], // literals ["null;", "null"], ["true;", "true"], ["false;", "false"], // regex ["/a/;", "1 regex"], ["/abc/;", "2 regex"], ["/abc[a-z]*def/g;", "3 regex"], ["/\\b/;", "4 regex"], ["/[a-zA-Z]/;", "5 regex"], // program tests (for as far as they havent been covered above) // regexp ["/foo(.*)/g;", "another regexp"], // arrays ["[];", "1 array"], ["[ ];", "2 array"], ["[1];", "3 array"], ["[1,2];", "4 array"], ["[1,2,,];", "5 array"], ["[1,2,3];", "6 array"], ["[1,2,3,,,];", "7 array"], // objects ["{};", "1 object"], ["({x:5});", "2 object"]
import '/resources/gis/leaflet/leaflet-lib.js'; import '/resources/gis/leaflet/markerrotation/leaflet.rotatedMarker.js';
BasicGame.Preloader = function (game) { this.background = null; this.preloadBar = null; this.ready = false; }; BasicGame.Preloader.prototype = { preload: function () { // These are the assets we loaded in Boot.js // A nice sparkly background and a loading progress bar this.background = this.add.sprite(0, 0, 'preloaderBackground'); this.preloadBar = this.add.sprite(120, 435, 'preloaderBar'); // This sets the preloadBar sprite as a loader sprite. // What that does is automatically crop the sprite from 0 to full-width // as the files below are loaded in. //this.load.setPreloadSprite(this.preloadBar); // Here we load the rest of the assets our game needs. // As this is just a Project Template I've not provided these assets, swap them for your own. this.load.image('titlepage', 'assets/images/main_menu.png'); this.load.atlas('buttons', 'assets/buttons/startButton.png', 'assets/buttons/startButton.json'); //Load player palyerCharacter.json this.load.atlasJSONHash('player', 'assets/images/palyerCharacter.png', 'assets/images/palyerCharacter.json'); //this.load.audio('titleMusic', ['audio/main_menu.mp3']); //this.load.bitmapFont('carrier_command', 'fonts/bitmapFonts/carrier_command.png', 'fonts/bitmapFonts/carrier_command.xml'); // + lots of other required assets here }, create: function () { // Once the load has finished we disable the crop because we're going to sit in the update loop for a short while as the music decodes //this.preloadBar.cropEnabled = false; }, update: function () { // You don't actually need to do this, but I find it gives a much smoother game experience. // Basically it will wait for our audio file to be decoded before proceeding to the MainMenu. // You can jump right into the menu if you want and still play the music, but you'll have a few // seconds of delay while the mp3 decodes - so if you need your music to be in-sync with your menu // it's best to wait for it to decode here first, then carry on. // If you don't have any music in your game then put the game.state.start line into the create function and delete // the update function completely. if (this.ready == false) { this.ready = true; //this.state.start('MainMenu'); this.state.start('Game'); } } };
version https://git-lfs.github.com/spec/v1 oid sha256:50e539cc660deb4e7e2bbd6ff64cf1eba14952ebb5e8e0394a326914fb4ff00f size 1568
/* server.js main server script for the socket.io chat demo */
#!/usr/bin/env node /****************************************************************************** * * * @file server.js * * @author Clément Désiles <main@jokester.fr> * * @licence MIT (see LICENCE file) * * @date 04/30/2012 * * * * A node.js configurable webserver * * Please modify config.json if you want to adapt it to your needs * * for further code modification, do not hesitate to suggest a patch * * on GitHub (see HACKING.md) * * * * Remind that this has to be as asynchronous as possible to reduce * * answser latency. This server use the cluster node.js library to fork * * the work between parallel co-workers. * * * *****************************************************************************/ // ----------------------------- DEPENDENCIES ---------------------------- // var config = require('./config.js').config, tools = require('./scripts/tools.js'), mtypes = require('./scripts/mimetypes.js'), cluster = require('cluster'), https = require('https'), http = require('http'), fs = require('fs'), url = require('url'), path = require('path'), zlib = require('zlib'), qs = require('querystring'), os = require('os'), exec = require('child_process').exec, crypto = require('crypto'), cconsole = require('colorize').console; // Include tools in da global scope :) for (tool in tools){ GLOBAL[tool] = tools[tool]; } // ------------------------------- GLOBALS ------------------------------- // // These variables are set to default. Some of these can be overwritten by CLI var SERVER_PORT = 443, SERVER_WORKERS = os.cpus().length, SERVER_RECONNECT_DELAY = 1000, //1s DOCUMENT_ROOT = false, //@see init AVAILABLE_LANGS = false; //@see init // ----------------------------- CREDENTIALS ----------------------------- // if (config.ssl){ var privatekeyPath = path.join(__dirname, config.ssl.path.privatekey); var certificatePath = path.join(__dirname, config.ssl.path.certificate); try{ var credentials = { key: fs.readFileSync(privatekeyPath), cert: fs.readFileSync(certificatePath) }; } catch (e){ console.error(timeLog(),'Bad SSL configuration or missing credentials.'); console.error('Please use ./run --ssl to generate certificates') cconsole.error('#yellow[',e,']'); process.exit(1); } } // --------------------------- INTERPRETE CLI ---------------------------- // //Disable development outputs on production if(process.env.NODE_ENV == 'production'){ console.log = function(){return}; cconsole.log = function(){return}; } if(process.argv.length==2){ // There is not any parameter -> init as is (default) init(); } else { // Parse each additional parameter var startServer = false; for (var i=2, l=process.argv.length; i<l && i>=2; i++){ var arg = process.argv[i].split('='); switch(arg[0]){ case '': init(); break; case '--port': SERVER_PORT = parseInt(arg[1]); startServer = true; break; case '--threads': SERVER_WORKERS = parseInt(arg[1]); startServer = true; break; case '--path': DOCUMENT_ROOT = path.resolve(__dirname, '..', arg[1]); AVAILABLE_LANGS = inspectLang(DOCUMENT_ROOT); startServer = true; break; case '--help': help(); startServer = false; break; default: //do nothing, ignored break; }; } if(startServer) init(); } /** * Initializer that should be called only once * by the cluster master. Fork the workers. * @return none */ function init(){ //Init root variable and available languages if(!DOCUMENT_ROOT) DOCUMENT_ROOT = path.resolve(__dirname, config.server.defaultClientPath); if(!AVAILABLE_LANGS) AVAILABLE_LANGS = inspectLang(DOCUMENT_ROOT); if (cluster.isMaster) { var relRootPath = path.relative(__dirname,DOCUMENT_ROOT); var sslStatus = (config.ssl)?'ON':'OFF'; console.info('******************************************************'); console.info('* Server starts'); console.info('******************************************************'); cconsole.info(' #yellow[DATE] : '+ new Date(Date.now()).toUTCString()); cconsole.info(' #yellow[DOCUMENT_ROOT] : '+ relRootPath); cconsole.info(' #yellow[PORT] : '+ SERVER_PORT); cconsole.info(' #yellow[SSL] : '+ sslStatus); cconsole.info(' #yellow[SERVER_WORKERS] : '+ SERVER_WORKERS); console.info('******************************************************'); // Fork workers for (var i = 0; i < SERVER_WORKERS; i++) { var worker = cluster.fork(); } // Reinit workers if needed cluster.on('death', function(worker) { console.log('worker ' + worker.pid + ' died. restart...'); cluster.fork(); }); } } /** * Display a quick help to the user * about different use cases provided by this script * @return none */ function help(){ if (cluster.isMaster) { var appName = ' ./'+path.basename(__filename); console.log('*******************************************************'); console.log('* Server usage'); console.log('*******************************************************'); console.log(appName + '\t\t\t launch the server on port 443'); console.log(appName + '\t--port=4430\t launch the server on port 4430'); console.log(appName + '\t--threads=4\t launch the server with 4 co-workers'); console.log(appName + '\t--path=$MY_PATH\t deserve pages located on path'); console.log(appName + '\t--help\t\t display this menu'); console.log(); process.exit(0); } } // ------------------------ START SERVER WORKERS ------------------------- // if (cluster.isWorker) { // Configuration file define HTTPS or HTTP if(config.server.https && config.ssl) { var serverInstance = https.createServer(credentials,server); } else { var serverInstance = http.createServer(server); } // Server error handler serverInstance.on('error', function (e) { switch(e.code){ case 'EADDRINUSE': console.log('port '+ SERVER_PORT + ' is already in use...'); break; case 'EACCES': console.log('Worker not allowed to bind on port '+ SERVER_PORT); process.exit(1); default: console.log('error `'+e.code+'` impossible to bind'); process.exit(1); } setTimeout(function () { serverInstance.listen(SERVER_PORT); }, SERVER_RECONNECT_DELAY); }); // Bound admin server to the specified port serverInstance.listen(SERVER_PORT, function() { var protocol = config.ssl != undefined?'HTTPS':'HTTP'; console.log('[+] '+ protocol +' server worker bound to port: '+ SERVER_PORT); }); } // ------------------------ SERVER MAIN FEATURES -------------------------- // /** * Deliver some static contents by calling `sendStatic` * rewrite some URLs and prevent some basic security issues * @param req {object} input socket (request) * @param res {object} output socket (response) * @return none */ function server(req,res) { // Protect uri against `../` and remove first `/` req.url = url.parse(req.url).pathname.substr(1); console.log('[GET] '+req.url); // Handle empty uri if(req.url == '' || req.url == '/'){ if(config.server.disableRedirect){ /* * WARNING No redirection means * breaking client relative paths! */ req.url = config.client.path.rootPage; } else { req.url = config.client.path.rootPage; redirect(req,res); return; } } // Parse cookies var cookies = {}; if(req.headers.cookie){ req.headers.cookie.split(';').forEach(function( cookie ) { var parts = cookie.split('='); cookies[ parts[ 0 ].trim() ] = ( parts[ 1 ] || '' ).trim(); }); } // If no cookies or no language use browser accept-language if(!cookies || !cookies.lang) { // Set a language to user var lang = getUserLang(req.headers['accept-language']); res.setHeader('Set-Cookie', ['lang='+lang+'; path=/']); } else if(req.url == config.basePageReal){ /* * Check if language is correct as this check is not mandatory, * for optimization purpose we only chek the basePage */ var lang = checkUserLang(cookies.lang); if(lang != cookies.lang){ res.setHeader('Set-Cookie', ['lang='+lang+'; path=/']); } } // Send static file sendStatic(req, res); }; /** * Pull a static ressource to the client's response socket * this function handle the relative path security issue * @param req {object} input socket (request) * @param res {object} output socket (response) * @return none */ function sendStatic(req,res) { var filepath = path.join(DOCUMENT_ROOT, '/', req.url); fs.exists(filepath, function(exists){ /* * Handle inexistant ressources * notice that Client has to handle not found * services itself while rewriting pages like: * /{config.client.name}/foo/bar */ if(!exists){ // If url starts with client name, it's a rewrited url if(startsWith(req.url,config.client.name)) { if(config.server.disableRedirect){ /* * WARNING No redirection means * breaking client relative paths! */ req.url = config.client.path.rootPage; filepath = path.join(DOCUMENT_ROOT, '/', req.url); } else { req.url = config.client.path.rootPage; redirect(req,res); return; } // Ressource not found -> 404 error } else { console.error(timeLog(), req.url, 'is unreachable'); send404(res); return; } } // Get the ressource mimetype from file extension var mimetype = mtypes.getMimeType(path.extname(filepath).substr(1)); // Read the file as a stream var raw = fs.createReadStream(filepath); // By default no gzip var gzipEncoding = false; // Time stats about file uptates to cache var stats = fs.statSync(filepath); // If client browser accept compression: activate it if(req.headers['accept-encoding']){ var acceptEncoding = req.headers['accept-encoding'].split(':'); } else { var acceptEncoding = []; } if(acceptEncoding.indexOf('gzip')>-1) { gzipEncoding=true; } if(config.cacheEnabled && req.headers['if-modified-since'] == stats.mtime ) { res.statusCode = 304; res.end(); } else { // Define content type and allow caching of every ressource var header = { 'Content-Type': mimetype }; if(config.cacheEnabled){ header['Cache-Control']='public'; header['Last-Modified']=stats.mtime; } // Gzip zippable mime types if(gzipEncoding && mtypes.isZippable(mimetype)) { var gzip = zlib.createGzip(); header['content-encoding']='gzip'; res.writeHead(200, header); raw.pipe(gzip).pipe(res); } else { res.writeHead(200, header); raw.pipe(res); } } }); } // ------------------------- SOME BASIC FEATURES ------------------------- // //TODO: store some of them in a separate file function importClientConfig(clientDir){ // Import client config in global configuration try { var clientConfiguration = require(path.join(clientDir,'/config.js')); config.client = clientConfiguration; /* * TODO make a complete check of all client properties * to handle every kind of client configuration error */ if(!config.client.path.rootPage){ console.error(timeLog(), 'Undefined path.rootPage in client application:'); console.error(config.server.defaultClientPath + '/config.json'); process.exit(1); } } catch (e) { console.error(timeLog(),'Impossible to import the client configuration.'); cconsole.error('\n Abort. #yellow[',e,']'); process.exit(1); } } /** * Return the lang i18n code that the user will use * accordingly to the languages available... * @param {string} - accept-language field of request header * @return {string} - a language key of AVAILABLE_LANGS array */ function getUserLang(header_accept_language){ // By default the user will get LANG_DEFAULT var userLang = config.client.defaultLang; //E.G. var header_accept_language = 'fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3' // TODO (cosmetic): order them relatively to q values // (but mainly browsers set them in order...) var m = header_accept_language.match(/([a-zA-Z]{2,4}(-[a-zA-Z]{2,4})?)/g); // Parse accepted languages for(var i=0 ; i<m.length ; i++){ var lang = m[i]; // If lang is in array of supported languages if (AVAILABLE_LANGS && (lang.toLowerCase() in AVAILABLE_LANGS)){ userLang = lang; //console.log('user will use: '+userLang); break; } } //console.log('user will use BYDEFAULT : '+userLang); return AVAILABLE_LANGS[userLang.toLowerCase()]; } /** * Check if the user lang is correct, and return * the language corrected if it was not * @param {string} user language * @return {string} corrected user language */ function checkUserLang(userLang){ // If lang is in array of supported languages for(availableLang in AVAILABLE_LANGS){ if(userLang.toLowerCase() == availableLang) { return AVAILABLE_LANGS[availableLang]; } } // User language do not match any, return default return AVAILABLE_LANGS[config.defaultLang.toLowerCase()]; } /** * Inspect a path and return the supported languages * @param {string} path of the client root directory * @return assocArray with supported languages */ function inspectLang(clientDir){ if(!config.client || !config.client.path){ importClientConfig(clientDir); } if(!config.client.path.lang) { console.error(timeLog(),'Bad configuration of client app.\nAbort'); process.exit(1); } // Array to be filled var langArray = {}; // List of files in that path var langPath = path.join(clientDir,config.client.path.lang); var langs = getLangList(langPath,true); // Filling array with correct infos for(i in langs){ var lang = String(langs[i]); // langArray['fr']='fr-FR' langArray[lang.split('-',1)[0].toLowerCase()] = lang; // langArray['fr-fr']='fr-FR' langArray[lang.toLowerCase()] = lang; } return langArray; } /** * Return the list of available languages in langPath * @param {string} - path where are stored the templates * @param {boolean} - true if should return list without file extension * @return {array} - list of the templates found */ function getLangList(langPath, withouExt){ var list = new Array(); // Get template list in dir var listFileName = fs.readdirSync(String(langPath)); // If filename match xx-XX.json add it (with || withoutExt) for(i in listFileName){ var fileName = listFileName[i]; if(fileName.match(/^([a-zA-Z]{1,4})[-]([a-zA-Z]{0,2})\.json$/)){ if(withouExt) list.push(fileName.split('.json',1)); else list.push(fileName); } } return list; } // ---------------------------- HTTP HANDLERS ---------------------------- // /** * Tell the client to redirect to the specified path and close connection * @param req {object} input socket (request) * @param res {object} output socket (response) * @return none */ function redirect(req,res) { console.log('redirection to: '+uri); uri = '/'+req.url; res.writeHead(302, { 'Location': uri }); res.end(); } /** * Tell the client that the requested ressource * is unavailable and close connection * @param res {object} output socket (response) * @return none */ function send404(res) { res.writeHead(404, {'Content-Type': 'text/html'}); res.write('404 Not Found\n'); res.end(); } /** * Tell the client that the access * to the requested ressource is forbidden * @param res {object} output socket (response) * @return none */ function send403(res) { res.writeHead(403, {'Content-Type': 'text/html'}); res.write('403 Forbidden\n'); res.end(); } /** * Send a customized error code to the client and close connection * @param res {object} - socket response * @param err {integer} - error code * @param msg {string} - error message * @return none */ function sendErr(res,err,msg) { res.writeHead(err, {'Content-Type': 'text/html'}); res.write(msg?msg:'Error code : '+err); res.end(); }
/** * Service Proxy for CpProxyAvOpenhomeOrgVolume3 * @module ohnet * @class Volume */ var CpProxyAvOpenhomeOrgVolume3 = function(udn){ this.url = window.location.protocol + "//" + window.location.host + "/" + udn + "/av.openhome.org-Volume-3/control"; // upnp control url this.domain = "av-openhome-org"; this.type = "Volume"; this.version = "3"; this.serviceName = "av.openhome.org-Volume-3"; this.subscriptionId = ""; // Subscription identifier unique to each Subscription Manager this.udn = udn; // device name // Collection of service properties this.serviceProperties = {}; this.serviceProperties["Volume"] = new ohnet.serviceproperty("Volume","int"); this.serviceProperties["Mute"] = new ohnet.serviceproperty("Mute","bool"); this.serviceProperties["Balance"] = new ohnet.serviceproperty("Balance","int"); this.serviceProperties["Fade"] = new ohnet.serviceproperty("Fade","int"); this.serviceProperties["VolumeLimit"] = new ohnet.serviceproperty("VolumeLimit","int"); this.serviceProperties["VolumeMax"] = new ohnet.serviceproperty("VolumeMax","int"); this.serviceProperties["VolumeUnity"] = new ohnet.serviceproperty("VolumeUnity","int"); this.serviceProperties["VolumeSteps"] = new ohnet.serviceproperty("VolumeSteps","int"); this.serviceProperties["VolumeMilliDbPerStep"] = new ohnet.serviceproperty("VolumeMilliDbPerStep","int"); this.serviceProperties["BalanceMax"] = new ohnet.serviceproperty("BalanceMax","int"); this.serviceProperties["FadeMax"] = new ohnet.serviceproperty("FadeMax","int"); this.serviceProperties["UnityGain"] = new ohnet.serviceproperty("UnityGain","bool"); this.serviceProperties["VolumeOffsets"] = new ohnet.serviceproperty("VolumeOffsets","string"); this.serviceProperties["VolumeOffsetMax"] = new ohnet.serviceproperty("VolumeOffsetMax","int"); this.serviceProperties["Trim"] = new ohnet.serviceproperty("Trim","string"); } /** * Subscribes the service to the subscription manager to listen for property change events * @method Subscribe * @param {Function} serviceAddedFunction The function that executes once the subscription is successful */ CpProxyAvOpenhomeOrgVolume3.prototype.subscribe = function (serviceAddedFunction) { ohnet.subscriptionmanager.addService(this,serviceAddedFunction); } /** * Unsubscribes the service from the subscription manager to stop listening for property change events * @method Unsubscribe */ CpProxyAvOpenhomeOrgVolume3.prototype.unsubscribe = function () { ohnet.subscriptionmanager.removeService(this.subscriptionId); } /** * Adds a listener to handle "Volume" property change events * @method Volume_Changed * @param {Function} stateChangedFunction The handler for state changes */ CpProxyAvOpenhomeOrgVolume3.prototype.Volume_Changed = function (stateChangedFunction) { this.serviceProperties.Volume.addListener(function (state) { stateChangedFunction(ohnet.soaprequest.readIntParameter(state)); }); } /** * Adds a listener to handle "Mute" property change events * @method Mute_Changed * @param {Function} stateChangedFunction The handler for state changes */ CpProxyAvOpenhomeOrgVolume3.prototype.Mute_Changed = function (stateChangedFunction) { this.serviceProperties.Mute.addListener(function (state) { stateChangedFunction(ohnet.soaprequest.readBoolParameter(state)); }); } /** * Adds a listener to handle "Balance" property change events * @method Balance_Changed * @param {Function} stateChangedFunction The handler for state changes */ CpProxyAvOpenhomeOrgVolume3.prototype.Balance_Changed = function (stateChangedFunction) { this.serviceProperties.Balance.addListener(function (state) { stateChangedFunction(ohnet.soaprequest.readIntParameter(state)); }); } /** * Adds a listener to handle "Fade" property change events * @method Fade_Changed * @param {Function} stateChangedFunction The handler for state changes */ CpProxyAvOpenhomeOrgVolume3.prototype.Fade_Changed = function (stateChangedFunction) { this.serviceProperties.Fade.addListener(function (state) { stateChangedFunction(ohnet.soaprequest.readIntParameter(state)); }); } /** * Adds a listener to handle "VolumeLimit" property change events * @method VolumeLimit_Changed * @param {Function} stateChangedFunction The handler for state changes */ CpProxyAvOpenhomeOrgVolume3.prototype.VolumeLimit_Changed = function (stateChangedFunction) { this.serviceProperties.VolumeLimit.addListener(function (state) { stateChangedFunction(ohnet.soaprequest.readIntParameter(state)); }); } /** * Adds a listener to handle "VolumeMax" property change events * @method VolumeMax_Changed * @param {Function} stateChangedFunction The handler for state changes */ CpProxyAvOpenhomeOrgVolume3.prototype.VolumeMax_Changed = function (stateChangedFunction) { this.serviceProperties.VolumeMax.addListener(function (state) { stateChangedFunction(ohnet.soaprequest.readIntParameter(state)); }); } /** * Adds a listener to handle "VolumeUnity" property change events * @method VolumeUnity_Changed * @param {Function} stateChangedFunction The handler for state changes */ CpProxyAvOpenhomeOrgVolume3.prototype.VolumeUnity_Changed = function (stateChangedFunction) { this.serviceProperties.VolumeUnity.addListener(function (state) { stateChangedFunction(ohnet.soaprequest.readIntParameter(state)); }); } /** * Adds a listener to handle "VolumeSteps" property change events * @method VolumeSteps_Changed * @param {Function} stateChangedFunction The handler for state changes */ CpProxyAvOpenhomeOrgVolume3.prototype.VolumeSteps_Changed = function (stateChangedFunction) { this.serviceProperties.VolumeSteps.addListener(function (state) { stateChangedFunction(ohnet.soaprequest.readIntParameter(state)); }); } /** * Adds a listener to handle "VolumeMilliDbPerStep" property change events * @method VolumeMilliDbPerStep_Changed * @param {Function} stateChangedFunction The handler for state changes */ CpProxyAvOpenhomeOrgVolume3.prototype.VolumeMilliDbPerStep_Changed = function (stateChangedFunction) { this.serviceProperties.VolumeMilliDbPerStep.addListener(function (state) { stateChangedFunction(ohnet.soaprequest.readIntParameter(state)); }); } /** * Adds a listener to handle "BalanceMax" property change events * @method BalanceMax_Changed * @param {Function} stateChangedFunction The handler for state changes */ CpProxyAvOpenhomeOrgVolume3.prototype.BalanceMax_Changed = function (stateChangedFunction) { this.serviceProperties.BalanceMax.addListener(function (state) { stateChangedFunction(ohnet.soaprequest.readIntParameter(state)); }); } /** * Adds a listener to handle "FadeMax" property change events * @method FadeMax_Changed * @param {Function} stateChangedFunction The handler for state changes */ CpProxyAvOpenhomeOrgVolume3.prototype.FadeMax_Changed = function (stateChangedFunction) { this.serviceProperties.FadeMax.addListener(function (state) { stateChangedFunction(ohnet.soaprequest.readIntParameter(state)); }); } /** * Adds a listener to handle "UnityGain" property change events * @method UnityGain_Changed * @param {Function} stateChangedFunction The handler for state changes */ CpProxyAvOpenhomeOrgVolume3.prototype.UnityGain_Changed = function (stateChangedFunction) { this.serviceProperties.UnityGain.addListener(function (state) { stateChangedFunction(ohnet.soaprequest.readBoolParameter(state)); }); } /** * Adds a listener to handle "VolumeOffsets" property change events * @method VolumeOffsets_Changed * @param {Function} stateChangedFunction The handler for state changes */ CpProxyAvOpenhomeOrgVolume3.prototype.VolumeOffsets_Changed = function (stateChangedFunction) { this.serviceProperties.VolumeOffsets.addListener(function (state) { stateChangedFunction(ohnet.soaprequest.readStringParameter(state)); }); } /** * Adds a listener to handle "VolumeOffsetMax" property change events * @method VolumeOffsetMax_Changed * @param {Function} stateChangedFunction The handler for state changes */ CpProxyAvOpenhomeOrgVolume3.prototype.VolumeOffsetMax_Changed = function (stateChangedFunction) { this.serviceProperties.VolumeOffsetMax.addListener(function (state) { stateChangedFunction(ohnet.soaprequest.readIntParameter(state)); }); } /** * Adds a listener to handle "Trim" property change events * @method Trim_Changed * @param {Function} stateChangedFunction The handler for state changes */ CpProxyAvOpenhomeOrgVolume3.prototype.Trim_Changed = function (stateChangedFunction) { this.serviceProperties.Trim.addListener(function (state) { stateChangedFunction(ohnet.soaprequest.readStringParameter(state)); }); } /** * A service action to Characteristics * @method Characteristics * @param {Function} successFunction The function that is executed when the action has completed successfully * @param {Function} errorFunction The function that is executed when the action has cause an error */ CpProxyAvOpenhomeOrgVolume3.prototype.Characteristics = function(successFunction, errorFunction){ var request = new ohnet.soaprequest("Characteristics", this.url, this.domain, this.type, this.version); request.send(function(result){ result["VolumeMax"] = ohnet.soaprequest.readIntParameter(result["VolumeMax"]); result["VolumeUnity"] = ohnet.soaprequest.readIntParameter(result["VolumeUnity"]); result["VolumeSteps"] = ohnet.soaprequest.readIntParameter(result["VolumeSteps"]); result["VolumeMilliDbPerStep"] = ohnet.soaprequest.readIntParameter(result["VolumeMilliDbPerStep"]); result["BalanceMax"] = ohnet.soaprequest.readIntParameter(result["BalanceMax"]); result["FadeMax"] = ohnet.soaprequest.readIntParameter(result["FadeMax"]); if (successFunction){ successFunction(result); } }, function(message, transport) { if (errorFunction) {errorFunction(message, transport);} }); } /** * A service action to SetVolume * @method SetVolume * @param {Int} Value An action parameter * @param {Function} successFunction The function that is executed when the action has completed successfully * @param {Function} errorFunction The function that is executed when the action has cause an error */ CpProxyAvOpenhomeOrgVolume3.prototype.SetVolume = function(Value, successFunction, errorFunction){ var request = new ohnet.soaprequest("SetVolume", this.url, this.domain, this.type, this.version); request.writeIntParameter("Value", Value); request.send(function(result){ if (successFunction){ successFunction(result); } }, function(message, transport) { if (errorFunction) {errorFunction(message, transport);} }); } /** * A service action to VolumeInc * @method VolumeInc * @param {Function} successFunction The function that is executed when the action has completed successfully * @param {Function} errorFunction The function that is executed when the action has cause an error */ CpProxyAvOpenhomeOrgVolume3.prototype.VolumeInc = function(successFunction, errorFunction){ var request = new ohnet.soaprequest("VolumeInc", this.url, this.domain, this.type, this.version); request.send(function(result){ if (successFunction){ successFunction(result); } }, function(message, transport) { if (errorFunction) {errorFunction(message, transport);} }); } /** * A service action to VolumeDec * @method VolumeDec * @param {Function} successFunction The function that is executed when the action has completed successfully * @param {Function} errorFunction The function that is executed when the action has cause an error */ CpProxyAvOpenhomeOrgVolume3.prototype.VolumeDec = function(successFunction, errorFunction){ var request = new ohnet.soaprequest("VolumeDec", this.url, this.domain, this.type, this.version); request.send(function(result){ if (successFunction){ successFunction(result); } }, function(message, transport) { if (errorFunction) {errorFunction(message, transport);} }); } /** * A service action to Volume * @method Volume * @param {Function} successFunction The function that is executed when the action has completed successfully * @param {Function} errorFunction The function that is executed when the action has cause an error */ CpProxyAvOpenhomeOrgVolume3.prototype.Volume = function(successFunction, errorFunction){ var request = new ohnet.soaprequest("Volume", this.url, this.domain, this.type, this.version); request.send(function(result){ result["Value"] = ohnet.soaprequest.readIntParameter(result["Value"]); if (successFunction){ successFunction(result); } }, function(message, transport) { if (errorFunction) {errorFunction(message, transport);} }); } /** * A service action to SetBalance * @method SetBalance * @param {Int} Value An action parameter * @param {Function} successFunction The function that is executed when the action has completed successfully * @param {Function} errorFunction The function that is executed when the action has cause an error */ CpProxyAvOpenhomeOrgVolume3.prototype.SetBalance = function(Value, successFunction, errorFunction){ var request = new ohnet.soaprequest("SetBalance", this.url, this.domain, this.type, this.version); request.writeIntParameter("Value", Value); request.send(function(result){ if (successFunction){ successFunction(result); } }, function(message, transport) { if (errorFunction) {errorFunction(message, transport);} }); } /** * A service action to BalanceInc * @method BalanceInc * @param {Function} successFunction The function that is executed when the action has completed successfully * @param {Function} errorFunction The function that is executed when the action has cause an error */ CpProxyAvOpenhomeOrgVolume3.prototype.BalanceInc = function(successFunction, errorFunction){ var request = new ohnet.soaprequest("BalanceInc", this.url, this.domain, this.type, this.version); request.send(function(result){ if (successFunction){ successFunction(result); } }, function(message, transport) { if (errorFunction) {errorFunction(message, transport);} }); } /** * A service action to BalanceDec * @method BalanceDec * @param {Function} successFunction The function that is executed when the action has completed successfully * @param {Function} errorFunction The function that is executed when the action has cause an error */ CpProxyAvOpenhomeOrgVolume3.prototype.BalanceDec = function(successFunction, errorFunction){ var request = new ohnet.soaprequest("BalanceDec", this.url, this.domain, this.type, this.version); request.send(function(result){ if (successFunction){ successFunction(result); } }, function(message, transport) { if (errorFunction) {errorFunction(message, transport);} }); } /** * A service action to Balance * @method Balance * @param {Function} successFunction The function that is executed when the action has completed successfully * @param {Function} errorFunction The function that is executed when the action has cause an error */ CpProxyAvOpenhomeOrgVolume3.prototype.Balance = function(successFunction, errorFunction){ var request = new ohnet.soaprequest("Balance", this.url, this.domain, this.type, this.version); request.send(function(result){ result["Value"] = ohnet.soaprequest.readIntParameter(result["Value"]); if (successFunction){ successFunction(result); } }, function(message, transport) { if (errorFunction) {errorFunction(message, transport);} }); } /** * A service action to SetFade * @method SetFade * @param {Int} Value An action parameter * @param {Function} successFunction The function that is executed when the action has completed successfully * @param {Function} errorFunction The function that is executed when the action has cause an error */ CpProxyAvOpenhomeOrgVolume3.prototype.SetFade = function(Value, successFunction, errorFunction){ var request = new ohnet.soaprequest("SetFade", this.url, this.domain, this.type, this.version); request.writeIntParameter("Value", Value); request.send(function(result){ if (successFunction){ successFunction(result); } }, function(message, transport) { if (errorFunction) {errorFunction(message, transport);} }); } /** * A service action to FadeInc * @method FadeInc * @param {Function} successFunction The function that is executed when the action has completed successfully * @param {Function} errorFunction The function that is executed when the action has cause an error */ CpProxyAvOpenhomeOrgVolume3.prototype.FadeInc = function(successFunction, errorFunction){ var request = new ohnet.soaprequest("FadeInc", this.url, this.domain, this.type, this.version); request.send(function(result){ if (successFunction){ successFunction(result); } }, function(message, transport) { if (errorFunction) {errorFunction(message, transport);} }); } /** * A service action to FadeDec * @method FadeDec * @param {Function} successFunction The function that is executed when the action has completed successfully * @param {Function} errorFunction The function that is executed when the action has cause an error */ CpProxyAvOpenhomeOrgVolume3.prototype.FadeDec = function(successFunction, errorFunction){ var request = new ohnet.soaprequest("FadeDec", this.url, this.domain, this.type, this.version); request.send(function(result){ if (successFunction){ successFunction(result); } }, function(message, transport) { if (errorFunction) {errorFunction(message, transport);} }); } /** * A service action to Fade * @method Fade * @param {Function} successFunction The function that is executed when the action has completed successfully * @param {Function} errorFunction The function that is executed when the action has cause an error */ CpProxyAvOpenhomeOrgVolume3.prototype.Fade = function(successFunction, errorFunction){ var request = new ohnet.soaprequest("Fade", this.url, this.domain, this.type, this.version); request.send(function(result){ result["Value"] = ohnet.soaprequest.readIntParameter(result["Value"]); if (successFunction){ successFunction(result); } }, function(message, transport) { if (errorFunction) {errorFunction(message, transport);} }); } /** * A service action to SetMute * @method SetMute * @param {Boolean} Value An action parameter * @param {Function} successFunction The function that is executed when the action has completed successfully * @param {Function} errorFunction The function that is executed when the action has cause an error */ CpProxyAvOpenhomeOrgVolume3.prototype.SetMute = function(Value, successFunction, errorFunction){ var request = new ohnet.soaprequest("SetMute", this.url, this.domain, this.type, this.version); request.writeBoolParameter("Value", Value); request.send(function(result){ if (successFunction){ successFunction(result); } }, function(message, transport) { if (errorFunction) {errorFunction(message, transport);} }); } /** * A service action to Mute * @method Mute * @param {Function} successFunction The function that is executed when the action has completed successfully * @param {Function} errorFunction The function that is executed when the action has cause an error */ CpProxyAvOpenhomeOrgVolume3.prototype.Mute = function(successFunction, errorFunction){ var request = new ohnet.soaprequest("Mute", this.url, this.domain, this.type, this.version); request.send(function(result){ result["Value"] = ohnet.soaprequest.readBoolParameter(result["Value"]); if (successFunction){ successFunction(result); } }, function(message, transport) { if (errorFunction) {errorFunction(message, transport);} }); } /** * A service action to VolumeLimit * @method VolumeLimit * @param {Function} successFunction The function that is executed when the action has completed successfully * @param {Function} errorFunction The function that is executed when the action has cause an error */ CpProxyAvOpenhomeOrgVolume3.prototype.VolumeLimit = function(successFunction, errorFunction){ var request = new ohnet.soaprequest("VolumeLimit", this.url, this.domain, this.type, this.version); request.send(function(result){ result["Value"] = ohnet.soaprequest.readIntParameter(result["Value"]); if (successFunction){ successFunction(result); } }, function(message, transport) { if (errorFunction) {errorFunction(message, transport);} }); } /** * A service action to UnityGain * @method UnityGain * @param {Function} successFunction The function that is executed when the action has completed successfully * @param {Function} errorFunction The function that is executed when the action has cause an error */ CpProxyAvOpenhomeOrgVolume3.prototype.UnityGain = function(successFunction, errorFunction){ var request = new ohnet.soaprequest("UnityGain", this.url, this.domain, this.type, this.version); request.send(function(result){ result["Value"] = ohnet.soaprequest.readBoolParameter(result["Value"]); if (successFunction){ successFunction(result); } }, function(message, transport) { if (errorFunction) {errorFunction(message, transport);} }); } /** * A service action to VolumeOffset * @method VolumeOffset * @param {String} Channel An action parameter * @param {Function} successFunction The function that is executed when the action has completed successfully * @param {Function} errorFunction The function that is executed when the action has cause an error */ CpProxyAvOpenhomeOrgVolume3.prototype.VolumeOffset = function(Channel, successFunction, errorFunction){ var request = new ohnet.soaprequest("VolumeOffset", this.url, this.domain, this.type, this.version); request.writeStringParameter("Channel", Channel); request.send(function(result){ result["VolumeOffsetBinaryMilliDb"] = ohnet.soaprequest.readIntParameter(result["VolumeOffsetBinaryMilliDb"]); if (successFunction){ successFunction(result); } }, function(message, transport) { if (errorFunction) {errorFunction(message, transport);} }); } /** * A service action to SetVolumeOffset * @method SetVolumeOffset * @param {String} Channel An action parameter * @param {Int} VolumeOffsetBinaryMilliDb An action parameter * @param {Function} successFunction The function that is executed when the action has completed successfully * @param {Function} errorFunction The function that is executed when the action has cause an error */ CpProxyAvOpenhomeOrgVolume3.prototype.SetVolumeOffset = function(Channel, VolumeOffsetBinaryMilliDb, successFunction, errorFunction){ var request = new ohnet.soaprequest("SetVolumeOffset", this.url, this.domain, this.type, this.version); request.writeStringParameter("Channel", Channel); request.writeIntParameter("VolumeOffsetBinaryMilliDb", VolumeOffsetBinaryMilliDb); request.send(function(result){ if (successFunction){ successFunction(result); } }, function(message, transport) { if (errorFunction) {errorFunction(message, transport);} }); } /** * A service action to Trim * @method Trim * @param {String} Channel An action parameter * @param {Function} successFunction The function that is executed when the action has completed successfully * @param {Function} errorFunction The function that is executed when the action has cause an error */ CpProxyAvOpenhomeOrgVolume3.prototype.Trim = function(Channel, successFunction, errorFunction){ var request = new ohnet.soaprequest("Trim", this.url, this.domain, this.type, this.version); request.writeStringParameter("Channel", Channel); request.send(function(result){ result["TrimBinaryMilliDb"] = ohnet.soaprequest.readIntParameter(result["TrimBinaryMilliDb"]); if (successFunction){ successFunction(result); } }, function(message, transport) { if (errorFunction) {errorFunction(message, transport);} }); } /** * A service action to SetTrim * @method SetTrim * @param {String} Channel An action parameter * @param {Int} TrimBinaryMilliDb An action parameter * @param {Function} successFunction The function that is executed when the action has completed successfully * @param {Function} errorFunction The function that is executed when the action has cause an error */ CpProxyAvOpenhomeOrgVolume3.prototype.SetTrim = function(Channel, TrimBinaryMilliDb, successFunction, errorFunction){ var request = new ohnet.soaprequest("SetTrim", this.url, this.domain, this.type, this.version); request.writeStringParameter("Channel", Channel); request.writeIntParameter("TrimBinaryMilliDb", TrimBinaryMilliDb); request.send(function(result){ if (successFunction){ successFunction(result); } }, function(message, transport) { if (errorFunction) {errorFunction(message, transport);} }); }
const validate = (input) => { const errors = {}; const values = input.toJS(); if (!values.username) { errors.username = 'Required'; } else if (values.username.length > 15) { errors.username = 'Must be 15 characters or less'; } else if (values.username.length < 3) { errors.username = 'Must be 3 characters or more'; } else if (!/^[a-zA-Zá-žÁ-Ž0-9_-]{3,15}$/i.test(values.username)) { errors.username = 'The password contains forbidden characters'; } if (!values.email) { errors.email = 'Required'; } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) { errors.email = 'Invalid email address'; } if (!values.password) { errors.password = 'Required'; } else if (values.password.length < 5) { errors.password = 'Password too short'; } if (values.password !== values.passwordConfirm) { errors.passwordConfirm = 'Passwords do not match'; } return errors; }; export default validate;
export * from './dbl-click-copy.directive'; export * from './visibility.directive'; export * from './directives.module'; //# sourceMappingURL=index.js.map
// Based on iniparser by shockie <https://npmjs.org/package/iniparser> var fs = require('fs'); /* * define the possible values: * section: [section] * param: key=value * comment: ;this is a comment */ var regex = { section: /^\s*\[(([^#;]|\\#|\\;)+)\]\s*([#;].*)?$/, param: /^\s*([\w\.\-\_]+)\s*[=:]\s*(.*?)\s*([#;].*)?$/, comment: /^\s*[#;].*$/ }; /** * parses a .ini file * @param {String} file, the location of the .ini file * @param {Function} callback, the function that will be called when parsing is done */ module.exports.parse = function (file, callback) { if (!callback) { return; } fs.readFile(file, 'utf8', function (err, data) { if (err) { callback(err); } else { callback(null, parse(data)); } }); }; module.exports.parseSync = function (file) { return parse(fs.readFileSync(file, 'utf8')); }; function parse (data) { var sectionBody = {}; var sectionName = null; var value = [[sectionName, sectionBody]]; var lines = data.split(/\r\n|\r|\n/); lines.forEach(function (line) { var match; if (regex.comment.test(line)) { return; } else if (regex.param.test(line)) { match = line.match(regex.param); sectionBody[match[1]] = match[2]; } else if (regex.section.test(line)) { match = line.match(regex.section); sectionName = match[1]; sectionBody = {}; value.push([sectionName, sectionBody]); } }); return value; } module.exports.parseString = parse;
// flow-typed signature: f2de767c1337d15eb591f26fd1ab3af4 // flow-typed version: <<STUB>>/babel-plugin-react-intl-auto_v^2.3.0/flow_v0.102.0 /** * This is an autogenerated libdef stub for: * * 'babel-plugin-react-intl-auto' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'babel-plugin-react-intl-auto' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'babel-plugin-react-intl-auto/lib/__tests__/components.test' { declare module.exports: any; } declare module 'babel-plugin-react-intl-auto/lib/__tests__/hook.test' { declare module.exports: any; } declare module 'babel-plugin-react-intl-auto/lib/__tests__/index.test' { declare module.exports: any; } declare module 'babel-plugin-react-intl-auto/lib/__tests__/injection.test' { declare module.exports: any; } declare module 'babel-plugin-react-intl-auto/lib' { declare module.exports: any; } declare module 'babel-plugin-react-intl-auto/lib/types' { declare module.exports: any; } // Filename aliases declare module 'babel-plugin-react-intl-auto/lib/__tests__/components.test.js' { declare module.exports: $Exports<'babel-plugin-react-intl-auto/lib/__tests__/components.test'>; } declare module 'babel-plugin-react-intl-auto/lib/__tests__/hook.test.js' { declare module.exports: $Exports<'babel-plugin-react-intl-auto/lib/__tests__/hook.test'>; } declare module 'babel-plugin-react-intl-auto/lib/__tests__/index.test.js' { declare module.exports: $Exports<'babel-plugin-react-intl-auto/lib/__tests__/index.test'>; } declare module 'babel-plugin-react-intl-auto/lib/__tests__/injection.test.js' { declare module.exports: $Exports<'babel-plugin-react-intl-auto/lib/__tests__/injection.test'>; } declare module 'babel-plugin-react-intl-auto/lib/index' { declare module.exports: $Exports<'babel-plugin-react-intl-auto/lib'>; } declare module 'babel-plugin-react-intl-auto/lib/index.js' { declare module.exports: $Exports<'babel-plugin-react-intl-auto/lib'>; } declare module 'babel-plugin-react-intl-auto/lib/types.js' { declare module.exports: $Exports<'babel-plugin-react-intl-auto/lib/types'>; }
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __spreadArray = (this && this.__spreadArray) || function (to, from) { for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) to[j] = from[i]; return to; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.gradleTemplate = exports.listLibClasses = void 0; var chalk_1 = __importDefault(require("chalk")); var fs_1 = __importDefault(require("fs")); var path_1 = __importDefault(require("path")); var redent_1 = __importDefault(require("redent")); var jszip_1 = __importDefault(require("jszip")); var glob_1 = require("glob"); var child_process_1 = require("child_process"); var errors_1 = require("../errors"); var constants_1 = require("../constants"); var parser = __importStar(require("../parser")); var utils = __importStar(require("../utils")); var interfaces_json_1 = __importDefault(require("../jdk/interfaces.json")); function default_1(offline) { return __awaiter(this, void 0, void 0, function () { var jars, classes; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!fs_1.default.existsSync(constants_1.path.PACKAGE)) { console.error(chalk_1.default.red(constants_1.path.PACKAGE + " does not exist.")); process.exit(errors_1.code.PROJECT_NOT_FOUND); } if (!offline) { npmInstall(); gradleInstall(); } jars = utils.listFilesByExt("lib", ".jar"); if (!(jars.length > 0)) return [3 /*break*/, 2]; console.log("Parsing classes from the following libraries:"); jars.map(function (it) { return console.log(" * " + it); }); return [4 /*yield*/, listLibClasses(jars)]; case 1: classes = _a.sent(); console.log("Found " + chalk_1.default.green(classes.length) + " classes"); console.log("Generating typescript definitions..."); parser.parse(jars, interfaces_json_1.default, classes, path_1.default.join(process.cwd(), "lib", "@types")); _a.label = 2; case 2: return [2 /*return*/]; } }); }); } exports.default = default_1; function listLibClasses(jars) { return __awaiter(this, void 0, void 0, function () { var classes, _i, jars_1, jar, data, files; return __generator(this, function (_a) { switch (_a.label) { case 0: classes = {}; _i = 0, jars_1 = jars; _a.label = 1; case 1: if (!(_i < jars_1.length)) return [3 /*break*/, 4]; jar = jars_1[_i]; data = fs_1.default.readFileSync(jar); return [4 /*yield*/, jszip_1.default.loadAsync(data)]; case 2: files = (_a.sent()).files; Object.keys(files).forEach(function (it) { if (it.endsWith(".class")) { var key = it.replace(/(\$\d+)*\.class$/, "").replace(/\//g, "."); if (key.split(".").reverse()[0].indexOf("-") < 0) { // Skip class like `package-info` classes[key] = true; } } }); _a.label = 3; case 3: _i++; return [3 /*break*/, 1]; case 4: return [2 /*return*/, Object.keys(classes)]; } }); }); } exports.listLibClasses = listLibClasses; function npmInstall() { var child = child_process_1.spawnSync("npm", ["install"], { stdio: "inherit" }); if (child.status) process.exit(child.status); } function gradleInstall() { fs_1.default.mkdirSync(path_1.default.join("lib", "@types"), { recursive: true }); fs_1.default.writeFileSync(path_1.default.join("lib", "@types", "index.d.ts"), ""); var mvnDependencies = {}; // find all mvnDependencies from node_modules __spreadArray([constants_1.path.PACKAGE], new glob_1.GlobSync(path_1.default.join("node_modules", "**", constants_1.path.PACKAGE)).found).forEach(function (it) { var pkg = JSON.parse(fs_1.default.readFileSync(it, "utf-8")); Object.keys(pkg.mvnDependencies || {}).forEach(function (k) { if (pkg.mvnDependencies[k] > (mvnDependencies[k] || "")) mvnDependencies[k] = pkg.mvnDependencies[k]; }); }); var deps = Object.keys(mvnDependencies).map(function (it) { return it + ":" + mvnDependencies[it]; }); fs_1.default.writeFileSync(path_1.default.join("lib", "build.gradle"), exports.gradleTemplate(deps)); var child = child_process_1.spawnSync("gradle", [ "-b", path_1.default.join("lib", "build.gradle"), "--no-daemon", "install" ], { stdio: "inherit" }); if (child.status) process.exit(child.status); } var gradleTemplate = function (deps) { return redent_1.default("\n apply plugin: \"java\"\n\n repositories {\n jcenter()\n mavenCentral()\n }\n\n task install(type: Copy) {\n into \".\"\n from configurations.runtime\n }\n\n dependencies {\n " + deps.map(function (it) { return "compile \"" + it + "\""; }).join("\n ") + "\n }\n", 0).trimStart(); }; exports.gradleTemplate = gradleTemplate;
var channelName = document.getElementById('channel-name'); var startButton = document.getElementById('start-button'); startButton.onclick = function(){ if(channelName.value){ var webrtc = new SimpleWebRTC({ // the id/element dom element that will hold "our" video localVideoEl: 'localVideo', // the id/element dom element that will hold remote videos remoteVideosEl: 'remoteVideos', // immediately ask for camera access autoRequestMedia: true }); // we have to wait until it's ready webrtc.on('readyToCall', function () { // you can name it anything webrtc.joinRoom(channelName.value); }); //显示本地视频窗口 localVideo.classList.remove('hidden'); }else{ alert('请输入频道名'); } }
/*! * Flickr Downloadr * Copyright: 2007-2015 Sondre Bjellås. http://sondreb.com/ * License: MIT */ 'use strict'; /* Simple wrapper for the socket.io. Hiding some of the details to create a new instance. Due to the individual socket pr. client nature of socket.io, we'll simply return the socket.io instance and don't do any abstractions of it's methods. */ module.exports = function (socket, storage, flickr) { // Bind the socket events with the Flickr API and storage API. socket.on('connection', function (client) { return; client.on('message', function (msg) { console.log('socket.io:message: ', msg); }); client.on('accessGranted', function (msg) { console.log('socket.io:accessGranted: ', msg); var token = msg.oauth_token; var verifier = msg.oauth_verifier; storage.openCollection('tokens').then(function (collection) { console.log('Opening collection... reading document by token..'); var document = storage.readByToken(token, collection).then(function (document) { if (document === undefined) { console.log('This should not happen. When the user have received verified, this document should exist in the database.'); throw new Error('Cannot find existing session. Cannot continue.'); } else { var doc = document; console.log('Found document: ', doc); doc.modified = new Date(); doc.tokenVerifier = verifier; var secret = doc.tokenSecret; flickr.getAccessToken(token, secret, verifier, function (err, message) { if (err) { throw err; } console.log('Get Access Token: ', message); // Return the access token to the user for local permanent storage. client.emit('token', message); // Now we should delete the session token from storage. // Perhaps we should have some sort of timeout, if there // is a connection issue with the WebSocket? //storage.delete(doc); }); } }).fail(function (err) { console.log('Failed to read document!! Error: ' + err); }); }); }); client.on('signUrl', function (msg) { return; console.log('Sign this method: ', msg); flickr.signUrl(msg.token, msg.secret, msg.method, msg.args, function (err, data) { console.log('URL SIGNED: ', data); // Return the login url to the user. client.emit('urlSigned', data); }); }); // When user requests auth URL, generate using the Flickr service. client.on('getUrl', function () { return; console.log('io: User requests login url.'); flickr.getAuthUrl(function (err, data) { if (err) { console.log('Error with getAuthUrl: ', err); return; } // Store these details in storage on the current client id. var oauthToken = data.oauthToken; var oauthTokenSecret = data.oauthTokenSecret; var clientId = client.id; console.log('oauthToken: ', oauthToken); console.log('oauthTokenSecret: ', oauthTokenSecret); console.log('clientId: ', clientId); // Return the login url to the user. client.emit('url', { url: data.url }); storage.openCollection('tokens').then(function (collection) { console.log('COLLECTION OPENED!! Searching for: ' + clientId); var document = storage.readBySessionId(clientId, collection).then(function (document) { if (document === undefined) { var doc = { modified: new Date(), connectionId: clientId, token: oauthToken, tokenSecret: oauthTokenSecret, tokenVerifier: '' }; storage.insert(doc, collection).then(function (document) { console.log('Saved document: ' + document); }); } else { console.log('Found document: ' + document); document.modified = new Date(); storage.update(document, collection); } }).fail(function (err) { console.log('Failed to read document!! Error: ' + err); }); }); }); }); }); };
/*global module:true*/ var lrSnippet = require('grunt-contrib-livereload/lib/utils').livereloadSnippet; var mountFolder = function (connect, dir) { return connect.static(require('path').resolve(dir)); }; var yeomanConfig = { app: 'app', dist: 'dist' }; module.exports = function (grunt) { 'use strict'; require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); grunt.initConfig({ yeoman: yeomanConfig, open: { server: { url: 'http://localhost:<%= connect.livereload.options.port %>' } }, // default watch configuration watch: { widgets: { files: ['app/widgets/**/*.js'], tasks: ['concat'] }, handlebars: { files: ['app/widgets/**/*.hbs'], tasks: ['handlebars'] }, livereload: { files: [ 'app/*.html', '{.tmp,app}/styles/*.css', '{.tmp,app}/extensions/*.js', '{.tmp,app}/scripts/*.js', 'app/images/*.{png,jpg,jpeg}' ], tasks: ['livereload'] } }, jshint: { all: [ 'app/scripts/[^templates].js', 'app/widgets/**/*.js' ] }, handlebars: { compile: { files: { "app/scripts/templates.js" : ["app/widgets/**/*.hbs"] }, options: { wrapped: true, namespace: "Handlebars.templates", processName: function (filename) { return filename.replace(/^app\/widgets\//, '').replace(/\.hbs$/, ''); } } } }, connect: { livereload: { options: { port: 9032, middleware: function (connect) { return [ lrSnippet, mountFolder(connect, '.tmp'), mountFolder(connect, 'app') ]; } } } }, clean: { dist: ['.tmp', 'dist/*'], server: '.tmp' }, uglify: { dist: { files: { 'dist/application.js': [ 'app/scripts/*.js' ] } } }, useminPrepare: { html: 'index.html' }, usemin: { html: ['dist/*.html'], css: ['dist/styles/*.css'] }, imagemin: { dist: { files: [{ expand: true, cwd: 'app/images', src: '*.{png,jpg,jpeg}', dest: 'dist/images' }] } }, cssmin: { dist: { files: { 'dist/application.css': [ 'app/components/ratchet/dist/ratchet.css', 'app/components/font-awesome/css/font-awesome.css', 'app/styles/*.css' ] } } }, copy: { dist: { files: [ { dest: 'dist/index.php', src: 'dist/index.html' }, { cwd: 'app/', dest: 'dist/', src: ['.htaccess', 'robots.txt'], expand: true }, { cwd: 'app/components/font-awesome/font/', dest: 'dist/font/', filter: 'isFile', src: '*', expand: true } ] } }, htmlmin: { dist: { options: { removeComments: false, removeCommentsFromCDATA: true, collapseWhitespace: false, collapseBooleanAttributes: true, removeAttributeQuotes: false, removeRedundantAttributes: false, useShortDoctype: true, removeEmptyAttributes: false, removeOptionalTags: false }, files: [{ expand: true, cwd: 'app', src: '*.html', dest: 'dist' }] } }, concat: { options: { separator: "\n\n\n\n//--------\n\n\n" }, dist: { src: ['app/widgets/**/*.js'], dest: 'app/scripts/widgets.js' } } }); grunt.renameTask('regarde', 'watch'); grunt.renameTask('mincss', 'cssmin'); grunt.registerTask('server', [ 'clean:server', 'livereload-start', 'connect:livereload', 'open', 'watch' ]); grunt.registerTask('test', [ 'clean:server', 'connect:livereload', 'watch' ]); grunt.registerTask('build', [ 'clean:dist', 'concat', 'jshint', 'handlebars', 'useminPrepare', 'uglify', 'imagemin', 'htmlmin', 'cssmin', 'usemin', 'copy' ]); grunt.registerTask('default', ['build']); };
function aggregateOffsetTop(element) { if (!element) { return -1; } let y = element.offsetTop; while (element = element.offsetParent) { y += element.offsetTop; } return y; } chrome.extension.sendMessage({}, function(response) { const readyStateCheckInterval = setInterval(function() { if (document.readyState === 'complete') { clearInterval(readyStateCheckInterval); /* assuming it will never change in the DOM */ let player = document.querySelector('.player-api'); if (!player) { return; } let { clientWidth, clientHeight, classList } = player; let playerOffsetTop = aggregateOffsetTop(player); let breakpoint = (clientHeight / 2) + playerOffsetTop; let timer = null; let isFloating = false; function handleScroll(event) { if (timer) { clearTimeout(timer); } timer = setTimeout(function() { if (window.scrollY > breakpoint) { if (!isFloating) { classList.add('__floating'); isFloating = true; } } else if (isFloating) { classList.remove('__floating'); isFloating = false; } }, 100); } document.addEventListener('scroll', handleScroll); } }, 10); });
'use strict' // var distance = require('./centimeter') // distance.set('league', 'centimeter', 1 / 0.0000020712373) // module.exports = distance module.exports = ['league', 'centimeter', 1 / 0.0000020712373]
jui.define("chart.brush.polygon.core", [], function() { var PolygonCoreBrush = function() { this.createPolygon = function(polygon, callback) { this.calculate3d(polygon); var element = callback.call(this, polygon); if(element) { element.order = this.axis.depth - polygon.max().z; return element; } } } PolygonCoreBrush.setup = function() { return { id: null, clip: false } } return PolygonCoreBrush; }, "chart.brush.core");
/**start**/this["JST"] = this["JST"] || {};this["JST"]["test/fixtures/template/shop.html"] = function(obj) {obj || (obj = {});var __t, __p = '', __e = _.escape;with (obj) {__p += '<div id="M-Shop"><h2>' +((__t = (title)) == null ? '' : __t) +'</h2><div class="shop-list"></div></div>';}return __p};this["JST"] = this["JST"] || {};this["JST"]["test/fixtures/template/area.html"] = function(obj) {obj || (obj = {});var __t, __p = '', __e = _.escape;with (obj) {__p += '<div id="M-Area"><h2>' +((__t = (title)) == null ? '' : __t) +'</h2><div class="area-list"></div></div>';}return __p};/**end**/var ShopModule=function(){CustomGetTemplateFn('shop.html')(obj);};var AreaModule=function(){CustomGetTemplateFn('area.html')(obj);};
// Keep track of which names are used so that there are no duplicates var userNames = (function () { var names = {}; var claim = function (name) { if (!name || names[name]) { return false; } else { names[name] = true; return true; } }; // find the lowest unused "guest" name and claim it var getGuestName = function () { var name, nextUserId = 1; do { name = 'Guest ' + nextUserId; nextUserId += 1; } while (!claim(name)); return name; }; // serialize claimed names as an array var getAll = function () { var nameArray = []; for (var key in names) { var val = names[key]; if (val) { nameArray.push({name: key}); } } return nameArray; }; var free = function (name) { if (names[name]) { delete names[name]; } }; return { claim: claim, free: free, getAll: getAll, getGuestName: getGuestName }; }()); var serverConnected = false; // export function for listening to the socket module.exports = function (socket) { //scope of this function is a client connection! var username; var isServer = false; socket.emit('ask:name'); //answer from clients socket.on('answer:name', function(data) { if (data && data.username && data.username !== null) { //client send a username //check if claim if (userNames.claim(data.username)) { username = data.username; } else { //name not available //give guest name username = userNames.getGuestName(); } } else { //client has no username sent, give guest username = userNames.getGuestName(); } // send the new user their name and a list of users socket.emit('init', { name: username, users: [] }); // notify other clients that a new user has joined socket.broadcast.emit('user:join', { name: username }); }); //answer from server socket.on('server', function() { socket.emit('init', {users: userNames.getAll()}) //a server is connected isServer = true; serverConnected = true; socket.broadcast.emit('server:ok'); }); // notify other clients score changed socket.on('score:change', function (data) { socket.broadcast.emit('score:change', data); }); // notify other clients for locks socket.on('score:lock', function () { socket.emit('score:lock'); socket.broadcast.emit('score:lock'); }); socket.on('score:unlock', function () { socket.emit('score:unlock'); socket.broadcast.emit('score:unlock'); }); // validate a user's name change, and broadcast it on success socket.on('change:name', function (data, fn) { if (userNames.claim(data.name)) { var oldName = username; userNames.free(oldName); username = data.name; socket.broadcast.emit('change:name', { oldName: oldName, newName: username }); fn(true); } else { fn(false); } }); //server will kick user socket.on('kick:name', function (data) { console.log("receive kick request of user: ", data); //free user userNames.free(data.username); socket.broadcast.emit('user:left', { name: data.username }); }); //clients can ask for server connection status socket.on('ask:server', function() { if (serverConnected) { socket.emit('server:ok'); } else { socket.emit('server:lost'); } }); // clean up when a user leaves, and broadcast it to other users socket.on('disconnect', function () { //For server notify server lost if (isServer) { serverConnected = false; socket.broadcast.emit('server:lost'); } else { //For clients, fire user:left and free username socket.broadcast.emit('user:left', { name: username }); userNames.free(username); } }); };
/** * Created by zpl on 15-3-22. * 专门存储token */ angular.module('RDash'). factory('SessionService',['$localStorage','$cookies','User','$window',function($localStorage,$cookies,User,$window){ return { getUserinfo: function(){ this.login() var user ={ //userid:1, userid: $cookies.get("u_id"), name:$cookies.get("u_name"), avatar:$cookies.get("u_avatar") } //if(user == null){ // //TODO need login,mock login // user = $localStorage.user; //} return user; }, isLogin:function(){ //if($localStorage.token) // return true; //return false; //return true; if(($cookies.get("token"))==undefined) { return false; } return true; }, getToken:function(){ var token = $cookies.get("token"); if(token == null){ //TODO need login,mock login this.login(); token = $cookies.get("token"); } return token; }, login:function(){ if(($cookies.get('token'))==undefined) { alert('请先登陆') $window.location.href = ssoUrl+window.location.href; exit; } }, logout:function(){ $cookies.remove('token',{ domain:'.learn4me.com' }); $cookies.remove('u_id',{ domain:'.learn4me.com' }); $window.location.href = "/"; //delete $cookies.token; //delete $cookies.u_id; } } }]);
'use strict'; var gulp = require('gulp'); var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); var babel = require('gulp-babel'); var compass = require('gulp-compass'); var cssmin = require('gulp-cssmin'); gulp.task('scripts', function(){ return gulp.src('./src/ng-circle.js') .pipe(babel()) .pipe(gulp.dest('dist')) .pipe(rename({extname: '.min.js'})) .pipe(uglify()) .pipe(gulp.dest('dist')); }); gulp.task('styles', function () { return gulp.src('./src/ng-circle.scss') .pipe(compass({ config_file: './config.rb', css: './dist/css', sass: './src', comments: true, sourcemap: true })) .pipe(gulp.dest('./dist/css')) .pipe(cssmin()) .pipe(rename({ extname: '.min.css'})) .pipe(gulp.dest('./dist/css')); }); gulp.task('watch', function() { gulp.watch('./src/ng-circle.js', ['scripts']); gulp.watch('./src/ng-circle.scss', ['styles']); }); gulp.task('default', ['scripts', 'styles', 'watch']); gulp.task('styles:demo', function () { return gulp.src('./demo/demo.scss') .pipe(compass({ //config_file: './config.rb', css: './demo/css', sass: './demo', comments: true, sourcemap: true })) .pipe(gulp.dest('./demo/css')) .pipe(cssmin()) .pipe(rename({ extname: '.min.css'})) .pipe(gulp.dest('./demo/css')); }); gulp.task('watch:demo', function() { //gulp.watch('./demo/demo.js', ['scripts']); gulp.watch('./demo/demo.scss', ['styles:demo']); }); gulp.task('demo', ['styles:demo', 'watch:demo']);
( function () { 'use strict'; mare.views.LogIn = Backbone.View.extend({ // this view controls the content of the modal window, create an element to insert into the modal tagName: 'section', // give the container for our view a class we can hook into className: 'log-in-container', initialize: function initialize() { // create a hook to access the log in modal contents template var html = $( '#log-in-template' ).html(); // compile the template to be used during rendering/repainting the log in modal this.template = Handlebars.compile( html ); }, // events need to be bound every time the modal is opened, so they can't be put in an event block bindEvents: function bindEvents() { // bind an event to allow closing of the modal $( '.modal__close' ).click( this.closeModal.bind( this ) ); $( '.log-in-form__forgot-password' ).click( this.toggleForgotPassword ); $( '.forgot-password__login-link' ).click( this.toggleLogin ); }, // events need to be unbound every time the modal is closed unbindEvents: function unbindEvents() { $( '.modal__close' ).unbind( 'click' ); }, render: function render() { // Pass the child model to through the template we stored during initialization var html = this.template( { target: mare.url.redirect } ); this.$el.html( html ); // Render the contents area and tabs $( '.modal-container__contents' ).html( this.$el ); // TODO: due to the child details for the gallery, the gallery by default shows a loading indicator instead of the contents // this fixes the display. Once the modal becomes it's own view that accepts options, hacky fixes like this won't be necessary $( '.modal-container__loading' ).hide(); $( '.modal-container__contents' ).show(); }, /* When a child card is clicked, display detailed information for that child in a modal window */ handleLogInClick: function handleLogInClick( event ) { // Open the modal this.openModal(); }, /* TODO: all modal functions below mirror the calls made in waiting-child-profiles-child-details.js. Both files need to use a modal.js Backbone view which should handle all this. /* Open the modal container */ openModal: function openModal() { // populate the modal with the log in template this.render(); // TODO: this adds a class to the modal to adjust it's size. This should be handled by passing in a size option to a modal view on initialization $( '.modal__container' ).addClass( 'modal__container--small' ); $( '.modal-container__contents' ).addClass( 'modal-container__contents--vertically-centered' ); $( '.modal__background' ).fadeIn(); $( '.modal__container' ).fadeIn(); mare.utils.disablePageScrolling(); // Bind click events for the newly rendered elements if( mare.views.childDetails ) { mare.views.childDetails.bindEvents(); } else { this.bindEvents(); } }, /* close the modal container */ closeModal: function closeModal() { $( '.modal__background' ).fadeOut(); $( '.modal__container' ).fadeOut( function() { // TODO: this removes a class from the modal to adjust it's size. This should be handled in the modal view once it's created // wait until the modal has finished fading out before changing the modal size by removing this class $( this ).removeClass( 'modal__container--small' ); }); mare.utils.enablePageScrolling(); /* TODO: this doesn't belong in modal, emit an event on close so the child details view can respond to it appropriatly */ // This event is called from a click event so the view context is lost, we need to explicitly call all functions if( mare.views.childDetails ) { mare.views.childDetails.unbindEvents(); } else { this.unbindEvents(); } }, /* switch the login view to the password reset view */ toggleForgotPassword: function setupForgotPassword(){ $( '.log-in' ).hide(); $( '.forgot-password' ).show(); }, toggleLogin: function displayLogin(){ $( '.forgot-password' ).hide(); $( '.log-in' ).show(); } }); }());
var crypto = require('crypto') , sync = require('sync'); var iterCnt = 512; var pwdtLen = 32; var saltLen = 16; var userToOTT = {}; function getOTT() { var shasum = crypto.createHash('sha1'); shasum.update(Date.now().toString()); return shasum.digest('hex'); } function generateOTT(uid, ott) { if (userToOTT[uid] == ott) { userToOTT[uid] = getOTT(); return userToOTT[uid]; } else { delete userToOTT[uid]; return false; } } exports.checkOTT = function checkOTT(req, res, next) { var ott = generateOTT(req.query.uid, req.query.ott); if (ott) { res.ott = ott; next(); } else { res.status(401); res.json({ error: 'Wrong token.' }); } }; exports.sessionCheck = function (req, res) { sync(function () { var ott = generateOTT(req.query.uid, req.query.ott);; if (ott) { var result = req.db.query.sync(req.db, 'SELECT id, username FROM users WHERE id = ?', [req.query.uid])[0][0]; result.ott = ott; res.json(result); } else { res.status(401); res.json({ error: 'Wrong token.' }); } }, function (err) { if (err) { console.log(err); } }); }; exports.auth = function auth(req, res) { sync(function () { var user = req.db.query.sync(req.db, 'SELECT id, username, password, salt FROM users WHERE username = ?', ['' + req.query.username])[0][0]; if (!user) { res.status(401); res.json({ error: 'User with this email does not exist.' }); } var pass = crypto.pbkdf2.sync(null, req.query.password + '', user.salt + '', iterCnt, pwdtLen).toString('hex'); if (pass == user.password) { var ott = getOTT(); userToOTT[user.id] = ott; res.json({ id: user.id, username: user.username, ott: ott }); } else { res.status(401); res.json({ error: 'Wrong email or password.' }); } }, function (err) { if (err) { throw err; } }); }; exports.register = function register(req, res) { sync(function () { if (req.body.pw == req.body.cpw) { var salt = crypto.randomBytes(saltLen).toString('hex'), password = crypto.pbkdf2.sync(null, req.body.pw, salt, iterCnt, pwdtLen).toString('hex'), accountValidation = req.db.query.sync(req.db, 'SELECT username FROM users WHERE username = ?', [req.body.username + ''])[0]; if (accountValidation.length === 0) { var insertedId = req.db.query.sync(req.db, 'INSERT INTO users (username, password, salt) VALUES (?, ?, ?)', [req.body.username, password, salt]).insertId, ott = getOTT(); userToOTT[insertedId] = ott; res.json({ id: insertedId, username: req.body.username, ott: ott }); } else { res.status(400); res.json({error: 'User already exist.'}); } } else { res.status(400); res.json({error: 'Password does not match the confirm password.'}); } }, function (err) { if (err) { console.log(err); } }); }; exports.getUsers = function getUsers(req, res) { sync(function () { var users = req.db.query.sync(req.db, 'SELECT `id`, `username`, `SU` FROM `users`')[0]; res.json(users); }, function (err) { if (err) { console.log(err); } }); };
(function($) { /* --------------------- Plugin Vars --------------------- */ var _ajax = $.ajax, fauxHandlers = [], fakedAjaxCalls = [], unhandled = []; /* ---------------- The Fauxjax Object ------------------- */ $.fauxjax = {}; /* -------------------- Public API ----------------------- */ /** * Create new instance of faux request handler * @param {Object} settings The settings for the faux request * @returns {Int} Returns index faux request in handler array */ $.fauxjax.new = function(settings) { fauxHandlers.push(settings); return fauxHandlers.length - 1; }; /** * Default settings for fauxjax requests */ $.fauxjax.settings = { status: 200, statusText: 'OK', responseTime: 0, isTimeout: false, content: '', contentType: 'application/x-www-form-urlencoded', strictMatching: true, debug: false, headers: {} }; /** * Clear all fauxjax arrays * @param {None} * @returns {undefined} */ $.fauxjax.clear = function() { fauxHandlers = []; fakedAjaxCalls = []; unhandled = []; }; /** * Remove faux handler from handlers array * @param {Integer} index The index of the faux handler to be removed * @returns {undefined} */ $.fauxjax.remove = function(index) { fauxHandlers[index] = null; }; /** * Gets an array containing all faux requests that have not been fired. * Useful is test teardown to check for unneeded mocking. * @param {None} * @returns {Array} Returns an array of faux requests that have not been fired */ $.fauxjax.unfired = function() { var results = []; for (var i=0, len=fauxHandlers.length; i<len; i++) { var handler = fauxHandlers[i]; if (handler !== null && !handler.fired) { results.push(handler); } } return results; }; /** * Gets an array containing all real ajax requests. * Useful in test teardown to check for requests that need to be mocked. * @param {None} * @returns {Array} Returns an array of real ajax requests that have been fired */ $.fauxjax.unhandled = function() { return unhandled; }; /** * Gets an array containing all ajax requests that have been faked. * @param {None} * @returns {Array} Returns an array of all faked ajax requests */ $.fauxjax.fakedAjaxCalls = function() { return fakedAjaxCalls; }; /* -------------------- Internal Plugin API ----------------------- */ $.extend({ ajax: interceptAjax }); /** * Called when shouldMockRequest returns false. If debug is set to true then log * debugging information * @param {String} url A string representing the requested url * @param {Sting} mismatchedProperty A string designating the property * that caused the request to not be matched * @returns {undefined} */ function debugInfo(mockVerb, realVerb, mockContentType, realContentType, mockData, realData, mockHeaders, realHeaders, mockUrl, realUrl) { if ($.fauxjax.settings.debug) { console.log('===== Fauxjax Debug Info ====='); console.log('*Real Request*'); console.log(' URL: ' + realUrl); console.log(' Type: ' + realVerb); console.log(' contentType: ' + realContentType); console.log(' Headers: ' + _.toPairs(realHeaders)); console.log(' Data: ' + JSON.stringify(realData)); console.log('*Mock Request*'); console.log(' URL: ' + mockUrl); console.log(' Type: ' + mockVerb); console.log(' contentType: ' + mockContentType); console.log(' Headers: ' + _.toPairs(mockHeaders)); console.log(' Data: ' + JSON.stringify(mockData)); } } /** * Currently fauxjax expects that contentType will be either `x-www-form-urlencoded` or `json` * If it is not one we return the other. * @param {Object} handler The request handler for either the real request or the fake * @returns {String} Returns the contentType */ function parseContentType(handler) { if (_.includes(handler.contentType, 'json')) { return 'application/json'; } return 'application/x-www-form-urlencoded'; } /** * Currently fauxjax expects that contentType will be either `x-www-form-urlencoded` or `json` * Given this assumption we will have data that is either text, objects or a stringified object * based on the specified `contentType` pase the data to allow comparison in the `shouldMockRequest` * function. * @param {String|Object} data The data provided with the request * @param {String} contentType The contentType for the request * @returns {String|Object} The parsed data to be compared for a match */ function parseData(data, contentType) { if (_.includes(['application/vnd.api+json', 'application/json'], contentType) && !_.isObject(data)) { return JSON.parse(data); } return data; } /** * Compares a mockHandler and a real Ajax request and determines if the real request should be mocked. * @param {Object} mockHandler A fauxjax settings object * @param {Object} realRequestContext The real context of the actual Ajax request * @returns {Boolean} Returns true if the real request should be mocked false otherwise */ function shouldMockRequest(mockHandler, realRequestContext) { if (mockHandler) { var strictMatching = mockHandler.request.strictMatching || $.fauxjax.settings.strictMatching; var mockVerb = mockHandler.request.method || mockHandler.request.type; var realVerb = realRequestContext.method || realRequestContext.type; var realContentType = parseContentType(realRequestContext); var mockContentType = parseContentType(mockHandler.request); var mockRequest = mockHandler.request; var mockData = parseData(mockHandler.request.data, mockContentType); var realData = parseData(realRequestContext.data, realContentType); var urlRegexMatch = _.isRegExp(mockRequest.url) && mockRequest.url.test(realRequestContext.url); if (!_.isEqual(mockRequest.url, realRequestContext.url) && !urlRegexMatch) { return false; } if (mockVerb && mockVerb.toLowerCase() !== realVerb.toLowerCase()) { return false; } if (!_.isEqual(realContentType, mockContentType)) { if (strictMatching || mockData && !realData) { debugInfo(mockVerb, realVerb, mockContentType, realContentType, mockData, realData, mockRequest.headers, realRequestContext.headers, mockRequest.url, realRequestContext.url); return false; } } if (_.some(_.compact([mockData, realData])) && !_.isEqual(mockData, realData)) { if (strictMatching || mockData && !realData) { debugInfo(mockVerb, realVerb, mockContentType, realContentType, mockData, realData, mockRequest.headers, realRequestContext.headers, mockRequest.url, realRequestContext.url); return false; } } if (!_.isEqual(mockRequest.headers, realRequestContext.headers) && strictMatching) { debugInfo(mockVerb, realVerb, mockContentType, realContentType, mockData, realData, mockRequest.headers, realRequestContext.headers, mockRequest.url, realRequestContext.url); return false; } return true; } else { return false; } } /** * Properly format the faux request's content to be sent in the faux xhr * @param {Object|String} content The value of `content` in the mock request * @returns {String} Returns a string version of the `content` */ function formatResponseText(content) { if (_.isObject(content)) { return JSON.stringify(content); } return content; } /** * Determine the response content-type based on the value of content * @param {Object|String} content The value of `content` in the mock request * @returns {String} Returns a string of the contentType */ function getResponseContentType(content) { if (_.isObject(content)) { return 'json'; } return 'text'; } /** * The send operation of the faux xhr object * @param {Object} mockRequestContext The context of the faux request * @param {Object} realRequestContext The context of the real Ajax request * @returns {undefined} */ function _xhrSend(mockRequestContext, realRequestContext) { var process = _.bind(function() { this.status = mockRequestContext.isTimeout ? -1 : mockRequestContext.status; this.statusText = mockRequestContext.statusText; this.responseText = formatResponseText(mockRequestContext.content); this.onload.call(this); }, this); return realRequestContext.async ? setTimeout(process, mockRequestContext.responseTime) : process(); } /** * Build the string used for response headers in the faux xhr object * @param {Object} mockRequestContext * @returns {Sting} Returns response headers */ function buildResponseHeaders(mockRequestContext) { var headers = ''; $.each(mockRequestContext.headers, function(k, v) { headers += k + ': ' + v + '\n'; }); return headers; } /** * Build a faux xhr object that can be used in the faux ajax response * @param {Object} mockHandler * @param {Object} realRequestContext * @returns {Object} Returns a faux xhr object */ function fauxXhr(mockHandler, realRequestContext) { deepCloneSettings = _.clone($.fauxjax.settings, true); mockRequestContext = _.assign({}, deepCloneSettings, mockHandler.response); mockRequestContext.headers['content-type'] = getResponseContentType(mockRequestContext.content); realRequestContext.headers = {}; return { status: mockRequestContext.status, statusText: mockRequestContext.statusText, open: function() { }, send: function() { mockHandler.fired = true; _xhrSend.call(this, mockRequestContext, realRequestContext); }, setRequestHeader: function(header, value) { realRequestContext.headers[header] = value; }, getAllResponseHeaders: function() { return buildResponseHeaders(mockRequestContext); } }; } /** * The actual call to the jQuery ajax method * @param {Object} mockHandler * @param {Object} realRequestContext * @param {Object} realRequestSettings * @returns {Object} Returns the actual jQuery ajax request object that was * created with the fauxXhr method */ function makeFauxAjaxCall(mockHandler, realRequestContext, realRequestSettings) { fauxRequest = _ajax.call($, _.assign({}, realRequestSettings, { xhr: function() {return fauxXhr(mockHandler, realRequestContext);} })); return fauxRequest; } /** * The entry point of the plugin. This intercepts calls to jQuery's ajax method * @param {Object} realRequestSettings The real request settings from the actual ajax call * @returns {Object} Returns a jQuery ajax request object, either real or faux */ function interceptAjax(realRequestSettings) { var realRequestContext = _.assign({}, $.ajaxSettings, realRequestSettings); for(var k = 0; k < fauxHandlers.length; k++) { if (shouldMockRequest(fauxHandlers[k], realRequestContext)) { fakedAjaxCalls.push(realRequestContext); fauxRequest = makeFauxAjaxCall(fauxHandlers[k], realRequestContext, realRequestSettings); return fauxRequest; } } unhandled.push(realRequestSettings); return _ajax.apply($, [realRequestSettings]); } })(jQuery);
/* ************************************************************************ Copyright: Hericus Software, LLC License: The MIT License (MIT) Authors: Steven M. Cherry ************************************************************************ */ qx.Mixin.define("dev.layout.LayoutTripleField", { members : { createTripleField: function ( theThis, node, parent ) { dev.Statics.addFieldsToForm(theThis, parent, node.getAttribute("label1"), this.fieldAreaFirst, node.getAttribute("varName1"), node.getAttribute("type1"), node.getAttribute("label2"), this.fieldAreaSecond, node.getAttribute("varName2"), node.getAttribute("type2"), node.getAttribute("label3"), this.fieldAreaThird, node.getAttribute("varName3"), node.getAttribute("type3") ); // Check for tooltips: this.addToolTip(theThis, node, "tooltip1", "varName1"); this.addToolTip(theThis, node, "tooltip2", "varName2"); this.addToolTip(theThis, node, "tooltip3", "varName3"); // Set read only state: this.setReadOnly(theThis, node, "readOnly1", "varName1"); this.setReadOnly(theThis, node, "readOnly2", "varName2"); this.setReadOnly(theThis, node, "readOnly3", "varName3"); // Check for field verification this.checkFieldVerification(theThis, node); // Load any static combo values this.loadComboValues(theThis, node, 1); this.loadComboValues(theThis, node, 2); this.loadComboValues(theThis, node, 3); } } });
'use babel'; import React, { Component } from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { createSession, connectToPeer, destroy } from '../actions/session' import SidebarHeader from '../components/SidebarHeader' import SidebarBody from '../components/SidebarBody' class Sidebar extends Component { componentWillMount() { const { user, createSession } = this.props createSession(user.username) } componentWillReceiveProps(nextProps) { if (nextProps.user.username != this.props.user.username) { this.props.destroy() this.props.createSession(nextProps.user.username) } } render() { const { user, connectToPeer, calling, callTarget } = this.props return ( <div className="sidebar"> <SidebarHeader user={user} connectToPeer={connectToPeer} calling={calling} callTarget={callTarget} /> <SidebarBody user={user} /> </div> ) } } function mapStateToProps(state) { const { login, session } = state; return { user: login.user, avatar: login.user ? login.user.avatar : '', calling: session.calling, callTarget: session.callTarget, } } function mapDispatchToProps(dispatch) { return bindActionCreators({ createSession, connectToPeer, destroy }, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(Sidebar)
/** * TranslationOverride Service * * @class TranslationOverrideService * @module Hightail * @submodule Hightail.Services * * @author justin.fiedler * @since 0.0.1 * * @copyright (c) 2014 Hightail Inc. All Rights Reserved */ 'use strict'; angular.wilson.service('TranslationOverrideService', function() { //Global Dictionary of override translations for fast lookup var translationOverrides = { // 'overriddenNS': { // 'textKey': { // 'overridingNs1': true // ... // }, // ... // }, // ... }; /** * Adds an overide entry for the given params * * @param nsToOverride The namespace you want to be overriden * @param overridingNs The namespace you want to override with * @param textKey The textKey to override */ var addOverride = function(nsToOverride, overridingNs, textKey) { var nsOverrides = translationOverrides[nsToOverride]; if (!nsOverrides) { //create a dictionary for 'nsToOverride' nsOverrides = translationOverrides[nsToOverride] = {}; } var textKeyEntry = nsOverrides[textKey]; if (!textKeyEntry) { //create and entry for the 'textKey' in 'nsToOverride' textKeyEntry = nsOverrides[textKey] = {}; } var overridingNsEntry = textKeyEntry[overridingNs]; if (!overridingNsEntry) { //mark the textKey as having an override for 'overridingNs' textKeyEntry[overridingNs] = true; } //console.log('translationOverrides', translationOverrides); }; /** * Returns true if namespace @ns has ANY overrides for @textKey * * @param ns * @param textKey * @returns {boolean} */ var hasOverride = function(ns, textKey) { return (translationOverrides[ns] && translationOverrides[ns][textKey]); }; /** * Returns true if namespace @ns has an override for @textKey in @overridingNs * * @param ns * @param textKey * @param overridingNs * @returns {boolean} */ var hasOverrideForNamespace = function(ns, textKey, overridingNs) { return (translationOverrides[ns] && translationOverrides[ns][textKey] && translationOverrides[ns][textKey][overridingNs]); }; // Service Object var service = { addOverride: addOverride, hasOverride: hasOverride, hasOverrideForNamespace: hasOverrideForNamespace }; return service; });
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow * @format */ 'use strict'; const QueryBuilder = require('../query/QueryBuilder'); const RelayMetaRoute = require('../route/RelayMetaRoute'); const RelayMutationTransactionStatus = require('./RelayMutationTransactionStatus'); const RelayQuery = require('../query/RelayQuery'); const invariant = require('invariant'); const {ConnectionInterface} = require('RelayRuntime'); import type {RelayConcreteNode} from '../query/RelayQL'; import type {RelayEnvironmentInterface} from '../store/RelayEnvironment'; import type RelayStoreData from '../store/RelayStoreData'; import type {ClientMutationID} from '../tools/RelayInternalTypes'; import type {RelayMutationTransactionCommitCallbacks} from '../tools/RelayTypes'; import type { RelayMutationTransactionCommitFailureCallback, RelayMutationTransactionCommitSuccessCallback, } from '../tools/RelayTypes'; import type {FileMap} from './RelayMutation'; import type RelayMutationTransaction from './RelayMutationTransaction'; import type {DeclarativeMutationConfig, Variables} from 'RelayRuntime'; const COUNTER_PREFIX = 'RelayGraphQLMutation'; let collisionIDCounter = 0; /** * @public * * Low-level API for modeling a GraphQL mutation. * * This is the lowest level of abstraction at which product code may deal with * mutations in Relay, and it corresponds to the mutation operation ("a write * followed by a fetch") described in the GraphQL Specification. You specify * the mutation, the inputs, and the query. * * (There is an even lower-level representation, `RelayMutationRequest`, * underlying this which is an entirely internal implementation detail that * product code need not be aware of.) * * @see http://facebook.github.io/graphql/. * */ class RelayGraphQLMutation { _callbacks: ?RelayMutationTransactionCommitCallbacks; _collisionKey: string; _environment: RelayEnvironmentInterface; _files: ?FileMap; _query: RelayConcreteNode; _transaction: ?PendingGraphQLTransaction; _variables: Object; /** * Simplest method for creating a RelayGraphQLMutation instance from a static * `mutation`, some `variables` and an `environment`. */ static create( mutation: RelayConcreteNode, variables: Object, environment: RelayEnvironmentInterface, ): RelayGraphQLMutation { return new RelayGraphQLMutation(mutation, variables, null, environment); } /** * Specialized method for creating RelayGraphQLMutation instances that takes a * `files` object in addition to the base `mutation`, `variables` and * `environment` parameters. */ static createWithFiles( mutation: RelayConcreteNode, variables: Variables, files: FileMap, environment: RelayEnvironmentInterface, ): RelayGraphQLMutation { return new RelayGraphQLMutation(mutation, variables, files, environment); } /** * General constructor for creating RelayGraphQLMutation instances with * optional `files`, `callbacks` and `collisionKey` arguments. * * Callers must provide an appropriate `mutation`: * * Relay.QL` * mutation StoryLikeQuery { * likeStory(input: $input) { * clientMutationId * story { * likeCount * likers { * actor { * name * } * } * } * } * } * `; * * And set of `variables`: * * { * input: { * feedbackId: 'aFeedbackId', * }, * } * * As per the GraphQL Relay Specification: * * - The mutation should take a single argument named "input". * - That input argument should contain a (string) "clientMutationId" property * for the purposes of reconciling requests and responses (automatically * added by the RelayGraphQLMutation API). * - The query should request "clientMutationId" as a subselection. * * @see http://facebook.github.io/relay/docs/graphql-mutations.html * @see http://facebook.github.io/relay/graphql/mutations.htm * * If not supplied, a unique collision key is derived (meaning that the * created mutation will be independent and not collide with any other). */ constructor( query: RelayConcreteNode, variables: Variables, files: ?FileMap, environment: RelayEnvironmentInterface, callbacks: ?RelayMutationTransactionCommitCallbacks, collisionKey: ?string, ) { this._query = query; this._variables = variables; this._files = files || null; this._environment = environment; this._callbacks = callbacks || null; this._collisionKey = collisionKey || `${COUNTER_PREFIX}:collisionKey:${getNextCollisionID()}`; this._transaction = null; } /** * Call this to optimistically apply an update to the store. * * The optional `config` parameter can be used to configure a `RANGE_ADD` type * mutation, similar to `RelayMutation` API. * * Optionally, follow up with a call to `commit()` to send the mutation * to the server. * * Note: An optimistic update may only be applied once. */ applyOptimistic( optimisticQuery: RelayConcreteNode, optimisticResponse: Object, configs: ?Array<DeclarativeMutationConfig>, ): RelayMutationTransaction { invariant( !this._transaction, 'RelayGraphQLMutation: `applyOptimistic()` was called on an instance ' + 'that already has a transaction in progress.', ); this._transaction = this._createTransaction( optimisticQuery, optimisticResponse, ); return this._transaction.applyOptimistic(configs); } /** * Call this to send the mutation to the server. * * The optional `config` parameter can be used to configure a `RANGE_ADD` type * mutation, similar to the `RelayMutation` API. * * Optionally, precede with a call to `applyOptimistic()` to apply an update * optimistically to the store. * * Note: This method may only be called once per instance. */ commit(configs: ?Array<DeclarativeMutationConfig>): RelayMutationTransaction { if (!this._transaction) { this._transaction = this._createTransaction(); } return this._transaction.commit(configs); } rollback(): void { if (this._transaction) { return this._transaction.rollback(); } } _createTransaction( optimisticQuery: ?RelayConcreteNode, optimisticResponse: ?Object, ): PendingGraphQLTransaction { return new PendingGraphQLTransaction( this._environment, this._query, this._variables, this._files, optimisticQuery, optimisticResponse, this._collisionKey, this._callbacks, ); } } function getNextCollisionID(): number { return collisionIDCounter++; } /** * @internal * * Data structure conforming to the `PendingTransaction` interface specified by * `RelayMutationQueue`. */ class PendingGraphQLTransaction { // These properties required to conform to the PendingTransaction interface: error: ?Error; id: ClientMutationID; mutationTransaction: RelayMutationTransaction; onFailure: ?RelayMutationTransactionCommitFailureCallback; onSuccess: ?RelayMutationTransactionCommitSuccessCallback; status: $Keys<typeof RelayMutationTransactionStatus>; // Other properties: _collisionKey: string; _configs: Array<DeclarativeMutationConfig>; _files: ?FileMap; _mutation: ?RelayQuery.Mutation; _optimisticConfigs: ?Array<DeclarativeMutationConfig>; _optimisticResponse: ?Object; _optimisticQuery: ?RelayConcreteNode; _optimisticMutation: ?RelayQuery.Mutation; _query: RelayConcreteNode; _variables: Variables; constructor( environment: RelayEnvironmentInterface, query: RelayConcreteNode, variables: Variables, files: ?FileMap, optimisticQuery: ?RelayConcreteNode, optimisticResponse: ?Object, collisionKey: string, callbacks: ?RelayMutationTransactionCommitCallbacks, ) { this._configs = []; this._query = query; this._variables = variables; this._files = files; this._optimisticQuery = optimisticQuery || null; this._optimisticResponse = optimisticResponse || null; this._collisionKey = collisionKey; this.onFailure = callbacks && callbacks.onFailure; this.onSuccess = callbacks && callbacks.onSuccess; this.status = RelayMutationTransactionStatus.CREATED; this.error = null; this._mutation = null; this._optimisticConfigs = null; this._optimisticMutation = null; this.mutationTransaction = environment .getStoreData() .getMutationQueue() .createTransactionWithPendingTransaction(this); this.id = this.mutationTransaction.getID(); } // Methods from the PendingTransaction interface. getCallName(): string { invariant( this._mutation, 'RelayGraphQLMutation: `getCallName()` called but no mutation exists ' + '(`getQuery()` must be called first to construct the mutation).', ); return this._mutation.getCall().name; } getCollisionKey(): ?string { return this._collisionKey; } getConfigs(): Array<DeclarativeMutationConfig> { return this._configs; } getFiles(): ?FileMap { return this._files; } getOptimisticConfigs(): ?Array<DeclarativeMutationConfig> { return this._optimisticConfigs; } getOptimisticQuery(storeData: RelayStoreData): ?RelayQuery.Mutation { if (!this._optimisticMutation && this._optimisticQuery) { const concreteMutation = QueryBuilder.getMutation(this._optimisticQuery); const mutation = RelayQuery.Mutation.create( concreteMutation, RelayMetaRoute.get('$RelayGraphQLMutation'), this._getVariables(), ); this._optimisticMutation = (mutation: any); // Cast RelayQuery.{Node -> Mutation}. } return this._optimisticMutation; } getOptimisticResponse(): ?Object { return { ...this._optimisticResponse, [ConnectionInterface.get().CLIENT_MUTATION_ID]: this.id, }; } getQuery(storeData: RelayStoreData): RelayQuery.Mutation { if (!this._mutation) { const concreteMutation = QueryBuilder.getMutation(this._query); const mutation = RelayQuery.Mutation.create( concreteMutation, RelayMetaRoute.get('$RelayGraphQLMutation'), this._getVariables(), ); this._mutation = (mutation: any); // Cast RelayQuery.{Node -> Mutation}. } return this._mutation; } // Additional methods outside the PendingTransaction interface. commit(configs: ?Array<DeclarativeMutationConfig>): RelayMutationTransaction { if (configs) { this._configs = configs; } return this.mutationTransaction.commit(); } applyOptimistic( configs: ?Array<DeclarativeMutationConfig>, ): RelayMutationTransaction { if (configs) { this._optimisticConfigs = configs; } return this.mutationTransaction.applyOptimistic(); } rollback(): void { this.mutationTransaction.rollback(); } _getVariables(): Variables { const input = this._variables.input; if (!input) { invariant( false, 'RelayGraphQLMutation: Required `input` variable is missing ' + '(supplied variables were: [%s]).', Object.keys(this._variables).join(', '), ); } return { ...this._variables, input: { ...(input: $FlowFixMe), [ConnectionInterface.get().CLIENT_MUTATION_ID]: this.id, }, }; } } module.exports = RelayGraphQLMutation;
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require jquery-ui/datepicker //= require bootstrap-sprockets //= require select2 //= require google-analytics //= require_tree .
angular .module('app') .factory('notificationService', notificationService); notificationService.$inject = ['$window', '$timeout', '$compile', '$rootScope', '$sce']; function notificationService($window, $timeout, $compile, $rootScope, $sce) { var elementBuffer = []; var service = { notify : notify, simple : simple, success : success, error : error, info : info, warning : warning, }; return service; function _reposite() { var verticalSpacing = 10; var lastBottom = 20; for(var i=elementBuffer.length-1; i>=0; i--) { var element = elementBuffer[i]; var height = parseInt(element[0].offsetHeight); var bottom = lastBottom; lastBottom = bottom+height+verticalSpacing; element.css('bottom', bottom+'px'); } } function _note(config) { var TEMPLATE = ''+ '<div class="notification" ng-class="type">'+ ' <div class="notification-icon" ng-show="icon"><i class="fa fa-fw" ng-class="icon"></i></div>'+ ' <div class="notification-content" ng-class="{\'has-icon\': icon}">' + ' <div class="notification-title" ng-show="title" ng-bind-html="title"></div>'+ ' <div class="notification-message" ng-bind-html="message"></div>'+ ' </div>' + '</div>'; var DEFAULT = { type : 'default', title : '', message : '', icon : false, delay : 3000, } // Default parameters config = tine.merge({}, DEFAULT, config); // Set scope variables to fill the template var scope = $rootScope.$new(); scope.type = config.type; scope.title = $sce.trustAsHtml(config.title); scope.message = $sce.trustAsHtml(config.message); scope.icon = config.icon; scope.delay = config.delay; // Create the DOM element and add events var element = $compile(TEMPLATE)(scope); element.bind('webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd click', function(e) { e = e.originalEvent || e; if (e.type==='click' || element.hasClass('killed')) { element.remove(); elementBuffer.remove(element); _reposite(); } }); if (angular.isNumber(config.delay)) { $timeout(function() { element.addClass('killed'); }, config.delay); } $timeout(function() { element.addClass('started'); _reposite(); }, 0); elementBuffer.push(element); angular.element(document.getElementsByTagName('body')).append(element); } function notify(config) { _note(config); } function simple(title, message) { _note({title:title, message:message, type:'default'}); } function success(title, message) { _note({title:title, message:message, icon:'fa-check', type:'success'}); } function error(title, message) { _note({title:title, message:message, icon:'fa-close', type:'error'}); } function info(title, message) { _note({title:title, message:message, icon:'fa-info', type:'info'}); } function warning(title, message) { _note({title:title, message:message, icon:'fa-warning', type:'warning'}); } }
/* * Given an array of integers, find if the array contains any duplicates. * Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. * * Tags: * - Array * - Hash Table */ /** * @param {number[]} nums * @return {boolean} */ var containsDuplicate = function(nums) { var record = []; for (var i = 0; i < nums.length; i++) { var n = nums[i]; if (record[n] === true) { return true; } record[n] = true; } return false; }; // mocha testing var expect = require('chai').expect; describe('Contains Duplicate', function() { it('[]', function () { var input = []; var output = containsDuplicate(input); expect(output).to.be.false; }); it('[0, 1, 2, 3]', function () { var input = [0, 1, 2, 3]; var output = containsDuplicate(input); expect(output).to.be.false; }); it('[0, 0, 1, 1, 2, 2]', function () { var input = [0, 0, 1, 1, 2, 2]; var output = containsDuplicate(input); expect(output).to.be.true; }); it('[0, 0, 1, 1, 2, 2, 3]', function () { var input = [0, 0, 1, 1, 2, 2, 3]; var output = containsDuplicate(input); expect(output).to.be.true; }); });
const co = require('co'); const phantomjs = require('../index'); // Tests whether SendEvent function works. // // If working, the following output should be: // // 1. Positions of Button { height: 27, left: 10, right: ~98, top: 10, width: ~88 } // 2. Clicked on body // 3. Clicked on button // 4. Clicked on button // // 2 and 3 happens because of the `click()` function, // where as 4 happens due to sendEvent let generatorFn = function* () { let phantom = yield phantomjs.create(); let html = '<html>' + '<head><title>Test</title></head>' + '<body style="width: 500px; height: 500px;"><button id="myButton">MyButton</button></body>' + '</html>'; // Creating a page is as simple as this, // and can be done several times for all the pages you need. // Make sure to run page.close() or phantom.exit() // when you are done. let page = yield phantom.createPage(); // Add listeners for console and error. // Console messages are sent when clicks happens, // errors if anything goes wrong page.onConsoleMessage(function(message) { console.log(message); }); page.onError(function(message) { console.log(message); }); yield page.openHtml(html); // then open google let positions = yield page.evaluate(function() { document.body.addEventListener('click', function() { console.log('Clicked on body'); }); // Retrieve the button we created var button = document.getElementById('myButton'); // Add an event listener to it. button.addEventListener('click', function(e) { if (e.stopPropagation) { e.stopPropagation(); } if (e.preventDefault) { e.preventDefault(); } console.log('Clicked on button'); }); return button.getBoundingClientRect(); }); // Check the button positions console.log('Positions of myButton', positions); // Calculate the positions, clicking in the // middle of the button let x = positions.left + positions.width / 2; let y = positions.top + positions.height / 2; // Perform clicks with `click` function just to // make sure they work. yield page.evaluate(function() { document.body.click(); document.getElementById('myButton').click(); }); // Send the event, it should work yield page.sendEvent('click', x, y, 'left'); yield page.close(); yield phantom.exit(); }; // Run the generatorFunction - returns a promise co(generatorFn) .then(() => console.log('Done')) .catch(err => console.error(err || err.stack));
var argscheck = require('cordova/argscheck'), exec = require('cordova/exec'); var safesmsExport = {}; /* * Methods */ safesmsExport.startWatch = function(filter, successCallback, failureCallback) { cordova.exec( successCallback, failureCallback, 'SMS', 'startWatch', [ filter ] ); }; safesmsExport.stopWatch = function(successCallback, failureCallback) { cordova.exec( successCallback, failureCallback, 'SMS', 'stopWatch', [] ); }; safesmsExport.enableIntercept = function(on_off, successCallback, failureCallback) { on_off = !! on_off; cordova.exec( successCallback, failureCallback, 'SMS', 'enableIntercept', [ on_off ] ); }; safesmsExport.listSMS = function(filter, successCallback, failureCallback) { cordova.exec( successCallback, failureCallback, 'SMS', 'listSMS', [ filter ] ); }; module.exports = safesmsExport;
import { isPlainObject, isPlain } from '../util/is' import { setDeep } from '../util/getset' import { mergeCore } from '../util/merge' export default function applyPatchFactory(patchers) { return function applyPatch(target, patch) { const mutations = [] const target_root = { '': target } // a trick to allow top level patches const patch_root = { '': patch } // a trick to allow top level patches const unpatch_root = { '': {} } function addMutation(target, prop, old_value, path) { mutations.push({ target, prop, old_value, path, }) } mergeCore(patch_root, target_root, ({ patch, target, prop, path }) => { const patch_value = patch[prop] const target_value = target[prop] if ( !target.hasOwnProperty(prop) || (patch_value !== target_value && !(isPlainObject(patch_value) && isPlain(target_value))) ) { const length = target.length // Applying patches const old_value = patchers.reduce( (old_value, patcher) => patcher({ patch, target, prop, old_value, applyPatch, }), target_value ) // We register the mutation if old_value is different to the new value if (target[prop] !== old_value) { addMutation(target, prop, old_value, path.slice(1)) if (target.length !== length) { addMutation( target, 'length', length, path.slice(1, path.length - 1).concat('length') ) } } return false // we don't go deeper } }) // Creating unpatch for (let index = mutations.length - 1; index >= 0; --index) { const { path, old_value } = mutations[index] setDeep(unpatch_root, [''].concat(path), old_value) } return { result: target_root[''], unpatch: unpatch_root[''], mutations, } } }
define(['core/core-modules/framework.form', 'core/core-modules/framework.table'], function (form, table) { var options; /** 查看详情按钮时间处理程序 */ var execute_action = function () { if ($(this).attr('disabled')) { return; } if ($(this).data('custom')) { return; } var data = table.getSelect(); switch (options.viewmode) { case "modal": form.openWidow({ 'url': options.page, 'title': options.title, 'width': options.width, 'height': options.height, 'onshow': function (parent) { if (options.callback && typeof options.callback === 'function') { options.callback(data, parent); } } }); break; case "page": form.openview({ 'url': options.page, 'title': options.title, 'callback': function () { if (options.callback && typeof options.callback === 'function') { options.callback(data); } } }); break; default: break; } } return { "define": { "name": "action-preview" }, /** 加载插件:打开详情界面 * @param {JSON} data 详情展示所需要的数据内容 * @returns */ "init": function (action, actionContainer, actionOption) { options = actionOption; let button = form.appendAction(actionContainer, 'btn-' + action, execute_action); if (actionOption.mulit) { button.addClass("qdp-mulit"); } else { button.addClass("qdp-single"); } }, /** 卸载插件 */ "destroy": function () { } }; });
(function (angular, noty) { "use strict"; angular.module('ClassesModule', ['myApp', 'ngRoute']) .config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/classes', { templateUrl: 'classes/show.html', controller: 'ClassesController', resolve: { classStyles: ['consts', '$http', 'ApiService', function (consts, $http) { return $http.get(consts.apiUrl + '/ClassStyles').then(function (response) { return response.data; }, function (err) { return false; }); }], classes: ['consts', '$http', 'ApiService', function (consts, $http) { return $http.get(consts.apiUrl + '/Classes', {params: {filter: {include: "classStyle"}}}).then(function (response) { return response.data; }, function (err) { return false; }); }] } }); }]) .controller('ClassesController', ['$scope', 'classStyles', 'classes', 'ngDialog', '$http', 'consts', '$route', function ($scope, classStyles, classes, ngDialog, $http, consts, $route) { $scope.edit = function (_class) { ngDialog.open({ template: 'classes/edit.html', className: 'ngdialog-theme-default', width: '70%', controller: 'ClassesEditController', resolve: { _class: [function () { return _class; }], classStyles: [function () { return classStyles; }] } }); }; $scope.remove = function (_class) { ngDialog.openConfirm({ template: '\ <p>Do you really want to remove this Class?</p>\ <div class="ngdialog-buttons">\ <button type="button" class="ngdialog-button ngdialog-button-secondary" ng-click="closeThisDialog(0)">No</button>\ <button type="button" class="ngdialog-button ngdialog-button-primary" ng-click="confirm(1)">Yes</button>\ </div>', plain: true }).then(function (confirm) { $http.delete(consts.apiUrl + '/Classes/' + _class.id) .then(function (response) { noty({type: 'warning', text: 'Class removed'}); $route.reload(); }, function (err) { if (err.data.error && err.data.error.message) { noty({type: 'error', text: err.data.error.message}); } else { console.error(err); noty({ type: 'error', text: 'An unknown error has ocurred, check browser\'s console for more info' }); } }); }); } $scope.new = function () { ngDialog.open({ template: 'classes/new.html', className: 'ngdialog-theme-default', width: '70%', controller: 'ClassesNewController', resolve: { classStyles: [function () { return classStyles; }] } }); }; $scope.classStyles = classStyles; $scope.classes = classes; }]) .controller('ClassesEditController', ['$scope', 'classStyles', '_class', 'ngDialog', '$http', '$route', 'consts', function ($scope, classStyles, _class, ngDialog, $http, $route, consts) { $scope.submit = function (_class) { $http.post(consts.apiUrl + '/Classes/update', _class, {params: {where: {id: _class.id}}}) .then(function (response) { noty({type: 'success', text: 'Changes saved '}); $scope.closeThisDialog(); $route.reload(); }, function (err) { if (err.data.error && err.data.error.message) { noty({type: 'error', text: err.data.error.message}); } else { console.error(err); noty({ type: 'error', text: 'An unknown error has ocurred, check browser\'s console for more info' }); } }); }; $scope.classStyles = angular.copy(classStyles); $scope._class = angular.copy(_class); }]) .controller('ClassesNewController', ['$scope', 'classStyles', 'ngDialog', '$http', '$route', 'consts', function ($scope, classStyles, ngDialog, $http, $route, consts) { $scope.submit = function (_class) { _class.dt_create = new Date(); $http.post(consts.apiUrl + '/Classes', _class) .then(function (response) { noty({type: 'success', text: 'Class saved'}); $scope.closeThisDialog(); $route.reload(); }, function (err) { if (err.data.error && err.data.error.message) { noty({type: 'error', text: err.data.error.message}); } else { console.error(err); noty({ type: 'error', text: 'An unknown error has ocurred, check browser\'s console for more info' }); } }); }; $scope._class = {}; $scope.classStyles = classStyles; }]) ; })(angular, noty);
const svgNS = 'http://www.w3.org/2000/svg'; let locationHref = ''; let _useWebWorker = false; const initialDefaultFrame = -999999; const setWebWorker = (flag) => { _useWebWorker = !!flag; }; const getWebWorker = () => _useWebWorker; const setLocationHref = (value) => { locationHref = value; }; const getLocationHref = () => locationHref; function createTag(type) { // return {appendChild:function(){},setAttribute:function(){},style:{}} return document.createElement(type); } function extendPrototype(sources, destination) { var i; var len = sources.length; var sourcePrototype; for (i = 0; i < len; i += 1) { sourcePrototype = sources[i].prototype; for (var attr in sourcePrototype) { if (Object.prototype.hasOwnProperty.call(sourcePrototype, 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; } // import Howl from '../../3rd_party/howler'; const audioControllerFactory = (function () { function AudioController(audioFactory) { this.audios = []; this.audioFactory = audioFactory; this._volume = 1; this._isMuted = false; } AudioController.prototype = { addAudio: function (audio) { this.audios.push(audio); }, pause: function () { var i; var len = this.audios.length; for (i = 0; i < len; i += 1) { this.audios[i].pause(); } }, resume: function () { var i; var len = this.audios.length; for (i = 0; i < len; i += 1) { this.audios[i].resume(); } }, setRate: function (rateValue) { var i; var len = this.audios.length; for (i = 0; i < len; i += 1) { this.audios[i].setRate(rateValue); } }, createAudio: function (assetPath) { if (this.audioFactory) { return this.audioFactory(assetPath); } if (window.Howl) { return new window.Howl({ src: [assetPath], }); } return { isPlaying: false, play: function () { this.isPlaying = true; }, seek: function () { this.isPlaying = false; }, playing: function () {}, rate: function () {}, setVolume: function () {}, }; }, setAudioFactory: function (audioFactory) { this.audioFactory = audioFactory; }, setVolume: function (value) { this._volume = value; this._updateVolume(); }, mute: function () { this._isMuted = true; this._updateVolume(); }, unmute: function () { this._isMuted = false; this._updateVolume(); }, getVolume: function () { return this._volume; }, _updateVolume: function () { var i; var len = this.audios.length; for (i = 0; i < len; i += 1) { this.audios[i].volume(this._volume * (this._isMuted ? 0 : 1)); } }, }; return function () { return new AudioController(); }; }()); const createTypedArray = (function () { function createRegularArray(type, len) { var i = 0; var arr = []; var 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 createTypedArrayFactory(type, len) { if (type === 'float32') { return new Float32Array(len); } if (type === 'int16') { return new Int16Array(len); } if (type === 'uint8c') { return new Uint8ClampedArray(len); } return createRegularArray(type, len); } if (typeof Uint8ClampedArray === 'function' && typeof Float32Array === 'function') { return createTypedArrayFactory; } return createRegularArray; }()); function createSizedArray(len) { return Array.apply(null, { length: len }); } let subframeEnabled = true; let expressionsPlugin = null; let idPrefix = ''; const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); let _shouldRoundValues = false; const bmPow = Math.pow; const bmSqrt = Math.sqrt; const bmFloor = Math.floor; const bmMax = Math.max; const bmMin = Math.min; const BMMath = {}; (function () { var propertyNames = ['abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'atan2', 'ceil', 'cbrt', 'expm1', 'clz32', 'cos', 'cosh', 'exp', 'floor', 'fround', 'hypot', 'imul', 'log', 'log1p', 'log2', 'log10', 'max', 'min', 'pow', 'random', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc', 'E', 'LN10', 'LN2', 'LOG10E', 'LOG2E', 'PI', 'SQRT1_2', 'SQRT2']; var i; var len = propertyNames.length; for (i = 0; i < len; i += 1) { BMMath[propertyNames[i]] = Math[propertyNames[i]]; } }()); function ProjectInterface$1() { 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; var len = val.length; for (i = 0; i < len; i += 1) { absArr[i] = Math.abs(val[i]); } return absArr; } return Math.abs(val); }; let defaultCurveSegments = 150; const degToRads = Math.PI / 180; const roundCorner = 0.5519; function roundValues(flag) { _shouldRoundValues = !!flag; } function bmRnd(value) { if (_shouldRoundValues) { return Math.round(value); } return value; } function styleDiv(element) { element.style.position = 'absolute'; element.style.top = 0; element.style.left = 0; element.style.display = 'block'; element.style.transformOrigin = '0 0'; element.style.webkitTransformOrigin = '0 0'; element.style.backfaceVisibility = 'visible'; element.style.webkitBackfaceVisibility = 'visible'; element.style.transformStyle = 'preserve-3d'; element.style.webkitTransformStyle = 'preserve-3d'; element.style.mozTransformStyle = 'preserve-3d'; } function BMEnterFrameEvent(type, currentTime, totalTime, frameMultiplier) { this.type = type; this.currentTime = currentTime; this.totalTime = totalTime; this.direction = frameMultiplier < 0 ? -1 : 1; } function BMCompleteEvent(type, frameMultiplier) { this.type = type; this.direction = frameMultiplier < 0 ? -1 : 1; } function BMCompleteLoopEvent(type, totalLoops, currentLoop, frameMultiplier) { this.type = type; this.currentLoop = currentLoop; this.totalLoops = totalLoops; this.direction = frameMultiplier < 0 ? -1 : 1; } function BMSegmentStartEvent(type, firstFrame, totalFrames) { this.type = type; this.firstFrame = firstFrame; this.totalFrames = totalFrames; } function BMDestroyEvent(type, target) { this.type = type; this.target = target; } function BMRenderFrameErrorEvent(nativeError, currentTime) { this.type = 'renderFrameError'; this.nativeError = nativeError; this.currentTime = currentTime; } function BMConfigErrorEvent(nativeError) { this.type = 'configError'; this.nativeError = nativeError; } function BMAnimationConfigErrorEvent(type, nativeError) { this.type = type; this.nativeError = nativeError; } const createElementID = (function () { var _count = 0; return function createID() { _count += 1; return idPrefix + '__lottie_element_' + _count; }; }()); function HSVtoRGB(h, s, v) { var r; var g; var b; var i; var f; var p; var q; var 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; default: break; } return [r, g, b]; } function RGBtoHSV(r, g, b) { var max = Math.max(r, g, b); var min = Math.min(r, g, b); var d = max - min; var h; var s = (max === 0 ? 0 : d / max); var 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; default: 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]); } const 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]; }; }()); const setSubframeEnabled = (flag) => { subframeEnabled = !!flag; }; const getSubframeEnabled = () => subframeEnabled; const setExpressionsPlugin = (value) => { expressionsPlugin = value; }; const getExpressionsPlugin = () => expressionsPlugin; const setDefaultCurveSegments = (value) => { defaultCurveSegments = value; }; const getDefaultCurveSegments = () => defaultCurveSegments; const setIdPrefix = (value) => { idPrefix = value; }; const getIdPrefix = () => idPrefix; function createNS(type) { // return {appendChild:function(){},setAttribute:function(){},style:{}} return document.createElementNS(svgNS, type); } const dataManager = (function () { var _counterId = 1; var processes = []; var workerFn; var workerInstance; var workerProxy = { onmessage: function () { }, postMessage: function (path) { workerFn({ data: path, }); }, }; var _workerSelf = { postMessage: function (data) { workerProxy.onmessage({ data: data, }); }, }; function createWorker(fn) { if (window.Worker && window.Blob && getWebWorker()) { var blob = new Blob(['var _workerSelf = self; self.onmessage = ', fn.toString()], { type: 'text/javascript' }); // var blob = new Blob(['self.onmessage = ', fn.toString()], { type: 'text/javascript' }); var url = URL.createObjectURL(blob); return new Worker(url); } workerFn = fn; return workerProxy; } function setupWorker() { if (!workerInstance) { workerInstance = createWorker(function workerStart(e) { function dataFunctionManager() { function completeLayers(layers, comps) { var layerData; var i; var len = layers.length; var j; var jLen; var k; var kLen; for (i = 0; i < len; i += 1) { layerData = layers[i]; if (('ks' in layerData) && !layerData.completed) { layerData.completed = true; if (layerData.tt) { layers[i - 1].td = layerData.tt; } 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); } else if (layerData.ty === 4) { completeShapes(layerData.shapes); } else if (layerData.ty === 5) { completeText(layerData); } } } } function completeChars(chars, assets) { if (chars) { var i = 0; var len = chars.length; for (i = 0; i < len; i += 1) { if (chars[i].t === 1) { // var compData = findComp(chars[i].data.refId, assets); chars[i].data.layers = findCompLayers(chars[i].data.refId, assets); // chars[i].data.ip = 0; // chars[i].data.op = 99999; // chars[i].data.st = 0; // chars[i].data.sr = 1; // chars[i].w = compData.w; // chars[i].data.ks = { // a: { k: [0, 0, 0], a: 0 }, // p: { k: [0, -compData.h, 0], a: 0 }, // r: { k: 0, a: 0 }, // s: { k: [100, 100], a: 0 }, // o: { k: 100, a: 0 }, // }; completeLayers(chars[i].data.layers, assets); } } } } function findComp(id, comps) { var i = 0; var len = comps.length; while (i < len) { if (comps[i].id === id) { return comps[i]; } i += 1; } return null; } function findCompLayers(id, comps) { var comp = findComp(id, comps); if (comp) { if (!comp.layers.__used) { comp.layers.__used = true; return comp.layers; } return JSON.parse(JSON.stringify(comp.layers)); } return null; } function completeShapes(arr) { var i; var len = arr.length; var j; var jLen; 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]); } } } } else if (arr[i].ty === 'gr') { completeShapes(arr[i].it); } } } function convertPathsToAbsoluteValues(path) { var i; var 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; } if (animVersion[0] > minimum[0]) { return false; } if (minimum[1] > animVersion[1]) { return true; } if (animVersion[1] > minimum[1]) { return false; } if (minimum[2] > animVersion[2]) { return true; } if (animVersion[2] > minimum[2]) { return false; } return null; } 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; var 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; var 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; var len = animationData.chars.length; for (i = 0; i < len; i += 1) { var charData = animationData.chars[i]; if (charData.data && charData.data.shapes) { completeShapes(charData.data.shapes); charData.data.ip = 0; charData.data.op = 99999; charData.data.st = 0; charData.data.sr = 1; charData.data.ks = { p: { k: [0, 0], a: 0 }, s: { k: [100, 100], a: 0 }, a: { k: [0, 0], a: 0 }, r: { k: 0, a: 0 }, o: { k: 100, a: 0 }, }; if (!animationData.chars[i].t) { charData.data.shapes.push( { ty: 'no', } ); charData.data.shapes[0].it.push( { p: { k: [0, 0], a: 0 }, s: { k: [100, 100], a: 0 }, a: { k: [0, 0], a: 0 }, r: { k: 0, a: 0 }, o: { k: 100, a: 0 }, sk: { k: 0, a: 0 }, sa: { k: 0, a: 0 }, ty: 'tr', } ); } } } } }; }()); var checkPathProperties = (function () { var minimumVersion = [5, 7, 15]; function updateTextLayer(textLayer) { var pathData = textLayer.t.p; if (typeof pathData.a === 'number') { pathData.a = { a: 0, k: pathData.a, }; } if (typeof pathData.p === 'number') { pathData.p = { a: 0, k: pathData.p, }; } if (typeof pathData.r === 'number') { pathData.r = { a: 0, k: pathData.r, }; } } function iterateLayers(layers) { var i; var 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; var len = animationData.assets.length; for (i = 0; i < len; i += 1) { if (animationData.assets[i].layers) { iterateLayers(animationData.assets[i].layers); } } } } }; }()); var checkColors = (function () { var minimumVersion = [4, 1, 9]; function iterateShapes(shapes) { var i; var len = shapes.length; var j; var 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; var 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; var 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 completeClosingShapes(arr) { var i; var len = arr.length; var j; var jLen; 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; } } } } else if (arr[i].ty === 'gr') { completeClosingShapes(arr[i].it); } } } function iterateLayers(layers) { var layerData; var i; var len = layers.length; var j; var jLen; var k; var 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) { completeClosingShapes(layerData.shapes); } } } return function (animationData) { if (checkVersion(minimumVersion, animationData.v)) { iterateLayers(animationData.layers); if (animationData.assets) { var i; var len = animationData.assets.length; for (i = 0; i < len; i += 1) { if (animationData.assets[i].layers) { iterateLayers(animationData.assets[i].layers); } } } } }; }()); function completeData(animationData) { if (animationData.__complete) { return; } checkColors(animationData); checkText(animationData); checkChars(animationData); checkPathProperties(animationData); checkShapes(animationData); completeLayers(animationData.layers, animationData.assets); completeChars(animationData.chars, animationData.assets); animationData.__complete = true; } function completeText(data) { if (data.t.a.length === 0 && !('m' in data.t.p)) { // data.singleShape = true; } } var moduleOb = {}; moduleOb.completeData = completeData; moduleOb.checkColors = checkColors; moduleOb.checkChars = checkChars; moduleOb.checkPathProperties = checkPathProperties; moduleOb.checkShapes = checkShapes; moduleOb.completeLayers = completeLayers; return moduleOb; } if (!_workerSelf.dataManager) { _workerSelf.dataManager = dataFunctionManager(); } if (!_workerSelf.assetLoader) { _workerSelf.assetLoader = (function () { function formatResponse(xhr) { // using typeof doubles the time of execution of this method, // so if available, it's better to use the header to validate the type var contentTypeHeader = xhr.getResponseHeader('content-type'); if (contentTypeHeader && xhr.responseType === 'json' && contentTypeHeader.indexOf('json') !== -1) { return xhr.response; } if (xhr.response && typeof xhr.response === 'object') { return xhr.response; } if (xhr.response && typeof xhr.response === 'string') { return JSON.parse(xhr.response); } if (xhr.responseText) { return JSON.parse(xhr.responseText); } return null; } function loadAsset(path, fullPath, callback, errorCallback) { var response; var xhr = new XMLHttpRequest(); // set responseType after calling open or IE will break. try { // This crashes on Android WebView prior to KitKat xhr.responseType = 'json'; } catch (err) {} // eslint-disable-line no-empty xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { response = formatResponse(xhr); callback(response); } else { try { response = formatResponse(xhr); callback(response); } catch (err) { if (errorCallback) { errorCallback(err); } } } } }; try { xhr.open('GET', path, true); } catch (error) { xhr.open('GET', fullPath + '/' + path, true); } xhr.send(); } return { load: loadAsset, }; }()); } if (e.data.type === 'loadAnimation') { _workerSelf.assetLoader.load( e.data.path, e.data.fullPath, function (data) { _workerSelf.dataManager.completeData(data); _workerSelf.postMessage({ id: e.data.id, payload: data, status: 'success', }); }, function () { _workerSelf.postMessage({ id: e.data.id, status: 'error', }); } ); } else if (e.data.type === 'complete') { var animation = e.data.animation; _workerSelf.dataManager.completeData(animation); _workerSelf.postMessage({ id: e.data.id, payload: animation, status: 'success', }); } else if (e.data.type === 'loadData') { _workerSelf.assetLoader.load( e.data.path, e.data.fullPath, function (data) { _workerSelf.postMessage({ id: e.data.id, payload: data, status: 'success', }); }, function () { _workerSelf.postMessage({ id: e.data.id, status: 'error', }); } ); } }); workerInstance.onmessage = function (event) { var data = event.data; var id = data.id; var process = processes[id]; processes[id] = null; if (data.status === 'success') { process.onComplete(data.payload); } else if (process.onError) { process.onError(); } }; } } function createProcess(onComplete, onError) { _counterId += 1; var id = 'processId_' + _counterId; processes[id] = { onComplete: onComplete, onError: onError, }; return id; } function loadAnimation(path, onComplete, onError) { setupWorker(); var processId = createProcess(onComplete, onError); workerInstance.postMessage({ type: 'loadAnimation', path: path, fullPath: window.location.origin + window.location.pathname, id: processId, }); } function loadData(path, onComplete, onError) { setupWorker(); var processId = createProcess(onComplete, onError); workerInstance.postMessage({ type: 'loadData', path: path, fullPath: window.location.origin + window.location.pathname, id: processId, }); } function completeAnimation(anim, onComplete, onError) { setupWorker(); var processId = createProcess(onComplete, onError); workerInstance.postMessage({ type: 'complete', animation: anim, id: processId, }); } return { loadAnimation: loadAnimation, loadData: loadData, completeAnimation: completeAnimation, }; }()); const ImagePreloader = (function () { var proxyImage = (function () { var canvas = createTag('canvas'); canvas.width = 1; canvas.height = 1; var ctx = canvas.getContext('2d'); ctx.fillStyle = 'rgba(0,0,0,0)'; ctx.fillRect(0, 0, 1, 1); return canvas; }()); function imageLoaded() { this.loadedAssets += 1; if (this.loadedAssets === this.totalImages && this.loadedFootagesCount === this.totalFootages) { if (this.imagesLoadedCb) { this.imagesLoadedCb(null); } } } function footageLoaded() { this.loadedFootagesCount += 1; if (this.loadedAssets === this.totalImages && this.loadedFootagesCount === this.totalFootages) { if (this.imagesLoadedCb) { this.imagesLoadedCb(null); } } } function getAssetsPath(assetData, assetsPath, originalPath) { var path = ''; if (assetData.e) { path = assetData.p; } else if (assetsPath) { var imagePath = assetData.p; if (imagePath.indexOf('images/') !== -1) { imagePath = imagePath.split('/')[1]; } path = assetsPath + imagePath; } else { path = originalPath; path += assetData.u ? assetData.u : ''; path += assetData.p; } return path; } function testImageLoaded(img) { var _count = 0; var intervalId = setInterval(function () { var box = img.getBBox(); if (box.width || _count > 500) { this._imageLoaded(); clearInterval(intervalId); } _count += 1; }.bind(this), 50); } function createImageData(assetData) { var path = getAssetsPath(assetData, this.assetsPath, this.path); var img = createNS('image'); if (isSafari) { this.testImageLoaded(img); } else { img.addEventListener('load', this._imageLoaded, false); } img.addEventListener('error', function () { ob.img = proxyImage; this._imageLoaded(); }.bind(this), false); img.setAttributeNS('http://www.w3.org/1999/xlink', 'href', path); if (this._elementHelper.append) { this._elementHelper.append(img); } else { this._elementHelper.appendChild(img); } var ob = { img: img, assetData: assetData, }; return ob; } function createImgData(assetData) { var path = getAssetsPath(assetData, this.assetsPath, this.path); var img = createTag('img'); img.crossOrigin = 'anonymous'; img.addEventListener('load', this._imageLoaded, false); img.addEventListener('error', function () { ob.img = proxyImage; this._imageLoaded(); }.bind(this), false); img.src = path; var ob = { img: img, assetData: assetData, }; return ob; } function createFootageData(data) { var ob = { assetData: data, }; var path = getAssetsPath(data, this.assetsPath, this.path); dataManager.loadData(path, function (footageData) { ob.img = footageData; this._footageLoaded(); }.bind(this), function () { ob.img = {}; this._footageLoaded(); }.bind(this)); return ob; } function loadAssets(assets, cb) { this.imagesLoadedCb = cb; var i; var len = assets.length; for (i = 0; i < len; i += 1) { if (!assets[i].layers) { if (!assets[i].t || assets[i].t === 'seq') { this.totalImages += 1; this.images.push(this._createImageData(assets[i])); } else if (assets[i].t === 3) { this.totalFootages += 1; this.images.push(this.createFootageData(assets[i])); } } } } function setPath(path) { this.path = path || ''; } function setAssetsPath(path) { this.assetsPath = path || ''; } function getAsset(assetData) { var i = 0; var len = this.images.length; while (i < len) { if (this.images[i].assetData === assetData) { return this.images[i].img; } i += 1; } return null; } function destroy() { this.imagesLoadedCb = null; this.images.length = 0; } function loadedImages() { return this.totalImages === this.loadedAssets; } function loadedFootages() { return this.totalFootages === this.loadedFootagesCount; } function setCacheType(type, elementHelper) { if (type === 'svg') { this._elementHelper = elementHelper; this._createImageData = this.createImageData.bind(this); } else { this._createImageData = this.createImgData.bind(this); } } function ImagePreloaderFactory() { this._imageLoaded = imageLoaded.bind(this); this._footageLoaded = footageLoaded.bind(this); this.testImageLoaded = testImageLoaded.bind(this); this.createFootageData = createFootageData.bind(this); this.assetsPath = ''; this.path = ''; this.totalImages = 0; this.totalFootages = 0; this.loadedAssets = 0; this.loadedFootagesCount = 0; this.imagesLoadedCb = null; this.images = []; } ImagePreloaderFactory.prototype = { loadAssets: loadAssets, setAssetsPath: setAssetsPath, setPath: setPath, loadedImages: loadedImages, loadedFootages: loadedFootages, destroy: destroy, getAsset: getAsset, createImgData: createImgData, createImageData: createImageData, imageLoaded: imageLoaded, footageLoaded: footageLoaded, setCacheType: setCacheType, }; return ImagePreloaderFactory; }()); function BaseEvent() {} BaseEvent.prototype = { triggerEvent: function (eventName, args) { if (this._cbs[eventName]) { var callbacks = this._cbs[eventName]; for (var i = 0; i < callbacks.length; i += 1) { callbacks[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; var 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; } } }, }; const markerParser = ( function () { function parsePayloadLines(payload) { var lines = payload.split('\r\n'); var keys = {}; var line; var keysCount = 0; for (var i = 0; i < lines.length; i += 1) { line = lines[i].split(':'); if (line.length === 2) { keys[line[0]] = line[1].trim(); keysCount += 1; } } if (keysCount === 0) { throw new Error(); } return keys; } return function (_markers) { var markers = []; for (var i = 0; i < _markers.length; i += 1) { var _marker = _markers[i]; var markerData = { time: _marker.tm, duration: _marker.dr, }; try { markerData.payload = JSON.parse(_markers[i].cm); } catch (_) { try { markerData.payload = parsePayloadLines(_markers[i].cm); } catch (__) { markerData.payload = { name: _markers[i], }; } } markers.push(markerData); } return markers; }; }()); const ProjectInterface = (function () { function registerComposition(comp) { this.compositions.push(comp); } return function () { function _thisProjectFunction(name) { var i = 0; var 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].data.xt) { this.compositions[i].prepareFrame(this.currentFrame); } return this.compositions[i].compInterface; } i += 1; } return null; } _thisProjectFunction.compositions = []; _thisProjectFunction.currentFrame = 0; _thisProjectFunction.registerComposition = registerComposition; return _thisProjectFunction; }; }()); const renderers = {}; const registerRenderer = (key, value) => { renderers[key] = value; }; function getRenderer(key) { return renderers[key]; } const AnimationItem = function () { this._cbs = []; this.name = ''; this.path = ''; this.isLoaded = false; this.currentFrame = 0; this.currentRawFrame = 0; this.firstFrame = 0; this.totalFrames = 0; this.frameRate = 0; this.frameMult = 0; this.playSpeed = 1; this.playDirection = 1; this.playCount = 0; this.animationData = {}; this.assets = []; this.isPaused = true; this.autoplay = false; this.loop = true; this.renderer = null; this.animationID = createElementID(); this.assetsPath = ''; this.timeCompleted = 0; this.segmentPos = 0; this.isSubframeEnabled = getSubframeEnabled(); this.segments = []; this._idle = true; this._completedLoop = false; this.projectInterface = ProjectInterface(); this.imagePreloader = new ImagePreloader(); this.audioController = audioControllerFactory(); this.markers = []; this.configAnimation = this.configAnimation.bind(this); this.onSetupError = this.onSetupError.bind(this); this.onSegmentComplete = this.onSegmentComplete.bind(this); }; extendPrototype([BaseEvent], AnimationItem); AnimationItem.prototype.setParams = function (params) { if (params.wrapper || params.container) { this.wrapper = params.wrapper || params.container; } var animType = 'svg'; if (params.animType) { animType = params.animType; } else if (params.renderer) { animType = params.renderer; } const RendererClass = getRenderer(animType); this.renderer = new RendererClass(this, params.rendererSettings); this.imagePreloader.setCacheType(animType, this.renderer.globalData.defs); this.renderer.setProjectInterface(this.projectInterface); this.animType = animType; if (params.loop === '' || params.loop === null || params.loop === undefined || params.loop === true) { this.loop = true; } else if (params.loop === false) { this.loop = false; } else { this.loop = parseInt(params.loop, 10); } this.autoplay = 'autoplay' in params ? params.autoplay : true; this.name = params.name ? params.name : ''; this.autoloadSegments = Object.prototype.hasOwnProperty.call(params, 'autoloadSegments') ? params.autoloadSegments : true; this.assetsPath = params.assetsPath; this.initialSegment = params.initialSegment; if (params.audioFactory) { this.audioController.setAudioFactory(params.audioFactory); } if (params.animationData) { this.setupAnimation(params.animationData); } else if (params.path) { 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')); dataManager.loadAnimation( params.path, this.configAnimation, this.onSetupError ); } }; AnimationItem.prototype.onSetupError = function () { this.trigger('data_failed'); }; AnimationItem.prototype.setupAnimation = function (data) { dataManager.completeAnimation( data, this.configAnimation ); }; AnimationItem.prototype.setData = function (wrapper, animationData) { if (animationData) { if (typeof animationData !== 'object') { animationData = JSON.parse(animationData); } } var params = { wrapper: wrapper, animationData: animationData, }; var wrapperAttributes = wrapper.attributes; params.path = wrapperAttributes.getNamedItem('data-animation-path') // eslint-disable-line no-nested-ternary ? wrapperAttributes.getNamedItem('data-animation-path').value : wrapperAttributes.getNamedItem('data-bm-path') // eslint-disable-line no-nested-ternary ? wrapperAttributes.getNamedItem('data-bm-path').value : wrapperAttributes.getNamedItem('bm-path') ? wrapperAttributes.getNamedItem('bm-path').value : ''; params.animType = wrapperAttributes.getNamedItem('data-anim-type') // eslint-disable-line no-nested-ternary ? wrapperAttributes.getNamedItem('data-anim-type').value : wrapperAttributes.getNamedItem('data-bm-type') // eslint-disable-line no-nested-ternary ? wrapperAttributes.getNamedItem('data-bm-type').value : wrapperAttributes.getNamedItem('bm-type') // eslint-disable-line no-nested-ternary ? wrapperAttributes.getNamedItem('bm-type').value : wrapperAttributes.getNamedItem('data-bm-renderer') // eslint-disable-line no-nested-ternary ? wrapperAttributes.getNamedItem('data-bm-renderer').value : wrapperAttributes.getNamedItem('bm-renderer') ? wrapperAttributes.getNamedItem('bm-renderer').value : 'canvas'; var loop = wrapperAttributes.getNamedItem('data-anim-loop') // eslint-disable-line no-nested-ternary ? wrapperAttributes.getNamedItem('data-anim-loop').value : wrapperAttributes.getNamedItem('data-bm-loop') // eslint-disable-line no-nested-ternary ? wrapperAttributes.getNamedItem('data-bm-loop').value : wrapperAttributes.getNamedItem('bm-loop') ? wrapperAttributes.getNamedItem('bm-loop').value : ''; if (loop === 'false') { params.loop = false; } else if (loop === 'true') { params.loop = true; } else if (loop !== '') { params.loop = parseInt(loop, 10); } var autoplay = wrapperAttributes.getNamedItem('data-anim-autoplay') // eslint-disable-line no-nested-ternary ? wrapperAttributes.getNamedItem('data-anim-autoplay').value : wrapperAttributes.getNamedItem('data-bm-autoplay') // eslint-disable-line no-nested-ternary ? 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') // eslint-disable-line no-nested-ternary ? wrapperAttributes.getNamedItem('data-name').value : wrapperAttributes.getNamedItem('data-bm-name') // eslint-disable-line no-nested-ternary ? wrapperAttributes.getNamedItem('data-bm-name').value : wrapperAttributes.getNamedItem('bm-name') ? wrapperAttributes.getNamedItem('bm-name').value : ''; var prerender = wrapperAttributes.getNamedItem('data-anim-prerender') // eslint-disable-line no-nested-ternary ? wrapperAttributes.getNamedItem('data-anim-prerender').value : wrapperAttributes.getNamedItem('data-bm-prerender') // eslint-disable-line no-nested-ternary ? 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); } var layers = this.animationData.layers; var i; var len = layers.length; var newLayers = data.layers; var j; var 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.animationData.__complete = false; dataManager.completeAnimation( this.animationData, this.onSegmentComplete ); }; AnimationItem.prototype.onSegmentComplete = function (data) { this.animationData = data; var expressionsPlugin = getExpressionsPlugin(); if (expressionsPlugin) { expressionsPlugin.initExpressions(this); } 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.totalFrames; return; } var segment = segments.shift(); this.timeCompleted = segment.time * this.frameRate; var segmentPath = this.path + this.fileName + '_' + this.segmentPos + '.json'; this.segmentPos += 1; dataManager.loadData(segmentPath, this.includeLayers.bind(this), function () { this.trigger('data_failed'); }.bind(this)); }; AnimationItem.prototype.loadSegments = function () { var segments = this.animationData.segments; if (!segments) { this.timeCompleted = this.totalFrames; } this.loadNextSegment(); }; AnimationItem.prototype.imagesLoaded = function () { this.trigger('loaded_images'); this.checkLoaded(); }; AnimationItem.prototype.preloadImages = function () { this.imagePreloader.setAssetsPath(this.assetsPath); this.imagePreloader.setPath(this.path); this.imagePreloader.loadAssets(this.animationData.assets, this.imagesLoaded.bind(this)); }; AnimationItem.prototype.configAnimation = function (animData) { if (!this.renderer) { return; } try { this.animationData = animData; if (this.initialSegment) { this.totalFrames = Math.floor(this.initialSegment[1] - this.initialSegment[0]); this.firstFrame = Math.round(this.initialSegment[0]); } else { this.totalFrames = Math.floor(this.animationData.op - this.animationData.ip); this.firstFrame = Math.round(this.animationData.ip); } this.renderer.configAnimation(animData); if (!animData.assets) { animData.assets = []; } this.assets = this.animationData.assets; this.frameRate = this.animationData.fr; this.frameMult = this.animationData.fr / 1000; this.renderer.searchExtraCompositions(animData.assets); this.markers = markerParser(animData.markers || []); this.trigger('config_ready'); this.preloadImages(); this.loadSegments(); this.updaFrameModifier(); this.waitForFontsLoaded(); if (this.isPaused) { this.audioController.pause(); } } catch (error) { this.triggerConfigError(error); } }; AnimationItem.prototype.waitForFontsLoaded = function () { if (!this.renderer) { return; } if (this.renderer.globalData.fontManager.isLoaded) { this.checkLoaded(); } else { setTimeout(this.waitForFontsLoaded.bind(this), 20); } }; AnimationItem.prototype.checkLoaded = function () { if (!this.isLoaded && this.renderer.globalData.fontManager.isLoaded && (this.imagePreloader.loadedImages() || this.renderer.rendererType !== 'canvas') && (this.imagePreloader.loadedFootages()) ) { this.isLoaded = true; var expressionsPlugin = getExpressionsPlugin(); if (expressionsPlugin) { expressionsPlugin.initExpressions(this); } this.renderer.initItems(); setTimeout(function () { this.trigger('DOMLoaded'); }.bind(this), 0); this.gotoFrame(); if (this.autoplay) { this.play(); } } }; AnimationItem.prototype.resize = function () { this.renderer.updateContainerSize(); }; AnimationItem.prototype.setSubframe = function (flag) { this.isSubframeEnabled = !!flag; }; AnimationItem.prototype.gotoFrame = function () { this.currentFrame = this.isSubframeEnabled ? this.currentRawFrame : ~~this.currentRawFrame; // eslint-disable-line no-bitwise if (this.timeCompleted !== this.totalFrames && this.currentFrame > this.timeCompleted) { this.currentFrame = this.timeCompleted; } this.trigger('enterFrame'); this.renderFrame(); this.trigger('drawnFrame'); }; AnimationItem.prototype.renderFrame = function () { if (this.isLoaded === false || !this.renderer) { return; } try { this.renderer.renderFrame(this.currentFrame + this.firstFrame); } catch (error) { this.triggerRenderFrameError(error); } }; AnimationItem.prototype.play = function (name) { if (name && this.name !== name) { return; } if (this.isPaused === true) { this.isPaused = false; this.audioController.resume(); 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'); this.audioController.pause(); } }; 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._completedLoop = false; this.setCurrentRawFrameValue(0); }; AnimationItem.prototype.getMarkerData = function (markerName) { var marker; for (var i = 0; i < this.markers.length; i += 1) { marker = this.markers[i]; if (marker.payload && marker.payload.name === markerName) { return marker; } } return null; }; AnimationItem.prototype.goToAndStop = function (value, isFrame, name) { if (name && this.name !== name) { return; } var numValue = Number(value); if (isNaN(numValue)) { var marker = this.getMarkerData(value); if (marker) { this.goToAndStop(marker.time, true); } } else if (isFrame) { this.setCurrentRawFrameValue(value); } else { this.setCurrentRawFrameValue(value * this.frameModifier); } this.pause(); }; AnimationItem.prototype.goToAndPlay = function (value, isFrame, name) { if (name && this.name !== name) { return; } var numValue = Number(value); if (isNaN(numValue)) { var marker = this.getMarkerData(value); if (marker) { if (!marker.duration) { this.goToAndStop(marker.time, true); } else { this.playSegments([marker.time, marker.time + marker.duration], true); } } } else { this.goToAndStop(numValue, 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 ? nextValue % this.totalFrames : 0)) { _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._completedLoop = true; 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)) { // eslint-disable-line no-plusplus this.setCurrentRawFrameValue(this.totalFrames + (nextValue % this.totalFrames)); if (!this._completedLoop) { this._completedLoop = true; } else { 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.totalFrames = arr[0] - arr[1]; this.timeCompleted = this.totalFrames; 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.totalFrames = arr[1] - arr[0]; this.timeCompleted = this.totalFrames; 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.totalFrames = end - init; this.timeCompleted = this.totalFrames; if (pendingFrame !== -1) { this.goToAndStop(pendingFrame, true); } }; AnimationItem.prototype.playSegments = function (arr, forceFlag) { if (forceFlag) { this.segments.length = 0; } if (typeof arr[0] === 'object') { var i; var len = arr.length; for (i = 0; i < len; i += 1) { this.segments.push(arr[i]); } } else { this.segments.push(arr); } if (this.segments.length && forceFlag) { this.adjustSegment(this.segments.shift(), 0); } if (this.isPaused) { this.play(); } }; AnimationItem.prototype.resetSegments = function (forceFlag) { this.segments.length = 0; this.segments.push([this.animationData.ip, this.animationData.op]); 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.destroy = function (name) { if ((name && this.name !== name) || !this.renderer) { return; } this.renderer.destroy(); this.imagePreloader.destroy(); this.trigger('destroy'); this._cbs = null; this.onEnterFrame = null; this.onLoopComplete = null; this.onComplete = null; this.onSegmentStart = null; this.onDestroy = null; this.renderer = null; this.renderer = null; this.imagePreloader = null; this.projectInterface = 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.setVolume = function (val, name) { if (name && this.name !== name) { return; } this.audioController.setVolume(val); }; AnimationItem.prototype.getVolume = function () { return this.audioController.getVolume(); }; AnimationItem.prototype.mute = function (name) { if (name && this.name !== name) { return; } this.audioController.mute(); }; AnimationItem.prototype.unmute = function (name) { if (name && this.name !== name) { return; } this.audioController.unmute(); }; AnimationItem.prototype.updaFrameModifier = function () { this.frameModifier = this.frameMult * this.playSpeed * this.playDirection; this.audioController.setRate(this.playSpeed * this.playDirection); }; AnimationItem.prototype.getPath = function () { return this.path; }; AnimationItem.prototype.getAssetsPath = function (assetData) { var path = ''; if (assetData.e) { path = assetData.p; } else 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; var len = this.assets.length; while (i < len) { if (id === this.assets[i].id) { return this.assets[i]; } i += 1; } return null; }; AnimationItem.prototype.hide = function () { this.renderer.hide(); }; AnimationItem.prototype.show = function () { this.renderer.show(); }; 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': case 'drawnFrame': this.triggerEvent(name, new BMEnterFrameEvent(name, this.currentFrame, this.totalFrames, this.frameModifier)); 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)); } }; AnimationItem.prototype.triggerRenderFrameError = function (nativeError) { var error = new BMRenderFrameErrorEvent(nativeError, this.currentFrame); this.triggerEvent('error', error); if (this.onError) { this.onError.call(this, error); } }; AnimationItem.prototype.triggerConfigError = function (nativeError) { var error = new BMConfigErrorEvent(nativeError, this.currentFrame); this.triggerEvent('error', error); if (this.onError) { this.onError.call(this, error); } }; const animationManager = (function () { var moduleOb = {}; var registeredAnimations = []; var initTime = 0; var len = 0; var playingAnimationsNum = 0; var _stopped = true; var _isFrozen = false; 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 getRegisteredAnimations() { var i; var lenAnims = registeredAnimations.length; var animations = []; for (i = 0; i < lenAnims; i += 1) { animations.push(registeredAnimations[i].animation); } return animations; } function addPlayingCount() { playingAnimationsNum += 1; activate(); } function subtractPlayingCount() { playingAnimationsNum -= 1; } 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 (playingAnimationsNum && !_isFrozen) { 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; var lenAnims = animElements.length; for (i = 0; i < lenAnims; i += 1) { if (renderer) { animElements[i].setAttribute('data-bm-type', renderer); } registerAnimation(animElements[i], animationData); } if (standalone && lenAnims === 0) { if (!renderer) { renderer = 'svg'; } var body = document.getElementsByTagName('body')[0]; body.innerText = ''; 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 activate() { if (!_isFrozen && playingAnimationsNum) { if (_stopped) { window.requestAnimationFrame(first); _stopped = false; } } } function freeze() { _isFrozen = true; } function unfreeze() { _isFrozen = false; activate(); } function setVolume(val, animation) { var i; for (i = 0; i < len; i += 1) { registeredAnimations[i].animation.setVolume(val, animation); } } function mute(animation) { var i; for (i = 0; i < len; i += 1) { registeredAnimations[i].animation.mute(animation); } } function unmute(animation) { var i; for (i = 0; i < len; i += 1) { registeredAnimations[i].animation.unmute(animation); } } 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; moduleOb.freeze = freeze; moduleOb.unfreeze = unfreeze; moduleOb.setVolume = setVolume; moduleOb.mute = mute; moduleOb.unmute = unmute; moduleOb.getRegisteredAnimations = getRegisteredAnimations; return moduleOb; }()); /* eslint-disable */ const 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); } if (initialSlope === 0.0) { return guessForT; } return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2); }, }; return ob; }()); const pooling = (function () { function double(arr) { return arr.concat(createSizedArray(arr.length)); } return { double: double, }; }()); const poolFactory = (function () { return function (initialLength, _create, _release) { 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 *= 2; } if (_release) { _release(element); } pool[_length] = element; _length += 1; } return ob; }; }()); const bezierLengthPool = (function () { function create() { return { addedLength: 0, percents: createTypedArray('float32', getDefaultCurveSegments()), lengths: createTypedArray('float32', getDefaultCurveSegments()), }; } return poolFactory(8, create); }()); const segmentsLengthPool = (function () { function create() { return { lengths: [], totalLength: 0, }; } function release(element) { var i; var len = element.lengths.length; for (i = 0; i < len; i += 1) { bezierLengthPool.release(element.lengths[i]); } element.lengths.length = 0; } return poolFactory(8, create, release); }()); function bezFunction() { 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 = getDefaultCurveSegments(); var k; var i; var len; var ptCoord; var perc; var addedLength = 0; var ptDistance; var point = []; var lastPoint = []; var lengthData = bezierLengthPool.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 = bmPow(1 - perc, 3) * pt1[i] + 3 * bmPow(1 - perc, 2) * perc * pt3[i] + 3 * (1 - perc) * bmPow(perc, 2) * pt4[i] + bmPow(perc, 3) * pt2[i]; point[i] = ptCoord; if (lastPoint[i] !== null) { ptDistance += bmPow(point[i] - lastPoint[i], 2); } lastPoint[i] = point[i]; } if (ptDistance) { ptDistance = bmSqrt(ptDistance); addedLength += ptDistance; } lengthData.percents[k] = perc; lengthData.lengths[k] = addedLength; } lengthData.addedLength = addedLength; return lengthData; }; }()); function getSegmentsLength(shapeData) { var segmentsLength = segmentsLengthPool.newElement(); var closed = shapeData.c; var pathV = shapeData.v; var pathO = shapeData.o; var pathI = shapeData.i; var i; var 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 && len) { 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 (pt1, pt2, pt3, pt4) { var bezierName = (pt1[0] + '_' + pt1[1] + '_' + pt2[0] + '_' + pt2[1] + '_' + pt3[0] + '_' + pt3[1] + '_' + pt4[0] + '_' + pt4[1]).replace(/\./g, 'p'); if (!storedData[bezierName]) { var curveSegments = getDefaultCurveSegments(); var k; var i; var len; var ptCoord; var perc; var addedLength = 0; var ptDistance; var point; var 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 = bmPow(1 - perc, 3) * pt1[i] + 3 * bmPow(1 - perc, 2) * perc * (pt1[i] + pt3[i]) + 3 * (1 - perc) * bmPow(perc, 2) * (pt2[i] + pt4[i]) + bmPow(perc, 3) * pt2[i]; point[i] = ptCoord; if (lastPoint !== null) { ptDistance += bmPow(point[i] - lastPoint[i], 2); } } ptDistance = bmSqrt(ptDistance); addedLength += ptDistance; bezierData.points[k] = new PointData(ptDistance, point); lastPoint = point; } bezierData.segmentLength = addedLength; storedData[bezierName] = bezierData; } return storedData[bezierName]; }; }()); function getDistancePerc(perc, bezierData) { var percents = bezierData.percents; var lengths = bezierData.lengths; var len = percents.length; var initPos = bmFloor((len - 1) * perc); var lengthPos = perc * bezierData.addedLength; var lPerc = 0; if (initPos === len - 1 || initPos === 0 || lengthPos === lengths[initPos]) { return percents[initPos]; } 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 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]; } var bezierSegmentPoints = createTypedArray('float32', 8); function getNewSegment(pt1, pt2, pt3, pt4, startPerc, endPerc, bezierData) { if (startPerc < 0) { startPerc = 0; } else if (startPerc > 1) { startPerc = 1; } var t0 = getDistancePerc(startPerc, bezierData); endPerc = endPerc > 1 ? 1 : endPerc; var t1 = getDistancePerc(endPerc, bezierData); var i; var len = pt1.length; var u0 = 1 - t0; var u1 = 1 - t1; var u0u0u0 = u0 * u0 * u0; var t0u0u0_3 = t0 * u0 * u0 * 3; // eslint-disable-line camelcase var t0t0u0_3 = t0 * t0 * u0 * 3; // eslint-disable-line camelcase var t0t0t0 = t0 * t0 * t0; // var u0u0u1 = u0 * u0 * u1; var t0u0u1_3 = t0 * u0 * u1 + u0 * t0 * u1 + u0 * u0 * t1; // eslint-disable-line camelcase var t0t0u1_3 = t0 * t0 * u1 + u0 * t0 * t1 + t0 * u0 * t1; // eslint-disable-line camelcase var t0t0t1 = t0 * t0 * t1; // var u0u1u1 = u0 * u1 * u1; var t0u1u1_3 = t0 * u1 * u1 + u0 * t1 * u1 + u0 * u1 * t1; // eslint-disable-line camelcase var t0t1u1_3 = t0 * t1 * u1 + u0 * t1 * t1 + t0 * u1 * t1; // eslint-disable-line camelcase var t0t1t1 = t0 * t1 * t1; // var u1u1u1 = u1 * u1 * u1; var t1u1u1_3 = t1 * u1 * u1 + u1 * t1 * u1 + u1 * u1 * t1; // eslint-disable-line camelcase var t1t1u1_3 = t1 * t1 * u1 + u1 * t1 * t1 + t1 * u1 * t1; // eslint-disable-line camelcase var t1t1t1 = t1 * t1 * t1; for (i = 0; i < len; i += 1) { bezierSegmentPoints[i * 4] = math.round((u0u0u0 * pt1[i] + t0u0u0_3 * pt3[i] + t0t0u0_3 * pt4[i] + t0t0t0 * pt2[i]) * 1000) / 1000; // eslint-disable-line camelcase bezierSegmentPoints[i * 4 + 1] = math.round((u0u0u1 * pt1[i] + t0u0u1_3 * pt3[i] + t0t0u1_3 * pt4[i] + t0t0t1 * pt2[i]) * 1000) / 1000; // eslint-disable-line camelcase bezierSegmentPoints[i * 4 + 2] = math.round((u0u1u1 * pt1[i] + t0u1u1_3 * pt3[i] + t0t1u1_3 * pt4[i] + t0t1t1 * pt2[i]) * 1000) / 1000; // eslint-disable-line camelcase bezierSegmentPoints[i * 4 + 3] = math.round((u1u1u1 * pt1[i] + t1u1u1_3 * pt3[i] + t1t1u1_3 * pt4[i] + t1t1t1 * pt2[i]) * 1000) / 1000; // eslint-disable-line camelcase } return bezierSegmentPoints; } return { getSegmentsLength: getSegmentsLength, getNewSegment: getNewSegment, getPointInSegment: getPointInSegment, buildBezierData: buildBezierData, pointOnLine2D: pointOnLine2D, pointOnLine3D: pointOnLine3D, }; } const bez = bezFunction(); const PropertyFactory = (function () { var initFrame = initialDefaultFrame; var mathAbs = 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; var flag = true; var keyData; var nextKeyData; var keyframeMetadata; 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; } } keyframeMetadata = this.keyframesMetadata[i] || {}; var k; var kLen; var perc; var jLen; var j; var fnc; var nextKeyTime = nextKeyData.t - offsetTime; var keyTime = keyData.t - offsetTime; var endValue; if (keyData.to) { if (!keyframeMetadata.bezierData) { keyframeMetadata.bezierData = bez.buildBezierData(keyData.s, nextKeyData.s || keyData.e, keyData.to, keyData.ti); } var bezierData = keyframeMetadata.bezierData; if (frameNum >= nextKeyTime || frameNum < keyTime) { var ind = frameNum >= nextKeyTime ? 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._lastKeyframeIndex = -1; } else { if (keyframeMetadata.__fnct) { fnc = keyframeMetadata.__fnct; } else { fnc = BezierFactory.getBezierEasing(keyData.o.x, keyData.o.y, keyData.i.x, keyData.i.y, keyData.n).get; keyframeMetadata.__fnct = fnc; } perc = fnc((frameNum - keyTime) / (nextKeyTime - keyTime)); var distanceInLine = bezierData.segmentLength * perc; var segmentPerc; var addedLength = (caching.lastFrame < frameNum && caching._lastKeyframeIndex === i) ? caching._lastAddedLength : 0; j = (caching.lastFrame < frameNum && caching._lastKeyframeIndex === i) ? 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._lastKeyframeIndex = i; } } else { var outX; var outY; var inX; var inY; var keyValue; len = keyData.s.length; endValue = nextKeyData.s || keyData.e; if (this.sh && keyData.h !== 1) { if (frameNum >= nextKeyTime) { newValue[0] = endValue[0]; newValue[1] = endValue[1]; newValue[2] = endValue[2]; } else if (frameNum <= keyTime) { newValue[0] = keyData.s[0]; newValue[1] = keyData.s[1]; newValue[2] = keyData.s[2]; } else { var quatStart = createQuaternion(keyData.s); var quatEnd = createQuaternion(endValue); var time = (frameNum - keyTime) / (nextKeyTime - keyTime); quaternionToEuler(newValue, slerp(quatStart, quatEnd, time)); } } else { for (i = 0; i < len; i += 1) { if (keyData.h !== 1) { if (frameNum >= nextKeyTime) { perc = 1; } else if (frameNum < keyTime) { perc = 0; } else { if (keyData.o.x.constructor === Array) { if (!keyframeMetadata.__fnct) { keyframeMetadata.__fnct = []; } if (!keyframeMetadata.__fnct[i]) { outX = keyData.o.x[i] === undefined ? keyData.o.x[0] : keyData.o.x[i]; outY = keyData.o.y[i] === undefined ? keyData.o.y[0] : keyData.o.y[i]; inX = keyData.i.x[i] === undefined ? keyData.i.x[0] : keyData.i.x[i]; inY = keyData.i.y[i] === undefined ? keyData.i.y[0] : keyData.i.y[i]; fnc = BezierFactory.getBezierEasing(outX, outY, inX, inY).get; keyframeMetadata.__fnct[i] = fnc; } else { fnc = keyframeMetadata.__fnct[i]; } } else if (!keyframeMetadata.__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.keyframeMetadata = fnc; } else { fnc = keyframeMetadata.__fnct; } perc = fnc((frameNum - keyTime) / (nextKeyTime - keyTime)); } } endValue = nextKeyData.s || keyData.e; keyValue = keyData.h === 1 ? keyData.s[i] : keyData.s[i] + (endValue[i] - keyData.s[i]) * perc; if (this.propType === 'multidimensional') { newValue[i] = keyValue; } else { newValue = 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]; var ay = a[1]; var az = a[2]; var aw = a[3]; var bx = b[0]; var by = b[1]; var bz = b[2]; var bw = b[3]; var omega; var cosom; var sinom; var scale0; var 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))))) { if (this._caching.lastFrame >= frameNum) { this._caching._lastKeyframeIndex = -1; 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 (mathAbs(this.v - multipliedValue) > 0.00001) { this.v = multipliedValue; this._mdf = true; } } else { var i = 0; var len = this.v.length; while (i < len) { multipliedValue = val[i] * this.mult; if (mathAbs(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 i; var 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; var len = data.k.length; this.v = createTypedArray('float32', len); this.pv = 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.keyframesMetadata = []; this.offsetTime = elem.data.st; this.frameId = -1; this._caching = { lastFrame: initFrame, lastIndex: 0, value: 0, _lastKeyframeIndex: -1, }; 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; var len = data.k.length; var s; var e; var to; var ti; for (i = 0; i < len - 1; i += 1) { if (data.k[i].to && data.k[i].s && data.k[i + 1] && data.k[i + 1].s) { s = data.k[i].s; e = data.k[i + 1].s; 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.data = data; this.keyframes = data.k; this.keyframesMetadata = []; 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.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; default: break; } } if (p.effectsSequence.length) { container.addDynamicProperty(p); } return p; } var ob = { getProp: getProp, }; return ob; }()); 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; var 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; }, }; const pointPool = (function () { function create() { return createTypedArray('float32', 2); } return poolFactory(8, create); }()); 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] = pointPool.newElement(); this.o[i] = pointPool.newElement(); this.i[i] = pointPool.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; default: arr = []; break; } if (!arr[pos] || (arr[pos] && !replace)) { arr[pos] = pointPool.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; var outPoints = this.o; var 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; }; const shapePool = (function () { function create() { return new ShapePath(); } function release(shapePath) { var len = shapePath._length; var i; for (i = 0; i < len; i += 1) { pointPool.release(shapePath.v[i]); pointPool.release(shapePath.i[i]); pointPool.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; var len = shape._length === undefined ? shape.v.length : shape._length; cloned.setLength(len); cloned.c = shape.c; 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 = poolFactory(4, create, release); factory.clone = clone; return factory; }()); 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) { shapePool.release(this.shapes[i]); } this._length = 0; }; const shapeCollectionPool = (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; var len = shapeCollection._length; for (i = 0; i < len; i += 1) { shapePool.release(shapeCollection.shapes[i]); } shapeCollection._length = 0; if (_length === _maxLength) { pool = pooling.double(pool); _maxLength *= 2; } pool[_length] = shapeCollection; _length += 1; } return ob; }()); const ShapePropertyFactory = (function () { var initFrame = -999999; function interpolateShape(frameNum, previousValue, caching) { var iterationIndex = caching.lastIndex; var keyPropS; var keyPropE; var isHold; var j; var k; var jLen; var kLen; var perc; var 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) { keyPropS = kf[kf.length - 1].s ? kf[kf.length - 1].s[0] : kf[kf.length - 2].e[0]; /* if(kf[kf.length - 1].s){ 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; var flag = true; var keyData; var nextKeyData; var keyframeMetadata; 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; } } keyframeMetadata = this.keyframesMetadata[i] || {}; 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 (keyframeMetadata.__fnct) { fnc = keyframeMetadata.__fnct; } else { fnc = BezierFactory.getBezierEasing(keyData.o.x, keyData.o.y, keyData.i.x, keyData.i.y).get; keyframeMetadata.__fnct = fnc; } perc = fnc((frameNum - (keyData.t - this.offsetTime)) / ((nextKeyData.t - this.offsetTime) - (keyData.t - this.offsetTime))); } keyPropE = nextKeyData.s ? nextKeyData.s[0] : 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; } } } 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; var 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 setVValue(newPath) { if (!shapesEqual(this.v, newPath)) { this.v = shapePool.clone(newPath); this.localShapeCollection.releaseShapes(); this.localShapeCollection.addShape(this.v); this._mdf = true; this.paths = this.localShapeCollection; } } function processEffectsSequence() { if (this.elem.globalData.frameId === this.frameId) { return; } if (!this.effectsSequence.length) { this._mdf = false; return; } if (this.lock) { this.setVValue(this.pv); return; } this.lock = true; this._mdf = false; var finalValue; if (this.kf) { finalValue = this.pv; } else if (this.data.ks) { finalValue = this.data.ks.k; } else { finalValue = this.data.pt.k; } var i; var len = this.effectsSequence.length; for (i = 0; i < len; i += 1) { finalValue = this.effectsSequence[i](finalValue); } this.setVValue(finalValue); this.lock = false; this.frameId = this.elem.globalData.frameId; } 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 = shapePool.clone(pathData); this.pv = shapePool.clone(this.v); this.localShapeCollection = shapeCollectionPool.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.setVValue = setVValue; 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.keyframesMetadata = []; this.k = true; this.kf = true; var len = this.keyframes[0].s[0].i.length; this.v = shapePool.newElement(); this.v.setPathData(this.keyframes[0].s[0].c, len); this.pv = shapePool.clone(this.v); this.localShapeCollection = shapeCollectionPool.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.setVValue = setVValue; KeyframedShapeProperty.prototype.addEffect = addEffect; var EllShapeProperty = (function () { var cPoint = roundCorner; function EllShapePropertyFactory(elem, data) { this.v = shapePool.newElement(); this.v.setPathData(true, 4); this.localShapeCollection = shapeCollectionPool.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(); } } EllShapePropertyFactory.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]; var p1 = this.p.v[1]; var s0 = this.s.v[0] / 2; var 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], EllShapePropertyFactory); return EllShapePropertyFactory; }()); var StarShapeProperty = (function () { function StarShapePropertyFactory(elem, data) { this.v = shapePool.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 = shapeCollectionPool.newShapeCollection(); this.localShapeCollection.addShape(this.v); this.paths = this.localShapeCollection; if (this.dynamicProperties.length) { this.k = true; } else { this.k = false; this.convertToPath(); } } StarShapePropertyFactory.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; var rad; var roundness; var perimSegment; var 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; var currentAng = -Math.PI * 0.5; 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], StarShapePropertyFactory); return StarShapePropertyFactory; }()); var RectShapeProperty = (function () { function RectShapePropertyFactory(elem, data) { this.v = shapePool.newElement(); this.v.c = true; this.localShapeCollection = shapeCollectionPool.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(); } } RectShapePropertyFactory.prototype = { convertRectToPath: function () { var p0 = this.p.v[0]; var p1 = this.p.v[1]; var v0 = this.s.v[0] / 2; var v1 = this.s.v[1] / 2; var round = bmMin(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 () { 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], RectShapePropertyFactory); return RectShapePropertyFactory; }()); 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 (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; }()); /*! 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 */ const 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) { if (!sz && sz !== 0) { sz = 1; } 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] *= 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]; } return matr; } 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 getInverseMatrix() { 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; var inverseMatrix = new Matrix(); inverseMatrix.props[0] = a; inverseMatrix.props[1] = b; inverseMatrix.props[4] = c; inverseMatrix.props[5] = d; inverseMatrix.props[12] = e; inverseMatrix.props[13] = f; return inverseMatrix; } function inversePoint(pt) { var inverseMatrix = this.getInverseMatrix(); return inverseMatrix.applyToPointArray(pt[0], pt[1], pt[2] || 0); } function inversePoints(pts) { var i; var len = pts.length; var 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]; var p1 = this.props[1]; var p4 = this.props[4]; var p5 = this.props[5]; var p12 = this.props[12]; var 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 Math.round((x * _p[0] + y * _p[4] + _p[12]) * 100) / 100 + ',' + Math.round((x * _p[1] + y * _p[5] + _p[13]) * 100) / 100; } 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.getInverseMatrix = getInverseMatrix; this._t = this.transform; this.isIdentity = isIdentity; this._identity = true; this._identityCalculated = false; this.props = createTypedArray('float32', 16); this.reset(); }; }()); const lottie = {}; var standalone = '__[STANDALONE]__'; var animationData = '__[ANIMATIONDATA]__'; var renderer = ''; function setLocation(href) { setLocationHref(href); } function searchAnimations() { if (standalone === true) { animationManager.searchAnimations(animationData, standalone, renderer); } else { animationManager.searchAnimations(); } } function setSubframeRendering(flag) { setSubframeEnabled(flag); } function setPrefix(prefix) { setIdPrefix(prefix); } function loadAnimation(params) { if (standalone === true) { params.animationData = JSON.parse(animationData); } return animationManager.loadAnimation(params); } function setQuality(value) { if (typeof value === 'string') { switch (value) { case 'high': setDefaultCurveSegments(200); break; default: case 'medium': setDefaultCurveSegments(50); break; case 'low': setDefaultCurveSegments(10); break; } } else if (!isNaN(value) && value > 1) { setDefaultCurveSegments(value); } if (getDefaultCurveSegments() >= 50) { roundValues(false); } else { roundValues(true); } } function inBrowser() { return typeof navigator !== 'undefined'; } function installPlugin(type, plugin) { if (type === 'expressions') { setExpressionsPlugin(plugin); } } function getFactory(name) { switch (name) { case 'propertyFactory': return PropertyFactory; case 'shapePropertyFactory': return ShapePropertyFactory; case 'matrix': return Matrix; default: return null; } } lottie.play = animationManager.play; lottie.pause = animationManager.pause; lottie.setLocationHref = setLocation; lottie.togglePause = animationManager.togglePause; lottie.setSpeed = animationManager.setSpeed; lottie.setDirection = animationManager.setDirection; lottie.stop = animationManager.stop; lottie.searchAnimations = searchAnimations; lottie.registerAnimation = animationManager.registerAnimation; lottie.loadAnimation = loadAnimation; lottie.setSubframeRendering = setSubframeRendering; lottie.resize = animationManager.resize; // lottie.start = start; lottie.goToAndStop = animationManager.goToAndStop; lottie.destroy = animationManager.destroy; lottie.setQuality = setQuality; lottie.inBrowser = inBrowser; lottie.installPlugin = installPlugin; lottie.freeze = animationManager.freeze; lottie.unfreeze = animationManager.unfreeze; lottie.setVolume = animationManager.setVolume; lottie.mute = animationManager.mute; lottie.unmute = animationManager.unmute; lottie.getRegisteredAnimations = animationManager.getRegisteredAnimations; lottie.useWebWorker = setWebWorker; lottie.setIDPrefix = setPrefix; lottie.__getFactory = getFactory; lottie.version = '[[BM_VERSION]]'; function checkReady() { if (document.readyState === 'complete') { clearInterval(readyStateCheckInterval); searchAnimations(); } } function getQueryVariable(variable) { var vars = queryString.split('&'); for (var i = 0; i < vars.length; i += 1) { var pair = vars[i].split('='); if (decodeURIComponent(pair[0]) == variable) { // eslint-disable-line eqeqeq return decodeURIComponent(pair[1]); } } return null; } var queryString; if (standalone) { var scripts = document.getElementsByTagName('script'); var index = scripts.length - 1; var myScript = scripts[index] || { src: '', }; queryString = myScript.src.replace(/^[^\?]+\??/, ''); // eslint-disable-line no-useless-escape renderer = getQueryVariable('renderer'); } var readyStateCheckInterval = setInterval(checkReady, 100); // this adds bodymovin to the window object for backwards compatibility try { if (!(typeof exports === 'object' && typeof module !== 'undefined') && !(typeof define === 'function' && define.amd) // eslint-disable-line no-undef ) { window.bodymovin = lottie; } } catch (err) { // } const 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) { // Adding shape to dynamic properties. It covers the case where a shape has no effects applied, to reset it's _mdf state on every tick. data.sh.container.addDynamicProperty(data.sh); var shapeData = { shape: data.sh, data: data, localShapeCollection: shapeCollectionPool.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; var len = segments.length; var segmentOb; for (i = 0; i < len; i += 1) { segmentOb = segments[i]; if (!(segmentOb.e * totalModifierLength < addedLength || segmentOb.s * totalModifierLength > addedLength + shapeLength)) { var shapeS; var 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; var len = pathsData.length; for (i = 0; i < len; i += 1) { segmentsLengthPool.release(pathsData[i]); } pathsData.length = 0; return pathsData; }; TrimModifier.prototype.processShapes = function (_isFirstFrame) { var s; var e; if (this._mdf || _isFirstFrame) { var o = (this.o.v % 360) / 360; if (o < 0) { o += 1; } if (this.s.v > 1) { s = 1 + o; } else if (this.s.v < 0) { s = 0 + o; } else { s = this.s.v + o; } if (this.e.v > 1) { e = 1 + o; } else if (this.e.v < 0) { e = 0 + o; } else { e = this.e.v + o; } if (s > e) { var _s = s; s = e; e = _s; } s = Math.round(s * 10000) * 0.0001; e = Math.round(e * 10000) * 0.0001; this.sValue = s; this.eValue = e; } else { s = this.sValue; e = this.eValue; } var shapePaths; var i; var len = this.shapes.length; var j; var jLen; var pathsData; var pathData; var totalShapeLength; var 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; if (this._mdf) { this.shapes[i].pathsData.length = 0; } } } else if (!((e === 1 && s === 0) || (e === 0 && s === 1))) { var segments = []; var shapeData; var 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; var shapeE = e; var addedLength = 0; var 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) { var lastShapeInCollection = shapeData.shape.paths.shapes[shapeData.shape.paths._length - 1]; if (lastShapeInCollection.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) { // Releasign Trim Cached paths data when no trim applied in case shapes are modified inbetween. // Don't remove this even if it's losing cached info. this.shapes[i].pathsData.length = 0; this.shapes[i].shape._mdf = true; } } }; TrimModifier.prototype.addPaths = function (newPaths, localShapeCollection) { var i; var 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; var len = shapeData.shape.paths._length; var j; var jLen; var addedLength = 0; var currentLengthData; var segmentCount; var lengths; var segment; var shapes = []; var initPos; var newShape = true; if (!shapePath) { shapePath = shapePool.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 && lengths.length) { 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 = shapePool.newElement(); newShape = true; shapes.push(shapePath); segmentCount = 0; } } return shapes; }; function PuckerAndBloatModifier() {} extendPrototype([ShapeModifier], PuckerAndBloatModifier); PuckerAndBloatModifier.prototype.initModifierProperties = function (elem, data) { this.getValue = this.processKeys; this.amount = PropertyFactory.getProp(elem, data.a, 0, null, this); this._isAnimated = !!this.amount.effectsSequence.length; }; PuckerAndBloatModifier.prototype.processPath = function (path, amount) { var percent = amount / 100; var centerPoint = [0, 0]; var pathLength = path._length; var i = 0; for (i = 0; i < pathLength; i += 1) { centerPoint[0] += path.v[i][0]; centerPoint[1] += path.v[i][1]; } centerPoint[0] /= pathLength; centerPoint[1] /= pathLength; var clonedPath = shapePool.newElement(); clonedPath.c = path.c; var vX; var vY; var oX; var oY; var iX; var iY; for (i = 0; i < pathLength; i += 1) { vX = path.v[i][0] + (centerPoint[0] - path.v[i][0]) * percent; vY = path.v[i][1] + (centerPoint[1] - path.v[i][1]) * percent; oX = path.o[i][0] + (centerPoint[0] - path.o[i][0]) * -percent; oY = path.o[i][1] + (centerPoint[1] - path.o[i][1]) * -percent; iX = path.i[i][0] + (centerPoint[0] - path.i[i][0]) * -percent; iY = path.i[i][1] + (centerPoint[1] - path.i[i][1]) * -percent; clonedPath.setTripleAt(vX, vY, oX, oY, iX, iY, i); } return clonedPath; }; PuckerAndBloatModifier.prototype.processShapes = function (_isFirstFrame) { var shapePaths; var i; var len = this.shapes.length; var j; var jLen; var amount = this.amount.v; if (amount !== 0) { var shapeData; var localShapeCollection; for (i = 0; i < len; i += 1) { shapeData = this.shapes[i]; 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], amount)); } } shapeData.shape.paths = shapeData.localShapeCollection; } } if (!this.dynamicProperties.length) { this._mdf = false; } }; const TransformPropertyFactory = (function () { var defaultVector = [0, 0]; 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) { var frameRate; 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) { var v1; var v2; frameRate = this.elem.globalData.frameRate; if (this.p && this.p.keyframes && this.p.getValueAtTime) { if (this.p._caching.lastFrame + this.p.offsetTime <= this.p.keyframes[0].t) { v1 = this.p.getValueAtTime((this.p.keyframes[0].t + 0.01) / frameRate, 0); v2 = this.p.getValueAtTime(this.p.keyframes[0].t / 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 / frameRate), 0); v2 = this.p.getValueAtTime((this.p.keyframes[this.p.keyframes.length - 1].t - 0.05) / frameRate, 0); } else { v1 = this.p.pv; v2 = this.p.getValueAtTime((this.p._caching.lastFrame + this.p.offsetTime - 0.01) / frameRate, this.p.offsetTime); } } else if (this.px && this.px.keyframes && this.py.keyframes && this.px.getValueAtTime && this.py.getValueAtTime) { v1 = []; v2 = []; var px = this.px; var py = this.py; if (px._caching.lastFrame + px.offsetTime <= px.keyframes[0].t) { v1[0] = px.getValueAtTime((px.keyframes[0].t + 0.01) / frameRate, 0); v1[1] = py.getValueAtTime((py.keyframes[0].t + 0.01) / frameRate, 0); v2[0] = px.getValueAtTime((px.keyframes[0].t) / frameRate, 0); v2[1] = py.getValueAtTime((py.keyframes[0].t) / frameRate, 0); } else if (px._caching.lastFrame + px.offsetTime >= px.keyframes[px.keyframes.length - 1].t) { v1[0] = px.getValueAtTime((px.keyframes[px.keyframes.length - 1].t / frameRate), 0); v1[1] = py.getValueAtTime((py.keyframes[py.keyframes.length - 1].t / frameRate), 0); v2[0] = px.getValueAtTime((px.keyframes[px.keyframes.length - 1].t - 0.01) / frameRate, 0); v2[1] = py.getValueAtTime((py.keyframes[py.keyframes.length - 1].t - 0.01) / frameRate, 0); } else { v1 = [px.pv, py.pv]; v2[0] = px.getValueAtTime((px._caching.lastFrame + px.offsetTime - 0.01) / frameRate, px.offsetTime); v2[1] = py.getValueAtTime((py._caching.lastFrame + py.offsetTime - 0.01) / frameRate, py.offsetTime); } } else { v2 = defaultVector; v1 = v2; } this.v.rotate(-Math.atan2(v1[1] - v2[1], v1[0] - v2[0])); } if (this.data.p && 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 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 && 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 || { k: [0, 0, 0] }, 1, 0, this); } 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; var len = data.or.k.length; for (i = 0; i < len; i += 1) { data.or.k[i].to = null; 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; } else { this.r = PropertyFactory.getProp(elem, data.r || { k: 0 }, 0, degToRads, this); } if (data.sk) { this.sk = PropertyFactory.getProp(elem, data.sk, 0, degToRads, this); this.sa = PropertyFactory.getProp(elem, data.sa, 0, degToRads, this); } this.a = PropertyFactory.getProp(elem, data.a || { k: [0, 0, 0] }, 1, 0, this); this.s = PropertyFactory.getProp(elem, data.s || { k: [100, 100, 100] }, 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 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.so = PropertyFactory.getProp(elem, data.tr.so, 0, 0.01, this); this.eo = PropertyFactory.getProp(elem, data.tr.eo, 0, 0.01, 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]); while (pos > 0) { pos -= 1; // this._elements.unshift(arr.splice(pos,1)[0]); this._elements.unshift(arr[pos]); } if (this.dynamicProperties.length) { this.k = true; } else { this.getValue(true); } }; RepeaterModifier.prototype.resetElements = function (elements) { var i; var 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 newElements = JSON.parse(JSON.stringify(elements)); this.resetElements(newElements); return newElements; }; RepeaterModifier.prototype.changeGroupRender = function (elements, renderFlag) { var i; var 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; var itemsTransform; var i; var dir; var cont; var hasReloaded = false; 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(); hasReloaded = true; } 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); if (!renderFlag) { var elems = this.elemsData[i].it; var transformData = elems[elems.length - 1]; if (transformData.transform.op.v !== 0) { transformData.transform.op._mdf = true; transformData.transform.op.v = 0; } else { transformData.transform.op._mdf = false; } } 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 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; var 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; items[items.length - 1].transform.op.v = this._currentCopies === 1 ? this.so.v : this.so.v + (this.eo.v - this.so.v) * (i / (this._currentCopies - 1)); 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; } } return hasReloaded; }; RepeaterModifier.prototype.addShape = function () {}; 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 clonedPath = shapePool.newElement(); clonedPath.c = path.c; var i; var len = path._length; var currentV; var currentI; var currentO; var closerV; var distance; var newPosPerc; var index = 0; var vX; var vY; var oX; var oY; var iX; var 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) { clonedPath.setTripleAt(currentV[0], currentV[1], currentO[0], currentO[1], currentI[0], currentI[1], index); /* clonedPath.v[index] = currentV; clonedPath.o[index] = currentO; clonedPath.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; iX = currentV[0] + (closerV[0] - currentV[0]) * newPosPerc; vX = iX; iY = currentV[1] - (currentV[1] - closerV[1]) * newPosPerc; vY = iY; oX = vX - (vX - currentV[0]) * roundCorner; oY = vY - (vY - currentV[1]) * roundCorner; clonedPath.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; oX = currentV[0] + (closerV[0] - currentV[0]) * newPosPerc; vX = oX; oY = currentV[1] + (closerV[1] - currentV[1]) * newPosPerc; vY = oY; iX = vX - (vX - currentV[0]) * roundCorner; iY = vY - (vY - currentV[1]) * roundCorner; clonedPath.setTripleAt(vX, vY, oX, oY, iX, iY, index); index += 1; } } else { clonedPath.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 clonedPath; }; RoundCornersModifier.prototype.processShapes = function (_isFirstFrame) { var shapePaths; var i; var len = this.shapes.length; var j; var jLen; var rd = this.rd.v; if (rd !== 0) { var shapeData; var localShapeCollection; for (i = 0; i < len; i += 1) { shapeData = this.shapes[i]; 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; } }; function getFontProperties(fontData) { var styles = fontData.fStyle ? fontData.fStyle.split(' ') : []; var fWeight = 'normal'; var fStyle = 'normal'; var len = styles.length; var styleName; for (var 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; default: break; } } return { style: fStyle, weight: fontData.fWeight || fWeight, }; } const FontManager = (function () { var maxWaitingTime = 5000; var emptyChar = { w: 0, size: 0, shapes: [], data: { 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]); var surrogateModifiers = [ 'd83cdffb', 'd83cdffc', 'd83cdffd', 'd83cdffe', 'd83cdfff', ]; var zeroWidthJoiner = [65039, 8205]; function trimFontOptions(font) { var familyArray = font.split(','); var i; var len = familyArray.length; var enabledFamilies = []; for (i = 0; i < len; i += 1) { if (familyArray[i] !== 'sans-serif' && familyArray[i] !== 'monospace') { enabledFamilies.push(familyArray[i]); } } return enabledFamilies.join(','); } function setUpNode(font, family) { var parentNode = createTag('span'); // Node is invisible to screen readers. parentNode.setAttribute('aria-hidden', true); parentNode.style.fontFamily = family; var node = createTag('span'); // Characters that vary significantly among different fonts node.innerText = '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 = trimFontOptions(font) + ', ' + family; return { node: node, w: width, parent: parentNode }; } function checkLoadedFonts() { var i; var len = this.fonts.length; var node; var w; var loadedCount = len; for (i = 0; i < len; i += 1) { if (this.fonts[i].loaded) { loadedCount -= 1; } 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(this.checkLoadedFontsBinded, 20); } else { setTimeout(this.setIsLoadedBinded, 10); } } function createHelper(def, fontData) { var tHelper = createNS('text'); tHelper.style.fontSize = '100px'; // tHelper.style.fontFamily = fontData.fFamily; var fontProps = getFontProperties(fontData); tHelper.setAttribute('font-family', fontData.fFamily); tHelper.setAttribute('font-style', fontProps.style); tHelper.setAttribute('font-weight', fontProps.weight); tHelper.textContent = '1'; if (fontData.fClass) { tHelper.style.fontFamily = 'inherit'; tHelper.setAttribute('class', 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.isLoaded = true; return; } if (this.chars) { this.isLoaded = true; this.fonts = fontData.list; return; } var fontArr = fontData.list; var i; var len = fontArr.length; var _pendingFonts = len; for (i = 0; i < len; i += 1) { var shouldLoadFont = true; var loadedSelector; var j; 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; _pendingFonts -= 1; } else if (fontArr[i].fOrigin === 'p' || fontArr[i].origin === 3) { loadedSelector = document.querySelectorAll('style[f-forigin="p"][f-family="' + fontArr[i].fFamily + '"], style[f-origin="3"][f-family="' + fontArr[i].fFamily + '"]'); if (loadedSelector.length > 0) { shouldLoadFont = false; } if (shouldLoadFont) { var s = createTag('style'); s.setAttribute('f-forigin', fontArr[i].fOrigin); s.setAttribute('f-origin', fontArr[i].origin); s.setAttribute('f-family', fontArr[i].fFamily); s.type = 'text/css'; s.innerText = '@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) { loadedSelector = document.querySelectorAll('link[f-forigin="g"], link[f-origin="1"]'); for (j = 0; j < loadedSelector.length; j += 1) { if (loadedSelector[j].href.indexOf(fontArr[i].fPath) !== -1) { // Font is already loaded shouldLoadFont = false; } } if (shouldLoadFont) { var l = createTag('link'); l.setAttribute('f-forigin', fontArr[i].fOrigin); l.setAttribute('f-origin', fontArr[i].origin); 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) { loadedSelector = document.querySelectorAll('script[f-forigin="t"], script[f-origin="2"]'); for (j = 0; j < loadedSelector.length; j += 1) { if (fontArr[i].fPath === loadedSelector[j].src) { // Font is already loaded shouldLoadFont = false; } } if (shouldLoadFont) { var sc = createTag('link'); sc.setAttribute('f-forigin', fontArr[i].fOrigin); sc.setAttribute('f-origin', fontArr[i].origin); sc.setAttribute('rel', 'stylesheet'); sc.setAttribute('href', fontArr[i].fPath); defs.appendChild(sc); } } fontArr[i].helper = createHelper(defs, fontArr[i]); fontArr[i].cache = {}; this.fonts.push(fontArr[i]); } if (_pendingFonts === 0) { this.isLoaded = true; } else { // On some cases even if the font is loaded, it won't load correctly when measuring text on canvas. // Adding this timeout seems to fix it setTimeout(this.checkLoadedFonts.bind(this), 100); } } function addChars(chars) { if (!chars) { return; } if (!this.chars) { this.chars = []; } var i; var len = chars.length; var j; var jLen = this.chars.length; var 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; var 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 (((typeof char === 'string' && char.charCodeAt(0) !== 13) || !char) && console && console.warn // eslint-disable-line no-console && !this._warned ) { this._warned = true; console.warn('Missing character from exported characters list: ', char, style, font); // eslint-disable-line no-console } 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) if (char === ' ') { tHelper.textContent = '|' + char + '|'; var doubleSize = tHelper.getComputedTextLength(); tHelper.textContent = '||'; var singleSize = tHelper.getComputedTextLength(); fontData.cache[index + 1] = (doubleSize - singleSize) / 100; } else { tHelper.textContent = char; fontData.cache[index + 1] = (tHelper.getComputedTextLength()) / 100; } } return fontData.cache[index + 1] * size; } function getFontByName(name) { var i = 0; var len = this.fonts.length; while (i < len) { if (this.fonts[i].fName === name) { return this.fonts[i]; } i += 1; } return this.fonts[0]; } function isModifier(firstCharCode, secondCharCode) { var sum = firstCharCode.toString(16) + secondCharCode.toString(16); return surrogateModifiers.indexOf(sum) !== -1; } function isZeroWidthJoiner(firstCharCode, secondCharCode) { if (!secondCharCode) { return firstCharCode === zeroWidthJoiner[1]; } return firstCharCode === zeroWidthJoiner[0] && secondCharCode === zeroWidthJoiner[1]; } function isCombinedCharacter(char) { return combinedCharacters.indexOf(char) !== -1; } function setIsLoaded() { this.isLoaded = true; } var Font = function () { this.fonts = []; this.chars = null; this.typekitLoaded = 0; this.isLoaded = false; this._warned = false; this.initTime = Date.now(); this.setIsLoadedBinded = this.setIsLoaded.bind(this); this.checkLoadedFontsBinded = this.checkLoadedFonts.bind(this); }; Font.isModifier = isModifier; Font.isZeroWidthJoiner = isZeroWidthJoiner; Font.isCombinedCharacter = isCombinedCharacter; var fontPrototype = { addChars: addChars, addFonts: addFonts, getCharData: getCharData, getFontByName: getFontByName, measureText: measureText, checkLoadedFonts: checkLoadedFonts, setIsLoaded: setIsLoaded, }; Font.prototype = fontPrototype; return Font; }()); 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; var 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 }; } return { w: this.data.width, h: this.data.height }; }, }; const 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; }, }); Object.defineProperty(MaskInterface.prototype, 'maskOpacity', { get: function () { if (this._mask.op.k) { this._mask.op.getValue(); } return this._mask.op.v * 100; }, }); var MaskManager = function (maskManager) { var _masksInterfaces = createSizedArray(maskManager.viewData.length); var i; var 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 null; }; return maskFunction; }; return MaskManager; }()); const ExpressionPropertyInterface = (function () { var defaultUnidimensionalValue = { pv: 0, v: 0, mult: 1 }; var defaultMultidimensionalValue = { pv: [0, 0, 0], v: [0, 0, 0], mult: 1 }; function completeProperty(expressionValue, property, type) { Object.defineProperty(expressionValue, 'velocity', { get: function () { return property.getVelocityAtTime(property.comp.currentFrame); }, }); expressionValue.numKeys = property.keyframes ? property.keyframes.length : 0; expressionValue.key = function (pos) { if (!expressionValue.numKeys) { return 0; } var value = ''; if ('s' in property.keyframes[pos - 1]) { value = property.keyframes[pos - 1].s; } else if ('e' in property.keyframes[pos - 2]) { value = property.keyframes[pos - 2].e; } else { value = property.keyframes[pos - 2].s; } var valueProp = type === 'unidimensional' ? new Number(value) : Object.assign({}, value); // eslint-disable-line no-new-wrappers valueProp.time = property.keyframes[pos - 1].t / property.elem.comp.globalData.frameRate; valueProp.value = type === 'unidimensional' ? value[0] : value; return valueProp; }; expressionValue.valueAtTime = property.getValueAtTime; expressionValue.speedAtTime = property.getSpeedAtTime; expressionValue.velocityAtTime = property.getVelocityAtTime; expressionValue.propertyGroup = property.propertyGroup; } function UnidimensionalPropertyInterface(property) { if (!property || !('pv' in property)) { property = defaultUnidimensionalValue; } var mult = 1 / property.mult; var val = property.pv * mult; var expressionValue = new Number(val); // eslint-disable-line no-new-wrappers expressionValue.value = val; completeProperty(expressionValue, property, 'unidimensional'); return function () { if (property.k) { property.getValue(); } val = property.v * mult; if (expressionValue.value !== val) { expressionValue = new Number(val); // eslint-disable-line no-new-wrappers expressionValue.value = val; completeProperty(expressionValue, property, 'unidimensional'); } return expressionValue; }; } function MultidimensionalPropertyInterface(property) { if (!property || !('pv' in property)) { property = defaultMultidimensionalValue; } var mult = 1 / property.mult; var len = (property.data && property.data.l) || property.pv.length; var expressionValue = createTypedArray('float32', len); var arrValue = createTypedArray('float32', len); expressionValue.value = arrValue; completeProperty(expressionValue, property, 'multidimensional'); return function () { if (property.k) { property.getValue(); } for (var i = 0; i < len; i += 1) { arrValue[i] = property.v[i] * mult; expressionValue[i] = arrValue[i]; } return expressionValue; }; } // TODO: try to avoid using this getter function defaultGetter() { return defaultUnidimensionalValue; } return function (property) { if (!property) { return defaultGetter; } if (property.propType === 'unidimensional') { return UnidimensionalPropertyInterface(property); } return MultidimensionalPropertyInterface(property); }; }()); const 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; default: return null; } } Object.defineProperty(_thisFunction, 'rotation', { get: ExpressionPropertyInterface(transform.r || transform.rz), }); Object.defineProperty(_thisFunction, 'zRotation', { get: ExpressionPropertyInterface(transform.rz || transform.r), }); Object.defineProperty(_thisFunction, 'xRotation', { get: ExpressionPropertyInterface(transform.rx), }); Object.defineProperty(_thisFunction, 'yRotation', { get: ExpressionPropertyInterface(transform.ry), }); Object.defineProperty(_thisFunction, 'scale', { get: ExpressionPropertyInterface(transform.s), }); var _px; var _py; var _pz; var _transformFactory; if (transform.p) { _transformFactory = ExpressionPropertyInterface(transform.p); } else { _px = ExpressionPropertyInterface(transform.px); _py = ExpressionPropertyInterface(transform.py); if (transform.pz) { _pz = ExpressionPropertyInterface(transform.pz); } } Object.defineProperty(_thisFunction, 'position', { get: function () { if (transform.p) { return _transformFactory(); } return [ _px(), _py(), _pz ? _pz() : 0]; }, }); Object.defineProperty(_thisFunction, 'xPosition', { get: ExpressionPropertyInterface(transform.px), }); Object.defineProperty(_thisFunction, 'yPosition', { get: ExpressionPropertyInterface(transform.py), }); Object.defineProperty(_thisFunction, 'zPosition', { get: ExpressionPropertyInterface(transform.pz), }); Object.defineProperty(_thisFunction, 'anchorPoint', { get: ExpressionPropertyInterface(transform.a), }); Object.defineProperty(_thisFunction, 'opacity', { get: ExpressionPropertyInterface(transform.o), }); Object.defineProperty(_thisFunction, 'skew', { get: ExpressionPropertyInterface(transform.sk), }); Object.defineProperty(_thisFunction, 'skewAxis', { get: ExpressionPropertyInterface(transform.sa), }); Object.defineProperty(_thisFunction, 'orientation', { get: ExpressionPropertyInterface(transform.or), }); return _thisFunction; }; }()); const LayerExpressionInterface = (function () { function getMatrix(time) { var toWorldMat = new Matrix(); if (time !== undefined) { var propMatrix = this._elem.finalTransform.mProp.getValueAtTime(time); propMatrix.clone(toWorldMat); } else { var transformMat = this._elem.finalTransform.mProp; transformMat.applyToMatrix(toWorldMat); } return toWorldMat; } function toWorldVec(arr, time) { var toWorldMat = this.getMatrix(time); toWorldMat.props[12] = 0; toWorldMat.props[13] = 0; toWorldMat.props[14] = 0; return this.applyPoint(toWorldMat, arr); } function toWorld(arr, time) { var toWorldMat = this.getMatrix(time); return this.applyPoint(toWorldMat, arr); } function fromWorldVec(arr, time) { var toWorldMat = this.getMatrix(time); toWorldMat.props[12] = 0; toWorldMat.props[13] = 0; toWorldMat.props[14] = 0; return this.invertPoint(toWorldMat, arr); } function fromWorld(arr, time) { var toWorldMat = this.getMatrix(time); return this.invertPoint(toWorldMat, arr); } function applyPoint(matrix, arr) { if (this._elem.hierarchy && this._elem.hierarchy.length) { var i; var len = this._elem.hierarchy.length; for (i = 0; i < len; i += 1) { this._elem.hierarchy[i].finalTransform.mProp.applyToMatrix(matrix); } } return matrix.applyToPointArray(arr[0], arr[1], arr[2] || 0); } function invertPoint(matrix, arr) { if (this._elem.hierarchy && this._elem.hierarchy.length) { var i; var len = this._elem.hierarchy.length; for (i = 0; i < len; i += 1) { this._elem.hierarchy[i].finalTransform.mProp.applyToMatrix(matrix); } } return matrix.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; var 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 sampleImage() { return [1, 1, 1, 1]; } 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': case 'effects': case 'Effects': return _thisLayerFunction.effect; case 'ADBE Text Properties': return _thisLayerFunction.textInterface; default: return null; } } _thisLayerFunction.getMatrix = getMatrix; _thisLayerFunction.invertPoint = invertPoint; _thisLayerFunction.applyPoint = applyPoint; _thisLayerFunction.toWorld = toWorld; _thisLayerFunction.toWorldVec = toWorldVec; _thisLayerFunction.fromWorld = fromWorld; _thisLayerFunction.fromWorldVec = fromWorldVec; _thisLayerFunction.toComp = toWorld; _thisLayerFunction.fromComp = fromComp; _thisLayerFunction.sampleImage = sampleImage; _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.inPoint = elem.data.ip / elem.comp.globalData.frameRate; _thisLayerFunction.outPoint = elem.data.op / elem.comp.globalData.frameRate; _thisLayerFunction._name = elem.data.nm; _thisLayerFunction.registerMaskInterface = _registerMaskInterface; _thisLayerFunction.registerEffectsInterface = _registerEffectsInterface; return _thisLayerFunction; }; }()); const propertyGroupFactory = (function () { return function (interfaceFunction, parentPropertyGroup) { return function (val) { val = val === undefined ? 1 : val; if (val <= 0) { return interfaceFunction; } return parentPropertyGroup(val - 1); }; }; }()); const PropertyInterface = (function () { return function (propertyName, propertyGroup) { var interfaceFunction = { _name: propertyName, }; function _propertyGroup(val) { val = val === undefined ? 1 : val; if (val <= 0) { return interfaceFunction; } return propertyGroup(val - 1); } return _propertyGroup; }; }()); const EffectsExpressionInterface = (function () { var ob = { createEffectsInterface: createEffectsInterface, }; function createEffectsInterface(elem, propertyGroup) { if (elem.effectsManager) { var effectElements = []; var effectsData = elem.data.ef; var i; var len = elem.effectsManager.effectElements.length; for (i = 0; i < len; i += 1) { effectElements.push(createGroupInterface(effectsData[i], elem.effectsManager.effectElements[i], propertyGroup, elem)); } var effects = elem.data.ef || []; var groupInterface = function (name) { 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; } return null; }; Object.defineProperty(groupInterface, 'numProperties', { get: function () { return effects.length; }, }); return groupInterface; } return null; } function createGroupInterface(data, elements, propertyGroup, elem) { function groupInterface(name) { var effects = data.ef; var i = 0; var 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]; } return effectElements[i](); } i += 1; } throw new Error(); } var _propertyGroup = propertyGroupFactory(groupInterface, propertyGroup); var effectElements = []; var i; var 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)); } } if (data.mn === 'ADBE Color Control') { Object.defineProperty(groupInterface, 'color', { get: function () { return effectElements[0](); }, }); } Object.defineProperties(groupInterface, { numProperties: { get: function () { return data.np; }, }, _name: { value: data.nm }, propertyGroup: { value: _propertyGroup }, }); groupInterface.enabled = data.en !== 0; groupInterface.active = groupInterface.enabled; return groupInterface; } function createValueInterface(element, type, elem, propertyGroup) { var expressionProperty = ExpressionPropertyInterface(element.p); function interfaceFunction() { if (type === 10) { return elem.comp.compInterface(element.p.v); } return expressionProperty(); } if (element.p.setGroupProperty) { element.p.setGroupProperty(PropertyInterface('', propertyGroup)); } return interfaceFunction; } return ob; }()); const CompExpressionInterface = (function () { return function (comp) { function _thisLayerFunction(name) { var i = 0; var 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 null; // return {active:false}; } Object.defineProperty(_thisLayerFunction, '_name', { value: comp.data.nm }); _thisLayerFunction.layer = _thisLayerFunction; _thisLayerFunction.pixelAspect = 1; _thisLayerFunction.height = comp.data.h || comp.globalData.compSize.h; _thisLayerFunction.width = comp.data.w || comp.globalData.compSize.w; _thisLayerFunction.pixelAspect = 1; _thisLayerFunction.frameDuration = 1 / comp.globalData.frameRate; _thisLayerFunction.displayStartTime = 0; _thisLayerFunction.numLayers = comp.layers.length; return _thisLayerFunction; }; }()); const ShapePathInterface = ( function () { return function pathInterfaceFactory(shape, view, propertyGroup) { var prop = view.sh; function interfaceFunction(val) { if (val === 'Shape' || val === 'shape' || val === 'Path' || val === 'path' || val === 'ADBE Vector Shape' || val === 2) { return interfaceFunction.path; } return null; } var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); prop.setGroupProperty(PropertyInterface('Path', _propertyGroup)); 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 }, propertyIndex: { value: shape.ix }, mn: { value: shape.mn }, propertyGroup: { value: propertyGroup }, }); return interfaceFunction; }; }() ); const ShapeExpressionInterface = (function () { function iterateElements(shapes, view, propertyGroup) { var arr = []; var i; var 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(ShapePathInterface(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)); } else if (shapes[i].ty === 'gf') { arr.push(gradientFillInterfaceFactory(shapes[i], view[i], propertyGroup)); } else { arr.push(defaultInterfaceFactory(shapes[i], view[i], propertyGroup)); } } return arr; } function contentsInterfaceFactory(shape, view, propertyGroup) { var interfaces; var interfaceFunction = function _interfaceFunction(value) { var i = 0; var 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]; } return null; }; interfaceFunction.propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); interfaces = iterateElements(shape.it, view.it, interfaceFunction.propertyGroup); interfaceFunction.numProperties = interfaces.length; var transformInterface = transformInterfaceFactory(shape.it[shape.it.length - 1], view.it[view.it.length - 1], interfaceFunction.propertyGroup); interfaceFunction.transform = transformInterface; 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 = propertyGroupFactory(interfaceFunction, propertyGroup); 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; } if (val === 'Opacity' || val === 'opacity') { return interfaceFunction.opacity; } return null; } Object.defineProperties(interfaceFunction, { color: { get: ExpressionPropertyInterface(view.c), }, opacity: { get: ExpressionPropertyInterface(view.o), }, _name: { value: shape.nm }, mn: { value: shape.mn }, }); view.c.setGroupProperty(PropertyInterface('Color', propertyGroup)); view.o.setGroupProperty(PropertyInterface('Opacity', propertyGroup)); return interfaceFunction; } function gradientFillInterfaceFactory(shape, view, propertyGroup) { function interfaceFunction(val) { if (val === 'Start Point' || val === 'start point') { return interfaceFunction.startPoint; } if (val === 'End Point' || val === 'end point') { return interfaceFunction.endPoint; } if (val === 'Opacity' || val === 'opacity') { return interfaceFunction.opacity; } return null; } Object.defineProperties(interfaceFunction, { startPoint: { get: ExpressionPropertyInterface(view.s), }, endPoint: { get: ExpressionPropertyInterface(view.e), }, opacity: { get: ExpressionPropertyInterface(view.o), }, type: { get: function () { return 'a'; }, }, _name: { value: shape.nm }, mn: { value: shape.mn }, }); view.s.setGroupProperty(PropertyInterface('Start Point', propertyGroup)); view.e.setGroupProperty(PropertyInterface('End Point', propertyGroup)); view.o.setGroupProperty(PropertyInterface('Opacity', propertyGroup)); return interfaceFunction; } function defaultInterfaceFactory() { function interfaceFunction() { return null; } return interfaceFunction; } function strokeInterfaceFactory(shape, view, propertyGroup) { var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); var _dashPropertyGroup = propertyGroupFactory(dashOb, _propertyGroup); function addPropertyToDashOb(i) { Object.defineProperty(dashOb, shape.d[i].nm, { get: ExpressionPropertyInterface(view.d.dataProps[i].p), }); } var i; var 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; } if (val === 'Opacity' || val === 'opacity') { return interfaceFunction.opacity; } if (val === 'Stroke Width' || val === 'stroke width') { return interfaceFunction.strokeWidth; } return null; } Object.defineProperties(interfaceFunction, { color: { get: ExpressionPropertyInterface(view.c), }, opacity: { get: ExpressionPropertyInterface(view.o), }, strokeWidth: { get: ExpressionPropertyInterface(view.w), }, dash: { get: function () { return dashOb; }, }, _name: { value: shape.nm }, mn: { value: shape.mn }, }); view.c.setGroupProperty(PropertyInterface('Color', _propertyGroup)); view.o.setGroupProperty(PropertyInterface('Opacity', _propertyGroup)); view.w.setGroupProperty(PropertyInterface('Stroke Width', _propertyGroup)); return interfaceFunction; } function trimInterfaceFactory(shape, view, 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; } return null; } var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); interfaceFunction.propertyIndex = shape.ix; view.s.setGroupProperty(PropertyInterface('Start', _propertyGroup)); view.e.setGroupProperty(PropertyInterface('End', _propertyGroup)); view.o.setGroupProperty(PropertyInterface('Offset', _propertyGroup)); interfaceFunction.propertyIndex = shape.ix; interfaceFunction.propertyGroup = propertyGroup; Object.defineProperties(interfaceFunction, { start: { get: ExpressionPropertyInterface(view.s), }, end: { get: ExpressionPropertyInterface(view.e), }, offset: { get: ExpressionPropertyInterface(view.o), }, _name: { value: shape.nm }, }); interfaceFunction.mn = shape.mn; return interfaceFunction; } function transformInterfaceFactory(shape, view, 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; } return null; } var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); view.transform.mProps.o.setGroupProperty(PropertyInterface('Opacity', _propertyGroup)); view.transform.mProps.p.setGroupProperty(PropertyInterface('Position', _propertyGroup)); view.transform.mProps.a.setGroupProperty(PropertyInterface('Anchor Point', _propertyGroup)); view.transform.mProps.s.setGroupProperty(PropertyInterface('Scale', _propertyGroup)); view.transform.mProps.r.setGroupProperty(PropertyInterface('Rotation', _propertyGroup)); if (view.transform.mProps.sk) { view.transform.mProps.sk.setGroupProperty(PropertyInterface('Skew', _propertyGroup)); view.transform.mProps.sa.setGroupProperty(PropertyInterface('Skew Angle', _propertyGroup)); } view.transform.op.setGroupProperty(PropertyInterface('Opacity', _propertyGroup)); Object.defineProperties(interfaceFunction, { opacity: { get: ExpressionPropertyInterface(view.transform.mProps.o), }, position: { get: ExpressionPropertyInterface(view.transform.mProps.p), }, anchorPoint: { get: ExpressionPropertyInterface(view.transform.mProps.a), }, scale: { get: ExpressionPropertyInterface(view.transform.mProps.s), }, rotation: { get: ExpressionPropertyInterface(view.transform.mProps.r), }, skew: { get: ExpressionPropertyInterface(view.transform.mProps.sk), }, skewAxis: { get: ExpressionPropertyInterface(view.transform.mProps.sa), }, _name: { value: shape.nm }, }); interfaceFunction.ty = 'tr'; interfaceFunction.mn = shape.mn; interfaceFunction.propertyGroup = propertyGroup; return interfaceFunction; } function ellipseInterfaceFactory(shape, view, propertyGroup) { function interfaceFunction(value) { if (shape.p.ix === value) { return interfaceFunction.position; } if (shape.s.ix === value) { return interfaceFunction.size; } return null; } var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); interfaceFunction.propertyIndex = shape.ix; var prop = view.sh.ty === 'tm' ? view.sh.prop : view.sh; prop.s.setGroupProperty(PropertyInterface('Size', _propertyGroup)); prop.p.setGroupProperty(PropertyInterface('Position', _propertyGroup)); Object.defineProperties(interfaceFunction, { size: { get: ExpressionPropertyInterface(prop.s), }, position: { get: ExpressionPropertyInterface(prop.p), }, _name: { value: shape.nm }, }); interfaceFunction.mn = shape.mn; return interfaceFunction; } function starInterfaceFactory(shape, view, 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 || value === 'ADBE Vector Star Outer Radius') { return interfaceFunction.outerRadius; } if (shape.os.ix === value) { return interfaceFunction.outerRoundness; } if (shape.ir && (shape.ir.ix === value || value === 'ADBE Vector Star Inner Radius')) { return interfaceFunction.innerRadius; } if (shape.is && shape.is.ix === value) { return interfaceFunction.innerRoundness; } return null; } var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); var prop = view.sh.ty === 'tm' ? view.sh.prop : view.sh; interfaceFunction.propertyIndex = shape.ix; prop.or.setGroupProperty(PropertyInterface('Outer Radius', _propertyGroup)); prop.os.setGroupProperty(PropertyInterface('Outer Roundness', _propertyGroup)); prop.pt.setGroupProperty(PropertyInterface('Points', _propertyGroup)); prop.p.setGroupProperty(PropertyInterface('Position', _propertyGroup)); prop.r.setGroupProperty(PropertyInterface('Rotation', _propertyGroup)); if (shape.ir) { prop.ir.setGroupProperty(PropertyInterface('Inner Radius', _propertyGroup)); prop.is.setGroupProperty(PropertyInterface('Inner Roundness', _propertyGroup)); } Object.defineProperties(interfaceFunction, { position: { get: ExpressionPropertyInterface(prop.p), }, rotation: { get: ExpressionPropertyInterface(prop.r), }, points: { get: ExpressionPropertyInterface(prop.pt), }, outerRadius: { get: ExpressionPropertyInterface(prop.or), }, outerRoundness: { get: ExpressionPropertyInterface(prop.os), }, innerRadius: { get: ExpressionPropertyInterface(prop.ir), }, innerRoundness: { get: ExpressionPropertyInterface(prop.is), }, _name: { value: shape.nm }, }); interfaceFunction.mn = shape.mn; return interfaceFunction; } function rectInterfaceFactory(shape, view, 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; } return null; } var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); var prop = view.sh.ty === 'tm' ? view.sh.prop : view.sh; interfaceFunction.propertyIndex = shape.ix; prop.p.setGroupProperty(PropertyInterface('Position', _propertyGroup)); prop.s.setGroupProperty(PropertyInterface('Size', _propertyGroup)); prop.r.setGroupProperty(PropertyInterface('Rotation', _propertyGroup)); Object.defineProperties(interfaceFunction, { position: { get: ExpressionPropertyInterface(prop.p), }, roundness: { get: ExpressionPropertyInterface(prop.r), }, size: { get: ExpressionPropertyInterface(prop.s), }, _name: { value: shape.nm }, }); interfaceFunction.mn = shape.mn; return interfaceFunction; } function roundedInterfaceFactory(shape, view, propertyGroup) { function interfaceFunction(value) { if (shape.r.ix === value || value === 'Round Corners 1') { return interfaceFunction.radius; } return null; } var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); var prop = view; interfaceFunction.propertyIndex = shape.ix; prop.rd.setGroupProperty(PropertyInterface('Radius', _propertyGroup)); Object.defineProperties(interfaceFunction, { radius: { get: ExpressionPropertyInterface(prop.rd), }, _name: { value: shape.nm }, }); interfaceFunction.mn = shape.mn; return interfaceFunction; } function repeaterInterfaceFactory(shape, view, propertyGroup) { function interfaceFunction(value) { if (shape.c.ix === value || value === 'Copies') { return interfaceFunction.copies; } if (shape.o.ix === value || value === 'Offset') { return interfaceFunction.offset; } return null; } var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); var prop = view; interfaceFunction.propertyIndex = shape.ix; prop.c.setGroupProperty(PropertyInterface('Copies', _propertyGroup)); prop.o.setGroupProperty(PropertyInterface('Offset', _propertyGroup)); Object.defineProperties(interfaceFunction, { copies: { get: ExpressionPropertyInterface(prop.c), }, offset: { get: ExpressionPropertyInterface(prop.o), }, _name: { value: shape.nm }, }); interfaceFunction.mn = shape.mn; return interfaceFunction; } return function (shapes, view, propertyGroup) { var interfaces; function _interfaceFunction(value) { if (typeof value === 'number') { value = value === undefined ? 1 : value; if (value === 0) { return propertyGroup; } return interfaces[value - 1]; } var i = 0; var len = interfaces.length; while (i < len) { if (interfaces[i]._name === value) { return interfaces[i]; } i += 1; } return null; } function parentGroupWrapper() { return propertyGroup; } _interfaceFunction.propertyGroup = propertyGroupFactory(_interfaceFunction, parentGroupWrapper); interfaces = iterateElements(shapes, view, _interfaceFunction.propertyGroup); _interfaceFunction.numProperties = interfaces.length; _interfaceFunction._name = 'Contents'; return _interfaceFunction; }; }()); const TextExpressionInterface = (function () { return function (elem) { var _prevValue; var _sourceText; function _thisLayerFunction(name) { switch (name) { case 'ADBE Text Document': return _thisLayerFunction.sourceText; default: return null; } } Object.defineProperty(_thisLayerFunction, 'sourceText', { get: function () { elem.textProperty.getValue(); var stringValue = elem.textProperty.currentData.t; if (stringValue !== _prevValue) { elem.textProperty.currentData.t = _prevValue; _sourceText = new String(stringValue); // eslint-disable-line no-new-wrappers // If stringValue is an empty string, eval returns undefined, so it has to be returned as a String primitive _sourceText.value = stringValue || new String(stringValue); // eslint-disable-line no-new-wrappers } return _sourceText; }, }); return _thisLayerFunction; }; }()); const getBlendMode = (function () { var blendModeEnums = { 0: 'source-over', 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', }; return function (mode) { return blendModeEnums[mode] || ''; }; }()); 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; var len = effects.length; var effectItem; for (i = 0; i < len; i += 1) { 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; var len = this.data.ef.length; var eff; var 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); } } }; function BaseElement() { } BaseElement.prototype = { checkMasks: function () { if (!this.data.hasMask) { return false; } var i = 0; var 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; } }, setBlendMode: function () { var blendModeValue = getBlendMode(this.data.bm); 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 = createElementID(); // 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; }, sourceRectAtTime: function () {}, }; /** * @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; var 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); } }, }; const FootageInterface = (function () { var outlineInterfaceFactory = (function (elem) { var currentPropertyName = ''; var currentProperty = elem.getFootageData(); function init() { currentPropertyName = ''; currentProperty = elem.getFootageData(); return searchProperty; } function searchProperty(value) { if (currentProperty[value]) { currentPropertyName = value; currentProperty = currentProperty[value]; if (typeof currentProperty === 'object') { return searchProperty; } return currentProperty; } var propertyNameIndex = value.indexOf(currentPropertyName); if (propertyNameIndex !== -1) { var index = parseInt(value.substr(propertyNameIndex + currentPropertyName.length), 10); currentProperty = currentProperty[index]; if (typeof currentProperty === 'object') { return searchProperty; } return currentProperty; } return ''; } return init; }); var dataInterfaceFactory = function (elem) { function interfaceFunction(value) { if (value === 'Outline') { return interfaceFunction.outlineInterface(); } return null; } interfaceFunction._name = 'Outline'; interfaceFunction.outlineInterface = outlineInterfaceFactory(elem); return interfaceFunction; }; return function (elem) { function _interfaceFunction(value) { if (value === 'Data') { return _interfaceFunction.dataInterface; } return null; } _interfaceFunction._name = 'Data'; _interfaceFunction.dataInterface = dataInterfaceFactory(elem); return _interfaceFunction; }; }()); function FootageElement(data, globalData, comp) { this.initFrame(); this.initRenderable(); this.assetData = globalData.getAssetData(data.refId); this.footageData = globalData.imageLoader.getAsset(this.assetData); this.initBaseData(data, globalData, comp); } FootageElement.prototype.prepareFrame = function () { }; extendPrototype([RenderableElement, BaseElement, FrameElement], FootageElement); FootageElement.prototype.getBaseElement = function () { return null; }; FootageElement.prototype.renderFrame = function () { }; FootageElement.prototype.destroy = function () { }; FootageElement.prototype.initExpressions = function () { this.layerInterface = FootageInterface(this); }; FootageElement.prototype.getFootageData = function () { return this.footageData; }; function AudioElement(data, globalData, comp) { this.initFrame(); this.initRenderable(); this.assetData = globalData.getAssetData(data.refId); this.initBaseData(data, globalData, comp); this._isPlaying = false; this._canPlay = false; var assetPath = this.globalData.getAssetsPath(this.assetData); this.audio = this.globalData.audioController.createAudio(assetPath); this._currentTime = 0; this.globalData.audioController.addAudio(this); this.tm = data.tm ? PropertyFactory.getProp(this, data.tm, 0, globalData.frameRate, this) : { _placeholder: true }; } AudioElement.prototype.prepareFrame = function (num) { this.prepareRenderableFrame(num, true); this.prepareProperties(num, true); if (!this.tm._placeholder) { var timeRemapped = this.tm.v; this._currentTime = timeRemapped; } else { this._currentTime = num / this.data.sr; } }; extendPrototype([RenderableElement, BaseElement, FrameElement], AudioElement); AudioElement.prototype.renderFrame = function () { if (this.isInRange && this._canPlay) { if (!this._isPlaying) { this.audio.play(); this.audio.seek(this._currentTime / this.globalData.frameRate); this._isPlaying = true; } else if (!this.audio.playing() || Math.abs(this._currentTime / this.globalData.frameRate - this.audio.seek()) > 0.1 ) { this.audio.seek(this._currentTime / this.globalData.frameRate); } } }; AudioElement.prototype.show = function () { // this.audio.play() }; AudioElement.prototype.hide = function () { this.audio.pause(); this._isPlaying = false; }; AudioElement.prototype.pause = function () { this.audio.pause(); this._isPlaying = false; this._canPlay = false; }; AudioElement.prototype.resume = function () { this._canPlay = true; }; AudioElement.prototype.setRate = function (rateValue) { this.audio.rate(rateValue); }; AudioElement.prototype.volume = function (volumeValue) { this.audio.volume(volumeValue); }; AudioElement.prototype.getBaseElement = function () { return null; }; AudioElement.prototype.destroy = function () { }; AudioElement.prototype.sourceRectAtTime = function () { }; AudioElement.prototype.initExpressions = function () { }; function BaseRenderer() {} BaseRenderer.prototype.checkLayers = function (num) { var i; var len = this.layers.length; var data; this.completeLayers = true; for (i = len - 1; i >= 0; i -= 1) { 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 6: return this.createAudio(layer); case 13: return this.createCamera(layer); case 15: return this.createFootage(layer); default: return this.createNull(layer); } }; BaseRenderer.prototype.createCamera = function () { throw new Error('You\'re using a 3d camera. Try the html renderer.'); }; BaseRenderer.prototype.createAudio = function (data) { return new AudioElement(data, this.globalData, this); }; BaseRenderer.prototype.createFootage = function (data) { return new FootageElement(data, this.globalData, this); }; BaseRenderer.prototype.buildAllItems = function () { var i; var 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; var len = newLayers.length; var j; var 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; var len = layers.length; while (i < len) { if (layers[i].ind == parentName) { // eslint-disable-line eqeqeq 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; var 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); } } }; BaseRenderer.prototype.setupGlobalData = function (animData, fontsContainer) { this.globalData.fontManager = new FontManager(); this.globalData.fontManager.addChars(animData.chars); this.globalData.fontManager.addFonts(animData.fonts, fontsContainer); this.globalData.getAssetData = this.animationItem.getAssetData.bind(this.animationItem); this.globalData.getAssetsPath = this.animationItem.getAssetsPath.bind(this.animationItem); this.globalData.imageLoader = this.animationItem.imagePreloader; this.globalData.audioController = this.animationItem.audioController; this.globalData.frameId = 0; this.globalData.frameRate = animData.fr; this.globalData.nm = animData.nm; this.globalData.compSize = { w: animData.w, h: animData.h, }; }; 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; var 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; var len = transforms.length; var 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 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; var len = this.masksProperties ? this.masksProperties.length : 0; this.viewData = createSizedArray(len); this.solidPath = ''; var path; var properties = this.masksProperties; var count = 0; var currentMasks = []; var j; var jLen; var layerId = createElementID(); var rect; var expansor; var feMorph; var x; var maskType = 'clipPath'; var maskRef = 'clip-path'; for (i = 0; i < len; i += 1) { if ((properties[i].mode !== 'a' && properties[i].mode !== 'n') || properties[i].inv || properties[i].o.k !== 100 || properties[i].o.x) { 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 || 0); rect.setAttribute('height', this.element.comp.data.h || 0); 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); } else { 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 = createElementID(); expansor = createNS('filter'); expansor.setAttribute('id', filterID); feMorph = createNS('feMorphology'); feMorph.setAttribute('operator', 'erode'); 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(' + getLocationHref() + '#' + 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(' + getLocationHref() + '#' + 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; var len = this.masksProperties.length; for (i = 0; i < len; i += 1) { 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('transform', finalMat.getInverseMatrix().to2dCSS()); } 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(' + getLocationHref() + '#' + 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; var 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; }; const filtersFactory = (function () { var ob = {}; ob.createFilter = createFilter; ob.createAlphaToLuminanceFilter = createAlphaToLuminanceFilter; function createFilter(filId, skipCoordinates) { var fil = createNS('filter'); fil.setAttribute('id', filId); if (skipCoordinates !== true) { 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; }()); const 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; }()); 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; var groupPath; var i; var 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 = createElementID(); 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(' + getLocationHref() + '#' + id + ')'); while (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; var len = this.paths.length; var mask; var path; for (i = 0; i < len; i += 1) { if (this.paths[i].m !== -1) { 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) * 0.01; var e = Math.max(this.filterManager.effectElements[7].p.v, this.filterManager.effectElements[8].p.v) * 0.01; 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 * 0.01; 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 * 0.01 + ' '; } dasharrayValue += '0 ' + l * 10 + ' 0 0'; } else { dasharrayValue = '1 ' + this.filterManager.effectElements[4].p.v * 2 * this.filterManager.effectElements[9].p.v * 0.01; } 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(' + bmFloor(color[0] * 255) + ',' + bmFloor(color[1] * 255) + ',' + bmFloor(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'); 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; pos += 1; cnt += 256 / (segments - 1); } return table.join(' '); }; SVGProLevelsFilter.prototype.renderFrame = function (forceRender) { if (forceRender || this.filterManager._mdf) { var val; 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) { var filterSize = filterManager.container.globalData.renderConfig.filterSize; filter.setAttribute('x', filterSize.x); filter.setAttribute('y', filterSize.y); filter.setAttribute('width', filterSize.width); filter.setAttribute('height', filterSize.height); 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 = []; 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; var 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; var 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 = createElementID(); 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 elements = this.elem.comp.elements; var i = 0; var len = elements.length; while (i < len) { if (elements[i] && elements[i].data.ind === ind) { this.setElementAsMask(this.elem, elements[i]); } i += 1; } this.initialized = true; }; SVGMatte3Effect.prototype.renderFrame = function () { if (!this.initialized) { this.initialize(); } }; function SVGGaussianBlurEffect(filter, filterManager) { // Outset the filter region by 100% on all sides to accommodate blur expansion. filter.setAttribute('x', '-100%'); filter.setAttribute('y', '-100%'); filter.setAttribute('width', '300%'); filter.setAttribute('height', '300%'); this.filterManager = filterManager; var feGaussianBlur = createNS('feGaussianBlur'); filter.appendChild(feGaussianBlur); this.feGaussianBlur = feGaussianBlur; } SVGGaussianBlurEffect.prototype.renderFrame = function (forceRender) { if (forceRender || this.filterManager._mdf) { // Empirical value, matching AE's blur appearance. var kBlurrinessToSigma = 0.3; var sigma = this.filterManager.effectElements[0].p.v * kBlurrinessToSigma; // Dimensions mapping: // // 1 -> horizontal & vertical // 2 -> horizontal only // 3 -> vertical only // var dimensions = this.filterManager.effectElements[1].p.v; var sigmaX = (dimensions == 3) ? 0 : sigma; // eslint-disable-line eqeqeq var sigmaY = (dimensions == 2) ? 0 : sigma; // eslint-disable-line eqeqeq this.feGaussianBlur.setAttribute('stdDeviation', sigmaX + ' ' + sigmaY); // Repeat edges mapping: // // 0 -> off -> duplicate // 1 -> on -> wrap var edgeMode = (this.filterManager.effectElements[2].p.v == 1) ? 'wrap' : 'duplicate'; // eslint-disable-line eqeqeq this.feGaussianBlur.setAttribute('edgeMode', edgeMode); } }; var registeredEffects = {}; function SVGEffects(elem) { var i; var len = elem.data.ef ? elem.data.ef.length : 0; var filId = createElementID(); var fil = filtersFactory.createFilter(filId, true); var count = 0; this.filters = []; var filterManager; for (i = 0; i < len; i += 1) { filterManager = null; var type = elem.data.ef[i].ty; if (registeredEffects[type]) { var Effect = registeredEffects[type].effect; filterManager = new Effect(fil, elem.effectsManager.effectElements[i], elem); if (registeredEffects[type].countsAsEffect) { count += 1; } } 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); } else if (elem.data.ef[i].ty === 29) { count += 1; filterManager = new SVGGaussianBlurEffect(fil, elem.effectsManager.effectElements[i]); } if (filterManager) { this.filters.push(filterManager); } } if (count) { elem.globalData.defs.appendChild(fil); elem.layerElement.setAttribute('filter', 'url(' + getLocationHref() + '#' + filId + ')'); } if (this.filters.length) { elem.addRenderableComponent(this); } } SVGEffects.prototype.renderFrame = function (_isFirstFrame) { var i; var len = this.filters.length; for (i = 0; i < len; i += 1) { this.filters[i].renderFrame(_isFirstFrame); } }; function registerEffect(id, effect, countsAsEffect) { registeredEffects[id] = { effect, countsAsEffect, }; } 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; var fil; var gg; if (this.data.td) { if (this.data.td == 3 || this.data.td == 1) { // eslint-disable-line eqeqeq var masker = createNS('mask'); masker.setAttribute('id', this.layerId); masker.setAttribute('mask-type', this.data.td == 3 ? 'luminance' : 'alpha'); // eslint-disable-line eqeqeq 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) { // eslint-disable-line eqeqeq masker.setAttribute('mask-type', 'luminance'); filId = createElementID(); 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(' + getLocationHref() + '#' + filId + ')'); } } else if (this.data.td == 2) { // eslint-disable-line eqeqeq var maskGroup = createNS('mask'); maskGroup.setAttribute('id', this.layerId); maskGroup.setAttribute('mask-type', 'alpha'); var maskGrouper = createNS('g'); maskGroup.appendChild(maskGrouper); filId = createElementID(); fil = filtersFactory.createFilter(filId); /// / // This solution doesn't work on Android when meta tag with viewport attribute is set /* 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(' + getLocationHref() + '#' + 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 = createElementID(); cp.setAttribute('id', clipId); cp.appendChild(pt); this.globalData.defs.appendChild(cp); if (this.checkMasks()) { var cpGroup = createNS('g'); cpGroup.setAttribute('clip-path', 'url(' + getLocationHref() + '#' + 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(' + getLocationHref() + '#' + clipId + ')'); } } if (this.data.bm !== 0) { this.setBlendMode(); } }, 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; }, createRenderableComponents: function () { this.maskManager = new MaskElement(this.data, this, this.globalData); this.renderableEffectsManager = new SVGEffects(this); }, setMatte: function (id) { if (!this.matteElement) { return; } this.matteElement.setAttribute('mask', 'url(' + getLocationHref() + '#' + id + ')'); }, }; /** * @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, []); } }, }; 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.createRenderableComponents(); this.createContent(); this.hide(); }, hide: function () { // console.log('HIDE', this); if (!this.hidden && (!this.isInRange || this.isTransparent)) { var elem = this.baseElement || this.layerElement; elem.style.display = 'none'; this.hidden = true; } }, show: function () { // console.log('SHOW', this); 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 IImageElement(data, globalData, comp) { this.assetData = globalData.getAssetData(data.refId); this.initElement(data, globalData, comp); this.sourceRect = { top: 0, left: 0, width: this.assetData.w, height: this.assetData.h, }; } 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', this.assetData.pr || this.globalData.renderConfig.imagePreserveAspectRatio); this.innerElem.setAttributeNS('http://www.w3.org/1999/xlink', 'href', assetPath); this.layerElement.appendChild(this.innerElem); }; IImageElement.prototype.sourceRectAtTime = function () { return this.sourceRect; }; function ProcessedElement(element, position) { this.elem = element; this.pos = position; } function IShapeElement() { } IShapeElement.prototype = { addShapeToModifiers: function (data) { var i; var len = this.shapeModifiers.length; for (i = 0; i < len; i += 1) { this.shapeModifiers[i].addShape(data); } }, isShapeInAnimatedModifiers: function (data) { var i = 0; var 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; var len = this.shapes.length; for (i = 0; i < len; i += 1) { this.shapes[i].sh.reset(); } len = this.shapeModifiers.length; var shouldBreakProcess; for (i = len - 1; i >= 0; i -= 1) { shouldBreakProcess = this.shapeModifiers[i].processShapes(this._isFirstFrame); // workaround to fix cases where a repeater resets the shape so the following processes get called twice // TODO: find a better solution for this if (shouldBreakProcess) { break; } } }, searchProcessedElement: function (elem) { var elements = this.processedElements; var i = 0; var 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); }, }; const lineCapEnum = { 1: 'butt', 2: 'round', 3: 'square', }; const lineJoinEnum = { 1: 'miter', 2: 'round', 3: 'bevel', }; 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; var 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 SVGStyleData(data, level) { this.data = data; this.type = data.ty; this.d = ''; this.lvl = level; this._mdf = false; this.closed = data.hd === true; this.pElem = createNS('path'); this.msElem = null; } SVGStyleData.prototype.reset = function () { this.d = ''; this._mdf = false; }; function DashProperty(elem, data, renderer, container) { 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(container); var i; var len = data.length || 0; var 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; var 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 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 SVGNoStyleData(elem, data, styleOb) { this.initDynamicPropertyContainer(elem); this.getValue = this.iterateDynamicProperties; this.style = styleOb; } extendPrototype([DynamicPropertyContainer], SVGNoStyleData); function GradientProperty(elem, data, container) { 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(container); 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; var len = this.o.length / 2; var 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; var 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; var len = this.data.p * 4; var mult; var 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); 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 = createElementID(); var gfill = createNS(data.t === 1 ? 'linearGradient' : 'radialGradient'); gfill.setAttribute('id', gradientId); gfill.setAttribute('spreadMethod', 'pad'); gfill.setAttribute('gradientUnits', 'userSpaceOnUse'); var stops = []; var stop; var j; var 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(' + getLocationHref() + '#' + gradientId + ')'); this.gf = gfill; this.cst = stops; }; SVGGradientFillStyleData.prototype.setGradientOpacity = function (data, styleOb) { if (this.g._hasOpacity && !this.g._collapsable) { var stop; var j; var jLen; var mask = createNS('mask'); var maskElement = createNS('path'); mask.appendChild(maskElement); var opacityId = createElementID(); var maskId = createElementID(); 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(' + getLocationHref() + '#' + opacityId + ')'); if (data.ty === 'gs') { maskElement.setAttribute('stroke-linecap', lineCapEnum[data.lc || 2]); maskElement.setAttribute('stroke-linejoin', lineJoinEnum[data.lj || 2]); if (data.lj === 1) { maskElement.setAttribute('stroke-miterlimit', data.ml); } } 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'); } 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; } const buildShapeString = function (pathNodes, length, closed, mat) { if (length === 0) { return ''; } var _o = pathNodes.o; var _i = pathNodes.i; var _v = pathNodes.v; var i; var 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; }; const SVGElementsRenderer = (function () { var _identityMatrix = new Matrix(); var _matrixHelper = new Matrix(); var ob = { createRenderFunction: createRenderFunction, }; function createRenderFunction(data) { 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; case 'no': return renderNoop; default: return null; } } 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 renderNoop() { } function renderPath(styleData, itemData, isFirstFrame) { var j; var jLen; var pathStringTransformed; var redraw; var pathNodes; var l; var lLen = itemData.styles.length; var lvl = itemData.lvl; var paths; var mat; var props; var iterations; var 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 -= 1; k -= 1; } 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 -= 1; k -= 1; } } } 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 += styleData.hd === true ? '' : 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(' + bmFloor(itemData.c.v[0]) + ',' + bmFloor(itemData.c.v[1]) + ',' + bmFloor(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; var 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; var i; var len; var 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; if (percent >= 1) { percent = 0.99; } else if (percent <= -1) { percent = -0.99; } 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(' + bmFloor(itemData.c.v[0]) + ',' + bmFloor(itemData.c.v[1]) + ',' + bmFloor(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 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; var len = this.shapes.length; var shape; var j; var jLen = this.stylesList.length; var style; 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; var 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(' + getLocationHref() + '#' + elementData.maskId + ')'); } } else if (data.ty === 'no') { elementData = new SVGNoStyleData(this, data, styleOb); } if (data.ty === 'st' || data.ty === 'gs') { pathElement.setAttribute('stroke-linecap', lineCapEnum[data.lc || 2]); pathElement.setAttribute('stroke-linejoin', lineJoinEnum[data.lj || 2]); 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); } if (data.bm) { pathElement.style['mix-blend-mode'] = getBlendMode(data.bm); } 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); } if (data.cl) { elementData.gr.setAttribute('class', data.cl); } if (data.bm) { elementData.gr.style['mix-blend-mode'] = getBlendMode(data.bm); } 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; var 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; var 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; var 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; var len = arr.length - 1; var j; var jLen; var ownStyles = []; var ownModifiers = []; var currentTransform; var modifier; var 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' || arr[i].ty === 'no') { if (!processedPos) { itemsData[i] = this.createStyleElement(arr[i], level); } else { itemsData[i].style.closed = false; } if (arr[i]._render) { if (itemsData[i].style.pElem.parentNode !== container) { 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) { if (itemsData[i].gr.parentNode !== container) { 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' || arr[i].ty === 'pb') { 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; var 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; var len = this.animatedContents.length; var animatedContent; for (i = 0; i < len; i += 1) { animatedContent = this.animatedContents[i]; if ((this._isFirstFrame || animatedContent.element._isAnimated) && animatedContent.data !== true) { animatedContent.fn(animatedContent.data, animatedContent.element, this._isFirstFrame); } } }; SVGShapeElement.prototype.destroy = function () { this.destroyBaseElement(); this.shapesData = null; this.itemsData = null; }; 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 = 0; 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, __complete: false, }; this.copyData(this.currentData, this.data.d.k[0].s); if (!this.searchProperty()) { this.completeTextData(this.currentData); } } TextProperty.prototype.defaultBoxWidth = [0, 0]; TextProperty.prototype.copyData = function (obj, data) { for (var s in data) { if (Object.prototype.hasOwnProperty.call(data, s)) { obj[s] = data[s]; } } return obj; }; TextProperty.prototype.setCurrentData = function (data) { if (!data.__complete) { this.completeTextData(data); } this.currentData = data; this.currentData.boxWidth = this.currentData.boxWidth || this.defaultBoxWidth; this._mdf = true; }; 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; } this.currentData.t = this.data.d.k[this.keysIndex].s.t; var currentValue = this.currentData; var currentIndex = this.keysIndex; if (this.lock) { this.setCurrentData(this.currentData); return; } this.lock = true; this._mdf = false; var i; var len = this.effectsSequence.length; var finalValue = _finalValue || this.data.d.k[this.keysIndex].s; for (i = 0; i < len; i += 1) { // Checking if index changed to prevent creating a new object every time the expression updates. if (currentIndex !== this.keysIndex) { finalValue = this.effectsSequence[i](finalValue, finalValue.t); } else { finalValue = this.effectsSequence[i](this.currentData, finalValue.t); } } if (currentValue !== finalValue) { this.setCurrentData(finalValue); } this.v = this.currentData; this.pv = this.v; this.lock = false; this.frameId = this.elem.globalData.frameId; }; TextProperty.prototype.getKeyframeValue = function () { var textKeys = this.data.d.k; var frameNum = this.elem.comp.renderedFrame; var i = 0; var len = textKeys.length; while (i <= len - 1) { if (i === len - 1 || textKeys[i + 1].t > frameNum) { break; } i += 1; } if (this.keysIndex !== i) { this.keysIndex = i; } return this.data.d.k[this.keysIndex].s; }; TextProperty.prototype.buildFinalText = function (text) { var charactersArray = []; var i = 0; var len = text.length; var charCode; var secondCharCode; var shouldCombine = false; while (i < len) { charCode = text.charCodeAt(i); if (FontManager.isCombinedCharacter(charCode)) { charactersArray[charactersArray.length - 1] += text.charAt(i); } else if (charCode >= 0xD800 && charCode <= 0xDBFF) { secondCharCode = text.charCodeAt(i + 1); if (secondCharCode >= 0xDC00 && secondCharCode <= 0xDFFF) { if (shouldCombine || FontManager.isModifier(charCode, secondCharCode)) { charactersArray[charactersArray.length - 1] += text.substr(i, 2); shouldCombine = false; } else { charactersArray.push(text.substr(i, 2)); } i += 1; } else { charactersArray.push(text.charAt(i)); } } else if (charCode > 0xDBFF) { secondCharCode = text.charCodeAt(i + 1); if (FontManager.isZeroWidthJoiner(charCode, secondCharCode)) { shouldCombine = true; charactersArray[charactersArray.length - 1] += text.substr(i, 2); i += 1; } else { charactersArray.push(text.charAt(i)); } } else if (FontManager.isZeroWidthJoiner(charCode)) { charactersArray[charactersArray.length - 1] += text.charAt(i); shouldCombine = true; } 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; var len; var newLineFlag; var index = 0; var val; var anchorGrouping = data.m.g; var currentSize = 0; var currentPos = 0; var currentLine = 0; var lineWidths = []; var lineWidth = 0; var maxLineWidth = 0; var j; var jLen; var fontData = fontManager.getFontByName(documentData.f); var charData; var cLength = 0; var fontProps = getFontProperties(fontData); documentData.fWeight = fontProps.weight; documentData.fStyle = fontProps.style; documentData.finalSize = documentData.s; documentData.finalText = this.buildFinalText(documentData.t); len = documentData.finalText.length; documentData.finalLineHeight = documentData.lh; var trackingOffset = (documentData.tr / 1000) * documentData.finalSize; var charCode; if (documentData.sz) { var flag = true; var boxWidth = documentData.sz[0]; var boxHeight = documentData.sz[1]; var currentHeight; var 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) { charCode = finalText[i].charCodeAt(0); newLineFlag = false; if (finalText[i] === ' ') { lastSpaceIndex = i; } else if (charCode === 13 || charCode === 3) { 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]; charCode = currentChar.charCodeAt(0); if (charCode === 13 || charCode === 3) { uncollapsedSpaces = 0; lineWidths.push(lineWidth); maxLineWidth = lineWidth > maxLineWidth ? lineWidth : maxLineWidth; lineWidth = -2 * trackingOffset; val = ''; newLineFlag = true; currentLine += 1; } else { val = currentChar; } 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) { // eslint-disable-line eqeqeq currentSize += cLength; if (val === '' || val === ' ' || i === len - 1) { if (val === '' || val === ' ') { 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) { // eslint-disable-line eqeqeq 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; var animatorData; var letterData; jLen = animators.length; var based; var ind; var 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 !== ' ') || (based == 3 && (letterData.n || letterData.val == ' ' || i == len - 1)) || (based == 4 && (letterData.n || i == len - 1))) { // eslint-disable-line eqeqeq if (animatorData.s.rn === 1) { indexes.push(ind); } ind += 1; } } data.a[j].s.totalChars = ind; var currentInd = -1; var newInd; if (animatorData.s.rn === 1) { for (i = 0; i < len; i += 1) { letterData = letters[i]; if (currentInd != letterData.anIndexes[j]) { // eslint-disable-line eqeqeq 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 : index; var dData = this.copyData({}, this.data.d.k[index].s); dData = this.copyData(dData, newData); this.data.d.k[index].s = dData; this.recalculate(index); this.elem.addDynamicProperty(this); }; TextProperty.prototype.recalculate = function (index) { var dData = this.data.d.k[index].s; dData.__complete = false; this.keysIndex = 0; this._isFirstFrame = true; this.getValue(dData); }; TextProperty.prototype.canResizeFont = function (_canResize) { this.canResize = _canResize; this.recalculate(this.keysIndex); this.elem.addDynamicProperty(this); }; TextProperty.prototype.setMinimumFontSize = function (_fontValue) { this.minimumFontSize = Math.floor(_fontValue) || 1; this.recalculate(this.keysIndex); this.elem.addDynamicProperty(this); }; const TextSelectorProp = (function () { var max = Math.max; var min = Math.min; var floor = Math.floor; function TextSelectorPropFactory(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.sm = PropertyFactory.getProp(elem, data.sm || { k: 100 }, 0, 0, this); this.a = PropertyFactory.getProp(elem, data.a, 0, 0.01, this); if (!this.dynamicProperties.length) { this.getValue(); } } TextSelectorPropFactory.prototype = { getMult: function (ind) { if (this._currentTextLength !== this.elem.textProperty.currentData.l.length) { this.getValue(); } var x1 = 0; var y1 = 0; var x2 = 1; var y2 = 1; if (this.ne.v > 0) { x1 = this.ne.v / 100.0; } else { y1 = -this.ne.v / 100.0; } if (this.xe.v > 0) { x2 = 1.0 - this.xe.v / 100.0; } else { y2 = 1.0 + this.xe.v / 100.0; } var easer = BezierFactory.getBezierEasing(x1, y1, x2, y2).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; // eslint-disable-line } mult = easer(mult); } else { if (ind >= floor(s)) { if (ind - s < 0) { mult = max(0, min(min(e, 1) - (s - ind), 1)); } else { mult = max(0, min(e - ind, 1)); } } mult = easer(mult); } // Smoothness implementation. // The smoothness represents a reduced range of the original [0; 1] range. // if smoothness is 25%, the new range will be [0.375; 0.625] // Steps are: // - find the lower value of the new range (threshold) // - if multiplier is smaller than that value, floor it to 0 // - if it is larger, // - subtract the threshold // - divide it by the smoothness (this will return the range to [0; 1]) // Note: If it doesn't work on some scenarios, consider applying it before the easer. if (this.sm.v !== 100) { var smoothness = this.sm.v * 0.01; if (smoothness === 0) { smoothness = 0.00000001; } var threshold = 0.5 - smoothness * 0.5; if (mult < threshold) { mult = 0; } else { mult = (mult - threshold) / smoothness; if (mult > 1) { mult = 1; } } } 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.data.totalChars; 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], TextSelectorPropFactory); function getTextSelectorProp(elem, data, arr) { return new TextSelectorPropFactory(elem, data, arr); } return { getTextSelectorProp: getTextSelectorProp, }; }()); function TextAnimatorDataProperty(elem, animatorProps, container) { var defaultData = { propType: false }; var getProp = PropertyFactory.getProp; var textAnimatorAnimatables = animatorProps.a; this.a = { r: textAnimatorAnimatables.r ? getProp(elem, textAnimatorAnimatables.r, 0, degToRads, container) : defaultData, rx: textAnimatorAnimatables.rx ? getProp(elem, textAnimatorAnimatables.rx, 0, degToRads, container) : defaultData, ry: textAnimatorAnimatables.ry ? getProp(elem, textAnimatorAnimatables.ry, 0, degToRads, container) : defaultData, sk: textAnimatorAnimatables.sk ? getProp(elem, textAnimatorAnimatables.sk, 0, degToRads, container) : defaultData, sa: textAnimatorAnimatables.sa ? getProp(elem, textAnimatorAnimatables.sa, 0, degToRads, container) : defaultData, s: textAnimatorAnimatables.s ? getProp(elem, textAnimatorAnimatables.s, 1, 0.01, container) : defaultData, a: textAnimatorAnimatables.a ? getProp(elem, textAnimatorAnimatables.a, 1, 0, container) : defaultData, o: textAnimatorAnimatables.o ? getProp(elem, textAnimatorAnimatables.o, 0, 0.01, container) : defaultData, p: textAnimatorAnimatables.p ? getProp(elem, textAnimatorAnimatables.p, 1, 0, container) : defaultData, sw: textAnimatorAnimatables.sw ? getProp(elem, textAnimatorAnimatables.sw, 0, 0, container) : defaultData, sc: textAnimatorAnimatables.sc ? getProp(elem, textAnimatorAnimatables.sc, 1, 0, container) : defaultData, fc: textAnimatorAnimatables.fc ? getProp(elem, textAnimatorAnimatables.fc, 1, 0, container) : defaultData, fh: textAnimatorAnimatables.fh ? getProp(elem, textAnimatorAnimatables.fh, 0, 0, container) : defaultData, fs: textAnimatorAnimatables.fs ? getProp(elem, textAnimatorAnimatables.fs, 0, 0.01, container) : defaultData, fb: textAnimatorAnimatables.fb ? getProp(elem, textAnimatorAnimatables.fb, 0, 0.01, container) : defaultData, t: textAnimatorAnimatables.t ? getProp(elem, textAnimatorAnimatables.t, 0, 0, container) : defaultData, }; this.s = TextSelectorProp.getTextSelectorProp(elem, animatorProps.s, container); this.s.t = animatorProps.s.t; } 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; var len = this._textData.a.length; var 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 = { a: getProp(this._elem, this._textData.p.a, 0, 0, this), f: getProp(this._elem, this._textData.p.f, 0, 0, this), l: getProp(this._elem, this._textData.p.l, 0, 0, this), r: getProp(this._elem, this._textData.p.r, 0, 0, this), p: getProp(this._elem, this._textData.p.p, 0, 0, this), 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 xPos; var yPos; var i; var len; var letters = documentData.l; var pathInfo; var currentLength; var currentPoint; var segmentLength; var flag; var pointInd; var segmentInd; var prevPoint; var points; var segments; var partialLength; var totalLength; var perc; var tanAngle; var mask; if (this._hasMaskedPath) { mask = this._pathData.m; if (!this._pathData.n || this._pathData._mdf) { var paths = mask.v; if (this._pathData.r.v) { paths = paths.reverse(); } // TODO: release bezier data cached from previous pathInfo: this._pathData.pi pathInfo = { tLength: 0, segments: [], }; len = paths._length - 1; var bezierData; totalLength = 0; for (i = 0; i < len; i += 1) { bezierData = bez.buildBezierData(paths.v[i], paths.v[i + 1], [paths.o[i][0] - paths.v[i][0], paths.o[i][1] - paths.v[i][1]], [paths.i[i + 1][0] - paths.v[i + 1][0], paths.i[i + 1][1] - paths.v[i + 1][1]]); pathInfo.tLength += bezierData.segmentLength; pathInfo.segments.push(bezierData); totalLength += bezierData.segmentLength; } i = len; if (mask.v.c) { bezierData = bez.buildBezierData(paths.v[i], paths.v[0], [paths.o[i][0] - paths.v[i][0], paths.o[i][1] - paths.v[i][1]], [paths.i[0][0] - paths.v[0][0], paths.i[0][1] - paths.v[0][1]]); pathInfo.tLength += bezierData.segmentLength; pathInfo.segments.push(bezierData); totalLength += 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].points; pointInd = points.length - 1; while (currentLength < 0) { currentLength += points[pointInd].partialLength; pointInd -= 1; if (pointInd < 0) { segmentInd -= 1; points = segments[segmentInd].points; pointInd = points.length - 1; } } } points = segments[segmentInd].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; var animatorSelector; var j; var jLen; var letterValue; jLen = animators.length; var mult; var ind = -1; var offf; var xPathPos; var yPathPos; var initPathPos = currentLength; var initSegmentInd = segmentInd; var initPointInd = pointInd; var currentLine = -1; var elemOpacity; var sc; var sw; var fc; var k; var letterSw; var letterSc; var letterFc; var letterM = ''; var letterP = this.defaultPropsArray; var 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; if (this._hasMaskedPath) { segmentInd = initSegmentInd; pointInd = initPointInd; points = segments[segmentInd].points; prevPoint = points[pointInd - 1]; currentPoint = points[pointInd]; partialLength = currentPoint.partialLength; segmentLength = 0; } letterM = ''; letterFc = ''; letterSw = ''; letterO = ''; 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; default: 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) * 0.005; 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; // Force alignment only works with a single line for now if (this._pathData.a.v) { currentLength = letters[0].an * 0.5 + ((totalLength - this._pathData.f.v - letters[0].an * 0.5 - letters[letters.length - 1].an * 0.5) * ind) / (len - 1); currentLength += this._pathData.f.v; } 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) * 0.005, -(alignment[1] * yOff) * 0.01); 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].points; } else { segmentLength -= currentPoint.partialLength; points = null; } } else { points = segments[segmentInd].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) * 0.005, (-alignment[1] * yOff) * 0.01, 0); } 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; } } } } 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] += (animatorProps.sc.v[k] - sc[k]) * mult[0]; } else { 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] += (animatorProps.fc.v[k] - fc[k]) * mult[0]; } else { 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) * 0.01 + yPos, 0); if (this._pathData.p.v) { 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) * 0.005; if (letters[i + 1] && ind !== letters[i + 1].ind) { currentLength += letters[i].an / 2; currentLength += (documentData.tr * 0.001) * 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; default: break; } matrixHelper.translate(0, -documentData.ls); matrixHelper.translate(offf, 0, 0); matrixHelper.translate((alignment[0] * letters[i].an) * 0.005, (alignment[1] * yOff) * 0.01, 0); xPos += letters[i].l + (documentData.tr * 0.001) * 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 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.createRenderableComponents(); 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; var jLen = shapes.length; var pathNodes; var shapeStr = ''; for (j = 0; j < jLen; j += 1) { if (shapes[j].ty === 'sh') { 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; default: 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 () { }; var emptyShapeData = { shapes: [], }; function SVGTextLottieElement(data, globalData, comp) { this.textSpans = []; this.renderType = 'svg'; this.initElement(data, globalData, comp); } extendPrototype([BaseElement, TransformElement, SVGBaseElement, HierarchyElement, FrameElement, RenderableDOMElement, ITextElement], SVGTextLottieElement); SVGTextLottieElement.prototype.createContent = function () { if (this.data.singleShape && !this.globalData.fontManager.chars) { this.textContainer = createNS('text'); } }; SVGTextLottieElement.prototype.buildTextContents = function (textArray) { var i = 0; var len = textArray.length; var textContents = []; var currentTextContent = ''; while (i < len) { if (textArray[i] === String.fromCharCode(13) || textArray[i] === String.fromCharCode(3)) { textContents.push(currentTextContent); currentTextContent = ''; } else { currentTextContent += textArray[i]; } i += 1; } textContents.push(currentTextContent); return textContents; }; SVGTextLottieElement.prototype.buildNewText = function () { this.addDynamicProperty(this); var i; var 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; var fStyle = documentData.fStyle; this.layerElement.setAttribute('font-style', fStyle); this.layerElement.setAttribute('font-weight', fWeight); } this.layerElement.setAttribute('aria-label', documentData.t); var letters = documentData.l || []; var usesGlyphs = !!this.globalData.fontManager.chars; len = letters.length; var tSpan; var matrixHelper = this.mHelper; var shapeStr = ''; var singleShape = this.data.singleShape; var xPos = 0; var yPos = 0; var firstLine = true; var trackingOffset = documentData.tr * 0.001 * 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; default: justify = 'start'; 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].span || createNS('tspan'); tSpan.textContent = textContent[i]; tSpan.setAttribute('x', 0); tSpan.setAttribute('y', yPos); tSpan.style.display = 'inherit'; tElement.appendChild(tSpan); if (!this.textSpans[i]) { this.textSpans[i] = { span: null, glyph: null, }; } this.textSpans[i].span = tSpan; yPos += documentData.finalLineHeight; } this.layerElement.appendChild(tElement); } else { var cachedSpansLength = this.textSpans.length; var charData; for (i = 0; i < len; i += 1) { if (!this.textSpans[i]) { this.textSpans[i] = { span: null, childSpan: null, glyph: null, }; } if (!usesGlyphs || !singleShape || i === 0) { tSpan = cachedSpansLength > i ? this.textSpans[i].span : createNS(usesGlyphs ? 'g' : 'text'); if (cachedSpansLength <= i) { tSpan.setAttribute('stroke-linecap', 'butt'); tSpan.setAttribute('stroke-linejoin', 'round'); tSpan.setAttribute('stroke-miterlimit', '4'); this.textSpans[i].span = tSpan; if (usesGlyphs) { var childSpan = createNS('g'); tSpan.appendChild(childSpan); this.textSpans[i].childSpan = childSpan; } this.textSpans[i].span = 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); var glyphElement; if (charData.t === 1) { glyphElement = new SVGCompElement(charData.data, this.globalData, this); } else { var data = emptyShapeData; if (charData.data && charData.data.shapes) { data = charData.data; } glyphElement = new SVGShapeElement(data, this.globalData, this); } this.textSpans[i].glyph = glyphElement; glyphElement._debug = true; glyphElement.prepareFrame(0); glyphElement.renderFrame(); this.textSpans[i].childSpan.appendChild(glyphElement.layerElement); this.textSpans[i].childSpan.setAttribute('transform', 'scale(' + documentData.finalSize / 100 + ',' + documentData.finalSize / 100 + ')'); } 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) { tSpan.setAttribute('d', shapeStr); } } while (i < this.textSpans.length) { this.textSpans[i].span.style.display = 'none'; i += 1; } this._sizeChanged = true; }; SVGTextLottieElement.prototype.sourceRectAtTime = function () { 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; }; SVGTextLottieElement.prototype.getValue = function () { var i; var len = this.textSpans.length; var glyphElement; this.renderedFrame = this.comp.renderedFrame; for (i = 0; i < len; i += 1) { glyphElement = this.textSpans[i].glyph; if (glyphElement) { glyphElement.prepareFrame(this.comp.renderedFrame - this.data.st); if (glyphElement._mdf) { this._mdf = true; } } } }; SVGTextLottieElement.prototype.renderInnerContent = function () { if (!this.data.singleShape || this._mdf) { this.textAnimator.getMeasures(this.textProperty.currentData, this.lettersChangedFlag); if (this.lettersChangedFlag || this.textAnimator.lettersChangedFlag) { this._sizeChanged = true; var i; var len; var renderedLetters = this.textAnimator.renderedLetters; var letters = this.textProperty.currentData.l; len = letters.length; var renderedLetter; var textSpan; var glyphElement; for (i = 0; i < len; i += 1) { if (!letters[i].n) { renderedLetter = renderedLetters[i]; textSpan = this.textSpans[i].span; glyphElement = this.textSpans[i].glyph; if (glyphElement) { glyphElement.renderFrame(); } 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 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 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 SVGRendererBase() { } extendPrototype([BaseRenderer], SVGRendererBase); SVGRendererBase.prototype.createNull = function (data) { return new NullElement(data, this.globalData, this); }; SVGRendererBase.prototype.createShape = function (data) { return new SVGShapeElement(data, this.globalData, this); }; SVGRendererBase.prototype.createText = function (data) { return new SVGTextLottieElement(data, this.globalData, this); }; SVGRendererBase.prototype.createImage = function (data) { return new IImageElement(data, this.globalData, this); }; SVGRendererBase.prototype.createSolid = function (data) { return new ISolidElement(data, this.globalData, this); }; SVGRendererBase.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)'; this.svgElement.style.contentVisibility = this.renderConfig.contentVisibility; } if (this.renderConfig.className) { this.svgElement.setAttribute('class', this.renderConfig.className); } if (this.renderConfig.id) { this.svgElement.setAttribute('id', this.renderConfig.id); } if (this.renderConfig.focusable !== undefined) { this.svgElement.setAttribute('focusable', this.renderConfig.focusable); } 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.setupGlobalData(animData, defs); this.globalData.progressiveLoad = this.renderConfig.progressiveLoad; 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 = createElementID(); maskElement.setAttribute('id', maskId); maskElement.appendChild(rect); this.layerElement.setAttribute('clip-path', 'url(' + getLocationHref() + '#' + maskId + ')'); defs.appendChild(maskElement); this.layers = animData.layers; this.elements = createSizedArray(animData.layers.length); }; SVGRendererBase.prototype.destroy = function () { if (this.animationItem.wrapper) { this.animationItem.wrapper.innerText = ''; } this.layerElement = null; this.globalData.defs = null; var i; var len = this.layers ? this.layers.length : 0; for (i = 0; i < len; i += 1) { if (this.elements[i]) { this.elements[i].destroy(); } } this.elements.length = 0; this.destroyed = true; this.animationItem = null; }; SVGRendererBase.prototype.updateContainerSize = function () { }; SVGRendererBase.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 (getExpressionsPlugin()) { 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); } } }; SVGRendererBase.prototype.checkPendingElements = function () { while (this.pendingElements.length) { var element = this.pendingElements.pop(); element.checkParenting(); if (element.data.tt) { var i = 0; var len = this.elements.length; while (i < len) { if (this.elements[i] === element) { element.setMatte(this.elements[i - 1].layerId); break; } i += 1; } } } }; SVGRendererBase.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; var len = this.layers.length; if (!this.completeLayers) { this.checkLayers(num); } for (i = len - 1; i >= 0; i -= 1) { 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(); } } } }; SVGRendererBase.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); } }; SVGRendererBase.prototype.hide = function () { this.layerElement.style.display = 'none'; }; SVGRendererBase.prototype.show = function () { this.layerElement.style.display = 'block'; }; 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.createRenderableComponents(); 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; var len = this.elements.length; if (!this.completeLayers) { this.checkLayers(this.renderedFrame); } // This iteration needs to be backwards because of how expressions connect between each other for (i = len - 1; i >= 0; 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; var 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; var 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 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.initElement(data, globalData, comp); this.tm = data.tm ? PropertyFactory.getProp(this, data.tm, 0, globalData.frameRate, this) : { _placeholder: true }; } extendPrototype([SVGRendererBase, ICompElement, SVGBaseElement], SVGCompElement); SVGCompElement.prototype.createComp = function (data) { return new SVGCompElement(data, this.globalData, this); }; function SVGRenderer(animationItem, config) { this.animationItem = animationItem; this.layers = null; this.renderedFrame = -1; this.svgElement = createNS('svg'); var ariaLabel = ''; if (config && config.title) { var titleElement = createNS('title'); var titleId = createElementID(); titleElement.setAttribute('id', titleId); titleElement.textContent = config.title; this.svgElement.appendChild(titleElement); ariaLabel += titleId; } if (config && config.description) { var descElement = createNS('desc'); var descId = createElementID(); descElement.setAttribute('id', descId); descElement.textContent = config.description; this.svgElement.appendChild(descElement); ariaLabel += ' ' + descId; } if (ariaLabel) { this.svgElement.setAttribute('aria-labelledby', ariaLabel); } var defs = createNS('defs'); this.svgElement.appendChild(defs); var maskElement = createNS('g'); this.svgElement.appendChild(maskElement); this.layerElement = maskElement; this.renderConfig = { preserveAspectRatio: (config && config.preserveAspectRatio) || 'xMidYMid meet', imagePreserveAspectRatio: (config && config.imagePreserveAspectRatio) || 'xMidYMid slice', contentVisibility: (config && config.contentVisibility) || 'visible', progressiveLoad: (config && config.progressiveLoad) || false, hideOnTransparent: !((config && config.hideOnTransparent === false)), viewBoxOnly: (config && config.viewBoxOnly) || false, viewBoxSize: (config && config.viewBoxSize) || false, className: (config && config.className) || '', id: (config && config.id) || '', focusable: config && config.focusable, filterSize: { width: (config && config.filterSize && config.filterSize.width) || '100%', height: (config && config.filterSize && config.filterSize.height) || '100%', x: (config && config.filterSize && config.filterSize.x) || '0%', y: (config && config.filterSize && config.filterSize.y) || '0%', }, }; this.globalData = { _mdf: false, frameNum: -1, defs: defs, renderConfig: this.renderConfig, }; this.elements = []; this.pendingElements = []; this.destroyed = false; this.rendererType = 'svg'; } extendPrototype([SVGRendererBase], SVGRenderer); SVGRenderer.prototype.createComp = function (data) { return new SVGCompElement(data, this.globalData, this); }; function CVEffects() { } CVEffects.prototype.renderFrame = function () {}; function HBaseElement() {} 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 () { var transformedElementStyle = this.transformedElement ? this.transformedElement.style : {}; if (this.finalTransform._matMdf) { var matrixValue = this.finalTransform.mat.toCSS(); transformedElementStyle.transform = matrixValue; transformedElementStyle.webkitTransform = matrixValue; } if (this.finalTransform._opMdf) { transformedElementStyle.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; } }, createRenderableComponents: function () { this.maskManager = new MaskElement(this.data, this, this.globalData); }, addEffects: function () { }, setMatte: function () {}, }; HBaseElement.prototype.getBaseElement = SVGBaseElement.prototype.getBaseElement; HBaseElement.prototype.destroyBaseElement = HBaseElement.prototype.destroy; HBaseElement.prototype.buildElementParenting = BaseRenderer.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 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; var 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; var len = shape._length; var vPoint; var oPoint; var nextIPoint; var nextVPoint; 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 = bmMin(bounds.left, boundingBox.x); boundingBox.xMax = bmMax(bounds.right, boundingBox.xMax); boundingBox.y = bmMin(bounds.top, boundingBox.y); boundingBox.yMax = bmMax(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) { // eslint-disable-line no-plusplus 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 |= 0; // eslint-disable-line no-bitwise a |= 0; // eslint-disable-line no-bitwise c |= 0; // eslint-disable-line no-bitwise if (a === 0 && b === 0) { // } else if (a === 0) { t = -c / b; if (t > 0 && t < 1) { bounds[i].push(this.calculateF(t, p0, p1, p2, p3, i)); } } else { b2ac = b * b - 4 * c * a; if (b2ac >= 0) { t1 = (-b + bmSqrt(b2ac)) / (2 * a); if (t1 > 0 && t1 < 1) bounds[i].push(this.calculateF(t1, p0, p1, p2, p3, i)); t2 = (-b - bmSqrt(b2ac)) / (2 * a); if (t2 > 0 && t2 < 1) bounds[i].push(this.calculateF(t2, p0, p1, p2, p3, i)); } } } this.shapeBoundingBox.left = bmMin.apply(null, bounds[0]); this.shapeBoundingBox.top = bmMin.apply(null, bounds[1]); this.shapeBoundingBox.right = bmMax.apply(null, bounds[0]); this.shapeBoundingBox.bottom = bmMax.apply(null, bounds[1]); }; HShapeElement.prototype.calculateF = function (t, p0, p1, p2, p3, i) { return bmPow(1 - t, 3) * p0[i] + 3 * bmPow(1 - t, 2) * t * p1[i] + 3 * (1 - t) * bmPow(t, 2) * p2[i] + bmPow(t, 3) * p3[i]; }; HShapeElement.prototype.calculateBoundingBox = function (itemsData, boundingBox) { var i; var len = itemsData.length; 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); var shapeStyle = this.shapeCont.style; var shapeTransform = 'translate(' + this.currentBBox.x + 'px,' + this.currentBBox.y + 'px)'; shapeStyle.transform = shapeTransform; shapeStyle.webkitTransform = shapeTransform; } } }; 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; var textColor = documentData.fc ? this.buildColor(documentData.fc) : 'rgba(0,0,0,0)'; innerElemStyle.fill = textColor; innerElemStyle.color = textColor; 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; var fStyle = documentData.fStyle; innerElemStyle.fontStyle = fStyle; innerElemStyle.fontWeight = fWeight; } } var i; var len; var letters = documentData.l; len = letters.length; var tSpan; var tParent; var tCont; var matrixHelper = this.mHelper; var shapes; var 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', lineCapEnum[1]); tSpan.setAttribute('stroke-linejoin', lineJoinEnum[2]); 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'); tParent.style.lineHeight = 0; 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 && shapeData.shapes.length) { 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)); var tContStyle = tCont.style; var tContTranslation = 'translate(' + (boundingBox.x - 1) + 'px,' + (boundingBox.y - 1) + 'px)'; tContStyle.transform = tContTranslation; tContStyle.webkitTransform = tContTranslation; 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); // var tStyle = tSpan.style; var tSpanTranslation = 'translate3d(0,' + -documentData.finalSize / 1.2 + 'px,0)'; tStyle.transform = tSpanTranslation; tStyle.webkitTransform = tSpanTranslation; } 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 () { var svgStyle; if (this.data.singleShape) { if (!this._isFirstFrame && !this.lettersChangedFlag) { return; } if (this.isMasked && this.finalTransform._matMdf) { // Todo Benchmark if using this is better than getBBox this.svgElement.setAttribute('viewBox', -this.finalTransform.mProp.p.v[0] + ' ' + -this.finalTransform.mProp.p.v[1] + ' ' + this.compW + ' ' + this.compH); svgStyle = this.svgElement.style; var translation = 'translate(' + -this.finalTransform.mProp.p.v[0] + 'px,' + -this.finalTransform.mProp.p.v[1] + 'px)'; svgStyle.transform = translation; svgStyle.webkitTransform = translation; } } this.textAnimator.getMeasures(this.textProperty.currentData, this.lettersChangedFlag); if (!this.lettersChangedFlag && !this.textAnimator.lettersChangedFlag) { return; } var i; var len; var count = 0; var renderedLetters = this.textAnimator.renderedLetters; var letters = this.textProperty.currentData.l; len = letters.length; var renderedLetter; var textSpan; var textPath; for (i = 0; i < len; i += 1) { if (letters[i].n) { count += 1; } else { textSpan = this.textSpans[i]; textPath = this.textPaths[i]; renderedLetter = renderedLetters[count]; count += 1; if (renderedLetter._mdf.m) { if (!this.isMasked) { textSpan.style.webkitTransform = renderedLetter.m; textSpan.style.transform = 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); svgStyle = this.svgElement.style; var svgTransform = 'translate(' + this.currentBBox.x + 'px,' + this.currentBBox.y + 'px)'; svgStyle.transform = svgTransform; svgStyle.webkitTransform = svgTransform; } } }; 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; var 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; // TODO: find a better way to make the HCamera element to be compatible with the LayerInterface and TransformInterface. this.finalTransform = { mProp: this, }; } extendPrototype([BaseElement, FrameElement, HierarchyElement], HCameraElement); HCameraElement.prototype.setup = function () { var i; var len = this.comp.threeDElements.length; var comp; var perspectiveStyle; var containerStyle; for (i = 0; i < len; i += 1) { // [perspectiveElem,container] comp = this.comp.threeDElements[i]; if (comp.type === '3d') { perspectiveStyle = comp.perspectiveElem.style; containerStyle = comp.container.style; var perspective = this.pe.v + 'px'; var origin = '0px 0px 0px'; var matrix = 'matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)'; perspectiveStyle.perspective = perspective; perspectiveStyle.webkitPerspective = perspective; containerStyle.transformOrigin = origin; containerStyle.mozTransformOrigin = origin; containerStyle.webkitTransformOrigin = origin; perspectiveStyle.transform = matrix; perspectiveStyle.webkitTransform = matrix; } } }; HCameraElement.prototype.createElements = function () { }; HCameraElement.prototype.hide = function () { }; HCameraElement.prototype.renderFrame = function () { var _mdf = this._isFirstFrame; var i; var 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.pe._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) { len = this.hierarchy.length - 1; for (i = len; i >= 0; i -= 1) { 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.or.v[0]).rotateY(-mTransf.or.v[1]).rotateZ(mTransf.or.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; if (this.p) { 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]]; } else { diffVector = [this.px.v - this.a.v[0], this.py.v - this.a.v[1], this.pz.v - 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 mRotationX = (Math.atan2(lookDir[1], lookLengthOnXZ)); var mRotationY = (Math.atan2(lookDir[0], -lookDir[2])); this.mat.rotateY(mRotationY).rotateX(-mRotationX); } 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); var hasMatrixChanged = !this._prevMat.equals(this.mat); if ((hasMatrixChanged || this.pe._mdf) && this.comp.threeDElements) { len = this.comp.threeDElements.length; var comp; var perspectiveStyle; var containerStyle; for (i = 0; i < len; i += 1) { comp = this.comp.threeDElements[i]; if (comp.type === '3d') { if (hasMatrixChanged) { var matValue = this.mat.toCSS(); containerStyle = comp.container.style; containerStyle.transform = matValue; containerStyle.webkitTransform = matValue; } if (this.pe._mdf) { perspectiveStyle = comp.perspectiveElem.style; perspectiveStyle.perspective = this.pe.v + 'px'; perspectiveStyle.webkitPerspective = this.pe.v + 'px'; } } } this.mat.clone(this._prevMat); } } this._isFirstFrame = false; }; HCameraElement.prototype.prepareFrame = function (num) { this.prepareProperties(num, true); }; HCameraElement.prototype.destroy = function () { }; HCameraElement.prototype.getBaseElement = function () { return null; }; 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.crossOrigin = 'anonymous'; img.src = assetPath; if (this.data.ln) { this.baseElement.setAttribute('id', this.data.ln); } }; function HybridRendererBase(animationItem, config) { this.animationItem = animationItem; this.layers = null; this.renderedFrame = -1; this.renderConfig = { className: (config && config.className) || '', imagePreserveAspectRatio: (config && config.imagePreserveAspectRatio) || 'xMidYMid slice', hideOnTransparent: !(config && config.hideOnTransparent === false), filterSize: { width: (config && config.filterSize && config.filterSize.width) || '400%', height: (config && config.filterSize && config.filterSize.height) || '400%', x: (config && config.filterSize && config.filterSize.x) || '-100%', y: (config && config.filterSize && config.filterSize.y) || '-100%', }, }; this.globalData = { _mdf: false, frameNum: -1, renderConfig: this.renderConfig, }; this.pendingElements = []; this.elements = []; this.threeDElements = []; this.destroyed = false; this.camera = null; this.supports3d = true; this.rendererType = 'html'; } extendPrototype([BaseRenderer], HybridRendererBase); HybridRendererBase.prototype.buildItem = SVGRenderer.prototype.buildItem; HybridRendererBase.prototype.checkPendingElements = function () { while (this.pendingElements.length) { var element = this.pendingElements.pop(); element.checkParenting(); } }; HybridRendererBase.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; var nextLayer; var 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); } }; HybridRendererBase.prototype.createShape = function (data) { if (!this.supports3d) { return new SVGShapeElement(data, this.globalData, this); } return new HShapeElement(data, this.globalData, this); }; HybridRendererBase.prototype.createText = function (data) { if (!this.supports3d) { return new SVGTextLottieElement(data, this.globalData, this); } return new HTextElement(data, this.globalData, this); }; HybridRendererBase.prototype.createCamera = function (data) { this.camera = new HCameraElement(data, this.globalData, this); return this.camera; }; HybridRendererBase.prototype.createImage = function (data) { if (!this.supports3d) { return new IImageElement(data, this.globalData, this); } return new HImageElement(data, this.globalData, this); }; HybridRendererBase.prototype.createSolid = function (data) { if (!this.supports3d) { return new ISolidElement(data, this.globalData, this); } return new HSolidElement(data, this.globalData, this); }; HybridRendererBase.prototype.createNull = SVGRenderer.prototype.createNull; HybridRendererBase.prototype.getThreeDContainerByPos = function (pos) { var i = 0; var 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; } return null; }; HybridRendererBase.prototype.createThreeDContainer = function (pos, type) { var perspectiveElem = createTag('div'); var style; var containerStyle; styleDiv(perspectiveElem); var container = createTag('div'); styleDiv(container); if (type === '3d') { style = perspectiveElem.style; style.width = this.globalData.compSize.w + 'px'; style.height = this.globalData.compSize.h + 'px'; var center = '50% 50%'; style.webkitTransformOrigin = center; style.mozTransformOrigin = center; style.transformOrigin = center; containerStyle = container.style; var matrix = 'matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)'; containerStyle.transform = matrix; containerStyle.webkitTransform = matrix; } 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; }; HybridRendererBase.prototype.build3dContainers = function () { var i; var 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 -= 1) { this.resizerElem.appendChild(this.threeDElements[i].perspectiveElem); } }; HybridRendererBase.prototype.addTo3dContainer = function (elem, pos) { var i = 0; var 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; } }; HybridRendererBase.prototype.configAnimation = function (animData) { var resizerElem = createTag('div'); var wrapper = this.animationItem.wrapper; var style = resizerElem.style; style.width = animData.w + 'px'; style.height = animData.h + 'px'; this.resizerElem = resizerElem; styleDiv(resizerElem); style.transformStyle = 'flat'; style.mozTransformStyle = 'flat'; style.webkitTransformStyle = 'flat'; if (this.renderConfig.className) { resizerElem.setAttribute('class', this.renderConfig.className); } wrapper.appendChild(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.data = animData; // Mask animation this.setupGlobalData(animData, svg); this.globalData.defs = defs; this.layers = animData.layers; this.layerElement = this.resizerElem; this.build3dContainers(); this.updateContainerSize(); }; HybridRendererBase.prototype.destroy = function () { if (this.animationItem.wrapper) { this.animationItem.wrapper.innerText = ''; } this.animationItem.container = null; this.globalData.defs = null; var i; var len = this.layers ? this.layers.length : 0; for (i = 0; i < len; i += 1) { this.elements[i].destroy(); } this.elements.length = 0; this.destroyed = true; this.animationItem = null; }; HybridRendererBase.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; var sy; var tx; var 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; } var style = this.resizerElem.style; style.webkitTransform = 'matrix3d(' + sx + ',0,0,0,0,' + sy + ',0,0,0,0,1,0,' + tx + ',' + ty + ',0,1)'; style.transform = style.webkitTransform; }; HybridRendererBase.prototype.renderFrame = SVGRenderer.prototype.renderFrame; HybridRendererBase.prototype.hide = function () { this.resizerElem.style.display = 'none'; }; HybridRendererBase.prototype.show = function () { this.resizerElem.style.display = 'block'; }; HybridRendererBase.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; var len = this.threeDElements.length; for (i = 0; i < len; i += 1) { var style = this.threeDElements[i].perspectiveElem.style; style.webkitPerspective = Math.sqrt(Math.pow(cWidth, 2) + Math.pow(cHeight, 2)) + 'px'; style.perspective = style.webkitPerspective; } } }; HybridRendererBase.prototype.searchExtraCompositions = function (assets) { var i; var 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 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([HybridRendererBase, 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); } }; HCompElement.prototype.createComp = function (data) { if (!this.supports3d) { return new SVGCompElement(data, this.globalData, this); } return new HCompElement(data, this.globalData, this); }; function HybridRenderer(animationItem, config) { this.animationItem = animationItem; this.layers = null; this.renderedFrame = -1; this.renderConfig = { className: (config && config.className) || '', imagePreserveAspectRatio: (config && config.imagePreserveAspectRatio) || 'xMidYMid slice', hideOnTransparent: !(config && config.hideOnTransparent === false), filterSize: { width: (config && config.filterSize && config.filterSize.width) || '400%', height: (config && config.filterSize && config.filterSize.height) || '400%', x: (config && config.filterSize && config.filterSize.x) || '-100%', y: (config && config.filterSize && config.filterSize.y) || '-100%', }, }; this.globalData = { _mdf: false, frameNum: -1, renderConfig: this.renderConfig, }; this.pendingElements = []; this.elements = []; this.threeDElements = []; this.destroyed = false; this.camera = null; this.supports3d = true; this.rendererType = 'html'; } extendPrototype([HybridRendererBase], HybridRenderer); HybridRenderer.prototype.createComp = function (data) { if (!this.supports3d) { return new SVGCompElement(data, this.globalData, this); } return new HCompElement(data, this.globalData, this); }; // Registering renderers registerRenderer('html', HybridRenderer); // Registering shape modifiers ShapeModifiers.registerModifier('tm', TrimModifier); ShapeModifiers.registerModifier('pb', PuckerAndBloatModifier); ShapeModifiers.registerModifier('rp', RepeaterModifier); ShapeModifiers.registerModifier('rd', RoundCornersModifier); export { lottie as default };
'use strict'; const assert = require('assert'); const app = require('../../../src/app'); describe('remitos service', function() { it('registered the remitos service', () => { assert.ok(app.service('remitos')); }); });
/*! * Stylus - Import * Copyright(c) 2010 LearnBoost <dev@learnboost.com> * MIT Licensed */ /** * Module dependencies. */ var Node = require('./node'); /** * Initialize a new `Import` with the given `expr`. * * @param {Expression} expr * @api public */ var Import = module.exports = function Import(expr, once){ Node.call(this); this.path = expr; this.once = once || false; }; /** * Inherit from `Node.prototype`. */ Import.prototype.__proto__ = Node.prototype; /** * Return a clone of this node. * * @return {Node} * @api public */ Import.prototype.clone = function(){ var clone = new Import(this.path.clone(), this.once); clone.lineno = this.lineno; clone.filename = this.filename; return clone; };
'use strict'; var path = require('path'); var assert = require('yeoman-assert'); var helpers = require('yeoman-test'); describe('generator-wass:app', () => { beforeAll(() => { return helpers.run(path.join(__dirname, '../generators/app')) .withPrompts({someAnswer: true}); }); it('creates files', () => { assert.file([ 'dummyfile.txt' ]); }); });
#!/usr/bin/env node const vows = require('vows'), assert = require("assert"), math = require("../math"); // require my math.js library vows.describe('division').addBatch({ 'div()' : { topic: math.div(), 'should be NaN': function (topic) { assert.ok(true, isNaN(topic)); } }, 'div(42, 0)' : { topic: math.div(42, 0), 'should be Infinity': function (topic) { assert.equal (topic, Infinity); } }, 'div(-42, 0)' : { topic: math.div(42, 0), 'should be Infinity': function (topic) { assert.equal (topic, Infinity); } }, 'div(42, 2)' : { topic: math.div(42, 2), 'should be 21': function (topic) { assert.equal (topic, 21); } }, 'div(0, 0)' : { topic: math.div(0, 0), 'should be NaN': function (topic) { assert.ok(true, isNaN(topic)); } }, 'div(0, 1)' : { topic: math.div(0, 1), 'should be 0': function (topic) { assert.equal (topic, 0); } }, 'div(1, 1)' : { topic: math.div(1, 1), 'should be 1': function (topic) { assert.equal (topic, 1); } }, 'div(1, 4)' : { topic: math.div(1, 4), 'should be 0.25': function (topic) { assert.equal (topic, 0.25); } }, 'div(4, 2)' : { topic: math.div(4, 2), 'should be 2': function (topic) { assert.equal (topic, 2); } }, 'div(Infinity, Infinity)' : { topic: math.div(Infinity, Infinity), 'should be NaN': function (topic) { assert.ok(true, isNaN(topic)); } }, 'div(0, Infinity)' : { topic: math.div(0, Infinity), 'should be 0': function (topic) { assert.equal (topic, 0); } } }).export(module);
/* Language: Haxe Author: Christopher Kaster <ikasoki@gmail.com> (Based on the actionscript.js language file by Alexander Myadzel) */ function(hljs) { var IDENT_RE = '[a-zA-Z_$][a-zA-Z0-9_$]*'; var IDENT_FUNC_RETURN_TYPE_RE = '([*]|[a-zA-Z_$][a-zA-Z0-9_$]*)'; return { aliases: ['hx'], keywords: { keyword: 'break callback case cast catch class continue default do dynamic else enum extends extern ' + 'for function here if implements import in inline interface never new override package private ' + 'public return static super switch this throw trace try typedef untyped using var while', literal: 'true false null' }, contains: [ hljs.APOS_STRING_MODE, hljs.QUOTE_STRING_MODE, hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE, hljs.C_NUMBER_MODE, { className: 'class', beginKeywords: 'class interface', end: '{', excludeEnd: true, contains: [ { beginKeywords: 'extends implements' }, hljs.TITLE_MODE ] }, { className: 'preprocessor', begin: '#', end: '$', keywords: 'if else elseif end error' }, { className: 'function', beginKeywords: 'function', end: '[{;]', excludeEnd: true, illegal: '\\S', contains: [ hljs.TITLE_MODE, { className: 'params', begin: '\\(', end: '\\)', contains: [ hljs.APOS_STRING_MODE, hljs.QUOTE_STRING_MODE, hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE ] }, { className: 'type', begin: ':', end: IDENT_FUNC_RETURN_TYPE_RE, relevance: 10 } ] } ] }; }
/* * RailsAdmin remote form @VERSION * * License * * http://www.railsadmin.org * * Depends: * jquery.ui.core.js * jquery.ui.widget.js * jquery.ui.dialog.js */ (function($) { $.widget("ra.remoteForm", { dialog: null, options: { dialogClass: "", height: 600, width: 720 }, _create: function() { var widget = this; var edit_url = $(this.element).siblings('select').data('edit-url'); if(typeof(edit_url) != 'undefined' && edit_url.length) { $('#' + this.element.parent().parent().attr('id') + ' .ra-multiselect option').live('dblclick', function(e){ e.preventDefault(); if($("#modal").length) { return false; // Only one modal at a time } var dialog = widget._getModal(); $.ajax({ url: edit_url.replace('__ID__', this.value), beforeSend: function(xhr) { xhr.setRequestHeader("Accept", "text/javascript"); }, success: function(data, status, xhr) { dialog.find('.modal-body').html(data); widget._bindFormEvents(); }, error: function(xhr, status, error) { dialog.find('.modal-body').html(xhr.responseText); }, dataType: 'text' }); }); } $(widget.element).bind("click", function(e){ e.preventDefault(); if($("#modal").length) { return false; // Only one modal at a time } var dialog = widget._getModal(); $.ajax({ url: $(this).attr("href"), beforeSend: function(xhr) { xhr.setRequestHeader("Accept", "text/javascript"); }, success: function(data, status, xhr) { dialog.find('.modal-body').html(data); widget._bindFormEvents(); }, error: function(xhr, status, error) { dialog.find('.modal-body').html(xhr.responseText); }, dataType: 'text' }); }); }, _bindFormEvents: function() { var dialog = this._getModal(), form = dialog.find("form"), widget = this, saveButtonText = dialog.find(":submit[name=_save]").text(), cancelButtonText = dialog.find(":submit[name=_continue]").text(); dialog.find('.actions').remove(); form.attr("data-remote", true); dialog.find('.modal-header-title').text(form.data('title')); dialog.find('.cancel-action').unbind().click(function(){ dialog.modal('hide'); return false; }).text(cancelButtonText); dialog.find('.save-action').unbind().click(function(){ form.submit(); return false; }).text(saveButtonText); form.bind("ajax:complete", function(xhr, data, status) { if (status == 'error') { dialog.find('.modal-body').html(data.responseText); widget._bindFormEvents(); } else { var json = $.parseJSON(data.responseText); var option = '<option value="' + json.id + '" selected>' + json.label + '</option>'; var select = widget.element.siblings('select'); if(widget.element.siblings('.input-append').length) { // select input (add) var input = widget.element.siblings('.input-append').children('.ra-filtering-select-input'); if(input.length > 0) { input[0].value = json.label; } if(select.length > 0) { select.html(option); select[0].value = json.id; } } else { // multi-select input var input = widget.element.siblings('.ra-filtering-select-input'); var multiselect = widget.element.siblings('.ra-multiselect'); if (select.find('option[value=' + json.id + ']').length) { // replace (changing name may be needed) select.find('option[value=' + json.id + ']').text(json.label); multiselect.find('option[value= ' + json.id + ']').text(json.label); } else { // add select.prepend(option); multiselect.find('select.ra-multiselect-selection').prepend(option); } } dialog.modal("hide"); } }); }, _getModal: function() { var widget = this; if (!widget.dialog) { widget.dialog = $('\ <div id="modal" class="modal">\ <div class="modal-header">\ <a href="#" class="close">&times;</a>\ <h3 class="modal-header-title">...</h3>\ </div>\ <div class="modal-body">\ ...\ </div>\ <div class="modal-footer">\ <a href="#" class="btn secondary cancel-action">...</a>\ <a href="#" class="btn primary save-action">...</a>\ </div>\ </div>') .modal({ keyboard: true, backdrop: true, show:true }) .bind('hidden', function(){ widget.dialog.remove(); // We don't want to reuse closed modals widget.dialog = null; }); } return this.dialog; } }); })(jQuery);
module.exports = { author : { nickName: 'makishvili', shortName: 'Вадим Макишвили', firstName: 'Вадим', middleName: 'Юрьевич', lastName: 'Макишвили' }, project : { root: '/Users/makishvili/projects/storymill-export/', import: '/Users/makishvili/Yandex.Disk/StoryMill/sm-import/', export: '/Users/makishvili/Yandex.Disk/StoryMill/sm-export/' }, pdfPrinter: { default: 'apachefop', // default: 'wkhtmltopdf', apachefop: { conf: '/Applications/Apache\\ FOP/fop-1.1/fop.xconf' }, wkhtmltopdf: { params: { global: { '--print-media-type': '', '--header-font-name': 'Times', '--footer-font-name': 'Times', '--header-font-size': '8', '--footer-font-size': '8', '--header-spacing': '4', '--footer-spacing': '4', '--footer-center': '[page]/[toPage]', '--header-right': 'makishvili.com/proza/%fileName%.html', }, toc: { '--xsl-style-sheet': '%projectPath%node_modules/storymill/wkhtmltopdf.toc.xsl' } } } }, bookList: [ { id: 'childhood', title: 'Последний вечер детства', completed: 'yes', published: 'no' }, { id: 'cold', title: 'Холодно', completed: 'yes', published: 'yes', month: 'Февраль', year: '2011' }, { id: 'kush', title: 'Сандалики на тонком ремешке', completed: 'yes', published: 'yes', month: 'Июль', year: '2011' }, { id: 'signs', title: 'Знаки', completed: 'yes', published: 'yes', month: 'Август', year: '2011' }, { id: 'cry', title: 'Время, когда плакать можно', completed: 'yes', published: 'yes', month: 'Июль', year: '2012' }, { id: 'dog', title: 'Убей собаку!', completed: 'yes', published: 'yes', month: 'Апрель', year: '2013' }, { id: 'in-the-car', title: 'Ребенок в машине', completed: 'no', published: 'no' }, { id: 'lift', title: 'Лифт', completed: 'no', published: 'no' }, { id: 'mall', title: 'Стрельба в Европейском', completed: 'no', published: 'no' }, { id: 'crocodile', title: 'Крокодил', completed: 'no', published: 'no' }, { id: 'water', title: 'Достать воды', completed: 'no', published: 'no' }, ] };
import * as THREE from '../../../build/three.module.js'; import { RGBELoader } from '../../../examples/jsm/loaders/RGBELoader.js'; import { TGALoader } from '../../../examples/jsm/loaders/TGALoader.js'; import { UIElement, UISpan, UIDiv, UIRow, UIButton, UICheckbox, UIText, UINumber } from './ui.js'; import { MoveObjectCommand } from '../commands/MoveObjectCommand.js'; function UITexture( mapping ) { UIElement.call( this ); var scope = this; var dom = document.createElement( 'span' ); var form = document.createElement( 'form' ); var input = document.createElement( 'input' ); input.type = 'file'; input.addEventListener( 'change', function ( event ) { loadFile( event.target.files[ 0 ] ); } ); form.appendChild( input ); var canvas = document.createElement( 'canvas' ); canvas.width = 32; canvas.height = 16; canvas.style.cursor = 'pointer'; canvas.style.marginRight = '5px'; canvas.style.border = '1px solid #888'; canvas.addEventListener( 'click', function () { input.click(); }, false ); canvas.addEventListener( 'drop', function () { event.preventDefault(); event.stopPropagation(); loadFile( event.dataTransfer.files[ 0 ] ); }, false ); dom.appendChild( canvas ); function loadFile( file ) { var extension = file.name.split( '.' ).pop().toLowerCase() var reader = new FileReader(); if ( extension === 'hdr' ) { reader.addEventListener( 'load', function ( event ) { // assuming RGBE/Radiance HDR iamge format var loader = new RGBELoader().setDataType( THREE.UnsignedByteType ); loader.load( event.target.result, function ( hdrTexture ) { hdrTexture.sourceFile = file.name; hdrTexture.isHDRTexture = true; scope.setValue( hdrTexture ); if ( scope.onChangeCallback ) scope.onChangeCallback( hdrTexture ); } ); } ); reader.readAsDataURL( file ); } else if ( extension === 'tga' ) { reader.addEventListener( 'load', function ( event ) { var canvas = new TGALoader().parse( event.target.result ); var texture = new THREE.CanvasTexture( canvas, mapping ); texture.sourceFile = file.name; scope.setValue( texture ); if ( scope.onChangeCallback ) scope.onChangeCallback( texture ); }, false ); reader.readAsArrayBuffer( file ); } else if ( file.type.match( 'image.*' ) ) { reader.addEventListener( 'load', function ( event ) { var image = document.createElement( 'img' ); image.addEventListener( 'load', function () { var texture = new THREE.Texture( this, mapping ); texture.sourceFile = file.name; texture.format = file.type === 'image/jpeg' ? THREE.RGBFormat : THREE.RGBAFormat; texture.needsUpdate = true; scope.setValue( texture ); if ( scope.onChangeCallback ) scope.onChangeCallback( texture ); }, false ); image.src = event.target.result; }, false ); reader.readAsDataURL( file ); } form.reset(); } this.dom = dom; this.texture = null; this.onChangeCallback = null; return this; } UITexture.prototype = Object.create( UIElement.prototype ); UITexture.prototype.constructor = UITexture; UITexture.prototype.getValue = function () { return this.texture; }; UITexture.prototype.setValue = function ( texture ) { var canvas = this.dom.children[ 0 ]; var context = canvas.getContext( '2d' ); // Seems like context can be null if the canvas is not visible if ( context ) { // Always clear the context before set new texture, because new texture may has transparency context.clearRect( 0, 0, canvas.width, canvas.height ); } if ( texture !== null ) { var image = texture.image; if ( image !== undefined && image.width > 0 ) { canvas.title = texture.sourceFile; var scale = canvas.width / image.width; if ( image.data === undefined ) { context.drawImage( image, 0, 0, image.width * scale, image.height * scale ); } else { var canvas2 = renderToCanvas( texture ); context.drawImage( canvas2, 0, 0, image.width * scale, image.height * scale ); } } else { canvas.title = texture.sourceFile + ' (error)'; } } else { canvas.title = 'empty'; } this.texture = texture; }; UITexture.prototype.setEncoding = function ( encoding ) { var texture = this.getValue(); if ( texture !== null ) { texture.encoding = encoding; } return this; }; UITexture.prototype.onChange = function ( callback ) { this.onChangeCallback = callback; return this; }; // UICubeTexture function UICubeTexture() { UIElement.call( this ); var container = new UIDiv(); this.cubeTexture = null; this.onChangeCallback = null; this.dom = container.dom; this.textures = []; var scope = this; var pRow = new UIRow(); var nRow = new UIRow(); pRow.add( new UIText( 'P:' ).setWidth( '35px' ) ); nRow.add( new UIText( 'N:' ).setWidth( '35px' ) ); var posXTexture = new UITexture().onChange( onTextureChanged ); var negXTexture = new UITexture().onChange( onTextureChanged ); var posYTexture = new UITexture().onChange( onTextureChanged ); var negYTexture = new UITexture().onChange( onTextureChanged ); var posZTexture = new UITexture().onChange( onTextureChanged ); var negZTexture = new UITexture().onChange( onTextureChanged ); this.textures.push( posXTexture, negXTexture, posYTexture, negYTexture, posZTexture, negZTexture ); pRow.add( posXTexture ); pRow.add( posYTexture ); pRow.add( posZTexture ); nRow.add( negXTexture ); nRow.add( negYTexture ); nRow.add( negZTexture ); container.add( pRow, nRow ); function onTextureChanged() { var images = []; for ( var i = 0; i < scope.textures.length; i ++ ) { var texture = scope.textures[ i ].getValue(); if ( texture !== null ) { images.push( texture.isHDRTexture ? texture : texture.image ); } } if ( images.length === 6 ) { var cubeTexture = new THREE.CubeTexture( images ); cubeTexture.needsUpdate = true; if ( images[ 0 ].isHDRTexture ) cubeTexture.isHDRTexture = true; scope.cubeTexture = cubeTexture; if ( scope.onChangeCallback ) scope.onChangeCallback( cubeTexture ); } } } UICubeTexture.prototype = Object.create( UIElement.prototype ); UICubeTexture.prototype.constructor = UICubeTexture; UICubeTexture.prototype.setEncoding = function ( encoding ) { var cubeTexture = this.getValue(); if ( cubeTexture !== null ) { cubeTexture.encoding = encoding; } return this; }; UICubeTexture.prototype.getValue = function () { return this.cubeTexture; }; UICubeTexture.prototype.setValue = function ( cubeTexture ) { this.cubeTexture = cubeTexture; if ( cubeTexture !== null ) { var images = cubeTexture.image; if ( Array.isArray( images ) === true && images.length === 6 ) { for ( var i = 0; i < images.length; i ++ ) { var image = images[ i ]; var texture = new THREE.Texture( image ); this.textures[ i ].setValue( texture ); } } } else { var textures = this.textures; for ( var i = 0; i < textures.length; i ++ ) { textures[ i ].setValue( null ); } } return this; }; UICubeTexture.prototype.onChange = function ( callback ) { this.onChangeCallback = callback; return this; }; // UIOutliner function UIOutliner( editor ) { UIElement.call( this ); var scope = this; var dom = document.createElement( 'div' ); dom.className = 'Outliner'; dom.tabIndex = 0; // keyup event is ignored without setting tabIndex // hack this.scene = editor.scene; // Prevent native scroll behavior dom.addEventListener( 'keydown', function ( event ) { switch ( event.keyCode ) { case 38: // up case 40: // down event.preventDefault(); event.stopPropagation(); break; } }, false ); // Keybindings to support arrow navigation dom.addEventListener( 'keyup', function ( event ) { switch ( event.keyCode ) { case 38: // up scope.selectIndex( scope.selectedIndex - 1 ); break; case 40: // down scope.selectIndex( scope.selectedIndex + 1 ); break; } }, false ); this.dom = dom; this.editor = editor; this.options = []; this.selectedIndex = - 1; this.selectedValue = null; return this; } UIOutliner.prototype = Object.create( UIElement.prototype ); UIOutliner.prototype.constructor = UIOutliner; UIOutliner.prototype.selectIndex = function ( index ) { if ( index >= 0 && index < this.options.length ) { this.setValue( this.options[ index ].value ); var changeEvent = document.createEvent( 'HTMLEvents' ); changeEvent.initEvent( 'change', true, true ); this.dom.dispatchEvent( changeEvent ); } }; UIOutliner.prototype.setOptions = function ( options ) { var scope = this; while ( scope.dom.children.length > 0 ) { scope.dom.removeChild( scope.dom.firstChild ); } function onClick() { scope.setValue( this.value ); var changeEvent = document.createEvent( 'HTMLEvents' ); changeEvent.initEvent( 'change', true, true ); scope.dom.dispatchEvent( changeEvent ); } // Drag var currentDrag; function onDrag() { currentDrag = this; } function onDragStart( event ) { event.dataTransfer.setData( 'text', 'foo' ); } function onDragOver( event ) { if ( this === currentDrag ) return; var area = event.offsetY / this.clientHeight; if ( area < 0.25 ) { this.className = 'option dragTop'; } else if ( area > 0.75 ) { this.className = 'option dragBottom'; } else { this.className = 'option drag'; } } function onDragLeave() { if ( this === currentDrag ) return; this.className = 'option'; } function onDrop( event ) { if ( this === currentDrag || currentDrag === undefined ) return; this.className = 'option'; var scene = scope.scene; var object = scene.getObjectById( currentDrag.value ); var area = event.offsetY / this.clientHeight; if ( area < 0.25 ) { var nextObject = scene.getObjectById( this.value ); moveObject( object, nextObject.parent, nextObject ); } else if ( area > 0.75 ) { var nextObject, parent; if ( this.nextSibling !== null ) { nextObject = scene.getObjectById( this.nextSibling.value ); parent = nextObject.parent; } else { // end of list (no next object) nextObject = null; parent = scene.getObjectById( this.value ).parent; } moveObject( object, parent, nextObject ); } else { var parentObject = scene.getObjectById( this.value ); moveObject( object, parentObject ); } } function moveObject( object, newParent, nextObject ) { if ( nextObject === null ) nextObject = undefined; var newParentIsChild = false; object.traverse( function ( child ) { if ( child === newParent ) newParentIsChild = true; } ); if ( newParentIsChild ) return; var editor = scope.editor; editor.execute( new MoveObjectCommand( editor, object, newParent, nextObject ) ); var changeEvent = document.createEvent( 'HTMLEvents' ); changeEvent.initEvent( 'change', true, true ); scope.dom.dispatchEvent( changeEvent ); } // scope.options = []; for ( var i = 0; i < options.length; i ++ ) { var div = options[ i ]; div.className = 'option'; scope.dom.appendChild( div ); scope.options.push( div ); div.addEventListener( 'click', onClick ); if ( div.draggable === true ) { div.addEventListener( 'drag', onDrag ); div.addEventListener( 'dragstart', onDragStart ); // Firefox needs this div.addEventListener( 'dragover', onDragOver ); div.addEventListener( 'dragleave', onDragLeave ); div.addEventListener( 'drop', onDrop ); } } return scope; }; UIOutliner.prototype.getValue = function () { return this.selectedValue; }; UIOutliner.prototype.setValue = function ( value ) { for ( var i = 0; i < this.options.length; i ++ ) { var element = this.options[ i ]; if ( element.value === value ) { element.classList.add( 'active' ); // scroll into view var y = element.offsetTop - this.dom.offsetTop; var bottomY = y + element.offsetHeight; var minScroll = bottomY - this.dom.offsetHeight; if ( this.dom.scrollTop > y ) { this.dom.scrollTop = y; } else if ( this.dom.scrollTop < minScroll ) { this.dom.scrollTop = minScroll; } this.selectedIndex = i; } else { element.classList.remove( 'active' ); } } this.selectedValue = value; return this; }; function UIPoints( onAddClicked ) { UIElement.call( this ); var span = new UISpan().setDisplay( 'inline-block' ); this.pointsList = new UIDiv(); span.add( this.pointsList ); var row = new UIRow(); span.add( row ); var addPointButton = new UIButton( '+' ).onClick( onAddClicked ); row.add( addPointButton ); this.update = function () { if ( this.onChangeCallback !== null ) { this.onChangeCallback(); } }.bind( this ); this.dom = span.dom; this.pointsUI = []; this.lastPointIdx = 0; this.onChangeCallback = null; return this; } UIPoints.prototype = Object.create( UIElement.prototype ); UIPoints.prototype.constructor = UIPoints; UIPoints.prototype.onChange = function ( callback ) { this.onChangeCallback = callback; return this; }; UIPoints.prototype.clear = function () { for ( var i = 0; i < this.pointsUI.length; ++ i ) { if ( this.pointsUI[ i ] ) { this.deletePointRow( i, true ); } } this.lastPointIdx = 0; }; UIPoints.prototype.deletePointRow = function ( idx, dontUpdate ) { if ( ! this.pointsUI[ idx ] ) return; this.pointsList.remove( this.pointsUI[ idx ].row ); this.pointsUI[ idx ] = null; if ( dontUpdate !== true ) { this.update(); } }; function UIPoints2() { UIPoints.call( this, UIPoints2.addRow.bind( this ) ); return this; } UIPoints2.prototype = Object.create( UIPoints.prototype ); UIPoints2.prototype.constructor = UIPoints2; UIPoints2.addRow = function () { if ( this.pointsUI.length === 0 ) { this.pointsList.add( this.createPointRow( 0, 0 ) ); } else { var point = this.pointsUI[ this.pointsUI.length - 1 ]; this.pointsList.add( this.createPointRow( point.x.getValue(), point.y.getValue() ) ); } this.update(); }; UIPoints2.prototype.getValue = function () { var points = []; var count = 0; for ( var i = 0; i < this.pointsUI.length; i ++ ) { var pointUI = this.pointsUI[ i ]; if ( ! pointUI ) continue; points.push( new THREE.Vector2( pointUI.x.getValue(), pointUI.y.getValue() ) ); ++ count; pointUI.lbl.setValue( count ); } return points; }; UIPoints2.prototype.setValue = function ( points ) { this.clear(); for ( var i = 0; i < points.length; i ++ ) { var point = points[ i ]; this.pointsList.add( this.createPointRow( point.x, point.y ) ); } this.update(); return this; }; UIPoints2.prototype.createPointRow = function ( x, y ) { var pointRow = new UIDiv(); var lbl = new UIText( this.lastPointIdx + 1 ).setWidth( '20px' ); var txtX = new UINumber( x ).setWidth( '30px' ).onChange( this.update ); var txtY = new UINumber( y ).setWidth( '30px' ).onChange( this.update ); var idx = this.lastPointIdx; var scope = this; var btn = new UIButton( '-' ).onClick( function () { if ( scope.isEditing ) return; scope.deletePointRow( idx ); } ); this.pointsUI.push( { row: pointRow, lbl: lbl, x: txtX, y: txtY } ); ++ this.lastPointIdx; pointRow.add( lbl, txtX, txtY, btn ); return pointRow; }; function UIPoints3() { UIPoints.call( this, UIPoints3.addRow.bind( this ) ); return this; } UIPoints3.prototype = Object.create( UIPoints.prototype ); UIPoints3.prototype.constructor = UIPoints3; UIPoints3.addRow = function () { if ( this.pointsUI.length === 0 ) { this.pointsList.add( this.createPointRow( 0, 0, 0 ) ); } else { var point = this.pointsUI[ this.pointsUI.length - 1 ]; this.pointsList.add( this.createPointRow( point.x.getValue(), point.y.getValue(), point.z.getValue() ) ); } this.update(); }; UIPoints3.prototype.getValue = function () { var points = []; var count = 0; for ( var i = 0; i < this.pointsUI.length; i ++ ) { var pointUI = this.pointsUI[ i ]; if ( ! pointUI ) continue; points.push( new THREE.Vector3( pointUI.x.getValue(), pointUI.y.getValue(), pointUI.z.getValue() ) ); ++ count; pointUI.lbl.setValue( count ); } return points; }; UIPoints3.prototype.setValue = function ( points ) { this.clear(); for ( var i = 0; i < points.length; i ++ ) { var point = points[ i ]; this.pointsList.add( this.createPointRow( point.x, point.y, point.z ) ); } this.update(); return this; }; UIPoints3.prototype.createPointRow = function ( x, y, z ) { var pointRow = new UIDiv(); var lbl = new UIText( this.lastPointIdx + 1 ).setWidth( '20px' ); var txtX = new UINumber( x ).setWidth( '30px' ).onChange( this.update ); var txtY = new UINumber( y ).setWidth( '30px' ).onChange( this.update ); var txtZ = new UINumber( z ).setWidth( '30px' ).onChange( this.update ); var idx = this.lastPointIdx; var scope = this; var btn = new UIButton( '-' ).onClick( function () { if ( scope.isEditing ) return; scope.deletePointRow( idx ); } ); this.pointsUI.push( { row: pointRow, lbl: lbl, x: txtX, y: txtY, z: txtZ } ); ++ this.lastPointIdx; pointRow.add( lbl, txtX, txtY, txtZ, btn ); return pointRow; }; function UIBoolean( boolean, text ) { UISpan.call( this ); this.setMarginRight( '10px' ); this.checkbox = new UICheckbox( boolean ); this.text = new UIText( text ).setMarginLeft( '3px' ); this.add( this.checkbox ); this.add( this.text ); } UIBoolean.prototype = Object.create( UISpan.prototype ); UIBoolean.prototype.constructor = UIBoolean; UIBoolean.prototype.getValue = function () { return this.checkbox.getValue(); }; UIBoolean.prototype.setValue = function ( value ) { return this.checkbox.setValue( value ); }; var renderer; function renderToCanvas( texture ) { if ( renderer === undefined ) { renderer = new THREE.WebGLRenderer(); renderer.outputEncoding = THREE.sRGBEncoding; } var image = texture.image; renderer.setSize( image.width, image.height, false ); var scene = new THREE.Scene(); var camera = new THREE.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 ); var material = new THREE.MeshBasicMaterial( { map: texture } ); var quad = new THREE.PlaneBufferGeometry( 2, 2 ); var mesh = new THREE.Mesh( quad, material ); scene.add( mesh ); renderer.render( scene, camera ); return renderer.domElement; } export { UITexture, UICubeTexture, UIOutliner, UIPoints, UIPoints2, UIPoints3, UIBoolean };
'use strict'; import EventConfiguration from './eventConfiguration'; import Dispatcher from './dispatcher'; import Container from './container.react'; import Handler from './handler.react'; var r34k7 = { 'EventConfiguration': EventConfiguration, 'Dispatcher': Dispatcher, 'Container': Container, 'Handler': Handler } export default r34k7;
import './classes_add.tpl.jade'; import { toast, error } from '/imports/ui/helpers/toasts.js' Template.classes_add.events({ "submit form"(event, template) { const name = event.target.name.value.trim(); const color = event.target.color.value.trim(); const short = event.target.short.value.trim(); Meteor.call('classes.insert', name, color, short, function (err, data) { if (data) { toast('Class added successful', 'done'); } else { error(err.reason, 'error_outline') } }); } });
define("Path",["JSYG"],function(JSYG) { "use strict"; /** * <strong>nécessite le module Path</strong><br/><br/> * Chemins SVG * @param arg optionnel, argument JSYG faisant référence � un chemin svg (balise &lt;path&gt;). Si non d�fni, un nouvel élément sera cr��. * @returns {JSYG.Path} */ JSYG.Path = function(arg) { if (!arg) { arg = '<path>'; } JSYG.call(this,arg); }; JSYG.Path.prototype = new JSYG(); JSYG.Path.prototype.constructor = JSYG.Path; /** * Renvoie la longueur totale du chemin * @returns {Number} */ JSYG.Path.prototype.getLength = function() { return this.node.getTotalLength(); }; /** * Clone le chemin * @returns {JSYG.Path} */ JSYG.Path.prototype.clone = function() { return new JSYG.Path(new JSYG(this.node).clone()); }; /** * Cr�e un objet segment. * Le premier argument est la lettre correspondant au segment, les arguments suivants sont les m�mes que les méthodes natives d�crites dans la <a href="http://www.w3.org/TR/SVG/paths.html#InterfaceSVGPathElement">norme SVG</a> * @param type {String} lettre correspondant au segment ('M','L','C','Z', etc) * @returns {SVGPathSeg} * @link http://www.w3.org/TR/SVG/paths.html#DOMInterfaces * @example <pre>var path = new JSYG.Path(); * var seg = path.createSeg('M',0,0); * var seg2 = path.createSeg('L',50,50); * var seg3 = path.createSeg('C',50,50,30,10,10,30); */ JSYG.Path.prototype.createSeg = function(type) { var method = 'createSVGPathSeg', type = arguments[0], args = Array.prototype.slice.call(arguments,1), low = type.toLowerCase(); switch (low) { case 'z' : method+='ClosePath'; break; case 'm' : method+='Moveto'; break; case 'l' : method+='Lineto'; break; case 'c' : method+='CurvetoCubic'; break; case 'q' : method+='CurvetoQuadratic'; break; case 'a' : method+='Arc'; break; case 'h' : method+='LinetoHorizontal'; break; case 'v' : method+='LinetoVertical'; break; case 's' : method+='CurvetoCubicSmooth'; break; case 't' : method+='CurvetoQuadraticSmooth'; break; default : throw type+' is not a correct letter for drawing paths !'; } if (low !== 'z') { method+= (low === type) ? 'Rel' : 'Abs'; } return this.node[method].apply(this.node,args); }; /** * Clone un segment * @param seg segment ou indice du segment � cloner. * @returns {SVGPathSeg} */ JSYG.Path.prototype.cloneSeg = function(seg) { if (typeof seg == 'number') seg = this.getSeg(seg); var letter = seg.pathSegTypeAsLetter, args = [letter]; letter = letter.toLowerCase(); if (letter === 'h') args.push(seg.x); else if (letter === 'v') args.push(seg.y); else { args.push(seg.x,seg.y); switch (letter) { case 'c' : args.push(seg.x1,seg.y1,seg.x2,seg.y2); break; case 'q' : args.push(seg.x1,seg.y1); break; case 'a' : args.push(seg.r1,seg.r2,seg.angle,seg.largeArcFlag,seg.sweepFlag); break; case 's' : args.push(seg.x2,seg.y2); break; } } return this.createSeg.apply(this,args); }; /** * Ajoute un segment � la liste * @returns {JSYG.Path} * @example <pre>var path = new JSYG.Path(); * path.addSeg('M',0,0); * path.addSeg('C',50,50,10,30,30,10); * * // équivalent � * var seg = path.createSeg('M',0,0); * path.appendSeg(seg); * * seg = path.createSeg('C',50,50,10,30,30,10); * path.appendSeg(seg); */ JSYG.Path.prototype.addSeg = function() { this.appendSeg(this.createSeg.apply(this,arguments)); return this; }; /** * R�initialise la liste des segments * @returns {JSYG.Path} */ JSYG.Path.prototype.clear = function() { this.node.pathSegList.clear(); return this; }; /** * récupère un segment * @param i indice du segment * @returns {SVGPathSeg} */ JSYG.Path.prototype.getSeg = function(i) { return this.node.pathSegList.getItem(i); }; /** * récupère la liste des segments sous forme de tableau * @returns {Array} */ JSYG.Path.prototype.getSegList = function() { return JSYG.makeArray(this.node.pathSegList); }; /** * Trace le chemin � partir d'une liste de segments * @param segList tableau de segments * @returns {JSYG.Path} */ JSYG.Path.prototype.setSegList = function(segList) { var path = new JSYG.Path(); segList.forEach(function(seg) { path.appendSeg(seg); }); this.applyPath(path); return this; }; /** * récupère le dernier segment * @returns {SVGPathSeg} */ JSYG.Path.prototype.getLastSeg = function() { return this.getSeg(this.nbSegs()-1); }; /** * Ajoute un objet segment � la liste * @param seg objet segment * @returns {JSYG.Path} * @example <pre>var path = new JSYG.Path(); * var seg = path.createSeg('M',0,0); * path.appendSeg(seg); * * //equivalent � * path.addSeg('M',0,0); */ JSYG.Path.prototype.appendSeg = function(seg) { this.node.pathSegList.appendItem( JSYG.support.needCloneSeg ? this.cloneSeg(seg) : seg ); return this; }; /** * Insert un segment � l'indice donn� * @param seg objet segment * @param i indice ou ins�rer le segment * @returns {JSYG.Path} */ JSYG.Path.prototype.insertSeg = function(seg,i) { this.node.pathSegList.insertItemBefore( JSYG.support.needCloneSeg ? this.cloneSeg(seg) : seg, i); return this; }; /** * Remplace un segment * @param i indice du segment � remplacer * @param seg nouveau segment * @returns {JSYG.Path} */ JSYG.Path.prototype.replaceSeg = function(i,seg) { if (typeof seg == 'string') { var args = Array.prototype.slice.call(arguments,1); seg = this.createSeg.apply(this,args); } else if (JSYG.support.needCloneSeg) { seg = this.cloneSeg(seg); } this.node.pathSegList.replaceItem(seg,i); return this; }; /** * Supprime un segment * @param i indice du segment � supprimer * @returns {JSYG.Path} */ JSYG.Path.prototype.removeSeg = function(i) { this.node.pathSegList.removeItem(i); return this; }; /** * Ajoute un segment de d�placement * @param x abcisse * @param y ordonn�e * @returns {JSYG.Path} * @example <pre>var path = new JSYG.Path(); * path.moveTo(40,40); * * //équivalent � * path.addSeg('M',40,40); * * //ou encore � * var seg = path.createSeg('M',40,40); * path.appendSeg(seg); */ JSYG.Path.prototype.moveTo = function(x,y) { this.addSeg('M',x,y); return this; }; /** * Ajout un segment de droite * @param x abcisse * @param y ordonn�e * @returns {JSYG.Path} * @example <pre>var path = new JSYG.Path(); * path.lineTo(40,40); * * //équivalent � * path.addSeg('L',40,40); * * //ou encore � * var seg = path.createSeg('L',40,40); * path.appendSeg(seg); */ JSYG.Path.prototype.lineTo = function(x,y) { this.addSeg('L',x,y); return this; }; /** * Ajoute un segment de B�zier (cubique) * @param x1 abcisse du 1er point de contr�le * @param y1 ordonn�e du 1er point de contr�le * @param x2 abcisse du 2� point de contr�le * @param y2 ordonn�e du 2� point de contr�le * @param x abcisse du point d'arriv�e * @param y ordonn�e du point d'arriv�e * @returns {JSYG.Path} * @example <pre>var path = new JSYG.Path(); * path.curveTo(40,40,10,30,30,10); * * //équivalent � * path.addSeg('C',40,40,10,30,30,10); * * //ou encore � * var seg = path.createSeg('C',40,40,10,30,30,10); * path.appendSeg(seg); */ JSYG.Path.prototype.curveTo = function(x1,y1,x2,y2,x,y) { this.addSeg('C',x,y,x1,y1,x2,y2); return this; }; /** * Ferme le chemin (ajout d'un segment "Z") * @returns {JSYG.Path} * <pre>var path = new JSYG.Path(); * path.curveTo(40,40,10,30,30,10); * path.close(); * * //équivalent � * path.addSeg('Z'); * * //ou encore � * var seg = path.createSeg('Z'); * path.appendSeg(seg); */ JSYG.Path.prototype.close = function() { this.addSeg('Z'); return this; }; /** * récupère le point courant. * Un segment donn� ne renseigne que du point d'arriv�e et non du point de départ dont on a souvent besoin.<br/> * <strong>Attention</strong>, cela ne marche qu'avec des segments définis en absolu et non en relatif. Utilisez * si besoin la méthode rel2abs. * @param i indice du segment * @returns {JSYG.Vect} * @see JSYG.Path.prototype.rel2abs * @example <pre>var path = new JSYG.Path(); * path.attr('d','M0,0 h50 * * path.getCurPt(0); // {x:20,y:20} * path.getCurPt(1); // {x:20,y:20} * path.getCurPt(2); // {x:20,y:20} */ JSYG.Path.prototype.getCurPt = function(i) { var j=i, x=null,y=null, seg; if (i===0) { seg = this.getSeg(0); return new JSYG.Vect(seg.x,seg.y); } while (x==null || y==null) { j--; if (j<0) { if (x == null) { x = 0; } if (y == null) { y = 0; } } else { seg = this.getSeg(j); if (seg.x!=null && x == null) { x = seg.x; } if (seg.y!=null && y == null) { y = seg.y; } } } return new JSYG.Vect(x,y); }; /** * Remplace un segment relatif par son équivalent en absolu. */ function rel2absSeg(jPath,ind) { var seg = jPath.getSeg(ind), letter = seg.pathSegTypeAsLetter.toLowerCase(), args,ref; if (seg.pathSegTypeAsLetter !== letter) return; //d�j� en absolu args = [ind,letter.toUpperCase()]; ref = jPath.getCurPt(ind); if (letter === 'h') args.push(ref.x+seg.x); else if (letter === 'v') args.push(ref.y+seg.y); else if (letter != "z") { args.push(ref.x+seg.x,ref.y+seg.y); switch (letter) { case 'c' : args.push(ref.x+seg.x1,ref.y+seg.y1,ref.x+seg.x2,ref.y+seg.y2); break; case 'q' : args.push(ref.x+seg.x1,ref.y+seg.y1); break; case 'a' : args.push(seg.r1,seg.r2,seg.angle,seg.largArcFlag,seg.sweepFlag); break; case 's' : args.push(ref.x+seg.x2,ref.y+seg.y2); break; } } jPath.replaceSeg.apply(jPath,args); }; /** * Applique le trac� d'un autre chemin * @param path argument JSYG faisant référence � un chemin * @returns {JSYG.Path} */ JSYG.Path.prototype.applyPath = function(path) { this.attr('d',path.attr('d')); return this; }; /** * Remplace les segments relatifs en segments absolus * @returns {JSYG.Path} */ JSYG.Path.prototype.rel2abs = function() { var jPath = this.clone(); for (var i=0,N=this.nbSegs();i<N;i++) rel2absSeg(jPath,i); this.applyPath(jPath); return this; }; /** * Teste si le chemin contient des arcs ou non (segments a ou A) * @returns {Boolean} */ JSYG.Path.prototype.hasArcs = function() { return /a/i.test(this.attr('d')); }; /** * Teste si le chemin contient des segments relatifs ou non * @returns */ JSYG.Path.prototype.hasRelSeg = function() { return /(m|l|h|v|c|s|q|t|a)/.test(this.attr('d')); }; /** * Teste si le chemin est normalis� ou non. Normalis� signifie que tous ces segments sont absolus et uniquement de type M, L, C ou Z (z). * @returns {Boolean} */ JSYG.Path.prototype.isNormalized = function() { return !/([a-y]|[A-BD-KN-Y])/.test(this.attr('d')); }; /** * Renvoie le nombre de segments * @returns */ JSYG.Path.prototype.nbSegs = function() { return this.node.pathSegList.numberOfItems; }; /** * Scinde le segment en deux et renvoie un objet JSYG.Path contenant les deux nouveaux segments. * @param ind indice du segment � diviser en 2. * @returns {JSYG.Path} */ JSYG.Path.prototype.splitSeg = function(ind) { var seg = this.getSeg(ind); var current = this.getCurPt(ind); var letter = seg.pathSegTypeAsLetter; var jPath = new JSYG.Path(); switch (letter) { case 'C' : var m1 = { x : (current.x+seg.x1)/2, y : (current.y+seg.y1)/2 }, m2 = { x : (seg.x1+seg.x2)/2, y : (seg.y1+seg.y2)/2 }, m3 = { x : (seg.x2+seg.x)/2, y : (seg.y2+seg.y)/2 }, mm1 = { x : (m1.x+m2.x)/2, y : (m1.y+m2.y)/2 }, mm2 = { x : (m2.x+m3.x)/2, y : (m2.y+m3.y)/2 }, mmm = { x : (mm1.x+mm2.x)/2, y : (mm1.y+mm2.y)/2 }; jPath.addSeg('C',mmm.x,mmm.y,m1.x,m1.y,mm1.x,mm1.y); jPath.addSeg('C',seg.x,seg.y,mm2.x,mm2.y,m3.x,m3.y); break; case 'L' : var m = { x: (current.x+seg.x)/2, y: (current.y+seg.y)/2 }; jPath.addSeg('L',m.x,m.y); jPath.addSeg('L',seg.x,seg.y); break; case 'Z' : seg = this.getSeg(0); var m = { x: (current.x+seg.x)/2, y: (current.y+seg.y)/2 }; jPath.addSeg('L',m.x,m.y); jPath.addSeg('Z'); break; case 'M' : jPath.addSeg('M',seg.x,seg.y); break; default : throw "You must normalize the jPath"; } return jPath; }; /** * Scinde chaque segment du chemin en 2. * @returns {JSYG.Path} */ JSYG.Path.prototype.split = function() { if (!this.isNormalized()) throw new Error("You must normalize the path"); var list, jPath = new JSYG.Path(), i,N,j,M; for(i=0,N=this.nbSegs();i<N;i++) { list = this.splitSeg(i); for (j=0,M=list.nbSegs();j<M;j++) jPath.appendSeg(list.getSeg(j)); } this.applyPath(jPath); return this; }; /** * Extrait une portion du chemin et renvoie un objet JSYG.Path contenant les segments de cette portion. * @param begin indice du premier segment. Si n�gatif, on part de la fin. * @param end indice du dernier segment. Si n�gatif, on part de la fin. Si non pr�cis�, dernier segment. * @returns {JSYG.Path} */ JSYG.Path.prototype.slice = function(begin,end) { var nbseg = this.nbSegs(); if (begin < 0) { begin = nbseg-begin; } if (end == null) { end = nbseg-1; } else if (end < 0) { end = nbseg-end; } var jPath = new JSYG.Path(); begin = Math.max(0,begin); end = Math.min(nbseg-1,end); var pt = this.getCurPt(begin); jPath.addSeg('M',pt.x,pt.y); for (var i=begin;i<=end;i++) { jPath.appendSeg(this.getSeg(i)); } return jPath; }; /** * Inverse l'ordre des points. Pas de diff�rence visuelle. * @returns {JSYG.Path} */ JSYG.Path.prototype.reverse = function() { if (!this.isNormalized()) { throw new Error("il faut normaliser le chemin"); } var jPath = new JSYG.Path(), item,current,i,N = this.nbSegs(); for (i=N-1;i>=0;i--) { item = this.getSeg(i); if (i===N-1) { jPath.addSeg('M',item.x,item.y); } current = this.getCurPt(i); switch(item.pathSegTypeAsLetter) { case 'L' : if (i===N-1) { break; } jPath.addSeg("L",current.x,current.y); break; case 'C' : jPath.addSeg("C",current.x,current.y,item.x2,item.y2,item.x1,item.y1); break; case 'Z' : case 'z' : current = this.getSeg(N-1); jPath.addSeg("L",current.x,current.y); break; } } this.applyPath(jPath); return this; }; /** * Transforme un segment quelconque en une série de segments de droites. * nécessite un segment normalis� (M,L,C,Z,z). * @param ind indice du segment * @param nbsegs nombre de segments de droite pour approximer le segment initial (dans le cas d'un segment C). * @returns {JSYG.Path} */ JSYG.Path.prototype.seg2Polyline = function(ind,nbsegs) { nbsegs = nbsegs || 10; var seg = this.getSeg(ind), letter = seg.pathSegTypeAsLetter.toUpperCase(), current = this.getCurPt(ind), jPath = new JSYG.Path(); switch (letter) { case 'M' : jPath.addSeg('M',current.x,current.y); break; case 'L' : jPath.addSeg('L',seg.x,seg.y); break; case 'C' : var t,a,b,c,d,x,y; for (var i=0;i<=nbsegs;i++) { t = i / nbsegs; a = Math.pow(1-t,3); b = 3 * t * Math.pow(1-t,2); c = 3 * Math.pow(t,2) * (1-t); d = Math.pow(t,3); x = a * current.x + b * seg.x1 + c * seg.x2 + d * seg.x; y = a * current.y + b * seg.y1 + c * seg.y2 + d * seg.y; jPath.addSeg('L',x,y); } break; case 'Z' : seg = this.getSeg(0); jPath.addSeg('L',seg.x,seg.y); break; default : throw new Error("Vous devez normaliser le chemin pour applique la méthode seg2Polyline"); } return jPath; }; /** * Transforme le chemin en une série de segments de droite. * Le chemin doit �tre normalis�. * @param nbsegs nombre de segments pour approximer les courbes. * @returns {JSYG.Path} */ JSYG.Path.prototype.toPolyline = function(nbsegs) { var list, jPath = new JSYG.Path(), i,N,j,M; if (!this.isNormalized()) { throw new Error("Il faut normaliser le chemin pour la méthode toPolyLine"); } for(i=0,N=this.nbSegs();i<N;i++) { list = this.seg2Polyline(i,nbsegs); for (j=0,M=list.nbSegs();j<M;j++) jPath.appendSeg(list.getSeg(j)); } this.applyPath(jPath); return this; }; /** * réduit le nombre de points du chemin en précisant une distance minimale entre 2 points. * @param minDistance distance minimale en pixels entre 2 points en dessous de laquelle l'un des 2 sera supprimé. * @param screen si true, cette distance est la distance en pixels visible à l'écran (donc plus faible si le chemin est zoomé), sinon * c'est la distance absolue entre 2 points du chemin. * @returns {JSYG.Path} */ JSYG.Path.prototype.slim = function(minDistance,screen) { var i = 0, ctm = screen ? this.parent().getMtx('screen') : new JSYG.Matrix(), seg,next; while (i < this.nbSegs()-2) { //pas le dernier point seg = new JSYG.Point(this.getSeg(i)).mtx(ctm); next = new JSYG.Point(this.getSeg(i+1)).mtx(ctm); if (JSYG.distance(seg,next) < minDistance) { if (i < this.nbSegs()-2) this.removeSeg(i+1); else this.removeSeg(i); } else i++; } return this; }; function getSegDist(p, p1, p2) { var x = p1.x, y = p1.y, dx = p2.x - x, dy = p2.y - y; if (dx !== 0 || dy !== 0) { var t = ((p.x - x) * dx + (p.y - y) * dy) / (dx * dx + dy * dy); if (t > 1) { x = p2.x; y = p2.y; } else if (t > 0) { x += dx * t; y += dy * t; } } dx = p.x - x; dy = p.y - y; return Math.sqrt(dx * dx + dy * dy); } /* Tiré de Simplify.js (c) 2013, Vladimir Agafonkin Simplify.js, a high-performance JS polyline simplification library mourner.github.io/simplify-js */ /** * Simplification du chemin par l'algorithme de Douglas-Peucker * @param tolerance * @returns {JSYG.Path} * */ JSYG.Path.prototype.simplify = function(tolerance,screen) { var segs = this.getSegList(), len = segs.length, sqTolerance = tolerance ? tolerance * tolerance : 1, ctm = screen ? this.parent().getMtx('screen') : new JSYG.Matrix(), markers = new Array(len), first = 0, last = len - 1, stack = [], jPath = new JSYG.Path(), i, maxDist, dist, index = null, p,p1,p2; if (len <= 1) return this; markers[first] = markers[last] = 1; while (last) { maxDist = 0; for (i = first + 1; i < last; i++) { p = new JSYG.Point(segs[i]).mtx(ctm); p1 = new JSYG.Point(segs[first]).mtx(ctm); p2 = new JSYG.Point(segs[last]).mtx(ctm); dist = getSegDist(p,p1,p2); if (dist > maxDist) { index = i; maxDist = dist; } } if (maxDist > sqTolerance) { markers[index] = 1; stack.push(first, index, index, last); } last = stack.pop(); first = stack.pop(); } for (i = 0; i < len; i++) { if (markers[i]) jPath.appendSeg(segs[i]); } this.applyPath(jPath); return this; }; /** * Teste si le chemin est fermé ou non * @returns {Boolean} */ JSYG.Path.prototype.isClosed = function() { var seg1 = this.getSeg(0), seg2 = this.getLastSeg(); return seg2.pathSegTypeAsLetter.toLowerCase() == 'z' || (seg1.x == seg2.x && seg1.y == seg2.y); }; /** * Lisse le chemin de mani�re automatique, sans avoir � définir de points de contr�les. * @param ind optionnel, indice du segment. Si pr�cis�, le chemin ne sera liss� qu'autour de ce point. * @returns {JSYG.Path} */ JSYG.Path.prototype.autoSmooth = function(ind) { var i,N = this.nbSegs(), closed = this.isClosed(), dontloop = arguments[1] || null, min,max, seg,nm1,n0,np1,np2,x0,y0,x1,y1,x2,y2,x3,y3, tgx0,tgy0,tgx3,tgy3,dx,dy,d,dt0,dt3,ft0,ft3; if (ind == null) { min = 0; max = N-1; } else { if (ind === 0 && !dontloop) { this.autoSmooth(N-1,true); } if (ind >= N-2 && !dontloop) { this.autoSmooth(0,true); } min = Math.max(0,ind-2); max = Math.min(N-1,ind+2); } if (this.getLastSeg().pathSegTypeAsLetter.toLowerCase() === 'z') { seg = this.getSeg(0); this.replaceSeg(this.nbSegs()-1, 'L', seg.x, seg.y); } if (N < 3) {return;} for (i=min;i<max;i++) { nm1 = (i===0) ? (closed ? this.getSeg(N-2) : this.getSeg(i)) : this.getSeg(i-1); n0 = this.getSeg(i); np1 = this.getSeg(i+1); np2 = (i===N-2) ? (closed ? this.getSeg(1) : this.getSeg(i+1)) : this.getSeg(i+2); x0 = n0.x; y0 = n0.y; x3 = np1.x; y3 = np1.y; tgx3 = x0 - np2.x; tgy3 = y0 - np2.y; tgx0 = nm1.x - np1.x; tgy0 = nm1.y - np1.y; dx = Math.abs(x0 - x3); dy = Math.abs(y0 - y3); d = Math.sqrt(dx*dx + dy*dy); dt3 = Math.sqrt(tgx3*tgx3 + tgy3*tgy3); dt0 = Math.sqrt(tgx0*tgx0 + tgy0*tgy0); if (d !== 0) { ft3 = (dt3 / d) * 3; ft0 = (dt0 / d) * 3; x1 = x0 - tgx0 / ft0; y1 = y0 - tgy0 / ft0; x2 = x3 + tgx3 / ft3; y2 = y3 + tgy3 / ft3; this.replaceSeg(i+1,'C',np1.x,np1.y,x1,y1,x2,y2); } } return this; }; /** * Teste si le point passé en param�tre est � l'int�rieur du polygone défini par le chemin ou non. * Le chemin doit donc �tre ferm� pour �ventuellement renvoyer true. * @param pt objet JSYG.Vect ou objet quelconque ayant les propriétés x et y. * @returns {Boolean} */ JSYG.Path.prototype.isPointInside = function(pt) { if (!this.isClosed()) { return false; } var counter=0; var x_inter; var mtx = this.getMtx(); var p1=this.getSeg(0); p1 = new JSYG.Vect(p1.x,p1.y).mtx(mtx); var i,N=this.nbSegs(); for (i=1;i<=N;i++) { var p2 = this.getSeg(i%N); p2 = new JSYG.Vect(p2.x,p2.y).mtx(mtx); if ( pt.y > Math.min(p1.y, p2.y)) { if ( pt.y <= Math.max(p1.y, p2.y)) { if ( pt.x <= Math.max(p1.x, p2.x)) { if ( p1.y != p2.y ) { x_inter = (pt.y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y) + p1.x; if ( p1.x == p2.x || pt.x <= x_inter) { counter++; } } } } } p1 = p2; } return ( counter % 2 == 1 ); }; /** * Normalise le chemin (segments M,L,C,Z,z uniquement). * @returns {JSYG.Path} */ JSYG.Path.prototype.normalize = function() { this.rel2abs(); var seg,letter,currentPoint, jPath = new JSYG.Path(), x,y, i=0,N = this.nbSegs(), j,M,bezier; for (;i<N;i++) { seg = this.getSeg(i); letter = seg.pathSegTypeAsLetter; currentPoint = this.getCurPt(i); if (letter === 'H') { jPath.addSeg('L',seg.x,currentPoint.y); } else if (letter === 'V') { jPath.addSeg('L',currentPoint.x,seg.y); } else if (letter === 'S') { //transform S to C if (i === 0 || this.getSeg(i-1).pathSegTypeAsLetter !== 'C') { x = currentPoint.x; y = currentPoint.y; } else { x = currentPoint.x * 2 - this.getSeg(i-1).x2; y = currentPoint.y * 2 - this.getSeg(i-1).y2; } this.replaceSeg( i, 'C',seg.x,seg.y,x,y,seg.x2,seg.y2 ); i--;continue; } else if (letter === 'Q') { jPath.addSeg('C',seg.x,seg.y, 1/3 * currentPoint.x + 2/3 * seg.x1, currentPoint.y/3 + 2/3 *seg.y1,2/3 * seg.x1 + 1/3 * seg.x, 2/3 * seg.y1 + 1/3 * seg.y); } else if (letter === 'T') { //transform T to Q if (i === 0 || this.getSeg(i-1).pathSegTypeAsLetter !== 'Q') { x = currentPoint.x; y = currentPoint.y; } else { x = currentPoint.x * 2 - this.getSeg(i-1).x1; y = currentPoint.y * 2 - this.getSeg(i-1).y1; } this.replaceSeg( i, 'Q',seg.x,seg.y,x,y,seg.x2,seg.y2 ); i--;continue; } else if (letter === 'A') { bezier = this.arc2bez(i); for (j=0,M=bezier.nbSegs();j<M;j++) { jPath.appendSeg(bezier.getSeg(j)); }; } else jPath.appendSeg(seg); } this.applyPath(jPath); return this; }; /** * Renvoie la longueur d'un segment * @param i indice du segment * @returns {Number} */ JSYG.Path.prototype.getSegLength = function(i) { return this.slice(0,i).getLength()-this.slice(0,i-1).getLength(); }; /** * Renvoie la longueur du chemin au niveau du segment pr�cis� * @param i indice du segment * @returns */ JSYG.Path.prototype.getLengthAtSeg = function(i) { return this.slice(0,i).getLength(); }; /** * Renvoie l'indice du segment situ� � la distance pr�cis�e * @param distance * @returns {Number} */ JSYG.Path.prototype.getSegAtLength = function(distance) { return this.node.getPathSegAtLength(distance); }; /** * Renvoie le point du chemin � la distance pr�cis�e * @param distance * @returns {JSYG.Vect} */ JSYG.Path.prototype.getPointAtLength = function(distance) { var pt = this.node.getPointAtLength(distance); return new JSYG.Vect(pt.x,pt.y); }; /** * Renvoie l'angle du chemin � la distance pr�cis�e * @param distance * @returns {Number} */ JSYG.Path.prototype.getRotateAtLength = function(distance) { var pt = this.getTangentAtLength(distance); return Math.atan2(pt.y,pt.x) * 180 / Math.PI; }; /** * Renvoie la tangente du chemin � la distance pr�cis�e * @param distance * @returns {JSYG.Vect} */ JSYG.Path.prototype.getTangentAtLength = function(distance) { if (!this.isNormalized()) throw new Error("Il faut normaliser le chemin"); var ind = this.node.getPathSegAtLength(distance); if (ind === -1) return null; var letter; var seg; do { seg = this.getSeg(ind); if (!seg) { return null; } letter = seg.pathSegTypeAsLetter; } while (letter === 'M' && ++ind); var current = this.getCurPt(ind); //var jPath = new JSYG.Path(); switch (letter) { case 'C' : var l1 = this.getLengthAtSeg(ind-1), l2 = this.getLengthAtSeg(ind), t = (distance-l1) / (l2-l1), //inspir� de http://www.planetclegg.com/projects/WarpingTextToSplines.html a = seg.x - 3 * seg.x2 + 3 * seg.x1 - current.x, b = 3 * seg.x2 - 6 * seg.x1 + 3 * current.x, c = 3 * seg.x1 - 3 * current.x, //d = current.x, e = seg.y - 3 * seg.y2 + 3 * seg.y1 - current.y, f = 3 * seg.y2 - 6 * seg.y1 + 3 * current.y, g = 3 * seg.y1 - 3 * current.y, //h = current.y, //point de la courbe de b�zier (equivalent � getPointAtLength) //x = a * Math.pow(t,3) + b * Math.pow(t,2) + c * t + d, //y = e * Math.pow(t,3) + f * Math.pow(t,2) + g * t + h, x = 3 * a * Math.pow(t,2) + 2 * b * t + c, y = 3 * e * Math.pow(t,2) + 2 * f * t + g, vect = new JSYG.Vect(x,y).normalize(); return vect; case 'L' : var vect = new JSYG.Vect(seg.x-current.x,seg.y-current.y).normalize(); return vect; case 'M' : case 'Z' : return null; default : throw new Error("You must normalize the jPath"); } }; /** * Trouve le segment le plus proche du point donn� en param�tre * @param point objet avec les propriétés x et y. * @param precision nombre de pixels maximal s�parant le point du chemin * @returns {Number} indice du segment trouv�, ou -1 */ JSYG.Path.prototype.findSeg = function(point,precision) { precision = precision || 1; var pt,i,N=this.node.getTotalLength(); for (i=0;i<=N;i++) { pt = this.node.getPointAtLength(i); if (JSYG.distance(pt,point) < precision) return this.node.getPathSegAtLength(i); } return -1; }; function getFromPoint(node,point,result,precision,borneMin,borneMax) { var pt,i,N=node.getTotalLength(); var distance,ptmin=null,length=null,min=Infinity; precision = Math.ceil(precision || 50); borneMin = Math.max(borneMin || 0,0); borneMax = Math.min(borneMax || N,N); for (i=borneMin;i<=borneMax;i+=precision) { pt = node.getPointAtLength(i); distance = JSYG.distance(pt,point); if (distance < min ) { ptmin = pt; min = distance; length = i; if (distance < 1) break; } } if (precision > 1) { return getFromPoint(node,point,result,precision/10,length-precision,length+precision); } return result === 'point' ? new JSYG.Vect(ptmin.x,ptmin.y) : length; }; /** * Trouve le point de la courbe le plus proche du point passé en param�tre * @param point objet avec les propriétés x et y * @returns {JSYG.Vect} */ JSYG.Path.prototype.getNearestPoint = function(point) { return getFromPoint(this.node,point,'point'); }; /** * Trouve la longueur de la courbe au point le plus proche du point passé en param�tre * @param point * @returns */ JSYG.Path.prototype.getLengthAtPoint = function(point) { return getFromPoint(this.node,point,'length'); }; /* JSYG.Path.prototype.getArea = function() { var area = 0, segs = this.getSegList(), i,N = segs.length; if (segs[N-1].pathSegTypeAsLetter.toLowerCase() == 'z') { segs[N-1] = null; N--; } for (i=0;i<N-1;i++) { area += segs[i].x * segs[i+1].y - segs[i+1].x * segs[i].y; } return area/2; }; JSYG.Path.prototype.getCentroid = function() { var area = this.getArea(), segs = this.getSegList(), i,N = segs.length, x=0,y=0; for (i=0;i<N-1;i++) { x += (segs[i].x + segs[i+1].x) * (segs[i].x * segs[i+1].y - segs[i+1].x * segs[i].y); y += (segs[i].y + segs[i+1].y) * (segs[i].x * segs[i+1].y - segs[i+1].x * segs[i].y); } return { x : x/(6*area) , y : y/(6*area) }; };*/ //cod� � partir de http://www.w3.org/TR/2003/REC-SVG11-20030114/implnote.html#ArcConversionEndpointToCenter function computeCenterAndAngles(startPoint,seg) { var rad = seg.angle * Math.PI / 180, x1 = startPoint.x, y1 = startPoint.y, xp1 = Math.cos(rad) * (x1-seg.x) / 2 + Math.sin(rad) * (y1-seg.y) / 2, yp1 = -Math.sin(rad) * (x1-seg.x) / 2 + Math.cos(rad) * (y1-seg.y) / 2, r1c = Math.pow(seg.r1,2), r2c = Math.pow(seg.r2,2), xp1c = Math.pow(xp1,2), yp1c = Math.pow(yp1,2), lambda = xp1c / r1c + yp1c / r2c; //Ensure radii are large enough if (lambda > 1) { seg.r1*=Math.sqrt(lambda); seg.r2*=Math.sqrt(lambda); r1c = Math.pow(seg.r1,2); r2c = Math.pow(seg.r2,2); } var coef = (seg.largeArcFlag === seg.sweepFlag ? -1 : 1 ) * Math.sqrt( Math.max(0,( r1c*r2c - r1c*yp1c - r2c*xp1c ) / ( r1c*yp1c + r2c*xp1c)) ), cpx = coef * ( seg.r1 * yp1 ) / seg.r2, cpy = coef * ( - seg.r2 * xp1 ) / seg.r1, cx = Math.cos(rad) * cpx - Math.sin(rad) * cpy + (x1 + seg.x) / 2, cy = Math.sin(rad) * cpx + Math.cos(rad) * cpy + (y1 + seg.y) / 2, cosTheta = ( (xp1-cpx)/seg.r1 ) / Math.sqrt( Math.pow( (xp1-cpx)/seg.r1 , 2 ) + Math.pow( (yp1-cpy)/seg.r2 , 2 ) ), theta = ( (yp1-cpy)/seg.r2 > 0 ? 1 : -1) * Math.acos(cosTheta), u = { x : (xp1-cpx) /seg.r1 , y : (yp1-cpy) /seg.r2 }, v = { x : (-xp1-cpx)/seg.r1 , y : (-yp1-cpy)/seg.r2 }, cosDeltaTheta = ( u.x * v.x + u.y * v.y ) / ( Math.sqrt(Math.pow(u.x,2) + Math.pow(u.y,2)) * Math.sqrt(Math.pow(v.x,2) + Math.pow(v.y,2)) ), deltaTheta = (u.x*v.y-u.y*v.x > 0 ? 1 : -1) * Math.acos(Math.max(-1,Math.min(1,cosDeltaTheta))) % (Math.PI*2); if (seg.sweepFlag === false && deltaTheta > 0) { deltaTheta-=Math.PI*2; } else if (seg.sweepFlag === true && deltaTheta < 0) { deltaTheta+=Math.PI*2; } seg.cx = cx; seg.cy = cy; seg.eta1 = theta; seg.eta2 = theta + deltaTheta; return seg; } function rationalFunction(x,c) { return (x * (x * c[0] + c[1]) + c[2]) / (x + c[3]); }; function estimateError(seg,etaA,etaB,bezierDegree) { var coefs = { degree2 : { low : [ [ [ 3.92478, -13.5822, -0.233377, 0.0128206 ], [ -1.08814, 0.859987, 0.000362265, 0.000229036 ], [ -0.942512, 0.390456, 0.0080909, 0.00723895 ], [ -0.736228, 0.20998, 0.0129867, 0.0103456 ] ], [ [ -0.395018, 6.82464, 0.0995293, 0.0122198 ], [ -0.545608, 0.0774863, 0.0267327, 0.0132482 ], [ 0.0534754, -0.0884167, 0.012595, 0.0343396 ], [ 0.209052, -0.0599987, -0.00723897, 0.00789976 ] ] ], high : [ [ [ 0.0863805, -11.5595, -2.68765, 0.181224 ], [ 0.242856, -1.81073, 1.56876, 1.68544 ], [ 0.233337, -0.455621, 0.222856, 0.403469 ], [ 0.0612978, -0.104879, 0.0446799, 0.00867312 ] ], [ [ 0.028973, 6.68407, 0.171472, 0.0211706 ], [ 0.0307674, -0.0517815, 0.0216803, -0.0749348 ], [ -0.0471179, 0.1288, -0.0781702, 2.0 ], [ -0.0309683, 0.0531557, -0.0227191, 0.0434511 ] ] ], safety : [ 0.001, 4.98, 0.207, 0.0067 ] }, degree3 : { low : [ [ [ 3.85268, -21.229, -0.330434, 0.0127842 ], [ -1.61486, 0.706564, 0.225945, 0.263682 ], [ -0.910164, 0.388383, 0.00551445, 0.00671814 ], [ -0.630184, 0.192402, 0.0098871, 0.0102527 ] ],[ [ -0.162211, 9.94329, 0.13723, 0.0124084 ], [ -0.253135, 0.00187735, 0.0230286, 0.01264 ], [ -0.0695069, -0.0437594, 0.0120636, 0.0163087 ], [ -0.0328856, -0.00926032, -0.00173573, 0.00527385 ] ] ], high : [ [ [ 0.0899116, -19.2349, -4.11711, 0.183362 ], [ 0.138148, -1.45804, 1.32044, 1.38474 ], [ 0.230903, -0.450262, 0.219963, 0.414038 ], [ 0.0590565, -0.101062, 0.0430592, 0.0204699 ] ], [ [ 0.0164649, 9.89394, 0.0919496, 0.00760802 ], [ 0.0191603, -0.0322058, 0.0134667, -0.0825018 ], [ 0.0156192, -0.017535, 0.00326508, -0.228157 ], [ -0.0236752, 0.0405821, -0.0173086, 0.176187 ] ] ], safety : [ 0.001, 4.98, 0.207, 0.0067 ] } }; var eta = 0.5 * (etaA + etaB); if (bezierDegree < 2) { // start point var aCosEtaA = seg.r1 * Math.cos(etaA), bSinEtaA = seg.r2 * Math.sin(etaA), xA = seg.cx + aCosEtaA * Math.cos(seg.angleRad) - bSinEtaA * Math.sin(seg.angleRad), yA = seg.cy + aCosEtaA * Math.sin(seg.angleRad) + Math.sin(seg.angleRad) * Math.cos(seg.angleRad), // end point aCosEtaB = seg.r1 * Math.cos(etaB), bSinEtaB = seg.r2 * Math.sin(etaB), xB = seg.cx + aCosEtaB * Math.cos(seg.angleRad) - bSinEtaB * Math.sin(seg.angleRad), yB = seg.cy + aCosEtaB * Math.sin(seg.angleRad) + bSinEtaB * Math.cos(seg.angleRad), // maximal error point aCosEta = seg.r1 * Math.cos(eta), bSinEta = seg.r2 * Math.sin(eta), x = seg.cx + aCosEta * Math.cos(seg.angleRad) - bSinEta * Math.sin(seg.angleRad), y = seg.cy + aCosEta * Math.sin(seg.angleRad) + bSinEta * Math.cos(seg.angleRad), dx = xB - xA, dy = yB - yA; return Math.abs(x * dy - y * dx + xB * yA - xA * yB) / Math.sqrt(dx * dx + dy * dy); } else { var x = seg.r2 / seg.r1, dEta = etaB - etaA, cos2 = Math.cos(2 * eta), cos4 = Math.cos(4 * eta), cos6 = Math.cos(6 * eta), coeffs = (x < 0.25) ? coefs['degree'+bezierDegree].low : coefs['degree'+bezierDegree].high,// select the right coeficients set according to degree and b/a c0 = rationalFunction(x, coeffs[0][0]) + cos2 * rationalFunction(x, coeffs[0][1]) + cos4 * rationalFunction(x, coeffs[0][2]) + cos6 * rationalFunction(x, coeffs[0][3]), c1 = rationalFunction(x, coeffs[1][0]) + cos2 * rationalFunction(x, coeffs[1][1]) + cos4 * rationalFunction(x, coeffs[1][2]) + cos6 * rationalFunction(x, coeffs[1][3]); return rationalFunction(x, coefs['degree'+bezierDegree].safety) * seg.r1 * Math.exp(c0 + c1 * dEta); } } /** * Convertit un arc en courbe de b�zier * @param ind indice du segment arc ("A") * @param bezierDegree optionnel, degr� de la courbe de b�zier � utiliser (3 par d�faut) * @param defaultFlatness optionnel, 0.5 (valeur par d�faut) semble �tre la valeur adapt�e. * @returns {JSYG.Path} */ JSYG.Path.prototype.arc2bez = function(ind,bezierDegree,defaultFlatness) { defaultFlatness = defaultFlatness || 0.5; bezierDegree = bezierDegree || 3; var seg = this.getSeg(ind); if (seg.pathSegTypeAsLetter !== 'A') { throw "You can only comput center and angles on 'A' segments"; } var startPoint = this.getCurPt(ind); //from Luc Maisonobe www.spaceroots.org seg.angleRad = seg.angle*Math.PI/180; seg.r1 = Math.abs(seg.r1); seg.r2 = Math.abs(seg.r2); // find the number of B�zier curves needed var found = false, i,n = 1, dEta,etaA,etaB, jPath = new JSYG.Path(); computeCenterAndAngles(startPoint,seg); while ((!found) && (n < 1024)) { dEta = (seg.eta2 - seg.eta1) / n; if (dEta <= 0.5 * Math.PI) { etaB = seg.eta1; found = true; for (i=0; found && (i<n); ++i) { etaA = etaB; etaB += dEta; found = ( estimateError(seg, etaA, etaB, bezierDegree) <= defaultFlatness ); } } n = n << 1; } dEta = (seg.eta2 - seg.eta1) / n; etaB = seg.eta1; var aCosEtaB = seg.r1 * Math.cos(etaB), bSinEtaB = seg.r2 * Math.sin(etaB), aSinEtaB = seg.r1 * Math.sin(etaB), bCosEtaB = seg.r2 * Math.cos(etaB), xB = seg.cx + aCosEtaB * Math.cos(seg.angleRad) - bSinEtaB * Math.sin(seg.angleRad), yB = seg.cy + aCosEtaB * Math.sin(seg.angleRad) + bSinEtaB * Math.cos(seg.angleRad), xADot, yADot, xBDot = -aSinEtaB * Math.cos(seg.angleRad) - bCosEtaB * Math.sin(seg.angleRad), yBDot = -aSinEtaB * Math.sin(seg.angleRad) + bCosEtaB * Math.cos(seg.angleRad); //jPath.addSeg('M',xB,yB); var t = Math.tan(0.5 * dEta), alpha = Math.sin(dEta) * (Math.sqrt(4 + 3 * t * t) - 1) / 3, xA,yA,k; for (var i = 0; i < n; ++i) { etaA = etaB; xA = xB; yA = yB; xADot = xBDot; yADot = yBDot; etaB += dEta; aCosEtaB = seg.r1 * Math.cos(etaB); bSinEtaB = seg.r2 * Math.sin(etaB); aSinEtaB = seg.r1 * Math.sin(etaB); bCosEtaB = seg.r2 * Math.cos(etaB); xB = seg.cx + aCosEtaB * Math.cos(seg.angleRad) - bSinEtaB * Math.sin(seg.angleRad); yB = seg.cy + aCosEtaB * Math.sin(seg.angleRad) + bSinEtaB * Math.cos(seg.angleRad); xBDot = -aSinEtaB * Math.cos(seg.angleRad) - bCosEtaB * Math.sin(seg.angleRad); yBDot = -aSinEtaB * Math.sin(seg.angleRad) + bCosEtaB * Math.cos(seg.angleRad); if (bezierDegree == 1) { jPath.addSeg('L',xB,yB); } else if (bezierDegree == 2) { k = (yBDot * (xB - xA) - xBDot * (yB - yA)) / (xADot * yBDot - yADot * xBDot); jPath.addSeg('Q', xB , yB , xA + k * xADot , yA + k * yADot); } else { jPath.addSeg('C', xB , yB , xA + alpha * xADot , yA + alpha * yADot, xB - alpha * xBDot, yB - alpha * yBDot); } } return jPath; }; /** * Constante pour approximer les arcs */ JSYG.kappa = 4 * (Math.sqrt(2)-1)/3; // JSYG.kappa = 0.551915; /** * récupère les propriétés de mise en page */ function getLayoutAttrs(elmt) { var tab, i=0,N, l={}; switch (elmt.tagName) { case 'circle' : tab = ['cx','cy','r']; break; case 'ellipse' : tab = ['cx','cy','rx','ry']; break; case 'rect' : tab = ['x','y','rx','ry','width','height']; break; case 'line' : tab = ['x1','y1','x2','y2']; break; case 'polygon' : case 'polyline' : tab = ['points']; break; case 'path' : tab = ['d']; break; default : tab = ['x','y','width','height']; break; } for(N=tab.length;i<N;i++) l[tab[i]] = parseFloat(elmt.getAttribute(tab[i]) || 0); return l; }; /** * Convertit une forme svg en chemin * @param opt optionnel, objet pouvant avoir les propriétés suivantes : * <ul> * <li>normalize : booleen, normalise ou non le chemin</li> * <li>style : booleen, clone ou non les attributs de style de la forme au chemin</li> * <li>transform : booleen, clone ou non l'attribut de trasnformation de la forme au chemin</li> * </ul> * @returns {JSYG.Path} */ JSYG.prototype.clonePath = function(opt) { opt = opt || {}; var normalize = opt.normalize, style = opt.style, transform = opt.transform, jPath = new JSYG.Path(), l = getLayoutAttrs(this.node), tag = this.getTag(), kx=0,ky=0,points,thisPath, i,N,pt; if (JSYG.svgShapes.indexOf( this.getTag() ) == -1) return null; switch (tag) { case 'circle' : case 'ellipse' : if (tag === 'circle') { l.rx = l.ry = l.r; } jPath.moveTo(l.cx+l.rx,l.cy); if (!normalize) { jPath.addSeg('A', l.cx-l.rx, l.cy, l.rx, l.ry, 0, 0, 1); jPath.addSeg('A', l.cx+l.rx, l.cy, l.rx, l.ry, 0, 0, 1); } else { kx = JSYG.kappa * l.rx; ky = JSYG.kappa * l.ry; jPath.curveTo(l.cx+l.rx, l.cy+ky, l.cx+kx, l.cy+l.ry, l.cx, l.cy+l.ry); jPath.curveTo(l.cx-kx, l.cy+l.ry, l.cx-l.rx, l.cy+ky,l.cx-l.rx, l.cy); jPath.curveTo(l.cx-l.rx, l.cy-ky, l.cx-kx, l.cy-l.ry,l.cx, l.cy-l.ry); jPath.curveTo(l.cx+kx, l.cy-l.ry, l.cx+l.rx, l.cy-ky,l.cx+l.rx, l.cy); } jPath.close(); break; case 'rect' : jPath.moveTo(l.x+l.rx,l.y); if (normalize) { if ((l.rx || l.ry)) { kx = JSYG.kappa*( l.rx || 0); ky = JSYG.kappa*( l.ry || 0); } jPath.lineTo(l.x+l.width-l.rx,l.y); if (l.rx || l.ry) { jPath.curveTo( l.x+l.width-l.rx+kx, l.y,l.x+l.width, l.y+l.ry-ky, l.x+l.width, l.y+l.ry); } jPath.lineTo(l.x+l.width,l.y+l.height-l.ry); if (l.rx || l.ry) { jPath.curveTo(l.x+l.width, l.y+l.height-l.ry+ky, l.x+l.width-l.rx+kx, l.y+l.height,l.x+l.width-l.rx, l.y+l.height); } jPath.lineTo(l.x+l.rx,l.y+l.height); if (l.rx || l.ry) { jPath.curveTo(l.x+l.rx-kx, l.y+l.height, l.x, l.y+l.height-l.ry+ky,l.x,l.y+l.height-l.ry); } jPath.lineTo(l.x,l.y+l.ry); if (l.rx || l.ry) { jPath.curveTo(l.x, l.y+l.ry-ky, l.x+l.rx-kx, l.y,l.x+l.rx,l.y); } } else { jPath.addSeg('H',l.x+l.width-l.rx); if (l.rx || l.ry) { jPath.addSeg('A', l.x+l.width, l.y+l.ry, l.rx, l.ry, 0, 0, 1); } jPath.addSeg('V',l.y+l.height-l.ry); if (l.rx || l.ry) { jPath.addSeg('A',l.x+l.width-l.rx, l.y+l.height, l.rx, l.ry, 0, 0, 1); } jPath.addSeg('H',l.x+l.rx); if (l.rx || l.ry) { jPath.addSeg('A', l.x,l.y+l.height-l.ry, l.rx, l.ry, 0, 0, 1); } jPath.addSeg('V',l.y+l.ry); if (l.rx || l.ry) { jPath.addSeg('A', l.x+l.rx,l.y, l.rx, l.ry, 0, 0, 1); } } jPath.addSeg('Z'); break; case 'line' : jPath.moveTo(l.x1,l.y1).lineTo(l.x2,l.y2); break; case 'polyline' : case 'polygon' : points = this.node.points; pt = points.getItem(0); jPath.moveTo(pt.x,pt.y); for(i=1,N=points.numberOfItems;i<N;i++) { pt = points.getItem(i); jPath.lineTo(pt.x,pt.y); } if (tag === 'polygon') jPath.close(); break; case 'path' : thisPath = new JSYG.Path(this.node); thisPath.getSegList().forEach(function(seg) { jPath.appendSeg(seg); }); if (normalize) jPath.normalize(); break; /* default : jPath.moveTo(l.x,l.y); jPath.lineTo(l.x+l.width,l.y); jPath.lineTo(l.x+l.width,l.y+l.height); jPath.lineTo(l.x,l.y+l.height); jPath.lineTo(l.x,l.y); jPath.close(); break; */ } if (transform) jPath.setMtx(this.getMtx()); if (style) jPath.styleClone(this.node); return jPath; }; /** * Teste si la forme passée en param�tre est � l'int�rieur de l'élément. * méthode de calcul un peu bourrin, gagnerait � �tre am�lior�. * @param shape argument JSYG faisant référence � une forme SVG * @returns {Boolean} */ JSYG.prototype.isShapeInside = function(shape) { if (!this.isClosed()) { return false; } var jShape = new JSYG(shape).clonePath({normalize:true,transform:true}).css('visibility','hidden').appendTo(this.parent()).mtx2attrs().toPolyline(); var clone = this.clonePath({normalize:true,transform:true}).css('visibility','hidden').appendTo(this.parent()).mtx2attrs().toPolyline(); var test = true; for (var i=0,N=jShape.getLength();i<N;i++) { if (!clone.isPointInside(jShape.getPointAtLength(i))) { test = false; break; } } jShape.remove(); clone.remove(); return test; }; /** * Transforme une courbe quelconque en segments de type C * @returns {JSYG.Path} */ JSYG.Path.prototype.toCubicCurve = function() { this.normalize(); var segList = this.getSegList(), that = this; segList.forEach(function(seg,i) { if (seg.pathSegTypeAsLetter != 'L') return; var prec = segList[i-1], newseg = that.createSeg('C',seg.x,seg.y,prec.x,prec.y,seg.x,seg.y); that.replaceSeg(i,newseg); }); return this; }; return JSYG.Path; });
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Geos2 Schema */ var Geos2Schema = new Schema({ name: { type: String, default: '', required: 'Please fill Geos2 name', trim: true }, created: { type: Date, default: Date.now }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('Geos2', Geos2Schema);
/** * Created by yangyxu on 8/20/14. */ zn.define(function () { return zn.Class({ statics: { getInstance: function (inArgs, context) { return new this(inArgs, context); } }, methods: { init: { auto: true, value: function (args, context){ this._table = null; this._context = context; this.sets(args); } }, build: function (message){ throw new Error(message || 'The Schema Class must be implement the build method.'); }, query: function () { return this._context.query(this.build()); } } }); });
define([ "backbone" ], function( Backbone ) { return Backbone.UniqueModel(Backbone.Model.extend({ }), "Contributor"); });
'use strict'; import createReactClass from 'create-react-class'; const SomeMixin = { componentDidMount() { console.log('did mount'); }, }; export default createReactClass({ displayName: 'class-prune-react.input', mixins: [SomeMixin], render: function() { return null; }, });
const { declMatches, parseSelector } = require('../../machinery/ast') const { isFile } = require('../../machinery/filename') const allowedInReset = [ 'width', 'height', 'max-width', 'max-height', 'margin', 'margin-top', 'margin-right', 'margin-bottom', 'margin-left', ] const messages = { 'no class selectors': selector => `Unexpected class selector '${selector}', only tag selectors are allowed in reset.css`, 'only scope custom element': `Invalid @kaliber-scoped, you can only scope using custom elements` } module.exports = { ruleName: 'reset', ruleInteraction: { 'layout-related-properties': { rootAllowDecl: decl => isReset(decl.root()) && declMatches(decl, allowedInReset), }, 'selector-policy': { tagSelectorsAllowCss: isReset }, 'at-rule-restrictions': { allowSpecificKaliberScoped: rule => isReset(rule.root()) && ( /[a-z]+(-[a-z]+)+/.test(rule.params) || messages['only scope custom element'] ), }, }, cssRequirements: { // resolvedCustomSelectors: true, TODO: add test case }, messages, create(config) { return ({ originalRoot, modifiedRoot, report, context }) => { onlyTagSelectorsInReset({ root: modifiedRoot, report }) } } } function onlyTagSelectorsInReset({ root, report }) { if (!isReset(root)) return root.walkRules(rule => { const selectors = parseSelector(rule) selectors.each(selector => { let [classNode] = selector.filter(x => x.type === 'class') const [globalNode] = selector.filter(x => x.type === 'pseudo' && x.value === ':global') if (!classNode) { if (!globalNode) return [classNode] = globalNode.first.filter(x => x.type === 'class') } report(rule, messages['no class selectors'](classNode.value), classNode.sourceIndex + 1) }) }) } function isReset(root) { return isFile(root, 'reset.css') }
(function(root, factory) { if(typeof exports === 'object') { module.exports = factory(); } else if(typeof define === 'function' && define.amd) { define('GMaps', [], factory); } root.GMaps = factory(); }(this, function() { /*! * GMaps.js v0.4.13 * http://hpneo.github.com/gmaps/ * * Copyright 2014, Gustavo Leon * Released under the MIT License. */ if (!(typeof window.google === 'object' && window.google.maps)) { throw 'Google Maps API is required. Please register the following JavaScript library http://maps.google.com/maps/api/js?sensor=true.' } var extend_object = function(obj, new_obj) { var name; if (obj === new_obj) { return obj; } for (name in new_obj) { obj[name] = new_obj[name]; } return obj; }; var replace_object = function(obj, replace) { var name; if (obj === replace) { return obj; } for (name in replace) { if (obj[name] != undefined) { obj[name] = replace[name]; } } return obj; }; var array_map = function(array, callback) { var original_callback_params = Array.prototype.slice.call(arguments, 2), array_return = [], array_length = array.length, i; if (Array.prototype.map && array.map === Array.prototype.map) { array_return = Array.prototype.map.call(array, function(item) { callback_params = original_callback_params; callback_params.splice(0, 0, item); return callback.apply(this, callback_params); }); } else { for (i = 0; i < array_length; i++) { callback_params = original_callback_params; callback_params.splice(0, 0, array[i]); array_return.push(callback.apply(this, callback_params)); } } return array_return; }; var array_flat = function(array) { var new_array = [], i; for (i = 0; i < array.length; i++) { new_array = new_array.concat(array[i]); } return new_array; }; var coordsToLatLngs = function(coords, useGeoJSON) { var first_coord = coords[0], second_coord = coords[1]; if (useGeoJSON) { first_coord = coords[1]; second_coord = coords[0]; } return new google.maps.LatLng(first_coord, second_coord); }; var arrayToLatLng = function(coords, useGeoJSON) { var i; for (i = 0; i < coords.length; i++) { if (coords[i].length > 0 && typeof(coords[i][0]) == "object") { coords[i] = arrayToLatLng(coords[i], useGeoJSON); } else { coords[i] = coordsToLatLngs(coords[i], useGeoJSON); } } return coords; }; var getElementById = function(id, context) { var element, id = id.replace('#', ''); if ('jQuery' in this && context) { element = $("#" + id, context)[0]; } else { element = document.getElementById(id); }; return element; }; var findAbsolutePosition = function(obj) { var curleft = 0, curtop = 0; if (obj.offsetParent) { do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while (obj = obj.offsetParent); } return [curleft, curtop]; }; var GMaps = (function(global) { "use strict"; var doc = document; var GMaps = function(options) { if (!this) return new GMaps(options); options.zoom = options.zoom || 15; options.mapType = options.mapType || 'roadmap'; var self = this, i, events_that_hide_context_menu = ['bounds_changed', 'center_changed', 'click', 'dblclick', 'drag', 'dragend', 'dragstart', 'idle', 'maptypeid_changed', 'projection_changed', 'resize', 'tilesloaded', 'zoom_changed'], events_that_doesnt_hide_context_menu = ['mousemove', 'mouseout', 'mouseover'], options_to_be_deleted = ['el', 'lat', 'lng', 'mapType', 'width', 'height', 'markerClusterer', 'enableNewStyle'], container_id = options.el || options.div, markerClustererFunction = options.markerClusterer, mapType = google.maps.MapTypeId[options.mapType.toUpperCase()], map_center = new google.maps.LatLng(options.lat, options.lng), zoomControl = options.zoomControl || true, zoomControlOpt = options.zoomControlOpt || { style: 'DEFAULT', position: 'TOP_LEFT' }, zoomControlStyle = zoomControlOpt.style || 'DEFAULT', zoomControlPosition = zoomControlOpt.position || 'TOP_LEFT', panControl = options.panControl || true, mapTypeControl = options.mapTypeControl || true, scaleControl = options.scaleControl || true, streetViewControl = options.streetViewControl || true, overviewMapControl = overviewMapControl || true, map_options = {}, map_base_options = { zoom: this.zoom, center: map_center, mapTypeId: mapType }, map_controls_options = { panControl: panControl, zoomControl: zoomControl, zoomControlOptions: { style: google.maps.ZoomControlStyle[zoomControlStyle], position: google.maps.ControlPosition[zoomControlPosition] }, mapTypeControl: mapTypeControl, scaleControl: scaleControl, streetViewControl: streetViewControl, overviewMapControl: overviewMapControl }; if (typeof(options.el) === 'string' || typeof(options.div) === 'string') { this.el = getElementById(container_id, options.context); } else { this.el = container_id; } if (typeof(this.el) === 'undefined' || this.el === null) { throw 'No element defined.'; } window.context_menu = window.context_menu || {}; window.context_menu[self.el.id] = {}; this.controls = []; this.overlays = []; this.layers = []; // array with kml/georss and fusiontables layers, can be as many this.singleLayers = {}; // object with the other layers, only one per layer this.markers = []; this.polylines = []; this.routes = []; this.polygons = []; this.infoWindow = null; this.overlay_el = null; this.zoom = options.zoom; this.registered_events = {}; this.el.style.width = options.width || this.el.scrollWidth || this.el.offsetWidth; this.el.style.height = options.height || this.el.scrollHeight || this.el.offsetHeight; google.maps.visualRefresh = options.enableNewStyle; for (i = 0; i < options_to_be_deleted.length; i++) { delete options[options_to_be_deleted[i]]; } if(options.disableDefaultUI != true) { map_base_options = extend_object(map_base_options, map_controls_options); } map_options = extend_object(map_base_options, options); for (i = 0; i < events_that_hide_context_menu.length; i++) { delete map_options[events_that_hide_context_menu[i]]; } for (i = 0; i < events_that_doesnt_hide_context_menu.length; i++) { delete map_options[events_that_doesnt_hide_context_menu[i]]; } this.map = new google.maps.Map(this.el, map_options); if (markerClustererFunction) { this.markerClusterer = markerClustererFunction.apply(this, [this.map]); } var buildContextMenuHTML = function(control, e) { var html = '', options = window.context_menu[self.el.id][control]; for (var i in options){ if (options.hasOwnProperty(i)) { var option = options[i]; html += '<li><a id="' + control + '_' + i + '" href="#">' + option.title + '</a></li>'; } } if (!getElementById('gmaps_context_menu')) return; var context_menu_element = getElementById('gmaps_context_menu'); context_menu_element.innerHTML = html; var context_menu_items = context_menu_element.getElementsByTagName('a'), context_menu_items_count = context_menu_items.length, i; for (i = 0; i < context_menu_items_count; i++) { var context_menu_item = context_menu_items[i]; var assign_menu_item_action = function(ev){ ev.preventDefault(); options[this.id.replace(control + '_', '')].action.apply(self, [e]); self.hideContextMenu(); }; google.maps.event.clearListeners(context_menu_item, 'click'); google.maps.event.addDomListenerOnce(context_menu_item, 'click', assign_menu_item_action, false); } var position = findAbsolutePosition.apply(this, [self.el]), left = position[0] + e.pixel.x - 15, top = position[1] + e.pixel.y- 15; context_menu_element.style.left = left + "px"; context_menu_element.style.top = top + "px"; context_menu_element.style.display = 'block'; }; this.buildContextMenu = function(control, e) { if (control === 'marker') { e.pixel = {}; var overlay = new google.maps.OverlayView(); overlay.setMap(self.map); overlay.draw = function() { var projection = overlay.getProjection(), position = e.marker.getPosition(); e.pixel = projection.fromLatLngToContainerPixel(position); buildContextMenuHTML(control, e); }; } else { buildContextMenuHTML(control, e); } }; this.setContextMenu = function(options) { window.context_menu[self.el.id][options.control] = {}; var i, ul = doc.createElement('ul'); for (i in options.options) { if (options.options.hasOwnProperty(i)) { var option = options.options[i]; window.context_menu[self.el.id][options.control][option.name] = { title: option.title, action: option.action }; } } ul.id = 'gmaps_context_menu'; ul.style.display = 'none'; ul.style.position = 'absolute'; ul.style.minWidth = '100px'; ul.style.background = 'white'; ul.style.listStyle = 'none'; ul.style.padding = '8px'; ul.style.boxShadow = '2px 2px 6px #ccc'; doc.body.appendChild(ul); var context_menu_element = getElementById('gmaps_context_menu') google.maps.event.addDomListener(context_menu_element, 'mouseout', function(ev) { if (!ev.relatedTarget || !this.contains(ev.relatedTarget)) { window.setTimeout(function(){ context_menu_element.style.display = 'none'; }, 400); } }, false); }; this.hideContextMenu = function() { var context_menu_element = getElementById('gmaps_context_menu'); if (context_menu_element) { context_menu_element.style.display = 'none'; } }; var setupListener = function(object, name) { google.maps.event.addListener(object, name, function(e){ if (e == undefined) { e = this; } options[name].apply(this, [e]); self.hideContextMenu(); }); }; for (var ev = 0; ev < events_that_hide_context_menu.length; ev++) { var name = events_that_hide_context_menu[ev]; if (name in options) { setupListener(this.map, name); } } for (var ev = 0; ev < events_that_doesnt_hide_context_menu.length; ev++) { var name = events_that_doesnt_hide_context_menu[ev]; if (name in options) { setupListener(this.map, name); } } google.maps.event.addListener(this.map, 'rightclick', function(e) { if (options.rightclick) { options.rightclick.apply(this, [e]); } if(window.context_menu[self.el.id]['map'] != undefined) { self.buildContextMenu('map', e); } }); this.refresh = function() { google.maps.event.trigger(this.map, 'resize'); }; this.fitZoom = function() { var latLngs = [], markers_length = this.markers.length, i; for (i = 0; i < markers_length; i++) { if(typeof(this.markers[i].visible) === 'boolean' && this.markers[i].visible) { latLngs.push(this.markers[i].getPosition()); } } this.fitLatLngBounds(latLngs); }; this.fitLatLngBounds = function(latLngs) { var total = latLngs.length; var bounds = new google.maps.LatLngBounds(); for(var i=0; i < total; i++) { bounds.extend(latLngs[i]); } this.map.fitBounds(bounds); }; this.setCenter = function(lat, lng, callback) { this.map.panTo(new google.maps.LatLng(lat, lng)); if (callback) { callback(); } }; this.getElement = function() { return this.el; }; this.zoomIn = function(value) { value = value || 1; this.zoom = this.map.getZoom() + value; this.map.setZoom(this.zoom); }; this.zoomOut = function(value) { value = value || 1; this.zoom = this.map.getZoom() - value; this.map.setZoom(this.zoom); }; var native_methods = [], method; for (method in this.map) { if (typeof(this.map[method]) == 'function' && !this[method]) { native_methods.push(method); } } for (i=0; i < native_methods.length; i++) { (function(gmaps, scope, method_name) { gmaps[method_name] = function(){ return scope[method_name].apply(scope, arguments); }; })(this, this.map, native_methods[i]); } }; return GMaps; })(this); GMaps.prototype.createControl = function(options) { var control = document.createElement('div'); control.style.cursor = 'pointer'; if (options.disableDefaultStyles !== true) { control.style.fontFamily = 'Roboto, Arial, sans-serif'; control.style.fontSize = '11px'; control.style.boxShadow = 'rgba(0, 0, 0, 0.298039) 0px 1px 4px -1px'; } for (var option in options.style) { control.style[option] = options.style[option]; } if (options.id) { control.id = options.id; } if (options.classes) { control.className = options.classes; } if (options.content) { control.innerHTML = options.content; } if (options.position) { control.position = google.maps.ControlPosition[options.position.toUpperCase()]; } for (var ev in options.events) { (function(object, name) { google.maps.event.addDomListener(object, name, function(){ options.events[name].apply(this, [this]); }); })(control, ev); } control.index = 1; return control; }; GMaps.prototype.addControl = function(options) { var control = this.createControl(options); this.controls.push(control); this.map.controls[control.position].push(control); return control; }; GMaps.prototype.removeControl = function(control) { var position = null; for (var i = 0; i < this.controls.length; i++) { if (this.controls[i] == control) { position = this.controls[i].position; this.controls.splice(i, 1); } } if (position) { for (i = 0; i < this.map.controls.length; i++) { var controlsForPosition = this.map.controls[control.position] if (controlsForPosition.getAt(i) == control) { controlsForPosition.removeAt(i); break; } } } return control; }; GMaps.prototype.createMarker = function(options) { if (options.lat == undefined && options.lng == undefined && options.position == undefined) { throw 'No latitude or longitude defined.'; } var self = this, details = options.details, fences = options.fences, outside = options.outside, base_options = { position: new google.maps.LatLng(options.lat, options.lng), map: null }, marker_options = extend_object(base_options, options); delete marker_options.lat; delete marker_options.lng; delete marker_options.fences; delete marker_options.outside; var marker = new google.maps.Marker(marker_options); marker.fences = fences; if (options.infoWindow) { marker.infoWindow = new google.maps.InfoWindow(options.infoWindow); var info_window_events = ['closeclick', 'content_changed', 'domready', 'position_changed', 'zindex_changed']; for (var ev = 0; ev < info_window_events.length; ev++) { (function(object, name) { if (options.infoWindow[name]) { google.maps.event.addListener(object, name, function(e){ options.infoWindow[name].apply(this, [e]); }); } })(marker.infoWindow, info_window_events[ev]); } } var marker_events = ['animation_changed', 'clickable_changed', 'cursor_changed', 'draggable_changed', 'flat_changed', 'icon_changed', 'position_changed', 'shadow_changed', 'shape_changed', 'title_changed', 'visible_changed', 'zindex_changed']; var marker_events_with_mouse = ['dblclick', 'drag', 'dragend', 'dragstart', 'mousedown', 'mouseout', 'mouseover', 'mouseup']; for (var ev = 0; ev < marker_events.length; ev++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(){ options[name].apply(this, [this]); }); } })(marker, marker_events[ev]); } for (var ev = 0; ev < marker_events_with_mouse.length; ev++) { (function(map, object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(me){ if(!me.pixel){ me.pixel = map.getProjection().fromLatLngToPoint(me.latLng) } options[name].apply(this, [me]); }); } })(this.map, marker, marker_events_with_mouse[ev]); } google.maps.event.addListener(marker, 'click', function() { this.details = details; if (options.click) { options.click.apply(this, [this]); } if (marker.infoWindow) { self.hideInfoWindows(); marker.infoWindow.open(self.map, marker); } }); google.maps.event.addListener(marker, 'rightclick', function(e) { e.marker = this; if (options.rightclick) { options.rightclick.apply(this, [e]); } if (window.context_menu[self.el.id]['marker'] != undefined) { self.buildContextMenu('marker', e); } }); if (marker.fences) { google.maps.event.addListener(marker, 'dragend', function() { self.checkMarkerGeofence(marker, function(m, f) { outside(m, f); }); }); } return marker; }; GMaps.prototype.addMarker = function(options) { var marker; if(options.hasOwnProperty('gm_accessors_')) { // Native google.maps.Marker object marker = options; } else { if ((options.hasOwnProperty('lat') && options.hasOwnProperty('lng')) || options.position) { marker = this.createMarker(options); } else { throw 'No latitude or longitude defined.'; } } marker.setMap(this.map); if(this.markerClusterer) { this.markerClusterer.addMarker(marker); } this.markers.push(marker); GMaps.fire('marker_added', marker, this); return marker; }; GMaps.prototype.addMarkers = function(array) { for (var i = 0, marker; marker=array[i]; i++) { this.addMarker(marker); } return this.markers; }; GMaps.prototype.hideInfoWindows = function() { for (var i = 0, marker; marker = this.markers[i]; i++){ if (marker.infoWindow) { marker.infoWindow.close(); } } }; GMaps.prototype.removeMarker = function(marker) { for (var i = 0; i < this.markers.length; i++) { if (this.markers[i] === marker) { this.markers[i].setMap(null); this.markers.splice(i, 1); if(this.markerClusterer) { this.markerClusterer.removeMarker(marker); } GMaps.fire('marker_removed', marker, this); break; } } return marker; }; GMaps.prototype.removeMarkers = function (collection) { var new_markers = []; if (typeof collection == 'undefined') { for (var i = 0; i < this.markers.length; i++) { this.markers[i].setMap(null); } this.markers = new_markers; } else { for (var i = 0; i < collection.length; i++) { if (this.markers.indexOf(collection[i]) > -1) { this.markers[i].setMap(null); } } for (var i = 0; i < this.markers.length; i++) { if (this.markers[i].getMap() != null) { new_markers.push(this.markers[i]); } } this.markers = new_markers; } }; GMaps.prototype.drawOverlay = function(options) { var overlay = new google.maps.OverlayView(), auto_show = true; overlay.setMap(this.map); if (options.auto_show != null) { auto_show = options.auto_show; } overlay.onAdd = function() { var el = document.createElement('div'); el.style.borderStyle = "none"; el.style.borderWidth = "0px"; el.style.position = "absolute"; el.style.zIndex = 100; el.innerHTML = options.content; overlay.el = el; if (!options.layer) { options.layer = 'overlayLayer'; } var panes = this.getPanes(), overlayLayer = panes[options.layer], stop_overlay_events = ['contextmenu', 'DOMMouseScroll', 'dblclick', 'mousedown']; overlayLayer.appendChild(el); for (var ev = 0; ev < stop_overlay_events.length; ev++) { (function(object, name) { google.maps.event.addDomListener(object, name, function(e){ if (navigator.userAgent.toLowerCase().indexOf('msie') != -1 && document.all) { e.cancelBubble = true; e.returnValue = false; } else { e.stopPropagation(); } }); })(el, stop_overlay_events[ev]); } if (options.click) { google.maps.event.addDomListener(overlay.el, 'click', function() { options.click.apply(overlay, [overlay]); }); } google.maps.event.trigger(this, 'ready'); }; overlay.draw = function() { var projection = this.getProjection(), pixel = projection.fromLatLngToDivPixel(new google.maps.LatLng(options.lat, options.lng)); options.horizontalOffset = options.horizontalOffset || 0; options.verticalOffset = options.verticalOffset || 0; var el = overlay.el, content = el.children[0], content_height = content.clientHeight, content_width = content.clientWidth; switch (options.verticalAlign) { case 'top': el.style.top = (pixel.y - content_height + options.verticalOffset) + 'px'; break; default: case 'middle': el.style.top = (pixel.y - (content_height / 2) + options.verticalOffset) + 'px'; break; case 'bottom': el.style.top = (pixel.y + options.verticalOffset) + 'px'; break; } switch (options.horizontalAlign) { case 'left': el.style.left = (pixel.x - content_width + options.horizontalOffset) + 'px'; break; default: case 'center': el.style.left = (pixel.x - (content_width / 2) + options.horizontalOffset) + 'px'; break; case 'right': el.style.left = (pixel.x + options.horizontalOffset) + 'px'; break; } el.style.display = auto_show ? 'block' : 'none'; if (!auto_show) { options.show.apply(this, [el]); } }; overlay.onRemove = function() { var el = overlay.el; if (options.remove) { options.remove.apply(this, [el]); } else { overlay.el.parentNode.removeChild(overlay.el); overlay.el = null; } }; this.overlays.push(overlay); return overlay; }; GMaps.prototype.removeOverlay = function(overlay) { for (var i = 0; i < this.overlays.length; i++) { if (this.overlays[i] === overlay) { this.overlays[i].setMap(null); this.overlays.splice(i, 1); break; } } }; GMaps.prototype.removeOverlays = function() { for (var i = 0, item; item = this.overlays[i]; i++) { item.setMap(null); } this.overlays = []; }; GMaps.prototype.drawPolyline = function(options) { var path = [], points = options.path; if (points.length) { if (points[0][0] === undefined) { path = points; } else { for (var i=0, latlng; latlng=points[i]; i++) { path.push(new google.maps.LatLng(latlng[0], latlng[1])); } } } var polyline_options = { map: this.map, path: path, strokeColor: options.strokeColor, strokeOpacity: options.strokeOpacity, strokeWeight: options.strokeWeight, geodesic: options.geodesic, clickable: true, editable: false, visible: true }; if (options.hasOwnProperty("clickable")) { polyline_options.clickable = options.clickable; } if (options.hasOwnProperty("editable")) { polyline_options.editable = options.editable; } if (options.hasOwnProperty("icons")) { polyline_options.icons = options.icons; } if (options.hasOwnProperty("zIndex")) { polyline_options.zIndex = options.zIndex; } var polyline = new google.maps.Polyline(polyline_options); var polyline_events = ['click', 'dblclick', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'rightclick']; for (var ev = 0; ev < polyline_events.length; ev++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(e){ options[name].apply(this, [e]); }); } })(polyline, polyline_events[ev]); } this.polylines.push(polyline); GMaps.fire('polyline_added', polyline, this); return polyline; }; GMaps.prototype.removePolyline = function(polyline) { for (var i = 0; i < this.polylines.length; i++) { if (this.polylines[i] === polyline) { this.polylines[i].setMap(null); this.polylines.splice(i, 1); GMaps.fire('polyline_removed', polyline, this); break; } } }; GMaps.prototype.removePolylines = function() { for (var i = 0, item; item = this.polylines[i]; i++) { item.setMap(null); } this.polylines = []; }; GMaps.prototype.drawCircle = function(options) { options = extend_object({ map: this.map, center: new google.maps.LatLng(options.lat, options.lng) }, options); delete options.lat; delete options.lng; var polygon = new google.maps.Circle(options), polygon_events = ['click', 'dblclick', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'rightclick']; for (var ev = 0; ev < polygon_events.length; ev++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(e){ options[name].apply(this, [e]); }); } })(polygon, polygon_events[ev]); } this.polygons.push(polygon); return polygon; }; GMaps.prototype.drawRectangle = function(options) { options = extend_object({ map: this.map }, options); var latLngBounds = new google.maps.LatLngBounds( new google.maps.LatLng(options.bounds[0][0], options.bounds[0][1]), new google.maps.LatLng(options.bounds[1][0], options.bounds[1][1]) ); options.bounds = latLngBounds; var polygon = new google.maps.Rectangle(options), polygon_events = ['click', 'dblclick', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'rightclick']; for (var ev = 0; ev < polygon_events.length; ev++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(e){ options[name].apply(this, [e]); }); } })(polygon, polygon_events[ev]); } this.polygons.push(polygon); return polygon; }; GMaps.prototype.drawPolygon = function(options) { var useGeoJSON = false; if(options.hasOwnProperty("useGeoJSON")) { useGeoJSON = options.useGeoJSON; } delete options.useGeoJSON; options = extend_object({ map: this.map }, options); if (useGeoJSON == false) { options.paths = [options.paths.slice(0)]; } if (options.paths.length > 0) { if (options.paths[0].length > 0) { options.paths = array_flat(array_map(options.paths, arrayToLatLng, useGeoJSON)); } } var polygon = new google.maps.Polygon(options), polygon_events = ['click', 'dblclick', 'mousedown', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'rightclick']; for (var ev = 0; ev < polygon_events.length; ev++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(e){ options[name].apply(this, [e]); }); } })(polygon, polygon_events[ev]); } this.polygons.push(polygon); GMaps.fire('polygon_added', polygon, this); return polygon; }; GMaps.prototype.removePolygon = function(polygon) { for (var i = 0; i < this.polygons.length; i++) { if (this.polygons[i] === polygon) { this.polygons[i].setMap(null); this.polygons.splice(i, 1); GMaps.fire('polygon_removed', polygon, this); break; } } }; GMaps.prototype.removePolygons = function() { for (var i = 0, item; item = this.polygons[i]; i++) { item.setMap(null); } this.polygons = []; }; GMaps.prototype.getFromFusionTables = function(options) { var events = options.events; delete options.events; var fusion_tables_options = options, layer = new google.maps.FusionTablesLayer(fusion_tables_options); for (var ev in events) { (function(object, name) { google.maps.event.addListener(object, name, function(e) { events[name].apply(this, [e]); }); })(layer, ev); } this.layers.push(layer); return layer; }; GMaps.prototype.loadFromFusionTables = function(options) { var layer = this.getFromFusionTables(options); layer.setMap(this.map); return layer; }; GMaps.prototype.getFromKML = function(options) { var url = options.url, events = options.events; delete options.url; delete options.events; var kml_options = options, layer = new google.maps.KmlLayer(url, kml_options); for (var ev in events) { (function(object, name) { google.maps.event.addListener(object, name, function(e) { events[name].apply(this, [e]); }); })(layer, ev); } this.layers.push(layer); return layer; }; GMaps.prototype.loadFromKML = function(options) { var layer = this.getFromKML(options); layer.setMap(this.map); return layer; }; GMaps.prototype.addLayer = function(layerName, options) { //var default_layers = ['weather', 'clouds', 'traffic', 'transit', 'bicycling', 'panoramio', 'places']; options = options || {}; var layer; switch(layerName) { case 'weather': this.singleLayers.weather = layer = new google.maps.weather.WeatherLayer(); break; case 'clouds': this.singleLayers.clouds = layer = new google.maps.weather.CloudLayer(); break; case 'traffic': this.singleLayers.traffic = layer = new google.maps.TrafficLayer(); break; case 'transit': this.singleLayers.transit = layer = new google.maps.TransitLayer(); break; case 'bicycling': this.singleLayers.bicycling = layer = new google.maps.BicyclingLayer(); break; case 'panoramio': this.singleLayers.panoramio = layer = new google.maps.panoramio.PanoramioLayer(); layer.setTag(options.filter); delete options.filter; //click event if (options.click) { google.maps.event.addListener(layer, 'click', function(event) { options.click(event); delete options.click; }); } break; case 'places': this.singleLayers.places = layer = new google.maps.places.PlacesService(this.map); //search, nearbySearch, radarSearch callback, Both are the same if (options.search || options.nearbySearch || options.radarSearch) { var placeSearchRequest = { bounds : options.bounds || null, keyword : options.keyword || null, location : options.location || null, name : options.name || null, radius : options.radius || null, rankBy : options.rankBy || null, types : options.types || null }; if (options.radarSearch) { layer.radarSearch(placeSearchRequest, options.radarSearch); } if (options.search) { layer.search(placeSearchRequest, options.search); } if (options.nearbySearch) { layer.nearbySearch(placeSearchRequest, options.nearbySearch); } } //textSearch callback if (options.textSearch) { var textSearchRequest = { bounds : options.bounds || null, location : options.location || null, query : options.query || null, radius : options.radius || null }; layer.textSearch(textSearchRequest, options.textSearch); } break; } if (layer !== undefined) { if (typeof layer.setOptions == 'function') { layer.setOptions(options); } if (typeof layer.setMap == 'function') { layer.setMap(this.map); } return layer; } }; GMaps.prototype.removeLayer = function(layer) { if (typeof(layer) == "string" && this.singleLayers[layer] !== undefined) { this.singleLayers[layer].setMap(null); delete this.singleLayers[layer]; } else { for (var i = 0; i < this.layers.length; i++) { if (this.layers[i] === layer) { this.layers[i].setMap(null); this.layers.splice(i, 1); break; } } } }; var travelMode, unitSystem; GMaps.prototype.getRoutes = function(options) { switch (options.travelMode) { case 'bicycling': travelMode = google.maps.TravelMode.BICYCLING; break; case 'transit': travelMode = google.maps.TravelMode.TRANSIT; break; case 'driving': travelMode = google.maps.TravelMode.DRIVING; break; default: travelMode = google.maps.TravelMode.WALKING; break; } if (options.unitSystem === 'imperial') { unitSystem = google.maps.UnitSystem.IMPERIAL; } else { unitSystem = google.maps.UnitSystem.METRIC; } var base_options = { avoidHighways: false, avoidTolls: false, optimizeWaypoints: false, waypoints: [] }, request_options = extend_object(base_options, options); request_options.origin = /string/.test(typeof options.origin) ? options.origin : new google.maps.LatLng(options.origin[0], options.origin[1]); request_options.destination = /string/.test(typeof options.destination) ? options.destination : new google.maps.LatLng(options.destination[0], options.destination[1]); request_options.travelMode = travelMode; request_options.unitSystem = unitSystem; delete request_options.callback; delete request_options.error; var self = this, service = new google.maps.DirectionsService(); service.route(request_options, function(result, status) { if (status === google.maps.DirectionsStatus.OK) { for (var r in result.routes) { if (result.routes.hasOwnProperty(r)) { self.routes.push(result.routes[r]); } } if (options.callback) { options.callback(self.routes); } } else { if (options.error) { options.error(result, status); } } }); }; GMaps.prototype.removeRoutes = function() { this.routes = []; }; GMaps.prototype.getElevations = function(options) { options = extend_object({ locations: [], path : false, samples : 256 }, options); if (options.locations.length > 0) { if (options.locations[0].length > 0) { options.locations = array_flat(array_map([options.locations], arrayToLatLng, false)); } } var callback = options.callback; delete options.callback; var service = new google.maps.ElevationService(); //location request if (!options.path) { delete options.path; delete options.samples; service.getElevationForLocations(options, function(result, status) { if (callback && typeof(callback) === "function") { callback(result, status); } }); //path request } else { var pathRequest = { path : options.locations, samples : options.samples }; service.getElevationAlongPath(pathRequest, function(result, status) { if (callback && typeof(callback) === "function") { callback(result, status); } }); } }; GMaps.prototype.cleanRoute = GMaps.prototype.removePolylines; GMaps.prototype.drawRoute = function(options) { var self = this; this.getRoutes({ origin: options.origin, destination: options.destination, travelMode: options.travelMode, waypoints: options.waypoints, unitSystem: options.unitSystem, error: options.error, callback: function(e) { if (e.length > 0) { self.drawPolyline({ path: e[e.length - 1].overview_path, strokeColor: options.strokeColor, strokeOpacity: options.strokeOpacity, strokeWeight: options.strokeWeight }); if (options.callback) { options.callback(e[e.length - 1]); } } } }); }; GMaps.prototype.travelRoute = function(options) { if (options.origin && options.destination) { this.getRoutes({ origin: options.origin, destination: options.destination, travelMode: options.travelMode, waypoints : options.waypoints, unitSystem: options.unitSystem, error: options.error, callback: function(e) { //start callback if (e.length > 0 && options.start) { options.start(e[e.length - 1]); } //step callback if (e.length > 0 && options.step) { var route = e[e.length - 1]; if (route.legs.length > 0) { var steps = route.legs[0].steps; for (var i=0, step; step=steps[i]; i++) { step.step_number = i; options.step(step, (route.legs[0].steps.length - 1)); } } } //end callback if (e.length > 0 && options.end) { options.end(e[e.length - 1]); } } }); } else if (options.route) { if (options.route.legs.length > 0) { var steps = options.route.legs[0].steps; for (var i=0, step; step=steps[i]; i++) { step.step_number = i; options.step(step); } } } }; GMaps.prototype.drawSteppedRoute = function(options) { var self = this; if (options.origin && options.destination) { this.getRoutes({ origin: options.origin, destination: options.destination, travelMode: options.travelMode, waypoints : options.waypoints, error: options.error, callback: function(e) { //start callback if (e.length > 0 && options.start) { options.start(e[e.length - 1]); } //step callback if (e.length > 0 && options.step) { var route = e[e.length - 1]; if (route.legs.length > 0) { var steps = route.legs[0].steps; for (var i=0, step; step=steps[i]; i++) { step.step_number = i; self.drawPolyline({ path: step.path, strokeColor: options.strokeColor, strokeOpacity: options.strokeOpacity, strokeWeight: options.strokeWeight }); options.step(step, (route.legs[0].steps.length - 1)); } } } //end callback if (e.length > 0 && options.end) { options.end(e[e.length - 1]); } } }); } else if (options.route) { if (options.route.legs.length > 0) { var steps = options.route.legs[0].steps; for (var i=0, step; step=steps[i]; i++) { step.step_number = i; self.drawPolyline({ path: step.path, strokeColor: options.strokeColor, strokeOpacity: options.strokeOpacity, strokeWeight: options.strokeWeight }); options.step(step); } } } }; GMaps.Route = function(options) { this.origin = options.origin; this.destination = options.destination; this.waypoints = options.waypoints; this.map = options.map; this.route = options.route; this.step_count = 0; this.steps = this.route.legs[0].steps; this.steps_length = this.steps.length; this.polyline = this.map.drawPolyline({ path: new google.maps.MVCArray(), strokeColor: options.strokeColor, strokeOpacity: options.strokeOpacity, strokeWeight: options.strokeWeight }).getPath(); }; GMaps.Route.prototype.getRoute = function(options) { var self = this; this.map.getRoutes({ origin : this.origin, destination : this.destination, travelMode : options.travelMode, waypoints : this.waypoints || [], error: options.error, callback : function() { self.route = e[0]; if (options.callback) { options.callback.call(self); } } }); }; GMaps.Route.prototype.back = function() { if (this.step_count > 0) { this.step_count--; var path = this.route.legs[0].steps[this.step_count].path; for (var p in path){ if (path.hasOwnProperty(p)){ this.polyline.pop(); } } } }; GMaps.Route.prototype.forward = function() { if (this.step_count < this.steps_length) { var path = this.route.legs[0].steps[this.step_count].path; for (var p in path){ if (path.hasOwnProperty(p)){ this.polyline.push(path[p]); } } this.step_count++; } }; GMaps.prototype.checkGeofence = function(lat, lng, fence) { return fence.containsLatLng(new google.maps.LatLng(lat, lng)); }; GMaps.prototype.checkMarkerGeofence = function(marker, outside_callback) { if (marker.fences) { for (var i = 0, fence; fence = marker.fences[i]; i++) { var pos = marker.getPosition(); if (!this.checkGeofence(pos.lat(), pos.lng(), fence)) { outside_callback(marker, fence); } } } }; GMaps.prototype.toImage = function(options) { var options = options || {}, static_map_options = {}; static_map_options['size'] = options['size'] || [this.el.clientWidth, this.el.clientHeight]; static_map_options['lat'] = this.getCenter().lat(); static_map_options['lng'] = this.getCenter().lng(); if (this.markers.length > 0) { static_map_options['markers'] = []; for (var i = 0; i < this.markers.length; i++) { static_map_options['markers'].push({ lat: this.markers[i].getPosition().lat(), lng: this.markers[i].getPosition().lng() }); } } if (this.polylines.length > 0) { var polyline = this.polylines[0]; static_map_options['polyline'] = {}; static_map_options['polyline']['path'] = google.maps.geometry.encoding.encodePath(polyline.getPath()); static_map_options['polyline']['strokeColor'] = polyline.strokeColor static_map_options['polyline']['strokeOpacity'] = polyline.strokeOpacity static_map_options['polyline']['strokeWeight'] = polyline.strokeWeight } return GMaps.staticMapURL(static_map_options); }; GMaps.staticMapURL = function(options){ var parameters = [], data, static_root = 'http://maps.googleapis.com/maps/api/staticmap'; if (options.url) { static_root = options.url; delete options.url; } static_root += '?'; var markers = options.markers; delete options.markers; if (!markers && options.marker) { markers = [options.marker]; delete options.marker; } var styles = options.styles; delete options.styles; var polyline = options.polyline; delete options.polyline; /** Map options **/ if (options.center) { parameters.push('center=' + options.center); delete options.center; } else if (options.address) { parameters.push('center=' + options.address); delete options.address; } else if (options.lat) { parameters.push(['center=', options.lat, ',', options.lng].join('')); delete options.lat; delete options.lng; } else if (options.visible) { var visible = encodeURI(options.visible.join('|')); parameters.push('visible=' + visible); } var size = options.size; if (size) { if (size.join) { size = size.join('x'); } delete options.size; } else { size = '630x300'; } parameters.push('size=' + size); if (!options.zoom && options.zoom !== false) { options.zoom = 15; } var sensor = options.hasOwnProperty('sensor') ? !!options.sensor : true; delete options.sensor; parameters.push('sensor=' + sensor); for (var param in options) { if (options.hasOwnProperty(param)) { parameters.push(param + '=' + options[param]); } } /** Markers **/ if (markers) { var marker, loc; for (var i=0; data=markers[i]; i++) { marker = []; if (data.size && data.size !== 'normal') { marker.push('size:' + data.size); delete data.size; } else if (data.icon) { marker.push('icon:' + encodeURI(data.icon)); delete data.icon; } if (data.color) { marker.push('color:' + data.color.replace('#', '0x')); delete data.color; } if (data.label) { marker.push('label:' + data.label[0].toUpperCase()); delete data.label; } loc = (data.address ? data.address : data.lat + ',' + data.lng); delete data.address; delete data.lat; delete data.lng; for(var param in data){ if (data.hasOwnProperty(param)) { marker.push(param + ':' + data[param]); } } if (marker.length || i === 0) { marker.push(loc); marker = marker.join('|'); parameters.push('markers=' + encodeURI(marker)); } // New marker without styles else { marker = parameters.pop() + encodeURI('|' + loc); parameters.push(marker); } } } /** Map Styles **/ if (styles) { for (var i = 0; i < styles.length; i++) { var styleRule = []; if (styles[i].featureType){ styleRule.push('feature:' + styles[i].featureType.toLowerCase()); } if (styles[i].elementType) { styleRule.push('element:' + styles[i].elementType.toLowerCase()); } for (var j = 0; j < styles[i].stylers.length; j++) { for (var p in styles[i].stylers[j]) { var ruleArg = styles[i].stylers[j][p]; if (p == 'hue' || p == 'color') { ruleArg = '0x' + ruleArg.substring(1); } styleRule.push(p + ':' + ruleArg); } } var rule = styleRule.join('|'); if (rule != '') { parameters.push('style=' + rule); } } } /** Polylines **/ function parseColor(color, opacity) { if (color[0] === '#'){ color = color.replace('#', '0x'); if (opacity) { opacity = parseFloat(opacity); opacity = Math.min(1, Math.max(opacity, 0)); if (opacity === 0) { return '0x00000000'; } opacity = (opacity * 255).toString(16); if (opacity.length === 1) { opacity += opacity; } color = color.slice(0,8) + opacity; } } return color; } if (polyline) { data = polyline; polyline = []; if (data.strokeWeight) { polyline.push('weight:' + parseInt(data.strokeWeight, 10)); } if (data.strokeColor) { var color = parseColor(data.strokeColor, data.strokeOpacity); polyline.push('color:' + color); } if (data.fillColor) { var fillcolor = parseColor(data.fillColor, data.fillOpacity); polyline.push('fillcolor:' + fillcolor); } var path = data.path; if (path.join) { for (var j=0, pos; pos=path[j]; j++) { polyline.push(pos.join(',')); } } else { polyline.push('enc:' + path); } polyline = polyline.join('|'); parameters.push('path=' + encodeURI(polyline)); } /** Retina support **/ var dpi = window.devicePixelRatio || 1; parameters.push('scale=' + dpi); parameters = parameters.join('&'); return static_root + parameters; }; GMaps.prototype.addMapType = function(mapTypeId, options) { if (options.hasOwnProperty("getTileUrl") && typeof(options["getTileUrl"]) == "function") { options.tileSize = options.tileSize || new google.maps.Size(256, 256); var mapType = new google.maps.ImageMapType(options); this.map.mapTypes.set(mapTypeId, mapType); } else { throw "'getTileUrl' function required."; } }; GMaps.prototype.addOverlayMapType = function(options) { if (options.hasOwnProperty("getTile") && typeof(options["getTile"]) == "function") { var overlayMapTypeIndex = options.index; delete options.index; this.map.overlayMapTypes.insertAt(overlayMapTypeIndex, options); } else { throw "'getTile' function required."; } }; GMaps.prototype.removeOverlayMapType = function(overlayMapTypeIndex) { this.map.overlayMapTypes.removeAt(overlayMapTypeIndex); }; GMaps.prototype.addStyle = function(options) { var styledMapType = new google.maps.StyledMapType(options.styles, { name: options.styledMapName }); this.map.mapTypes.set(options.mapTypeId, styledMapType); }; GMaps.prototype.setStyle = function(mapTypeId) { this.map.setMapTypeId(mapTypeId); }; GMaps.prototype.createPanorama = function(streetview_options) { if (!streetview_options.hasOwnProperty('lat') || !streetview_options.hasOwnProperty('lng')) { streetview_options.lat = this.getCenter().lat(); streetview_options.lng = this.getCenter().lng(); } this.panorama = GMaps.createPanorama(streetview_options); this.map.setStreetView(this.panorama); return this.panorama; }; GMaps.createPanorama = function(options) { var el = getElementById(options.el, options.context); options.position = new google.maps.LatLng(options.lat, options.lng); delete options.el; delete options.context; delete options.lat; delete options.lng; var streetview_events = ['closeclick', 'links_changed', 'pano_changed', 'position_changed', 'pov_changed', 'resize', 'visible_changed'], streetview_options = extend_object({visible : true}, options); for (var i = 0; i < streetview_events.length; i++) { delete streetview_options[streetview_events[i]]; } var panorama = new google.maps.StreetViewPanorama(el, streetview_options); for (var i = 0; i < streetview_events.length; i++) { (function(object, name) { if (options[name]) { google.maps.event.addListener(object, name, function(){ options[name].apply(this); }); } })(panorama, streetview_events[i]); } return panorama; }; GMaps.prototype.on = function(event_name, handler) { return GMaps.on(event_name, this, handler); }; GMaps.prototype.off = function(event_name) { GMaps.off(event_name, this); }; GMaps.custom_events = ['marker_added', 'marker_removed', 'polyline_added', 'polyline_removed', 'polygon_added', 'polygon_removed', 'geolocated', 'geolocation_failed']; GMaps.on = function(event_name, object, handler) { if (GMaps.custom_events.indexOf(event_name) == -1) { if(object instanceof GMaps) object = object.map; return google.maps.event.addListener(object, event_name, handler); } else { var registered_event = { handler : handler, eventName : event_name }; object.registered_events[event_name] = object.registered_events[event_name] || []; object.registered_events[event_name].push(registered_event); return registered_event; } }; GMaps.off = function(event_name, object) { if (GMaps.custom_events.indexOf(event_name) == -1) { if(object instanceof GMaps) object = object.map; google.maps.event.clearListeners(object, event_name); } else { object.registered_events[event_name] = []; } }; GMaps.fire = function(event_name, object, scope) { if (GMaps.custom_events.indexOf(event_name) == -1) { google.maps.event.trigger(object, event_name, Array.prototype.slice.apply(arguments).slice(2)); } else { if(event_name in scope.registered_events) { var firing_events = scope.registered_events[event_name]; for(var i = 0; i < firing_events.length; i++) { (function(handler, scope, object) { handler.apply(scope, [object]); })(firing_events[i]['handler'], scope, object); } } } }; GMaps.geolocate = function(options) { var complete_callback = options.always || options.complete; if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { options.success(position); if (complete_callback) { complete_callback(); } }, function(error) { options.error(error); if (complete_callback) { complete_callback(); } }, options.options); } else { options.not_supported(); if (complete_callback) { complete_callback(); } } }; GMaps.geocode = function(options) { this.geocoder = new google.maps.Geocoder(); var callback = options.callback; if (options.hasOwnProperty('lat') && options.hasOwnProperty('lng')) { options.latLng = new google.maps.LatLng(options.lat, options.lng); } delete options.lat; delete options.lng; delete options.callback; this.geocoder.geocode(options, function(results, status) { callback(results, status); }); }; //========================== // Polygon containsLatLng // https://github.com/tparkin/Google-Maps-Point-in-Polygon // Poygon getBounds extension - google-maps-extensions // http://code.google.com/p/google-maps-extensions/source/browse/google.maps.Polygon.getBounds.js if (!google.maps.Polygon.prototype.getBounds) { google.maps.Polygon.prototype.getBounds = function(latLng) { var bounds = new google.maps.LatLngBounds(); var paths = this.getPaths(); var path; for (var p = 0; p < paths.getLength(); p++) { path = paths.getAt(p); for (var i = 0; i < path.getLength(); i++) { bounds.extend(path.getAt(i)); } } return bounds; }; } if (!google.maps.Polygon.prototype.containsLatLng) { // Polygon containsLatLng - method to determine if a latLng is within a polygon google.maps.Polygon.prototype.containsLatLng = function(latLng) { // Exclude points outside of bounds as there is no way they are in the poly var bounds = this.getBounds(); if (bounds !== null && !bounds.contains(latLng)) { return false; } // Raycast point in polygon method var inPoly = false; var numPaths = this.getPaths().getLength(); for (var p = 0; p < numPaths; p++) { var path = this.getPaths().getAt(p); var numPoints = path.getLength(); var j = numPoints - 1; for (var i = 0; i < numPoints; i++) { var vertex1 = path.getAt(i); var vertex2 = path.getAt(j); if (vertex1.lng() < latLng.lng() && vertex2.lng() >= latLng.lng() || vertex2.lng() < latLng.lng() && vertex1.lng() >= latLng.lng()) { if (vertex1.lat() + (latLng.lng() - vertex1.lng()) / (vertex2.lng() - vertex1.lng()) * (vertex2.lat() - vertex1.lat()) < latLng.lat()) { inPoly = !inPoly; } } j = i; } } return inPoly; }; } google.maps.LatLngBounds.prototype.containsLatLng = function(latLng) { return this.contains(latLng); }; google.maps.Marker.prototype.setFences = function(fences) { this.fences = fences; }; google.maps.Marker.prototype.addFence = function(fence) { this.fences.push(fence); }; google.maps.Marker.prototype.getId = function() { return this['__gm_id']; }; //========================== // Array indexOf // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) { "use strict"; if (this == null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n != n) { // shortcut for verifying if it's NaN n = 0; } else if (n != 0 && n != Infinity && n != -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; } } return GMaps; }));
( function ( mw ) { QUnit.module( 'ext.pageTriage.actionQueue' ); QUnit.test( 'Testing the queue: synchronous and asynchronous methods', function ( assert ) { var test = {}, pushToTest = function ( action, text, data ) { test[ action ] = test[ action ] || []; test[ action ].push( { action: action, text: text, data: data } ); }, done1 = assert.async(), done2 = assert.async(); mw.pageTriage.actionQueue.reset(); mw.pageTriage.actionQueue.add( 'action1', function ( data ) { pushToTest( 'action1', 'synchronous', data ); return true; } ); mw.pageTriage.actionQueue.add( 'action2', function ( data ) { pushToTest( 'action2', 'synchronous without returning true', data ); } ); mw.pageTriage.actionQueue.add( 'action1', function ( data ) { var $deferred = $.Deferred(); setTimeout( function () { pushToTest( 'action1', 'slow asynchronous success', data ); $deferred.resolve(); }, 500 ); return $deferred.promise(); } ); mw.pageTriage.actionQueue.add( 'action1', function ( data ) { var $deferred = $.Deferred(); setTimeout( function () { pushToTest( 'action1', 'quick asynchronous failure', data ); $deferred.reject(); }, 100 ); return $deferred.promise(); } ); // Check that on running the actions, the correct functions were added assert.deepEqual( mw.pageTriage.actionQueue.peek( 'action1' ).length, 3, 'Added three methods to "action1"' ); assert.deepEqual( mw.pageTriage.actionQueue.peek( 'action2' ).length, 1, 'Added one method to "action2"' ); // Run the queue mw.pageTriage.actionQueue.run( 'action1', [ 'testparam1', 'testparam2' ] ) .always( function () { assert.deepEqual( test.action1, [ { action: 'action1', text: 'synchronous', data: [ 'testparam1', 'testparam2' ] }, { action: 'action1', text: 'quick asynchronous failure', data: [ 'testparam1', 'testparam2' ] }, // Making sure that the slow success ran even thought there's a rejected promise before it { action: 'action1', text: 'slow asynchronous success', data: [ 'testparam1', 'testparam2' ] } ], 'Methods in "action1" ran successfully.' ); done1(); } ); mw.pageTriage.actionQueue.run( 'action2', { test1: 'param3', test2: 'param4' } ) .always( function () { assert.deepEqual( test.action2, [ { action: 'action2', text: 'synchronous without returning true', data: { test1: 'param3', test2: 'param4' } } ], 'Methods in "action2" ran successfully.' ); done2(); } ); } ); QUnit.test( 'Testing the queue: run() with multiple actions', function ( assert ) { var test = [], pushToTest = function ( action, text, data ) { test.push( { action: action, text: text, data: data } ); }, done = assert.async(); mw.pageTriage.actionQueue.reset(); // Add multiple methods to action1 mw.pageTriage.actionQueue.add( 'action1', function ( data ) { pushToTest( 'action1', 'foo', data ); } ); mw.pageTriage.actionQueue.add( 'action1', function ( data ) { pushToTest( 'action1', 'bar', data ); } ); mw.pageTriage.actionQueue.add( 'action1', function ( data ) { pushToTest( 'action1', 'baz', data ); } ); mw.pageTriage.actionQueue.add( 'action1', function ( data ) { var $deferred = $.Deferred(); setTimeout( function () { pushToTest( 'action1', 'slow asynchronous success', data ); $deferred.resolve(); }, 500 ); return $deferred.promise(); } ); // Add multiple methods to action2 mw.pageTriage.actionQueue.add( 'action2', function ( data ) { pushToTest( 'action2', 'foo2', data ); } ); mw.pageTriage.actionQueue.add( 'action2', function ( data ) { pushToTest( 'action2', 'bar2', data ); } ); mw.pageTriage.actionQueue.add( 'action2', function ( data ) { pushToTest( 'action2', 'baz2', data ); } ); mw.pageTriage.actionQueue.add( 'action2', function ( data ) { var $deferred = $.Deferred(); setTimeout( function () { pushToTest( 'action2', 'quick asynchronous failure', data ); $deferred.reject(); }, 100 ); return $deferred.promise(); } ); // Run both actions at once mw.pageTriage.actionQueue.run( [ 'action1', 'action2' ], { param1: 'something', param2: 'else' } ) .then( function () { // Check that all functions from both action queues ran assert.deepEqual( test, [ { action: 'action1', text: 'foo', data: { param1: 'something', param2: 'else' } }, { action: 'action1', text: 'bar', data: { param1: 'something', param2: 'else' } }, { action: 'action1', text: 'baz', data: { param1: 'something', param2: 'else' } }, { action: 'action2', text: 'foo2', data: { param1: 'something', param2: 'else' } }, { action: 'action2', text: 'bar2', data: { param1: 'something', param2: 'else' } }, { action: 'action2', text: 'baz2', data: { param1: 'something', param2: 'else' } }, { action: 'action2', text: 'quick asynchronous failure', data: { param1: 'something', param2: 'else' } }, { action: 'action1', text: 'slow asynchronous success', data: { param1: 'something', param2: 'else' } } ], 'Methods from both queues ran successfully.' ); done(); } ); } ); QUnit.test( 'Testing the queue: run() with actions with action-specific data', function ( assert ) { var test = [], pushToTest = function ( action, text, data ) { test.push( { action: action, text: text, data: data } ); }, done = assert.async(); mw.pageTriage.actionQueue.reset(); // Add multiple methods to action1 mw.pageTriage.actionQueue.add( 'action1', function ( data ) { pushToTest( 'action1', 'foo', data ); } ); mw.pageTriage.actionQueue.add( 'action1', function ( data ) { pushToTest( 'action1', 'bar', data ); } ); mw.pageTriage.actionQueue.add( 'action1', function ( data ) { pushToTest( 'action1', 'baz', data ); } ); mw.pageTriage.actionQueue.add( 'action1', function ( data ) { var $deferred = $.Deferred(); setTimeout( function () { pushToTest( 'action1', 'slow asynchronous success', data ); $deferred.resolve(); }, 500 ); return $deferred.promise(); } ); // Add multiple methods to action2 mw.pageTriage.actionQueue.add( 'action2', function ( data ) { pushToTest( 'action2', 'foo2', data ); } ); mw.pageTriage.actionQueue.add( 'action2', function ( data ) { pushToTest( 'action2', 'bar2', data ); } ); mw.pageTriage.actionQueue.add( 'action2', function ( data ) { pushToTest( 'action2', 'baz2', data ); } ); mw.pageTriage.actionQueue.add( 'action2', function ( data ) { var $deferred = $.Deferred(); setTimeout( function () { pushToTest( 'action2', 'quick asynchronous failure', data ); $deferred.reject(); }, 100 ); return $deferred.promise(); } ); // Run both actions at once mw.pageTriage.actionQueue.run( { action1: { actionSpecific: 'onlyAction1GetsThis' }, action2: { somethingElse: true, andAnother: 'somethingAction2Does' } }, // General data sent to all { param1: 'allActions', param2: 'getThese' } ) .then( function () { // Check that all functions from both action queues ran assert.deepEqual( test, [ { action: 'action1', text: 'foo', data: { param1: 'allActions', param2: 'getThese', actionSpecific: 'onlyAction1GetsThis' } }, { action: 'action1', text: 'bar', data: { param1: 'allActions', param2: 'getThese', actionSpecific: 'onlyAction1GetsThis' } }, { action: 'action1', text: 'baz', data: { param1: 'allActions', param2: 'getThese', actionSpecific: 'onlyAction1GetsThis' } }, { action: 'action2', text: 'foo2', data: { param1: 'allActions', param2: 'getThese', somethingElse: true, andAnother: 'somethingAction2Does' } }, { action: 'action2', text: 'bar2', data: { param1: 'allActions', param2: 'getThese', somethingElse: true, andAnother: 'somethingAction2Does' } }, { action: 'action2', text: 'baz2', data: { param1: 'allActions', param2: 'getThese', somethingElse: true, andAnother: 'somethingAction2Does' } }, { action: 'action2', text: 'quick asynchronous failure', data: { param1: 'allActions', param2: 'getThese', somethingElse: true, andAnother: 'somethingAction2Does' } }, { action: 'action1', text: 'slow asynchronous success', data: { param1: 'allActions', param2: 'getThese', actionSpecific: 'onlyAction1GetsThis' } } ], 'Methods from both queues ran successfully.' ); done(); } ); } ); }( mediaWiki ) );
/*! * dc 2.0.0-beta.18 * http://dc-js.github.io/dc.js/ * Copyright 2012-2015 Nick Zhu & the dc.js Developers * https://github.com/dc-js/dc.js/blob/master/AUTHORS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function() { function _dc(d3, crossfilter) { 'use strict'; /** * The entire dc.js library is scoped under the **dc** name space. It does not introduce * anything else into the global name space. * * Most `dc` functions are designed to allow function chaining, meaning they return the current chart * instance whenever it is appropriate. The getter forms of functions do not participate in function * chaining because they necessarily return values that are not the chart. Although some, * such as `.svg` and `.xAxis`, return values that are chainable d3 objects. * @namespace dc * @version 2.0.0-beta.18 * @example * // Example chaining * chart.width(300) * .height(300) * .filter('sunday'); */ /*jshint -W062*/ /*jshint -W079*/ var dc = { version: '2.0.0-beta.18', constants: { CHART_CLASS: 'dc-chart', DEBUG_GROUP_CLASS: 'debug', STACK_CLASS: 'stack', DESELECTED_CLASS: 'deselected', SELECTED_CLASS: 'selected', NODE_INDEX_NAME: '__index__', GROUP_INDEX_NAME: '__group_index__', DEFAULT_CHART_GROUP: '__default_chart_group__', EVENT_DELAY: 40, NEGLIGIBLE_NUMBER: 1e-10 }, _renderlet: null }; dc.chartRegistry = function () { // chartGroup:string => charts:array var _chartMap = {}; function initializeChartGroup (group) { if (!group) { group = dc.constants.DEFAULT_CHART_GROUP; } if (!_chartMap[group]) { _chartMap[group] = []; } return group; } return { has: function (chart) { for (var e in _chartMap) { if (_chartMap[e].indexOf(chart) >= 0) { return true; } } return false; }, register: function (chart, group) { group = initializeChartGroup(group); _chartMap[group].push(chart); }, deregister: function (chart, group) { group = initializeChartGroup(group); for (var i = 0; i < _chartMap[group].length; i++) { if (_chartMap[group][i].anchorName() === chart.anchorName()) { _chartMap[group].splice(i, 1); break; } } }, clear: function (group) { if (group) { delete _chartMap[group]; } else { _chartMap = {}; } }, list: function (group) { group = initializeChartGroup(group); return _chartMap[group]; } }; }(); /*jshint +W062 */ /*jshint +W079*/ dc.registerChart = function (chart, group) { dc.chartRegistry.register(chart, group); }; dc.deregisterChart = function (chart, group) { dc.chartRegistry.deregister(chart, group); }; dc.hasChart = function (chart) { return dc.chartRegistry.has(chart); }; dc.deregisterAllCharts = function (group) { dc.chartRegistry.clear(group); }; /** * Clear all filters on all charts within the given chart group. If the chart group is not given then * only charts that belong to the default chart group will be reset. * @memberof dc * @name filterAll * @param {String} [group] */ dc.filterAll = function (group) { var charts = dc.chartRegistry.list(group); for (var i = 0; i < charts.length; ++i) { charts[i].filterAll(); } }; /** * Reset zoom level / focus on all charts that belong to the given chart group. If the chart group is * not given then only charts that belong to the default chart group will be reset. * @memberof dc * @name refocusAll * @param {String} [group] */ dc.refocusAll = function (group) { var charts = dc.chartRegistry.list(group); for (var i = 0; i < charts.length; ++i) { if (charts[i].focus) { charts[i].focus(); } } }; /** * Re-render all charts belong to the given chart group. If the chart group is not given then only * charts that belong to the default chart group will be re-rendered. * @memberof dc * @name renderAll * @param {String} [group] */ dc.renderAll = function (group) { var charts = dc.chartRegistry.list(group); for (var i = 0; i < charts.length; ++i) { charts[i].render(); } if (dc._renderlet !== null) { dc._renderlet(group); } }; /** * Redraw all charts belong to the given chart group. If the chart group is not given then only charts * that belong to the default chart group will be re-drawn. Redraw is different from re-render since * when redrawing dc tries to update the graphic incrementally, using transitions, instead of starting * from scratch. * @memberof dc * @name redrawAll * @param {String} [group] */ dc.redrawAll = function (group) { var charts = dc.chartRegistry.list(group); for (var i = 0; i < charts.length; ++i) { charts[i].redraw(); } if (dc._renderlet !== null) { dc._renderlet(group); } }; /** * If this boolean is set truthy, all transitions will be disabled, and changes to the charts will happen * immediately * @memberof dc * @name disableTransitions * @type {Boolean} * @default false */ dc.disableTransitions = false; dc.transition = function (selections, duration, callback, name) { if (duration <= 0 || duration === undefined || dc.disableTransitions) { return selections; } var s = selections .transition(name) .duration(duration); if (typeof(callback) === 'function') { callback(s); } return s; }; /* somewhat silly, but to avoid duplicating logic */ dc.optionalTransition = function (enable, duration, callback, name) { if (enable) { return function (selection) { return dc.transition(selection, duration, callback, name); }; } else { return function (selection) { return selection; }; } }; /** * @name units * @memberof dc * @type {{}} */ dc.units = {}; /** * The default value for `xUnits` for the [Coordinate Grid Chart](#coordinate-grid-chart) and should * be used when the x values are a sequence of integers. * It is a function that counts the number of integers in the range supplied in its start and end parameters. * @name integers * @memberof dc.units * @example * chart.xUnits(dc.units.integers) // already the default * @param {Number} start * @param {Number} end * @returns {Number} */ dc.units.integers = function (start, end) { return Math.abs(end - start); }; /** * This argument can be passed to the `xUnits` function of the to specify ordinal units for the x * axis. Usually this parameter is used in combination with passing `d3.scale.ordinal()` to `.x`. * It just returns the domain passed to it, which for ordinal charts is an array of all values. * @name ordinal * @memberof dc.units * @example * chart.xUnits(dc.units.ordinal) * .x(d3.scale.ordinal()) * @param {*} start * @param {*} end * @param {Array<String>} domain * @returns {Array<String>} */ dc.units.ordinal = function (start, end, domain) { return domain; }; /** * @name fp * @memberof dc.units * @type {{}} */ dc.units.fp = {}; /** * This function generates an argument for the [Coordinate Grid Chart's](#coordinate-grid-chart) * `xUnits` function specifying that the x values are floating-point numbers with the given * precision. * The returned function determines how many values at the given precision will fit into the range * supplied in its start and end parameters. * @name precision * @memberof dc.units.fp * @example * // specify values (and ticks) every 0.1 units * chart.xUnits(dc.units.fp.precision(0.1) * // there are 500 units between 0.5 and 1 if the precision is 0.001 * var thousandths = dc.units.fp.precision(0.001); * thousandths(0.5, 1.0) // returns 500 * @param {Number} precision * @returns {Function} start-end unit function */ dc.units.fp.precision = function (precision) { var _f = function (s, e) { var d = Math.abs((e - s) / _f.resolution); if (dc.utils.isNegligible(d - Math.floor(d))) { return Math.floor(d); } else { return Math.ceil(d); } }; _f.resolution = precision; return _f; }; dc.round = {}; dc.round.floor = function (n) { return Math.floor(n); }; dc.round.ceil = function (n) { return Math.ceil(n); }; dc.round.round = function (n) { return Math.round(n); }; dc.override = function (obj, functionName, newFunction) { var existingFunction = obj[functionName]; obj['_' + functionName] = existingFunction; obj[functionName] = newFunction; }; dc.renderlet = function (_) { if (!arguments.length) { return dc._renderlet; } dc._renderlet = _; return dc; }; dc.instanceOfChart = function (o) { return o instanceof Object && o.__dcFlag__ && true; }; dc.errors = {}; dc.errors.Exception = function (msg) { var _msg = msg || 'Unexpected internal error'; this.message = _msg; this.toString = function () { return _msg; }; }; dc.errors.InvalidStateException = function () { dc.errors.Exception.apply(this, arguments); }; dc.dateFormat = d3.time.format('%m/%d/%Y'); dc.printers = {}; dc.printers.filters = function (filters) { var s = ''; for (var i = 0; i < filters.length; ++i) { if (i > 0) { s += ', '; } s += dc.printers.filter(filters[i]); } return s; }; dc.printers.filter = function (filter) { var s = ''; if (typeof filter !== 'undefined' && filter !== null) { if (filter instanceof Array) { if (filter.length >= 2) { s = '[' + dc.utils.printSingleValue(filter[0]) + ' -> ' + dc.utils.printSingleValue(filter[1]) + ']'; } else if (filter.length >= 1) { s = dc.utils.printSingleValue(filter[0]); } } else { s = dc.utils.printSingleValue(filter); } } return s; }; dc.pluck = function (n, f) { if (!f) { return function (d) { return d[n]; }; } return function (d, i) { return f.call(d, d[n], i); }; }; dc.utils = {}; dc.utils.printSingleValue = function (filter) { var s = '' + filter; if (filter instanceof Date) { s = dc.dateFormat(filter); } else if (typeof(filter) === 'string') { s = filter; } else if (dc.utils.isFloat(filter)) { s = dc.utils.printSingleValue.fformat(filter); } else if (dc.utils.isInteger(filter)) { s = Math.round(filter); } return s; }; dc.utils.printSingleValue.fformat = d3.format('.2f'); // FIXME: these assume than any string r is a percentage (whether or not it // includes %). They also generate strange results if l is a string. dc.utils.add = function (l, r) { if (typeof r === 'string') { r = r.replace('%', ''); } if (l instanceof Date) { if (typeof r === 'string') { r = +r; } var d = new Date(); d.setTime(l.getTime()); d.setDate(l.getDate() + r); return d; } else if (typeof r === 'string') { var percentage = (+r / 100); return l > 0 ? l * (1 + percentage) : l * (1 - percentage); } else { return l + r; } }; dc.utils.subtract = function (l, r) { if (typeof r === 'string') { r = r.replace('%', ''); } if (l instanceof Date) { if (typeof r === 'string') { r = +r; } var d = new Date(); d.setTime(l.getTime()); d.setDate(l.getDate() - r); return d; } else if (typeof r === 'string') { var percentage = (+r / 100); return l < 0 ? l * (1 + percentage) : l * (1 - percentage); } else { return l - r; } }; dc.utils.isNumber = function (n) { return n === +n; }; dc.utils.isFloat = function (n) { return n === +n && n !== (n | 0); }; dc.utils.isInteger = function (n) { return n === +n && n === (n | 0); }; dc.utils.isNegligible = function (n) { return !dc.utils.isNumber(n) || (n < dc.constants.NEGLIGIBLE_NUMBER && n > -dc.constants.NEGLIGIBLE_NUMBER); }; dc.utils.clamp = function (val, min, max) { return val < min ? min : (val > max ? max : val); }; var _idCounter = 0; dc.utils.uniqueId = function () { return ++_idCounter; }; dc.utils.nameToId = function (name) { return name.toLowerCase().replace(/[\s]/g, '_').replace(/[\.']/g, ''); }; dc.utils.appendOrSelect = function (parent, selector, tag) { tag = tag || selector; var element = parent.select(selector); if (element.empty()) { element = parent.append(tag); } return element; }; dc.utils.safeNumber = function (n) { return dc.utils.isNumber(+n) ? +n : 0;}; dc.logger = {}; dc.logger.enableDebugLog = false; dc.logger.warn = function (msg) { if (console) { if (console.warn) { console.warn(msg); } else if (console.log) { console.log(msg); } } return dc.logger; }; dc.logger.debug = function (msg) { if (dc.logger.enableDebugLog && console) { if (console.debug) { console.debug(msg); } else if (console.log) { console.log(msg); } } return dc.logger; }; dc.logger.deprecate = function (fn, msg) { // Allow logging of deprecation var warned = false; function deprecated () { if (!warned) { dc.logger.warn(msg); warned = true; } return fn.apply(this, arguments); } return deprecated; }; dc.events = { current: null }; /** * This function triggers a throttled event function with a specified delay (in milli-seconds). Events * that are triggered repetitively due to user interaction such brush dragging might flood the library * and invoke more renders than can be executed in time. Using this function to wrap your event * function allows the library to smooth out the rendering by throttling events and only responding to * the most recent event. * @name events.trigger * @memberof dc * @example * chart.on('renderlet', function(chart) { * // smooth the rendering through event throttling * dc.events.trigger(function(){ * // focus some other chart to the range selected by user on this chart * someOtherChart.focus(chart.filter()); * }); * }) * @param {Function} closure * @param {Number} [delay] */ dc.events.trigger = function (closure, delay) { if (!delay) { closure(); return; } dc.events.current = closure; setTimeout(function () { if (closure === dc.events.current) { closure(); } }, delay); }; /** * The dc.js filters are functions which are passed into crossfilter to chose which records will be * accumulated to produce values for the charts. In the crossfilter model, any filters applied on one * dimension will affect all the other dimensions but not that one. dc always applies a filter * function to the dimension; the function combines multiple filters and if any of them accept a * record, it is filtered in. * * These filter constructors are used as appropriate by the various charts to implement brushing. We * mention below which chart uses which filter. In some cases, many instances of a filter will be added. * @name filters * @memberof dc * @type {{}} */ dc.filters = {}; /** * RangedFilter is a filter which accepts keys between `low` and `high`. It is used to implement X * axis brushing for the [coordinate grid charts](#coordinate-grid-mixin). * @name RangedFilter * @memberof dc.filters * @param {Number} low * @param {Number} high * @returns {Array<Number>} * @constructor */ dc.filters.RangedFilter = function (low, high) { var range = new Array(low, high); range.isFiltered = function (value) { return value >= this[0] && value < this[1]; }; return range; }; /** * TwoDimensionalFilter is a filter which accepts a single two-dimensional value. It is used by the * [heat map chart](#heat-map) to include particular cells as they are clicked. (Rows and columns are * filtered by filtering all the cells in the row or column.) * @name TwoDimensionalFilter * @memberof dc.filters * @param {Array<Number>} filter * @returns {Array<Number>} * @constructor */ dc.filters.TwoDimensionalFilter = function (filter) { if (filter === null) { return null; } var f = filter; f.isFiltered = function (value) { return value.length && value.length === f.length && value[0] === f[0] && value[1] === f[1]; }; return f; }; /** * The RangedTwoDimensionalFilter allows filtering all values which fit within a rectangular * region. It is used by the [scatter plot](#scatter-plot) to implement rectangular brushing. * * It takes two two-dimensional points in the form `[[x1,y1],[x2,y2]]`, and normalizes them so that * `x1 <= x2` and `y1 <- y2`. It then returns a filter which accepts any points which are in the * rectangular range including the lower values but excluding the higher values. * * If an array of two values are given to the RangedTwoDimensionalFilter, it interprets the values as * two x coordinates `x1` and `x2` and returns a filter which accepts any points for which `x1 <= x < * x2`. * @name RangedTwoDimensionalFilter * @memberof dc.filters * @param {Array<Array<Number>>} filter * @returns {Array<Array<Number>>} * @constructor */ dc.filters.RangedTwoDimensionalFilter = function (filter) { if (filter === null) { return null; } var f = filter; var fromBottomLeft; if (f[0] instanceof Array) { fromBottomLeft = [ [Math.min(filter[0][0], filter[1][0]), Math.min(filter[0][1], filter[1][1])], [Math.max(filter[0][0], filter[1][0]), Math.max(filter[0][1], filter[1][1])] ]; } else { fromBottomLeft = [[filter[0], -Infinity], [filter[1], Infinity]]; } f.isFiltered = function (value) { var x, y; if (value instanceof Array) { if (value.length !== 2) { return false; } x = value[0]; y = value[1]; } else { x = value; y = fromBottomLeft[0][1]; } return x >= fromBottomLeft[0][0] && x < fromBottomLeft[1][0] && y >= fromBottomLeft[0][1] && y < fromBottomLeft[1][1]; }; return f; }; /** * Base Mixin is an abstract functional object representing a basic dc chart object * for all chart and widget implementations. Methods from the Base Mixin are inherited * and available on all chart implementations in the DC library. * @name baseMixin * @memberof dc * @mixin * @param {Chart} _chart * @returns {Chart} */ dc.baseMixin = function (_chart) { _chart.__dcFlag__ = dc.utils.uniqueId(); var _dimension; var _group; var _anchor; var _root; var _svg; var _isChild; var _minWidth = 200; var _defaultWidth = function (element) { var width = element && element.getBoundingClientRect && element.getBoundingClientRect().width; return (width && width > _minWidth) ? width : _minWidth; }; var _width = _defaultWidth; var _minHeight = 200; var _defaultHeight = function (element) { var height = element && element.getBoundingClientRect && element.getBoundingClientRect().height; return (height && height > _minHeight) ? height : _minHeight; }; var _height = _defaultHeight; var _keyAccessor = dc.pluck('key'); var _valueAccessor = dc.pluck('value'); var _label = dc.pluck('key'); var _ordering = dc.pluck('key'); var _orderSort; var _renderLabel = false; var _title = function (d) { return _chart.keyAccessor()(d) + ': ' + _chart.valueAccessor()(d); }; var _renderTitle = true; var _transitionDuration = 750; var _filterPrinter = dc.printers.filters; var _mandatoryAttributes = ['dimension', 'group']; var _chartGroup = dc.constants.DEFAULT_CHART_GROUP; var _listeners = d3.dispatch( 'preRender', 'postRender', 'preRedraw', 'postRedraw', 'filtered', 'zoomed', 'renderlet', 'pretransition'); var _legend; var _filters = []; var _filterHandler = function (dimension, filters) { dimension.filter(null); if (filters.length === 0) { dimension.filter(null); } else { dimension.filterFunction(function (d) { for (var i = 0; i < filters.length; i++) { var filter = filters[i]; if (filter.isFiltered && filter.isFiltered(d)) { return true; } else if (filter <= d && filter >= d) { return true; } } return false; }); } return filters; }; var _data = function (group) { return group.all(); }; /** * Set or get the width attribute of a chart. See `.height` below for further description of the * behavior. * @name width * @memberof dc.baseMixin * @instance * @param {Number|Function} w * @returns {Number} */ _chart.width = function (w) { if (!arguments.length) { return _width(_root.node()); } _width = d3.functor(w || _defaultWidth); return _chart; }; /** * Set or get the height attribute of a chart. The height is applied to the SVG element generated by * the chart when rendered (or rerendered). If a value is given, then it will be used to calculate * the new height and the chart returned for method chaining. The value can either be a numeric, a * function, or falsy. If no value is specified then the value of the current height attribute will * be returned. * * By default, without an explicit height being given, the chart will select the width of its * anchor element. If that isn't possible it defaults to 200. Setting the value falsy will return * the chart to the default behavior * @name height * @memberof dc.baseMixin * @instance * @example * chart.height(250); // Set the chart's height to 250px; * chart.height(function(anchor) { return doSomethingWith(anchor); }); // set the chart's height with a function * chart.height(null); // reset the height to the default auto calculation * @param {Number|Function} h * @returns {Number} */ _chart.height = function (h) { if (!arguments.length) { return _height(_root.node()); } _height = d3.functor(h || _defaultHeight); return _chart; }; /** * Set or get the minimum width attribute of a chart. This only applicable if the width is * calculated by dc. * @name minWidth * @memberof dc.baseMixin * @instance * @param {Number} w * @returns {Number} */ _chart.minWidth = function (w) { if (!arguments.length) { return _minWidth; } _minWidth = w; return _chart; }; /** * Set or get the minimum height attribute of a chart. This only applicable if the height is * calculated by dc. * @name minHeight * @memberof dc.baseMixin * @instance * @param {Number} h * @returns {Number} */ _chart.minHeight = function (h) { if (!arguments.length) { return _minHeight; } _minHeight = h; return _chart; }; /** * **mandatory** * * Set or get the dimension attribute of a chart. In dc a dimension can be any valid [crossfilter * dimension](https://github.com/square/crossfilter/wiki/API-Reference#wiki-dimension). * * If a value is given, then it will be used as the new dimension. If no value is specified then * the current dimension will be returned. * @name dimension * @memberof dc.baseMixin * @instance * @param {Dimension} d * @returns {Dimension} */ _chart.dimension = function (d) { if (!arguments.length) { return _dimension; } _dimension = d; _chart.expireCache(); return _chart; }; /** * Set the data callback or retrieve the chart's data set. The data callback is passed the chart's * group and by default will return `group.all()`. This behavior may be modified to, for instance, * return only the top 5 groups. * @name data * @memberof dc.baseMixin * @instance * @example * chart.data(function(group) { * return group.top(5); * }); * @param {Function} [callback] * @returns {*} */ _chart.data = function (callback) { if (!arguments.length) { return _data.call(_chart, _group); } _data = d3.functor(callback); _chart.expireCache(); return _chart; }; /** * **mandatory** * * Set or get the group attribute of a chart. In dc a group is a [crossfilter * group](https://github.com/square/crossfilter/wiki/API-Reference#wiki-group). Usually the group * should be created from the particular dimension associated with the same chart. If a value is * given, then it will be used as the new group. * * If no value specified then the current group will be returned. * If `name` is specified then it will be used to generate legend label. * @name group * @memberof dc.baseMixin * @instance * @param {Group} [group] * @param {String} [name] * @returns {Group} */ _chart.group = function (group, name) { if (!arguments.length) { return _group; } _group = group; _chart._groupName = name; _chart.expireCache(); return _chart; }; /** * Get or set an accessor to order ordinal charts * @name ordering * @memberof dc.baseMixin * @instance * @param {Function} [orderFunction] * @returns {Function} */ _chart.ordering = function (orderFunction) { if (!arguments.length) { return _ordering; } _ordering = orderFunction; _orderSort = crossfilter.quicksort.by(_ordering); _chart.expireCache(); return _chart; }; _chart._computeOrderedGroups = function (data) { var dataCopy = data.slice(0); if (dataCopy.length <= 1) { return dataCopy; } if (!_orderSort) { _orderSort = crossfilter.quicksort.by(_ordering); } return _orderSort(dataCopy, 0, dataCopy.length); }; /** * Clear all filters associated with this chart. * @name filterAll * @memberof dc.baseMixin * @instance * @returns {Chart} */ _chart.filterAll = function () { return _chart.filter(null); }; /** * Execute d3 single selection in the chart's scope using the given selector and return the d3 * selection. * * This function is **not chainable** since it does not return a chart instance; however the d3 * selection result can be chained to d3 function calls. * @name select * @memberof dc.baseMixin * @instance * @example * // Similar to: * d3.select('#chart-id').select(selector); * @returns {Selection} */ _chart.select = function (s) { return _root.select(s); }; /** * Execute in scope d3 selectAll using the given selector and return d3 selection result. * * This function is **not chainable** since it does not return a chart instance; however the d3 * selection result can be chained to d3 function calls. * @name selectAll * @memberof dc.baseMixin * @instance * @example * // Similar to: * d3.select('#chart-id').selectAll(selector); * @returns {Selection} */ _chart.selectAll = function (s) { return _root ? _root.selectAll(s) : null; }; /** * Set the svg root to either be an existing chart's root; or any valid [d3 single * selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying a dom * block element such as a div; or a dom element or d3 selection. Optionally registers the chart * within the chartGroup. This class is called internally on chart initialization, but be called * again to relocate the chart. However, it will orphan any previously created SVG elements. * @name anchor * @memberof dc.baseMixin * @instance * @param {anchorChart|anchorSelector|anchorNode} [a] * @param {chartGroup} [chartGroup] * @returns {Chart} */ _chart.anchor = function (a, chartGroup) { if (!arguments.length) { return _anchor; } if (dc.instanceOfChart(a)) { _anchor = a.anchor(); _root = a.root(); _isChild = true; } else { _anchor = a; _root = d3.select(_anchor); _root.classed(dc.constants.CHART_CLASS, true); dc.registerChart(_chart, chartGroup); _isChild = false; } _chartGroup = chartGroup; return _chart; }; /** * Returns the dom id for the chart's anchored location. * @name anchorName * @memberof dc.baseMixin * @instance * @return {String} */ _chart.anchorName = function () { var a = _chart.anchor(); if (a && a.id) { return a.id; } if (a && a.replace) { return a.replace('#', ''); } return 'dc-chart' + _chart.chartID(); }; /** * Returns the root element where a chart resides. Usually it will be the parent div element where * the svg was created. You can also pass in a new root element however this is usually handled by * dc internally. Resetting the root element on a chart outside of dc internals may have * unexpected consequences. * @name root * @memberof dc.baseMixin * @instance * @param {Element} [rootElement] * @return {Element} */ _chart.root = function (rootElement) { if (!arguments.length) { return _root; } _root = rootElement; return _chart; }; /** * Returns the top svg element for this specific chart. You can also pass in a new svg element, * however this is usually handled by dc internally. Resetting the svg element on a chart outside * of dc internals may have unexpected consequences. * @name svg * @memberof dc.baseMixin * @instance * @param {SVGElement} [svgElement] * @return {SVGElement} */ _chart.svg = function (svgElement) { if (!arguments.length) { return _svg; } _svg = svgElement; return _chart; }; /** * Remove the chart's SVG elements from the dom and recreate the container SVG element. * @name resetSvg * @memberof dc.baseMixin * @instance * @return {SVGElement} */ _chart.resetSvg = function () { _chart.select('svg').remove(); return generateSvg(); }; function sizeSvg () { if (_svg) { _svg .attr('width', _chart.width()) .attr('height', _chart.height()); } } function generateSvg () { _svg = _chart.root().append('svg'); sizeSvg(); return _svg; } /** * Set or get the filter printer function. The filter printer function is used to generate human * friendly text for filter value(s) associated with the chart instance. By default dc charts use a * default filter printer `dc.printers.filter` that provides simple printing support for both * single value and ranged filters. * @name filterPrinter * @memberof dc.baseMixin * @instance * @param {Function} [filterPrinterFunction] * @return {Function} */ _chart.filterPrinter = function (filterPrinterFunction) { if (!arguments.length) { return _filterPrinter; } _filterPrinter = filterPrinterFunction; return _chart; }; /** #### .turnOnControls() & .turnOffControls() Turn on/off optional control elements within the root element. dc currently supports the following html control elements. * root.selectAll('.reset') - elements are turned on if the chart has an active filter. This type of control element is usually used to store a reset link to allow user to reset filter on a certain chart. This element will be turned off automatically if the filter is cleared. * root.selectAll('.filter') elements are turned on if the chart has an active filter. The text content of this element is then replaced with the current filter value using the filter printer function. This type of element will be turned off automatically if the filter is cleared. **/ /** * Turn on optional control elements within the root element. dc currently supports the * following html control elements. * * root.selectAll('.reset') - elements are turned on if the chart has an active filter. This type * of control element is usually used to store a reset link to allow user to reset filter on a * certain chart. This element will be turned off automatically if the filter is cleared. * * root.selectAll('.filter') elements are turned on if the chart has an active filter. The text * content of this element is then replaced with the current filter value using the filter printer * function. This type of element will be turned off automatically if the filter is cleared. * @name turnOnControls * @memberof dc.baseMixin * @instance * @return {Chart} */ _chart.turnOnControls = function () { if (_root) { _chart.selectAll('.reset').style('display', null); _chart.selectAll('.filter').text(_filterPrinter(_chart.filters())).style('display', null); } return _chart; }; /** * Turn off optional control elements within the root element. * @name turnOffControls * @memberof dc.baseMixin * @instance * @return {Chart} */ _chart.turnOffControls = function () { if (_root) { _chart.selectAll('.reset').style('display', 'none'); _chart.selectAll('.filter').style('display', 'none').text(_chart.filter()); } return _chart; }; /** * Set or get the animation transition duration (in milliseconds) for this chart instance. * @name transitionDuration * @memberof dc.baseMixin * @instance * @param {Number} [duration] * @return {Number} */ _chart.transitionDuration = function (duration) { if (!arguments.length) { return _transitionDuration; } _transitionDuration = duration; return _chart; }; _chart._mandatoryAttributes = function (_) { if (!arguments.length) { return _mandatoryAttributes; } _mandatoryAttributes = _; return _chart; }; function checkForMandatoryAttributes (a) { if (!_chart[a] || !_chart[a]()) { throw new dc.errors.InvalidStateException('Mandatory attribute chart.' + a + ' is missing on chart[#' + _chart.anchorName() + ']'); } } /** * Invoking this method will force the chart to re-render everything from scratch. Generally it * should only be used to render the chart for the first time on the page or if you want to make * sure everything is redrawn from scratch instead of relying on the default incremental redrawing * behaviour. * @name render * @memberof dc.baseMixin * @instance * @return {Chart} */ _chart.render = function () { _listeners.preRender(_chart); if (_mandatoryAttributes) { _mandatoryAttributes.forEach(checkForMandatoryAttributes); } var result = _chart._doRender(); if (_legend) { _legend.render(); } _chart._activateRenderlets('postRender'); return result; }; _chart._activateRenderlets = function (event) { _listeners.pretransition(_chart); if (_chart.transitionDuration() > 0 && _svg) { _svg.transition().duration(_chart.transitionDuration()) .each('end', function () { _listeners.renderlet(_chart); if (event) { _listeners[event](_chart); } }); } else { _listeners.renderlet(_chart); if (event) { _listeners[event](_chart); } } }; /** * Calling redraw will cause the chart to re-render data changes incrementally. If there is no * change in the underlying data dimension then calling this method will have no effect on the * chart. Most chart interaction in dc will automatically trigger this method through internal * events (in particular [dc.redrawAll](#dcredrawallchartgroup)); therefore, you only need to * manually invoke this function if data is manipulated outside of dc's control (for example if * data is loaded in the background using `crossfilter.add()`). * @name redraw * @memberof dc.baseMixin * @instance * @return {Chart} */ _chart.redraw = function () { sizeSvg(); _listeners.preRedraw(_chart); var result = _chart._doRedraw(); if (_legend) { _legend.render(); } _chart._activateRenderlets('postRedraw'); return result; }; _chart.redrawGroup = function () { dc.redrawAll(_chart.chartGroup()); }; _chart.renderGroup = function () { dc.renderAll(_chart.chartGroup()); }; _chart._invokeFilteredListener = function (f) { if (f !== undefined) { _listeners.filtered(_chart, f); } }; _chart._invokeZoomedListener = function () { _listeners.zoomed(_chart); }; var _hasFilterHandler = function (filters, filter) { if (filter === null || typeof(filter) === 'undefined') { return filters.length > 0; } return filters.some(function (f) { return filter <= f && filter >= f; }); }; /** * Set or get the has filter handler. The has filter handler is a function that checks to see if * the chart's current filters include a specific filter. Using a custom has filter handler allows * you to change the way filters are checked for and replaced. * @name hasFilterHandler * @memberof dc.baseMixin * @instance * @example * // default has filter handler * function (filters, filter) { * if (filter === null || typeof(filter) === 'undefined') { * return filters.length > 0; * } * return filters.some(function (f) { * return filter <= f && filter >= f; * }); * } * * // custom filter handler (no-op) * chart.hasFilterHandler(function(filters, filter) { * return false; * }); * @param {Function} [hasFilterHandler] * @return {Chart} */ _chart.hasFilterHandler = function (hasFilterHandler) { if (!arguments.length) { return _hasFilterHandler; } _hasFilterHandler = hasFilterHandler; return _chart; }; /** * Check whether any active filter or a specific filter is associated with particular chart instance. * This function is **not chainable**. * @name hasFilter * @memberof dc.baseMixin * @instance * @param {*} [filter] * @return {Boolean} */ _chart.hasFilter = function (filter) { return _hasFilterHandler(_filters, filter); }; var _removeFilterHandler = function (filters, filter) { for (var i = 0; i < filters.length; i++) { if (filters[i] <= filter && filters[i] >= filter) { filters.splice(i, 1); break; } } return filters; }; /** * Set or get the remove filter handler. The remove filter handler is a function that removes a * filter from the chart's current filters. Using a custom remove filter handler allows you to * change how filters are removed or perform additional work when removing a filter, e.g. when * using a filter server other than crossfilter. * * Any changes should modify the `filters` array argument and return that array. * @name removeFilterHandler * @memberof dc.baseMixin * @instance * @example * // default remove filter handler * function (filters, filter) { * for (var i = 0; i < filters.length; i++) { * if (filters[i] <= filter && filters[i] >= filter) { * filters.splice(i, 1); * break; * } * } * return filters; * } * * // custom filter handler (no-op) * chart.removeFilterHandler(function(filters, filter) { * return filters; * }); * @param {Function} [removeFilterHandler] * @return {Chart} */ _chart.removeFilterHandler = function (removeFilterHandler) { if (!arguments.length) { return _removeFilterHandler; } _removeFilterHandler = removeFilterHandler; return _chart; }; var _addFilterHandler = function (filters, filter) { filters.push(filter); return filters; }; /** * Set or get the add filter handler. The add filter handler is a function that adds a filter to * the chart's filter list. Using a custom add filter handler allows you to change the way filters * are added or perform additional work when adding a filter, e.g. when using a filter server other * than crossfilter. * * Any changes should modify the `filters` array argument and return that array. * @name addFilterHandler * @memberof dc.baseMixin * @instance * @example * // default add filter handler * function (filters, filter) { * filters.push(filter); * return filters; * } * * // custom filter handler (no-op) * chart.addFilterHandler(function(filters, filter) { * return filters; * }); * @param {Function} [addFilterHandler] * @return {Chart} */ _chart.addFilterHandler = function (addFilterHandler) { if (!arguments.length) { return _addFilterHandler; } _addFilterHandler = addFilterHandler; return _chart; }; var _resetFilterHandler = function (filters) { return []; }; /** * Set or get the reset filter handler. The reset filter handler is a function that resets the * chart's filter list by returning a new list. Using a custom reset filter handler allows you to * change the way filters are reset, or perform additional work when resetting the filters, * e.g. when using a filter server other than crossfilter. * * This function should return an array. * @name resetFilterHandler * @memberof dc.baseMixin * @instance * @example * // default remove filter handler * function (filters) { * return []; * } * * // custom filter handler (no-op) * chart.resetFilterHandler(function(filters) { * return filters; * }); * @param {Function} [resetFilterHandler] * @return {Chart} */ _chart.resetFilterHandler = function (resetFilterHandler) { if (!arguments.length) { return _resetFilterHandler; } _resetFilterHandler = resetFilterHandler; return _chart; }; function applyFilters () { if (_chart.dimension() && _chart.dimension().filter) { var fs = _filterHandler(_chart.dimension(), _filters); _filters = fs ? fs : _filters; } } _chart.replaceFilter = function (_) { _filters = []; _chart.filter(_); }; /** * Filter the chart by the given value or return the current filter if the input parameter is missing. * @name filter * @memberof dc.baseMixin * @instance * @example * // filter by a single string * chart.filter('Sunday'); * // filter by a single age * chart.filter(18); * @param {*} [filter] * @return {Chart} */ _chart.filter = function (filter) { if (!arguments.length) { return _filters.length > 0 ? _filters[0] : null; } if (filter instanceof Array && filter[0] instanceof Array && !filter.isFiltered) { filter[0].forEach(function (d) { if (_chart.hasFilter(d)) { _removeFilterHandler(_filters, d); } else { _addFilterHandler(_filters, d); } }); } else if (filter === null) { _filters = _resetFilterHandler(_filters); } else { if (_chart.hasFilter(filter)) { _removeFilterHandler(_filters, filter); } else { _addFilterHandler(_filters, filter); } } applyFilters(); _chart._invokeFilteredListener(filter); if (_root !== null && _chart.hasFilter()) { _chart.turnOnControls(); } else { _chart.turnOffControls(); } return _chart; }; /** * Returns all current filters. This method does not perform defensive cloning of the internal * filter array before returning, therefore any modification of the returned array will effect the * chart's internal filter storage. * @name filters * @memberof dc.baseMixin * @instance * @return {Array<*>} */ _chart.filters = function () { return _filters; }; _chart.highlightSelected = function (e) { d3.select(e).classed(dc.constants.SELECTED_CLASS, true); d3.select(e).classed(dc.constants.DESELECTED_CLASS, false); }; _chart.fadeDeselected = function (e) { d3.select(e).classed(dc.constants.SELECTED_CLASS, false); d3.select(e).classed(dc.constants.DESELECTED_CLASS, true); }; _chart.resetHighlight = function (e) { d3.select(e).classed(dc.constants.SELECTED_CLASS, false); d3.select(e).classed(dc.constants.DESELECTED_CLASS, false); }; /** * This function is passed to d3 as the onClick handler for each chart. The default behavior is to * filter on the clicked datum (passed to the callback) and redraw the chart group. * @name onClick * @memberof dc.baseMixin * @instance * @param {*} datum */ _chart.onClick = function (datum) { var filter = _chart.keyAccessor()(datum); dc.events.trigger(function () { _chart.filter(filter); _chart.redrawGroup(); }); }; /** * Set or get the filter handler. The filter handler is a function that performs the filter action * on a specific dimension. Using a custom filter handler allows you to perform additional logic * before or after filtering. * @name filterHandler * @memberof dc.baseMixin * @instance * @example * // default filter handler * function(dimension, filter){ * dimension.filter(filter); // perform filtering * return filter; // return the actual filter value * } * * // custom filter handler * chart.filterHandler(function(dimension, filter){ * var newFilter = filter + 10; * dimension.filter(newFilter); * return newFilter; // set the actual filter value to the new value * }); * @param {Function} filterHandler * @return {Chart} */ _chart.filterHandler = function (filterHandler) { if (!arguments.length) { return _filterHandler; } _filterHandler = filterHandler; return _chart; }; // abstract function stub _chart._doRender = function () { // do nothing in base, should be overridden by sub-function return _chart; }; _chart._doRedraw = function () { // do nothing in base, should be overridden by sub-function return _chart; }; _chart.legendables = function () { // do nothing in base, should be overridden by sub-function return []; }; _chart.legendHighlight = function () { // do nothing in base, should be overridden by sub-function }; _chart.legendReset = function () { // do nothing in base, should be overridden by sub-function }; _chart.legendToggle = function () { // do nothing in base, should be overriden by sub-function }; _chart.isLegendableHidden = function () { // do nothing in base, should be overridden by sub-function return false; }; /** * Set or get the key accessor function. The key accessor function is used to retrieve the key * value from the crossfilter group. Key values are used differently in different charts, for * example keys correspond to slices in a pie chart and x axis positions in a grid coordinate chart. * @name keyAccessor * @memberof dc.baseMixin * @instance * @example * // default key accessor * chart.keyAccessor(function(d) { return d.key; }); * // custom key accessor for a multi-value crossfilter reduction * chart.keyAccessor(function(p) { return p.value.absGain; }); * @param {Function} keyAccessor * @return {Chart} */ _chart.keyAccessor = function (keyAccessor) { if (!arguments.length) { return _keyAccessor; } _keyAccessor = keyAccessor; return _chart; }; /** * Set or get the value accessor function. The value accessor function is used to retrieve the * value from the crossfilter group. Group values are used differently in different charts, for * example values correspond to slice sizes in a pie chart and y axis positions in a grid * coordinate chart. * @name valueAccessor * @memberof dc.baseMixin * @instance * @example * // default value accessor * chart.valueAccessor(function(d) { return d.value; }); * // custom value accessor for a multi-value crossfilter reduction * chart.valueAccessor(function(p) { return p.value.percentageGain; }); * @param {Function} valueAccessor * @return {Chart} */ _chart.valueAccessor = function (valueAccessor) { if (!arguments.length) { return _valueAccessor; } _valueAccessor = valueAccessor; return _chart; }; /** * Set or get the label function. The chart class will use this function to render labels for each * child element in the chart, e.g. slices in a pie chart or bubbles in a bubble chart. Not every * chart supports the label function for example bar chart and line chart do not use this function * at all. * @name label * @memberof dc.baseMixin * @instance * @example * // default label function just return the key * chart.label(function(d) { return d.key; }); * // label function has access to the standard d3 data binding and can get quite complicated * chart.label(function(d) { return d.data.key + '(' + Math.floor(d.data.value / all.value() * 100) + '%)'; }); * @param {Function} labelFunction * @return {Chart} */ _chart.label = function (labelFunction) { if (!arguments.length) { return _label; } _label = labelFunction; _renderLabel = true; return _chart; }; /** * Turn on/off label rendering * @name renderLabel * @memberof dc.baseMixin * @instance * @param {Boolean} renderLabel * @return {Boolean} */ _chart.renderLabel = function (renderLabel) { if (!arguments.length) { return _renderLabel; } _renderLabel = renderLabel; return _chart; }; /** * Set or get the title function. The chart class will use this function to render the svg title * (usually interpreted by browser as tooltips) for each child element in the chart, e.g. a slice * in a pie chart or a bubble in a bubble chart. Almost every chart supports the title function; * however in grid coordinate charts you need to turn off the brush in order to see titles, because * otherwise the brush layer will block tooltip triggering. * @name title * @memberof dc.baseMixin * @instance * @example * // default title function just return the key * chart.title(function(d) { return d.key + ': ' + d.value; }); * // title function has access to the standard d3 data binding and can get quite complicated * chart.title(function(p) { * return p.key.getFullYear() * + '\n' * + 'Index Gain: ' + numberFormat(p.value.absGain) + '\n' * + 'Index Gain in Percentage: ' + numberFormat(p.value.percentageGain) + '%\n' * + 'Fluctuation / Index Ratio: ' + numberFormat(p.value.fluctuationPercentage) + '%'; * }); * @param {Function} titleFunction * @return {Function} */ _chart.title = function (titleFunction) { if (!arguments.length) { return _title; } _title = titleFunction; return _chart; }; /** * Turn on/off title rendering, or return the state of the render title flag if no arguments are * given. * @name renderTitle * @memberof dc.baseMixin * @instance * @param {Boolean} renderTitle * @return {Boolean} */ _chart.renderTitle = function (renderTitle) { if (!arguments.length) { return _renderTitle; } _renderTitle = renderTitle; return _chart; }; /** * A renderlet is similar to an event listener on rendering event. Multiple renderlets can be added * to an individual chart. Each time a chart is rerendered or redrawn the renderlets are invoked * right after the chart finishes its transitions, giving you a way to modify the svg * elements. Renderlet functions take the chart instance as the only input parameter and you can * use the dc API or use raw d3 to achieve pretty much any effect. * @name renderlet * @memberof dc.baseMixin * @instance * @deprecated Use [Listeners](#Listeners) with a 'renderlet' prefix. * Generates a random key for the renderlet, which makes it hard to remove. * @example * // do this instead of .renderlet(function(chart) { ... }) * chart.on("renderlet", function(chart){ * // mix of dc API and d3 manipulation * chart.select('g.y').style('display', 'none'); * // its a closure so you can also access other chart variable available in the closure scope * moveChart.filter(chart.filter()); * }); * @param {Function} renderletFunction * @return {Function} */ _chart.renderlet = dc.logger.deprecate(function (renderletFunction) { _chart.on('renderlet.' + dc.utils.uniqueId(), renderletFunction); return _chart; }, 'chart.renderlet has been deprecated. Please use chart.on("renderlet.<renderletKey>", renderletFunction)'); /** * Get or set the chart group to which this chart belongs. Chart groups are rendered or redrawn * together since it is expected they share the same underlying crossfilter data set. * @name chartGroup * @memberof dc.baseMixin * @instance * @param {String} chartGroup * @return {String} */ _chart.chartGroup = function (chartGroup) { if (!arguments.length) { return _chartGroup; } if (!_isChild) { dc.deregisterChart(_chart, _chartGroup); } _chartGroup = chartGroup; if (!_isChild) { dc.registerChart(_chart, _chartGroup); } return _chart; }; /** * Expire the internal chart cache. dc charts cache some data internally on a per chart basis to * speed up rendering and avoid unnecessary calculation; however it might be useful to clear the * cache if you have changed state which will affect rendering. For example if you invoke the * `crossfilter.add` function or reset group or dimension after rendering it is a good idea to * clear the cache to make sure charts are rendered properly. * @name expireCache * @memberof dc.baseMixin * @instance * @return {Chart} */ _chart.expireCache = function () { // do nothing in base, should be overridden by sub-function return _chart; }; /** * Attach a dc.legend widget to this chart. The legend widget will automatically draw legend labels * based on the color setting and names associated with each group. * @name legend * @memberof dc.baseMixin * @instance * @example * chart.legend(dc.legend().x(400).y(10).itemHeight(13).gap(5)) * @param {dc.legend} [legend] * @return {dc.legend} */ _chart.legend = function (legend) { if (!arguments.length) { return _legend; } _legend = legend; _legend.parent(_chart); return _chart; }; /** * Returns the internal numeric ID of the chart. * @name chartID * @memberof dc.baseMixin * @instance * @return {String} */ _chart.chartID = function () { return _chart.__dcFlag__; }; /** * Set chart options using a configuration object. Each key in the object will cause the method of * the same name to be called with the value to set that attribute for the chart. * @name options * @memberof dc.baseMixin * @instance * @example * chart.options({dimension: myDimension, group: myGroup}); * @param {{}} opts * @return {Chart} */ _chart.options = function (opts) { var applyOptions = [ 'anchor', 'group', 'xAxisLabel', 'yAxisLabel', 'stack', 'title', 'point', 'getColor', 'overlayGeoJson' ]; for (var o in opts) { if (typeof(_chart[o]) === 'function') { if (opts[o] instanceof Array && applyOptions.indexOf(o) !== -1) { _chart[o].apply(_chart, opts[o]); } else { _chart[o].call(_chart, opts[o]); } } else { dc.logger.debug('Not a valid option setter name: ' + o); } } return _chart; }; /** * All dc chart instance supports the following listeners. * Supports the following events: * * 'renderlet' - This listener function will be invoked after transitions after redraw and render. Replaces the * deprecated `.renderlet()` method. * * 'pretransition' - Like `.on('renderlet', ...)` but the event is fired before transitions start. * * 'preRender' - This listener function will be invoked before chart rendering. * * 'postRender' - This listener function will be invoked after chart finish rendering including * all renderlets' logic. * * 'preRedraw' - This listener function will be invoked before chart redrawing. * * 'postRedraw' - This listener function will be invoked after chart finish redrawing * including all renderlets' logic. * * 'filtered' - This listener function will be invoked after a filter is applied, added or removed. * * 'zoomed' - This listener function will be invoked after a zoom is triggered. * @name on * @memberof dc.baseMixin * @instance * @example * .on('renderlet', function(chart, filter){...}) * .on('pretransition', function(chart, filter){...}) * .on('preRender', function(chart){...}) * .on('postRender', function(chart){...}) * .on('preRedraw', function(chart){...}) * .on('postRedraw', function(chart){...}) * .on('filtered', function(chart, filter){...}) * .on('zoomed', function(chart, filter){...}) * @param {String} event * @param {Function} listener * @return {Chart} */ _chart.on = function (event, listener) { _listeners.on(event, listener); return _chart; }; return _chart; }; /** * Margin is a mixin that provides margin utility functions for both the Row Chart and Coordinate Grid * Charts. * @name marginMixin * @memberof dc * @mixin * @param {Chart} _chart * @returns {Chart} */ dc.marginMixin = function (_chart) { var _margin = {top: 10, right: 50, bottom: 30, left: 30}; /** * Get or set the margins for a particular coordinate grid chart instance. The margins is stored as * an associative Javascript array. * @name margins * @memberof dc.marginMixin * @instance * @example * var leftMargin = chart.margins().left; // 30 by default * chart.margins().left = 50; * leftMargin = chart.margins().left; // now 50 * @param {{top:Number, right: Number, left: Number, bottom: Number}} [margins={top: 10, right: 50, bottom: 30, left: 30}] * @returns {Chart} */ _chart.margins = function (margins) { if (!arguments.length) { return _margin; } _margin = margins; return _chart; }; _chart.effectiveWidth = function () { return _chart.width() - _chart.margins().left - _chart.margins().right; }; _chart.effectiveHeight = function () { return _chart.height() - _chart.margins().top - _chart.margins().bottom; }; return _chart; }; /** * The Color Mixin is an abstract chart functional class providing universal coloring support * as a mix-in for any concrete chart implementation. * @name colorMixin * @memberof dc * @mixin * @param {Chart} _chart * @returns {Chart} */ dc.colorMixin = function (_chart) { var _colors = d3.scale.category20c(); var _defaultAccessor = true; var _colorAccessor = function (d) { return _chart.keyAccessor()(d); }; /** * Retrieve current color scale or set a new color scale. This methods accepts any function that * operates like a d3 scale. * @name colors * @memberof dc.colorMixin * @instance * @example * // alternate categorical scale * chart.colors(d3.scale.category20b()); * * // ordinal scale * chart.colors(d3.scale.ordinal().range(['red','green','blue'])); * // convenience method, the same as above * chart.ordinalColors(['red','green','blue']); * * // set a linear scale * chart.linearColors(["#4575b4", "#ffffbf", "#a50026"]); * @param {D3Scale} [colorScale=d3.scale.category20c()] * @returns {Chart} */ _chart.colors = function (colorScale) { if (!arguments.length) { return _colors; } if (colorScale instanceof Array) { _colors = d3.scale.quantize().range(colorScale); // deprecated legacy support, note: this fails for ordinal domains } else { _colors = d3.functor(colorScale); } return _chart; }; /** * Convenience method to set the color scale to d3.scale.ordinal with range `r`. * @name ordinalColors * @memberof dc.colorMixin * @instance * @param {Array<String>} r * @returns {Chart} */ _chart.ordinalColors = function (r) { return _chart.colors(d3.scale.ordinal().range(r)); }; /** * Convenience method to set the color scale to an Hcl interpolated linear scale with range `r`. * @name linearColors * @memberof dc.colorMixin * @instance * @param {Array<Number>} r * @returns {Chart} */ _chart.linearColors = function (r) { return _chart.colors(d3.scale.linear() .range(r) .interpolate(d3.interpolateHcl)); }; /** * Set or the get color accessor function. This function will be used to map a data point in a * crossfilter group to a color value on the color scale. The default function uses the key * accessor. * @name linearColors * @memberof dc.colorMixin * @instance * @example * // default index based color accessor * .colorAccessor(function (d, i){return i;}) * // color accessor for a multi-value crossfilter reduction * .colorAccessor(function (d){return d.value.absGain;}) * @param {Function} [colorAccessorFunction] * @returns {Function} */ _chart.colorAccessor = function (colorAccessorFunction) { if (!arguments.length) { return _colorAccessor; } _colorAccessor = colorAccessorFunction; _defaultAccessor = false; return _chart; }; // what is this? _chart.defaultColorAccessor = function () { return _defaultAccessor; }; /** * Set or get the current domain for the color mapping function. The domain must be supplied as an * array. * * Note: previously this method accepted a callback function. Instead you may use a custom scale * set by `.colors`. * @name colorDomain * @memberof dc.colorMixin * @instance * @param {Array<String>} [domain] * @returns {Function} */ _chart.colorDomain = function (domain) { if (!arguments.length) { return _colors.domain(); } _colors.domain(domain); return _chart; }; /** * Set the domain by determining the min and max values as retrieved by `.colorAccessor` over the * chart's dataset. * @name calculateColorDomain * @memberof dc.colorMixin * @instance * @returns {Chart} */ _chart.calculateColorDomain = function () { var newDomain = [d3.min(_chart.data(), _chart.colorAccessor()), d3.max(_chart.data(), _chart.colorAccessor())]; _colors.domain(newDomain); return _chart; }; /** * Get the color for the datum d and counter i. This is used internally by charts to retrieve a color. * @name getColor * @memberof dc.colorMixin * @instance * @param {*} d * @param {Number} [i] * @returns {String} */ _chart.getColor = function (d, i) { return _colors(_colorAccessor.call(this, d, i)); }; /** * Get the color for the datum d and counter i. This is used internally by charts to retrieve a color. * @name colorCalculator * @memberof dc.colorMixin * @instance * @param {*} [colorCalculator] * @returns {*} */ _chart.colorCalculator = function (colorCalculator) { if (!arguments.length) { return _chart.getColor; } _chart.getColor = colorCalculator; return _chart; }; return _chart; }; /** * Coordinate Grid is an abstract base chart designed to support a number of coordinate grid based * concrete chart types, e.g. bar chart, line chart, and bubble chart. * @name coordinateGridMixin * @memberof dc * @mixin * @mixes dc.colorMixin * @mixes dc.marginMixin * @mixes dc.baseMixin * @param {Chart} _chart * @returns {Chart} */ dc.coordinateGridMixin = function (_chart) { var GRID_LINE_CLASS = 'grid-line'; var HORIZONTAL_CLASS = 'horizontal'; var VERTICAL_CLASS = 'vertical'; var Y_AXIS_LABEL_CLASS = 'y-axis-label'; var X_AXIS_LABEL_CLASS = 'x-axis-label'; var DEFAULT_AXIS_LABEL_PADDING = 12; _chart = dc.colorMixin(dc.marginMixin(dc.baseMixin(_chart))); _chart.colors(d3.scale.category10()); _chart._mandatoryAttributes().push('x'); function zoomHandler () { _refocused = true; if (_zoomOutRestrict) { _chart.x().domain(constrainRange(_chart.x().domain(), _xOriginalDomain)); if (_rangeChart) { _chart.x().domain(constrainRange(_chart.x().domain(), _rangeChart.x().domain())); } } var domain = _chart.x().domain(); var domFilter = dc.filters.RangedFilter(domain[0], domain[1]); _chart.replaceFilter(domFilter); _chart.rescale(); _chart.redraw(); if (_rangeChart && !rangesEqual(_chart.filter(), _rangeChart.filter())) { dc.events.trigger(function () { _rangeChart.replaceFilter(domFilter); _rangeChart.redraw(); }); } _chart._invokeZoomedListener(); dc.events.trigger(function () { _chart.redrawGroup(); }, dc.constants.EVENT_DELAY); _refocused = !rangesEqual(domain, _xOriginalDomain); } var _parent; var _g; var _chartBodyG; var _x; var _xOriginalDomain; var _xAxis = d3.svg.axis().orient('bottom'); var _xUnits = dc.units.integers; var _xAxisPadding = 0; var _xElasticity = false; var _xAxisLabel; var _xAxisLabelPadding = 0; var _lastXDomain; var _y; var _yAxis = d3.svg.axis().orient('left'); var _yAxisPadding = 0; var _yElasticity = false; var _yAxisLabel; var _yAxisLabelPadding = 0; var _brush = d3.svg.brush(); var _brushOn = true; var _round; var _renderHorizontalGridLine = false; var _renderVerticalGridLine = false; var _refocused = false, _resizing = false; var _unitCount; var _zoomScale = [1, Infinity]; var _zoomOutRestrict = true; var _zoom = d3.behavior.zoom().on('zoom', zoomHandler); var _nullZoom = d3.behavior.zoom().on('zoom', null); var _hasBeenMouseZoomable = false; var _rangeChart; var _focusChart; var _mouseZoomable = false; var _clipPadding = 0; var _outerRangeBandPadding = 0.5; var _rangeBandPadding = 0; var _useRightYAxis = false; /** * When changing the domain of the x or y scale, it is necessary to tell the chart to recalculate * and redraw the axes. (`.rescale()` is called automatically when the x or y scale is replaced * with `.x()` or `.y()`, and has no effect on elastic scales.) * @name rescale * @memberof dc.coordinateGridMixin * @instance * @returns {Chart} */ _chart.rescale = function () { _unitCount = undefined; _resizing = true; return _chart; }; /** * Get or set the range selection chart associated with this instance. Setting the range selection * chart using this function will automatically update its selection brush when the current chart * zooms in. In return the given range chart will also automatically attach this chart as its focus * chart hence zoom in when range brush updates. See the [Nasdaq 100 * Index](http://dc-js.github.com/dc.js/) example for this effect in action. * @name rangeChart * @memberof dc.coordinateGridMixin * @instance * @param {Chart} [rangeChart] * @returns {Chart} */ _chart.rangeChart = function (rangeChart) { if (!arguments.length) { return _rangeChart; } _rangeChart = rangeChart; _rangeChart.focusChart(_chart); return _chart; }; /** * Get or set the scale extent for mouse zooms. * @name zoomScale * @memberof dc.coordinateGridMixin * @instance * @param {Array<*>} [extent] * @returns {Chart} */ _chart.zoomScale = function (extent) { if (!arguments.length) { return _zoomScale; } _zoomScale = extent; return _chart; }; /** * Get or set the zoom restriction for the chart. If true limits the zoom to origional domain of the chart. * @name zoomOutRestrict * @memberof dc.coordinateGridMixin * @instance * @param {Boolean} [zoomOutRestrict=true] * @returns {Chart} */ _chart.zoomOutRestrict = function (zoomOutRestrict) { if (!arguments.length) { return _zoomOutRestrict; } _zoomScale[0] = zoomOutRestrict ? 1 : 0; _zoomOutRestrict = zoomOutRestrict; return _chart; }; _chart._generateG = function (parent) { if (parent === undefined) { _parent = _chart.svg(); } else { _parent = parent; } _g = _parent.append('g'); _chartBodyG = _g.append('g').attr('class', 'chart-body') .attr('transform', 'translate(' + _chart.margins().left + ', ' + _chart.margins().top + ')') .attr('clip-path', 'url(#' + getClipPathId() + ')'); return _g; }; /** * Get or set the root g element. This method is usually used to retrieve the g element in order to * overlay custom svg drawing programatically. **Caution**: The root g element is usually generated * by dc.js internals, and resetting it might produce unpredictable result. * @name g * @memberof dc.coordinateGridMixin * @instance * @param {svg} [gElement] * @returns {Chart} */ _chart.g = function (gElement) { if (!arguments.length) { return _g; } _g = gElement; return _chart; }; /** * Set or get mouse zoom capability flag (default: false). When turned on the chart will be * zoomable using the mouse wheel. If the range selector chart is attached zooming will also update * the range selection brush on the associated range selector chart. * @name mouseZoomable * @memberof dc.coordinateGridMixin * @instance * @param {Boolean} [mouseZoomable] * @returns {Chart} */ _chart.mouseZoomable = function (mouseZoomable) { if (!arguments.length) { return _mouseZoomable; } _mouseZoomable = mouseZoomable; return _chart; }; /** * Retrieve the svg group for the chart body. * @name chartBodyG * @memberof dc.coordinateGridMixin * @instance * @param {svg} [chartBodyG] * @returns {Chart} */ _chart.chartBodyG = function (chartBodyG) { if (!arguments.length) { return _chartBodyG; } _chartBodyG = chartBodyG; return _chart; }; /** * **mandatory** * * Get or set the x scale. The x scale can be any d3 * [quantitive scale](https://github.com/mbostock/d3/wiki/Quantitative-Scales) or * [ordinal scale](https://github.com/mbostock/d3/wiki/Ordinal-Scales). * @name x * @memberof dc.coordinateGridMixin * @instance * @example * // set x to a linear scale * chart.x(d3.scale.linear().domain([-2500, 2500])) * // set x to a time scale to generate histogram * chart.x(d3.time.scale().domain([new Date(1985, 0, 1), new Date(2012, 11, 31)])) * @param {d3.scale} [xScale] * @returns {Chart} */ _chart.x = function (xScale) { if (!arguments.length) { return _x; } _x = xScale; _xOriginalDomain = _x.domain(); _chart.rescale(); return _chart; }; _chart.xOriginalDomain = function () { return _xOriginalDomain; }; /** * Set or get the xUnits function. The coordinate grid chart uses the xUnits function to calculate * the number of data projections on x axis such as the number of bars for a bar chart or the * number of dots for a line chart. This function is expected to return a Javascript array of all * data points on x axis, or the number of points on the axis. [d3 time range functions * d3.time.days, d3.time.months, and * d3.time.years](https://github.com/mbostock/d3/wiki/Time-Intervals#aliases) are all valid xUnits * function. dc.js also provides a few units function, see the [Utilities](#utilities) section for * a list of built-in units functions. The default xUnits function is dc.units.integers. * @name xUnits * @memberof dc.coordinateGridMixin * @instance * @example * // set x units to count days * chart.xUnits(d3.time.days); * // set x units to count months * chart.xUnits(d3.time.months); * * // A custom xUnits function can be used as long as it follows the following interface: * // units in integer * function(start, end, xDomain) { * // simply calculates how many integers in the domain * return Math.abs(end - start); * }; * * // fixed units * function(start, end, xDomain) { * // be aware using fixed units will disable the focus/zoom ability on the chart * return 1000; * @param {Function} [xUnits] * @returns {Chart} */ _chart.xUnits = function (xUnits) { if (!arguments.length) { return _xUnits; } _xUnits = xUnits; return _chart; }; /** * Set or get the x axis used by a particular coordinate grid chart instance. This function is most * useful when x axis customization is required. The x axis in dc.js is an instance of a [d3 * axis object](https://github.com/mbostock/d3/wiki/SVG-Axes#wiki-axis); therefore it supports any * valid d3 axis manipulation. **Caution**: The x axis is usually generated internally by dc; * resetting it may cause unexpected results. * @name xAxis * @memberof dc.coordinateGridMixin * @instance * @example * // customize x axis tick format * chart.xAxis().tickFormat(function(v) {return v + '%';}); * // customize x axis tick values * chart.xAxis().tickValues([0, 100, 200, 300]); * @param {d3.svg.axis} [xAxis] * @returns {Chart} */ _chart.xAxis = function (xAxis) { if (!arguments.length) { return _xAxis; } _xAxis = xAxis; return _chart; }; /** * Turn on/off elastic x axis behavior. If x axis elasticity is turned on, then the grid chart will * attempt to recalculate the x axis range whenever a redraw event is triggered. * @name elasticX * @memberof dc.coordinateGridMixin * @instance * @param {Boolean} [elasticX=false] * @returns {Chart} */ _chart.elasticX = function (elasticX) { if (!arguments.length) { return _xElasticity; } _xElasticity = elasticX; return _chart; }; /** * Set or get x axis padding for the elastic x axis. The padding will be added to both end of the x * axis if elasticX is turned on; otherwise it is ignored. * * padding can be an integer or percentage in string (e.g. '10%'). Padding can be applied to * number or date x axes. When padding a date axis, an integer represents number of days being padded * and a percentage string will be treated the same as an integer. * @name xAxisPadding * @memberof dc.coordinateGridMixin * @instance * @param {Number|String} [padding] * @returns {Chart} */ _chart.xAxisPadding = function (padding) { if (!arguments.length) { return _xAxisPadding; } _xAxisPadding = padding; return _chart; }; /** * Returns the number of units displayed on the x axis using the unit measure configured by * .xUnits. * @name xUnitCount * @memberof dc.coordinateGridMixin * @instance * @returns {Number} */ _chart.xUnitCount = function () { if (_unitCount === undefined) { var units = _chart.xUnits()(_chart.x().domain()[0], _chart.x().domain()[1], _chart.x().domain()); if (units instanceof Array) { _unitCount = units.length; } else { _unitCount = units; } } return _unitCount; }; /** * Gets or sets whether the chart should be drawn with a right axis instead of a left axis. When * used with a chart in a composite chart, allows both left and right Y axes to be shown on a * chart. * @name useRightYAxis * @memberof dc.coordinateGridMixin * @instance * @param {Boolean} [useRightYAxis=false] * @returns {Chart} */ _chart.useRightYAxis = function (useRightYAxis) { if (!arguments.length) { return _useRightYAxis; } _useRightYAxis = useRightYAxis; return _chart; }; /** * Returns true if the chart is using ordinal xUnits ([dc.units.ordinal](#dcunitsordinal)), or false * otherwise. Most charts behave differently with ordinal data and use the result of this method to * trigger the appropriate logic. * @name isOrdinal * @memberof dc.coordinateGridMixin * @instance * @returns {Boolean} */ _chart.isOrdinal = function () { return _chart.xUnits() === dc.units.ordinal; }; _chart._useOuterPadding = function () { return true; }; _chart._ordinalXDomain = function () { var groups = _chart._computeOrderedGroups(_chart.data()); return groups.map(_chart.keyAccessor()); }; function compareDomains (d1, d2) { return !d1 || !d2 || d1.length !== d2.length || d1.some(function (elem, i) { return elem.toString() !== d2[i].toString(); }); } function prepareXAxis (g, render) { if (!_chart.isOrdinal()) { if (_chart.elasticX()) { _x.domain([_chart.xAxisMin(), _chart.xAxisMax()]); } } else { // _chart.isOrdinal() if (_chart.elasticX() || _x.domain().length === 0) { _x.domain(_chart._ordinalXDomain()); } } // has the domain changed? var xdom = _x.domain(); if (render || compareDomains(_lastXDomain, xdom)) { _chart.rescale(); } _lastXDomain = xdom; // please can't we always use rangeBands for bar charts? if (_chart.isOrdinal()) { _x.rangeBands([0, _chart.xAxisLength()], _rangeBandPadding, _chart._useOuterPadding() ? _outerRangeBandPadding : 0); } else { _x.range([0, _chart.xAxisLength()]); } _xAxis = _xAxis.scale(_chart.x()); renderVerticalGridLines(g); } _chart.renderXAxis = function (g) { var axisXG = g.selectAll('g.x'); if (axisXG.empty()) { axisXG = g.append('g') .attr('class', 'axis x') .attr('transform', 'translate(' + _chart.margins().left + ',' + _chart._xAxisY() + ')'); } var axisXLab = g.selectAll('text.' + X_AXIS_LABEL_CLASS); if (axisXLab.empty() && _chart.xAxisLabel()) { axisXLab = g.append('text') .attr('class', X_AXIS_LABEL_CLASS) .attr('transform', 'translate(' + (_chart.margins().left + _chart.xAxisLength() / 2) + ',' + (_chart.height() - _xAxisLabelPadding) + ')') .attr('text-anchor', 'middle'); } if (_chart.xAxisLabel() && axisXLab.text() !== _chart.xAxisLabel()) { axisXLab.text(_chart.xAxisLabel()); } dc.transition(axisXG, _chart.transitionDuration()) .attr('transform', 'translate(' + _chart.margins().left + ',' + _chart._xAxisY() + ')') .call(_xAxis); dc.transition(axisXLab, _chart.transitionDuration()) .attr('transform', 'translate(' + (_chart.margins().left + _chart.xAxisLength() / 2) + ',' + (_chart.height() - _xAxisLabelPadding) + ')'); }; function renderVerticalGridLines (g) { var gridLineG = g.selectAll('g.' + VERTICAL_CLASS); if (_renderVerticalGridLine) { if (gridLineG.empty()) { gridLineG = g.insert('g', ':first-child') .attr('class', GRID_LINE_CLASS + ' ' + VERTICAL_CLASS) .attr('transform', 'translate(' + _chart.margins().left + ',' + _chart.margins().top + ')'); } var ticks = _xAxis.tickValues() ? _xAxis.tickValues() : (typeof _x.ticks === 'function' ? _x.ticks(_xAxis.ticks()[0]) : _x.domain()); var lines = gridLineG.selectAll('line') .data(ticks); // enter var linesGEnter = lines.enter() .append('line') .attr('x1', function (d) { return _x(d); }) .attr('y1', _chart._xAxisY() - _chart.margins().top) .attr('x2', function (d) { return _x(d); }) .attr('y2', 0) .attr('opacity', 0); dc.transition(linesGEnter, _chart.transitionDuration()) .attr('opacity', 1); // update dc.transition(lines, _chart.transitionDuration()) .attr('x1', function (d) { return _x(d); }) .attr('y1', _chart._xAxisY() - _chart.margins().top) .attr('x2', function (d) { return _x(d); }) .attr('y2', 0); // exit lines.exit().remove(); } else { gridLineG.selectAll('line').remove(); } } _chart._xAxisY = function () { return (_chart.height() - _chart.margins().bottom); }; _chart.xAxisLength = function () { return _chart.effectiveWidth(); }; /** * Set or get the x axis label. If setting the label, you may optionally include additional padding to * the margin to make room for the label. By default the padded is set to 12 to accomodate the text height. * @name xAxisLabel * @memberof dc.coordinateGridMixin * @instance * @param {String} [labelText] * @param {Number} [padding=12] * @returns {Chart} */ _chart.xAxisLabel = function (labelText, padding) { if (!arguments.length) { return _xAxisLabel; } _xAxisLabel = labelText; _chart.margins().bottom -= _xAxisLabelPadding; _xAxisLabelPadding = (padding === undefined) ? DEFAULT_AXIS_LABEL_PADDING : padding; _chart.margins().bottom += _xAxisLabelPadding; return _chart; }; _chart._prepareYAxis = function (g) { if (_y === undefined || _chart.elasticY()) { if (_y === undefined) { _y = d3.scale.linear(); } var min = _chart.yAxisMin() || 0, max = _chart.yAxisMax() || 0; _y.domain([min, max]).rangeRound([_chart.yAxisHeight(), 0]); } _y.range([_chart.yAxisHeight(), 0]); _yAxis = _yAxis.scale(_y); if (_useRightYAxis) { _yAxis.orient('right'); } _chart._renderHorizontalGridLinesForAxis(g, _y, _yAxis); }; _chart.renderYAxisLabel = function (axisClass, text, rotation, labelXPosition) { labelXPosition = labelXPosition || _yAxisLabelPadding; var axisYLab = _chart.g().selectAll('text.' + Y_AXIS_LABEL_CLASS + '.' + axisClass + '-label'); var labelYPosition = (_chart.margins().top + _chart.yAxisHeight() / 2); if (axisYLab.empty() && text) { axisYLab = _chart.g().append('text') .attr('transform', 'translate(' + labelXPosition + ',' + labelYPosition + '),rotate(' + rotation + ')') .attr('class', Y_AXIS_LABEL_CLASS + ' ' + axisClass + '-label') .attr('text-anchor', 'middle') .text(text); } if (text && axisYLab.text() !== text) { axisYLab.text(text); } dc.transition(axisYLab, _chart.transitionDuration()) .attr('transform', 'translate(' + labelXPosition + ',' + labelYPosition + '),rotate(' + rotation + ')'); }; _chart.renderYAxisAt = function (axisClass, axis, position) { var axisYG = _chart.g().selectAll('g.' + axisClass); if (axisYG.empty()) { axisYG = _chart.g().append('g') .attr('class', 'axis ' + axisClass) .attr('transform', 'translate(' + position + ',' + _chart.margins().top + ')'); } dc.transition(axisYG, _chart.transitionDuration()) .attr('transform', 'translate(' + position + ',' + _chart.margins().top + ')') .call(axis); }; _chart.renderYAxis = function () { var axisPosition = _useRightYAxis ? (_chart.width() - _chart.margins().right) : _chart._yAxisX(); _chart.renderYAxisAt('y', _yAxis, axisPosition); var labelPosition = _useRightYAxis ? (_chart.width() - _yAxisLabelPadding) : _yAxisLabelPadding; var rotation = _useRightYAxis ? 90 : -90; _chart.renderYAxisLabel('y', _chart.yAxisLabel(), rotation, labelPosition); }; _chart._renderHorizontalGridLinesForAxis = function (g, scale, axis) { var gridLineG = g.selectAll('g.' + HORIZONTAL_CLASS); if (_renderHorizontalGridLine) { var ticks = axis.tickValues() ? axis.tickValues() : scale.ticks(axis.ticks()[0]); if (gridLineG.empty()) { gridLineG = g.insert('g', ':first-child') .attr('class', GRID_LINE_CLASS + ' ' + HORIZONTAL_CLASS) .attr('transform', 'translate(' + _chart.margins().left + ',' + _chart.margins().top + ')'); } var lines = gridLineG.selectAll('line') .data(ticks); // enter var linesGEnter = lines.enter() .append('line') .attr('x1', 1) .attr('y1', function (d) { return scale(d); }) .attr('x2', _chart.xAxisLength()) .attr('y2', function (d) { return scale(d); }) .attr('opacity', 0); dc.transition(linesGEnter, _chart.transitionDuration()) .attr('opacity', 1); // update dc.transition(lines, _chart.transitionDuration()) .attr('x1', 1) .attr('y1', function (d) { return scale(d); }) .attr('x2', _chart.xAxisLength()) .attr('y2', function (d) { return scale(d); }); // exit lines.exit().remove(); } else { gridLineG.selectAll('line').remove(); } }; _chart._yAxisX = function () { return _chart.useRightYAxis() ? _chart.width() - _chart.margins().right : _chart.margins().left; }; /** * Set or get the y axis label. If setting the label, you may optionally include additional padding * to the margin to make room for the label. By default the padded is set to 12 to accomodate the * text height. * @name yAxisLabel * @memberof dc.coordinateGridMixin * @instance * @param {String} [labelText] * @param {Number} [padding=12] * @returns {Chart} */ _chart.yAxisLabel = function (labelText, padding) { if (!arguments.length) { return _yAxisLabel; } _yAxisLabel = labelText; _chart.margins().left -= _yAxisLabelPadding; _yAxisLabelPadding = (padding === undefined) ? DEFAULT_AXIS_LABEL_PADDING : padding; _chart.margins().left += _yAxisLabelPadding; return _chart; }; /** * Get or set the y scale. The y scale is typically automatically determined by the chart implementation. * @name y * @memberof dc.coordinateGridMixin * @instance * @param {d3.scale} [yScale] * @returns {Chart} */ _chart.y = function (yScale) { if (!arguments.length) { return _y; } _y = yScale; _chart.rescale(); return _chart; }; /** * Set or get the y axis used by the coordinate grid chart instance. This function is most useful * when y axis customization is required. The y axis in dc.js is simply an instance of a [d3 axis * object](https://github.com/mbostock/d3/wiki/SVG-Axes#wiki-_axis); therefore it supports any * valid d3 axis manipulation. **Caution**: The y axis is usually generated internally by dc; * resetting it may cause unexpected results. * @name yAxis * @memberof dc.coordinateGridMixin * @instance * @example * // customize y axis tick format * chart.yAxis().tickFormat(function(v) {return v + '%';}); * // customize y axis tick values * chart.yAxis().tickValues([0, 100, 200, 300]); * @param {d3.svg.axis} [yAxis=d3.svg.axis().orient('left')] * @returns {Chart} */ _chart.yAxis = function (yAxis) { if (!arguments.length) { return _yAxis; } _yAxis = yAxis; return _chart; }; /** * Turn on/off elastic y axis behavior. If y axis elasticity is turned on, then the grid chart will * attempt to recalculate the y axis range whenever a redraw event is triggered. * @name elasticY * @memberof dc.coordinateGridMixin * @instance * @param {Boolean} [elasticY=false] * @returns {Chart} */ _chart.elasticY = function (elasticY) { if (!arguments.length) { return _yElasticity; } _yElasticity = elasticY; return _chart; }; /** * Turn on/off horizontal grid lines. * @name renderHorizontalGridLines * @memberof dc.coordinateGridMixin * @instance * @param {Boolean} [renderHorizontalGridLines=false] * @returns {Chart} */ _chart.renderHorizontalGridLines = function (renderHorizontalGridLines) { if (!arguments.length) { return _renderHorizontalGridLine; } _renderHorizontalGridLine = renderHorizontalGridLines; return _chart; }; /** * Turn on/off vertical grid lines. * @name renderVerticalGridLines * @memberof dc.coordinateGridMixin * @instance * @param {Boolean} [renderVerticalGridLines=false] * @returns {Chart} */ _chart.renderVerticalGridLines = function (renderVerticalGridLines) { if (!arguments.length) { return _renderVerticalGridLine; } _renderVerticalGridLine = renderVerticalGridLines; return _chart; }; /** * Calculates the minimum x value to display in the chart. Includes xAxisPadding if set. * @name xAxisMin * @memberof dc.coordinateGridMixin * @instance * @returns {*} */ _chart.xAxisMin = function () { var min = d3.min(_chart.data(), function (e) { return _chart.keyAccessor()(e); }); return dc.utils.subtract(min, _xAxisPadding); }; /** * Calculates the maximum x value to display in the chart. Includes xAxisPadding if set. * @name xAxisMax * @memberof dc.coordinateGridMixin * @instance * @returns {*} */ _chart.xAxisMax = function () { var max = d3.max(_chart.data(), function (e) { return _chart.keyAccessor()(e); }); return dc.utils.add(max, _xAxisPadding); }; /** * Calculates the minimum y value to display in the chart. Includes yAxisPadding if set. * @name yAxisMin * @memberof dc.coordinateGridMixin * @instance * @returns {*} */ _chart.yAxisMin = function () { var min = d3.min(_chart.data(), function (e) { return _chart.valueAccessor()(e); }); return dc.utils.subtract(min, _yAxisPadding); }; /** * Calculates the maximum y value to display in the chart. Includes yAxisPadding if set. * @name yAxisMax * @memberof dc.coordinateGridMixin * @instance * @returns {*} */ _chart.yAxisMax = function () { var max = d3.max(_chart.data(), function (e) { return _chart.valueAccessor()(e); }); return dc.utils.add(max, _yAxisPadding); }; /** * Set or get y axis padding for the elastic y axis. The padding will be added to the top of the y * axis if elasticY is turned on; otherwise it is ignored. * * padding can be an integer or percentage in string (e.g. '10%'). Padding can be applied to * number or date axes. When padding a date axis, an integer represents number of days being padded * and a percentage string will be treated the same as an integer. * @name yAxisPadding * @memberof dc.coordinateGridMixin * @instance * @param {Number|String} [padding=0] * @returns {Chart} */ _chart.yAxisPadding = function (padding) { if (!arguments.length) { return _yAxisPadding; } _yAxisPadding = padding; return _chart; }; _chart.yAxisHeight = function () { return _chart.effectiveHeight(); }; /** * Set or get the rounding function used to quantize the selection when brushing is enabled. * @name round * @memberof dc.coordinateGridMixin * @instance * @example * // set x unit round to by month, this will make sure range selection brush will * // select whole months * chart.round(d3.time.month.round); * @param {Function} [round] * @returns {Chart} */ _chart.round = function (round) { if (!arguments.length) { return _round; } _round = round; return _chart; }; _chart._rangeBandPadding = function (_) { if (!arguments.length) { return _rangeBandPadding; } _rangeBandPadding = _; return _chart; }; _chart._outerRangeBandPadding = function (_) { if (!arguments.length) { return _outerRangeBandPadding; } _outerRangeBandPadding = _; return _chart; }; dc.override(_chart, 'filter', function (_) { if (!arguments.length) { return _chart._filter(); } _chart._filter(_); if (_) { _chart.brush().extent(_); } else { _chart.brush().clear(); } return _chart; }); _chart.brush = function (_) { if (!arguments.length) { return _brush; } _brush = _; return _chart; }; function brushHeight () { return _chart._xAxisY() - _chart.margins().top; } _chart.renderBrush = function (g) { if (_brushOn) { _brush.on('brush', _chart._brushing); _brush.on('brushstart', _chart._disableMouseZoom); _brush.on('brushend', configureMouseZoom); var gBrush = g.append('g') .attr('class', 'brush') .attr('transform', 'translate(' + _chart.margins().left + ',' + _chart.margins().top + ')') .call(_brush.x(_chart.x())); _chart.setBrushY(gBrush, false); _chart.setHandlePaths(gBrush); if (_chart.hasFilter()) { _chart.redrawBrush(g, false); } } }; _chart.setHandlePaths = function (gBrush) { gBrush.selectAll('.resize').append('path').attr('d', _chart.resizeHandlePath); }; _chart.setBrushY = function (gBrush) { gBrush.selectAll('.brush rect') .attr('height', brushHeight()); gBrush.selectAll('.resize path') .attr('d', _chart.resizeHandlePath); }; _chart.extendBrush = function () { var extent = _brush.extent(); if (_chart.round()) { extent[0] = extent.map(_chart.round())[0]; extent[1] = extent.map(_chart.round())[1]; _g.select('.brush') .call(_brush.extent(extent)); } return extent; }; _chart.brushIsEmpty = function (extent) { return _brush.empty() || !extent || extent[1] <= extent[0]; }; _chart._brushing = function () { var extent = _chart.extendBrush(); _chart.redrawBrush(_g, false); if (_chart.brushIsEmpty(extent)) { dc.events.trigger(function () { _chart.filter(null); _chart.redrawGroup(); }, dc.constants.EVENT_DELAY); } else { var rangedFilter = dc.filters.RangedFilter(extent[0], extent[1]); dc.events.trigger(function () { _chart.replaceFilter(rangedFilter); _chart.redrawGroup(); }, dc.constants.EVENT_DELAY); } }; _chart.redrawBrush = function (g, doTransition) { if (_brushOn) { if (_chart.filter() && _chart.brush().empty()) { _chart.brush().extent(_chart.filter()); } var gBrush = dc.optionalTransition(doTransition, _chart.transitionDuration())(g.select('g.brush')); _chart.setBrushY(gBrush); gBrush.call(_chart.brush() .x(_chart.x()) .extent(_chart.brush().extent())); } _chart.fadeDeselectedArea(); }; _chart.fadeDeselectedArea = function () { // do nothing, sub-chart should override this function }; // borrowed from Crossfilter example _chart.resizeHandlePath = function (d) { var e = +(d === 'e'), x = e ? 1 : -1, y = brushHeight() / 3; return 'M' + (0.5 * x) + ',' + y + 'A6,6 0 0 ' + e + ' ' + (6.5 * x) + ',' + (y + 6) + 'V' + (2 * y - 6) + 'A6,6 0 0 ' + e + ' ' + (0.5 * x) + ',' + (2 * y) + 'Z' + 'M' + (2.5 * x) + ',' + (y + 8) + 'V' + (2 * y - 8) + 'M' + (4.5 * x) + ',' + (y + 8) + 'V' + (2 * y - 8); }; function getClipPathId () { return _chart.anchorName().replace(/[ .#=\[\]]/g, '-') + '-clip'; } /** * Get or set the padding in pixels for the clip path. Once set padding will be applied evenly to * the top, left, right, and bottom when the clip path is generated. If set to zero, the clip area * will be exactly the chart body area minus the margins. * @name clipPadding * @memberof dc.coordinateGridMixin * @instance * @param {Number} [padding=5] * @returns {Chart} */ _chart.clipPadding = function (padding) { if (!arguments.length) { return _clipPadding; } _clipPadding = padding; return _chart; }; function generateClipPath () { var defs = dc.utils.appendOrSelect(_parent, 'defs'); // cannot select <clippath> elements; bug in WebKit, must select by id // https://groups.google.com/forum/#!topic/d3-js/6EpAzQ2gU9I var id = getClipPathId(); var chartBodyClip = dc.utils.appendOrSelect(defs, '#' + id, 'clipPath').attr('id', id); var padding = _clipPadding * 2; dc.utils.appendOrSelect(chartBodyClip, 'rect') .attr('width', _chart.xAxisLength() + padding) .attr('height', _chart.yAxisHeight() + padding) .attr('transform', 'translate(-' + _clipPadding + ', -' + _clipPadding + ')'); } _chart._preprocessData = function () {}; _chart._doRender = function () { _chart.resetSvg(); _chart._preprocessData(); _chart._generateG(); generateClipPath(); drawChart(true); configureMouseZoom(); return _chart; }; _chart._doRedraw = function () { _chart._preprocessData(); drawChart(false); generateClipPath(); return _chart; }; function drawChart (render) { if (_chart.isOrdinal()) { _brushOn = false; } prepareXAxis(_chart.g(), render); _chart._prepareYAxis(_chart.g()); _chart.plotData(); if (_chart.elasticX() || _resizing || render) { _chart.renderXAxis(_chart.g()); } if (_chart.elasticY() || _resizing || render) { _chart.renderYAxis(_chart.g()); } if (render) { _chart.renderBrush(_chart.g(), false); } else { _chart.redrawBrush(_chart.g(), _resizing); } _chart.fadeDeselectedArea(); _resizing = false; } function configureMouseZoom () { if (_mouseZoomable) { _chart._enableMouseZoom(); } else if (_hasBeenMouseZoomable) { _chart._disableMouseZoom(); } } _chart._enableMouseZoom = function () { _hasBeenMouseZoomable = true; _zoom.x(_chart.x()) .scaleExtent(_zoomScale) .size([_chart.width(), _chart.height()]) .duration(_chart.transitionDuration()); _chart.root().call(_zoom); }; _chart._disableMouseZoom = function () { _chart.root().call(_nullZoom); }; function constrainRange (range, constraint) { var constrainedRange = []; constrainedRange[0] = d3.max([range[0], constraint[0]]); constrainedRange[1] = d3.min([range[1], constraint[1]]); return constrainedRange; } /** * Zoom this chart to focus on the given range. The given range should be an array containing only * 2 elements (`[start, end]`) defining a range in the x domain. If the range is not given or set * to null, then the zoom will be reset. _For focus to work elasticX has to be turned off; * otherwise focus will be ignored. * @name focus * @memberof dc.coordinateGridMixin * @instance * @example * chart.on('renderlet', function(chart) { * // smooth the rendering through event throttling * dc.events.trigger(function(){ * // focus some other chart to the range selected by user on this chart * someOtherChart.focus(chart.filter()); * }); * }) * @param {Array<Number>} [range] */ _chart.focus = function (range) { if (hasRangeSelected(range)) { _chart.x().domain(range); } else { _chart.x().domain(_xOriginalDomain); } _zoom.x(_chart.x()); zoomHandler(); }; _chart.refocused = function () { return _refocused; }; _chart.focusChart = function (c) { if (!arguments.length) { return _focusChart; } _focusChart = c; _chart.on('filtered', function (chart) { if (!chart.filter()) { dc.events.trigger(function () { _focusChart.x().domain(_focusChart.xOriginalDomain()); }); } else if (!rangesEqual(chart.filter(), _focusChart.filter())) { dc.events.trigger(function () { _focusChart.focus(chart.filter()); }); } }); return _chart; }; function rangesEqual (range1, range2) { if (!range1 && !range2) { return true; } else if (!range1 || !range2) { return false; } else if (range1.length === 0 && range2.length === 0) { return true; } else if (range1[0].valueOf() === range2[0].valueOf() && range1[1].valueOf() === range2[1].valueOf()) { return true; } return false; } /** * Turn on/off the brush-based range filter. When brushing is on then user can drag the mouse * across a chart with a quantitative scale to perform range filtering based on the extent of the * brush, or click on the bars of an ordinal bar chart or slices of a pie chart to filter and * unfilter them. However turning on the brush filter will disable other interactive elements on * the chart such as highlighting, tool tips, and reference lines. Zooming will still be possible * if enabled, but only via scrolling (panning will be disabled.) * @name brushOn * @memberof dc.coordinateGridMixin * @instance * @param {Boolean} [brushOn=true] * @return {Chart} */ _chart.brushOn = function (brushOn) { if (!arguments.length) { return _brushOn; } _brushOn = brushOn; return _chart; }; function hasRangeSelected (range) { return range instanceof Array && range.length > 1; } return _chart; }; /** * Stack Mixin is an mixin that provides cross-chart support of stackability using d3.layout.stack. * @name stackMixin * @memberof dc * @mixin * @param {Chart} _chart * @returns {Chart} */ dc.stackMixin = function (_chart) { function prepareValues (layer, layerIdx) { var valAccessor = layer.accessor || _chart.valueAccessor(); layer.name = String(layer.name || layerIdx); layer.values = layer.group.all().map(function (d, i) { return { x: _chart.keyAccessor()(d, i), y: layer.hidden ? null : valAccessor(d, i), data: d, layer: layer.name, hidden: layer.hidden }; }); layer.values = layer.values.filter(domainFilter()); return layer.values; } var _stackLayout = d3.layout.stack() .values(prepareValues); var _stack = []; var _titles = {}; var _hidableStacks = false; function domainFilter () { if (!_chart.x()) { return d3.functor(true); } var xDomain = _chart.x().domain(); if (_chart.isOrdinal()) { // TODO #416 //var domainSet = d3.set(xDomain); return function () { return true; //domainSet.has(p.x); }; } if (_chart.elasticX()) { return function () { return true; }; } return function (p) { //return true; return p.x >= xDomain[0] && p.x <= xDomain[xDomain.length - 1]; }; } /** * Stack a new crossfilter group onto this chart with an optional custom value accessor. All stacks * in the same chart will share the same key accessor and therefore the same set of keys. * * For example, in a stacked bar chart, the bars of each stack will be positioned using the same set * of keys on the x axis, while stacked vertically. If name is specified then it will be used to * generate the legend label. * @name stack * @memberof dc.stackMixin * @instance * @example * // stack group using default accessor * chart.stack(valueSumGroup) * // stack group using custom accessor * .stack(avgByDayGroup, function(d){return d.value.avgByDay;}); * @param {CrossfilterGroup} group * @param {String} [name] * @param {Function} [accessor] * @returns {Chart} */ _chart.stack = function (group, name, accessor) { if (!arguments.length) { return _stack; } if (arguments.length <= 2) { accessor = name; } var layer = {group: group}; if (typeof name === 'string') { layer.name = name; } if (typeof accessor === 'function') { layer.accessor = accessor; } _stack.push(layer); return _chart; }; dc.override(_chart, 'group', function (g, n, f) { if (!arguments.length) { return _chart._group(); } _stack = []; _titles = {}; _chart.stack(g, n); if (f) { _chart.valueAccessor(f); } return _chart._group(g, n); }); /** * Allow named stacks to be hidden or shown by clicking on legend items. * This does not affect the behavior of hideStack or showStack. * @name hidableStacks * @memberof dc.stackMixin * @instance * @param {Boolean} hidableStacks * @returns {Chart} */ _chart.hidableStacks = function (hidableStacks) { if (!arguments.length) { return _hidableStacks; } _hidableStacks = hidableStacks; return _chart; }; function findLayerByName (n) { var i = _stack.map(dc.pluck('name')).indexOf(n); return _stack[i]; } /** * Hide all stacks on the chart with the given name. * The chart must be re-rendered for this change to appear. * @name hideStack * @memberof dc.stackMixin * @instance * @param {String} stackName * @returns {Chart} */ _chart.hideStack = function (stackName) { var layer = findLayerByName(stackName); if (layer) { layer.hidden = true; } return _chart; }; /** * Show all stacks on the chart with the given name. * The chart must be re-rendered for this change to appear. * @name showStack * @memberof dc.stackMixin * @instance * @param {String} stackName * @returns {Chart} */ _chart.showStack = function (stackName) { var layer = findLayerByName(stackName); if (layer) { layer.hidden = false; } return _chart; }; _chart.getValueAccessorByIndex = function (index) { return _stack[index].accessor || _chart.valueAccessor(); }; _chart.yAxisMin = function () { var min = d3.min(flattenStack(), function (p) { return (p.y + p.y0 < p.y0) ? (p.y + p.y0) : p.y0; }); return dc.utils.subtract(min, _chart.yAxisPadding()); }; _chart.yAxisMax = function () { var max = d3.max(flattenStack(), function (p) { return p.y + p.y0; }); return dc.utils.add(max, _chart.yAxisPadding()); }; function flattenStack () { var valueses = _chart.data().map(function (layer) { return layer.values; }); return Array.prototype.concat.apply([], valueses); } _chart.xAxisMin = function () { var min = d3.min(flattenStack(), dc.pluck('x')); return dc.utils.subtract(min, _chart.xAxisPadding()); }; _chart.xAxisMax = function () { var max = d3.max(flattenStack(), dc.pluck('x')); return dc.utils.add(max, _chart.xAxisPadding()); }; /** * Set or get the title function. Chart class will use this function to render svg title (usually interpreted by * browser as tooltips) for each child element in the chart, i.e. a slice in a pie chart or a bubble in a bubble chart. * Almost every chart supports title function however in grid coordinate chart you need to turn off brush in order to * use title otherwise the brush layer will block tooltip trigger. * * If the first argument is a stack name, the title function will get or set the title for that stack. If stackName * is not provided, the first stack is implied. * @name title * @memberof dc.stackMixin * @instance * @example * // set a title function on 'first stack' * chart.title('first stack', function(d) { return d.key + ': ' + d.value; }); * // get a title function from 'second stack' * var secondTitleFunction = chart.title('second stack'); * @param {String} [stackName] * @param {Function} [titleAccessor] * @returns {Chart} */ dc.override(_chart, 'title', function (stackName, titleAccessor) { if (!stackName) { return _chart._title(); } if (typeof stackName === 'function') { return _chart._title(stackName); } if (stackName === _chart._groupName && typeof titleAccessor === 'function') { return _chart._title(titleAccessor); } if (typeof titleAccessor !== 'function') { return _titles[stackName] || _chart._title(); } _titles[stackName] = titleAccessor; return _chart; }); /** * Gets or sets the stack layout algorithm, which computes a baseline for each stack and * propagates it to the next * @name stackLayout * @memberof dc.stackMixin * @instance * @param {Function} [stack=d3.layout.stack] * @returns {Chart} */ _chart.stackLayout = function (stack) { if (!arguments.length) { return _stackLayout; } _stackLayout = stack; return _chart; }; function visability (l) { return !l.hidden; } _chart.data(function () { var layers = _stack.filter(visability); return layers.length ? _chart.stackLayout()(layers) : []; }); _chart._ordinalXDomain = function () { var flat = flattenStack().map(dc.pluck('data')); var ordered = _chart._computeOrderedGroups(flat); return ordered.map(_chart.keyAccessor()); }; _chart.colorAccessor(function (d) { var layer = this.layer || this.name || d.name || d.layer; return layer; }); _chart.legendables = function () { return _stack.map(function (layer, i) { return { chart: _chart, name: layer.name, hidden: layer.hidden || false, color: _chart.getColor.call(layer, layer.values, i) }; }); }; _chart.isLegendableHidden = function (d) { var layer = findLayerByName(d.name); return layer ? layer.hidden : false; }; _chart.legendToggle = function (d) { if (_hidableStacks) { if (_chart.isLegendableHidden(d)) { _chart.showStack(d.name); } else { _chart.hideStack(d.name); } //_chart.redraw(); _chart.renderGroup(); } }; return _chart; }; /** * Cap is a mixin that groups small data elements below a _cap_ into an *others* grouping for both the * Row and Pie Charts. * * The top ordered elements in the group up to the cap amount will be kept in the chart, and the rest * will be replaced with an *others* element, with value equal to the sum of the replaced values. The * keys of the elements below the cap limit are recorded in order to filter by those keys when the * others* element is clicked. * @name capMixin * @memberof dc * @mixin * @param {Chart} _chart * @returns {Chart} */ dc.capMixin = function (_chart) { var _cap = Infinity; var _othersLabel = 'Others'; var _othersGrouper = function (topRows) { var topRowsSum = d3.sum(topRows, _chart.valueAccessor()), allRows = _chart.group().all(), allRowsSum = d3.sum(allRows, _chart.valueAccessor()), topKeys = topRows.map(_chart.keyAccessor()), allKeys = allRows.map(_chart.keyAccessor()), topSet = d3.set(topKeys), others = allKeys.filter(function (d) {return !topSet.has(d);}); if (allRowsSum > topRowsSum) { return topRows.concat([{'others': others, 'key': _othersLabel, 'value': allRowsSum - topRowsSum}]); } return topRows; }; _chart.cappedKeyAccessor = function (d, i) { if (d.others) { return d.key; } return _chart.keyAccessor()(d, i); }; _chart.cappedValueAccessor = function (d, i) { if (d.others) { return d.value; } return _chart.valueAccessor()(d, i); }; _chart.data(function (group) { if (_cap === Infinity) { return _chart._computeOrderedGroups(group.all()); } else { var topRows = group.top(_cap); // ordered by crossfilter group order (default value) topRows = _chart._computeOrderedGroups(topRows); // re-order using ordering (default key) if (_othersGrouper) { return _othersGrouper(topRows); } return topRows; } }); /** * Get or set the count of elements to that will be included in the cap. * @name cap * @memberof dc.capMixin * @instance * @param {Number} [count=Infinity] * @returns {Number} */ _chart.cap = function (count) { if (!arguments.length) { return _cap; } _cap = count; return _chart; }; /** * Get or set the label for *Others* slice when slices cap is specified * @name othersLabel * @memberof dc.capMixin * @instance * @param {String} [label=Others] * @returns {String} */ _chart.othersLabel = function (label) { if (!arguments.length) { return _othersLabel; } _othersLabel = label; return _chart; }; /** * Get or set the grouper function that will perform the insertion of data for the *Others* slice * if the slices cap is specified. If set to a falsy value, no others will be added. By default the * grouper function computes the sum of all values below the cap. * @name othersGrouper * @memberof dc.capMixin * @instance * @example * chart.othersGrouper(function (data) { * // compute the value for others, presumably the sum of all values below the cap * var othersSum = yourComputeOthersValueLogic(data) * * // the keys are needed to properly filter when the others element is clicked * var othersKeys = yourComputeOthersKeysArrayLogic(data); * * // add the others row to the dataset * data.push({'key': 'Others', 'value': othersSum, 'others': othersKeys }); * * return data; * }); * @param {Function} [grouperFunction] * @returns {Function} */ _chart.othersGrouper = function (grouperFunction) { if (!arguments.length) { return _othersGrouper; } _othersGrouper = grouperFunction; return _chart; }; dc.override(_chart, 'onClick', function (d) { if (d.others) { _chart.filter([d.others]); } _chart._onClick(d); }); return _chart; }; /** * This Mixin provides reusable functionalities for any chart that needs to visualize data using bubbles. * @name bubbleMixin * @memberof dc * @mixin * @mixes dc.colorMixin * @param {Chart} _chart * @returns {Chart} */ dc.bubbleMixin = function (_chart) { var _maxBubbleRelativeSize = 0.3; var _minRadiusWithLabel = 10; _chart.BUBBLE_NODE_CLASS = 'node'; _chart.BUBBLE_CLASS = 'bubble'; _chart.MIN_RADIUS = 10; _chart = dc.colorMixin(_chart); _chart.renderLabel(true); _chart.data(function (group) { return group.top(Infinity); }); var _r = d3.scale.linear().domain([0, 100]); var _rValueAccessor = function (d) { return d.r; }; /** * Get or set the bubble radius scale. By default the bubble chart uses * `d3.scale.linear().domain([0, 100])` as its radius scale. * @name r * @memberof dc.bubbleMixin * @instance * @param {Number[]} [bubbleRadiusScale] * @returns {Number[]} */ _chart.r = function (bubbleRadiusScale) { if (!arguments.length) { return _r; } _r = bubbleRadiusScale; return _chart; }; /** * Get or set the radius value accessor function. If set, the radius value accessor function will * be used to retrieve a data value for each bubble. The data retrieved then will be mapped using * the r scale to the actual bubble radius. This allows you to encode a data dimension using bubble * size. * @name radiusValueAccessor * @memberof dc.bubbleMixin * @instance * @param {Function} [radiusValueAccessor] * @returns {Function} */ _chart.radiusValueAccessor = function (radiusValueAccessor) { if (!arguments.length) { return _rValueAccessor; } _rValueAccessor = radiusValueAccessor; return _chart; }; _chart.rMin = function () { var min = d3.min(_chart.data(), function (e) { return _chart.radiusValueAccessor()(e); }); return min; }; _chart.rMax = function () { var max = d3.max(_chart.data(), function (e) { return _chart.radiusValueAccessor()(e); }); return max; }; _chart.bubbleR = function (d) { var value = _chart.radiusValueAccessor()(d); var r = _chart.r()(value); if (isNaN(r) || value <= 0) { r = 0; } return r; }; var labelFunction = function (d) { return _chart.label()(d); }; var labelOpacity = function (d) { return (_chart.bubbleR(d) > _minRadiusWithLabel) ? 1 : 0; }; _chart._doRenderLabel = function (bubbleGEnter) { if (_chart.renderLabel()) { var label = bubbleGEnter.select('text'); if (label.empty()) { label = bubbleGEnter.append('text') .attr('text-anchor', 'middle') .attr('dy', '.3em') .on('click', _chart.onClick); } label .attr('opacity', 0) .text(labelFunction); dc.transition(label, _chart.transitionDuration()) .attr('opacity', labelOpacity); } }; _chart.doUpdateLabels = function (bubbleGEnter) { if (_chart.renderLabel()) { var labels = bubbleGEnter.selectAll('text') .text(labelFunction); dc.transition(labels, _chart.transitionDuration()) .attr('opacity', labelOpacity); } }; var titleFunction = function (d) { return _chart.title()(d); }; _chart._doRenderTitles = function (g) { if (_chart.renderTitle()) { var title = g.select('title'); if (title.empty()) { g.append('title').text(titleFunction); } } }; _chart.doUpdateTitles = function (g) { if (_chart.renderTitle()) { g.selectAll('title').text(titleFunction); } }; /** * Get or set the minimum radius. This will be used to initialize the radius scale's range. * @name minRadius * @memberof dc.bubbleMixin * @instance * @param {Number} [radius=10] * @returns {Number} */ _chart.minRadius = function (radius) { if (!arguments.length) { return _chart.MIN_RADIUS; } _chart.MIN_RADIUS = radius; return _chart; }; /** * Get or set the minimum radius for label rendering. If a bubble's radius is less than this value * then no label will be rendered. * @name minRadiusWithLabel * @memberof dc.bubbleMixin * @instance * @param {Number} [radius=10] * @returns {Number} */ _chart.minRadiusWithLabel = function (radius) { if (!arguments.length) { return _minRadiusWithLabel; } _minRadiusWithLabel = radius; return _chart; }; /** * Get or set the maximum relative size of a bubble to the length of x axis. This value is useful * when the difference in radius between bubbles is too great. * @name maxBubbleRelativeSize * @memberof dc.bubbleMixin * @instance * @param {Number} [relativeSize=0.3] * @returns {Number} */ _chart.maxBubbleRelativeSize = function (relativeSize) { if (!arguments.length) { return _maxBubbleRelativeSize; } _maxBubbleRelativeSize = relativeSize; return _chart; }; _chart.fadeDeselectedArea = function () { if (_chart.hasFilter()) { _chart.selectAll('g.' + _chart.BUBBLE_NODE_CLASS).each(function (d) { if (_chart.isSelectedNode(d)) { _chart.highlightSelected(this); } else { _chart.fadeDeselected(this); } }); } else { _chart.selectAll('g.' + _chart.BUBBLE_NODE_CLASS).each(function () { _chart.resetHighlight(this); }); } }; _chart.isSelectedNode = function (d) { return _chart.hasFilter(d.key); }; _chart.onClick = function (d) { var filter = d.key; dc.events.trigger(function () { _chart.filter(filter); _chart.redrawGroup(); }); }; return _chart; }; /** * The pie chart implementation is usually used to visualize a small categorical distribution. The pie * chart uses keyAccessor to determine the slices, and valueAccessor to calculate the size of each * slice relative to the sum of all values. Slices are ordered by `.ordering` which defaults to sorting * by key. * @name pieChart * @memberof dc * @mixes dc.capMixin * @mixes dc.colorMixin * @mixes dc.baseMixin * @example * // create a pie chart under #chart-container1 element using the default global chart group * var chart1 = dc.pieChart('#chart-container1'); * // create a pie chart under #chart-container2 element using chart group A * var chart2 = dc.pieChart('#chart-container2', 'chartGroupA'); * @param {String|node|d3.selection|dc.compositeChart} parent - Any valid * [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying * a dom block element such as a div; or a dom element or d3 selection. If the bar chart is a sub-chart * in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {PieChart} */ dc.pieChart = function (parent, chartGroup) { var DEFAULT_MIN_ANGLE_FOR_LABEL = 0.5; var _sliceCssClass = 'pie-slice'; var _emptyCssClass = 'empty-chart'; var _emptyTitle = 'empty'; var _radius, _givenRadius, // specified radius, if any _innerRadius = 0, _externalRadiusPadding = 0; var _g; var _cx; var _cy; var _minAngleForLabel = DEFAULT_MIN_ANGLE_FOR_LABEL; var _externalLabelRadius; var _chart = dc.capMixin(dc.colorMixin(dc.baseMixin({}))); _chart.colorAccessor(_chart.cappedKeyAccessor); _chart.title(function (d) { return _chart.cappedKeyAccessor(d) + ': ' + _chart.cappedValueAccessor(d); }); /** * Get or set the maximum number of slices the pie chart will generate. The top slices are determined by * value from high to low. Other slices exeeding the cap will be rolled up into one single *Others* slice. * @name slicesCap * @memberof dc.pieChart * @instance * @param {Number} [cap] * @returns {Chart} */ _chart.slicesCap = _chart.cap; _chart.label(_chart.cappedKeyAccessor); _chart.renderLabel(true); _chart.transitionDuration(350); _chart._doRender = function () { _chart.resetSvg(); _g = _chart.svg() .append('g') .attr('transform', 'translate(' + _chart.cx() + ',' + _chart.cy() + ')'); drawChart(); return _chart; }; function drawChart () { // set radius on basis of chart dimension if missing _radius = _givenRadius ? _givenRadius : d3.min([_chart.width(), _chart.height()]) / 2; var arc = buildArcs(); var pie = pieLayout(); var pieData; // if we have data... if (d3.sum(_chart.data(), _chart.valueAccessor())) { pieData = pie(_chart.data()); _g.classed(_emptyCssClass, false); } else { // otherwise we'd be getting NaNs, so override // note: abuse others for its ignoring the value accessor pieData = pie([{key: _emptyTitle, value: 1, others: [_emptyTitle]}]); _g.classed(_emptyCssClass, true); } if (_g) { var slices = _g.selectAll('g.' + _sliceCssClass) .data(pieData); createElements(slices, arc, pieData); updateElements(pieData, arc); removeElements(slices); highlightFilter(); dc.transition(_g, _chart.transitionDuration()) .attr('transform', 'translate(' + _chart.cx() + ',' + _chart.cy() + ')'); } } function createElements (slices, arc, pieData) { var slicesEnter = createSliceNodes(slices); createSlicePath(slicesEnter, arc); createTitles(slicesEnter); createLabels(pieData, arc); } function createSliceNodes (slices) { var slicesEnter = slices .enter() .append('g') .attr('class', function (d, i) { return _sliceCssClass + ' _' + i; }); return slicesEnter; } function createSlicePath (slicesEnter, arc) { var slicePath = slicesEnter.append('path') .attr('fill', fill) .on('click', onClick) .attr('d', function (d, i) { return safeArc(d, i, arc); }); dc.transition(slicePath, _chart.transitionDuration(), function (s) { s.attrTween('d', tweenPie); }); } function createTitles (slicesEnter) { if (_chart.renderTitle()) { slicesEnter.append('title').text(function (d) { return _chart.title()(d.data); }); } } function positionLabels (labelsEnter, arc) { dc.transition(labelsEnter, _chart.transitionDuration()) .attr('transform', function (d) { return labelPosition(d, arc); }) .attr('text-anchor', 'middle') .text(function (d) { var data = d.data; if ((sliceHasNoData(data) || sliceTooSmall(d)) && !isSelectedSlice(d)) { return ''; } return _chart.label()(d.data); }); } function createLabels (pieData, arc) { if (_chart.renderLabel()) { var labels = _g.selectAll('text.' + _sliceCssClass) .data(pieData); labels.exit().remove(); var labelsEnter = labels .enter() .append('text') .attr('class', function (d, i) { var classes = _sliceCssClass + ' _' + i; if (_externalLabelRadius) { classes += ' external'; } return classes; }) .on('click', onClick); positionLabels(labelsEnter, arc); } } function updateElements (pieData, arc) { updateSlicePaths(pieData, arc); updateLabels(pieData, arc); updateTitles(pieData); } function updateSlicePaths (pieData, arc) { var slicePaths = _g.selectAll('g.' + _sliceCssClass) .data(pieData) .select('path') .attr('d', function (d, i) { return safeArc(d, i, arc); }); dc.transition(slicePaths, _chart.transitionDuration(), function (s) { s.attrTween('d', tweenPie); }).attr('fill', fill); } function updateLabels (pieData, arc) { if (_chart.renderLabel()) { var labels = _g.selectAll('text.' + _sliceCssClass) .data(pieData); positionLabels(labels, arc); } } function updateTitles (pieData) { if (_chart.renderTitle()) { _g.selectAll('g.' + _sliceCssClass) .data(pieData) .select('title') .text(function (d) { return _chart.title()(d.data); }); } } function removeElements (slices) { slices.exit().remove(); } function highlightFilter () { if (_chart.hasFilter()) { _chart.selectAll('g.' + _sliceCssClass).each(function (d) { if (isSelectedSlice(d)) { _chart.highlightSelected(this); } else { _chart.fadeDeselected(this); } }); } else { _chart.selectAll('g.' + _sliceCssClass).each(function () { _chart.resetHighlight(this); }); } } /** * Get or set the external radius padding of the pie chart. This will force the radius of the * pie chart to become smaller or larger depending on the value. * @name externalRadiusPadding * @memberof dc.pieChart * @instance * @param {Number} [externalRadiusPadding=0] * @returns {Chart} */ _chart.externalRadiusPadding = function (externalRadiusPadding) { if (!arguments.length) { return _externalRadiusPadding; } _externalRadiusPadding = externalRadiusPadding; return _chart; }; /** * Get or set the inner radius of the pie chart. If the inner radius is greater than 0px then the * pie chart will be rendered as a doughnut chart. * @name innerRadius * @memberof dc.pieChart * @instance * @param {Number} [innerRadius=0] * @returns {Chart} */ _chart.innerRadius = function (innerRadius) { if (!arguments.length) { return _innerRadius; } _innerRadius = innerRadius; return _chart; }; /** * Get or set the outer radius. If the radius is not set, it will be half of the minimum of the * chart width and height. * @name radius * @memberof dc.pieChart * @instance * @param {Number} [radius] * @returns {Chart} */ _chart.radius = function (radius) { if (!arguments.length) { return _givenRadius; } _givenRadius = radius; return _chart; }; /** * Get or set center x coordinate position. Default is center of svg. * @name cx * @memberof dc.pieChart * @instance * @param {Number} [cx] * @returns {Chart} */ _chart.cx = function (cx) { if (!arguments.length) { return (_cx || _chart.width() / 2); } _cx = cx; return _chart; }; /** * Get or set center y coordinate position. Default is center of svg. * @name cy * @memberof dc.pieChart * @instance * @param {Number} [cy] * @returns {Chart} */ _chart.cy = function (cy) { if (!arguments.length) { return (_cy || _chart.height() / 2); } _cy = cy; return _chart; }; function buildArcs () { return d3.svg.arc().outerRadius(_radius - _externalRadiusPadding).innerRadius(_innerRadius); } function isSelectedSlice (d) { return _chart.hasFilter(_chart.cappedKeyAccessor(d.data)); } _chart._doRedraw = function () { drawChart(); return _chart; }; /** * Get or set the minimal slice angle for label rendering. Any slice with a smaller angle will not * display a slice label. * @name minAngleForLabel * @memberof dc.pieChart * @instance * @param {Number} [minAngleForLabel=0.5] * @returns {Chart} */ _chart.minAngleForLabel = function (minAngleForLabel) { if (!arguments.length) { return _minAngleForLabel; } _minAngleForLabel = minAngleForLabel; return _chart; }; function pieLayout () { return d3.layout.pie().sort(null).value(_chart.cappedValueAccessor); } function sliceTooSmall (d) { var angle = (d.endAngle - d.startAngle); return isNaN(angle) || angle < _minAngleForLabel; } function sliceHasNoData (d) { return _chart.cappedValueAccessor(d) === 0; } function tweenPie (b) { b.innerRadius = _innerRadius; var current = this._current; if (isOffCanvas(current)) { current = {startAngle: 0, endAngle: 0}; } var i = d3.interpolate(current, b); this._current = i(0); return function (t) { return safeArc(i(t), 0, buildArcs()); }; } function isOffCanvas (current) { return !current || isNaN(current.startAngle) || isNaN(current.endAngle); } function fill (d, i) { return _chart.getColor(d.data, i); } function onClick (d, i) { if (_g.attr('class') !== _emptyCssClass) { _chart.onClick(d.data, i); } } function safeArc (d, i, arc) { var path = arc(d, i); if (path.indexOf('NaN') >= 0) { path = 'M0,0'; } return path; } /** * Title to use for the only slice when there is no data. * @name emptyTitle * @memberof dc.pieChart * @instance * @param {String} [title] * @returns {Chart} */ _chart.emptyTitle = function (title) { if (arguments.length === 0) { return _emptyTitle; } _emptyTitle = title; return _chart; }; /** * Position slice labels offset from the outer edge of the chart * * The given argument sets the radial offset. * @name externalLabels * @memberof dc.pieChart * @instance * @param {Number} [radius] * @returns {Chart} */ _chart.externalLabels = function (radius) { if (arguments.length === 0) { return _externalLabelRadius; } else if (radius) { _externalLabelRadius = radius; } else { _externalLabelRadius = undefined; } return _chart; }; function labelPosition (d, arc) { var centroid; if (_externalLabelRadius) { centroid = d3.svg.arc() .outerRadius(_radius - _externalRadiusPadding + _externalLabelRadius) .innerRadius(_radius - _externalRadiusPadding + _externalLabelRadius) .centroid(d); } else { centroid = arc.centroid(d); } if (isNaN(centroid[0]) || isNaN(centroid[1])) { return 'translate(0,0)'; } else { return 'translate(' + centroid + ')'; } } _chart.legendables = function () { return _chart.data().map(function (d, i) { var legendable = {name: d.key, data: d.value, others: d.others, chart: _chart}; legendable.color = _chart.getColor(d, i); return legendable; }); }; _chart.legendHighlight = function (d) { highlightSliceFromLegendable(d, true); }; _chart.legendReset = function (d) { highlightSliceFromLegendable(d, false); }; _chart.legendToggle = function (d) { _chart.onClick({key: d.name, others: d.others}); }; function highlightSliceFromLegendable (legendable, highlighted) { _chart.selectAll('g.pie-slice').each(function (d) { if (legendable.name === d.data.key) { d3.select(this).classed('highlight', highlighted); } }); } return _chart.anchor(parent, chartGroup); }; /** * Concrete bar chart/histogram implementation. * Examples: * - [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) * - [Canadian City Crime Stats](http://dc-js.github.com/dc.js/crime/index.html) * @name barChart * @memberof dc * @mixes dc.stackMixin * @mixes dc.coordinateGridMixin * @example * // create a bar chart under #chart-container1 element using the default global chart group * var chart1 = dc.barChart('#chart-container1'); * // create a bar chart under #chart-container2 element using chart group A * var chart2 = dc.barChart('#chart-container2', 'chartGroupA'); * // create a sub-chart under a composite parent chart * var chart3 = dc.barChart(compositeChart); * @param {String|node|d3.selection|dc.compositeChart} parent - Any valid * [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying * a dom block element such as a div; or a dom element or d3 selection. If the bar chart is a sub-chart * in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {BarChart} */ dc.barChart = function (parent, chartGroup) { var MIN_BAR_WIDTH = 1; var DEFAULT_GAP_BETWEEN_BARS = 2; var _chart = dc.stackMixin(dc.coordinateGridMixin({})); var _gap = DEFAULT_GAP_BETWEEN_BARS; var _centerBar = false; var _alwaysUseRounding = false; var _barWidth; dc.override(_chart, 'rescale', function () { _chart._rescale(); _barWidth = undefined; return _chart; }); dc.override(_chart, 'render', function () { if (_chart.round() && _centerBar && !_alwaysUseRounding) { dc.logger.warn('By default, brush rounding is disabled if bars are centered. ' + 'See dc.js bar chart API documentation for details.'); } return _chart._render(); }); _chart.plotData = function () { var layers = _chart.chartBodyG().selectAll('g.stack') .data(_chart.data()); calculateBarWidth(); layers .enter() .append('g') .attr('class', function (d, i) { return 'stack ' + '_' + i; }); layers.each(function (d, i) { var layer = d3.select(this); renderBars(layer, i, d); }); }; function barHeight (d) { return dc.utils.safeNumber(Math.abs(_chart.y()(d.y + d.y0) - _chart.y()(d.y0))); } function renderBars (layer, layerIndex, d) { var bars = layer.selectAll('rect.bar') .data(d.values, dc.pluck('x')); var enter = bars.enter() .append('rect') .attr('class', 'bar') .attr('fill', dc.pluck('data', _chart.getColor)) .attr('y', _chart.yAxisHeight()) .attr('height', 0); if (_chart.renderTitle()) { enter.append('title').text(dc.pluck('data', _chart.title(d.name))); } if (_chart.isOrdinal()) { bars.on('click', _chart.onClick); } dc.transition(bars, _chart.transitionDuration()) .attr('x', function (d) { var x = _chart.x()(d.x); if (_centerBar) { x -= _barWidth / 2; } if (_chart.isOrdinal() && _gap !== undefined) { x += _gap / 2; } return dc.utils.safeNumber(x); }) .attr('y', function (d) { var y = _chart.y()(d.y + d.y0); if (d.y < 0) { y -= barHeight(d); } return dc.utils.safeNumber(y); }) .attr('width', _barWidth) .attr('height', function (d) { return barHeight(d); }) .attr('fill', dc.pluck('data', _chart.getColor)) .select('title').text(dc.pluck('data', _chart.title(d.name))); dc.transition(bars.exit(), _chart.transitionDuration()) .attr('height', 0) .remove(); } function calculateBarWidth () { if (_barWidth === undefined) { var numberOfBars = _chart.xUnitCount(); // please can't we always use rangeBands for bar charts? if (_chart.isOrdinal() && _gap === undefined) { _barWidth = Math.floor(_chart.x().rangeBand()); } else if (_gap) { _barWidth = Math.floor((_chart.xAxisLength() - (numberOfBars - 1) * _gap) / numberOfBars); } else { _barWidth = Math.floor(_chart.xAxisLength() / (1 + _chart.barPadding()) / numberOfBars); } if (_barWidth === Infinity || isNaN(_barWidth) || _barWidth < MIN_BAR_WIDTH) { _barWidth = MIN_BAR_WIDTH; } } } _chart.fadeDeselectedArea = function () { var bars = _chart.chartBodyG().selectAll('rect.bar'); var extent = _chart.brush().extent(); if (_chart.isOrdinal()) { if (_chart.hasFilter()) { bars.classed(dc.constants.SELECTED_CLASS, function (d) { return _chart.hasFilter(d.x); }); bars.classed(dc.constants.DESELECTED_CLASS, function (d) { return !_chart.hasFilter(d.x); }); } else { bars.classed(dc.constants.SELECTED_CLASS, false); bars.classed(dc.constants.DESELECTED_CLASS, false); } } else { if (!_chart.brushIsEmpty(extent)) { var start = extent[0]; var end = extent[1]; bars.classed(dc.constants.DESELECTED_CLASS, function (d) { return d.x < start || d.x >= end; }); } else { bars.classed(dc.constants.DESELECTED_CLASS, false); } } }; /** * Whether the bar chart will render each bar centered around the data position on x axis * @name centerBar * @memberof dc.barChart * @instance * @param {Boolean} [centerBar=false] * @returns {Boolean} */ _chart.centerBar = function (centerBar) { if (!arguments.length) { return _centerBar; } _centerBar = centerBar; return _chart; }; dc.override(_chart, 'onClick', function (d) { _chart._onClick(d.data); }); /** * Get or set the spacing between bars as a fraction of bar size. Valid values are between 0-1. * Setting this value will also remove any previously set `gap`. See the * [d3 docs](https://github.com/mbostock/d3/wiki/Ordinal-Scales#wiki-ordinal_rangeBands) * for a visual description of how the padding is applied. * @name barPadding * @memberof dc.barChart * @instance * @param {Number} [barPadding] * @returns {Number} */ _chart.barPadding = function (barPadding) { if (!arguments.length) { return _chart._rangeBandPadding(); } _chart._rangeBandPadding(barPadding); _gap = undefined; return _chart; }; _chart._useOuterPadding = function () { return _gap === undefined; }; /** * Get or set the outer padding on an ordinal bar chart. This setting has no effect on non-ordinal charts. * Will pad the width by `padding * barWidth` on each side of the chart. * @name outerPadding * @memberof dc.barChart * @instance * @param {Number} [padding=0.5] * @returns {Number} */ _chart.outerPadding = _chart._outerRangeBandPadding; /** * Manually set fixed gap (in px) between bars instead of relying on the default auto-generated * gap. By default the bar chart implementation will calculate and set the gap automatically * based on the number of data points and the length of the x axis. * @name gap * @memberof dc.barChart * @instance * @param {Number} [gap=2] * @returns {Number} */ _chart.gap = function (gap) { if (!arguments.length) { return _gap; } _gap = gap; return _chart; }; _chart.extendBrush = function () { var extent = _chart.brush().extent(); if (_chart.round() && (!_centerBar || _alwaysUseRounding)) { extent[0] = extent.map(_chart.round())[0]; extent[1] = extent.map(_chart.round())[1]; _chart.chartBodyG().select('.brush') .call(_chart.brush().extent(extent)); } return extent; }; /** * Set or get whether rounding is enabled when bars are centered. Default: false. If false, using * rounding with centered bars will result in a warning and rounding will be ignored. This flag * has no effect if bars are not centered. * When using standard d3.js rounding methods, the brush often doesn't align correctly with * centered bars since the bars are offset. The rounding function must add an offset to * compensate, such as in the following example. * @name alwaysUseRounding * @memberof dc.barChart * @instance * @example * chart.round(function(n) {return Math.floor(n)+0.5}); * @param {Boolean} [alwaysUseRounding=false] * @returns {Boolean} */ _chart.alwaysUseRounding = function (alwaysUseRounding) { if (!arguments.length) { return _alwaysUseRounding; } _alwaysUseRounding = alwaysUseRounding; return _chart; }; function colorFilter (color, inv) { return function () { var item = d3.select(this); var match = item.attr('fill') === color; return inv ? !match : match; }; } _chart.legendHighlight = function (d) { if (!_chart.isLegendableHidden(d)) { _chart.g().selectAll('rect.bar') .classed('highlight', colorFilter(d.color)) .classed('fadeout', colorFilter(d.color, true)); } }; _chart.legendReset = function () { _chart.g().selectAll('rect.bar') .classed('highlight', false) .classed('fadeout', false); }; dc.override(_chart, 'xAxisMax', function () { var max = this._xAxisMax(); if ('resolution' in _chart.xUnits()) { var res = _chart.xUnits().resolution; max += res; } return max; }); return _chart.anchor(parent, chartGroup); }; /** * Concrete line/area chart implementation. * Examples: * - [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) * - [Canadian City Crime Stats](http://dc-js.github.com/dc.js/crime/index.html) * @name lineChart * @memberof dc * @mixes dc.stackMixin * @mixes dc.coordinateGridMixin * @example * // create a line chart under #chart-container1 element using the default global chart group * var chart1 = dc.lineChart('#chart-container1'); * // create a line chart under #chart-container2 element using chart group A * var chart2 = dc.lineChart('#chart-container2', 'chartGroupA'); * // create a sub-chart under a composite parent chart * var chart3 = dc.lineChart(compositeChart); * @param {String|node|d3.selection|dc.compositeChart} parent - Any valid * [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying * a dom block element such as a div; or a dom element or d3 selection. If the bar chart is a sub-chart * in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {LineChart} */ dc.lineChart = function (parent, chartGroup) { var DEFAULT_DOT_RADIUS = 5; var TOOLTIP_G_CLASS = 'dc-tooltip'; var DOT_CIRCLE_CLASS = 'dot'; var Y_AXIS_REF_LINE_CLASS = 'yRef'; var X_AXIS_REF_LINE_CLASS = 'xRef'; var DEFAULT_DOT_OPACITY = 1e-6; var _chart = dc.stackMixin(dc.coordinateGridMixin({})); var _renderArea = false; var _dotRadius = DEFAULT_DOT_RADIUS; var _dataPointRadius = null; var _dataPointFillOpacity = DEFAULT_DOT_OPACITY; var _dataPointStrokeOpacity = DEFAULT_DOT_OPACITY; var _interpolate = 'linear'; var _tension = 0.7; var _defined; var _dashStyle; var _xyTipsOn = true; _chart.transitionDuration(500); _chart._rangeBandPadding(1); _chart.plotData = function () { var chartBody = _chart.chartBodyG(); var layersList = chartBody.selectAll('g.stack-list'); if (layersList.empty()) { layersList = chartBody.append('g').attr('class', 'stack-list'); } var layers = layersList.selectAll('g.stack').data(_chart.data()); var layersEnter = layers .enter() .append('g') .attr('class', function (d, i) { return 'stack ' + '_' + i; }); drawLine(layersEnter, layers); drawArea(layersEnter, layers); drawDots(chartBody, layers); }; /** * Gets or sets the interpolator to use for lines drawn, by string name, allowing e.g. step * functions, splines, and cubic interpolation. This is passed to * [d3.svg.line.interpolate](https://github.com/mbostock/d3/wiki/SVG-Shapes#line_interpolate) and * [d3.svg.area.interpolate](https://github.com/mbostock/d3/wiki/SVG-Shapes#area_interpolate), * where you can find a complete list of valid arguments * @name interpolate * @memberof dc.lineChart * @instance * @param {String} [interpolate='linear'] * @returns {Chart} */ _chart.interpolate = function (interpolate) { if (!arguments.length) { return _interpolate; } _interpolate = interpolate; return _chart; }; /** * Gets or sets the tension to use for lines drawn, in the range 0 to 1. * This parameter further customizes the interpolation behavior. It is passed to * [d3.svg.line.tension](https://github.com/mbostock/d3/wiki/SVG-Shapes#line_tension) and * [d3.svg.area.tension](https://github.com/mbostock/d3/wiki/SVG-Shapes#area_tension). * @name tension * @memberof dc.lineChart * @instance * @param {Number} [tension=0.7] * @returns {Chart} */ _chart.tension = function (tension) { if (!arguments.length) { return _tension; } _tension = tension; return _chart; }; /** * Gets or sets a function that will determine discontinuities in the line which should be * skipped: the path will be broken into separate subpaths if some points are undefined. * This function is passed to * [d3.svg.line.defined](https://github.com/mbostock/d3/wiki/SVG-Shapes#line_defined) * * Note: crossfilter will sometimes coerce nulls to 0, so you may need to carefully write * custom reduce functions to get this to work, depending on your data. See * https://github.com/dc-js/dc.js/issues/615#issuecomment-49089248 * @name defined * @memberof dc.lineChart * @instance * @param {Function} [defined] * @returns {Chart} */ _chart.defined = function (defined) { if (!arguments.length) { return _defined; } _defined = defined; return _chart; }; /** * Set the line's d3 dashstyle. This value becomes the 'stroke-dasharray' of line. Defaults to empty * array (solid line). * @name dashStyle * @memberof dc.lineChart * @instance * @example * // create a Dash Dot Dot Dot * chart.dashStyle([3,1,1,1]); * @param {Array<Number>} [dashStyle=[]] * @returns {Chart} */ _chart.dashStyle = function (dashStyle) { if (!arguments.length) { return _dashStyle; } _dashStyle = dashStyle; return _chart; }; /** * Get or set render area flag. If the flag is set to true then the chart will render the area * beneath each line and the line chart effectively becomes an area chart. * @name renderArea * @memberof dc.lineChart * @instance * @param {Boolean} [renderArea=false] * @returns {Chart} */ _chart.renderArea = function (renderArea) { if (!arguments.length) { return _renderArea; } _renderArea = renderArea; return _chart; }; function colors (d, i) { return _chart.getColor.call(d, d.values, i); } function drawLine (layersEnter, layers) { var line = d3.svg.line() .x(function (d) { return _chart.x()(d.x); }) .y(function (d) { return _chart.y()(d.y + d.y0); }) .interpolate(_interpolate) .tension(_tension); if (_defined) { line.defined(_defined); } var path = layersEnter.append('path') .attr('class', 'line') .attr('stroke', colors); if (_dashStyle) { path.attr('stroke-dasharray', _dashStyle); } dc.transition(layers.select('path.line'), _chart.transitionDuration()) //.ease('linear') .attr('stroke', colors) .attr('d', function (d) { return safeD(line(d.values)); }); } function drawArea (layersEnter, layers) { if (_renderArea) { var area = d3.svg.area() .x(function (d) { return _chart.x()(d.x); }) .y(function (d) { return _chart.y()(d.y + d.y0); }) .y0(function (d) { return _chart.y()(d.y0); }) .interpolate(_interpolate) .tension(_tension); if (_defined) { area.defined(_defined); } layersEnter.append('path') .attr('class', 'area') .attr('fill', colors) .attr('d', function (d) { return safeD(area(d.values)); }); dc.transition(layers.select('path.area'), _chart.transitionDuration()) //.ease('linear') .attr('fill', colors) .attr('d', function (d) { return safeD(area(d.values)); }); } } function safeD (d) { return (!d || d.indexOf('NaN') >= 0) ? 'M0,0' : d; } function drawDots (chartBody, layers) { if (!_chart.brushOn() && _chart.xyTipsOn()) { var tooltipListClass = TOOLTIP_G_CLASS + '-list'; var tooltips = chartBody.select('g.' + tooltipListClass); if (tooltips.empty()) { tooltips = chartBody.append('g').attr('class', tooltipListClass); } layers.each(function (d, layerIndex) { var points = d.values; if (_defined) { points = points.filter(_defined); } var g = tooltips.select('g.' + TOOLTIP_G_CLASS + '._' + layerIndex); if (g.empty()) { g = tooltips.append('g').attr('class', TOOLTIP_G_CLASS + ' _' + layerIndex); } createRefLines(g); var dots = g.selectAll('circle.' + DOT_CIRCLE_CLASS) .data(points, dc.pluck('x')); dots.enter() .append('circle') .attr('class', DOT_CIRCLE_CLASS) .attr('r', getDotRadius()) .style('fill-opacity', _dataPointFillOpacity) .style('stroke-opacity', _dataPointStrokeOpacity) .on('mousemove', function () { var dot = d3.select(this); showDot(dot); showRefLines(dot, g); }) .on('mouseout', function () { var dot = d3.select(this); hideDot(dot); hideRefLines(g); }); dots .attr('cx', function (d) { return dc.utils.safeNumber(_chart.x()(d.x)); }) .attr('cy', function (d) { return dc.utils.safeNumber(_chart.y()(d.y + d.y0)); }) .attr('fill', _chart.getColor) .call(renderTitle, d); dots.exit().remove(); }); } } function createRefLines (g) { var yRefLine = g.select('path.' + Y_AXIS_REF_LINE_CLASS).empty() ? g.append('path').attr('class', Y_AXIS_REF_LINE_CLASS) : g.select('path.' + Y_AXIS_REF_LINE_CLASS); yRefLine.style('display', 'none').attr('stroke-dasharray', '5,5'); var xRefLine = g.select('path.' + X_AXIS_REF_LINE_CLASS).empty() ? g.append('path').attr('class', X_AXIS_REF_LINE_CLASS) : g.select('path.' + X_AXIS_REF_LINE_CLASS); xRefLine.style('display', 'none').attr('stroke-dasharray', '5,5'); } function showDot (dot) { dot.style('fill-opacity', 0.8); dot.style('stroke-opacity', 0.8); dot.attr('r', _dotRadius); return dot; } function showRefLines (dot, g) { var x = dot.attr('cx'); var y = dot.attr('cy'); var yAxisX = (_chart._yAxisX() - _chart.margins().left); var yAxisRefPathD = 'M' + yAxisX + ' ' + y + 'L' + (x) + ' ' + (y); var xAxisRefPathD = 'M' + x + ' ' + _chart.yAxisHeight() + 'L' + x + ' ' + y; g.select('path.' + Y_AXIS_REF_LINE_CLASS).style('display', '').attr('d', yAxisRefPathD); g.select('path.' + X_AXIS_REF_LINE_CLASS).style('display', '').attr('d', xAxisRefPathD); } function getDotRadius () { return _dataPointRadius || _dotRadius; } function hideDot (dot) { dot.style('fill-opacity', _dataPointFillOpacity) .style('stroke-opacity', _dataPointStrokeOpacity) .attr('r', getDotRadius()); } function hideRefLines (g) { g.select('path.' + Y_AXIS_REF_LINE_CLASS).style('display', 'none'); g.select('path.' + X_AXIS_REF_LINE_CLASS).style('display', 'none'); } function renderTitle (dot, d) { if (_chart.renderTitle()) { dot.selectAll('title').remove(); dot.append('title').text(dc.pluck('data', _chart.title(d.name))); } } /** * Turn on/off the mouseover behavior of an individual data point which renders a circle and x/y axis * dashed lines back to each respective axis. This is ignored if the chart brush is on (`brushOn`) * @name xyTipsOn * @memberof dc.lineChart * @instance * @param {Boolean} [xyTipsOn=false] * @returns {Chart} */ _chart.xyTipsOn = function (xyTipsOn) { if (!arguments.length) { return _xyTipsOn; } _xyTipsOn = xyTipsOn; return _chart; }; /** * Get or set the radius (in px) for dots displayed on the data points. * @name dotRadius * @memberof dc.lineChart * @instance * @param {Number} [dotRadius=5] * @returns {Chart} */ _chart.dotRadius = function (dotRadius) { if (!arguments.length) { return _dotRadius; } _dotRadius = dotRadius; return _chart; }; /** * Always show individual dots for each datapoint. * If `options` is falsy, it disables data point rendering. * * If no `options` are provided, the current `options` values are instead returned. * @name renderDataPoints * @memberof dc.lineChart * @instance * @example * chart.renderDataPoints({radius: 2, fillOpacity: 0.8, strokeOpacity: 0.8}) * @param {{fillOpacity: Number, strokeOpacity: Number, radius: Number}} [options={fillOpacity: 0.8, strokeOpacity: 0.8, radius: 2}] * @returns {Chart} */ _chart.renderDataPoints = function (options) { if (!arguments.length) { return { fillOpacity: _dataPointFillOpacity, strokeOpacity: _dataPointStrokeOpacity, radius: _dataPointRadius }; } else if (!options) { _dataPointFillOpacity = DEFAULT_DOT_OPACITY; _dataPointStrokeOpacity = DEFAULT_DOT_OPACITY; _dataPointRadius = null; } else { _dataPointFillOpacity = options.fillOpacity || 0.8; _dataPointStrokeOpacity = options.strokeOpacity || 0.8; _dataPointRadius = options.radius || 2; } return _chart; }; function colorFilter (color, dashstyle, inv) { return function () { var item = d3.select(this); var match = (item.attr('stroke') === color && item.attr('stroke-dasharray') === ((dashstyle instanceof Array) ? dashstyle.join(',') : null)) || item.attr('fill') === color; return inv ? !match : match; }; } _chart.legendHighlight = function (d) { if (!_chart.isLegendableHidden(d)) { _chart.g().selectAll('path.line, path.area') .classed('highlight', colorFilter(d.color, d.dashstyle)) .classed('fadeout', colorFilter(d.color, d.dashstyle, true)); } }; _chart.legendReset = function () { _chart.g().selectAll('path.line, path.area') .classed('highlight', false) .classed('fadeout', false); }; dc.override(_chart, 'legendables', function () { var legendables = _chart._legendables(); if (!_dashStyle) { return legendables; } return legendables.map(function (l) { l.dashstyle = _dashStyle; return l; }); }); return _chart.anchor(parent, chartGroup); }; /** * The data count widget is a simple widget designed to display the number of records selected by the * current filters out of the total number of records in the data set. Once created the data count widget * will automatically update the text content of the following elements under the parent element. * * '.total-count' - total number of records * '.filter-count' - number of records matched by the current filters * * Examples: * - [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) * @name dataCount * @memberof dc * @mixes dc.baseMixin * @example * var ndx = crossfilter(data); * var all = ndx.groupAll(); * * dc.dataCount('.dc-data-count') * .dimension(ndx) * .group(all); * @param {String|node|d3.selection|dc.compositeChart} parent - Any valid * [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying * a dom block element such as a div; or a dom element or d3 selection. If the bar chart is a sub-chart * in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {DataCount} */ dc.dataCount = function (parent, chartGroup) { var _formatNumber = d3.format(',d'); var _chart = dc.baseMixin({}); var _html = {some: '', all: ''}; /** * Gets or sets an optional object specifying HTML templates to use depending how many items are * selected. The text `%total-count` will replaced with the total number of records, and the text * `%filter-count` will be replaced with the number of selected records. * - all: HTML template to use if all items are selected * - some: HTML template to use if not all items are selected * @name html * @memberof dc.dataCount * @instance * @example * counter.html({ * some: '%filter-count out of %total-count records selected', * all: 'All records selected. Click on charts to apply filters' * }) * @param {{some:String, all: String}} [options] * @returns {Chart} */ _chart.html = function (options) { if (!arguments.length) { return _html; } if (options.all) { _html.all = options.all; } if (options.some) { _html.some = options.some; } return _chart; }; /** * Gets or sets an optional function to format the filter count and total count. * @name formatNumber * @memberof dc.dataCount * @instance * @example * counter.formatNumber(d3.format('.2g')) * @param {Function} [formatter=d3.format('.2g')] * @returns {Chart} */ _chart.formatNumber = function (formatter) { if (!arguments.length) { return _formatNumber; } _formatNumber = formatter; return _chart; }; _chart._doRender = function () { var tot = _chart.dimension().size(), val = _chart.group().value(); var all = _formatNumber(tot); var selected = _formatNumber(val); if ((tot === val) && (_html.all !== '')) { _chart.root().html(_html.all.replace('%total-count', all).replace('%filter-count', selected)); } else if (_html.some !== '') { _chart.root().html(_html.some.replace('%total-count', all).replace('%filter-count', selected)); } else { _chart.selectAll('.total-count').text(all); _chart.selectAll('.filter-count').text(selected); } return _chart; }; _chart._doRedraw = function () { return _chart._doRender(); }; return _chart.anchor(parent, chartGroup); }; /** * The data table is a simple widget designed to list crossfilter focused data set (rows being * filtered) in a good old tabular fashion. * * Note: Unlike other charts, the data table (and data grid chart) use the group attribute as a keying function * for [nesting](https://github.com/mbostock/d3/wiki/Arrays#-nest) the data together in groups. * Do not pass in a crossfilter group as this will not work. * * Examples: * - [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) * @name dataTable * @memberof dc * @mixes dc.baseMixin * @param {String|node|d3.selection|dc.compositeChart} parent - Any valid * [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying * a dom block element such as a div; or a dom element or d3 selection. If the bar chart is a sub-chart * in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {DataTable} */ dc.dataTable = function (parent, chartGroup) { var LABEL_CSS_CLASS = 'dc-table-label'; var ROW_CSS_CLASS = 'dc-table-row'; var COLUMN_CSS_CLASS = 'dc-table-column'; var GROUP_CSS_CLASS = 'dc-table-group'; var HEAD_CSS_CLASS = 'dc-table-head'; var _chart = dc.baseMixin({}); var _size = 25; var _columns = []; var _sortBy = function (d) { return d; }; var _order = d3.ascending; var _showGroups = true; _chart._doRender = function () { _chart.selectAll('tbody').remove(); renderRows(renderGroups()); return _chart; }; _chart._doColumnValueFormat = function (v, d) { return ((typeof v === 'function') ? v(d) : // v as function ((typeof v === 'string') ? d[v] : // v is field name string v.format(d) // v is Object, use fn (element 2) ) ); }; _chart._doColumnHeaderFormat = function (d) { // if 'function', convert to string representation // show a string capitalized // if an object then display it's label string as-is. return (typeof d === 'function') ? _chart._doColumnHeaderFnToString(d) : ((typeof d === 'string') ? _chart._doColumnHeaderCapitalize(d) : String(d.label)); }; _chart._doColumnHeaderCapitalize = function (s) { // capitalize return s.charAt(0).toUpperCase() + s.slice(1); }; _chart._doColumnHeaderFnToString = function (f) { // columnString(f) { var s = String(f); var i1 = s.indexOf('return '); if (i1 >= 0) { var i2 = s.lastIndexOf(';'); if (i2 >= 0) { s = s.substring(i1 + 7, i2); var i3 = s.indexOf('numberFormat'); if (i3 >= 0) { s = s.replace('numberFormat', ''); } } } return s; }; function renderGroups () { // The 'original' example uses all 'functions'. // If all 'functions' are used, then don't remove/add a header, and leave // the html alone. This preserves the functionality of earlier releases. // A 2nd option is a string representing a field in the data. // A third option is to supply an Object such as an array of 'information', and // supply your own _doColumnHeaderFormat and _doColumnValueFormat functions to // create what you need. var bAllFunctions = true; _columns.forEach(function (f) { bAllFunctions = bAllFunctions & (typeof f === 'function'); }); if (!bAllFunctions) { _chart.selectAll('th').remove(); var headcols = _chart.root().selectAll('th') .data(_columns); var headGroup = headcols .enter() .append('th'); headGroup .attr('class', HEAD_CSS_CLASS) .html(function (d) { return (_chart._doColumnHeaderFormat(d)); }); } var groups = _chart.root().selectAll('tbody') .data(nestEntries(), function (d) { return _chart.keyAccessor()(d); }); var rowGroup = groups .enter() .append('tbody'); if (_showGroups === true) { rowGroup .append('tr') .attr('class', GROUP_CSS_CLASS) .append('td') .attr('class', LABEL_CSS_CLASS) .attr('colspan', _columns.length) .html(function (d) { return _chart.keyAccessor()(d); }); } groups.exit().remove(); return rowGroup; } function nestEntries () { var entries; if (_order === d3.ascending) { entries = _chart.dimension().bottom(_size); } else { entries = _chart.dimension().top(_size); } return d3.nest() .key(_chart.group()) .sortKeys(_order) .entries(entries.sort(function (a, b) { return _order(_sortBy(a), _sortBy(b)); })); } function renderRows (groups) { var rows = groups.order() .selectAll('tr.' + ROW_CSS_CLASS) .data(function (d) { return d.values; }); var rowEnter = rows.enter() .append('tr') .attr('class', ROW_CSS_CLASS); _columns.forEach(function (v, i) { rowEnter.append('td') .attr('class', COLUMN_CSS_CLASS + ' _' + i) .html(function (d) { return _chart._doColumnValueFormat(v, d); }); }); rows.exit().remove(); return rows; } _chart._doRedraw = function () { return _chart._doRender(); }; /** * Get or set the table size which determines the number of rows displayed by the widget. * @name size * @memberof dc.dataTable * @instance * @param {Number} [size=25] * @returns {Chart} */ _chart.size = function (size) { if (!arguments.length) { return _size; } _size = size; return _chart; }; /** * Get or set column functions. The data table widget now supports several methods of specifying * the columns to display. The original method, first shown below, uses an array of functions to * generate dynamic columns. Column functions are simple javascript functions with only one input * argument `d` which represents a row in the data set. The return value of these functions will be * used directly to generate table content for each cell. However, this method requires the .html * table entry to have a fixed set of column headers. * * The second example shows you can simply list the data (d) content directly without * specifying it as a function, except where necessary (ie, computed columns). Note * the data element accessor name is capitalized when displayed in the table. You can * also mix in functions as desired or necessary, but you must use the * Object = [Label, Fn] method as shown below. * You may wish to override the following two functions, which are internally used to * translate the column information or function into a displayed header. The first one * is used on the simple "string" column specifier, the second is used to transform the * String(fn) into something displayable. For the Stock example, the function for Change * becomes a header of 'd.close - d.open'. * _chart._doColumnHeaderCapitalize _chart._doColumnHeaderFnToString * You may use your own Object definition, however you must then override * _chart._doColumnHeaderFormat , _chart._doColumnValueFormat * Be aware that fields without numberFormat specification will be displayed just as * they are stored in the data, unformatted. * * The third example, where all fields are specified using the Object = [Label, Fn] method. * @name columns * @memberof dc.dataTable * @instance * @example * chart.columns([ * function(d) { return d.date; }, * function(d) { return d.open; }, * function(d) { return d.close; }, * function(d) { return numberFormat(d.close - d.open); }, * function(d) { return d.volume; } * ]); * @example * chart.columns([ * "date", // d["date"], ie, a field accessor; capitalized automatically * "open", // ... * "close", // ... * ["Change", // Specify an Object = [Label, Fn] * function (d) { return numberFormat(d.close - d.open); }], * "volume" // d["volume"], ie, a field accessor; capitalized automatically * ]); * @example * chart.columns([ * ["Date", // Specify an Object = [Label, Fn] * function (d) { return d.date; }], * ["Open", * function (d) { return numberFormat(d.open); }], * ["Close", * function (d) { return numberFormat(d.close); }], * ["Change", * function (d) { return numberFormat(d.close - d.open); }], * ["Volume", * function (d) { return d.volume; }] * ]); * @param {Array<Function>} [columns=[]] * @returns {Chart} */ _chart.columns = function (columns) { if (!arguments.length) { return _columns; } _columns = columns; return _chart; }; /** * Get or set sort-by function. This function works as a value accessor at row level and returns a * particular field to be sorted by. Default value: identity function * @name sortBy * @memberof dc.dataTable * @instance * @example * chart.sortBy(function(d) { * return d.date; * }); * @param {Function} [sortBy] * @returns {Chart} */ _chart.sortBy = function (sortBy) { if (!arguments.length) { return _sortBy; } _sortBy = sortBy; return _chart; }; /** * Get or set sort order. * @name order * @memberof dc.dataTable * @instance * @example * chart.order(d3.descending); * @param {Function} [order=d3.ascending] * @returns {Chart} */ _chart.order = function (order) { if (!arguments.length) { return _order; } _order = order; return _chart; }; /** * Get or set if group rows will be shown. * * The .group() getter-setter must be provided in either case. * @name order * @memberof dc.dataTable * @instance * @example * chart * .group([value], [name]) * .showGroups(true|false); * @param {Boolean} [showGroups=true] * @returns {Chart} */ _chart.showGroups = function (showGroups) { if (!arguments.length) { return _showGroups; } _showGroups = showGroups; return _chart; }; return _chart.anchor(parent, chartGroup); }; /** * Data grid is a simple widget designed to list the filtered records, providing * a simple way to define how the items are displayed. * * Note: Unlike other charts, the data grid chart (and data table) use the group attribute as a keying function * for [nesting](https://github.com/mbostock/d3/wiki/Arrays#-nest) the data together in groups. * Do not pass in a crossfilter group as this will not work. * * Examples: * - [List of members of the european parliament](http://europarl.me/dc.js/web/ep/index.html) * @name dataGrid * @memberof dc * @mixes dc.baseMixin * @param {String|node|d3.selection|dc.compositeChart} parent - Any valid * [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying * a dom block element such as a div; or a dom element or d3 selection. If the bar chart is a sub-chart * in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {DataGrid} */ dc.dataGrid = function (parent, chartGroup) { var LABEL_CSS_CLASS = 'dc-grid-label'; var ITEM_CSS_CLASS = 'dc-grid-item'; var GROUP_CSS_CLASS = 'dc-grid-group'; var GRID_CSS_CLASS = 'dc-grid-top'; var _chart = dc.baseMixin({}); var _size = 999; // shouldn't be needed, but you might var _html = function (d) { return 'you need to provide an html() handling param: ' + JSON.stringify(d); }; var _sortBy = function (d) { return d; }; var _order = d3.ascending; var _beginSlice = 0, _endSlice; var _htmlGroup = function (d) { return '<div class=\'' + GROUP_CSS_CLASS + '\'><h1 class=\'' + LABEL_CSS_CLASS + '\'>' + _chart.keyAccessor()(d) + '</h1></div>'; }; _chart._doRender = function () { _chart.selectAll('div.' + GRID_CSS_CLASS).remove(); renderItems(renderGroups()); return _chart; }; function renderGroups () { var groups = _chart.root().selectAll('div.' + GRID_CSS_CLASS) .data(nestEntries(), function (d) { return _chart.keyAccessor()(d); }); var itemGroup = groups .enter() .append('div') .attr('class', GRID_CSS_CLASS); if (_htmlGroup) { itemGroup .html(function (d) { return _htmlGroup(d); }); } groups.exit().remove(); return itemGroup; } function nestEntries () { var entries = _chart.dimension().top(_size); return d3.nest() .key(_chart.group()) .sortKeys(_order) .entries(entries.sort(function (a, b) { return _order(_sortBy(a), _sortBy(b)); }).slice(_beginSlice, _endSlice)); } function renderItems (groups) { var items = groups.order() .selectAll('div.' + ITEM_CSS_CLASS) .data(function (d) { return d.values; }); items.enter() .append('div') .attr('class', ITEM_CSS_CLASS) .html(function (d) { return _html(d); }); items.exit().remove(); return items; } _chart._doRedraw = function () { return _chart._doRender(); }; /** * Get or set the index of the beginning slice which determines which entries get displayed by the widget * Useful when implementing pagination. * @name beginSlice * @memberof dc.dataGrid * @instance * @param {Number} [beginSlice=0] * @returns {Chart} */ _chart.beginSlice = function (beginSlice) { if (!arguments.length) { return _beginSlice; } _beginSlice = beginSlice; return _chart; }; /** * Get or set the index of the end slice which determines which entries get displayed by the widget * Useful when implementing pagination. * @name endSlice * @memberof dc.dataGrid * @instance * @param {Number} [endSlice] * @returns {Chart} */ _chart.endSlice = function (endSlice) { if (!arguments.length) { return _endSlice; } _endSlice = endSlice; return _chart; }; /** * Get or set the grid size which determines the number of items displayed by the widget. * @name size * @memberof dc.dataGrid * @instance * @param {Number} [size=999] * @returns {Chart} */ _chart.size = function (size) { if (!arguments.length) { return _size; } _size = size; return _chart; }; /** * Get or set the function that formats an item. The data grid widget uses a * function to generate dynamic html. Use your favourite templating engine or * generate the string directly. * @name html * @memberof dc.dataGrid * @instance * @example * chart.html(function (d) { return '<div class='item '+data.exampleCategory+''>'+data.exampleString+'</div>';}); * @param {Function} [html] * @returns {Chart} */ _chart.html = function (html) { if (!arguments.length) { return _html; } _html = html; return _chart; }; /** * Get or set the function that formats a group label. * @name htmlGroup * @memberof dc.dataGrid * @instance * @example * chart.htmlGroup (function (d) { return '<h2>'.d.key . 'with ' . d.values.length .' items</h2>'}); * @param {Function} [htmlGroup] * @returns {Chart} */ _chart.htmlGroup = function (htmlGroup) { if (!arguments.length) { return _htmlGroup; } _htmlGroup = htmlGroup; return _chart; }; /** * Get or set sort-by function. This function works as a value accessor at the item * level and returns a particular field to be sorted. * @name sortBy * @memberof dc.dataGrid * @instance * @example * chart.sortBy(function(d) { * return d.date; * }); * @param {Function} [sortByFunction] * @returns {Chart} */ _chart.sortBy = function (sortByFunction) { if (!arguments.length) { return _sortBy; } _sortBy = sortByFunction; return _chart; }; /** * Get or set sort order function. * @name order * @memberof dc.dataGrid * @instance * @example * chart.order(d3.descending); * @param {Function} [order=d3.ascending] * @returns {Chart} */ _chart.order = function (order) { if (!arguments.length) { return _order; } _order = order; return _chart; }; return _chart.anchor(parent, chartGroup); }; /** * A concrete implementation of a general purpose bubble chart that allows data visualization using the * following dimensions: * - x axis position * - y axis position * - bubble radius * - color * Examples: * - [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) * - [US Venture Capital Landscape 2011](http://dc-js.github.com/dc.js/vc/index.html) * @name bubbleChart * @memberof dc * @mixes dc.bubbleMixin * @mixes dc.coordinateGridMixin * @example * // create a bubble chart under #chart-container1 element using the default global chart group * var bubbleChart1 = dc.bubbleChart('#chart-container1'); * // create a bubble chart under #chart-container2 element using chart group A * var bubbleChart2 = dc.bubbleChart('#chart-container2', 'chartGroupA'); * @param {String|node|d3.selection|dc.compositeChart} parent - Any valid * [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying * a dom block element such as a div; or a dom element or d3 selection. If the bar chart is a sub-chart * in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {BubbleChart} */ dc.bubbleChart = function (parent, chartGroup) { var _chart = dc.bubbleMixin(dc.coordinateGridMixin({})); var _elasticRadius = false; _chart.transitionDuration(750); var bubbleLocator = function (d) { return 'translate(' + (bubbleX(d)) + ',' + (bubbleY(d)) + ')'; }; /** * Turn on or off the elastic bubble radius feature, or return the value of the flag. If this * feature is turned on, then bubble radii will be automatically rescaled to fit the chart better. * @name elasticRadius * @memberof dc.bubbleChart * @instance * @param {Boolean} [elasticRadius=false] * @returns {Boolean} */ _chart.elasticRadius = function (elasticRadius) { if (!arguments.length) { return _elasticRadius; } _elasticRadius = elasticRadius; return _chart; }; _chart.plotData = function () { if (_elasticRadius) { _chart.r().domain([_chart.rMin(), _chart.rMax()]); } _chart.r().range([_chart.MIN_RADIUS, _chart.xAxisLength() * _chart.maxBubbleRelativeSize()]); var bubbleG = _chart.chartBodyG().selectAll('g.' + _chart.BUBBLE_NODE_CLASS) .data(_chart.data(), function (d) { return d.key; }); renderNodes(bubbleG); updateNodes(bubbleG); removeNodes(bubbleG); _chart.fadeDeselectedArea(); }; function renderNodes (bubbleG) { var bubbleGEnter = bubbleG.enter().append('g'); bubbleGEnter .attr('class', _chart.BUBBLE_NODE_CLASS) .attr('transform', bubbleLocator) .append('circle').attr('class', function (d, i) { return _chart.BUBBLE_CLASS + ' _' + i; }) .on('click', _chart.onClick) .attr('fill', _chart.getColor) .attr('r', 0); dc.transition(bubbleG, _chart.transitionDuration()) .selectAll('circle.' + _chart.BUBBLE_CLASS) .attr('r', function (d) { return _chart.bubbleR(d); }) .attr('opacity', function (d) { return (_chart.bubbleR(d) > 0) ? 1 : 0; }); _chart._doRenderLabel(bubbleGEnter); _chart._doRenderTitles(bubbleGEnter); } function updateNodes (bubbleG) { dc.transition(bubbleG, _chart.transitionDuration()) .attr('transform', bubbleLocator) .selectAll('circle.' + _chart.BUBBLE_CLASS) .attr('fill', _chart.getColor) .attr('r', function (d) { return _chart.bubbleR(d); }) .attr('opacity', function (d) { return (_chart.bubbleR(d) > 0) ? 1 : 0; }); _chart.doUpdateLabels(bubbleG); _chart.doUpdateTitles(bubbleG); } function removeNodes (bubbleG) { bubbleG.exit().remove(); } function bubbleX (d) { var x = _chart.x()(_chart.keyAccessor()(d)); if (isNaN(x)) { x = 0; } return x; } function bubbleY (d) { var y = _chart.y()(_chart.valueAccessor()(d)); if (isNaN(y)) { y = 0; } return y; } _chart.renderBrush = function () { // override default x axis brush from parent chart }; _chart.redrawBrush = function () { // override default x axis brush from parent chart _chart.fadeDeselectedArea(); }; return _chart.anchor(parent, chartGroup); }; /** * Composite charts are a special kind of chart that render multiple charts on the same Coordinate * Grid. You can overlay (compose) different bar/line/area charts in a single composite chart to * achieve some quite flexible charting effects. * @name compositeChart * @memberof dc * @mixes dc.coordinateGridMixin * @example * // create a composite chart under #chart-container1 element using the default global chart group * var compositeChart1 = dc.compositeChart('#chart-container1'); * // create a composite chart under #chart-container2 element using chart group A * var compositeChart2 = dc.compositeChart('#chart-container2', 'chartGroupA'); * @param {String|node|d3.selection|dc.compositeChart} parent - Any valid * [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying * a dom block element such as a div; or a dom element or d3 selection. If the bar chart is a sub-chart * in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {CompositeChart} */ dc.compositeChart = function (parent, chartGroup) { var SUB_CHART_CLASS = 'sub'; var DEFAULT_RIGHT_Y_AXIS_LABEL_PADDING = 12; var _chart = dc.coordinateGridMixin({}); var _children = []; var _childOptions = {}; var _shareColors = false, _shareTitle = true; var _rightYAxis = d3.svg.axis(), _rightYAxisLabel = 0, _rightYAxisLabelPadding = DEFAULT_RIGHT_Y_AXIS_LABEL_PADDING, _rightY, _rightAxisGridLines = false; _chart._mandatoryAttributes([]); _chart.transitionDuration(500); dc.override(_chart, '_generateG', function () { var g = this.__generateG(); for (var i = 0; i < _children.length; ++i) { var child = _children[i]; generateChildG(child, i); if (!child.dimension()) { child.dimension(_chart.dimension()); } if (!child.group()) { child.group(_chart.group()); } child.chartGroup(_chart.chartGroup()); child.svg(_chart.svg()); child.xUnits(_chart.xUnits()); child.transitionDuration(_chart.transitionDuration()); child.brushOn(_chart.brushOn()); child.renderTitle(_chart.renderTitle()); child.elasticX(_chart.elasticX()); } return g; }); _chart._brushing = function () { var extent = _chart.extendBrush(); var brushIsEmpty = _chart.brushIsEmpty(extent); for (var i = 0; i < _children.length; ++i) { _children[i].filter(null); if (!brushIsEmpty) { _children[i].filter(extent); } } }; _chart._prepareYAxis = function () { if (leftYAxisChildren().length !== 0) { prepareLeftYAxis(); } if (rightYAxisChildren().length !== 0) { prepareRightYAxis(); } if (leftYAxisChildren().length > 0 && !_rightAxisGridLines) { _chart._renderHorizontalGridLinesForAxis(_chart.g(), _chart.y(), _chart.yAxis()); } else if (rightYAxisChildren().length > 0) { _chart._renderHorizontalGridLinesForAxis(_chart.g(), _rightY, _rightYAxis); } }; _chart.renderYAxis = function () { if (leftYAxisChildren().length !== 0) { _chart.renderYAxisAt('y', _chart.yAxis(), _chart.margins().left); _chart.renderYAxisLabel('y', _chart.yAxisLabel(), -90); } if (rightYAxisChildren().length !== 0) { _chart.renderYAxisAt('yr', _chart.rightYAxis(), _chart.width() - _chart.margins().right); _chart.renderYAxisLabel('yr', _chart.rightYAxisLabel(), 90, _chart.width() - _rightYAxisLabelPadding); } }; function prepareRightYAxis () { if (_chart.rightY() === undefined || _chart.elasticY()) { if (_chart.rightY() === undefined) { _chart.rightY(d3.scale.linear()); } _chart.rightY().domain([rightYAxisMin(), rightYAxisMax()]).rangeRound([_chart.yAxisHeight(), 0]); } _chart.rightY().range([_chart.yAxisHeight(), 0]); _chart.rightYAxis(_chart.rightYAxis().scale(_chart.rightY())); _chart.rightYAxis().orient('right'); } function prepareLeftYAxis () { if (_chart.y() === undefined || _chart.elasticY()) { if (_chart.y() === undefined) { _chart.y(d3.scale.linear()); } _chart.y().domain([yAxisMin(), yAxisMax()]).rangeRound([_chart.yAxisHeight(), 0]); } _chart.y().range([_chart.yAxisHeight(), 0]); _chart.yAxis(_chart.yAxis().scale(_chart.y())); _chart.yAxis().orient('left'); } function generateChildG (child, i) { child._generateG(_chart.g()); child.g().attr('class', SUB_CHART_CLASS + ' _' + i); } _chart.plotData = function () { for (var i = 0; i < _children.length; ++i) { var child = _children[i]; if (!child.g()) { generateChildG(child, i); } if (_shareColors) { child.colors(_chart.colors()); } child.x(_chart.x()); child.xAxis(_chart.xAxis()); if (child.useRightYAxis()) { child.y(_chart.rightY()); child.yAxis(_chart.rightYAxis()); } else { child.y(_chart.y()); child.yAxis(_chart.yAxis()); } child.plotData(); child._activateRenderlets(); } }; /** * Get or set whether to draw gridlines from the right y axis. Drawing from the left y axis is the * default behavior. This option is only respected when subcharts with both left and right y-axes * are present. * @name useRightAxisGridLines * @memberof dc.compositeChart * @instance * @param {Boolean} [useRightAxisGridLines=false] * @return {Chart} */ _chart.useRightAxisGridLines = function (useRightAxisGridLines) { if (!arguments) { return _rightAxisGridLines; } _rightAxisGridLines = useRightAxisGridLines; return _chart; }; /** * Get or set chart-specific options for all child charts. This is equivalent to calling `.options` * on each child chart. * @name childOptions * @memberof dc.compositeChart * @instance * @param {Object} [childOptions] * @return {Chart} */ _chart.childOptions = function (childOptions) { if (!arguments.length) { return _childOptions; } _childOptions = childOptions; _children.forEach(function (child) { child.options(_childOptions); }); return _chart; }; _chart.fadeDeselectedArea = function () { for (var i = 0; i < _children.length; ++i) { var child = _children[i]; child.brush(_chart.brush()); child.fadeDeselectedArea(); } }; /** * Set or get the right y axis label. * @name rightYAxisLabel * @memberof dc.compositeChart * @instance * @param {String} [rightYAxisLabel] * @param {Number} [padding] * @return {Chart} */ _chart.rightYAxisLabel = function (rightYAxisLabel, padding) { if (!arguments.length) { return _rightYAxisLabel; } _rightYAxisLabel = rightYAxisLabel; _chart.margins().right -= _rightYAxisLabelPadding; _rightYAxisLabelPadding = (padding === undefined) ? DEFAULT_RIGHT_Y_AXIS_LABEL_PADDING : padding; _chart.margins().right += _rightYAxisLabelPadding; return _chart; }; /** * Combine the given charts into one single composite coordinate grid chart. * @name compose * @memberof dc.compositeChart * @instance * @example * moveChart.compose([ * // when creating sub-chart you need to pass in the parent chart * dc.lineChart(moveChart) * .group(indexAvgByMonthGroup) // if group is missing then parent's group will be used * .valueAccessor(function (d){return d.value.avg;}) * // most of the normal functions will continue to work in a composed chart * .renderArea(true) * .stack(monthlyMoveGroup, function (d){return d.value;}) * .title(function (d){ * var value = d.value.avg?d.value.avg:d.value; * if(isNaN(value)) value = 0; * return dateFormat(d.key) + '\n' + numberFormat(value); * }), * dc.barChart(moveChart) * .group(volumeByMonthGroup) * .centerBar(true) * ]); * @param {Array<Chart>} [subChartArray] * @return {Chart} */ _chart.compose = function (subChartArray) { _children = subChartArray; _children.forEach(function (child) { child.height(_chart.height()); child.width(_chart.width()); child.margins(_chart.margins()); if (_shareTitle) { child.title(_chart.title()); } child.options(_childOptions); }); return _chart; }; /** * Returns the child charts which are composed into the composite chart. * @name children * @memberof dc.compositeChart * @instance * @return {Array<Chart>} */ _chart.children = function () { return _children; }; /** * Get or set color sharing for the chart. If set, the `.colors()` value from this chart * will be shared with composed children. Additionally if the child chart implements * Stackable and has not set a custom .colorAccessor, then it will generate a color * specific to its order in the composition. * @name shareColors * @memberof dc.compositeChart * @instance * @param {Boolean} [shareColors=false] * @return {Chart} */ _chart.shareColors = function (shareColors) { if (!arguments.length) { return _shareColors; } _shareColors = shareColors; return _chart; }; /** * Get or set title sharing for the chart. If set, the `.title()` value from this chart will be * shared with composed children. * @name shareTitle * @memberof dc.compositeChart * @instance * @param {Boolean} [shareTitle=true] * @return {Chart} */ _chart.shareTitle = function (shareTitle) { if (!arguments.length) { return _shareTitle; } _shareTitle = shareTitle; return _chart; }; /** * Get or set the y scale for the right axis. The right y scale is typically automatically * generated by the chart implementation. * @name rightY * @memberof dc.compositeChart * @instance * @param {d3.scale} [yScale] * @return {Chart} */ _chart.rightY = function (yScale) { if (!arguments.length) { return _rightY; } _rightY = yScale; _chart.rescale(); return _chart; }; function leftYAxisChildren () { return _children.filter(function (child) { return !child.useRightYAxis(); }); } function rightYAxisChildren () { return _children.filter(function (child) { return child.useRightYAxis(); }); } function getYAxisMin (charts) { return charts.map(function (c) { return c.yAxisMin(); }); } delete _chart.yAxisMin; function yAxisMin () { return d3.min(getYAxisMin(leftYAxisChildren())); } function rightYAxisMin () { return d3.min(getYAxisMin(rightYAxisChildren())); } function getYAxisMax (charts) { return charts.map(function (c) { return c.yAxisMax(); }); } delete _chart.yAxisMax; function yAxisMax () { return dc.utils.add(d3.max(getYAxisMax(leftYAxisChildren())), _chart.yAxisPadding()); } function rightYAxisMax () { return dc.utils.add(d3.max(getYAxisMax(rightYAxisChildren())), _chart.yAxisPadding()); } function getAllXAxisMinFromChildCharts () { return _children.map(function (c) { return c.xAxisMin(); }); } dc.override(_chart, 'xAxisMin', function () { return dc.utils.subtract(d3.min(getAllXAxisMinFromChildCharts()), _chart.xAxisPadding()); }); function getAllXAxisMaxFromChildCharts () { return _children.map(function (c) { return c.xAxisMax(); }); } dc.override(_chart, 'xAxisMax', function () { return dc.utils.add(d3.max(getAllXAxisMaxFromChildCharts()), _chart.xAxisPadding()); }); _chart.legendables = function () { return _children.reduce(function (items, child) { if (_shareColors) { child.colors(_chart.colors()); } items.push.apply(items, child.legendables()); return items; }, []); }; _chart.legendHighlight = function (d) { for (var j = 0; j < _children.length; ++j) { var child = _children[j]; child.legendHighlight(d); } }; _chart.legendReset = function (d) { for (var j = 0; j < _children.length; ++j) { var child = _children[j]; child.legendReset(d); } }; _chart.legendToggle = function () { console.log('composite should not be getting legendToggle itself'); }; /** * Set or get the right y axis used by the composite chart. This function is most useful when y * axis customization is required. The y axis in dc.js is an instance of a [d3 axis * object](https://github.com/mbostock/d3/wiki/SVG-Axes#wiki-_axis) therefore it supports any valid * d3 axis manipulation. **Caution**: The y axis is usually generated internally by dc; * resetting it may cause unexpected results. * @name rightYAxis * @memberof dc.compositeChart * @instance * @example * // customize y axis tick format * chart.rightYAxis().tickFormat(function (v) {return v + '%';}); * // customize y axis tick values * chart.rightYAxis().tickValues([0, 100, 200, 300]); * @param {d3.svg.axis} [rightYAxis] * @return {Chart} */ _chart.rightYAxis = function (rightYAxis) { if (!arguments.length) { return _rightYAxis; } _rightYAxis = rightYAxis; return _chart; }; return _chart.anchor(parent, chartGroup); }; /** * A series chart is a chart that shows multiple series of data overlaid on one chart, where the * series is specified in the data. It is a specialization of Composite Chart and inherits all * composite features other than recomposing the chart. * @name seriesChart * @memberof dc * @mixes dc.compositeChart * @example * // create a series chart under #chart-container1 element using the default global chart group * var seriesChart1 = dc.seriesChart("#chart-container1"); * // create a series chart under #chart-container2 element using chart group A * var seriesChart2 = dc.seriesChart("#chart-container2", "chartGroupA"); * @param {String|node|d3.selection|dc.compositeChart} parent - Any valid * [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying * a dom block element such as a div; or a dom element or d3 selection. If the bar chart is a sub-chart * in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {SeriesChart} */ dc.seriesChart = function (parent, chartGroup) { var _chart = dc.compositeChart(parent, chartGroup); function keySort (a, b) { return d3.ascending(_chart.keyAccessor()(a), _chart.keyAccessor()(b)); } var _charts = {}; var _chartFunction = dc.lineChart; var _seriesAccessor; var _seriesSort = d3.ascending; var _valueSort = keySort; _chart._mandatoryAttributes().push('seriesAccessor', 'chart'); _chart.shareColors(true); _chart._preprocessData = function () { var keep = []; var childrenChanged; var nester = d3.nest().key(_seriesAccessor); if (_seriesSort) { nester.sortKeys(_seriesSort); } if (_valueSort) { nester.sortValues(_valueSort); } var nesting = nester.entries(_chart.data()); var children = nesting.map(function (sub, i) { var subChart = _charts[sub.key] || _chartFunction.call(_chart, _chart, chartGroup, sub.key, i); if (!_charts[sub.key]) { childrenChanged = true; } _charts[sub.key] = subChart; keep.push(sub.key); return subChart .dimension(_chart.dimension()) .group({all: d3.functor(sub.values)}, sub.key) .keyAccessor(_chart.keyAccessor()) .valueAccessor(_chart.valueAccessor()) .brushOn(_chart.brushOn()); }); // this works around the fact compositeChart doesn't really // have a removal interface Object.keys(_charts) .filter(function (c) {return keep.indexOf(c) === -1;}) .forEach(function (c) { clearChart(c); childrenChanged = true; }); _chart._compose(children); if (childrenChanged && _chart.legend()) { _chart.legend().render(); } }; function clearChart (c) { if (_charts[c].g()) { _charts[c].g().remove(); } delete _charts[c]; } function resetChildren () { Object.keys(_charts).map(clearChart); _charts = {}; } /** * Get or set the chart function, which generates the child charts. * @name chart * @memberof dc.seriesChart * @instance * @example * // put interpolation on the line charts used for the series * chart.chart(function(c) { return dc.lineChart(c).interpolate('basis'); }) * // do a scatter series chart * chart.chart(dc.scatterPlot) * @param {Function} [chartFunction=dc.lineChart] * @returns {Chart} */ _chart.chart = function (chartFunction) { if (!arguments.length) { return _chartFunction; } _chartFunction = chartFunction; resetChildren(); return _chart; }; /** * Get or set accessor function for the displayed series. Given a datum, this function * should return the series that datum belongs to. * @name seriesAccessor * @memberof dc.seriesChart * @instance * @param {Function} [accessor] * @returns {Chart} */ _chart.seriesAccessor = function (accessor) { if (!arguments.length) { return _seriesAccessor; } _seriesAccessor = accessor; resetChildren(); return _chart; }; /** * Get or set a function to sort the list of series by, given series values. * @name seriesSort * @memberof dc.seriesChart * @instance * @example * chart.seriesSort(d3.descending); * @param {Function} [sortFunction=d3.ascending] * @returns {Chart} */ _chart.seriesSort = function (sortFunction) { if (!arguments.length) { return _seriesSort; } _seriesSort = sortFunction; resetChildren(); return _chart; }; /** * Get or set a function to sort each series values by. By default this is the key accessor which, * for example, will ensure a lineChart series connects its points in increasing key/x order, * rather than haphazardly. * @name valueSort * @memberof dc.seriesChart * @instance * @param {Function} [sortFunction] * @returns {Chart} */ _chart.valueSort = function (sortFunction) { if (!arguments.length) { return _valueSort; } _valueSort = sortFunction; resetChildren(); return _chart; }; // make compose private _chart._compose = _chart.compose; delete _chart.compose; return _chart; }; /** * The geo choropleth chart is designed as an easy way to create a crossfilter driven choropleth map * from GeoJson data. This chart implementation was inspired by [the great d3 choropleth example](http://bl.ocks.org/4060606). * Examples: * - [US Venture Capital Landscape 2011](http://dc-js.github.com/dc.js/vc/index.html) * @name geoChoroplethChart * @memberof dc * @mixes dc.colorMixin * @mixes dc.baseMixin * @example * // create a choropleth chart under '#us-chart' element using the default global chart group * var chart1 = dc.geoChoroplethChart('#us-chart'); * // create a choropleth chart under '#us-chart2' element using chart group A * var chart2 = dc.compositeChart('#us-chart2', 'chartGroupA'); * @param {String|node|d3.selection|dc.compositeChart} parent - Any valid * [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying * a dom block element such as a div; or a dom element or d3 selection. If the bar chart is a sub-chart * in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {GeoChoroplethChart} */ dc.geoChoroplethChart = function (parent, chartGroup) { var _chart = dc.colorMixin(dc.baseMixin({})); _chart.colorAccessor(function (d) { return d || 0; }); var _geoPath = d3.geo.path(); var _projectionFlag; var _geoJsons = []; _chart._doRender = function () { _chart.resetSvg(); for (var layerIndex = 0; layerIndex < _geoJsons.length; ++layerIndex) { var states = _chart.svg().append('g') .attr('class', 'layer' + layerIndex); var regionG = states.selectAll('g.' + geoJson(layerIndex).name) .data(geoJson(layerIndex).data) .enter() .append('g') .attr('class', geoJson(layerIndex).name); regionG .append('path') .attr('fill', 'white') .attr('d', _geoPath); regionG.append('title'); plotData(layerIndex); } _projectionFlag = false; }; function plotData (layerIndex) { var data = generateLayeredData(); if (isDataLayer(layerIndex)) { var regionG = renderRegionG(layerIndex); renderPaths(regionG, layerIndex, data); renderTitle(regionG, layerIndex, data); } } function generateLayeredData () { var data = {}; var groupAll = _chart.data(); for (var i = 0; i < groupAll.length; ++i) { data[_chart.keyAccessor()(groupAll[i])] = _chart.valueAccessor()(groupAll[i]); } return data; } function isDataLayer (layerIndex) { return geoJson(layerIndex).keyAccessor; } function renderRegionG (layerIndex) { var regionG = _chart.svg() .selectAll(layerSelector(layerIndex)) .classed('selected', function (d) { return isSelected(layerIndex, d); }) .classed('deselected', function (d) { return isDeselected(layerIndex, d); }) .attr('class', function (d) { var layerNameClass = geoJson(layerIndex).name; var regionClass = dc.utils.nameToId(geoJson(layerIndex).keyAccessor(d)); var baseClasses = layerNameClass + ' ' + regionClass; if (isSelected(layerIndex, d)) { baseClasses += ' selected'; } if (isDeselected(layerIndex, d)) { baseClasses += ' deselected'; } return baseClasses; }); return regionG; } function layerSelector (layerIndex) { return 'g.layer' + layerIndex + ' g.' + geoJson(layerIndex).name; } function isSelected (layerIndex, d) { return _chart.hasFilter() && _chart.hasFilter(getKey(layerIndex, d)); } function isDeselected (layerIndex, d) { return _chart.hasFilter() && !_chart.hasFilter(getKey(layerIndex, d)); } function getKey (layerIndex, d) { return geoJson(layerIndex).keyAccessor(d); } function geoJson (index) { return _geoJsons[index]; } function renderPaths (regionG, layerIndex, data) { var paths = regionG .select('path') .attr('fill', function () { var currentFill = d3.select(this).attr('fill'); if (currentFill) { return currentFill; } return 'none'; }) .on('click', function (d) { return _chart.onClick(d, layerIndex); }); dc.transition(paths, _chart.transitionDuration()).attr('fill', function (d, i) { return _chart.getColor(data[geoJson(layerIndex).keyAccessor(d)], i); }); } _chart.onClick = function (d, layerIndex) { var selectedRegion = geoJson(layerIndex).keyAccessor(d); dc.events.trigger(function () { _chart.filter(selectedRegion); _chart.redrawGroup(); }); }; function renderTitle (regionG, layerIndex, data) { if (_chart.renderTitle()) { regionG.selectAll('title').text(function (d) { var key = getKey(layerIndex, d); var value = data[key]; return _chart.title()({key: key, value: value}); }); } } _chart._doRedraw = function () { for (var layerIndex = 0; layerIndex < _geoJsons.length; ++layerIndex) { plotData(layerIndex); if (_projectionFlag) { _chart.svg().selectAll('g.' + geoJson(layerIndex).name + ' path').attr('d', _geoPath); } } _projectionFlag = false; }; /** * **mandatory** * * Use this function to insert a new GeoJson map layer. This function can be invoked multiple times * if you have multiple GeoJson data layers to render on top of each other. If you overlay multiple * layers with the same name the new overlay will override the existing one. * @name overlayGeoJson * @memberof dc.geoChoroplethChart * @instance * @example * // insert a layer for rendering US states * chart.overlayGeoJson(statesJson.features, 'state', function(d) { * return d.properties.name; * }); * @param {Object} json - a geojson feed * @param {String} name - name of the layer * @param {Function} keyAccessor - accessor function used to extract 'key' from the GeoJson data. The key extracted by * this function should match the keys returned by the crossfilter groups. * @returns {Chart} */ _chart.overlayGeoJson = function (json, name, keyAccessor) { for (var i = 0; i < _geoJsons.length; ++i) { if (_geoJsons[i].name === name) { _geoJsons[i].data = json; _geoJsons[i].keyAccessor = keyAccessor; return _chart; } } _geoJsons.push({name: name, data: json, keyAccessor: keyAccessor}); return _chart; }; /** * Set custom geo projection function. See the available [d3 geo projection * functions](https://github.com/mbostock/d3/wiki/Geo-Projections). * @name projection * @memberof dc.geoChoroplethChart * @instance * @param {d3.projection} [projection=d3.projection.albersUsa()] * @returns {Chart} */ _chart.projection = function (projection) { _geoPath.projection(projection); _projectionFlag = true; return _chart; }; /** * Returns all GeoJson layers currently registered with this chart. The returned array is a * reference to this chart's internal data structure, so any modification to this array will also * modify this chart's internal registration. * @name geoJsons * @memberof dc.geoChoroplethChart * @instance * @returns {Array<{name:String, data: Object, accessor: Function}>} */ _chart.geoJsons = function () { return _geoJsons; }; /** * Returns the [d3.geo.path](https://github.com/mbostock/d3/wiki/Geo-Paths#path) object used to * render the projection and features. Can be useful for figuring out the bounding box of the * feature set and thus a way to calculate scale and translation for the projection. * @name geoPath * @memberof dc.geoChoroplethChart * @instance * @returns {d3.geo.path} */ _chart.geoPath = function () { return _geoPath; }; /** * Remove a GeoJson layer from this chart by name * @name removeGeoJson * @memberof dc.geoChoroplethChart * @instance * @param {String} name * @returns {Chart} */ _chart.removeGeoJson = function (name) { var geoJsons = []; for (var i = 0; i < _geoJsons.length; ++i) { var layer = _geoJsons[i]; if (layer.name !== name) { geoJsons.push(layer); } } _geoJsons = geoJsons; return _chart; }; return _chart.anchor(parent, chartGroup); }; /** * The bubble overlay chart is quite different from the typical bubble chart. With the bubble overlay * chart you can arbitrarily place bubbles on an existing svg or bitmap image, thus changing the * typical x and y positioning while retaining the capability to visualize data using bubble radius * and coloring. * Examples: * - [Canadian City Crime Stats](http://dc-js.github.com/dc.js/crime/index.html) * @name bubbleOverlay * @memberof dc * @mixes dc.bubbleMixin * @mixes dc.baseMixin * @example * // create a bubble overlay chart on top of the '#chart-container1 svg' element using the default global chart group * var bubbleChart1 = dc.bubbleOverlayChart('#chart-container1').svg(d3.select('#chart-container1 svg')); * // create a bubble overlay chart on top of the '#chart-container2 svg' element using chart group A * var bubbleChart2 = dc.compositeChart('#chart-container2', 'chartGroupA').svg(d3.select('#chart-container2 svg')); * @param {String|node|d3.selection|dc.compositeChart} parent - Any valid * [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying * a dom block element such as a div; or a dom element or d3 selection. If the bar chart is a sub-chart * in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {BubbleOverlay} */ dc.bubbleOverlay = function (parent, chartGroup) { var BUBBLE_OVERLAY_CLASS = 'bubble-overlay'; var BUBBLE_NODE_CLASS = 'node'; var BUBBLE_CLASS = 'bubble'; /** * **mandatory** * * Set the underlying svg image element. Unlike other dc charts this chart will not generate a svg * element; therefore the bubble overlay chart will not work if this function is not invoked. If the * underlying image is a bitmap, then an empty svg will need to be created on top of the image. * @name svg * @memberof dc.bubbleOverlay * @instance * @example * // set up underlying svg element * chart.svg(d3.select('#chart svg')); * @param {Selection} [imageElement] * @returns {Chart} */ var _chart = dc.bubbleMixin(dc.baseMixin({})); var _g; var _points = []; _chart.transitionDuration(750); _chart.radiusValueAccessor(function (d) { return d.value; }); /** * **mandatory** * * Set up a data point on the overlay. The name of a data point should match a specific 'key' among * data groups generated using keyAccessor. If a match is found (point name <-> data group key) * then a bubble will be generated at the position specified by the function. x and y * value specified here are relative to the underlying svg. * @name point * @memberof dc.bubbleOverlay * @instance * @param {String} name * @param {Number} x * @param {Number} y * @returns {Chart} */ _chart.point = function (name, x, y) { _points.push({name: name, x: x, y: y}); return _chart; }; _chart._doRender = function () { _g = initOverlayG(); _chart.r().range([_chart.MIN_RADIUS, _chart.width() * _chart.maxBubbleRelativeSize()]); initializeBubbles(); _chart.fadeDeselectedArea(); return _chart; }; function initOverlayG () { _g = _chart.select('g.' + BUBBLE_OVERLAY_CLASS); if (_g.empty()) { _g = _chart.svg().append('g').attr('class', BUBBLE_OVERLAY_CLASS); } return _g; } function initializeBubbles () { var data = mapData(); _points.forEach(function (point) { var nodeG = getNodeG(point, data); var circle = nodeG.select('circle.' + BUBBLE_CLASS); if (circle.empty()) { circle = nodeG.append('circle') .attr('class', BUBBLE_CLASS) .attr('r', 0) .attr('fill', _chart.getColor) .on('click', _chart.onClick); } dc.transition(circle, _chart.transitionDuration()) .attr('r', function (d) { return _chart.bubbleR(d); }); _chart._doRenderLabel(nodeG); _chart._doRenderTitles(nodeG); }); } function mapData () { var data = {}; _chart.data().forEach(function (datum) { data[_chart.keyAccessor()(datum)] = datum; }); return data; } function getNodeG (point, data) { var bubbleNodeClass = BUBBLE_NODE_CLASS + ' ' + dc.utils.nameToId(point.name); var nodeG = _g.select('g.' + dc.utils.nameToId(point.name)); if (nodeG.empty()) { nodeG = _g.append('g') .attr('class', bubbleNodeClass) .attr('transform', 'translate(' + point.x + ',' + point.y + ')'); } nodeG.datum(data[point.name]); return nodeG; } _chart._doRedraw = function () { updateBubbles(); _chart.fadeDeselectedArea(); return _chart; }; function updateBubbles () { var data = mapData(); _points.forEach(function (point) { var nodeG = getNodeG(point, data); var circle = nodeG.select('circle.' + BUBBLE_CLASS); dc.transition(circle, _chart.transitionDuration()) .attr('r', function (d) { return _chart.bubbleR(d); }) .attr('fill', _chart.getColor); _chart.doUpdateLabels(nodeG); _chart.doUpdateTitles(nodeG); }); } _chart.debug = function (flag) { if (flag) { var debugG = _chart.select('g.' + dc.constants.DEBUG_GROUP_CLASS); if (debugG.empty()) { debugG = _chart.svg() .append('g') .attr('class', dc.constants.DEBUG_GROUP_CLASS); } var debugText = debugG.append('text') .attr('x', 10) .attr('y', 20); debugG .append('rect') .attr('width', _chart.width()) .attr('height', _chart.height()) .on('mousemove', function () { var position = d3.mouse(debugG.node()); var msg = position[0] + ', ' + position[1]; debugText.text(msg); }); } else { _chart.selectAll('.debug').remove(); } return _chart; }; _chart.anchor(parent, chartGroup); return _chart; }; /** * Concrete row chart implementation. * @name rowChart * @memberof dc * @mixes dc.capMixin * @mixes dc.marginMixin * @mixes dc.colorMixin * @mixes dc.baseMixin * @example * // create a row chart under #chart-container1 element using the default global chart group * var chart1 = dc.rowChart('#chart-container1'); * // create a row chart under #chart-container2 element using chart group A * var chart2 = dc.rowChart('#chart-container2', 'chartGroupA'); * @param {String|node|d3.selection|dc.compositeChart} parent - Any valid * [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying * a dom block element such as a div; or a dom element or d3 selection. If the bar chart is a sub-chart * in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {RowChart} */ dc.rowChart = function (parent, chartGroup) { var _g; var _labelOffsetX = 10; var _labelOffsetY = 15; var _hasLabelOffsetY = false; var _dyOffset = '0.35em'; // this helps center labels https://github.com/mbostock/d3/wiki/SVG-Shapes#svg_text var _titleLabelOffsetX = 2; var _gap = 5; var _fixedBarHeight = false; var _rowCssClass = 'row'; var _titleRowCssClass = 'titlerow'; var _renderTitleLabel = false; var _chart = dc.capMixin(dc.marginMixin(dc.colorMixin(dc.baseMixin({})))); var _x; var _elasticX; var _xAxis = d3.svg.axis().orient('bottom'); var _rowData; _chart.rowsCap = _chart.cap; function calculateAxisScale () { if (!_x || _elasticX) { var extent = d3.extent(_rowData, _chart.cappedValueAccessor); if (extent[0] > 0) { extent[0] = 0; } _x = d3.scale.linear().domain(extent) .range([0, _chart.effectiveWidth()]); } _xAxis.scale(_x); } function drawAxis () { var axisG = _g.select('g.axis'); calculateAxisScale(); if (axisG.empty()) { axisG = _g.append('g').attr('class', 'axis') .attr('transform', 'translate(0, ' + _chart.effectiveHeight() + ')'); } dc.transition(axisG, _chart.transitionDuration()) .call(_xAxis); } _chart._doRender = function () { _chart.resetSvg(); _g = _chart.svg() .append('g') .attr('transform', 'translate(' + _chart.margins().left + ',' + _chart.margins().top + ')'); drawChart(); return _chart; }; _chart.title(function (d) { return _chart.cappedKeyAccessor(d) + ': ' + _chart.cappedValueAccessor(d); }); _chart.label(_chart.cappedKeyAccessor); /** * Gets or sets the x scale. The x scale can be any d3 * [quantitive scale](https://github.com/mbostock/d3/wiki/Quantitative-Scales) * @name x * @memberof dc.rowChart * @instance * @param {d3.scale} [scale] * @returns {Chart} */ _chart.x = function (scale) { if (!arguments.length) { return _x; } _x = scale; return _chart; }; function drawGridLines () { _g.selectAll('g.tick') .select('line.grid-line') .remove(); _g.selectAll('g.tick') .append('line') .attr('class', 'grid-line') .attr('x1', 0) .attr('y1', 0) .attr('x2', 0) .attr('y2', function () { return -_chart.effectiveHeight(); }); } function drawChart () { _rowData = _chart.data(); drawAxis(); drawGridLines(); var rows = _g.selectAll('g.' + _rowCssClass) .data(_rowData); createElements(rows); removeElements(rows); updateElements(rows); } function createElements (rows) { var rowEnter = rows.enter() .append('g') .attr('class', function (d, i) { return _rowCssClass + ' _' + i; }); rowEnter.append('rect').attr('width', 0); createLabels(rowEnter); updateLabels(rows); } function removeElements (rows) { rows.exit().remove(); } function rootValue () { var root = _x(0); return (root === -Infinity || root !== root) ? _x(1) : root; } function updateElements (rows) { var n = _rowData.length; var height; if (!_fixedBarHeight) { height = (_chart.effectiveHeight() - (n + 1) * _gap) / n; } else { height = _fixedBarHeight; } // vertically align label in center unless they override the value via property setter if (!_hasLabelOffsetY) { _labelOffsetY = height / 2; } var rect = rows.attr('transform', function (d, i) { return 'translate(0,' + ((i + 1) * _gap + i * height) + ')'; }).select('rect') .attr('height', height) .attr('fill', _chart.getColor) .on('click', onClick) .classed('deselected', function (d) { return (_chart.hasFilter()) ? !isSelectedRow(d) : false; }) .classed('selected', function (d) { return (_chart.hasFilter()) ? isSelectedRow(d) : false; }); dc.transition(rect, _chart.transitionDuration()) .attr('width', function (d) { return Math.abs(rootValue() - _x(_chart.valueAccessor()(d))); }) .attr('transform', translateX); createTitles(rows); updateLabels(rows); } function createTitles (rows) { if (_chart.renderTitle()) { rows.selectAll('title').remove(); rows.append('title').text(_chart.title()); } } function createLabels (rowEnter) { if (_chart.renderLabel()) { rowEnter.append('text') .on('click', onClick); } if (_chart.renderTitleLabel()) { rowEnter.append('text') .attr('class', _titleRowCssClass) .on('click', onClick); } } function updateLabels (rows) { if (_chart.renderLabel()) { var lab = rows.select('text') .attr('x', _labelOffsetX) .attr('y', _labelOffsetY) .attr('dy', _dyOffset) .on('click', onClick) .attr('class', function (d, i) { return _rowCssClass + ' _' + i; }) .text(function (d) { return _chart.label()(d); }); dc.transition(lab, _chart.transitionDuration()) .attr('transform', translateX); } if (_chart.renderTitleLabel()) { var titlelab = rows.select('.' + _titleRowCssClass) .attr('x', _chart.effectiveWidth() - _titleLabelOffsetX) .attr('y', _labelOffsetY) .attr('text-anchor', 'end') .on('click', onClick) .attr('class', function (d, i) { return _titleRowCssClass + ' _' + i ; }) .text(function (d) { return _chart.title()(d); }); dc.transition(titlelab, _chart.transitionDuration()) .attr('transform', translateX); } } /** * Turn on/off Title label rendering (values) using SVG style of text-anchor 'end' * @name renderTitleLabel * @memberof dc.rowChart * @instance * @param {Boolean} [renderTitleLabel=false] * @returns {Chart} */ _chart.renderTitleLabel = function (renderTitleLabel) { if (!arguments.length) { return _renderTitleLabel; } _renderTitleLabel = renderTitleLabel; return _chart; }; function onClick (d) { _chart.onClick(d); } function translateX (d) { var x = _x(_chart.cappedValueAccessor(d)), x0 = rootValue(), s = x > x0 ? x0 : x; return 'translate(' + s + ',0)'; } _chart._doRedraw = function () { drawChart(); return _chart; }; /** * Get the x axis for the row chart instance. Note: not settable for row charts. * See the [d3 axis object](https://github.com/mbostock/d3/wiki/SVG-Axes#wiki-axis) documention for more information. * @name xAxis * @memberof dc.rowChart * @instance * @example * // customize x axis tick format * chart.xAxis().tickFormat(function (v) {return v + '%';}); * // customize x axis tick values * chart.xAxis().tickValues([0, 100, 200, 300]); * @returns {d3.svg.Axis} */ _chart.xAxis = function () { return _xAxis; }; /** * Get or set the fixed bar height. Default is [false] which will auto-scale bars. * For example, if you want to fix the height for a specific number of bars (useful in TopN charts) * you could fix height as follows (where count = total number of bars in your TopN and gap is * your vertical gap space). * @name fixedBarHeight * @memberof dc.rowChart * @instance * @example * chart.fixedBarHeight( chartheight - (count + 1) * gap / count); * @param {Boolean|Number} [fixedBarHeight=false] * @returns {Chart} */ _chart.fixedBarHeight = function (fixedBarHeight) { if (!arguments.length) { return _fixedBarHeight; } _fixedBarHeight = fixedBarHeight; return _chart; }; /** * Get or set the vertical gap space between rows on a particular row chart instance * @name gap * @memberof dc.rowChart * @instance * @param {Number} [gap=5] * @returns {Chart} */ _chart.gap = function (gap) { if (!arguments.length) { return _gap; } _gap = gap; return _chart; }; /** * Get or set the elasticity on x axis. If this attribute is set to true, then the x axis will rescle to auto-fit the * data range when filtered. * @name elasticX * @memberof dc.rowChart * @instance * @param {Boolean} [elasticX] * @returns {Chart} */ _chart.elasticX = function (elasticX) { if (!arguments.length) { return _elasticX; } _elasticX = elasticX; return _chart; }; /** * Get or set the x offset (horizontal space to the top left corner of a row) for labels on a particular row chart. * @name labelOffsetX * @memberof dc.rowChart * @instance * @param {Number} [labelOffsetX=10] * @returns {Chart} */ _chart.labelOffsetX = function (labelOffsetX) { if (!arguments.length) { return _labelOffsetX; } _labelOffsetX = labelOffsetX; return _chart; }; /** * Get or set the y offset (vertical space to the top left corner of a row) for labels on a particular row chart. * @name labelOffsetY * @memberof dc.rowChart * @instance * @param {Number} [labelOffsety=15] * @returns {Chart} */ _chart.labelOffsetY = function (labelOffsety) { if (!arguments.length) { return _labelOffsetY; } _labelOffsetY = labelOffsety; _hasLabelOffsetY = true; return _chart; }; /** * Get of set the x offset (horizontal space between right edge of row and right edge or text. * @name titleLabelOffsetX * @memberof dc.rowChart * @instance * @param {Number} [titleLabelOffsetX=2] * @returns {Chart} */ _chart.titleLabelOffsetX = function (titleLabelOffsetX) { if (!arguments.length) { return _titleLabelOffsetX; } _titleLabelOffsetX = titleLabelOffsetX; return _chart; }; function isSelectedRow (d) { return _chart.hasFilter(_chart.cappedKeyAccessor(d)); } return _chart.anchor(parent, chartGroup); }; /** * Legend is a attachable widget that can be added to other dc charts to render horizontal legend * labels. * Examples: * - [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) * - [Canadian City Crime Stats](http://dc-js.github.com/dc.js/crime/index.html) * @name legend * @memberof dc * @example * chart.legend(dc.legend().x(400).y(10).itemHeight(13).gap(5)) * @returns {Legend} */ dc.legend = function () { var LABEL_GAP = 2; var _legend = {}, _parent, _x = 0, _y = 0, _itemHeight = 12, _gap = 5, _horizontal = false, _legendWidth = 560, _itemWidth = 70, _autoItemWidth = false; var _g; _legend.parent = function (p) { if (!arguments.length) { return _parent; } _parent = p; return _legend; }; _legend.render = function () { _parent.svg().select('g.dc-legend').remove(); _g = _parent.svg().append('g') .attr('class', 'dc-legend') .attr('transform', 'translate(' + _x + ',' + _y + ')'); var legendables = _parent.legendables(); var itemEnter = _g.selectAll('g.dc-legend-item') .data(legendables) .enter() .append('g') .attr('class', 'dc-legend-item') .on('mouseover', function (d) { _parent.legendHighlight(d); }) .on('mouseout', function (d) { _parent.legendReset(d); }) .on('click', function (d) { d.chart.legendToggle(d); }); _g.selectAll('g.dc-legend-item') .classed('fadeout', function (d) { return d.chart.isLegendableHidden(d); }); if (legendables.some(dc.pluck('dashstyle'))) { itemEnter .append('line') .attr('x1', 0) .attr('y1', _itemHeight / 2) .attr('x2', _itemHeight) .attr('y2', _itemHeight / 2) .attr('stroke-width', 2) .attr('stroke-dasharray', dc.pluck('dashstyle')) .attr('stroke', dc.pluck('color')); } else { itemEnter .append('rect') .attr('width', _itemHeight) .attr('height', _itemHeight) .attr('fill', function (d) {return d ? d.color : 'blue';}); } itemEnter.append('text') .text(dc.pluck('name')) .attr('x', _itemHeight + LABEL_GAP) .attr('y', function () { return _itemHeight / 2 + (this.clientHeight ? this.clientHeight : 13) / 2 - 2; }); var _cumulativeLegendTextWidth = 0; var row = 0; itemEnter.attr('transform', function (d, i) { if (_horizontal) { var translateBy = 'translate(' + _cumulativeLegendTextWidth + ',' + row * legendItemHeight() + ')'; var itemWidth = _autoItemWidth === true ? this.getBBox().width + _gap : _itemWidth; if ((_cumulativeLegendTextWidth + itemWidth) >= _legendWidth) { ++row ; _cumulativeLegendTextWidth = 0 ; } else { _cumulativeLegendTextWidth += itemWidth; } return translateBy; } else { return 'translate(0,' + i * legendItemHeight() + ')'; } }); }; function legendItemHeight () { return _gap + _itemHeight; } /** * Set or get x coordinate for legend widget. * @name x * @memberof dc.legend * @instance * @param {Number} [x=0] * @returns {Legend} */ _legend.x = function (x) { if (!arguments.length) { return _x; } _x = x; return _legend; }; /** * Set or get y coordinate for legend widget. * @name y * @memberof dc.legend * @instance * @param {Number} [y=0] * @returns {Legend} */ _legend.y = function (y) { if (!arguments.length) { return _y; } _y = y; return _legend; }; /** * Set or get gap between legend items. * @name gap * @memberof dc.legend * @instance * @param {Number} [gap=5] * @returns {Legend} */ _legend.gap = function (gap) { if (!arguments.length) { return _gap; } _gap = gap; return _legend; }; /** * Set or get legend item height. * @name itemHeight * @memberof dc.legend * @instance * @param {Number} [itemHeight=12] * @returns {Legend} */ _legend.itemHeight = function (itemHeight) { if (!arguments.length) { return _itemHeight; } _itemHeight = itemHeight; return _legend; }; /** * Position legend horizontally instead of vertically. * @name horizontal * @memberof dc.legend * @instance * @param {Boolean} [horizontal=false] * @returns {Legend} */ _legend.horizontal = function (horizontal) { if (!arguments.length) { return _horizontal; } _horizontal = horizontal; return _legend; }; /** * Maximum width for horizontal legend. * @name legendWidth * @memberof dc.legend * @instance * @param {Number} [legendWidth=500] * @returns {Legend} */ _legend.legendWidth = function (legendWidth) { if (!arguments.length) { return _legendWidth; } _legendWidth = legendWidth; return _legend; }; /** * legendItem width for horizontal legend. * @name itemWidth * @memberof dc.legend * @instance * @param {Number} [itemWidth=70] * @returns {Legend} */ _legend.itemWidth = function (itemWidth) { if (!arguments.length) { return _itemWidth; } _itemWidth = itemWidth; return _legend; }; /** * Turn automatic width for legend items on or off. If true, itemWidth() is ignored. * This setting takes into account gap(). * @name autoItemWidth * @memberof dc.legend * @instance * @param {Boolean} [autoItemWidth=false] * @returns {Legend} */ _legend.autoItemWidth = function (autoItemWidth) { if (!arguments.length) { return _autoItemWidth; } _autoItemWidth = autoItemWidth; return _legend; }; return _legend; }; /** * A scatter plot chart * @name scatterPlot * @memberof dc * @mixes dc.coordinateGridMixin * @example * // create a scatter plot under #chart-container1 element using the default global chart group * var chart1 = dc.scatterPlot('#chart-container1'); * // create a scatter plot under #chart-container2 element using chart group A * var chart2 = dc.scatterPlot('#chart-container2', 'chartGroupA'); * // create a sub-chart under a composite parent chart * var chart3 = dc.scatterPlot(compositeChart); * @param {String|node|d3.selection|dc.compositeChart} parent - Any valid * [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying * a dom block element such as a div; or a dom element or d3 selection. If the bar chart is a sub-chart * in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {SeriesChart} */ dc.scatterPlot = function (parent, chartGroup) { var _chart = dc.coordinateGridMixin({}); var _symbol = d3.svg.symbol(); var _existenceAccessor = function (d) { return d.value; }; var originalKeyAccessor = _chart.keyAccessor(); _chart.keyAccessor(function (d) { return originalKeyAccessor(d)[0]; }); _chart.valueAccessor(function (d) { return originalKeyAccessor(d)[1]; }); _chart.colorAccessor(function () { return _chart._groupName; }); var _locator = function (d) { return 'translate(' + _chart.x()(_chart.keyAccessor()(d)) + ',' + _chart.y()(_chart.valueAccessor()(d)) + ')'; }; var _symbolSize = 3; var _highlightedSize = 5; var _hiddenSize = 0; _symbol.size(function (d) { if (!_existenceAccessor(d)) { return _hiddenSize; } else if (this.filtered) { return Math.pow(_highlightedSize, 2); } else { return Math.pow(_symbolSize, 2); } }); dc.override(_chart, '_filter', function (filter) { if (!arguments.length) { return _chart.__filter(); } return _chart.__filter(dc.filters.RangedTwoDimensionalFilter(filter)); }); _chart.plotData = function () { var symbols = _chart.chartBodyG().selectAll('path.symbol') .data(_chart.data()); symbols .enter() .append('path') .attr('class', 'symbol') .attr('opacity', 0) .attr('fill', _chart.getColor) .attr('transform', _locator); dc.transition(symbols, _chart.transitionDuration()) .attr('opacity', function (d) { return _existenceAccessor(d) ? 1 : 0; }) .attr('fill', _chart.getColor) .attr('transform', _locator) .attr('d', _symbol); dc.transition(symbols.exit(), _chart.transitionDuration()) .attr('opacity', 0).remove(); }; /** * Get or set the existence accessor. If a point exists, it is drawn with symbolSize radius and * opacity 1; if it does not exist, it is drawn with hiddenSize radius and opacity 0. By default, * the existence accessor checks if the reduced value is truthy. * @name existenceAccessor * @memberof dc.scatterPlot * @instance * @param {Function} [accessor] * @returns {Chart} */ _chart.existenceAccessor = function (accessor) { if (!arguments.length) { return _existenceAccessor; } _existenceAccessor = accessor; return this; }; /** * Get or set the symbol type used for each point. By default the symbol is a circle. See the D3 * [docs](https://github.com/mbostock/d3/wiki/SVG-Shapes#wiki-symbol_type) for acceptable types. * Type can be a constant or an accessor. * @name symbol * @memberof dc.scatterPlot * @instance * @param {Function} [type] * @returns {Chart} */ _chart.symbol = function (type) { if (!arguments.length) { return _symbol.type(); } _symbol.type(type); return _chart; }; /** * Set or get radius for symbols. * @name symbolSize * @memberof dc.scatterPlot * @instance * @param {Number} [symbolSize=3] * @returns {Chart} */ _chart.symbolSize = function (symbolSize) { if (!arguments.length) { return _symbolSize; } _symbolSize = symbolSize; return _chart; }; /** * Set or get radius for highlighted symbols. * @name highlightedSize * @memberof dc.scatterPlot * @instance * @param {Number} [highlightedSize=5] * @returns {Chart} */ _chart.highlightedSize = function (highlightedSize) { if (!arguments.length) { return _highlightedSize; } _highlightedSize = highlightedSize; return _chart; }; /** * Set or get radius for symbols when the group is empty. * @name hiddenSize * @memberof dc.scatterPlot * @instance * @param {Number} [_hiddenSize=0] * @returns {Chart} */ _chart.hiddenSize = function (hiddenSize) { if (!arguments.length) { return _hiddenSize; } _hiddenSize = hiddenSize; return _chart; }; _chart.legendables = function () { return [{chart: _chart, name: _chart._groupName, color: _chart.getColor()}]; }; _chart.legendHighlight = function (d) { resizeSymbolsWhere(function (symbol) { return symbol.attr('fill') === d.color; }, _highlightedSize); _chart.selectAll('.chart-body path.symbol').filter(function () { return d3.select(this).attr('fill') !== d.color; }).classed('fadeout', true); }; _chart.legendReset = function (d) { resizeSymbolsWhere(function (symbol) { return symbol.attr('fill') === d.color; }, _symbolSize); _chart.selectAll('.chart-body path.symbol').filter(function () { return d3.select(this).attr('fill') !== d.color; }).classed('fadeout', false); }; function resizeSymbolsWhere (condition, size) { var symbols = _chart.selectAll('.chart-body path.symbol').filter(function () { return condition(d3.select(this)); }); var oldSize = _symbol.size(); _symbol.size(Math.pow(size, 2)); dc.transition(symbols, _chart.transitionDuration()).attr('d', _symbol); _symbol.size(oldSize); } _chart.setHandlePaths = function () { // no handle paths for poly-brushes }; _chart.extendBrush = function () { var extent = _chart.brush().extent(); if (_chart.round()) { extent[0] = extent[0].map(_chart.round()); extent[1] = extent[1].map(_chart.round()); _chart.g().select('.brush') .call(_chart.brush().extent(extent)); } return extent; }; _chart.brushIsEmpty = function (extent) { return _chart.brush().empty() || !extent || extent[0][0] >= extent[1][0] || extent[0][1] >= extent[1][1]; }; function resizeFiltered (filter) { var symbols = _chart.selectAll('.chart-body path.symbol').each(function (d) { this.filtered = filter && filter.isFiltered(d.key); }); dc.transition(symbols, _chart.transitionDuration()).attr('d', _symbol); } _chart._brushing = function () { var extent = _chart.extendBrush(); _chart.redrawBrush(_chart.g()); if (_chart.brushIsEmpty(extent)) { dc.events.trigger(function () { _chart.filter(null); _chart.redrawGroup(); }); resizeFiltered(false); } else { var ranged2DFilter = dc.filters.RangedTwoDimensionalFilter(extent); dc.events.trigger(function () { _chart.filter(null); _chart.filter(ranged2DFilter); _chart.redrawGroup(); }, dc.constants.EVENT_DELAY); resizeFiltered(ranged2DFilter); } }; _chart.setBrushY = function (gBrush) { gBrush.call(_chart.brush().y(_chart.y())); }; return _chart.anchor(parent, chartGroup); }; /** * A display of a single numeric value. * Unlike other charts, you do not need to set a dimension. Instead a group object must be provided and * a valueAccessor that returns a single value. * @name numberDisplay * @memberof dc * @mixes dc.baseMixin * @example * // create a number display under #chart-container1 element using the default global chart group * var display1 = dc.numberDisplay('#chart-container1'); * @param {String|node|d3.selection|dc.compositeChart} parent - Any valid * [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying * a dom block element such as a div; or a dom element or d3 selection. If the bar chart is a sub-chart * in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {NumberDisplay} */ dc.numberDisplay = function (parent, chartGroup) { var SPAN_CLASS = 'number-display'; var _formatNumber = d3.format('.2s'); var _chart = dc.baseMixin({}); var _html = {one: '', some: '', none: ''}; // dimension not required _chart._mandatoryAttributes(['group']); /** * Gets or sets an optional object specifying HTML templates to use depending on the number * displayed. The text `%number` will be replaced with the current value. * - one: HTML template to use if the number is 1 * - zero: HTML template to use if the number is 0 * - some: HTML template to use otherwise * @name html * @memberof dc.numberDisplay * @instance * @example * numberWidget.html({ * one:'%number record', * some:'%number records', * none:'no records'}) * @param {{one:String, some:String, none:String}} [html={one: '', some: '', none: ''}] * @returns {Chart} */ _chart.html = function (html) { if (!arguments.length) { return _html; } if (html.none) { _html.none = html.none;//if none available } else if (html.one) { _html.none = html.one;//if none not available use one } else if (html.some) { _html.none = html.some;//if none and one not available use some } if (html.one) { _html.one = html.one;//if one available } else if (html.some) { _html.one = html.some;//if one not available use some } if (html.some) { _html.some = html.some;//if some available } else if (html.one) { _html.some = html.one;//if some not available use one } return _chart; }; /** * Calculate and return the underlying value of the display * @name value * @memberof dc.numberDisplay * @instance * @returns {Number} */ _chart.value = function () { return _chart.data(); }; _chart.data(function (group) { var valObj = group.value ? group.value() : group.top(1)[0]; return _chart.valueAccessor()(valObj); }); _chart.transitionDuration(250); // good default _chart._doRender = function () { var newValue = _chart.value(), span = _chart.selectAll('.' + SPAN_CLASS); if (span.empty()) { span = span.data([0]) .enter() .append('span') .attr('class', SPAN_CLASS); } span.transition() .duration(_chart.transitionDuration()) .ease('quad-out-in') .tween('text', function () { var interp = d3.interpolateNumber(this.lastValue || 0, newValue); this.lastValue = newValue; return function (t) { var html = null, num = _chart.formatNumber()(interp(t)); if (newValue === 0 && (_html.none !== '')) { html = _html.none; } else if (newValue === 1 && (_html.one !== '')) { html = _html.one; } else if (_html.some !== '') { html = _html.some; } this.innerHTML = html ? html.replace('%number', num) : num; }; }); }; _chart._doRedraw = function () { return _chart._doRender(); }; /** * Get or set a function to format the value for the display. * @name formatNumber * @memberof dc.numberDisplay * @instance * @param {Function} [formatter=d3.format('.2s')] * @returns {Chart} */ _chart.formatNumber = function (formatter) { if (!arguments.length) { return _formatNumber; } _formatNumber = formatter; return _chart; }; return _chart.anchor(parent, chartGroup); }; /** * A heat map is matrix that represents the values of two dimensions of data using colors. * @name heatMap * @memberof dc * @mixes dc.colorMixin * @mixes dc.marginMixin * @mixes dc.baseMixin * @example * // create a heat map under #chart-container1 element using the default global chart group * var heatMap1 = dc.heatMap('#chart-container1'); * // create a heat map under #chart-container2 element using chart group A * var heatMap2 = dc.heatMap('#chart-container2', 'chartGroupA'); * @param {String|node|d3.selection|dc.compositeChart} parent - Any valid * [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying * a dom block element such as a div; or a dom element or d3 selection. If the bar chart is a sub-chart * in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {HeatMap} */ dc.heatMap = function (parent, chartGroup) { var DEFAULT_BORDER_RADIUS = 6.75; var _chartBody; var _cols; var _rows; var _xBorderRadius = DEFAULT_BORDER_RADIUS; var _yBorderRadius = DEFAULT_BORDER_RADIUS; var _chart = dc.colorMixin(dc.marginMixin(dc.baseMixin({}))); _chart._mandatoryAttributes(['group']); _chart.title(_chart.colorAccessor()); var _colsLabel = function (d) { return d; }; var _rowsLabel = function (d) { return d; }; /** * Set or get the column label function. The chart class uses this function to render * column labels on the X axis. It is passed the column name. * @name colsLabel * @memberof dc.heatMap * @instance * @example * // the default label function just returns the name * chart.colsLabel(function(d) { return d; }); * @param {Function} [labelFunction=function(d) { return d; }] * @returns {Chart} */ _chart.colsLabel = function (labelFunction) { if (!arguments.length) { return _colsLabel; } _colsLabel = labelFunction; return _chart; }; /** * Set or get the row label function. The chart class uses this function to render * row labels on the Y axis. It is passed the row name. * @name rowsLabel * @memberof dc.heatMap * @instance * @example * // the default label function just returns the name * chart.rowsLabel(function(d) { return d; }); * @param {Function} [labelFunction=function(d) { return d; }] * @returns {Chart} */ _chart.rowsLabel = function (labelFunction) { if (!arguments.length) { return _rowsLabel; } _rowsLabel = labelFunction; return _chart; }; var _xAxisOnClick = function (d) { filterAxis(0, d); }; var _yAxisOnClick = function (d) { filterAxis(1, d); }; var _boxOnClick = function (d) { var filter = d.key; dc.events.trigger(function () { _chart.filter(filter); _chart.redrawGroup(); }); }; function filterAxis (axis, value) { var cellsOnAxis = _chart.selectAll('.box-group').filter(function (d) { return d.key[axis] === value; }); var unfilteredCellsOnAxis = cellsOnAxis.filter(function (d) { return !_chart.hasFilter(d.key); }); dc.events.trigger(function () { if (unfilteredCellsOnAxis.empty()) { cellsOnAxis.each(function (d) { _chart.filter(d.key); }); } else { unfilteredCellsOnAxis.each(function (d) { _chart.filter(d.key); }); } _chart.redrawGroup(); }); } dc.override(_chart, 'filter', function (filter) { if (!arguments.length) { return _chart._filter(); } return _chart._filter(dc.filters.TwoDimensionalFilter(filter)); }); function uniq (d, i, a) { return !i || a[i - 1] !== d; } /** * Gets or sets the values used to create the rows of the heatmap, as an array. By default, all * the values will be fetched from the data using the value accessor, and they will be sorted in * ascending order. * @name rows * @memberof dc.heatMap * @instance * @param {Array<String|Number>} [rows] * @returns {Chart} */ _chart.rows = function (rows) { if (arguments.length) { _rows = rows; return _chart; } if (_rows) { return _rows; } var rowValues = _chart.data().map(_chart.valueAccessor()); rowValues.sort(d3.ascending); return d3.scale.ordinal().domain(rowValues.filter(uniq)); }; /** * Gets or sets the keys used to create the columns of the heatmap, as an array. By default, all * the values will be fetched from the data using the key accessor, and they will be sorted in * ascending order. * @name cols * @memberof dc.heatMap * @instance * @param {Array<String|Number>} [cols] * @returns {Chart} */ _chart.cols = function (cols) { if (arguments.length) { _cols = cols; return _chart; } if (_cols) { return _cols; } var colValues = _chart.data().map(_chart.keyAccessor()); colValues.sort(d3.ascending); return d3.scale.ordinal().domain(colValues.filter(uniq)); }; _chart._doRender = function () { _chart.resetSvg(); _chartBody = _chart.svg() .append('g') .attr('class', 'heatmap') .attr('transform', 'translate(' + _chart.margins().left + ',' + _chart.margins().top + ')'); return _chart._doRedraw(); }; _chart._doRedraw = function () { var rows = _chart.rows(), cols = _chart.cols(), rowCount = rows.domain().length, colCount = cols.domain().length, boxWidth = Math.floor(_chart.effectiveWidth() / colCount), boxHeight = Math.floor(_chart.effectiveHeight() / rowCount); cols.rangeRoundBands([0, _chart.effectiveWidth()]); rows.rangeRoundBands([_chart.effectiveHeight(), 0]); var boxes = _chartBody.selectAll('g.box-group').data(_chart.data(), function (d, i) { return _chart.keyAccessor()(d, i) + '\0' + _chart.valueAccessor()(d, i); }); var gEnter = boxes.enter().append('g') .attr('class', 'box-group'); gEnter.append('rect') .attr('class', 'heat-box') .attr('fill', 'white') .on('click', _chart.boxOnClick()); if (_chart.renderTitle()) { gEnter.append('title'); boxes.selectAll('title').text(_chart.title()); } dc.transition(boxes.selectAll('rect'), _chart.transitionDuration()) .attr('x', function (d, i) { return cols(_chart.keyAccessor()(d, i)); }) .attr('y', function (d, i) { return rows(_chart.valueAccessor()(d, i)); }) .attr('rx', _xBorderRadius) .attr('ry', _yBorderRadius) .attr('fill', _chart.getColor) .attr('width', boxWidth) .attr('height', boxHeight); boxes.exit().remove(); var gCols = _chartBody.selectAll('g.cols'); if (gCols.empty()) { gCols = _chartBody.append('g').attr('class', 'cols axis'); } var gColsText = gCols.selectAll('text').data(cols.domain()); gColsText.enter().append('text') .attr('x', function (d) { return cols(d) + boxWidth / 2; }) .style('text-anchor', 'middle') .attr('y', _chart.effectiveHeight()) .attr('dy', 12) .on('click', _chart.xAxisOnClick()) .text(_chart.colsLabel()); dc.transition(gColsText, _chart.transitionDuration()) .text(_chart.colsLabel()) .attr('x', function (d) { return cols(d) + boxWidth / 2; }) .attr('y', _chart.effectiveHeight()); gColsText.exit().remove(); var gRows = _chartBody.selectAll('g.rows'); if (gRows.empty()) { gRows = _chartBody.append('g').attr('class', 'rows axis'); } var gRowsText = gRows.selectAll('text').data(rows.domain()); gRowsText.enter().append('text') .attr('dy', 6) .style('text-anchor', 'end') .attr('x', 0) .attr('dx', -2) .on('click', _chart.yAxisOnClick()) .text(_chart.rowsLabel()); dc.transition(gRowsText, _chart.transitionDuration()) .text(_chart.rowsLabel()) .attr('y', function (d) { return rows(d) + boxHeight / 2; }); gRowsText.exit().remove(); if (_chart.hasFilter()) { _chart.selectAll('g.box-group').each(function (d) { if (_chart.isSelectedNode(d)) { _chart.highlightSelected(this); } else { _chart.fadeDeselected(this); } }); } else { _chart.selectAll('g.box-group').each(function () { _chart.resetHighlight(this); }); } return _chart; }; /** * Gets or sets the handler that fires when an individual cell is clicked in the heatmap. * By default, filtering of the cell will be toggled. * @name boxOnClick * @memberof dc.heatMap * @instance * @param {Function} [handler] * @returns {Chart} */ _chart.boxOnClick = function (handler) { if (!arguments.length) { return _boxOnClick; } _boxOnClick = handler; return _chart; }; /** * Gets or sets the handler that fires when a column tick is clicked in the x axis. * By default, if any cells in the column are unselected, the whole column will be selected, * otherwise the whole column will be unselected. * @name xAxisOnClick * @memberof dc.heatMap * @instance * @param {Function} [handler] * @returns {Chart} */ _chart.xAxisOnClick = function (handler) { if (!arguments.length) { return _xAxisOnClick; } _xAxisOnClick = handler; return _chart; }; /** * Gets or sets the handler that fires when a row tick is clicked in the y axis. * By default, if any cells in the row are unselected, the whole row will be selected, * otherwise the whole row will be unselected. * @name yAxisOnClick * @memberof dc.heatMap * @instance * @param {Function} [handler] * @returns {Chart} */ _chart.yAxisOnClick = function (handler) { if (!arguments.length) { return _yAxisOnClick; } _yAxisOnClick = handler; return _chart; }; /** * Gets or sets the X border radius. Set to 0 to get full rectangles. * @name xBorderRadius * @memberof dc.heatMap * @instance * @param {Number} [xBorderRadius=6.75] * @returns {Chart} */ _chart.xBorderRadius = function (xBorderRadius) { if (!arguments.length) { return _xBorderRadius; } _xBorderRadius = xBorderRadius; return _chart; }; /** * Gets or sets the Y border radius. Set to 0 to get full rectangles. * @name yBorderRadius * @memberof dc.heatMap * @instance * @param {Number} [yBorderRadius=6.75] * @returns {Chart} */ _chart.yBorderRadius = function (yBorderRadius) { if (!arguments.length) { return _yBorderRadius; } _yBorderRadius = yBorderRadius; return _chart; }; _chart.isSelectedNode = function (d) { return _chart.hasFilter(d.key); }; return _chart.anchor(parent, chartGroup); }; // https://github.com/d3/d3-plugins/blob/master/box/box.js (function () { // Inspired by http://informationandvisualization.de/blog/box-plot d3.box = function () { var width = 1, height = 1, duration = 0, domain = null, value = Number, whiskers = boxWhiskers, quartiles = boxQuartiles, tickFormat = null; // For each small multiple… function box (g) { g.each(function (d, i) { d = d.map(value).sort(d3.ascending); var g = d3.select(this), n = d.length, min = d[0], max = d[n - 1]; // Compute quartiles. Must return exactly 3 elements. var quartileData = d.quartiles = quartiles(d); // Compute whiskers. Must return exactly 2 elements, or null. var whiskerIndices = whiskers && whiskers.call(this, d, i), whiskerData = whiskerIndices && whiskerIndices.map(function (i) { return d[i]; }); // Compute outliers. If no whiskers are specified, all data are 'outliers'. // We compute the outliers as indices, so that we can join across transitions! var outlierIndices = whiskerIndices ? d3.range(0, whiskerIndices[0]).concat(d3.range(whiskerIndices[1] + 1, n)) : d3.range(n); // Compute the new x-scale. var x1 = d3.scale.linear() .domain(domain && domain.call(this, d, i) || [min, max]) .range([height, 0]); // Retrieve the old x-scale, if this is an update. var x0 = this.__chart__ || d3.scale.linear() .domain([0, Infinity]) .range(x1.range()); // Stash the new scale. this.__chart__ = x1; // Note: the box, median, and box tick elements are fixed in number, // so we only have to handle enter and update. In contrast, the outliers // and other elements are variable, so we need to exit them! Variable // elements also fade in and out. // Update center line: the vertical line spanning the whiskers. var center = g.selectAll('line.center') .data(whiskerData ? [whiskerData] : []); center.enter().insert('line', 'rect') .attr('class', 'center') .attr('x1', width / 2) .attr('y1', function (d) { return x0(d[0]); }) .attr('x2', width / 2) .attr('y2', function (d) { return x0(d[1]); }) .style('opacity', 1e-6) .transition() .duration(duration) .style('opacity', 1) .attr('y1', function (d) { return x1(d[0]); }) .attr('y2', function (d) { return x1(d[1]); }); center.transition() .duration(duration) .style('opacity', 1) .attr('y1', function (d) { return x1(d[0]); }) .attr('y2', function (d) { return x1(d[1]); }); center.exit().transition() .duration(duration) .style('opacity', 1e-6) .attr('y1', function (d) { return x1(d[0]); }) .attr('y2', function (d) { return x1(d[1]); }) .remove(); // Update innerquartile box. var box = g.selectAll('rect.box') .data([quartileData]); box.enter().append('rect') .attr('class', 'box') .attr('x', 0) .attr('y', function (d) { return x0(d[2]); }) .attr('width', width) .attr('height', function (d) { return x0(d[0]) - x0(d[2]); }) .transition() .duration(duration) .attr('y', function (d) { return x1(d[2]); }) .attr('height', function (d) { return x1(d[0]) - x1(d[2]); }); box.transition() .duration(duration) .attr('y', function (d) { return x1(d[2]); }) .attr('height', function (d) { return x1(d[0]) - x1(d[2]); }); // Update median line. var medianLine = g.selectAll('line.median') .data([quartileData[1]]); medianLine.enter().append('line') .attr('class', 'median') .attr('x1', 0) .attr('y1', x0) .attr('x2', width) .attr('y2', x0) .transition() .duration(duration) .attr('y1', x1) .attr('y2', x1); medianLine.transition() .duration(duration) .attr('y1', x1) .attr('y2', x1); // Update whiskers. var whisker = g.selectAll('line.whisker') .data(whiskerData || []); whisker.enter().insert('line', 'circle, text') .attr('class', 'whisker') .attr('x1', 0) .attr('y1', x0) .attr('x2', width) .attr('y2', x0) .style('opacity', 1e-6) .transition() .duration(duration) .attr('y1', x1) .attr('y2', x1) .style('opacity', 1); whisker.transition() .duration(duration) .attr('y1', x1) .attr('y2', x1) .style('opacity', 1); whisker.exit().transition() .duration(duration) .attr('y1', x1) .attr('y2', x1) .style('opacity', 1e-6) .remove(); // Update outliers. var outlier = g.selectAll('circle.outlier') .data(outlierIndices, Number); outlier.enter().insert('circle', 'text') .attr('class', 'outlier') .attr('r', 5) .attr('cx', width / 2) .attr('cy', function (i) { return x0(d[i]); }) .style('opacity', 1e-6) .transition() .duration(duration) .attr('cy', function (i) { return x1(d[i]); }) .style('opacity', 1); outlier.transition() .duration(duration) .attr('cy', function (i) { return x1(d[i]); }) .style('opacity', 1); outlier.exit().transition() .duration(duration) .attr('cy', function (i) { return x1(d[i]); }) .style('opacity', 1e-6) .remove(); // Compute the tick format. var format = tickFormat || x1.tickFormat(8); // Update box ticks. var boxTick = g.selectAll('text.box') .data(quartileData); boxTick.enter().append('text') .attr('class', 'box') .attr('dy', '.3em') .attr('dx', function (d, i) { return i & 1 ? 6 : -6; }) .attr('x', function (d, i) { return i & 1 ? width : 0; }) .attr('y', x0) .attr('text-anchor', function (d, i) { return i & 1 ? 'start' : 'end'; }) .text(format) .transition() .duration(duration) .attr('y', x1); boxTick.transition() .duration(duration) .text(format) .attr('y', x1); // Update whisker ticks. These are handled separately from the box // ticks because they may or may not exist, and we want don't want // to join box ticks pre-transition with whisker ticks post-. var whiskerTick = g.selectAll('text.whisker') .data(whiskerData || []); whiskerTick.enter().append('text') .attr('class', 'whisker') .attr('dy', '.3em') .attr('dx', 6) .attr('x', width) .attr('y', x0) .text(format) .style('opacity', 1e-6) .transition() .duration(duration) .attr('y', x1) .style('opacity', 1); whiskerTick.transition() .duration(duration) .text(format) .attr('y', x1) .style('opacity', 1); whiskerTick.exit().transition() .duration(duration) .attr('y', x1) .style('opacity', 1e-6) .remove(); }); d3.timer.flush(); } box.width = function (x) { if (!arguments.length) { return width; } width = x; return box; }; box.height = function (x) { if (!arguments.length) { return height; } height = x; return box; }; box.tickFormat = function (x) { if (!arguments.length) { return tickFormat; } tickFormat = x; return box; }; box.duration = function (x) { if (!arguments.length) { return duration; } duration = x; return box; }; box.domain = function (x) { if (!arguments.length) { return domain; } domain = x === null ? x : d3.functor(x); return box; }; box.value = function (x) { if (!arguments.length) { return value; } value = x; return box; }; box.whiskers = function (x) { if (!arguments.length) { return whiskers; } whiskers = x; return box; }; box.quartiles = function (x) { if (!arguments.length) { return quartiles; } quartiles = x; return box; }; return box; }; function boxWhiskers (d) { return [0, d.length - 1]; } function boxQuartiles (d) { return [ d3.quantile(d, 0.25), d3.quantile(d, 0.5), d3.quantile(d, 0.75) ]; } })(); /** * A box plot is a chart that depicts numerical data via their quartile ranges. * Examples: * - [Nasdaq 100 Index](http://dc-js.github.com/dc.js/) * - [Canadian City Crime Stats](http://dc-js.github.com/dc.js/crime/index.html) * @name boxPlot * @memberof dc * @mixes dc.coordinateGridMixin * @example * // create a box plot under #chart-container1 element using the default global chart group * var boxPlot1 = dc.boxPlot('#chart-container1'); * // create a box plot under #chart-container2 element using chart group A * var boxPlot2 = dc.boxPlot('#chart-container2', 'chartGroupA'); * @param {String|node|d3.selection|dc.compositeChart} parent - Any valid * [d3 single selector](https://github.com/mbostock/d3/wiki/Selections#selecting-elements) specifying * a dom block element such as a div; or a dom element or d3 selection. If the bar chart is a sub-chart * in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. * @param {String} [chartGroup] - The name of the chart group this chart instance should be placed in. * Interaction with a chart will only trigger events and redraws within the chart's group. * @returns {BoxPlot} */ dc.boxPlot = function (parent, chartGroup) { var _chart = dc.coordinateGridMixin({}); // Returns a function to compute the interquartile range. function DEFAULT_WHISKERS_IQR (k) { return function (d) { var q1 = d.quartiles[0], q3 = d.quartiles[2], iqr = (q3 - q1) * k, i = -1, j = d.length; /*jshint -W116*/ /*jshint -W035*/ while (d[++i] < q1 - iqr) {} while (d[--j] > q3 + iqr) {} /*jshint +W116*/ return [i, j]; /*jshint +W035*/ }; } var _whiskerIqrFactor = 1.5; var _whiskersIqr = DEFAULT_WHISKERS_IQR; var _whiskers = _whiskersIqr(_whiskerIqrFactor); var _box = d3.box(); var _tickFormat = null; var _boxWidth = function (innerChartWidth, xUnits) { if (_chart.isOrdinal()) { return _chart.x().rangeBand(); } else { return innerChartWidth / (1 + _chart.boxPadding()) / xUnits; } }; // default padding to handle min/max whisker text _chart.yAxisPadding(12); // default to ordinal _chart.x(d3.scale.ordinal()); _chart.xUnits(dc.units.ordinal); // valueAccessor should return an array of values that can be coerced into numbers // or if data is overloaded for a static array of arrays, it should be `Number`. // Empty arrays are not included. _chart.data(function (group) { return group.all().map(function (d) { d.map = function (accessor) { return accessor.call(d, d); }; return d; }).filter(function (d) { var values = _chart.valueAccessor()(d); return values.length !== 0; }); }); /** * Get or set the spacing between boxes as a fraction of box size. Valid values are within 0-1. * See the [d3 docs](https://github.com/mbostock/d3/wiki/Ordinal-Scales#wiki-ordinal_rangeBands) * for a visual description of how the padding is applied. * @name boxPadding * @memberof dc.boxPlot * @instance * @param {Number} [padding=0.8] * @returns {Number} */ _chart.boxPadding = _chart._rangeBandPadding; _chart.boxPadding(0.8); /** * Get or set the outer padding on an ordinal box chart. This setting has no effect on non-ordinal charts * or on charts with a custom `.boxWidth`. Will pad the width by `padding * barWidth` on each side of the chart. * @name outerPadding * @memberof dc.boxPlot * @instance * @param {Number} [padding=0.5] * @returns {Number} */ _chart.outerPadding = _chart._outerRangeBandPadding; _chart.outerPadding(0.5); /** * Get or set the numerical width of the boxplot box. The width may also be a function taking as * parameters the chart width excluding the right and left margins, as well as the number of x * units. * @example * // Using numerical parameter * chart.boxWidth(10); * // Using function * chart.boxWidth((innerChartWidth, xUnits) { ... }); * @name boxWidth * @memberof dc.boxPlot * @instance * @param {Number|Function} [boxWidth=0.5] * @returns {Number|Function} */ _chart.boxWidth = function (boxWidth) { if (!arguments.length) { return _boxWidth; } _boxWidth = d3.functor(boxWidth); return _chart; }; var boxTransform = function (d, i) { var xOffset = _chart.x()(_chart.keyAccessor()(d, i)); return 'translate(' + xOffset + ', 0)'; }; _chart._preprocessData = function () { if (_chart.elasticX()) { _chart.x().domain([]); } }; _chart.plotData = function () { var _calculatedBoxWidth = _boxWidth(_chart.effectiveWidth(), _chart.xUnitCount()); _box.whiskers(_whiskers) .width(_calculatedBoxWidth) .height(_chart.effectiveHeight()) .value(_chart.valueAccessor()) .domain(_chart.y().domain()) .duration(_chart.transitionDuration()) .tickFormat(_tickFormat); var boxesG = _chart.chartBodyG().selectAll('g.box').data(_chart.data(), function (d) { return d.key; }); renderBoxes(boxesG); updateBoxes(boxesG); removeBoxes(boxesG); _chart.fadeDeselectedArea(); }; function renderBoxes (boxesG) { var boxesGEnter = boxesG.enter().append('g'); boxesGEnter .attr('class', 'box') .attr('transform', boxTransform) .call(_box) .on('click', function (d) { _chart.filter(d.key); _chart.redrawGroup(); }); } function updateBoxes (boxesG) { dc.transition(boxesG, _chart.transitionDuration()) .attr('transform', boxTransform) .call(_box) .each(function () { d3.select(this).select('rect.box').attr('fill', _chart.getColor); }); } function removeBoxes (boxesG) { boxesG.exit().remove().call(_box); } _chart.fadeDeselectedArea = function () { if (_chart.hasFilter()) { _chart.g().selectAll('g.box').each(function (d) { if (_chart.isSelectedNode(d)) { _chart.highlightSelected(this); } else { _chart.fadeDeselected(this); } }); } else { _chart.g().selectAll('g.box').each(function () { _chart.resetHighlight(this); }); } }; _chart.isSelectedNode = function (d) { return _chart.hasFilter(d.key); }; _chart.yAxisMin = function () { var min = d3.min(_chart.data(), function (e) { return d3.min(_chart.valueAccessor()(e)); }); return dc.utils.subtract(min, _chart.yAxisPadding()); }; _chart.yAxisMax = function () { var max = d3.max(_chart.data(), function (e) { return d3.max(_chart.valueAccessor()(e)); }); return dc.utils.add(max, _chart.yAxisPadding()); }; /** * Set the numerical format of the boxplot median, whiskers and quartile labels. Defaults to * integer formatting. * @example * // format ticks to 2 decimal places * chart.tickFormat(d3.format('.2f')); * @name tickFormat * @memberof dc.boxPlot * @instance * @param {Function} [tickFormat] * @returns {Number|Function} */ _chart.tickFormat = function (tickFormat) { if (!arguments.length) { return _tickFormat; } _tickFormat = tickFormat; return _chart; }; return _chart.anchor(parent, chartGroup); }; // Renamed functions dc.abstractBubbleChart = dc.bubbleMixin; dc.baseChart = dc.baseMixin; dc.capped = dc.capMixin; dc.colorChart = dc.colorMixin; dc.coordinateGridChart = dc.coordinateGridMixin; dc.marginable = dc.marginMixin; dc.stackableChart = dc.stackMixin; // Expose d3 and crossfilter, so that clients in browserify // case can obtain them if they need them. dc.d3 = d3; dc.crossfilter = crossfilter; return dc;} if(typeof define === "function" && define.amd) { define(["d3", "crossfilter"], _dc); } else if(typeof module === "object" && module.exports) { var _d3 = require('d3'); var _crossfilter = require('crossfilter'); // When using npm + browserify, 'crossfilter' is a function, // since package.json specifies index.js as main function, and it // does special handling. When using bower + browserify, // there's no main in bower.json (in fact, there's no bower.json), // so we need to fix it. if (typeof _crossfilter !== "function") { _crossfilter = _crossfilter.crossfilter; } module.exports = _dc(_d3, _crossfilter); } else { this.dc = _dc(d3, crossfilter); } } )(); //# sourceMappingURL=dc.js.map
import Jasmine from 'jasmine'; console.log('Running specs in node..'); const jasmine = new Jasmine(); jasmine.loadConfigFile('tests/jasmine.conf.json'); jasmine.execute();
/** * @copyright Lloyd Brookes <75pound@gmail.com> */ function copyrightedFunction () {}
'use strict'; var uuid = require('node-uuid'); function getRandomToken() { return uuid.v4(); } function findUser(User, username, callback) { User.find({ usernameToLower: username.toLowerCase() }, (err, users) => { if (err) { throw err; } callback(users[0]); }); } module.exports = function(User) { return { get: (req, res) => { User.find({}, (err, users) => { if (err) { throw err; } res.json(users); }); }, post: (req, res) => { let reqUser = req.body; findUser(User, reqUser.username, user => { if (user) { res.status(400) .json({ msg: 'Duplicated user' }); return; } reqUser.usernameToLower = reqUser.username.toLowerCase(); var user = new User(reqUser); user.save((err) => { if (err) { throw err; } res.json(true); }) }); }, put: (req, res) => { let reqUser = req.body; findUser(User, reqUser.username, (user) => { if (!user || user.authKey !== reqUser.authKey) { res.status(404) .json({ msg: 'Invalid username or password' }) } if (!user.token) { user.token = getRandomToken(); user.save(); } res.json({ username: user.username, token: user.token }) }); } }; }
import Typography from 'typography'; export default new Typography({ baseFontSize: '18px', headerFontFamily: ['Roboto Slab', 'Arial', 'sans-serif'], headerWeight: 300, bodyFontFamily: ['Roboto', 'Arial', 'sans-serif'], });
'use strict'; /** @this */ function $IntervalProvider() { this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser', function($rootScope, $window, $q, $$q, $browser) { var intervals = {}; /** * @ngdoc service * @name $interval * * @description * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay` * milliseconds. * * The return value of registering an interval function is a promise. This promise will be * notified upon each tick of the interval, and will be resolved after `count` iterations, or * run indefinitely if `count` is not defined. The value of the notification will be the * number of iterations that have run. * To cancel an interval, call `$interval.cancel(promise)`. * * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to * move forward by `millis` milliseconds and trigger any functions scheduled to run in that * time. * * <div class="alert alert-warning"> * **Note**: Intervals created by this service must be explicitly destroyed when you are finished * with them. In particular they are not automatically destroyed when a controller's scope or a * directive's element are destroyed. * You should take this into consideration and make sure to always cancel the interval at the * appropriate moment. See the example below for more details on how and when to do this. * </div> * * @param {function()} fn A function that should be called repeatedly. If no additional arguments * are passed (see below), the function is called with the current iteration count. * @param {number} delay Number of milliseconds between each function call. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat * indefinitely. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. * @param {...*=} Pass additional parameters to the executed function. * @returns {promise} A promise which will be notified on each iteration. It will resolve once all iterations of the interval complete. * * @example * <example module="intervalExample" name="interval-service"> * <file name="index.html"> * <script> * angular.module('intervalExample', []) * .controller('ExampleController', ['$scope', '$interval', * function($scope, $interval) { * $scope.format = 'M/d/yy h:mm:ss a'; * $scope.blood_1 = 100; * $scope.blood_2 = 120; * * var stop; * $scope.fight = function() { * // Don't start a new fight if we are already fighting * if ( angular.isDefined(stop) ) return; * * stop = $interval(function() { * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) { * $scope.blood_1 = $scope.blood_1 - 3; * $scope.blood_2 = $scope.blood_2 - 4; * } else { * $scope.stopFight(); * } * }, 100); * }; * * $scope.stopFight = function() { * if (angular.isDefined(stop)) { * $interval.cancel(stop); * stop = undefined; * } * }; * * $scope.resetFight = function() { * $scope.blood_1 = 100; * $scope.blood_2 = 120; * }; * * $scope.$on('$destroy', function() { * // Make sure that the interval is destroyed too * $scope.stopFight(); * }); * }]) * // Register the 'myCurrentTime' directive factory method. * // We inject $interval and dateFilter service since the factory method is DI. * .directive('myCurrentTime', ['$interval', 'dateFilter', * function($interval, dateFilter) { * // return the directive link function. (compile function not needed) * return function(scope, element, attrs) { * var format, // date format * stopTime; // so that we can cancel the time updates * * // used to update the UI * function updateTime() { * element.text(dateFilter(new Date(), format)); * } * * // watch the expression, and update the UI on change. * scope.$watch(attrs.myCurrentTime, function(value) { * format = value; * updateTime(); * }); * * stopTime = $interval(updateTime, 1000); * * // listen on DOM destroy (removal) event, and cancel the next UI update * // to prevent updating time after the DOM element was removed. * element.on('$destroy', function() { * $interval.cancel(stopTime); * }); * } * }]); * </script> * * <div> * <div ng-controller="ExampleController"> * <label>Date format: <input ng-model="format"></label> <hr/> * Current time is: <span my-current-time="format"></span> * <hr/> * Blood 1 : <font color='red'>{{blood_1}}</font> * Blood 2 : <font color='red'>{{blood_2}}</font> * <button type="button" data-ng-click="fight()">Fight</button> * <button type="button" data-ng-click="stopFight()">StopFight</button> * <button type="button" data-ng-click="resetFight()">resetFight</button> * </div> * </div> * * </file> * </example> */ function interval(fn, delay, count, invokeApply) { var hasParams = arguments.length > 4, args = hasParams ? sliceArgs(arguments, 4) : [], setInterval = $window.setInterval, clearInterval = $window.clearInterval, iteration = 0, skipApply = (isDefined(invokeApply) && !invokeApply), deferred = (skipApply ? $$q : $q).defer(), promise = deferred.promise; count = isDefined(count) ? count : 0; promise.$$intervalId = setInterval(function tick() { if (skipApply) { $browser.defer(callback); } else { $rootScope.$evalAsync(callback); } deferred.notify(iteration++); if (count > 0 && iteration >= count) { deferred.resolve(iteration); clearInterval(promise.$$intervalId); delete intervals[promise.$$intervalId]; } if (!skipApply) $rootScope.$apply(); }, delay); intervals[promise.$$intervalId] = deferred; return promise; function callback() { if (!hasParams) { fn(iteration); } else { fn.apply(null, args); } } } /** * @ngdoc method * @name $interval#cancel * * @description * Cancels a task associated with the `promise`. * * @param {Promise=} promise returned by the `$interval` function. * @returns {boolean} Returns `true` if the task was successfully canceled. */ interval.cancel = function(promise) { if (promise && promise.$$intervalId in intervals) { // Interval cancels should not report as unhandled promise. intervals[promise.$$intervalId].promise.catch(noop); intervals[promise.$$intervalId].reject('canceled'); $window.clearInterval(promise.$$intervalId); delete intervals[promise.$$intervalId]; return true; } return false; }; return interval; }]; }
const ngtools = require('@ngtools/webpack'); const webpackMerge = require('webpack-merge'); const commonPartial = require('./webpack/webpack.common'); const clientPartial = require('./webpack/webpack.client'); const serverPartial = require('./webpack/webpack.server'); const prodPartial = require('./webpack/webpack.prod'); const { getAotPlugin } = require('./webpack/webpack.aot'); module.exports = function (options) { options = options || {}; if (options.aot) { console.log(`Running build for ${options.client ? 'client' : 'server'} with AoT Compilation`) } const serverConfig = webpackMerge({}, commonPartial, serverPartial, { plugins: [ getAotPlugin('server', !!options.aot) ] }); let clientConfig = webpackMerge({}, commonPartial, clientPartial, { plugins: [ getAotPlugin('client', !!options.aot) ] }); const configs = []; if (!options.aot) { configs.push(clientConfig, serverConfig); } else if (options.client) { configs.push(clientConfig); } else if (options.server) { configs.push(serverConfig); } return configs; }
import reducer from './reducer'; import Counter from './components/counter'; import * as constants from './constants'; export default { constants, Counter, reducer, };
'use strict'; const MySqlSource = require('sifttt/lib/beam/MySqlSource'); const h = require('highland'); let phrase = (prefix, values, separator) => { let ret = ''; if (values) { ret = prefix + ' ' + ( (Array.isArray(values)) ? values.join(separator && ` ${separator} `) : values ); } return ret; }; class MySqlSource2 extends MySqlSource { constructor(opts) { let query = ` ${phrase('SET SESSION sql_mode =', opts.mode && (opts.mode + ';'))} ${phrase('SELECT', opts.select)} ${phrase('FROM', opts.from)} ${phrase('WHERE', opts.where, 'AND')} ${phrase('ORDER BY', opts.orderBy)} ${phrase('LIMIT', opts.limit)} ; `; if (opts.dryrun || opts.verbose) { console.error(`About to run query: ${query}`); if (opts.dryrun) { process.exit(); } } /** * If there's an sql_mode command at the beginning then we need to allow * for multiple statements to be run, and also drop the first result: */ super( query, { multipleStatements: (opts.mode) ? true : false, drop: (opts.mode) ? 1 : 0, host: opts.dbhostReadonly, user: opts.dbuser, password: opts.dbpass, database: opts.database } ); } getStream() { return h(super.getStream()) .drop(this._options.drop); } } module.exports = MySqlSource2;
'use strict'; var baseAddr = Module.findBaseAddress('example'); console.log('software main executable baseAddr: ' + baseAddr); var strncpy = resolveAddress('0xdf0'); var fuzzed_data; var dst_addr; var dst_len = 0; Interceptor.attach(strncpy, { onEnter: function (args) { console.log('[+] Called strncpy @' + strncpy); console.log('[+] Dest: ' + args[0]); dst_addr = args[0] console.log('[+] Src: ' + args[1]); console.log('[+] Len: ' + args[2]); dst_len = args[2].toInt32() if(args[2].toInt32() > 0){ dumpAddr('Input', args[1], args[2].toInt32()); var buf = Memory.readByteArray(args[1], args[2].toInt32()); send('data', buf); var op = recv('input', function(value, data) { fuzzed_data = data }); op.wait(); } }, onLeave: function (retval) { if(dst_len > 0){ Memory.writeByteArray(dst_addr, fuzzed_data); dumpAddr('Input after fuzzing', dst_addr, dst_len); } console.log('[+] Returned from strncpy: ' + retval); console.log(''); } }); function dumpAddr(info, addr, size) { if (addr.isNull()) return; console.log('Data dump ' + info + ' :'); var buf = Memory.readByteArray(addr, size); console.log(hexdump(buf, { offset: 0, length: size, header: true, ansi: false })); } function resolveAddress(addr) { var offset = ptr(addr); var result = baseAddr.add(offset); console.log('[+] New addr=' + result); return result; }