code
stringlengths
2
1.05M
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M6.5 2c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm9 7.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5S17.83 8 17 8s-1.5.67-1.5 1.5zm3 2.5h-2.84c-.58.01-1.14.32-1.45.86l-.92 1.32L9.72 8c-.37-.63-1.03-.99-1.71-1H5c-1.1 0-2 .9-2 2v6h1.5v7h5V11.61L12.03 16h2.2l.77-1.1V22h4v-5h1v-3.5c0-.82-.67-1.5-1.5-1.5z" }), 'EscalatorWarningOutlined');
/** * 给所有的 Model 扩展功能 * http://mongoosejs.com/docs/plugins.html */ var tools = require('../common/tools'); module.exports = function (schema) { schema.methods.create_at_ago = function () { return tools.formatDate(this.create_at, true); }; schema.methods.updated_at_ago = function () { return tools.formatDate(this.create_at, true); }; };
describe('the canary spec', () => { it('shows the infrastructure works', () => { true.should.be.true(); }); });
import {curryN} from './curryN' import {map} from './map' import {max} from './max' import {reduce} from './reduce' export function converge(fn, transformers) { if (arguments.length === 1) return _transformers => converge(fn, _transformers) const highestArity = reduce((a, b) => max(a, b.length), 0, transformers) return curryN(highestArity, function () { return fn.apply( this, map(g => g.apply(this, arguments), transformers) ) }) }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M12 2c-4.42 0-8 .5-8 4v10c0 .88.39 1.67 1 2.22V20c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h8v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1.78c.61-.55 1-1.34 1-2.22V6c0-3.5-3.58-4-8-4zm5.66 2.99H6.34C6.89 4.46 8.31 4 12 4s5.11.46 5.66.99zm.34 2V10H6V6.99h12zm-.34 9.74l-.29.27H6.63l-.29-.27C6.21 16.62 6 16.37 6 16v-4h12v4c0 .37-.21.62-.34.73z" /><circle cx="8.5" cy="14.5" r="1.5" /><circle cx="15.5" cy="14.5" r="1.5" /></React.Fragment> , 'DirectionsBusOutlined');
(function() { "use strict"; describe('Scale test - ', function() { var helper, RzSliderOptions, $rootScope, $timeout; beforeEach(module('test-helper')); beforeEach(inject(function(TestHelper, _RzSliderOptions_, _$rootScope_, _$timeout_) { helper = TestHelper; RzSliderOptions = _RzSliderOptions_; $rootScope = _$rootScope_; $timeout = _$timeout_; })); afterEach(function() { helper.clean(); }); describe('Linear scale - ', function() { beforeEach(function() { var sliderConf = { value: 10, options: { floor: 0, ceil: 100, step: 10 } }; helper.createSlider(sliderConf); }); it('should have a correct linearValueToPosition', function() { var actual = helper.slider.linearValueToPosition(0, 0, 50); expect(actual).to.equal(0); actual = helper.slider.linearValueToPosition(25, 0, 50); expect(actual.toFixed(2)).to.equal('0.50'); actual = helper.slider.linearValueToPosition(50, 0, 50); expect(actual).to.equal(1); }); it('should have a correct linearPositionToValue', function() { var actual = helper.slider.linearPositionToValue(0, 0, 50); expect(actual).to.equal(0); actual = helper.slider.linearPositionToValue(0.5, 0, 50); expect(actual).to.equal(25); actual = Math.round(helper.slider.linearPositionToValue(1, 0, 50)); expect(actual).to.equal(50); }); }); describe('Logarithm scale - ', function() { beforeEach(function() { var sliderConf = { value: 10, options: { floor: 1, ceil: 100, step: 10, logScale: true } }; helper.createSlider(sliderConf); }); it('should throw an error if floor is 0', function() { var testFn = function() { helper.scope.slider.options.floor = 0; helper.scope.$digest(); }; expect(testFn).to.throw("Can't use floor=0 with logarithmic scale"); }); it('should have a correct logValueToPosition', function() { var actual = helper.slider.logValueToPosition(1, 1, 50); expect(actual).to.equal(0); actual = helper.slider.logValueToPosition(25, 1, 50); expect(actual.toFixed(2)).to.equal('0.82'); actual = helper.slider.logValueToPosition(50, 1, 50); expect(actual).to.equal(1); }); it('should have a correct logPositionToValue', function() { var actual = helper.slider.logPositionToValue(0, 1, 50); expect(actual).to.equal(1); actual = helper.slider.logPositionToValue(0.5, 1, 50); expect(actual.toFixed(2)).to.equal('7.07'); actual = Math.round(helper.slider.logPositionToValue(1, 1, 50)); expect(actual).to.equal(50); }); it('should handle click and drag on minH correctly', function () { helper.fireMousedown(helper.slider.minH, 0); var expectedValue = 50, position = helper.getMousePosition(expectedValue); helper.fireMousemove(position); expect(helper.scope.slider.value).to.equal(expectedValue + 1); // + 1 because we start at 1 }); }); describe('Custom scale (here a x^2 scale)- ', function() { beforeEach(function() { var sliderConf = { value: 50, options: { floor: 0, ceil: 100, step: 10, customValueToPosition: function(val, minVal, maxVal) { val = Math.sqrt(val); minVal = Math.sqrt(minVal); maxVal = Math.sqrt(maxVal); var range = maxVal - minVal; return (val - minVal) / range; }, customPositionToValue: function(percent, minVal, maxVal) { minVal = Math.sqrt(minVal); maxVal = Math.sqrt(maxVal); var value = percent * (maxVal - minVal) + minVal; return Math.pow(value, 2); } } }; helper.createSlider(sliderConf); }); - it('should have a correct valueToPosition', function() { var actual = helper.slider.valueToPosition(0); expect(actual).to.equal(0); actual = helper.slider.valueToPosition(25); expect(actual).to.equal(helper.slider.maxPos / 2); actual = helper.slider.valueToPosition(100); expect(actual).to.equal(helper.slider.maxPos); }); it('should have a correct positionToValue', function() { var actual = helper.slider.positionToValue(0); expect(actual).to.equal(0); actual = helper.slider.positionToValue(helper.slider.maxPos / 2); expect(actual).to.equal(25); actual = Math.round(helper.slider.positionToValue(helper.slider.maxPos)); expect(actual).to.equal(100); }); it('should handle click and drag on minH correctly', function () { helper.fireMousedown(helper.slider.minH, 0); var expectedValue = 50, position = helper.getMousePosition(expectedValue); helper.fireMousemove(position); expect(helper.scope.slider.value).to.equal(expectedValue); }); }); }); }());
var redis = require('redis'); var async = require('async'); var stats = require('./stats.js'); module.exports = function(logger, portalConfig, poolConfigs){ var _this = this; var portalStats = this.stats = new stats(logger, portalConfig, poolConfigs); this.liveStatConnections = {}; this.handleApiRequest = function(req, res, next){ switch(req.params.method){ case 'stats': res.header('Content-Type', 'application/json'); res.end(portalStats.statsString); return; case 'pool_stats': res.header('Content-Type', 'application/json'); res.end(JSON.stringify(portalStats.statPoolHistory)); return; case 'blocks': case 'getblocksstats': portalStats.getBlocks(function(data){ res.header('Content-Type', 'application/json'); res.end(JSON.stringify(data)); }); break; case 'payments': var poolBlocks = []; for(var pool in portalStats.stats.pools) { poolBlocks.push({name: pool, pending: portalStats.stats.pools[pool].pending, payments: portalStats.stats.pools[pool].payments}); } res.header('Content-Type', 'application/json'); res.end(JSON.stringify(poolBlocks)); return; case 'worker_stats': res.header('Content-Type', 'application/json'); if (req.url.indexOf("?")>0) { var url_parms = req.url.split("?"); if (url_parms.length > 0) { var history = {}; var workers = {}; var address = url_parms[1] || null; //res.end(portalStats.getWorkerStats(address)); if (address != null && address.length > 0) { // make sure it is just the miners address address = address.split(".")[0]; // get miners balance along with worker balances portalStats.getBalanceByAddress(address, function(balances) { // get current round share total portalStats.getTotalSharesByAddress(address, function(shares) { var totalHash = parseFloat(0.0); var totalShares = shares; var networkSols = 0; for (var h in portalStats.statHistory) { for(var pool in portalStats.statHistory[h].pools) { for(var w in portalStats.statHistory[h].pools[pool].workers){ if (w.startsWith(address)) { if (history[w] == null) { history[w] = []; } if (portalStats.statHistory[h].pools[pool].workers[w].hashrate) { history[w].push({time: portalStats.statHistory[h].time, hashrate:portalStats.statHistory[h].pools[pool].workers[w].hashrate}); } } } // order check... //console.log(portalStats.statHistory[h].time); } } for(var pool in portalStats.stats.pools) { for(var w in portalStats.stats.pools[pool].workers){ if (w.startsWith(address)) { workers[w] = portalStats.stats.pools[pool].workers[w]; for (var b in balances.balances) { if (w == balances.balances[b].worker) { workers[w].paid = balances.balances[b].paid; workers[w].balance = balances.balances[b].balance; } } workers[w].balance = (workers[w].balance || 0); workers[w].paid = (workers[w].paid || 0); totalHash += portalStats.stats.pools[pool].workers[w].hashrate; networkSols = portalStats.stats.pools[pool].poolStats.networkSols; } } } res.end(JSON.stringify({miner: address, totalHash: totalHash, totalShares: totalShares, networkSols: networkSols, immature: balances.totalImmature, balance: balances.totalHeld, paid: balances.totalPaid, workers: workers, history: history})); }); }); } else { res.end(JSON.stringify({result: "error"})); } } else { res.end(JSON.stringify({result: "error"})); } } else { res.end(JSON.stringify({result: "error"})); } return; case 'live_stats': res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' }); res.write('\n'); var uid = Math.random().toString(); _this.liveStatConnections[uid] = res; res.flush(); req.on("close", function() { delete _this.liveStatConnections[uid]; }); return; default: next(); } }; this.handleAdminApiRequest = function(req, res, next){ switch(req.params.method){ case 'pools': { res.end(JSON.stringify({result: poolConfigs})); return; } default: next(); } }; };
/** * Created by alnedorezov on 5/26/17. */ let Tool = { onClick(isButtonPressed) { } }; // for creating new objects (tools) with a set of properties, but with a particular prototype let fromPrototype = function (prototype, object) { let newObject = Object.create(prototype); for (let prop in object) { if (object.hasOwnProperty(prop)) { newObject[prop] = object[prop]; } } return newObject; };
import React from 'react'; import { render, waitFor, screen } from '@testing-library/react'; import { IntlProvider } from 'react-intl'; import { QueryClient, QueryClientProvider } from 'react-query'; import { ThemeProvider, lightTheme } from '@strapi/design-system'; import ProfilePage from '../index'; import server from './utils/server'; jest.mock('../../../components/LocalesProvider/useLocalesProvider', () => () => ({ changeLocale: () => {}, localeNames: ['en'], messages: ['test'], })); jest.mock('@strapi/helper-plugin', () => ({ ...jest.requireActual('@strapi/helper-plugin'), useNotification: jest.fn(), useFocusWhenNavigate: jest.fn(), useAppInfos: jest.fn(() => ({ setUserDisplayName: jest.fn() })), useOverlayBlocker: jest.fn(() => ({ lockApp: jest.fn, unlockApp: jest.fn() })), })); const client = new QueryClient({ defaultOptions: { queries: { retry: false, }, }, }); const App = ( <QueryClientProvider client={client}> <IntlProvider messages={{}} textComponent="span" locale="en"> <ThemeProvider theme={lightTheme}> <ProfilePage /> </ThemeProvider> </IntlProvider> </QueryClientProvider> ); describe('ADMIN | Pages | Profile page', () => { beforeAll(() => server.listen()); beforeEach(() => { jest.clearAllMocks(); }); afterEach(() => { server.resetHandlers(); }); afterAll(() => { jest.resetAllMocks(); server.close(); }); it('renders and matches the snapshot', async () => { const { container } = render(App); await waitFor(() => { expect(screen.getByText('Interface language')).toBeInTheDocument(); }); expect(container.firstChild).toMatchInlineSnapshot(` .c13 { padding-bottom: 56px; } .c16 { background: #ffffff; padding-top: 24px; padding-right: 32px; padding-bottom: 24px; padding-left: 32px; border-radius: 4px; box-shadow: 0px 1px 4px rgba(33,33,52,0.1); } .c11 { font-weight: 600; color: #32324d; font-size: 0.75rem; line-height: 1.33; } .c8 { padding-right: 8px; } .c5 { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; cursor: pointer; padding: 8px; border-radius: 4px; background: #ffffff; border: 1px solid #dcdce4; position: relative; outline: none; } .c5 svg { height: 12px; width: 12px; } .c5 svg > g, .c5 svg path { fill: #ffffff; } .c5[aria-disabled='true'] { pointer-events: none; } .c5:after { -webkit-transition-property: all; transition-property: all; -webkit-transition-duration: 0.2s; transition-duration: 0.2s; border-radius: 8px; content: ''; position: absolute; top: -4px; bottom: -4px; left: -4px; right: -4px; border: 2px solid transparent; } .c5:focus-visible { outline: none; } .c5:focus-visible:after { border-radius: 8px; content: ''; position: absolute; top: -5px; bottom: -5px; left: -5px; right: -5px; border: 2px solid #4945ff; } .c9 { height: 100%; } .c6 { -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; padding: 8px 16px; background: #4945ff; border: none; border: 1px solid #4945ff; background: #4945ff; } .c6 .c7 { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; } .c6 .c10 { color: #ffffff; } .c6[aria-disabled='true'] { border: 1px solid #dcdce4; background: #eaeaef; } .c6[aria-disabled='true'] .c10 { color: #666687; } .c6[aria-disabled='true'] svg > g, .c6[aria-disabled='true'] svg path { fill: #666687; } .c6[aria-disabled='true']:active { border: 1px solid #dcdce4; background: #eaeaef; } .c6[aria-disabled='true']:active .c10 { color: #666687; } .c6[aria-disabled='true']:active svg > g, .c6[aria-disabled='true']:active svg path { fill: #666687; } .c6:hover { border: 1px solid #7b79ff; background: #7b79ff; } .c6:active { border: 1px solid #4945ff; background: #4945ff; } .c32 { border: none; background: transparent; font-size: 1.6rem; width: auto; padding: 0; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; } .c40 { position: absolute; left: 0; right: 0; bottom: 0; top: 0; width: 100%; background: transparent; border: none; } .c40:focus { outline: none; } .c40[aria-disabled='true'] { cursor: not-allowed; } .c37 { font-weight: 600; color: #32324d; font-size: 0.75rem; line-height: 1.33; } .c44 { color: #32324d; display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-size: 0.875rem; line-height: 1.43; } .c48 { color: #666687; font-size: 0.75rem; line-height: 1.33; } .c43 { padding-right: 16px; padding-left: 16px; } .c46 { padding-left: 12px; } .c38 { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; } .c41 { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-box-pack: justify; -webkit-justify-content: space-between; -ms-flex-pack: justify; justify-content: space-between; -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; } .c36 { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; } .c36 > * { margin-top: 0; margin-bottom: 0; } .c36 > * + * { margin-top: 4px; } .c39 { position: relative; border: 1px solid #dcdce4; padding-right: 12px; border-radius: 4px; background: #ffffff; overflow: hidden; min-height: 2.5rem; outline: none; box-shadow: 0; -webkit-transition-property: border-color,box-shadow,fill; transition-property: border-color,box-shadow,fill; -webkit-transition-duration: 0.2s; transition-duration: 0.2s; } .c39:focus-within { border: 1px solid #4945ff; box-shadow: #4945ff 0px 0px 0px 2px; } .c45 { background: transparent; border: none; position: relative; z-index: 1; } .c45 svg { height: 0.6875rem; width: 0.6875rem; } .c45 svg path { fill: #666687; } .c47 { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; background: none; border: none; } .c47 svg { width: 0.375rem; } .c42 { width: 100%; } .c15 { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; } .c15 > * { margin-top: 0; margin-bottom: 0; } .c15 > * + * { margin-top: 24px; } .c17 { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; } .c17 > * { margin-top: 0; margin-bottom: 0; } .c17 > * + * { margin-top: 16px; } .c34 { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; } .c34 > * { margin-top: 0; margin-bottom: 0; } .c34 > * + * { margin-top: 4px; } .c23 { font-weight: 600; color: #32324d; font-size: 0.75rem; line-height: 1.33; } .c24 { color: #d02b20; font-size: 0.875rem; line-height: 1.43; } .c25 { line-height: 0; } .c31 { padding-right: 12px; padding-left: 8px; } .c22 { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; } .c26 { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-box-pack: justify; -webkit-justify-content: space-between; -ms-flex-pack: justify; justify-content: space-between; -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; } .c28 { border: none; border-radius: 4px; padding-left: 16px; padding-right: 16px; color: #32324d; font-weight: 400; font-size: 0.875rem; display: block; width: 100%; } .c28::-webkit-input-placeholder { color: #8e8ea9; opacity: 1; } .c28::-moz-placeholder { color: #8e8ea9; opacity: 1; } .c28:-ms-input-placeholder { color: #8e8ea9; opacity: 1; } .c28::placeholder { color: #8e8ea9; opacity: 1; } .c28[aria-disabled='true'] { background: inherit; color: inherit; } .c28:focus { outline: none; box-shadow: none; } .c29 { border: none; border-radius: 4px; padding-left: 16px; padding-right: 0; color: #32324d; font-weight: 400; font-size: 0.875rem; display: block; width: 100%; } .c29::-webkit-input-placeholder { color: #8e8ea9; opacity: 1; } .c29::-moz-placeholder { color: #8e8ea9; opacity: 1; } .c29:-ms-input-placeholder { color: #8e8ea9; opacity: 1; } .c29::placeholder { color: #8e8ea9; opacity: 1; } .c29[aria-disabled='true'] { background: inherit; color: inherit; } .c29:focus { outline: none; box-shadow: none; } .c27 { border: 1px solid #dcdce4; border-radius: 4px; background: #ffffff; height: 2.5rem; outline: none; box-shadow: 0; -webkit-transition-property: border-color,box-shadow,fill; transition-property: border-color,box-shadow,fill; -webkit-transition-duration: 0.2s; transition-duration: 0.2s; } .c27:focus-within { border: 1px solid #4945ff; box-shadow: #4945ff 0px 0px 0px 2px; } .c21 { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; } .c21 > * { margin-top: 0; margin-bottom: 0; } .c21 > * + * { margin-top: 4px; } .c18 { color: #32324d; font-weight: 500; font-size: 1rem; line-height: 1.25; } .c35 { color: #32324d; font-size: 0.875rem; line-height: 1.43; } .c0:focus-visible { outline: none; } .c1 { background: #f6f6f9; padding-top: 40px; padding-right: 56px; padding-bottom: 40px; padding-left: 56px; } .c14 { padding-right: 56px; padding-left: 56px; } .c2 { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-box-pack: justify; -webkit-justify-content: space-between; -ms-flex-pack: justify; justify-content: space-between; -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; } .c3 { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; } .c4 { color: #32324d; font-weight: 600; font-size: 2rem; line-height: 1.25; } .c12 { color: #666687; font-size: 1rem; line-height: 1.5; } .c19 { display: grid; grid-template-columns: repeat(12,1fr); gap: 20px; } .c20 { grid-column: span 6; max-width: 100%; } .c30::-ms-reveal { display: none; } .c33 svg { height: 1rem; width: 1rem; } .c33 svg path { fill: #666687; } @media (max-width:68.75rem) { .c20 { grid-column: span 12; } } @media (max-width:34.375rem) { .c20 { grid-column: span; } } <main aria-busy="false" aria-labelledby="main-content-title" class="c0" id="main-content" tabindex="-1" > <form action="#" novalidate="" > <div style="height: 0px;" > <div class="c1" data-strapi-header="true" > <div class="c2" > <div class="c3" > <h1 class="c4" > yolo </h1> </div> <button aria-disabled="false" class="c5 c6" type="submit" > <div aria-hidden="true" class="c7 c8 c9" > <svg fill="none" height="1em" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg" > <path d="M20.727 2.97a.2.2 0 01.286 0l2.85 2.89a.2.2 0 010 .28L9.554 20.854a.2.2 0 01-.285 0l-9.13-9.243a.2.2 0 010-.281l2.85-2.892a.2.2 0 01.284 0l6.14 6.209L20.726 2.97z" fill="#212134" /> </svg> </div> <span class="c10 c11" > Save </span> </button> </div> <p class="c12" /> </div> </div> <div class="c13" > <div class="c14" > <div class="c15" > <div class="c16" > <div class="c17" > <h2 class="c18" > Profile </h2> <div class="c19" > <div class="c20" > <div class="" > <div> <div> <div class="c21" > <div class="c22" > <label class="c23" for="firstname" required="" > First name <span class="c24 c25" > * </span> </label> </div> <div class="c26 c27" > <input aria-disabled="false" aria-invalid="false" class="c28" id="firstname" name="firstname" placeholder="" type="text" value="michoko" /> </div> </div> </div> </div> </div> </div> <div class="c20" > <div class="" > <div> <div> <div class="c21" > <div class="c22" > <label class="c23" for="lastname" > Last name </label> </div> <div class="c26 c27" > <input aria-disabled="false" aria-invalid="false" class="c28" id="lastname" name="lastname" placeholder="" type="text" value="ronronscelestes" /> </div> </div> </div> </div> </div> </div> <div class="c20" > <div class="" > <div> <div> <div class="c21" > <div class="c22" > <label class="c23" for="email" required="" > Email <span class="c24 c25" > * </span> </label> </div> <div class="c26 c27" > <input aria-disabled="false" aria-invalid="false" class="c28" id="email" name="email" placeholder="" type="email" value="michka@michka.fr" /> </div> </div> </div> </div> </div> </div> <div class="c20" > <div class="" > <div> <div> <div class="c21" > <div class="c22" > <label class="c23" for="username" > Username </label> </div> <div class="c26 c27" > <input aria-disabled="false" aria-invalid="false" class="c28" id="username" name="username" placeholder="" type="text" value="yolo" /> </div> </div> </div> </div> </div> </div> </div> </div> </div> <div class="c16" > <div class="c17" > <h2 class="c18" > Change password </h2> <div class="c19" > <div class="c20" > <div class="" > <div> <div> <div class="c21" > <div class="c22" > <label class="c23" for="textinput-1" > Current Password </label> </div> <div class="c26 c27" > <input aria-disabled="false" aria-invalid="false" class="c29 c30" id="textinput-1" name="currentPassword" type="password" value="" /> <div class="c31" > <button aria-label="Hide password" class="c32 c33" type="button" > <svg fill="none" height="1em" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg" > <path d="M4.048 6.875L2.103 4.93a1 1 0 111.414-1.415l16.966 16.966a1 1 0 11-1.414 1.415l-2.686-2.686a12.247 12.247 0 01-4.383.788c-3.573 0-6.559-1.425-8.962-3.783a15.842 15.842 0 01-2.116-2.568 11.096 11.096 0 01-.711-1.211 1.145 1.145 0 010-.875c.124-.258.36-.68.711-1.211.58-.876 1.283-1.75 2.116-2.569.326-.32.663-.622 1.01-.906zm10.539 10.539l-1.551-1.551a4.005 4.005 0 01-4.9-4.9L6.584 9.411a6 6 0 008.002 8.002zM7.617 4.787A12.248 12.248 0 0112 3.998c3.572 0 6.559 1.426 8.961 3.783a15.845 15.845 0 012.117 2.569c.351.532.587.954.711 1.211.116.242.115.636 0 .875-.124.257-.36.68-.711 1.211-.58.876-1.283 1.75-2.117 2.568-.325.32-.662.623-1.01.907l-2.536-2.537a6 6 0 00-8.002-8.002L7.617 4.787zm3.347 3.347A4.005 4.005 0 0116 11.998c0 .359-.047.706-.136 1.037l-4.9-4.901z" fill="#212134" /> </svg> </button> </div> </div> </div> </div> </div> </div> </div> </div> <div class="c19" > <div class="c20" > <div class="" > <div> <div> <div class="c21" > <div class="c22" > <label class="c23" for="textinput-2" > Password </label> </div> <div class="c26 c27" > <input aria-disabled="false" aria-invalid="false" class="c29 c30" id="textinput-2" name="password" type="password" value="" /> <div class="c31" > <button aria-label="Hide password" class="c32 c33" type="button" > <svg fill="none" height="1em" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg" > <path d="M4.048 6.875L2.103 4.93a1 1 0 111.414-1.415l16.966 16.966a1 1 0 11-1.414 1.415l-2.686-2.686a12.247 12.247 0 01-4.383.788c-3.573 0-6.559-1.425-8.962-3.783a15.842 15.842 0 01-2.116-2.568 11.096 11.096 0 01-.711-1.211 1.145 1.145 0 010-.875c.124-.258.36-.68.711-1.211.58-.876 1.283-1.75 2.116-2.569.326-.32.663-.622 1.01-.906zm10.539 10.539l-1.551-1.551a4.005 4.005 0 01-4.9-4.9L6.584 9.411a6 6 0 008.002 8.002zM7.617 4.787A12.248 12.248 0 0112 3.998c3.572 0 6.559 1.426 8.961 3.783a15.845 15.845 0 012.117 2.569c.351.532.587.954.711 1.211.116.242.115.636 0 .875-.124.257-.36.68-.711 1.211-.58.876-1.283 1.75-2.117 2.568-.325.32-.662.623-1.01.907l-2.536-2.537a6 6 0 00-8.002-8.002L7.617 4.787zm3.347 3.347A4.005 4.005 0 0116 11.998c0 .359-.047.706-.136 1.037l-4.9-4.901z" fill="#212134" /> </svg> </button> </div> </div> </div> </div> </div> </div> </div> <div class="c20" > <div class="" > <div> <div> <div class="c21" > <div class="c22" > <label class="c23" for="textinput-3" > Password confirmation </label> </div> <div class="c26 c27" > <input aria-disabled="false" aria-invalid="false" class="c29 c30" id="textinput-3" name="confirmPassword" type="password" value="" /> <div class="c31" > <button aria-label="Hide password" class="c32 c33" type="button" > <svg fill="none" height="1em" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg" > <path d="M4.048 6.875L2.103 4.93a1 1 0 111.414-1.415l16.966 16.966a1 1 0 11-1.414 1.415l-2.686-2.686a12.247 12.247 0 01-4.383.788c-3.573 0-6.559-1.425-8.962-3.783a15.842 15.842 0 01-2.116-2.568 11.096 11.096 0 01-.711-1.211 1.145 1.145 0 010-.875c.124-.258.36-.68.711-1.211.58-.876 1.283-1.75 2.116-2.569.326-.32.663-.622 1.01-.906zm10.539 10.539l-1.551-1.551a4.005 4.005 0 01-4.9-4.9L6.584 9.411a6 6 0 008.002 8.002zM7.617 4.787A12.248 12.248 0 0112 3.998c3.572 0 6.559 1.426 8.961 3.783a15.845 15.845 0 012.117 2.569c.351.532.587.954.711 1.211.116.242.115.636 0 .875-.124.257-.36.68-.711 1.211-.58.876-1.283 1.75-2.117 2.568-.325.32-.662.623-1.01.907l-2.536-2.537a6 6 0 00-8.002-8.002L7.617 4.787zm3.347 3.347A4.005 4.005 0 0116 11.998c0 .359-.047.706-.136 1.037l-4.9-4.901z" fill="#212134" /> </svg> </button> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> <div class="c16" > <div class="c17" > <div class="c34" > <h2 class="c18" > Experience </h2> <span class="c35" > Selection will change the interface language only for you. Please refer to this <a href="https://docs.strapi.io/developer-docs/latest/development/admin-customization.html#locales" rel="noopener noreferrer" target="_blank" > documentation </a> to make other languages available for your team. </span> </div> <div class="c19" > <div class="c20" > <div class="" > <div> <div class="c36" > <span class="c37" for="select-1" id="select-1-label" > Interface language </span> <div class="c38 c39" > <button aria-describedby="select-1-hint" aria-disabled="false" aria-expanded="false" aria-haspopup="listbox" aria-labelledby="select-1-label select-1-content" class="c40" id="select-1" type="button" /> <div class="c41 c42" > <div class="c38" > <div class="c43" > <span class="c44" id="select-1-content" > Select </span> </div> </div> <div class="c38" > <button aria-disabled="false" aria-label="Clear the interface language selected" class="c45" > <svg fill="none" height="1em" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg" > <path d="M24 2.417L21.583 0 12 9.583 2.417 0 0 2.417 9.583 12 0 21.583 2.417 24 12 14.417 21.583 24 24 21.583 14.417 12 24 2.417z" fill="#212134" /> </svg> </button> <button aria-hidden="true" class="c46 c45 c47" tabindex="-1" type="button" > <svg fill="none" height="1em" viewBox="0 0 14 8" width="1em" xmlns="http://www.w3.org/2000/svg" > <path clip-rule="evenodd" d="M14 .889a.86.86 0 01-.26.625L7.615 7.736A.834.834 0 017 8a.834.834 0 01-.615-.264L.26 1.514A.861.861 0 010 .889c0-.24.087-.45.26-.625A.834.834 0 01.875 0h12.25c.237 0 .442.088.615.264a.86.86 0 01.26.625z" fill="#32324D" fill-rule="evenodd" /> </svg> </button> </div> </div> </div> <p class="c48" id="select-1-hint" > This will only display your own interface in the chosen language. </p> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </form> </main> `); }); it('should display username if it exists', async () => { render(App); await waitFor(() => { expect(screen.getByText('yolo')).toBeInTheDocument(); }); }); test.todo('should display firstname/lastname when the username is null'); });
'use strict'; var AppDispatcher = require('../dispatcher/AppDispatcher'); var VotesConstants = require('../constants/VotesConstants'); var api = require('../utils/api'); var VotesActions = { fetch: function () { api.votes.get(function (err, votes) { if (err) return console.error(err); VotesActions.set(votes); }.bind(this)); }, set: function (votes) { AppDispatcher.handleViewAction({ actionType: VotesConstants.VOTES_SET, data: votes }); }, doVote: function() { api.votes.post(function (err) { if (err) console.error(err); }); } }; module.exports = VotesActions;
'use strict'; /** * Input node that take a recording device as input * @ngdoc service * @name webClientSideApp.Inputnode * @description * # Inputnode * Factory in the webClientSideApp. */ angular.module('webClientSideApp') .factory('Inputnode', function ($http, $log, AbstractSoundnode) { // Service logic function Inputnode() {} Inputnode.prototype = Object.create(AbstractSoundnode.prototype); Inputnode.prototype.type = 'input'; Inputnode.prototype.ready = false; Inputnode.prototype.play = false; Inputnode.prototype.music = null; Inputnode.prototype.playSound = null; Inputnode.prototype.output = null; Inputnode.prototype.labelButton = 'PLAY'; Inputnode.prototype.connect = function(output) { $log.debug('input conection'); if(this.output !== null) { $log.debug('connecting output of input'); this.output.connect(output.getInput()); } if(this.playSound !== null) { $log.debug('connecting playSound of input on '+output.id); $log.debug(output); this.playSound.connect(output.getInput()); } }; Inputnode.prototype.disconnect = function (output) { if(this.output !== null) this.output.disconnect(); if(this.playSound !== null) this.playSound.disconnect(); }; Inputnode.prototype.initNode = function(audioContext) { }; Inputnode.prototype.buttonMusic = function() { if(this.ready) { if(this.play) { this.labelButton = 'PLAY'; this.playSound.stop(0); this.play = false; } else { this.labelButton = 'STOP'; this.playSound.start(0); this.play = true; } } }; Inputnode.prototype.getInput = function() { return null; }; Inputnode.prototype.getOutput = function() { return [this.output, this.playSound]; }; // Public API here return Inputnode; });
{ "addButtonText": "Aggiungere", "addItemHeader": "Aggiungere", "cancelText": "Annulla", "confirmDeletion": "Sei sicuro?", "deleteText": "Elimina", "emptyDataText": "Nessun record trovato.", "errorDataText": "Errore nei dati.", "insertItemText": "Aggiungi", "loadingText": "Caricamento in corso ...", "modifyItemHeader": "Modificare", "modifyText": "Modifica", "saveText": "Salva" }
define([ 'client/controllers/services', 'client/views/table', 'common/collections/services', 'backbone', 'extensions/models/model', 'jquery' ], function (ServicesController, TableView, ServicesCollection, Backbone) { describe('Services view', function () { it('should render the view when a filter event occurs', function () { var controller, model = new Backbone.Model(), collection = new ServicesCollection([], { axes:{} }); spyOn(ServicesCollection.prototype, 'filterServices').andCallFake(function () { return [{}]; }); spyOn(TableView.prototype, 'render'); controller = new ServicesController({ model: model, collection: collection }); controller.renderView({ el: '<div class="#content"><div class="visualisation-table"></div>', model: model, collection: collection }); // will have been called once on initial render, so reset calls count TableView.prototype.render.reset(); controller.view.filter('filter'); expect(TableView.prototype.render.calls.length).toEqual(1); }); }); });
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; it('renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(<App />, div); ReactDOM.unmountComponentAtNode(div); });
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zM7 9c0-2.76 2.24-5 5-5s5 2.24 5 5c0 2.88-2.88 7.19-5 9.88C9.92 16.21 7 11.85 7 9z" /><circle cx="12" cy="9" r="2.5" /></React.Fragment> , 'LocationOnOutlined');
/*! * CanJS - 2.2.7 * http://canjs.com/ * Copyright (c) 2015 Bitovi * Fri, 24 Jul 2015 20:57:32 GMT * Licensed MIT */ /*can@2.2.7#util/util*/ steal('can/util/jquery', function (can) { return can; });
var ioc = { dataSource : { type : "org.apache.commons.dbcp.BasicDataSource", events : { depose : 'close' }, fields : { driverClassName : 'org.h2.Driver', url : 'jdbc:localhost:3306/weifang', username : 'weifang', password : 'titps4gg' } }, dao : { type : "org.nutz.dao.impl.NutDao", fields : { dataSource : {refer : 'dataSource'} } } }
import debug from '../debug' export default { rule ({ path }) { return { beforeCreate () { debug.assertModule(this.$vuet, path) }, destroyed () { this.$vuet.getModule(path).reset() } } } }
/** * React Static Boilerplate * https://github.com/koistya/react-static-boilerplate * Copyright (c) Konstantin Tarkus (@koistya) | MIT license */ import React, { PropTypes } from 'react'; import './Layout.scss'; function Layout({ children }) { return ( <div className="Layout"> {children} </div> ); } Layout.propTypes = { children: PropTypes.element.isRequired, }; export default Layout;
import { StringWrapper, isBlank, isPresent } from '../facade/lang'; import { HtmlCommentAst, HtmlElementAst, HtmlTextAst, htmlVisitAll } from '../html_ast'; import { ParseError } from '../parse_util'; import { Message } from './message'; export const I18N_ATTR = 'i18n'; export const I18N_ATTR_PREFIX = 'i18n-'; var CUSTOM_PH_EXP = /\/\/[\s\S]*i18n[\s\S]*\([\s\S]*ph[\s\S]*=[\s\S]*"([\s\S]*?)"[\s\S]*\)/g; /** * An i18n error. */ export class I18nError extends ParseError { constructor(span, msg) { super(span, msg); } } export function partition(nodes, errors, implicitTags) { let parts = []; for (let i = 0; i < nodes.length; ++i) { let n = nodes[i]; let temp = []; if (_isOpeningComment(n)) { let i18n = n.value.replace(/^i18n:?/, '').trim(); i++; while (!_isClosingComment(nodes[i])) { temp.push(nodes[i++]); if (i === nodes.length) { errors.push(new I18nError(n.sourceSpan, 'Missing closing \'i18n\' comment.')); break; } } parts.push(new Part(null, null, temp, i18n, true)); } else if (n instanceof HtmlElementAst) { let i18n = _findI18nAttr(n); let hasI18n = isPresent(i18n) || implicitTags.indexOf(n.name) > -1; parts.push(new Part(n, null, n.children, isPresent(i18n) ? i18n.value : null, hasI18n)); } else if (n instanceof HtmlTextAst) { parts.push(new Part(null, n, null, null, false)); } } return parts; } export class Part { constructor(rootElement, rootTextNode, children, i18n, hasI18n) { this.rootElement = rootElement; this.rootTextNode = rootTextNode; this.children = children; this.i18n = i18n; this.hasI18n = hasI18n; } get sourceSpan() { if (isPresent(this.rootElement)) { return this.rootElement.sourceSpan; } if (isPresent(this.rootTextNode)) { return this.rootTextNode.sourceSpan; } return this.children[0].sourceSpan; } createMessage(parser) { return new Message(stringifyNodes(this.children, parser), meaning(this.i18n), description(this.i18n)); } } function _isOpeningComment(n) { return n instanceof HtmlCommentAst && isPresent(n.value) && n.value.startsWith('i18n'); } function _isClosingComment(n) { return n instanceof HtmlCommentAst && isPresent(n.value) && n.value == '/i18n'; } function _findI18nAttr(p) { let attrs = p.attrs; for (let i = 0; i < attrs.length; i++) { if (attrs[i].name === I18N_ATTR) { return attrs[i]; } } return null; } export function meaning(i18n) { if (isBlank(i18n) || i18n == '') return null; return i18n.split('|')[0]; } export function description(i18n) { if (isBlank(i18n) || i18n == '') return null; let parts = i18n.split('|', 2); return parts.length > 1 ? parts[1] : null; } /** * Extract a translation string given an `i18n-` prefixed attribute. * * @internal */ export function messageFromI18nAttribute(parser, p, i18nAttr) { let expectedName = i18nAttr.name.substring(5); let attr = p.attrs.find(a => a.name == expectedName); if (attr) { return messageFromAttribute(parser, attr, meaning(i18nAttr.value), description(i18nAttr.value)); } throw new I18nError(p.sourceSpan, `Missing attribute '${expectedName}'.`); } export function messageFromAttribute(parser, attr, meaning = null, description = null) { let value = removeInterpolation(attr.value, attr.sourceSpan, parser); return new Message(value, meaning, description); } export function removeInterpolation(value, source, parser) { try { let parsed = parser.splitInterpolation(value, source.toString()); let usedNames = new Map(); if (isPresent(parsed)) { let res = ''; for (let i = 0; i < parsed.strings.length; ++i) { res += parsed.strings[i]; if (i != parsed.strings.length - 1) { let customPhName = getPhNameFromBinding(parsed.expressions[i], i); customPhName = dedupePhName(usedNames, customPhName); res += `<ph name="${customPhName}"/>`; } } return res; } else { return value; } } catch (e) { return value; } } export function getPhNameFromBinding(input, index) { let customPhMatch = StringWrapper.split(input, CUSTOM_PH_EXP); return customPhMatch.length > 1 ? customPhMatch[1] : `${index}`; } export function dedupePhName(usedNames, name) { let duplicateNameCount = usedNames.get(name); if (isPresent(duplicateNameCount)) { usedNames.set(name, duplicateNameCount + 1); return `${name}_${duplicateNameCount}`; } else { usedNames.set(name, 1); return name; } } export function stringifyNodes(nodes, parser) { let visitor = new _StringifyVisitor(parser); return htmlVisitAll(visitor, nodes).join(''); } class _StringifyVisitor { constructor(_parser) { this._parser = _parser; this._index = 0; } visitElement(ast, context) { let name = this._index++; let children = this._join(htmlVisitAll(this, ast.children), ''); return `<ph name="e${name}">${children}</ph>`; } visitAttr(ast, context) { return null; } visitText(ast, context) { let index = this._index++; let noInterpolation = removeInterpolation(ast.value, ast.sourceSpan, this._parser); if (noInterpolation != ast.value) { return `<ph name="t${index}">${noInterpolation}</ph>`; } return ast.value; } visitComment(ast, context) { return ''; } visitExpansion(ast, context) { return null; } visitExpansionCase(ast, context) { return null; } _join(strs, str) { return strs.filter(s => s.length > 0).join(str); } } //# sourceMappingURL=shared.js.map
var elasticsearch = require('elasticsearch'); var elasticClient = new elasticsearch.Client({ host: 'localhost:9200', log: 'info' }); var indexName = "randomindex"; /** * Delete an existing index */ function deleteIndex() { return elasticClient.indices.delete({ index: indexName }); } exports.deleteIndex = deleteIndex; /** * create the index */ function initIndex() { return elasticClient.indices.create({ index: indexName }); } exports.initIndex = initIndex; /** * check if the index exists */ function indexExists() { return elasticClient.indices.exists({ index: indexName }); } exports.indexExists = indexExists; function initMapping() { return elasticClient.indices.putMapping({ index: indexName, type: "document", body: { properties: { title: { type: "string" }, content: { type: "string" }, suggest: { type: "completion", analyzer: "simple", search_analyzer: "simple", payloads: true } } } }); } exports.initMapping = initMapping; function addDocument(document) { return elasticClient.index({ index: indexName, type: "document", body: { title: document.title, content: document.content, suggest: { input: document.title.split(" "), output: document.title, payload: document.metadata || {} } } }); } exports.addDocument = addDocument; function getSuggestions(input) { return elasticClient.suggest({ index: indexName, type: "document", body: { docsuggest: { text: input, completion: { field: "suggest", fuzzy: true } } } }) } exports.getSuggestions = getSuggestions;
//============================================================================= // Yanfly Engine Plugins - Save Event Locations // YEP_SaveEventLocations.js //============================================================================= var Imported = Imported || {}; Imported.YEP_SaveEventLocations = true; var Yanfly = Yanfly || {}; Yanfly.SEL = Yanfly.SEL || {}; //============================================================================= /*: * @plugindesc v1.00 Enable specified maps to memorize the locations of * events when leaving and loading them upon reentering map. * @author Yanfly Engine Plugins * * @help * ============================================================================ * Introduction * ============================================================================ * * Normally in RPG Maker MV, leaving a map and returning to it will reset the * map positions of all the events. For certain types of maps, such as puzzles, * you would want the map to retain their locations. * * ============================================================================ * Notetags * ============================================================================ * * Map Notetag: * <Save Event Locations> * This will cause the map to save every event's location on that map. After * leaving and returning to that map, the events will be reloaded onto their * last saved positions in addition to the direction they were facing. * * Event Notetag: * <Save Event Location> * This will enable this specific event to save its location on this map. * After leaving and returning to the map, the event will be reloaded onto * its last saved position in addition to the direction it was facing. * * If you wish to reset the position of the Event, simply use the Event Editor * and use "Set Event Location" to anchor the event's location to the desired * point as if you would normally. * * ============================================================================ * Plugin Commands * ============================================================================ * * Plugin Command * ResetAllEventLocations This resets all the event locations on the map. */ //============================================================================= //============================================================================= // DataManager //============================================================================= DataManager.processSELNotetags1 = function() { if (!$dataMap) return; if (!$dataMap.note) return; var notedata = $dataMap.note.split(/[\r\n]+/); $dataMap.saveEventLocations = false; for (var i = 0; i < notedata.length; i++) { var line = notedata[i]; if (line.match(/<(?:SAVE EVENT LOCATION|save event locations)>/i)) { $dataMap.saveEventLocations = true; } } }; DataManager.processSELNotetags2 = function(obj) { var notedata = obj.note.split(/[\r\n]+/); obj.saveEventLocation = false; for (var i = 0; i < notedata.length; i++) { var line = notedata[i]; if (line.match(/<(?:SAVE EVENT LOCATION|save event locations)>/i)) { obj.saveEventLocation = true; } } }; //============================================================================= // Game_System //============================================================================= Yanfly.SEL.Game_System_initialize = Game_System.prototype.initialize; Game_System.prototype.initialize = function() { Yanfly.SEL.Game_System_initialize.call(this); this.initSavedEventLocations(); }; Game_System.prototype.initSavedEventLocations = function() { this._savedEventLocations = {}; }; Game_System.prototype.savedEventLocations = function() { if (this._savedEventLocations === undefined) this.initSavedEventLocations(); return this._savedEventLocations; }; Game_System.prototype.isSavedEventLocation = function(mapId, eventId) { if (this._savedEventLocations === undefined) this.initSavedEventLocations(); return this._savedEventLocations[[mapId, eventId]] !== undefined; }; Game_System.prototype.getSavedEventX = function(mapId, eventId) { if (this._savedEventLocations === undefined) this.initSavedEventLocations(); return this._savedEventLocations[[mapId, eventId]][0]; }; Game_System.prototype.getSavedEventY = function(mapId, eventId) { if (this._savedEventLocations === undefined) this.initSavedEventLocations(); return this._savedEventLocations[[mapId, eventId]][1]; }; Game_System.prototype.getSavedEventDir = function(mapId, eventId) { if (this._savedEventLocations === undefined) this.initSavedEventLocations(); return this._savedEventLocations[[mapId, eventId]][2]; }; Game_System.prototype.saveEventLocation = function(mapId, event) { if (this._savedEventLocations === undefined) this.initSavedEventLocations(); var eventId = event.eventId(); var eventX = event.x; var eventY = event.y; var eventDir = event.direction(); this._savedEventLocations[[mapId, eventId]] = [eventX, eventY, eventDir]; }; //============================================================================= // Game_Map //============================================================================= Yanfly.SEL.Game_Map_setup = Game_Map.prototype.setup; Game_Map.prototype.setup = function(mapId) { if ($dataMap) DataManager.processSELNotetags1(); Yanfly.SEL.Game_Map_setup.call(this, mapId); }; Game_Map.prototype.isSaveEventLocations = function() { return $dataMap.saveEventLocations; }; Game_Map.prototype.resetAllEventLocations = function() { for (var i = 0; i < this.events().length; ++i) { var ev = this.events()[i]; ev.resetLocation(); } }; //============================================================================= // Game_Event //============================================================================= Yanfly.SEL.Game_Event_locate = Game_Event.prototype.locate; Game_Event.prototype.locate = function(x, y) { DataManager.processSELNotetags2(this.event()); Yanfly.SEL.Game_Event_locate.call(this, x, y); this.loadLocation(); }; Yanfly.SEL.Game_Event_updateMove = Game_Event.prototype.updateMove; Game_Event.prototype.updateMove = function() { Yanfly.SEL.Game_Event_updateMove.call(this); this.saveLocation(); }; Game_Event.prototype.isSaveLocation = function() { if ($gameMap.isSaveEventLocations()) return true; return this.event().saveEventLocation; }; Game_Event.prototype.saveLocation = function() { if (!this.isSaveLocation()) return; $gameSystem.saveEventLocation($gameMap.mapId(), this); }; Game_Event.prototype.isLoadLocation = function() { if (!this.isSaveLocation()) return false; return $gameSystem.isSavedEventLocation($gameMap.mapId(), this.eventId()); }; Game_Event.prototype.loadLocation = function() { if (!this.isLoadLocation()) return; var x = $gameSystem.getSavedEventX($gameMap.mapId(), this.eventId()); var y = $gameSystem.getSavedEventY($gameMap.mapId(), this.eventId()); this.setPosition(x, y); var dir = $gameSystem.getSavedEventDir($gameMap.mapId(), this.eventId()); this.setDirection(dir); }; Game_Event.prototype.resetLocation = function() { Yanfly.SEL.Game_Event_locate.call(this, this.event().x, this.event().y); this.setDirection(this._originalDirection); }; //============================================================================= // Game_Interpreter //============================================================================= Yanfly.SEL.Game_Interpreter_pluginCommand = Game_Interpreter.prototype.pluginCommand; Game_Interpreter.prototype.pluginCommand = function(command, args) { Yanfly.SEL.Game_Interpreter_pluginCommand.call(this, command, args) if (command === 'ResetAllEventLocations') $gameMap.resetAllEventLocations(); }; //============================================================================= // End of File //=============================================================================
/** @jsx React.DOM */ /** * Reusable titled section for the home page */ var Loader = require('./loading-spinner'); module.exports = React.createClass({ mixins: ['modelAware'], render: function() { var props = this.props, icon = props.icon, model = this.getModel(); var headerChildren = []; if (icon) { headerChildren.push(<i className={'icon ' + icon}></i>); } if (props.title) { headerChildren.push(this.props.title); } var children = []; if (headerChildren.length) { children.push(<h3 className="header item">{headerChildren}</h3>); } children.push( <div className="body"> <Loader model={model}> <div className="attached top"> {this.props.children} </div> </Loader> </div> ); return ( <section className={'ui segment tile ' + (this.props.size || 'natural') + (' ' + this.props.className || '')}> {children} </section> ); } });
AclEditorController = function( dialog ) { this.dialog = dialog; this.dialog.setTitle( AclEditorController.DIALOG_TITLE ); this.aclCtrl = dialog.getAclEditorCtrl(); this.dialog.enableOkBtnEl( false ); var localThis = this; dialog.setOnSaveHandler( function( event ) { var value = localThis.aclCtrl.getValue(); localThis.saveAcl( value ); } ); dialog.setOnCancelHandler( function( event ) { localThis.dialog.hide(); } ); // as soon as any checkbox is modified, enable the Ok button this.aclCtrl.setOnItemCheckHandler( function( event ) { localThis.dialog.enableOkBtnEl( localThis.canEnableOkBtn() ); } ); }; /*private static*/AclEditorController.PENTAHO_HTTP_WEBSERVICE_URL = "../ServiceAction"; /*private static*/AclEditorController.SOLUTION_REPOSITORY_WEBSERVICE_URL = "../SolutionRepositoryService"; // TODO sbarkdull, need to localize text /*private static*/AclEditorController.FILE_LABEL = Messages.getString( "PATH_LABEL" ); /*private static*/AclEditorController.DIALOG_TITLE = Messages.getString( "SHARE_PERMISSIONS" ); /** * */ AclEditorController.prototype.loadPage = function( solution, path, filename ) { this.solution = solution; this.path = path; this.filename = filename; var localThis = this; this.aclCtrl.setTitle( AclEditorController.FILE_LABEL + "/" + solution + ( path != "" ? "/" : "" ) + path + "/" + filename ); this.loadUsers( function( xmlDoc ) { if ( undefined != xmlDoc ) { var errorMsg = XmlUtil.getErrorMsg( xmlDoc ); if ( !errorMsg ) { localThis.aclCtrl.setUsers( xmlDoc ); } else { alert( errorMsg ); // TODO sbarkdull, better msg UI? } } // start loadRoles -------------------------- localThis.loadRoles( function( xmlDoc ) { if ( undefined != xmlDoc ) { var errorMsg = XmlUtil.getErrorMsg( xmlDoc ); if ( !errorMsg ) { localThis.aclCtrl.setRoles( xmlDoc ); } else { alert( errorMsg ); // TODO sbarkdull, better msg UI? } } // start loadAcl -------------------------- localThis.loadAcl( function( xmlDoc ) { if ( undefined != xmlDoc ) { var errorMsg = XmlUtil.getErrorMsg( xmlDoc ); if ( !errorMsg ) { localThis.aclCtrl.setAcl( xmlDoc ); } else { alert( errorMsg ); // TODO sbarkdull, better msg UI? } } } ); // end loadAcl -------------------------- } ); // end loadRoles -------------------------- } ); }; AclEditorController.prototype.saveAcl = function( strXml ) { // TODO sbarkdull, show "working" and "hour glass", see WAQR code this.dialog.enableOkBtnEl( false ); this.dialog.enableCancelBtnEl( false ); var localThis = this; WebServiceProxy.post( AclEditorController.SOLUTION_REPOSITORY_WEBSERVICE_URL, "setAcl", { solution: this.solution, path: this.path, filename: this.filename, aclXml: strXml }, function( xmlDoc ) { localThis.dialog.enableOkBtnEl( true ); localThis.dialog.enableCancelBtnEl( true ); if ( undefined != xmlDoc ) { var errorMsg = XmlUtil.getErrorMsg( xmlDoc ); if ( errorMsg ) { alert( errorMsg ); // TODO sbarkdull, better msg UI? } else { localThis.dialog.hide(); // NO NEED TO SHOW DIALOG SAYING SAVE WORKED, USEFUL FOR DEBUGGING // var statusMsg = XmlUtil.getStatusMsg( xmlDoc ); // if ( statusMsg ) // { // alert( statusMsg ); // } } } } ); }; AclEditorController.prototype.loadAcl = function( onLoadHandler ) { var localThis = this; WebServiceProxy.post( AclEditorController.SOLUTION_REPOSITORY_WEBSERVICE_URL, "getAcl", { solution: localThis.solution, path: localThis.path, filename: localThis.filename }, onLoadHandler ); }; AclEditorController.prototype.loadUsers = function( onLoadHandler ) { var localThis = this; WebServiceProxy.post( AclEditorController.PENTAHO_HTTP_WEBSERVICE_URL, undefined, { action:"securitydetails", details:"users" }, onLoadHandler ); }; AclEditorController.prototype.loadRoles = function( onLoadHandler ) { var localThis = this; WebServiceProxy.post( AclEditorController.PENTAHO_HTTP_WEBSERVICE_URL, undefined, { action:"securitydetails", details:"roles" }, onLoadHandler ); }; AclEditorController.prototype.canEnableOkBtn = function() { return true; };
/** * Created by zoey on 2015/6/26. */ var response = require('../routes/common/response'); var fs = require('fs'); var path = require('path'); var config = require('../config').config; /** * 上传模块 **/ exports.upload_img = function(req, res) { var callback=null; // Parse file. if(req.files) { var file=req.files.img; // Read file. fs.readFile(file.path, function (err, data) { var name=new Date().getTime()+'.'+file.name.split('\.')[1]; console.log(config.upload_talk_dir); var p = path.join(config.upload_talk_dir, name); // Save file. fs.writeFile(p, data, 'utf8', function (err) { if (err) { console.log(err) return res.json(response.buildError('Something went wrong!')); } else { // res.json(response.buildOK('/uploads/'+p)); var up_img='http://115.29.42.238:5000/upload/talk/img/'+name; return res.json(response.buildOK(up_img)); } }); }); } }; exports.upload_voice = function(req, res) { var callback=null; // Parse file. if(req.files) { var file=req.files.voice; // Read file. fs.readFile(file.path, function (err, data) { var name=new Date().getTime()+'.'+file.name.split('\.')[1]; console.log(config.upload_talk_voice_dir); var p = path.join(config.upload_talk_voice_dir, name); // Save file. fs.writeFile(p, data, 'utf8', function (err) { if (err) { console.log(err) return res.json(response.buildError('Something went wrong!')); } else { // res.json(response.buildOK('/uploads/'+p)); var up_voice='http://115.29.42.238:5000/upload/talk/voice/'+name; return res.json(response.buildOK(up_voice)); } }); }); } };
/** * HTTP DELETE request. */ global.DELETE = METHOD({ run : function(params, responseListenerOrListeners) { 'use strict'; //REQUIRED: params //REQUIRED: params.host //OPTIONAL: params.port //OPTIONAL: params.isSecure //OPTIONAL: params.uri //OPTIONAL: params.paramStr //OPTIONAL: params.data //OPTIONAL: params.headers //REQUIRED: responseListenerOrListeners REQUEST(COMBINE([params, { method : 'DELETE' }]), responseListenerOrListeners); } });
BASE.require([ "BASE.async.Future", "BASE.async.Task", "BASE.web.ajax" ], function () { BASE.namespace("BASE.query"); var Task = BASE.async.Task; var Future = BASE.async.Future; var defaultAjax = BASE.web.ajax; BASE.query.ODataProvider = (function (Super) { var ODataProvider = function (config) { var self = this; BASE.assertNotGlobal(self); Super.call(self); config = config || {}; var endPoint = config.endPoint || null; var model = config.model || { properties: {} }; var headers = config.headers || {}; var ajax = config.ajax || defaultAjax; if (endPoint === null) { throw new Error("Provider needs a endPoint."); } self.count = function (queryable) { var expression = queryable.getExpression(); return new Future(function (setValue, setError) { var visitor = new ODataVisitor(model); var where = ""; var take = ""; var skip = ""; var orderBy = ""; var atIndex = 0; if (expression.where) { where = visitor.parse(expression.where); } if (expression.skip) { skip = visitor.parse(expression.skip); atIndex = expression.skip.children[0].value; } if (expression.orderBy) { orderBy = visitor.parse(expression.orderBy); } var odataString = where + "&$top=0" + orderBy; var url = BASE.concatPaths(self.baseUrl, "?" + odataString + "&$inlinecount=allpages"); var settings = { headers: headers }; ajax.GET(url + skip, settings).then(function (ajaxResponse) { setValue(ajaxResponse.data.Count); }).ifError(function (e) { setError(e); }); }); }; self.execute = self.toArray = function (queryable) { var expression = queryable.getExpression(); var visitor = new ODataVisitor(); var dtos = []; var where = ""; var take = ""; var skip = ""; var orderBy = ""; var defaultTake = 100; var atIndex = 0; if (expression.where) { where = visitor.parse(expression.where); } if (expression.skip) { skip = visitor.parse(expression.skip); atIndex = expression.skip.children[0].value; } if (expression.take) { take = visitor.parse(expression.take); defaultTake = expression.take.children[0].value } if (expression.orderBy) { orderBy = visitor.parse(expression.orderBy); } return new Future(function (setValue, setError) { var odataString = where + take + orderBy; var url = BASE.concatPaths(self.baseUrl, "?" + odataString + "&$inlinecount=allpages"); ajax.GET(url, { headers: headers }).then(function (ajaxResponse) { dtos = ajaxResponse.data.Data; if (ajaxResponse.data.Error) { setError(new Error(ajaxResponse.data.message)); } else { // return the dtos we have all of the dtos, otherwise get the rest. if (dtos.length === ajaxResponse.data.Count) { setValue(dtos); } else { var task = new Task(); var collectionCount = ajaxResponse.data.Count; for (x = dtos.length; (atIndex + x) < collectionCount && x < defaultTake ; x += ajaxResponse.data.Data.length) { task.add(ajax.GET(url + "&$skip=" + (atIndex + x), settings)); } task.start().whenAll(function (futures) { futures.forEach(function (future) { var data = future.value.data; // This handles xhr errors. if (future.error) { var err = future.error; setError(err); return; } // The server may not return a data object. if (!data) { setValue(dtos); return; } //This handles server errors. if (data.Error) { setError(data.Error); return false; } else { data.Data.forEach(function (item) { if (dtos.length < defaultTake) { dtos.push(item); } }); } }); setValue(dtos); }); } } }).ifError(setError); }); }; }; BASE.extend(ODataProvider, Super); return ODataProvider; }(BASE.query.Provider)); });
var searchData= [ ['options',['options',['../structoptions.html',1,'']]] ];
var a = [,,"hello"]; a.forEach(function(el) { console.log(1); });
//>>built define(["../_base"],function(b){var a=b.constants;b.languages.sql={case_insensitive:!0,defaultMode:{lexems:[a.IDENT_RE],contains:["string","number","comment"],keywords:{keyword:{all:1,partial:1,global:1,month:1,current_timestamp:1,using:1,go:1,revoke:1,smallint:1,indicator:1,"end-exec":1,disconnect:1,zone:1,"with":1,character:1,assertion:1,to:1,add:1,current_user:1,usage:1,input:1,local:1,alter:1,match:1,collate:1,real:1,then:1,rollback:1,get:1,read:1,timestamp:1,session_user:1,not:1,integer:1,bit:1, unique:1,day:1,minute:1,desc:1,insert:1,execute:1,like:1,level:1,decimal:1,drop:1,"continue":1,isolation:1,found:1,where:1,constraints:1,domain:1,right:1,national:1,some:1,module:1,transaction:1,relative:1,second:1,connect:1,escape:1,close:1,system_user:1,"for":1,deferred:1,section:1,cast:1,current:1,sqlstate:1,allocate:1,intersect:1,deallocate:1,numeric:1,"public":1,preserve:1,full:1,"goto":1,initially:1,asc:1,no:1,key:1,output:1,collation:1,group:1,by:1,union:1,session:1,both:1,last:1,language:1, constraint:1,column:1,of:1,space:1,foreign:1,deferrable:1,prior:1,connection:1,unknown:1,action:1,commit:1,view:1,or:1,first:1,into:1,"float":1,year:1,primary:1,cascaded:1,except:1,restrict:1,set:1,references:1,names:1,table:1,outer:1,open:1,select:1,size:1,are:1,rows:1,from:1,prepare:1,distinct:1,leading:1,create:1,only:1,next:1,inner:1,authorization:1,schema:1,corresponding:1,option:1,declare:1,precision:1,immediate:1,"else":1,timezone_minute:1,external:1,varying:1,translation:1,"true":1,"case":1, exception:1,join:1,hour:1,"default":1,"double":1,scroll:1,value:1,cursor:1,descriptor:1,values:1,dec:1,fetch:1,procedure:1,"delete":1,and:1,"false":1,"int":1,is:1,describe:1,"char":1,as:1,at:1,"in":1,varchar:1,"null":1,trailing:1,any:1,absolute:1,current_time:1,end:1,grant:1,privileges:1,when:1,cross:1,check:1,write:1,current_date:1,pad:1,begin:1,temporary:1,exec:1,time:1,update:1,catalog:1,user:1,sql:1,date:1,on:1,identity:1,timezone_hour:1,natural:1,whenever:1,interval:1,work:1,order:1,cascade:1, diagnostics:1,nchar:1,having:1,left:1},aggregate:{count:1,sum:1,min:1,max:1,avg:1}}},modes:[a.C_NUMBER_MODE,a.C_BLOCK_COMMENT_MODE,{className:"comment",begin:"--",end:"$"},{className:"string",begin:"'",end:"'",contains:["escape","squote"],relevance:0},{className:"squote",begin:"''",end:"^"},{className:"string",begin:'"',end:'"',contains:["escape","dquote"],relevance:0},{className:"dquote",begin:'""',end:"^"},{className:"string",begin:"`",end:"`",contains:["escape"]},a.BACKSLASH_ESCAPE]};return b.languages.sql});
'use strict'; /* Controllers */ angular.module('myApp.controllers', []). controller('MyCtrl1', ['$scope', 'Hello', function($scope, Hello) { // Simple communication sample, return world $scope.hello = Hello.get(); }]) .controller('MyCtrl2', ['$scope', 'Todos', function($scope, Todos) { // Load Todos with secured connection $scope.todos = Todos.query(); $scope.addTodo = function() { var todo = {text:$scope.todoText, done:false}; $scope.todos.push(todo); $scope.todoText = ''; }; $scope.remaining = function() { var count = 0; angular.forEach($scope.todos, function(todo) { count += todo.done ? 0 : 1; }); return count; }; $scope.archive = function() { var oldTodos = $scope.todos; $scope.todos = []; angular.forEach(oldTodos, function(todo) { if (!todo.done) $scope.todos.push(todo); }); }; }]);
export { default } from 'ember-data-github/models/github-commit';
expect = require('chai').expect;
/* global it, describe, expect, jest */ import React from 'react'; // eslint-disable-line no-unused-vars import Datetime from '../src/DateTime'; import renderer from 'react-test-renderer'; // findDOMNode is not supported by the react-test-renderer, // and even though this component is not using that method // a dependency is probably using it. So we need to mock it // to make the tests pass. // https://github.com/facebook/react/issues/7371 jest.mock('react-dom', () => ({ findDOMNode: () => {}, })); // Mock date to get rid of time as a factor to make tests deterministic // 2016-12-21T23:36:07.071Z Date.now = jest.fn(() => 1482363367071); it('everything default: renders correctly', () => { const tree = renderer.create( <Datetime /> ).toJSON(); expect(tree).toMatchSnapshot(); }); it('value: set to arbitrary value', () => { const tree = renderer.create( <Datetime defaultValue={Date.now()} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); it('defaultValue: set to arbitrary value', () => { const tree = renderer.create( <Datetime defaultValue={Date.now()} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); describe('dateFormat', () => { it('set to true', () => { const tree = renderer.create( <Datetime dateFormat={true} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); it('set to false', () => { const tree = renderer.create( <Datetime dateFormat={false} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); }); describe('timeFormat', () => { it('set to true', () => { const tree = renderer.create( <Datetime timeFormat={true} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); it('set to false', () => { const tree = renderer.create( <Datetime timeFormat={false} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); }); describe('input', () => { it('input: set to true', () => { const tree = renderer.create( <Datetime input={true} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); it('input: set to false', () => { const tree = renderer.create( <Datetime input={false} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); }); describe('open', () => { it('set to true', () => { const tree = renderer.create( <Datetime open={true} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); it('set to false', () => { const tree = renderer.create( <Datetime open={false} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); }); describe('viewMode', () => { it('set to days', () => { const tree = renderer.create( <Datetime viewMode={'days'} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); it('set to months', () => { const tree = renderer.create( <Datetime viewMode={'months'} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); it('set to years', () => { const tree = renderer.create( <Datetime viewMode={'years'} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); it('set to time', () => { const tree = renderer.create( <Datetime viewMode={'time'} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); }); it('className: set to arbitraty value', () => { const tree = renderer.create( <Datetime className={'arbitrary-value'} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); describe('inputProps', () => { it('with placeholder specified', () => { const tree = renderer.create( <Datetime inputProps={{ placeholder: 'arbitrary-placeholder' }} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); it('with disabled specified', () => { const tree = renderer.create( <Datetime inputProps={{ disabled: true }} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); it('with required specified', () => { const tree = renderer.create( <Datetime inputProps={{ required: true }} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); it('with name specified', () => { const tree = renderer.create( <Datetime inputProps={{ name: 'arbitrary-name' }} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); it('with className specified', () => { const tree = renderer.create( <Datetime inputProps={{ className: 'arbitrary-className' }} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); }); it('isValidDate: only valid if after yesterday', () => { const yesterday = Datetime.moment().subtract(1, 'day'); const valid = (current) => current.isAfter(yesterday); const tree = renderer.create( <Datetime isValidDate={ valid } /> ).toJSON(); expect(tree).toMatchSnapshot(); }); it('renderDay: specified', () => { const renderDay = (props, currentDate) => <td {...props}>{ '0' + currentDate.date() }</td>; const tree = renderer.create( <Datetime renderDay={renderDay} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); it('renderMonth: specified', () => { const renderMonth = (props, currentDate) => <td {...props}>{ '0' + currentDate.date() }</td>; const tree = renderer.create( <Datetime renderMonth={renderMonth} /> ).toJSON(); expect(tree).toMatchSnapshot(); }); it('renderYear: specified', () => { const renderYear = (props, currentDate) => <td {...props}>{ '0' + currentDate.date() }</td>; const tree = renderer.create( <Datetime renderYear={renderYear} /> ).toJSON(); expect(tree).toMatchSnapshot(); });
Polymer('dialog-load',{ open: function(){ this.$.dialog.open(); }, toggle: function(){ this.$.dialog.toggle(); } });
/* (c) Anton Medvedev <anton@elfet.ru> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ var popovers = {}; class Popover { constructor(id, button = null, box = '.box') { var _this = this; this.id = id; this.box = $(box); this.margin = 10; this.onTop = 'top'; this.onBottom = 'bottom'; this.onLeft = 'left'; this.onRight = 'right'; this.autohide = false; if (button !== null) { this.on(button); } $(window).resize(function () { return _this.reposition(); }); $('body').mouseup((event) => { if (_this.autohide && _this.getPopover().has(event.target).length === 0) { _this.hide(); } }); } static create(id, button) { if (popovers[id]) { return popovers[id].on(button); } else { return popovers[id] = new Popover(id, button); } } static get(id) { return popovers[id]; } on(button) { var _this = this; this.button = $(button); this.button.mousedown((event) => { _this.autohide = false; }); return this; } reposition() { var arrow, arrowPosition, boxSize, buttonOffset, buttonSize, offset, over, popover, popoverPosition, popoverSize; arrow = this.getArrow(); popover = this.getPopover(); boxSize = { width: this.box.width(), height: this.box.height() }; buttonOffset = this.button.offset(); buttonSize = { width: this.button.outerWidth(), height: this.button.outerHeight() }; popoverSize = { width: popover.outerWidth(), height: popover.outerHeight() }; if (popover.hasClass(this.onLeft) || popover.hasClass(this.onRight)) { if (popover.hasClass(this.onLeft)) { popoverPosition = { top: buttonOffset.top - (popoverSize.height / 2) + (buttonSize.height / 2), left: buttonOffset.left - popoverSize.width }; } else { popoverPosition = { top: buttonOffset.top - (popoverSize.height / 2) + (buttonSize.height / 2), left: buttonOffset.left + buttonSize.width }; } arrowPosition = { top: popoverSize.height / 2 }; if ((over = popoverPosition.top + popoverSize.height) > boxSize.height) { offset = over - boxSize.height + this.margin; popoverPosition.top -= offset; arrowPosition.top += offset; } if ((over = popoverPosition.top) < 0) { offset = -over + this.margin; popoverPosition.top += offset; arrowPosition.top -= offset; } } else { popoverPosition = { top: buttonSize.height + buttonOffset.top, left: buttonOffset.left - (popoverSize.width / 2) + (buttonSize.width / 2) }; arrowPosition = { left: popoverSize.width / 2 }; if (popoverPosition.top + popoverSize.height > boxSize.height || popover.hasClass(this.onTop)) { popoverPosition.top = buttonOffset.top - popoverSize.height; } if ((over = popoverPosition.left + popoverSize.width) > boxSize.width) { offset = over - boxSize.width + this.margin; popoverPosition.left -= offset; arrowPosition.left += offset; } if ((over = popoverPosition.left) < 0) { offset = -over + this.margin; popoverPosition.left += offset; arrowPosition.left -= offset; } } popover.css(popoverPosition); arrow.css(arrowPosition); } show() { this.reposition(); this.getPopover().show(); return this.autohide = true; } hide() { return this.getPopover().hide(); } toggle() { this.reposition(); this.getPopover().toggle(); return this.autohide = true; } getPopover() { return $('#' + this.id); } getArrow() { return this.getPopover().find('.arrow'); } }
var proto=function(){function u(a,c){for(var d=0,p=a.length;d<p;d++){var v=a[d];if(c(v))return v}return null}function w(a,c,d,p,v){return[a[0]*p+c,a[1]*v+d,a[2]*p+c,a[3]*v+d]}function M(a){for(var c={},d=arguments,p=/svg|fill|stroke/,v=/width|height|left|top|border|background/,k=1;k<d.length;k++){var y=d[k];if(y)for(var R in y)a&&!R.search(v)||!a&&!R.search(p)||(c[R]=y[R])}return c}function D(a,c){if(a==c)return!0;if(a&&c){for(var d in c)if(("_"!=d[0]||"_base"==d)&&a[d]!=c[d])return!1;return!0}return!1} function N(a){return a.a&&!a.b.classed("disabled")}function A(a){return a.c}function q(a){return a.d}function x(a){return a.e}function m(a){return a.f}function b(a,c){var d=this,p=a.split(" "),v=p[1],k=I("#"+v),y=k.node(),R=[],b;for(b in c){var f=c[b];"string"==typeof f&&(f=c[f]);R.push(new h(b,f))}d.g=R;d.h=-1;d.i=Array(r.length);d.b=k;d.j=0<y.namespaceURI.search("svg");d.k=!!k.attr("data-clip-path");d.a=!0;d.l=[];d.m=g;if(p=I("#"+p[0]).datum())d.n=p,p.l.push(d);"IFRAME"==y.tagName&&(k.on("load", function(){d.c=!0;O()}).attr("src",k.attr("data-src")+"?embedded"),d.c=!1,d.o=v,d.p=y.contentWindow,d.q="",S.push(d));if(d.k)for(d.o="url(#"+v+"_cp)",p.r=d;p;)p.b.style("pointer-events","none"),p=p.n;d.s=k.classed("button")?new l(d,v):null;k.classed("_",1).datum(d);la.push(d)}function g(){if(this.r)return this.r.f;var a=this.f;if(!a)for(var c=this.l,d=c.length;d--;)var p=c[d].m(),a=a&&p?[a[0]<p[0]?a[0]:p[0],a[1]<p[1]?a[1]:p[1],a[2]>p[2]?a[2]:p[2],a[3]>p[3]?a[3]:p[3]]:a||p;return a}function l(a,c){this.o= c;this.e=this.d=!1;this.q=this.t=""}function h(a,c){var d=a.match(Aa);this.u=d.splice(0,1);this.i=r.map(function(a){return 0<=d.indexOf(a)});this.v=c}function T(){var a=f.innerWidth,c=f.innerHeight,d=document.body;d.parentNode.style.overflow=oa?"hidden":"auto";oa?(U=Math.min(c/V,a/W),a=(a-U*W)/2,c=(c-U*V)/2):(U=1,a=a<W?0:(a-W)/2,c=c<V?0:(c-V)/2);I(d).style({background:ta?"none":X.background,width:W+"px",height:V+"px",transform:"translate("+a+"px,"+c+"px) scale("+U+")"})}function J(a,c){if(ua)pa.push(c); else{ua=!0;for(var d=r.length,p=E.styles,v=[],k,y=[],b=d;b--;)k=da.indexOf(r[b]),k=0>k?1:da.length-k,v[b]=k;for(k=la.length;k--;)la[k].i.fill(!1);for(b=d;b--;)k=r[b],ea("."+k+"._, ."+k+" ._").each(function(a){a.i[b]=!0});if(C||!ma){for(b in Y)Y[b].w=0;for(b=da.length;b--;){k=da[b];var f=r.indexOf(k);ea("."+k+" ._,."+k+"._").each(function(a){for(var d=0;d<a.g.length;d++){var c=a.g[d],k=Y[c.u],c=c.i;k&&c[f]&&(k.w+=b)}})}var n;k=-1;for(b in Y){var e=Y[b].w;e>k&&(k=e,n=b)}z=n;ma=Y[n]}k=ma.width;n=ma.height; if(W!=k||V!=n)W=k,V=n,T();for(k=0;k<la.length;k++){n=la[k];var g=n.b,e=!n.n||n.n.a,t=null,h=-1,l=-1,q=n.v;if(e){for(var m=0;m<n.g.length;m++){var u=n.g[m];if(u.u==z){for(var e=0,x=n.i,w=u.i,b=d;b--;)x[b]==!!w[b]?e+=v[b]:w[b]&&(e=-Infinity);e>l&&(l=e,h=m,t=u.v)}}e=!!t}g.classed("hidden",!e);n.a=e;if(q!=h||a)if(n.k&&(n.j?(e=t?n.o:"none",n.n.b.attr({"clip-path":e}).style({"-webkit-clip-path":e,"clip-path":e})):t&&Z(n.b.select("div"),{left:("-"+t.left).replace("--",""),top:("-"+t.top).replace("--","")}, null!=q)),t){if(e=n.s)l=t._opt,e.t=l&&l.pivot||"",e.e=l&&l["default"];n.v=h;n.f=t._rect;n.x=t._act;if(h=t._content){var h=g.selectAll("p").data(h),A=h.size();h.exit().remove();h.enter().append("p");h.html(function(a,d){Z(I(this),p[a._base],d<A);return a.text})}if(null==q||a||!D(n.g[q].v,t))t=M(n.j,p[t._base],t),Z(g,t,null!=q);y.push(n)}else n.f=null,n.v=null}for(k=0;k<y.length;k++)n=y[k],d=(d=n.x)&&d.load,v=y[k]=n.b.node(),d&&aa.call(v,{y:d,z:new fa(v,"load")});k&&ga.update.call(this,{elements:y}); ua=!1;if(pa.length){var y=pa,B;pa=[];for(J();y.length;)(B=y.shift())&&B()}c&&c()}}function Z(a,c,d){var b={},v={},k=null,e;for(e in c)"_"!=e[0]&&(0==e.search("svg-")?b[e.slice(4)]=c[e]:"transform"==e&&d?k=K(a.node().style[e],c[e]):v[e]=c[e]);d?(e=a.node(),c=va(e),d=wa(e),e=xa(e).split(" "),a=a.transition().ease(e[0],e[1]).duration(c).delay(d).style(v).attr(b),k&&k(a)):a.style(v).attr(b)}function K(a,c){for(var d=/([-\d\.]+)(?=deg)/,b=a.split(d),d=c.split(d),e=1;e<d.length;e+=2){var k=1*b[e],f=1*d[e]; isNaN(k)&&(a+=" rotate(0deg)",k=0);for(f-=k;180<f;)f-=360;for(;-180>f;)f+=360;d[e]=k+f}var r=d3.interpolateString(a,d.join(""));return function(a){a.styleTween("transform",function(a){return r}).each("end",function(){this.style.transform=c})}}function F(a,c,d){if(a&&a!=e){var b={},f;for(f in ba)a==ba[f].scene&&(b[f]=ba[f]);Object.keys(b).length&&(ga.navigate.call(this,{oldScene:e,newScene:a}),e=a,Y=b,z=Object.keys(b)[0],ma=b[z],J(!1,function(){c?P(c):ha&&!d&&P()}))}}function G(a,c,d){c||(d=a.C,c= a.B,a=a.G);if(2==a)if(C&&C.s)a=I(".button.focus").node(),qa[c].call(a,d);else{var b=C?C.p:L;H.E(b,7,{G:a,B:c,C:d})}else 0==a?qa[c].call(f,d):1==a?H.E(L,c,d):(b=I(a).datum().p)?H.E(b,c,d):qa[c].call(a,d)}function ca(a,c){var d=S.filter(N);H.F(d,2,m,function(b){var e=[],k=0;ea(".button:not(.hidden):not(.disabled),iframe:not(.hidden):not(.disabled)").each(function(a){var c=a.s;if(c){if(a=a.m())c.f=a,e[k++]=c}else if(c=d.indexOf(a),0<=c)for(c=b[c],a=c.length;a--;)e[k++]=c[a]});if(a)for(var f=e.length;f--;){var r= e[f];r.f=w(r.f,a[0],a[1],U,U)}c&&c(e)})}function B(a,c){if(c){var d=c.length;a=Ba[a];var b=u(c,q);if(!b)return null;var e=null,k;if(4>a)for(var b=b.f,f=Ca[a],r=f[4]-1,t=f[0],g=f[1],h=f[2],f=f[3];d--;){var l=c[d],z=Da[a],m=l.t,z=[(l.f[h]-b[f])*r,m.length&&z&&z.test(m)?-1:0],m=Math.min(l.f[t],b[t])-Math.max(l.f[g],b[g]);if(0<=z[0]+8&&(z[1]||8<m))for(z[0]>>=3,z[2]=l.f[g]>>3,m=0;3>m;m++)if(!k||z[m]<k[m]){e=l;k=z;break}else if(z[m]>k[m])break}else e=c.indexOf(b),e=c[((4==a?e+1:e-1)+d)%d];e&&na(e)}else ca(0, function(c){B(a,c)})}function na(a,c){var d;ha=!1;ea(".has-focus").classed("has-focus",0);(ya=a)&&ia===a.q&&(ha=!0,d=Q(I("#"+a.o).datum()));H.F(S,3,a,function(a){for(var b=a.length;b--;)a[b]&&(ha=!0,d=Q(S[b]));ha||(d=Q());d&&J();c&&c(ha)})}function Q(a){if(C!=a){C&&(C.s&&(C.s.d=!1),ea(".focus").classed("focus",0));if(a){a.s&&(a.s.d=!0);a.b.classed("focus",1);for(var c=a;c;)c.b.classed("has-focus",1),c=c.n}ga.focuschange.call(this,{oldFocus:C&&C.b.node(),newFocus:a&&a.b.node()});C=a;return 1}}function P(a){a? (a instanceof Array&&(a=u(a,x)||a[0]),L?H.E(L,6,a):a&&na(a)):ca(0,P)}function ra(){for(var a;a=ja.pop();)if(a[0]!=e)return F(a[0],a[1]);L&&H.E(L,5)}function fa(a,c,d){return{src:ia+(ia?"/":"")+(a.id||""),type:c,data:d}}function O(a,c){a&&(ia=a,ea(".button").each(function(c){c.s.q=a}),sa=c,L=this.source);S.every(A)&&(ta&&!sa||H.F(S,1,function(a){return a.q=(ia?ia+"/":"")+a.o},function(){sa?sa():P();ga.ready.call(this,{isMaster:!ta})}))}function aa(a){var c=a.y;a=a.z||new fa(this,"",a.C);if(c){for(var c= c+",",d=!1,b=c.length,e="",f=[],r=[],g=0;g<b;g++){var h=c[g];'"'==h?d=!d:d?e+=h:" "==h||","==h?(e.length&&(f.push(e),e=""),","==h&&f.length&&(r.push(f),f=[])):e+=h}for(g=0;g<r.length;g++)if(c=r[g],d=t[c[0]])a.args=c,d.call(this,a)}}var E=proto_data,ba=E.artboards,X=E.settings,r=E.states,f=window,t=[],e,ma,z,Y,W,V,U,I=d3.select,ea=d3.selectAll,ka=d3.functor,za=f.addEventListener,la=[],S=[],L,ia="",sa,ja=[],ha=!1,C,ya,va=ka(X.transition_duration),xa=ka(X.easing_func+"-"+X.easing_mode),wa=ka(0),oa=X.auto_scale, da=["press","focus","hover"],ga=d3.dispatch("fallback","ready","focuschange","navigate","update"),ta=null!=f.location.search.match(/\bembedded\b/),ua=!1,pa=[],Ba={U:0,R:1,D:2,L:3,N:4,P:5},Aa=/[^:]+/g,Da=[/u|y|a/i,/r|x|a/i,/d|y|a/i,/l|x|a/i],Ca=["20310","31022","20132","31200"],qa=[null,O,ca,na,function(a){var c;"src"in a?c=u(S,function(c){return!a.src.search(c.q+"/")}):(c=I(this).datum(),a=new fa(this,a.H,a.C));for(var d=a.type,b=!1;c;){var e=c.x;if(e&&e[d]){aa.call(c.b.node(),{y:e[d],z:a});b=!0; break}c=c.n}b||(L?H.E(L,4,a):ga.fallback.call(this,a))},ra,P,G,aa],H=function(a){function c(a,c,e,f){if(a){var r="r"+b++;f&&(d[r]=f);a.postMessage({o:r,A:!!f,B:c,C:e},"*")}}var d={},b=0;za("message",function(c){var b=c.data,e=b.C,f=b.B;0==f?(f=e.o,d[f]&&(d[f](e.C),d[f]=null)):(b=b.A?function(a){H.D(c,a)}:null,(f=a[f])&&f.call(c,e,b))});return{E:c,F:function(a,d,b,e){var f=a.length,r=[];!f&&e&&e(r);a.map(function(a,g){var t="function"==typeof b?b(a,g):b;c(a.p,d,t,function(a){r[g]=a;!--f&&e&&e(r)})})}, D:function(a,d){c(a.source,0,{o:a.data.o,C:d})}}}(qa);return{SELF:0,PARENT:1,FOCUS:2,init:function(){var a=E.keyframes,c;for(c in a)new b(c,a[c]);za("resize",T);F(ba[0].scene);O()},tell:function(a,c,d){G(a,8,{y:c,C:d})},move:B,trigger:function(a,c,d){c&&G(a,4,{H:c,C:d})},on:function(a,c){return ga.on(a,c)},back:ra,update:J,focus:function(a){if(a){var c=I(a).datum(),d=c.s;d?P(d):c.p&&G(a,6)}},"goto":function(a,c){var d=ja.pop();d&&d[0]!=e&&ja.push(d);ja.push([e,ya]);99<ja.length&&ja.shift();F(a,null, c)},define:function(a,c){a.pop||(a=[a]);for(var d=a.length;d--;)t[a[d]]=c},option:function(a,c){var d=void 0===c;switch(a){case "duration":return d?va:va=ka(c);case "delay":return d?wa:wa=ka(c);case "easing":return d?xa:xa=ka(c);case "autoscale":return d?oa:T(oa=c);case "states":return d?da:da=c}}}}(); (function(){function u(b,g){var l=b.split("/").filter(Boolean);return[l[g?"pop":"shift"](),l.join("/")]}function w(b){return d3.selectAll('[data-name="'+b+'"]')[0]}function M(b,g,l){for(var h=!1,m=b.length;m--;){var q=b[m].classList,u=q.contains(l);if("add"==g?!u:"remove"==g?u:1)h=!0;q[g](l)}h&&A.update()}function D(b){var g=u(b,0),l=g[0];b=g[1];var h='"'+[].slice.call(arguments,1).join('" "')+'"';b&&(h="tell "+b+" "+h);"."==l?x(proto.PARENT,h):w(l).map(function(b){x(b,h)})}function N(b){b=u(b,1); var g=b[0];(b=b[1])?D(b,"focus",g):(g=w(g)[0])&&A.focus(g)}var A=proto,q=A.define,x=A.tell;q(["set","unset","toggle"],function(b){var g,l=b.args;b=l[0];g=l[1];if(l=l[2]){g=u(g,1);var h=g[0];if(g=g[1]){D(g,b,h,l);return}g=w(h)}else l=g,g=[this];M(g,"set"==b?"add":"unset"==b?"remove":"toggle",l)});q("tell",function(b){D.apply(this,b.args.slice(1))});q("do",function(b){A.trigger(2,b.args[1])});q("move",function(b){A.move(b.args[1])});var m={};q("wait",function(b){b=b.args;var g='"'+[].slice.call(b,2).join('" "')+ '"',l=this,h=setTimeout(function(){x(l,g);delete m[h]},1*b[1]);m[h]=this});q("cancel-wait",function(b){for(var g in m)if(b=m[g],this==b||this.contains(b))clearTimeout(g),delete m[g]});q("goto",function(b){b=b.args;var g=b[1];"focus"==b[2]?(A["goto"](g,!0),N(b[3])):A["goto"](g)});q(["enable","disable","toggle-enable"],function(b){function g(b){if(b.classList.contains("button")||"IFRAME"==b.tagName)m.push(b);else{b=b.querySelectorAll(".button,iframe");for(var g=b.length;g--;)m.push(b[g])}}var l=b.args; b=l[0];var h=l[1],m=[];h?(h=u(h,1),l=h[0],(h=h[1])?D(h,b,l):w(l).map(g)):g(this);M(m,"disable"==b?"add":"enable"==b?"remove":"toggle","disabled")});q("focus",function(b){N(b.args[1])});q("back",function(){A.back()})})(); proto.on("ready.input",function(u){function w(b){return!b.classList.contains("disabled")}function M(b){if(J!=b){var f=document.body.classList;J&&f.remove(J);f.add(b);J=b;G()}}function D(){w(this)&&(this.classList.add("press"),G())}function N(){T(".button.press").classed("press",!1).size()&&G()}function A(b){var f=typeof b;if("string"==f||"number"==f)return!0;if("object"==f){for(var g in b)if(f=typeof b[g],"string"!=f&&"number"!=f)return!1;return!0}}function q(b){var f={},g;for(g in b){var e=b[g]; A(e)&&(f[g]=e)}return f}var x=u.isMaster,m=proto;u=proto_data.settings;var b=!1,g=!1,l=!1,h=window.addEventListener,T=d3.selectAll,J,Z=m.define,K=m.tell,F=m.trigger,G=m.update,ca=m.move,B=m.FOCUS;m.on("fallback",function(b){b=b.type;switch(b){case "L":case "R":case "U":case "D":ca(b);break;case "TAB":ca("N");break;case "STAB":ca("P");break;case "B":case "ESC":case "BACK":K(B,"back")}});Z("_input",function(b){M(b.args[1])});Z("_press",D);Z("_release",N);if(u.input_controller&&x){var na=function(b, f){this.P=b;this.J=f;this.R=0;this.N=!1;var g=this.Q=0,e=18,h=0,l=0;this.I=function(b,f){this.R=f||0;b?(0<g?g--:(Q("buttondown",this),this.Q++,g=e,2<e&&(e=2*e/3)),this.N||(h=12),0<h&&h--):this.N&&(Q("buttonup",this),g=0,e=18,this.Q=0,0<h&&(0<l?(Q("buttondbltap",this),l=0):l=24));0<l&&(l--,0==l&&Q("buttontap",this));this.N=b}},Q=function(b,f){var g={controller:f.P,button:f.J.O,repeated:f.Q,value:f.R,isHandled:!1},e=document.createEvent("CustomEvent");e.initCustomEvent(b,!1,!1,g);window.dispatchEvent(e)}, P=function(b){this.I=(new ra(b,X)).I},ra=function(b,f){for(var g=[],e=0;e<f.length;e++)g[e]=new na(b,f[e]);this.I=function(b){for(var e=g.length;e--;){var f=g[e],h=f.J;if(null!=h.K){var l=b.buttons[h.K];l&&f.I(l.pressed,l.value)}else null!=h.L&&(l=b.axes[h.L],h=l*h.M,f.I(.7<h?!0:.2>h?!1:f.N,l))}}},fa=function(){E=Date.now();if(E-aa>ba){aa=E-(E-aa)%ba;for(var b=navigator.getGamepads(),f=0;f<b.length;f++){var g=b[f];g&&(O[f]||/xbox 360|controller/i.test(g.id)&&15<=g.buttons.length&&(O[f]=new P(f)), O[f]&&O[f].I(g))}}window.requestAnimationFrame(fa)},O=[],aa=Date.now(),E,ba=17;navigator.getGamepads&&(fa(),x=function(b){return function(f){f=f.detail;f.isHandled||F(2,b[f.button],f)}},h("buttondown",x({LStickLeft:"L",DpadLeft:"L",LStickRight:"R",DpadRight:"R",LStickUp:"U",DpadUp:"U",LStickDown:"D",DpadDown:"D",LB:"LB",RB:"RB",LT:"LT",RT:"RT"})),h("buttonup",x({A:"A",B:"B",X:"X",Start:"Menu",Back:"View"})),h("buttontap",x({Y:"Y"})),h("buttondbltap",x({Y:"dblY"})),h("buttondown",function(g){K(B,"_input controller"); "A"!=g.detail.button||b||(b=!0,K(B,"_press"))}),h("buttonup",function(g){"A"==g.detail.button&&(b=!1,K(B,"_release"))}));var X=[{K:0,O:"A"},{K:1,O:"B"},{K:2,O:"X"},{K:3,O:"Y"},{K:4,O:"LB"},{K:5,O:"RB"},{K:6,O:"LT"},{K:7,O:"RT"},{K:8,O:"Back"},{K:9,O:"Start"},{K:10,O:"LStick"},{K:11,O:"RStick"},{K:12,O:"DpadUp"},{K:13,O:"DpadDown"},{K:14,O:"DpadLeft"},{K:15,O:"DpadRight"},{L:0,M:-1,O:"LStickLeft"},{L:0,M:1,O:"LStickRight"},{L:1,M:-1,O:"LStickUp"},{L:1,M:1,O:"LStickDown"},{L:2,M:-1,O:"RStickLeft"}, {L:2,M:1,O:"RStickRight"},{L:3,M:-1,O:"RStickUp"},{L:3,M:1,O:"RStickDown"}]}u.input_keyboard&&(x=function(b,f){return function(g){var e=g.keyCode;g.shiftKey&&(e+="+");if(e=f(e)||b[e])F(B,e,q(g)),g.preventDefault()}},h("keydown",x({37:"L",38:"U",39:"R",40:"D",9:"TAB","9+":"STAB"},function(b){K(B,"_input keyboard");13!=b||g||(g=!0,K(B,"_press"))})),h("keyup",x({8:"BACK",27:"ESC",32:"SPACE",33:"PGUP",34:"PGDN",35:"END",36:"HOME"},function(b){var f=String.fromCharCode(b);if(65<=b&&90>=b)return f+"Key"; if(48<=b&&57>=b)return"D"+f;if(13==b)return g=!1,K(B,"_release"),"ENTER"})));u.input_mouse&&(T(".button").on("mouseenter",function(){w(this)&&(this.classList.add("hover"),G())}).on("mouseleave",function(){this.classList.remove("hover");G()}).on("mousedown",function(){w(this)&&(M("mouse"),D.call(this),m.focus(this))}).on("click",function(){w(this)&&F(this,"MLB",q(d3.event))}).on("dblclick",function(){w(this)&&F(this,"dblMLB",q(d3.event))}).on("contextmenu",function(){w(this)&&F(this,"MRB",q(d3.event)); d3.event.preventDefault()}),h("mouseup",function(){N()}));if(u.input_touch)T("head").append("script").attr("type","text/javascript").attr("src","https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.6/hammer.min.js").on("load",function(){var b=function(b){for(b=b.target;b&&!b.classList.contains("button");)b=b.parentElement;return b},f=function(e){return function(f){var g=f.pointerType;("touch"==g||"pen"==g)&&(g=b(f))&&F(g,e,q(f))}},g=Hammer;(new g.Manager(document.body,{recognizers:[[g.Tap],[g.Press], [g.Pan],[g.Pinch,null,["pan"]],[g.Swipe,null,["pan"]]]})).on("tap",f("TAP")).on("press",f("HOLD")).on("panend panmove",f("PAN")).on("swipeup",f("SWIPEU")).on("swipedown",f("SWIPED")).on("swipeleft",f("SWIPEL")).on("swiperight",f("SWIPER")).on("pinchend pinchmove",f("PINCH")).on("hammer.input",function(e){var f=e.pointerType;if("touch"==f||"pen"==f){e.preventDefault();var g=0<e.srcEvent.touches.length;g&&!l?(e=b(e))&&w(e)&&(M(f),D.call(e),m.focus(e)):!g&&l&&N();l=g}})})});
/** * * Supersample Anti-Aliasing Render Pass * * This manual approach to SSAA re-renders the scene ones for each sample with camera jitter and accumulates the results. * * References: https://en.wikipedia.org/wiki/Supersampling * */ THREE.SSAARenderPass = function ( scene, camera, clearColor, clearAlpha ) { THREE.Pass.call( this ); this.scene = scene; this.camera = camera; this.sampleLevel = 4; // specified as n, where the number of samples is 2^n, so sampleLevel = 4, is 2^4 samples, 16. this.unbiased = true; // as we need to clear the buffer in this pass, clearColor must be set to something, defaults to black. this.clearColor = ( clearColor !== undefined ) ? clearColor : 0x000000; this.clearAlpha = ( clearAlpha !== undefined ) ? clearAlpha : 0; this._oldClearColor = new THREE.Color(); if ( THREE.CopyShader === undefined ) console.error( 'THREE.SSAARenderPass relies on THREE.CopyShader' ); var copyShader = THREE.CopyShader; this.copyUniforms = THREE.UniformsUtils.clone( copyShader.uniforms ); this.copyMaterial = new THREE.ShaderMaterial( { uniforms: this.copyUniforms, vertexShader: copyShader.vertexShader, fragmentShader: copyShader.fragmentShader, premultipliedAlpha: true, transparent: true, blending: THREE.AdditiveBlending, depthTest: false, depthWrite: false } ); this.fsQuad = new THREE.Pass.FullScreenQuad( this.copyMaterial ); }; THREE.SSAARenderPass.prototype = Object.assign( Object.create( THREE.Pass.prototype ), { constructor: THREE.SSAARenderPass, dispose: function () { if ( this.sampleRenderTarget ) { this.sampleRenderTarget.dispose(); this.sampleRenderTarget = null; } }, setSize: function ( width, height ) { if ( this.sampleRenderTarget ) this.sampleRenderTarget.setSize( width, height ); }, render: function ( renderer, writeBuffer, readBuffer ) { if ( ! this.sampleRenderTarget ) { this.sampleRenderTarget = new THREE.WebGLRenderTarget( readBuffer.width, readBuffer.height, { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat } ); this.sampleRenderTarget.texture.name = 'SSAARenderPass.sample'; } var jitterOffsets = THREE.SSAARenderPass.JitterVectors[ Math.max( 0, Math.min( this.sampleLevel, 5 ) ) ]; var autoClear = renderer.autoClear; renderer.autoClear = false; renderer.getClearColor( this._oldClearColor ); var oldClearAlpha = renderer.getClearAlpha(); var baseSampleWeight = 1.0 / jitterOffsets.length; var roundingRange = 1 / 32; this.copyUniforms[ 'tDiffuse' ].value = this.sampleRenderTarget.texture; var width = readBuffer.width, height = readBuffer.height; // render the scene multiple times, each slightly jitter offset from the last and accumulate the results. for ( var i = 0; i < jitterOffsets.length; i ++ ) { var jitterOffset = jitterOffsets[ i ]; if ( this.camera.setViewOffset ) { this.camera.setViewOffset( width, height, jitterOffset[ 0 ] * 0.0625, jitterOffset[ 1 ] * 0.0625, // 0.0625 = 1 / 16 width, height ); } var sampleWeight = baseSampleWeight; if ( this.unbiased ) { // the theory is that equal weights for each sample lead to an accumulation of rounding errors. // The following equation varies the sampleWeight per sample so that it is uniformly distributed // across a range of values whose rounding errors cancel each other out. var uniformCenteredDistribution = ( - 0.5 + ( i + 0.5 ) / jitterOffsets.length ); sampleWeight += roundingRange * uniformCenteredDistribution; } this.copyUniforms[ 'opacity' ].value = sampleWeight; renderer.setClearColor( this.clearColor, this.clearAlpha ); renderer.setRenderTarget( this.sampleRenderTarget ); renderer.clear(); renderer.render( this.scene, this.camera ); renderer.setRenderTarget( this.renderToScreen ? null : writeBuffer ); if ( i === 0 ) { renderer.setClearColor( 0x000000, 0.0 ); renderer.clear(); } this.fsQuad.render( renderer ); } if ( this.camera.clearViewOffset ) this.camera.clearViewOffset(); renderer.autoClear = autoClear; renderer.setClearColor( this._oldClearColor, oldClearAlpha ); } } ); // These jitter vectors are specified in integers because it is easier. // I am assuming a [-8,8) integer grid, but it needs to be mapped onto [-0.5,0.5) // before being used, thus these integers need to be scaled by 1/16. // // Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396 THREE.SSAARenderPass.JitterVectors = [ [ [ 0, 0 ] ], [ [ 4, 4 ], [ - 4, - 4 ] ], [ [ - 2, - 6 ], [ 6, - 2 ], [ - 6, 2 ], [ 2, 6 ] ], [ [ 1, - 3 ], [ - 1, 3 ], [ 5, 1 ], [ - 3, - 5 ], [ - 5, 5 ], [ - 7, - 1 ], [ 3, 7 ], [ 7, - 7 ] ], [ [ 1, 1 ], [ - 1, - 3 ], [ - 3, 2 ], [ 4, - 1 ], [ - 5, - 2 ], [ 2, 5 ], [ 5, 3 ], [ 3, - 5 ], [ - 2, 6 ], [ 0, - 7 ], [ - 4, - 6 ], [ - 6, 4 ], [ - 8, 0 ], [ 7, - 4 ], [ 6, 7 ], [ - 7, - 8 ] ], [ [ - 4, - 7 ], [ - 7, - 5 ], [ - 3, - 5 ], [ - 5, - 4 ], [ - 1, - 4 ], [ - 2, - 2 ], [ - 6, - 1 ], [ - 4, 0 ], [ - 7, 1 ], [ - 1, 2 ], [ - 6, 3 ], [ - 3, 3 ], [ - 7, 6 ], [ - 3, 6 ], [ - 5, 7 ], [ - 1, 7 ], [ 5, - 7 ], [ 1, - 6 ], [ 6, - 5 ], [ 4, - 4 ], [ 2, - 3 ], [ 7, - 2 ], [ 1, - 1 ], [ 4, - 1 ], [ 2, 1 ], [ 6, 2 ], [ 0, 4 ], [ 4, 4 ], [ 2, 5 ], [ 7, 5 ], [ 5, 6 ], [ 3, 7 ] ] ];
//parse a string like "4,200.1" into Number 4200.1 const parseNumeric = str => { //remove ordinal - 'th/rd' str = str.replace(/1st$/, '1') str = str.replace(/2nd$/, '2') str = str.replace(/3rd$/, '3') str = str.replace(/([4567890])r?th$/, '$1') //remove prefixes str = str.replace(/^[$€¥£¢]/, '') //remove suffixes str = str.replace(/[%$€¥£¢]$/, '') //remove commas str = str.replace(/,/g, '') //split '5kg' from '5' str = str.replace(/([0-9])([a-z\u00C0-\u00FF]{1,2})$/, '$1') return str } module.exports = parseNumeric
/** * EVENT_NAME_MAP is used to determine which event fired when a * transition/animation ends, based on the style property used to * define that event. */ const EVENT_NAME_MAP = { transitionend: { transition: 'transitionend', WebkitTransition: 'webkitTransitionEnd', MozTransition: 'mozTransitionEnd', OTransition: 'oTransitionEnd', msTransition: 'MSTransitionEnd' }, animationend: { animation: 'animationend', WebkitAnimation: 'webkitAnimationEnd', MozAnimation: 'mozAnimationEnd', OAnimation: 'oAnimationEnd', msAnimation: 'MSAnimationEnd' } } let endEvents = [] const detectEvents = function () { const testEl = document.createElement('div') const style = testEl.style // On some platforms, in particular some releases of Android 4.x, // the un-prefixed "animation" and "transition" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are useable, and if not remove them // from the map if (!('AnimationEvent' in window)) { delete EVENT_NAME_MAP.animationend.animation } if (!('TransitionEvent' in window)) { delete EVENT_NAME_MAP.transitionend.transition } for (const baseEventName in EVENT_NAME_MAP) { const baseEvents = EVENT_NAME_MAP[baseEventName] for (const styleName in baseEvents) { if (styleName in style) { endEvents.push(baseEvents[styleName]) break } } } } if (typeof window !== 'undefined') { detectEvents() } // We use the raw {add|remove}EventListener() call because EventListener // does not know how to remove event listeners and we really should // clean up. Also, these events are not triggered in older browsers // so we should be A-OK here. export function addEventListener (target, eventName, eventListener) { if (target.addEventListener) { target.addEventListener(eventName, eventListener, false) return { remove () { target.removeEventListener(eventName, eventListener, false) } } } else if (target.attachEvent) { target.attachEvent('on' + eventName, eventListener) return { remove () { target.detachEvent('on' + eventName, eventListener) } } } } const removeEventListener = function (node, eventName, eventListener) { node.removeEventListener(eventName, eventListener, false) } export function addEndEventListener (node, eventListener) { if (endEvents.length === 0) { // If CSS transitions are not supported, trigger an "end animation" // event immediately. window.setTimeout(eventListener, 0) return } endEvents.forEach(endEvent => { addEventListener(node, endEvent, eventListener) }) } export function removeEndEventListener (node, eventListener) { if (endEvents.length === 0) { return } endEvents.forEach(endEvent => { removeEventListener(node, endEvent, eventListener) }) }
/*! VelocityJS.org (1.3.1). (C) 2014 Julian Shapiro. MIT @license: en.wikipedia.org/wiki/MIT_License */ /************************* Velocity jQuery Shim *************************/ /*! VelocityJS.org jQuery Shim (1.0.1). (C) 2014 The jQuery Foundation. MIT @license: en.wikipedia.org/wiki/MIT_License. */ /* This file contains the jQuery functions that Velocity relies on, thereby removing Velocity's dependency on a full copy of jQuery, and allowing it to work in any environment. */ /* These shimmed functions are only used if jQuery isn't present. If both this shim and jQuery are loaded, Velocity defaults to jQuery proper. */ /* Browser support: Using this shim instead of jQuery proper removes support for IE8. */ (function(window) { "use strict"; /*************** Setup ***************/ /* If jQuery is already loaded, there's no point in loading this shim. */ if (window.jQuery) { return; } /* jQuery base. */ var $ = function(selector, context) { return new $.fn.init(selector, context); }; /******************** Private Methods ********************/ /* jQuery */ $.isWindow = function(obj) { /* jshint eqeqeq: false */ return obj && obj === obj.window; }; /* jQuery */ $.type = function(obj) { if (!obj) { return obj + ""; } return typeof obj === "object" || typeof obj === "function" ? class2type[toString.call(obj)] || "object" : typeof obj; }; /* jQuery */ $.isArray = Array.isArray || function(obj) { return $.type(obj) === "array"; }; /* jQuery */ function isArraylike(obj) { var length = obj.length, type = $.type(obj); if (type === "function" || $.isWindow(obj)) { return false; } if (obj.nodeType === 1 && length) { return true; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && (length - 1) in obj; } /*************** $ Methods ***************/ /* jQuery: Support removed for IE<9. */ $.isPlainObject = function(obj) { var key; if (!obj || $.type(obj) !== "object" || obj.nodeType || $.isWindow(obj)) { return false; } try { if (obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) { return false; } } catch (e) { return false; } for (key in obj) { } return key === undefined || hasOwn.call(obj, key); }; /* jQuery */ $.each = function(obj, callback, args) { var value, i = 0, length = obj.length, isArray = isArraylike(obj); if (args) { if (isArray) { for (; i < length; i++) { value = callback.apply(obj[i], args); if (value === false) { break; } } } else { for (i in obj) { if (!obj.hasOwnProperty(i)) { continue; } value = callback.apply(obj[i], args); if (value === false) { break; } } } } else { if (isArray) { for (; i < length; i++) { value = callback.call(obj[i], i, obj[i]); if (value === false) { break; } } } else { for (i in obj) { if (!obj.hasOwnProperty(i)) { continue; } value = callback.call(obj[i], i, obj[i]); if (value === false) { break; } } } } return obj; }; /* Custom */ $.data = function(node, key, value) { /* $.getData() */ if (value === undefined) { var getId = node[$.expando], store = getId && cache[getId]; if (key === undefined) { return store; } else if (store) { if (key in store) { return store[key]; } } /* $.setData() */ } else if (key !== undefined) { var setId = node[$.expando] || (node[$.expando] = ++$.uuid); cache[setId] = cache[setId] || {}; cache[setId][key] = value; return value; } }; /* Custom */ $.removeData = function(node, keys) { var id = node[$.expando], store = id && cache[id]; if (store) { // Cleanup the entire store if no keys are provided. if (!keys) { delete cache[id]; } else { $.each(keys, function(_, key) { delete store[key]; }); } } }; /* jQuery */ $.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; if (typeof target === "boolean") { deep = target; target = arguments[i] || {}; i++; } if (typeof target !== "object" && $.type(target) !== "function") { target = {}; } if (i === length) { target = this; i--; } for (; i < length; i++) { if ((options = arguments[i])) { for (name in options) { if (!options.hasOwnProperty(name)) { continue; } src = target[name]; copy = options[name]; if (target === copy) { continue; } if (deep && copy && ($.isPlainObject(copy) || (copyIsArray = $.isArray(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && $.isArray(src) ? src : []; } else { clone = src && $.isPlainObject(src) ? src : {}; } target[name] = $.extend(deep, clone, copy); } else if (copy !== undefined) { target[name] = copy; } } } } return target; }; /* jQuery 1.4.3 */ $.queue = function(elem, type, data) { function $makeArray(arr, results) { var ret = results || []; if (arr) { if (isArraylike(Object(arr))) { /* $.merge */ (function(first, second) { var len = +second.length, j = 0, i = first.length; while (j < len) { first[i++] = second[j++]; } if (len !== len) { while (second[j] !== undefined) { first[i++] = second[j++]; } } first.length = i; return first; })(ret, typeof arr === "string" ? [arr] : arr); } else { [].push.call(ret, arr); } } return ret; } if (!elem) { return; } type = (type || "fx") + "queue"; var q = $.data(elem, type); if (!data) { return q || []; } if (!q || $.isArray(data)) { q = $.data(elem, type, $makeArray(data)); } else { q.push(data); } return q; }; /* jQuery 1.4.3 */ $.dequeue = function(elems, type) { /* Custom: Embed element iteration. */ $.each(elems.nodeType ? [elems] : elems, function(i, elem) { type = type || "fx"; var queue = $.queue(elem, type), fn = queue.shift(); if (fn === "inprogress") { fn = queue.shift(); } if (fn) { if (type === "fx") { queue.unshift("inprogress"); } fn.call(elem, function() { $.dequeue(elem, type); }); } }); }; /****************** $.fn Methods ******************/ /* jQuery */ $.fn = $.prototype = { init: function(selector) { /* Just return the element wrapped inside an array; don't proceed with the actual jQuery node wrapping process. */ if (selector.nodeType) { this[0] = selector; return this; } else { throw new Error("Not a DOM node."); } }, offset: function() { /* jQuery altered code: Dropped disconnected DOM node checking. */ var box = this[0].getBoundingClientRect ? this[0].getBoundingClientRect() : {top: 0, left: 0}; return { top: box.top + (window.pageYOffset || document.scrollTop || 0) - (document.clientTop || 0), left: box.left + (window.pageXOffset || document.scrollLeft || 0) - (document.clientLeft || 0) }; }, position: function() { /* jQuery */ function offsetParentFn(elem) { var offsetParent = elem.offsetParent || document; while (offsetParent && (offsetParent.nodeType.toLowerCase !== "html" && offsetParent.style.position === "static")) { offsetParent = offsetParent.offsetParent; } return offsetParent || document; } /* Zepto */ var elem = this[0], offsetParent = offsetParentFn(elem), offset = this.offset(), parentOffset = /^(?:body|html)$/i.test(offsetParent.nodeName) ? {top: 0, left: 0} : $(offsetParent).offset(); offset.top -= parseFloat(elem.style.marginTop) || 0; offset.left -= parseFloat(elem.style.marginLeft) || 0; if (offsetParent.style) { parentOffset.top += parseFloat(offsetParent.style.borderTopWidth) || 0; parentOffset.left += parseFloat(offsetParent.style.borderLeftWidth) || 0; } return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; } }; /********************** Private Variables **********************/ /* For $.data() */ var cache = {}; $.expando = "velocity" + (new Date().getTime()); $.uuid = 0; /* For $.queue() */ var class2type = {}, hasOwn = class2type.hasOwnProperty, toString = class2type.toString; var types = "Boolean Number String Function Array Date RegExp Object Error".split(" "); for (var i = 0; i < types.length; i++) { class2type["[object " + types[i] + "]"] = types[i].toLowerCase(); } /* Makes $(node) possible, without having to call init. */ $.fn.init.prototype = $.fn; /* Globalize Velocity onto the window, and assign its Utilities property. */ window.Velocity = {Utilities: $}; })(window); /****************** Velocity.js ******************/ (function(factory) { "use strict"; /* CommonJS module. */ if (typeof module === "object" && typeof module.exports === "object") { module.exports = factory(); /* AMD module. */ } else if (typeof define === "function" && define.amd) { define(factory); /* Browser globals. */ } else { factory(); } }(function() { "use strict"; return function(global, window, document, undefined) { /*************** Summary ***************/ /* - CSS: CSS stack that works independently from the rest of Velocity. - animate(): Core animation method that iterates over the targeted elements and queues the incoming call onto each element individually. - Pre-Queueing: Prepare the element for animation by instantiating its data cache and processing the call's options. - Queueing: The logic that runs once the call has reached its point of execution in the element's $.queue() stack. Most logic is placed here to avoid risking it becoming stale (if the element's properties have changed). - Pushing: Consolidation of the tween data followed by its push onto the global in-progress calls container. - tick(): The single requestAnimationFrame loop responsible for tweening all in-progress calls. - completeCall(): Handles the cleanup process for each Velocity call. */ /********************* Helper Functions *********************/ /* IE detection. Gist: https://gist.github.com/julianshapiro/9098609 */ var IE = (function() { if (document.documentMode) { return document.documentMode; } else { for (var i = 7; i > 4; i--) { var div = document.createElement("div"); div.innerHTML = "<!--[if IE " + i + "]><span></span><![endif]-->"; if (div.getElementsByTagName("span").length) { div = null; return i; } } } return undefined; })(); /* rAF shim. Gist: https://gist.github.com/julianshapiro/9497513 */ var rAFShim = (function() { var timeLast = 0; return window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) { var timeCurrent = (new Date()).getTime(), timeDelta; /* Dynamically set delay on a per-tick basis to match 60fps. */ /* Technique by Erik Moller. MIT license: https://gist.github.com/paulirish/1579671 */ timeDelta = Math.max(0, 16 - (timeCurrent - timeLast)); timeLast = timeCurrent + timeDelta; return setTimeout(function() { callback(timeCurrent + timeDelta); }, timeDelta); }; })(); /* Array compacting. Copyright Lo-Dash. MIT License: https://github.com/lodash/lodash/blob/master/LICENSE.txt */ function compactSparseArray(array) { var index = -1, length = array ? array.length : 0, result = []; while (++index < length) { var value = array[index]; if (value) { result.push(value); } } return result; } function sanitizeElements(elements) { /* Unwrap jQuery/Zepto objects. */ if (Type.isWrapped(elements)) { elements = [].slice.call(elements); /* Wrap a single element in an array so that $.each() can iterate with the element instead of its node's children. */ } else if (Type.isNode(elements)) { elements = [elements]; } return elements; } var Type = { isString: function(variable) { return (typeof variable === "string"); }, isArray: Array.isArray || function(variable) { return Object.prototype.toString.call(variable) === "[object Array]"; }, isFunction: function(variable) { return Object.prototype.toString.call(variable) === "[object Function]"; }, isNode: function(variable) { return variable && variable.nodeType; }, /* Copyright Martin Bohm. MIT License: https://gist.github.com/Tomalak/818a78a226a0738eaade */ isNodeList: function(variable) { return typeof variable === "object" && /^\[object (HTMLCollection|NodeList|Object)\]$/.test(Object.prototype.toString.call(variable)) && variable.length !== undefined && (variable.length === 0 || (typeof variable[0] === "object" && variable[0].nodeType > 0)); }, /* Determine if variable is a wrapped jQuery or Zepto element. */ isWrapped: function(variable) { return variable && (variable.jquery || (window.Zepto && window.Zepto.zepto.isZ(variable))); }, isSVG: function(variable) { return window.SVGElement && (variable instanceof window.SVGElement); }, isEmptyObject: function(variable) { for (var name in variable) { if (variable.hasOwnProperty(name)) { return false; } } return true; } }; /***************** Dependencies *****************/ var $, isJQuery = false; if (global.fn && global.fn.jquery) { $ = global; isJQuery = true; } else { $ = window.Velocity.Utilities; } if (IE <= 8 && !isJQuery) { throw new Error("Velocity: IE8 and below require jQuery to be loaded before Velocity."); } else if (IE <= 7) { /* Revert to jQuery's $.animate(), and lose Velocity's extra features. */ jQuery.fn.velocity = jQuery.fn.animate; /* Now that $.fn.velocity is aliased, abort this Velocity declaration. */ return; } /***************** Constants *****************/ var DURATION_DEFAULT = 400, EASING_DEFAULT = "swing"; /************* State *************/ var Velocity = { /* Container for page-wide Velocity state data. */ State: { /* Detect mobile devices to determine if mobileHA should be turned on. */ isMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent), /* The mobileHA option's behavior changes on older Android devices (Gingerbread, versions 2.3.3-2.3.7). */ isAndroid: /Android/i.test(navigator.userAgent), isGingerbread: /Android 2\.3\.[3-7]/i.test(navigator.userAgent), isChrome: window.chrome, isFirefox: /Firefox/i.test(navigator.userAgent), /* Create a cached element for re-use when checking for CSS property prefixes. */ prefixElement: document.createElement("div"), /* Cache every prefix match to avoid repeating lookups. */ prefixMatches: {}, /* Cache the anchor used for animating window scrolling. */ scrollAnchor: null, /* Cache the browser-specific property names associated with the scroll anchor. */ scrollPropertyLeft: null, scrollPropertyTop: null, /* Keep track of whether our RAF tick is running. */ isTicking: false, /* Container for every in-progress call to Velocity. */ calls: [] }, /* Velocity's custom CSS stack. Made global for unit testing. */ CSS: { /* Defined below. */}, /* A shim of the jQuery utility functions used by Velocity -- provided by Velocity's optional jQuery shim. */ Utilities: $, /* Container for the user's custom animation redirects that are referenced by name in place of the properties map argument. */ Redirects: { /* Manually registered by the user. */}, Easings: { /* Defined below. */}, /* Attempt to use ES6 Promises by default. Users can override this with a third-party promises library. */ Promise: window.Promise, /* Velocity option defaults, which can be overriden by the user. */ defaults: { queue: "", duration: DURATION_DEFAULT, easing: EASING_DEFAULT, begin: undefined, complete: undefined, progress: undefined, display: undefined, visibility: undefined, loop: false, delay: false, mobileHA: true, /* Advanced: Set to false to prevent property values from being cached between consecutive Velocity-initiated chain calls. */ _cacheValues: true, /* Advanced: Set to false if the promise should always resolve on empty element lists. */ promiseRejectEmpty: true }, /* A design goal of Velocity is to cache data wherever possible in order to avoid DOM requerying. Accordingly, each element has a data cache. */ init: function(element) { $.data(element, "velocity", { /* Store whether this is an SVG element, since its properties are retrieved and updated differently than standard HTML elements. */ isSVG: Type.isSVG(element), /* Keep track of whether the element is currently being animated by Velocity. This is used to ensure that property values are not transferred between non-consecutive (stale) calls. */ isAnimating: false, /* A reference to the element's live computedStyle object. Learn more here: https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle */ computedStyle: null, /* Tween data is cached for each animation on the element so that data can be passed across calls -- in particular, end values are used as subsequent start values in consecutive Velocity calls. */ tweensContainer: null, /* The full root property values of each CSS hook being animated on this element are cached so that: 1) Concurrently-animating hooks sharing the same root can have their root values' merged into one while tweening. 2) Post-hook-injection root values can be transferred over to consecutively chained Velocity calls as starting root values. */ rootPropertyValueCache: {}, /* A cache for transform updates, which must be manually flushed via CSS.flushTransformCache(). */ transformCache: {} }); }, /* A parallel to jQuery's $.css(), used for getting/setting Velocity's hooked CSS properties. */ hook: null, /* Defined below. */ /* Velocity-wide animation time remapping for testing purposes. */ mock: false, version: {major: 1, minor: 3, patch: 1}, /* Set to 1 or 2 (most verbose) to output debug info to console. */ debug: false, /* Use rAF high resolution timestamp when available */ timestamp: true }; /* Retrieve the appropriate scroll anchor and property name for the browser: https://developer.mozilla.org/en-US/docs/Web/API/Window.scrollY */ if (window.pageYOffset !== undefined) { Velocity.State.scrollAnchor = window; Velocity.State.scrollPropertyLeft = "pageXOffset"; Velocity.State.scrollPropertyTop = "pageYOffset"; } else { Velocity.State.scrollAnchor = document.documentElement || document.body.parentNode || document.body; Velocity.State.scrollPropertyLeft = "scrollLeft"; Velocity.State.scrollPropertyTop = "scrollTop"; } /* Shorthand alias for jQuery's $.data() utility. */ function Data(element) { /* Hardcode a reference to the plugin name. */ var response = $.data(element, "velocity"); /* jQuery <=1.4.2 returns null instead of undefined when no match is found. We normalize this behavior. */ return response === null ? undefined : response; } /************** Easing **************/ /* Step easing generator. */ function generateStep(steps) { return function(p) { return Math.round(p * steps) * (1 / steps); }; } /* Bezier curve function generator. Copyright Gaetan Renaudeau. MIT License: http://en.wikipedia.org/wiki/MIT_License */ function generateBezier(mX1, mY1, mX2, mY2) { var NEWTON_ITERATIONS = 4, NEWTON_MIN_SLOPE = 0.001, SUBDIVISION_PRECISION = 0.0000001, SUBDIVISION_MAX_ITERATIONS = 10, kSplineTableSize = 11, kSampleStepSize = 1.0 / (kSplineTableSize - 1.0), float32ArraySupported = "Float32Array" in window; /* Must contain four arguments. */ if (arguments.length !== 4) { return false; } /* Arguments must be numbers. */ for (var i = 0; i < 4; ++i) { if (typeof arguments[i] !== "number" || isNaN(arguments[i]) || !isFinite(arguments[i])) { return false; } } /* X values must be in the [0, 1] range. */ mX1 = Math.min(mX1, 1); mX2 = Math.min(mX2, 1); mX1 = Math.max(mX1, 0); mX2 = Math.max(mX2, 0); var mSampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize); 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; } function calcBezier(aT, aA1, aA2) { return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT; } function getSlope(aT, aA1, aA2) { return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1); } function newtonRaphsonIterate(aX, aGuessT) { 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; } function calcSampleValues() { for (var i = 0; i < kSplineTableSize; ++i) { mSampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2); } } function binarySubdivide(aX, aA, aB) { 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 getTForX(aX) { var intervalStart = 0.0, currentSample = 1, lastSample = kSplineTableSize - 1; for (; currentSample !== lastSample && mSampleValues[currentSample] <= aX; ++currentSample) { intervalStart += kSampleStepSize; } --currentSample; var dist = (aX - mSampleValues[currentSample]) / (mSampleValues[currentSample + 1] - mSampleValues[currentSample]), guessForT = intervalStart + dist * kSampleStepSize, initialSlope = getSlope(guessForT, mX1, mX2); if (initialSlope >= NEWTON_MIN_SLOPE) { return newtonRaphsonIterate(aX, guessForT); } else if (initialSlope === 0.0) { return guessForT; } else { return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize); } } var _precomputed = false; function precompute() { _precomputed = true; if (mX1 !== mY1 || mX2 !== mY2) { calcSampleValues(); } } var f = function(aX) { if (!_precomputed) { precompute(); } if (mX1 === mY1 && mX2 === mY2) { return aX; } if (aX === 0) { return 0; } if (aX === 1) { return 1; } return calcBezier(getTForX(aX), mY1, mY2); }; f.getControlPoints = function() { return [{x: mX1, y: mY1}, {x: mX2, y: mY2}]; }; var str = "generateBezier(" + [mX1, mY1, mX2, mY2] + ")"; f.toString = function() { return str; }; return f; } /* Runge-Kutta spring physics function generator. Adapted from Framer.js, copyright Koen Bok. MIT License: http://en.wikipedia.org/wiki/MIT_License */ /* Given a tension, friction, and duration, a simulation at 60FPS will first run without a defined duration in order to calculate the full path. A second pass then adjusts the time delta -- using the relation between actual time and duration -- to calculate the path for the duration-constrained animation. */ var generateSpringRK4 = (function() { function springAccelerationForState(state) { return (-state.tension * state.x) - (state.friction * state.v); } function springEvaluateStateWithDerivative(initialState, dt, derivative) { var state = { x: initialState.x + derivative.dx * dt, v: initialState.v + derivative.dv * dt, tension: initialState.tension, friction: initialState.friction }; return {dx: state.v, dv: springAccelerationForState(state)}; } function springIntegrateState(state, dt) { var a = { dx: state.v, dv: springAccelerationForState(state) }, b = springEvaluateStateWithDerivative(state, dt * 0.5, a), c = springEvaluateStateWithDerivative(state, dt * 0.5, b), d = springEvaluateStateWithDerivative(state, dt, c), dxdt = 1.0 / 6.0 * (a.dx + 2.0 * (b.dx + c.dx) + d.dx), dvdt = 1.0 / 6.0 * (a.dv + 2.0 * (b.dv + c.dv) + d.dv); state.x = state.x + dxdt * dt; state.v = state.v + dvdt * dt; return state; } return function springRK4Factory(tension, friction, duration) { var initState = { x: -1, v: 0, tension: null, friction: null }, path = [0], time_lapsed = 0, tolerance = 1 / 10000, DT = 16 / 1000, have_duration, dt, last_state; tension = parseFloat(tension) || 500; friction = parseFloat(friction) || 20; duration = duration || null; initState.tension = tension; initState.friction = friction; have_duration = duration !== null; /* Calculate the actual time it takes for this animation to complete with the provided conditions. */ if (have_duration) { /* Run the simulation without a duration. */ time_lapsed = springRK4Factory(tension, friction); /* Compute the adjusted time delta. */ dt = time_lapsed / duration * DT; } else { dt = DT; } while (true) { /* Next/step function .*/ last_state = springIntegrateState(last_state || initState, dt); /* Store the position. */ path.push(1 + last_state.x); time_lapsed += 16; /* If the change threshold is reached, break. */ if (!(Math.abs(last_state.x) > tolerance && Math.abs(last_state.v) > tolerance)) { break; } } /* If duration is not defined, return the actual time required for completing this animation. Otherwise, return a closure that holds the computed path and returns a snapshot of the position according to a given percentComplete. */ return !have_duration ? time_lapsed : function(percentComplete) { return path[ (percentComplete * (path.length - 1)) | 0 ]; }; }; }()); /* jQuery easings. */ Velocity.Easings = { linear: function(p) { return p; }, swing: function(p) { return 0.5 - Math.cos(p * Math.PI) / 2; }, /* Bonus "spring" easing, which is a less exaggerated version of easeInOutElastic. */ spring: function(p) { return 1 - (Math.cos(p * 4.5 * Math.PI) * Math.exp(-p * 6)); } }; /* CSS3 and Robert Penner easings. */ $.each( [ ["ease", [0.25, 0.1, 0.25, 1.0]], ["ease-in", [0.42, 0.0, 1.00, 1.0]], ["ease-out", [0.00, 0.0, 0.58, 1.0]], ["ease-in-out", [0.42, 0.0, 0.58, 1.0]], ["easeInSine", [0.47, 0, 0.745, 0.715]], ["easeOutSine", [0.39, 0.575, 0.565, 1]], ["easeInOutSine", [0.445, 0.05, 0.55, 0.95]], ["easeInQuad", [0.55, 0.085, 0.68, 0.53]], ["easeOutQuad", [0.25, 0.46, 0.45, 0.94]], ["easeInOutQuad", [0.455, 0.03, 0.515, 0.955]], ["easeInCubic", [0.55, 0.055, 0.675, 0.19]], ["easeOutCubic", [0.215, 0.61, 0.355, 1]], ["easeInOutCubic", [0.645, 0.045, 0.355, 1]], ["easeInQuart", [0.895, 0.03, 0.685, 0.22]], ["easeOutQuart", [0.165, 0.84, 0.44, 1]], ["easeInOutQuart", [0.77, 0, 0.175, 1]], ["easeInQuint", [0.755, 0.05, 0.855, 0.06]], ["easeOutQuint", [0.23, 1, 0.32, 1]], ["easeInOutQuint", [0.86, 0, 0.07, 1]], ["easeInExpo", [0.95, 0.05, 0.795, 0.035]], ["easeOutExpo", [0.19, 1, 0.22, 1]], ["easeInOutExpo", [1, 0, 0, 1]], ["easeInCirc", [0.6, 0.04, 0.98, 0.335]], ["easeOutCirc", [0.075, 0.82, 0.165, 1]], ["easeInOutCirc", [0.785, 0.135, 0.15, 0.86]] ], function(i, easingArray) { Velocity.Easings[easingArray[0]] = generateBezier.apply(null, easingArray[1]); }); /* Determine the appropriate easing type given an easing input. */ function getEasing(value, duration) { var easing = value; /* The easing option can either be a string that references a pre-registered easing, or it can be a two-/four-item array of integers to be converted into a bezier/spring function. */ if (Type.isString(value)) { /* Ensure that the easing has been assigned to jQuery's Velocity.Easings object. */ if (!Velocity.Easings[value]) { easing = false; } } else if (Type.isArray(value) && value.length === 1) { easing = generateStep.apply(null, value); } else if (Type.isArray(value) && value.length === 2) { /* springRK4 must be passed the animation's duration. */ /* Note: If the springRK4 array contains non-numbers, generateSpringRK4() returns an easing function generated with default tension and friction values. */ easing = generateSpringRK4.apply(null, value.concat([duration])); } else if (Type.isArray(value) && value.length === 4) { /* Note: If the bezier array contains non-numbers, generateBezier() returns false. */ easing = generateBezier.apply(null, value); } else { easing = false; } /* Revert to the Velocity-wide default easing type, or fall back to "swing" (which is also jQuery's default) if the Velocity-wide default has been incorrectly modified. */ if (easing === false) { if (Velocity.Easings[Velocity.defaults.easing]) { easing = Velocity.defaults.easing; } else { easing = EASING_DEFAULT; } } return easing; } /***************** CSS Stack *****************/ /* The CSS object is a highly condensed and performant CSS stack that fully replaces jQuery's. It handles the validation, getting, and setting of both standard CSS properties and CSS property hooks. */ /* Note: A "CSS" shorthand is aliased so that our code is easier to read. */ var CSS = Velocity.CSS = { /************* RegEx *************/ RegEx: { isHex: /^#([A-f\d]{3}){1,2}$/i, /* Unwrap a property value's surrounding text, e.g. "rgba(4, 3, 2, 1)" ==> "4, 3, 2, 1" and "rect(4px 3px 2px 1px)" ==> "4px 3px 2px 1px". */ valueUnwrap: /^[A-z]+\((.*)\)$/i, wrappedValueAlreadyExtracted: /[0-9.]+ [0-9.]+ [0-9.]+( [0-9.]+)?/, /* Split a multi-value property into an array of subvalues, e.g. "rgba(4, 3, 2, 1) 4px 3px 2px 1px" ==> [ "rgba(4, 3, 2, 1)", "4px", "3px", "2px", "1px" ]. */ valueSplit: /([A-z]+\(.+\))|(([A-z0-9#-.]+?)(?=\s|$))/ig }, /************ Lists ************/ Lists: { colors: ["fill", "stroke", "stopColor", "color", "backgroundColor", "borderColor", "borderTopColor", "borderRightColor", "borderBottomColor", "borderLeftColor", "outlineColor"], transformsBase: ["translateX", "translateY", "scale", "scaleX", "scaleY", "skewX", "skewY", "rotateZ"], transforms3D: ["transformPerspective", "translateZ", "scaleZ", "rotateX", "rotateY"] }, /************ Hooks ************/ /* Hooks allow a subproperty (e.g. "boxShadowBlur") of a compound-value CSS property (e.g. "boxShadow: X Y Blur Spread Color") to be animated as if it were a discrete property. */ /* Note: Beyond enabling fine-grained property animation, hooking is necessary since Velocity only tweens properties with single numeric values; unlike CSS transitions, Velocity does not interpolate compound-values. */ Hooks: { /******************** Registration ********************/ /* Templates are a concise way of indicating which subproperties must be individually registered for each compound-value CSS property. */ /* Each template consists of the compound-value's base name, its constituent subproperty names, and those subproperties' default values. */ templates: { "textShadow": ["Color X Y Blur", "black 0px 0px 0px"], "boxShadow": ["Color X Y Blur Spread", "black 0px 0px 0px 0px"], "clip": ["Top Right Bottom Left", "0px 0px 0px 0px"], "backgroundPosition": ["X Y", "0% 0%"], "transformOrigin": ["X Y Z", "50% 50% 0px"], "perspectiveOrigin": ["X Y", "50% 50%"] }, /* A "registered" hook is one that has been converted from its template form into a live, tweenable property. It contains data to associate it with its root property. */ registered: { /* Note: A registered hook looks like this ==> textShadowBlur: [ "textShadow", 3 ], which consists of the subproperty's name, the associated root property's name, and the subproperty's position in the root's value. */ }, /* Convert the templates into individual hooks then append them to the registered object above. */ register: function() { /* Color hooks registration: Colors are defaulted to white -- as opposed to black -- since colors that are currently set to "transparent" default to their respective template below when color-animated, and white is typically a closer match to transparent than black is. An exception is made for text ("color"), which is almost always set closer to black than white. */ for (var i = 0; i < CSS.Lists.colors.length; i++) { var rgbComponents = (CSS.Lists.colors[i] === "color") ? "0 0 0 1" : "255 255 255 1"; CSS.Hooks.templates[CSS.Lists.colors[i]] = ["Red Green Blue Alpha", rgbComponents]; } var rootProperty, hookTemplate, hookNames; /* In IE, color values inside compound-value properties are positioned at the end the value instead of at the beginning. Thus, we re-arrange the templates accordingly. */ if (IE) { for (rootProperty in CSS.Hooks.templates) { if (!CSS.Hooks.templates.hasOwnProperty(rootProperty)) { continue; } hookTemplate = CSS.Hooks.templates[rootProperty]; hookNames = hookTemplate[0].split(" "); var defaultValues = hookTemplate[1].match(CSS.RegEx.valueSplit); if (hookNames[0] === "Color") { /* Reposition both the hook's name and its default value to the end of their respective strings. */ hookNames.push(hookNames.shift()); defaultValues.push(defaultValues.shift()); /* Replace the existing template for the hook's root property. */ CSS.Hooks.templates[rootProperty] = [hookNames.join(" "), defaultValues.join(" ")]; } } } /* Hook registration. */ for (rootProperty in CSS.Hooks.templates) { if (!CSS.Hooks.templates.hasOwnProperty(rootProperty)) { continue; } hookTemplate = CSS.Hooks.templates[rootProperty]; hookNames = hookTemplate[0].split(" "); for (var j in hookNames) { if (!hookNames.hasOwnProperty(j)) { continue; } var fullHookName = rootProperty + hookNames[j], hookPosition = j; /* For each hook, register its full name (e.g. textShadowBlur) with its root property (e.g. textShadow) and the hook's position in its template's default value string. */ CSS.Hooks.registered[fullHookName] = [rootProperty, hookPosition]; } } }, /***************************** Injection and Extraction *****************************/ /* Look up the root property associated with the hook (e.g. return "textShadow" for "textShadowBlur"). */ /* Since a hook cannot be set directly (the browser won't recognize it), style updating for hooks is routed through the hook's root property. */ getRoot: function(property) { var hookData = CSS.Hooks.registered[property]; if (hookData) { return hookData[0]; } else { /* If there was no hook match, return the property name untouched. */ return property; } }, /* Convert any rootPropertyValue, null or otherwise, into a space-delimited list of hook values so that the targeted hook can be injected or extracted at its standard position. */ cleanRootPropertyValue: function(rootProperty, rootPropertyValue) { /* If the rootPropertyValue is wrapped with "rgb()", "clip()", etc., remove the wrapping to normalize the value before manipulation. */ if (CSS.RegEx.valueUnwrap.test(rootPropertyValue)) { rootPropertyValue = rootPropertyValue.match(CSS.RegEx.valueUnwrap)[1]; } /* If rootPropertyValue is a CSS null-value (from which there's inherently no hook value to extract), default to the root's default value as defined in CSS.Hooks.templates. */ /* Note: CSS null-values include "none", "auto", and "transparent". They must be converted into their zero-values (e.g. textShadow: "none" ==> textShadow: "0px 0px 0px black") for hook manipulation to proceed. */ if (CSS.Values.isCSSNullValue(rootPropertyValue)) { rootPropertyValue = CSS.Hooks.templates[rootProperty][1]; } return rootPropertyValue; }, /* Extracted the hook's value from its root property's value. This is used to get the starting value of an animating hook. */ extractValue: function(fullHookName, rootPropertyValue) { var hookData = CSS.Hooks.registered[fullHookName]; if (hookData) { var hookRoot = hookData[0], hookPosition = hookData[1]; rootPropertyValue = CSS.Hooks.cleanRootPropertyValue(hookRoot, rootPropertyValue); /* Split rootPropertyValue into its constituent hook values then grab the desired hook at its standard position. */ return rootPropertyValue.toString().match(CSS.RegEx.valueSplit)[hookPosition]; } else { /* If the provided fullHookName isn't a registered hook, return the rootPropertyValue that was passed in. */ return rootPropertyValue; } }, /* Inject the hook's value into its root property's value. This is used to piece back together the root property once Velocity has updated one of its individually hooked values through tweening. */ injectValue: function(fullHookName, hookValue, rootPropertyValue) { var hookData = CSS.Hooks.registered[fullHookName]; if (hookData) { var hookRoot = hookData[0], hookPosition = hookData[1], rootPropertyValueParts, rootPropertyValueUpdated; rootPropertyValue = CSS.Hooks.cleanRootPropertyValue(hookRoot, rootPropertyValue); /* Split rootPropertyValue into its individual hook values, replace the targeted value with hookValue, then reconstruct the rootPropertyValue string. */ rootPropertyValueParts = rootPropertyValue.toString().match(CSS.RegEx.valueSplit); rootPropertyValueParts[hookPosition] = hookValue; rootPropertyValueUpdated = rootPropertyValueParts.join(" "); return rootPropertyValueUpdated; } else { /* If the provided fullHookName isn't a registered hook, return the rootPropertyValue that was passed in. */ return rootPropertyValue; } } }, /******************* Normalizations *******************/ /* Normalizations standardize CSS property manipulation by pollyfilling browser-specific implementations (e.g. opacity) and reformatting special properties (e.g. clip, rgba) to look like standard ones. */ Normalizations: { /* Normalizations are passed a normalization target (either the property's name, its extracted value, or its injected value), the targeted element (which may need to be queried), and the targeted property value. */ registered: { clip: function(type, element, propertyValue) { switch (type) { case "name": return "clip"; /* Clip needs to be unwrapped and stripped of its commas during extraction. */ case "extract": var extracted; /* If Velocity also extracted this value, skip extraction. */ if (CSS.RegEx.wrappedValueAlreadyExtracted.test(propertyValue)) { extracted = propertyValue; } else { /* Remove the "rect()" wrapper. */ extracted = propertyValue.toString().match(CSS.RegEx.valueUnwrap); /* Strip off commas. */ extracted = extracted ? extracted[1].replace(/,(\s+)?/g, " ") : propertyValue; } return extracted; /* Clip needs to be re-wrapped during injection. */ case "inject": return "rect(" + propertyValue + ")"; } }, blur: function(type, element, propertyValue) { switch (type) { case "name": return Velocity.State.isFirefox ? "filter" : "-webkit-filter"; case "extract": var extracted = parseFloat(propertyValue); /* If extracted is NaN, meaning the value isn't already extracted. */ if (!(extracted || extracted === 0)) { var blurComponent = propertyValue.toString().match(/blur\(([0-9]+[A-z]+)\)/i); /* If the filter string had a blur component, return just the blur value and unit type. */ if (blurComponent) { extracted = blurComponent[1]; /* If the component doesn't exist, default blur to 0. */ } else { extracted = 0; } } return extracted; /* Blur needs to be re-wrapped during injection. */ case "inject": /* For the blur effect to be fully de-applied, it needs to be set to "none" instead of 0. */ if (!parseFloat(propertyValue)) { return "none"; } else { return "blur(" + propertyValue + ")"; } } }, /* <=IE8 do not support the standard opacity property. They use filter:alpha(opacity=INT) instead. */ opacity: function(type, element, propertyValue) { if (IE <= 8) { switch (type) { case "name": return "filter"; case "extract": /* <=IE8 return a "filter" value of "alpha(opacity=\d{1,3})". Extract the value and convert it to a decimal value to match the standard CSS opacity property's formatting. */ var extracted = propertyValue.toString().match(/alpha\(opacity=(.*)\)/i); if (extracted) { /* Convert to decimal value. */ propertyValue = extracted[1] / 100; } else { /* When extracting opacity, default to 1 since a null value means opacity hasn't been set. */ propertyValue = 1; } return propertyValue; case "inject": /* Opacified elements are required to have their zoom property set to a non-zero value. */ element.style.zoom = 1; /* Setting the filter property on elements with certain font property combinations can result in a highly unappealing ultra-bolding effect. There's no way to remedy this throughout a tween, but dropping the value altogether (when opacity hits 1) at leasts ensures that the glitch is gone post-tweening. */ if (parseFloat(propertyValue) >= 1) { return ""; } else { /* As per the filter property's spec, convert the decimal value to a whole number and wrap the value. */ return "alpha(opacity=" + parseInt(parseFloat(propertyValue) * 100, 10) + ")"; } } /* With all other browsers, normalization is not required; return the same values that were passed in. */ } else { switch (type) { case "name": return "opacity"; case "extract": return propertyValue; case "inject": return propertyValue; } } } }, /***************************** Batched Registrations *****************************/ /* Note: Batched normalizations extend the CSS.Normalizations.registered object. */ register: function() { /***************** Transforms *****************/ /* Transforms are the subproperties contained by the CSS "transform" property. Transforms must undergo normalization so that they can be referenced in a properties map by their individual names. */ /* Note: When transforms are "set", they are actually assigned to a per-element transformCache. When all transform setting is complete complete, CSS.flushTransformCache() must be manually called to flush the values to the DOM. Transform setting is batched in this way to improve performance: the transform style only needs to be updated once when multiple transform subproperties are being animated simultaneously. */ /* Note: IE9 and Android Gingerbread have support for 2D -- but not 3D -- transforms. Since animating unsupported transform properties results in the browser ignoring the *entire* transform string, we prevent these 3D values from being normalized for these browsers so that tweening skips these properties altogether (since it will ignore them as being unsupported by the browser.) */ if ((!IE || IE > 9) && !Velocity.State.isGingerbread) { /* Note: Since the standalone CSS "perspective" property and the CSS transform "perspective" subproperty share the same name, the latter is given a unique token within Velocity: "transformPerspective". */ CSS.Lists.transformsBase = CSS.Lists.transformsBase.concat(CSS.Lists.transforms3D); } for (var i = 0; i < CSS.Lists.transformsBase.length; i++) { /* Wrap the dynamically generated normalization function in a new scope so that transformName's value is paired with its respective function. (Otherwise, all functions would take the final for loop's transformName.) */ (function() { var transformName = CSS.Lists.transformsBase[i]; CSS.Normalizations.registered[transformName] = function(type, element, propertyValue) { switch (type) { /* The normalized property name is the parent "transform" property -- the property that is actually set in CSS. */ case "name": return "transform"; /* Transform values are cached onto a per-element transformCache object. */ case "extract": /* If this transform has yet to be assigned a value, return its null value. */ if (Data(element) === undefined || Data(element).transformCache[transformName] === undefined) { /* Scale CSS.Lists.transformsBase default to 1 whereas all other transform properties default to 0. */ return /^scale/i.test(transformName) ? 1 : 0; /* When transform values are set, they are wrapped in parentheses as per the CSS spec. Thus, when extracting their values (for tween calculations), we strip off the parentheses. */ } return Data(element).transformCache[transformName].replace(/[()]/g, ""); case "inject": var invalid = false; /* If an individual transform property contains an unsupported unit type, the browser ignores the *entire* transform property. Thus, protect users from themselves by skipping setting for transform values supplied with invalid unit types. */ /* Switch on the base transform type; ignore the axis by removing the last letter from the transform's name. */ switch (transformName.substr(0, transformName.length - 1)) { /* Whitelist unit types for each transform. */ case "translate": invalid = !/(%|px|em|rem|vw|vh|\d)$/i.test(propertyValue); break; /* Since an axis-free "scale" property is supported as well, a little hack is used here to detect it by chopping off its last letter. */ case "scal": case "scale": /* Chrome on Android has a bug in which scaled elements blur if their initial scale value is below 1 (which can happen with forcefeeding). Thus, we detect a yet-unset scale property and ensure that its first value is always 1. More info: http://stackoverflow.com/questions/10417890/css3-animations-with-transform-causes-blurred-elements-on-webkit/10417962#10417962 */ if (Velocity.State.isAndroid && Data(element).transformCache[transformName] === undefined && propertyValue < 1) { propertyValue = 1; } invalid = !/(\d)$/i.test(propertyValue); break; case "skew": invalid = !/(deg|\d)$/i.test(propertyValue); break; case "rotate": invalid = !/(deg|\d)$/i.test(propertyValue); break; } if (!invalid) { /* As per the CSS spec, wrap the value in parentheses. */ Data(element).transformCache[transformName] = "(" + propertyValue + ")"; } /* Although the value is set on the transformCache object, return the newly-updated value for the calling code to process as normal. */ return Data(element).transformCache[transformName]; } }; })(); } /************* Colors *************/ /* Since Velocity only animates a single numeric value per property, color animation is achieved by hooking the individual RGBA components of CSS color properties. Accordingly, color values must be normalized (e.g. "#ff0000", "red", and "rgb(255, 0, 0)" ==> "255 0 0 1") so that their components can be injected/extracted by CSS.Hooks logic. */ for (var j = 0; j < CSS.Lists.colors.length; j++) { /* Wrap the dynamically generated normalization function in a new scope so that colorName's value is paired with its respective function. (Otherwise, all functions would take the final for loop's colorName.) */ (function() { var colorName = CSS.Lists.colors[j]; /* Note: In IE<=8, which support rgb but not rgba, color properties are reverted to rgb by stripping off the alpha component. */ CSS.Normalizations.registered[colorName] = function(type, element, propertyValue) { switch (type) { case "name": return colorName; /* Convert all color values into the rgb format. (Old IE can return hex values and color names instead of rgb/rgba.) */ case "extract": var extracted; /* If the color is already in its hookable form (e.g. "255 255 255 1") due to having been previously extracted, skip extraction. */ if (CSS.RegEx.wrappedValueAlreadyExtracted.test(propertyValue)) { extracted = propertyValue; } else { var converted, colorNames = { black: "rgb(0, 0, 0)", blue: "rgb(0, 0, 255)", gray: "rgb(128, 128, 128)", green: "rgb(0, 128, 0)", red: "rgb(255, 0, 0)", white: "rgb(255, 255, 255)" }; /* Convert color names to rgb. */ if (/^[A-z]+$/i.test(propertyValue)) { if (colorNames[propertyValue] !== undefined) { converted = colorNames[propertyValue]; } else { /* If an unmatched color name is provided, default to black. */ converted = colorNames.black; } /* Convert hex values to rgb. */ } else if (CSS.RegEx.isHex.test(propertyValue)) { converted = "rgb(" + CSS.Values.hexToRgb(propertyValue).join(" ") + ")"; /* If the provided color doesn't match any of the accepted color formats, default to black. */ } else if (!(/^rgba?\(/i.test(propertyValue))) { converted = colorNames.black; } /* Remove the surrounding "rgb/rgba()" string then replace commas with spaces and strip repeated spaces (in case the value included spaces to begin with). */ extracted = (converted || propertyValue).toString().match(CSS.RegEx.valueUnwrap)[1].replace(/,(\s+)?/g, " "); } /* So long as this isn't <=IE8, add a fourth (alpha) component if it's missing and default it to 1 (visible). */ if ((!IE || IE > 8) && extracted.split(" ").length === 3) { extracted += " 1"; } return extracted; case "inject": /* If this is IE<=8 and an alpha component exists, strip it off. */ if (IE <= 8) { if (propertyValue.split(" ").length === 4) { propertyValue = propertyValue.split(/\s+/).slice(0, 3).join(" "); } /* Otherwise, add a fourth (alpha) component if it's missing and default it to 1 (visible). */ } else if (propertyValue.split(" ").length === 3) { propertyValue += " 1"; } /* Re-insert the browser-appropriate wrapper("rgb/rgba()"), insert commas, and strip off decimal units on all values but the fourth (R, G, and B only accept whole numbers). */ return (IE <= 8 ? "rgb" : "rgba") + "(" + propertyValue.replace(/\s+/g, ",").replace(/\.(\d)+(?=,)/g, "") + ")"; } }; })(); } /************** Dimensions **************/ function augmentDimension(name, element, wantInner) { var isBorderBox = CSS.getPropertyValue(element, "boxSizing").toString().toLowerCase() === "border-box"; if (isBorderBox === (wantInner || false)) { /* in box-sizing mode, the CSS width / height accessors already give the outerWidth / outerHeight. */ var i, value, augment = 0, sides = name === "width" ? ["Left", "Right"] : ["Top", "Bottom"], fields = ["padding" + sides[0], "padding" + sides[1], "border" + sides[0] + "Width", "border" + sides[1] + "Width"]; for (i = 0; i < fields.length; i++) { value = parseFloat(CSS.getPropertyValue(element, fields[i])); if (!isNaN(value)) { augment += value; } } return wantInner ? -augment : augment; } return 0; } function getDimension(name, wantInner) { return function(type, element, propertyValue) { switch (type) { case "name": return name; case "extract": return parseFloat(propertyValue) + augmentDimension(name, element, wantInner); case "inject": return (parseFloat(propertyValue) - augmentDimension(name, element, wantInner)) + "px"; } }; } CSS.Normalizations.registered.innerWidth = getDimension("width", true); CSS.Normalizations.registered.innerHeight = getDimension("height", true); CSS.Normalizations.registered.outerWidth = getDimension("width"); CSS.Normalizations.registered.outerHeight = getDimension("height"); } }, /************************ CSS Property Names ************************/ Names: { /* Camelcase a property name into its JavaScript notation (e.g. "background-color" ==> "backgroundColor"). Camelcasing is used to normalize property names between and across calls. */ camelCase: function(property) { return property.replace(/-(\w)/g, function(match, subMatch) { return subMatch.toUpperCase(); }); }, /* For SVG elements, some properties (namely, dimensional ones) are GET/SET via the element's HTML attributes (instead of via CSS styles). */ SVGAttribute: function(property) { var SVGAttributes = "width|height|x|y|cx|cy|r|rx|ry|x1|x2|y1|y2"; /* Certain browsers require an SVG transform to be applied as an attribute. (Otherwise, application via CSS is preferable due to 3D support.) */ if (IE || (Velocity.State.isAndroid && !Velocity.State.isChrome)) { SVGAttributes += "|transform"; } return new RegExp("^(" + SVGAttributes + ")$", "i").test(property); }, /* Determine whether a property should be set with a vendor prefix. */ /* If a prefixed version of the property exists, return it. Otherwise, return the original property name. If the property is not at all supported by the browser, return a false flag. */ prefixCheck: function(property) { /* If this property has already been checked, return the cached value. */ if (Velocity.State.prefixMatches[property]) { return [Velocity.State.prefixMatches[property], true]; } else { var vendors = ["", "Webkit", "Moz", "ms", "O"]; for (var i = 0, vendorsLength = vendors.length; i < vendorsLength; i++) { var propertyPrefixed; if (i === 0) { propertyPrefixed = property; } else { /* Capitalize the first letter of the property to conform to JavaScript vendor prefix notation (e.g. webkitFilter). */ propertyPrefixed = vendors[i] + property.replace(/^\w/, function(match) { return match.toUpperCase(); }); } /* Check if the browser supports this property as prefixed. */ if (Type.isString(Velocity.State.prefixElement.style[propertyPrefixed])) { /* Cache the match. */ Velocity.State.prefixMatches[property] = propertyPrefixed; return [propertyPrefixed, true]; } } /* If the browser doesn't support this property in any form, include a false flag so that the caller can decide how to proceed. */ return [property, false]; } } }, /************************ CSS Property Values ************************/ Values: { /* Hex to RGB conversion. Copyright Tim Down: http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb */ hexToRgb: function(hex) { var shortformRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i, longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i, rgbParts; hex = hex.replace(shortformRegex, function(m, r, g, b) { return r + r + g + g + b + b; }); rgbParts = longformRegex.exec(hex); return rgbParts ? [parseInt(rgbParts[1], 16), parseInt(rgbParts[2], 16), parseInt(rgbParts[3], 16)] : [0, 0, 0]; }, isCSSNullValue: function(value) { /* The browser defaults CSS values that have not been set to either 0 or one of several possible null-value strings. Thus, we check for both falsiness and these special strings. */ /* Null-value checking is performed to default the special strings to 0 (for the sake of tweening) or their hook templates as defined as CSS.Hooks (for the sake of hook injection/extraction). */ /* Note: Chrome returns "rgba(0, 0, 0, 0)" for an undefined color whereas IE returns "transparent". */ return (!value || /^(none|auto|transparent|(rgba\(0, ?0, ?0, ?0\)))$/i.test(value)); }, /* Retrieve a property's default unit type. Used for assigning a unit type when one is not supplied by the user. */ getUnitType: function(property) { if (/^(rotate|skew)/i.test(property)) { return "deg"; } else if (/(^(scale|scaleX|scaleY|scaleZ|alpha|flexGrow|flexHeight|zIndex|fontWeight)$)|((opacity|red|green|blue|alpha)$)/i.test(property)) { /* The above properties are unitless. */ return ""; } else { /* Default to px for all other properties. */ return "px"; } }, /* HTML elements default to an associated display type when they're not set to display:none. */ /* Note: This function is used for correctly setting the non-"none" display value in certain Velocity redirects, such as fadeIn/Out. */ getDisplayType: function(element) { var tagName = element && element.tagName.toString().toLowerCase(); if (/^(b|big|i|small|tt|abbr|acronym|cite|code|dfn|em|kbd|strong|samp|var|a|bdo|br|img|map|object|q|script|span|sub|sup|button|input|label|select|textarea)$/i.test(tagName)) { return "inline"; } else if (/^(li)$/i.test(tagName)) { return "list-item"; } else if (/^(tr)$/i.test(tagName)) { return "table-row"; } else if (/^(table)$/i.test(tagName)) { return "table"; } else if (/^(tbody)$/i.test(tagName)) { return "table-row-group"; /* Default to "block" when no match is found. */ } else { return "block"; } }, /* The class add/remove functions are used to temporarily apply a "velocity-animating" class to elements while they're animating. */ addClass: function(element, className) { if (element.classList) { element.classList.add(className); } else { element.className += (element.className.length ? " " : "") + className; } }, removeClass: function(element, className) { if (element.classList) { element.classList.remove(className); } else { element.className = element.className.toString().replace(new RegExp("(^|\\s)" + className.split(" ").join("|") + "(\\s|$)", "gi"), " "); } } }, /**************************** Style Getting & Setting ****************************/ /* The singular getPropertyValue, which routes the logic for all normalizations, hooks, and standard CSS properties. */ getPropertyValue: function(element, property, rootPropertyValue, forceStyleLookup) { /* Get an element's computed property value. */ /* Note: Retrieving the value of a CSS property cannot simply be performed by checking an element's style attribute (which only reflects user-defined values). Instead, the browser must be queried for a property's *computed* value. You can read more about getComputedStyle here: https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle */ function computePropertyValue(element, property) { /* When box-sizing isn't set to border-box, height and width style values are incorrectly computed when an element's scrollbars are visible (which expands the element's dimensions). Thus, we defer to the more accurate offsetHeight/Width property, which includes the total dimensions for interior, border, padding, and scrollbar. We subtract border and padding to get the sum of interior + scrollbar. */ var computedValue = 0; /* IE<=8 doesn't support window.getComputedStyle, thus we defer to jQuery, which has an extensive array of hacks to accurately retrieve IE8 property values. Re-implementing that logic here is not worth bloating the codebase for a dying browser. The performance repercussions of using jQuery here are minimal since Velocity is optimized to rarely (and sometimes never) query the DOM. Further, the $.css() codepath isn't that slow. */ if (IE <= 8) { computedValue = $.css(element, property); /* GET */ /* All other browsers support getComputedStyle. The returned live object reference is cached onto its associated element so that it does not need to be refetched upon every GET. */ } else { /* Browsers do not return height and width values for elements that are set to display:"none". Thus, we temporarily toggle display to the element type's default value. */ var toggleDisplay = false; if (/^(width|height)$/.test(property) && CSS.getPropertyValue(element, "display") === 0) { toggleDisplay = true; CSS.setPropertyValue(element, "display", CSS.Values.getDisplayType(element)); } var revertDisplay = function() { if (toggleDisplay) { CSS.setPropertyValue(element, "display", "none"); } }; if (!forceStyleLookup) { if (property === "height" && CSS.getPropertyValue(element, "boxSizing").toString().toLowerCase() !== "border-box") { var contentBoxHeight = element.offsetHeight - (parseFloat(CSS.getPropertyValue(element, "borderTopWidth")) || 0) - (parseFloat(CSS.getPropertyValue(element, "borderBottomWidth")) || 0) - (parseFloat(CSS.getPropertyValue(element, "paddingTop")) || 0) - (parseFloat(CSS.getPropertyValue(element, "paddingBottom")) || 0); revertDisplay(); return contentBoxHeight; } else if (property === "width" && CSS.getPropertyValue(element, "boxSizing").toString().toLowerCase() !== "border-box") { var contentBoxWidth = element.offsetWidth - (parseFloat(CSS.getPropertyValue(element, "borderLeftWidth")) || 0) - (parseFloat(CSS.getPropertyValue(element, "borderRightWidth")) || 0) - (parseFloat(CSS.getPropertyValue(element, "paddingLeft")) || 0) - (parseFloat(CSS.getPropertyValue(element, "paddingRight")) || 0); revertDisplay(); return contentBoxWidth; } } var computedStyle; /* For elements that Velocity hasn't been called on directly (e.g. when Velocity queries the DOM on behalf of a parent of an element its animating), perform a direct getComputedStyle lookup since the object isn't cached. */ if (Data(element) === undefined) { computedStyle = window.getComputedStyle(element, null); /* GET */ /* If the computedStyle object has yet to be cached, do so now. */ } else if (!Data(element).computedStyle) { computedStyle = Data(element).computedStyle = window.getComputedStyle(element, null); /* GET */ /* If computedStyle is cached, use it. */ } else { computedStyle = Data(element).computedStyle; } /* IE and Firefox do not return a value for the generic borderColor -- they only return individual values for each border side's color. Also, in all browsers, when border colors aren't all the same, a compound value is returned that Velocity isn't setup to parse. So, as a polyfill for querying individual border side colors, we just return the top border's color and animate all borders from that value. */ if (property === "borderColor") { property = "borderTopColor"; } /* IE9 has a bug in which the "filter" property must be accessed from computedStyle using the getPropertyValue method instead of a direct property lookup. The getPropertyValue method is slower than a direct lookup, which is why we avoid it by default. */ if (IE === 9 && property === "filter") { computedValue = computedStyle.getPropertyValue(property); /* GET */ } else { computedValue = computedStyle[property]; } /* Fall back to the property's style value (if defined) when computedValue returns nothing, which can happen when the element hasn't been painted. */ if (computedValue === "" || computedValue === null) { computedValue = element.style[property]; } revertDisplay(); } /* For top, right, bottom, and left (TRBL) values that are set to "auto" on elements of "fixed" or "absolute" position, defer to jQuery for converting "auto" to a numeric value. (For elements with a "static" or "relative" position, "auto" has the same effect as being set to 0, so no conversion is necessary.) */ /* An example of why numeric conversion is necessary: When an element with "position:absolute" has an untouched "left" property, which reverts to "auto", left's value is 0 relative to its parent element, but is often non-zero relative to its *containing* (not parent) element, which is the nearest "position:relative" ancestor or the viewport (and always the viewport in the case of "position:fixed"). */ if (computedValue === "auto" && /^(top|right|bottom|left)$/i.test(property)) { var position = computePropertyValue(element, "position"); /* GET */ /* For absolute positioning, jQuery's $.position() only returns values for top and left; right and bottom will have their "auto" value reverted to 0. */ /* Note: A jQuery object must be created here since jQuery doesn't have a low-level alias for $.position(). Not a big deal since we're currently in a GET batch anyway. */ if (position === "fixed" || (position === "absolute" && /top|left/i.test(property))) { /* Note: jQuery strips the pixel unit from its returned values; we re-add it here to conform with computePropertyValue's behavior. */ computedValue = $(element).position()[property] + "px"; /* GET */ } } return computedValue; } var propertyValue; /* If this is a hooked property (e.g. "clipLeft" instead of the root property of "clip"), extract the hook's value from a normalized rootPropertyValue using CSS.Hooks.extractValue(). */ if (CSS.Hooks.registered[property]) { var hook = property, hookRoot = CSS.Hooks.getRoot(hook); /* If a cached rootPropertyValue wasn't passed in (which Velocity always attempts to do in order to avoid requerying the DOM), query the DOM for the root property's value. */ if (rootPropertyValue === undefined) { /* Since the browser is now being directly queried, use the official post-prefixing property name for this lookup. */ rootPropertyValue = CSS.getPropertyValue(element, CSS.Names.prefixCheck(hookRoot)[0]); /* GET */ } /* If this root has a normalization registered, peform the associated normalization extraction. */ if (CSS.Normalizations.registered[hookRoot]) { rootPropertyValue = CSS.Normalizations.registered[hookRoot]("extract", element, rootPropertyValue); } /* Extract the hook's value. */ propertyValue = CSS.Hooks.extractValue(hook, rootPropertyValue); /* If this is a normalized property (e.g. "opacity" becomes "filter" in <=IE8) or "translateX" becomes "transform"), normalize the property's name and value, and handle the special case of transforms. */ /* Note: Normalizing a property is mutually exclusive from hooking a property since hook-extracted values are strictly numerical and therefore do not require normalization extraction. */ } else if (CSS.Normalizations.registered[property]) { var normalizedPropertyName, normalizedPropertyValue; normalizedPropertyName = CSS.Normalizations.registered[property]("name", element); /* Transform values are calculated via normalization extraction (see below), which checks against the element's transformCache. At no point do transform GETs ever actually query the DOM; initial stylesheet values are never processed. This is because parsing 3D transform matrices is not always accurate and would bloat our codebase; thus, normalization extraction defaults initial transform values to their zero-values (e.g. 1 for scaleX and 0 for translateX). */ if (normalizedPropertyName !== "transform") { normalizedPropertyValue = computePropertyValue(element, CSS.Names.prefixCheck(normalizedPropertyName)[0]); /* GET */ /* If the value is a CSS null-value and this property has a hook template, use that zero-value template so that hooks can be extracted from it. */ if (CSS.Values.isCSSNullValue(normalizedPropertyValue) && CSS.Hooks.templates[property]) { normalizedPropertyValue = CSS.Hooks.templates[property][1]; } } propertyValue = CSS.Normalizations.registered[property]("extract", element, normalizedPropertyValue); } /* If a (numeric) value wasn't produced via hook extraction or normalization, query the DOM. */ if (!/^[\d-]/.test(propertyValue)) { /* For SVG elements, dimensional properties (which SVGAttribute() detects) are tweened via their HTML attribute values instead of their CSS style values. */ var data = Data(element); if (data && data.isSVG && CSS.Names.SVGAttribute(property)) { /* Since the height/width attribute values must be set manually, they don't reflect computed values. Thus, we use use getBBox() to ensure we always get values for elements with undefined height/width attributes. */ if (/^(height|width)$/i.test(property)) { /* Firefox throws an error if .getBBox() is called on an SVG that isn't attached to the DOM. */ try { propertyValue = element.getBBox()[property]; } catch (error) { propertyValue = 0; } /* Otherwise, access the attribute value directly. */ } else { propertyValue = element.getAttribute(property); } } else { propertyValue = computePropertyValue(element, CSS.Names.prefixCheck(property)[0]); /* GET */ } } /* Since property lookups are for animation purposes (which entails computing the numeric delta between start and end values), convert CSS null-values to an integer of value 0. */ if (CSS.Values.isCSSNullValue(propertyValue)) { propertyValue = 0; } if (Velocity.debug >= 2) { console.log("Get " + property + ": " + propertyValue); } return propertyValue; }, /* The singular setPropertyValue, which routes the logic for all normalizations, hooks, and standard CSS properties. */ setPropertyValue: function(element, property, propertyValue, rootPropertyValue, scrollData) { var propertyName = property; /* In order to be subjected to call options and element queueing, scroll animation is routed through Velocity as if it were a standard CSS property. */ if (property === "scroll") { /* If a container option is present, scroll the container instead of the browser window. */ if (scrollData.container) { scrollData.container["scroll" + scrollData.direction] = propertyValue; /* Otherwise, Velocity defaults to scrolling the browser window. */ } else { if (scrollData.direction === "Left") { window.scrollTo(propertyValue, scrollData.alternateValue); } else { window.scrollTo(scrollData.alternateValue, propertyValue); } } } else { /* Transforms (translateX, rotateZ, etc.) are applied to a per-element transformCache object, which is manually flushed via flushTransformCache(). Thus, for now, we merely cache transforms being SET. */ if (CSS.Normalizations.registered[property] && CSS.Normalizations.registered[property]("name", element) === "transform") { /* Perform a normalization injection. */ /* Note: The normalization logic handles the transformCache updating. */ CSS.Normalizations.registered[property]("inject", element, propertyValue); propertyName = "transform"; propertyValue = Data(element).transformCache[property]; } else { /* Inject hooks. */ if (CSS.Hooks.registered[property]) { var hookName = property, hookRoot = CSS.Hooks.getRoot(property); /* If a cached rootPropertyValue was not provided, query the DOM for the hookRoot's current value. */ rootPropertyValue = rootPropertyValue || CSS.getPropertyValue(element, hookRoot); /* GET */ propertyValue = CSS.Hooks.injectValue(hookName, propertyValue, rootPropertyValue); property = hookRoot; } /* Normalize names and values. */ if (CSS.Normalizations.registered[property]) { propertyValue = CSS.Normalizations.registered[property]("inject", element, propertyValue); property = CSS.Normalizations.registered[property]("name", element); } /* Assign the appropriate vendor prefix before performing an official style update. */ propertyName = CSS.Names.prefixCheck(property)[0]; /* A try/catch is used for IE<=8, which throws an error when "invalid" CSS values are set, e.g. a negative width. Try/catch is avoided for other browsers since it incurs a performance overhead. */ if (IE <= 8) { try { element.style[propertyName] = propertyValue; } catch (error) { if (Velocity.debug) { console.log("Browser does not support [" + propertyValue + "] for [" + propertyName + "]"); } } /* SVG elements have their dimensional properties (width, height, x, y, cx, etc.) applied directly as attributes instead of as styles. */ /* Note: IE8 does not support SVG elements, so it's okay that we skip it for SVG animation. */ } else { var data = Data(element); if (data && data.isSVG && CSS.Names.SVGAttribute(property)) { /* Note: For SVG attributes, vendor-prefixed property names are never used. */ /* Note: Not all CSS properties can be animated via attributes, but the browser won't throw an error for unsupported properties. */ element.setAttribute(property, propertyValue); } else { element.style[propertyName] = propertyValue; } } if (Velocity.debug >= 2) { console.log("Set " + property + " (" + propertyName + "): " + propertyValue); } } } /* Return the normalized property name and value in case the caller wants to know how these values were modified before being applied to the DOM. */ return [propertyName, propertyValue]; }, /* To increase performance by batching transform updates into a single SET, transforms are not directly applied to an element until flushTransformCache() is called. */ /* Note: Velocity applies transform properties in the same order that they are chronogically introduced to the element's CSS styles. */ flushTransformCache: function(element) { var transformString = "", data = Data(element); /* Certain browsers require that SVG transforms be applied as an attribute. However, the SVG transform attribute takes a modified version of CSS's transform string (units are dropped and, except for skewX/Y, subproperties are merged into their master property -- e.g. scaleX and scaleY are merged into scale(X Y). */ if ((IE || (Velocity.State.isAndroid && !Velocity.State.isChrome)) && data && data.isSVG) { /* Since transform values are stored in their parentheses-wrapped form, we use a helper function to strip out their numeric values. Further, SVG transform properties only take unitless (representing pixels) values, so it's okay that parseFloat() strips the unit suffixed to the float value. */ var getTransformFloat = function(transformProperty) { return parseFloat(CSS.getPropertyValue(element, transformProperty)); }; /* Create an object to organize all the transforms that we'll apply to the SVG element. To keep the logic simple, we process *all* transform properties -- even those that may not be explicitly applied (since they default to their zero-values anyway). */ var SVGTransforms = { translate: [getTransformFloat("translateX"), getTransformFloat("translateY")], skewX: [getTransformFloat("skewX")], skewY: [getTransformFloat("skewY")], /* If the scale property is set (non-1), use that value for the scaleX and scaleY values (this behavior mimics the result of animating all these properties at once on HTML elements). */ scale: getTransformFloat("scale") !== 1 ? [getTransformFloat("scale"), getTransformFloat("scale")] : [getTransformFloat("scaleX"), getTransformFloat("scaleY")], /* Note: SVG's rotate transform takes three values: rotation degrees followed by the X and Y values defining the rotation's origin point. We ignore the origin values (default them to 0). */ rotate: [getTransformFloat("rotateZ"), 0, 0] }; /* Iterate through the transform properties in the user-defined property map order. (This mimics the behavior of non-SVG transform animation.) */ $.each(Data(element).transformCache, function(transformName) { /* Except for with skewX/Y, revert the axis-specific transform subproperties to their axis-free master properties so that they match up with SVG's accepted transform properties. */ if (/^translate/i.test(transformName)) { transformName = "translate"; } else if (/^scale/i.test(transformName)) { transformName = "scale"; } else if (/^rotate/i.test(transformName)) { transformName = "rotate"; } /* Check that we haven't yet deleted the property from the SVGTransforms container. */ if (SVGTransforms[transformName]) { /* Append the transform property in the SVG-supported transform format. As per the spec, surround the space-delimited values in parentheses. */ transformString += transformName + "(" + SVGTransforms[transformName].join(" ") + ")" + " "; /* After processing an SVG transform property, delete it from the SVGTransforms container so we don't re-insert the same master property if we encounter another one of its axis-specific properties. */ delete SVGTransforms[transformName]; } }); } else { var transformValue, perspective; /* Transform properties are stored as members of the transformCache object. Concatenate all the members into a string. */ $.each(Data(element).transformCache, function(transformName) { transformValue = Data(element).transformCache[transformName]; /* Transform's perspective subproperty must be set first in order to take effect. Store it temporarily. */ if (transformName === "transformPerspective") { perspective = transformValue; return true; } /* IE9 only supports one rotation type, rotateZ, which it refers to as "rotate". */ if (IE === 9 && transformName === "rotateZ") { transformName = "rotate"; } transformString += transformName + transformValue + " "; }); /* If present, set the perspective subproperty first. */ if (perspective) { transformString = "perspective" + perspective + " " + transformString; } } CSS.setPropertyValue(element, "transform", transformString); } }; /* Register hooks and normalizations. */ CSS.Hooks.register(); CSS.Normalizations.register(); /* Allow hook setting in the same fashion as jQuery's $.css(). */ Velocity.hook = function(elements, arg2, arg3) { var value; elements = sanitizeElements(elements); $.each(elements, function(i, element) { /* Initialize Velocity's per-element data cache if this element hasn't previously been animated. */ if (Data(element) === undefined) { Velocity.init(element); } /* Get property value. If an element set was passed in, only return the value for the first element. */ if (arg3 === undefined) { if (value === undefined) { value = CSS.getPropertyValue(element, arg2); } /* Set property value. */ } else { /* sPV returns an array of the normalized propertyName/propertyValue pair used to update the DOM. */ var adjustedSet = CSS.setPropertyValue(element, arg2, arg3); /* Transform properties don't automatically set. They have to be flushed to the DOM. */ if (adjustedSet[0] === "transform") { Velocity.CSS.flushTransformCache(element); } value = adjustedSet; } }); return value; }; /***************** Animation *****************/ var animate = function() { var opts; /****************** Call Chain ******************/ /* Logic for determining what to return to the call stack when exiting out of Velocity. */ function getChain() { /* If we are using the utility function, attempt to return this call's promise. If no promise library was detected, default to null instead of returning the targeted elements so that utility function's return value is standardized. */ if (isUtility) { return promiseData.promise || null; /* Otherwise, if we're using $.fn, return the jQuery-/Zepto-wrapped element set. */ } else { return elementsWrapped; } } /************************* Arguments Assignment *************************/ /* To allow for expressive CoffeeScript code, Velocity supports an alternative syntax in which "elements" (or "e"), "properties" (or "p"), and "options" (or "o") objects are defined on a container object that's passed in as Velocity's sole argument. */ /* Note: Some browsers automatically populate arguments with a "properties" object. We detect it by checking for its default "names" property. */ var syntacticSugar = (arguments[0] && (arguments[0].p || (($.isPlainObject(arguments[0].properties) && !arguments[0].properties.names) || Type.isString(arguments[0].properties)))), /* Whether Velocity was called via the utility function (as opposed to on a jQuery/Zepto object). */ isUtility, /* When Velocity is called via the utility function ($.Velocity()/Velocity()), elements are explicitly passed in as the first parameter. Thus, argument positioning varies. We normalize them here. */ elementsWrapped, argumentIndex; var elements, propertiesMap, options; /* Detect jQuery/Zepto elements being animated via the $.fn method. */ if (Type.isWrapped(this)) { isUtility = false; argumentIndex = 0; elements = this; elementsWrapped = this; /* Otherwise, raw elements are being animated via the utility function. */ } else { isUtility = true; argumentIndex = 1; elements = syntacticSugar ? (arguments[0].elements || arguments[0].e) : arguments[0]; } /*************** Promises ***************/ var promiseData = { promise: null, resolver: null, rejecter: null }; /* If this call was made via the utility function (which is the default method of invocation when jQuery/Zepto are not being used), and if promise support was detected, create a promise object for this call and store references to its resolver and rejecter methods. The resolve method is used when a call completes naturally or is prematurely stopped by the user. In both cases, completeCall() handles the associated call cleanup and promise resolving logic. The reject method is used when an invalid set of arguments is passed into a Velocity call. */ /* Note: Velocity employs a call-based queueing architecture, which means that stopping an animating element actually stops the full call that triggered it -- not that one element exclusively. Similarly, there is one promise per call, and all elements targeted by a Velocity call are grouped together for the purposes of resolving and rejecting a promise. */ if (isUtility && Velocity.Promise) { promiseData.promise = new Velocity.Promise(function(resolve, reject) { promiseData.resolver = resolve; promiseData.rejecter = reject; }); } if (syntacticSugar) { propertiesMap = arguments[0].properties || arguments[0].p; options = arguments[0].options || arguments[0].o; } else { propertiesMap = arguments[argumentIndex]; options = arguments[argumentIndex + 1]; } elements = sanitizeElements(elements); if (!elements) { if (promiseData.promise) { if (!propertiesMap || !options || options.promiseRejectEmpty !== false) { promiseData.rejecter(); } else { promiseData.resolver(); } } return; } /* The length of the element set (in the form of a nodeList or an array of elements) is defaulted to 1 in case a single raw DOM element is passed in (which doesn't contain a length property). */ var elementsLength = elements.length, elementsIndex = 0; /*************************** Argument Overloading ***************************/ /* Support is included for jQuery's argument overloading: $.animate(propertyMap [, duration] [, easing] [, complete]). Overloading is detected by checking for the absence of an object being passed into options. */ /* Note: The stop and finish actions do not accept animation options, and are therefore excluded from this check. */ if (!/^(stop|finish|finishAll)$/i.test(propertiesMap) && !$.isPlainObject(options)) { /* The utility function shifts all arguments one position to the right, so we adjust for that offset. */ var startingArgumentPosition = argumentIndex + 1; options = {}; /* Iterate through all options arguments */ for (var i = startingArgumentPosition; i < arguments.length; i++) { /* Treat a number as a duration. Parse it out. */ /* Note: The following RegEx will return true if passed an array with a number as its first item. Thus, arrays are skipped from this check. */ if (!Type.isArray(arguments[i]) && (/^(fast|normal|slow)$/i.test(arguments[i]) || /^\d/.test(arguments[i]))) { options.duration = arguments[i]; /* Treat strings and arrays as easings. */ } else if (Type.isString(arguments[i]) || Type.isArray(arguments[i])) { options.easing = arguments[i]; /* Treat a function as a complete callback. */ } else if (Type.isFunction(arguments[i])) { options.complete = arguments[i]; } } } /********************* Action Detection *********************/ /* Velocity's behavior is categorized into "actions": Elements can either be specially scrolled into view, or they can be started, stopped, or reversed. If a literal or referenced properties map is passed in as Velocity's first argument, the associated action is "start". Alternatively, "scroll", "reverse", or "stop" can be passed in instead of a properties map. */ var action; switch (propertiesMap) { case "scroll": action = "scroll"; break; case "reverse": action = "reverse"; break; case "finish": case "finishAll": case "stop": /******************* Action: Stop *******************/ /* Clear the currently-active delay on each targeted element. */ $.each(elements, function(i, element) { if (Data(element) && Data(element).delayTimer) { /* Stop the timer from triggering its cached next() function. */ clearTimeout(Data(element).delayTimer.setTimeout); /* Manually call the next() function so that the subsequent queue items can progress. */ if (Data(element).delayTimer.next) { Data(element).delayTimer.next(); } delete Data(element).delayTimer; } /* If we want to finish everything in the queue, we have to iterate through it and call each function. This will make them active calls below, which will cause them to be applied via the duration setting. */ if (propertiesMap === "finishAll" && (options === true || Type.isString(options))) { /* Iterate through the items in the element's queue. */ $.each($.queue(element, Type.isString(options) ? options : ""), function(_, item) { /* The queue array can contain an "inprogress" string, which we skip. */ if (Type.isFunction(item)) { item(); } }); /* Clearing the $.queue() array is achieved by resetting it to []. */ $.queue(element, Type.isString(options) ? options : "", []); } }); var callsToStop = []; /* When the stop action is triggered, the elements' currently active call is immediately stopped. The active call might have been applied to multiple elements, in which case all of the call's elements will be stopped. When an element is stopped, the next item in its animation queue is immediately triggered. */ /* An additional argument may be passed in to clear an element's remaining queued calls. Either true (which defaults to the "fx" queue) or a custom queue string can be passed in. */ /* Note: The stop command runs prior to Velocity's Queueing phase since its behavior is intended to take effect *immediately*, regardless of the element's current queue state. */ /* Iterate through every active call. */ $.each(Velocity.State.calls, function(i, activeCall) { /* Inactive calls are set to false by the logic inside completeCall(). Skip them. */ if (activeCall) { /* Iterate through the active call's targeted elements. */ $.each(activeCall[1], function(k, activeElement) { /* If true was passed in as a secondary argument, clear absolutely all calls on this element. Otherwise, only clear calls associated with the relevant queue. */ /* Call stopping logic works as follows: - options === true --> stop current default queue calls (and queue:false calls), including remaining queued ones. - options === undefined --> stop current queue:"" call and all queue:false calls. - options === false --> stop only queue:false calls. - options === "custom" --> stop current queue:"custom" call, including remaining queued ones (there is no functionality to only clear the currently-running queue:"custom" call). */ var queueName = (options === undefined) ? "" : options; if (queueName !== true && (activeCall[2].queue !== queueName) && !(options === undefined && activeCall[2].queue === false)) { return true; } /* Iterate through the calls targeted by the stop command. */ $.each(elements, function(l, element) { /* Check that this call was applied to the target element. */ if (element === activeElement) { /* Optionally clear the remaining queued calls. If we're doing "finishAll" this won't find anything, due to the queue-clearing above. */ if (options === true || Type.isString(options)) { /* Iterate through the items in the element's queue. */ $.each($.queue(element, Type.isString(options) ? options : ""), function(_, item) { /* The queue array can contain an "inprogress" string, which we skip. */ if (Type.isFunction(item)) { /* Pass the item's callback a flag indicating that we want to abort from the queue call. (Specifically, the queue will resolve the call's associated promise then abort.) */ item(null, true); } }); /* Clearing the $.queue() array is achieved by resetting it to []. */ $.queue(element, Type.isString(options) ? options : "", []); } if (propertiesMap === "stop") { /* Since "reverse" uses cached start values (the previous call's endValues), these values must be changed to reflect the final value that the elements were actually tweened to. */ /* Note: If only queue:false animations are currently running on an element, it won't have a tweensContainer object. Also, queue:false animations can't be reversed. */ var data = Data(element); if (data && data.tweensContainer && queueName !== false) { $.each(data.tweensContainer, function(m, activeTween) { activeTween.endValue = activeTween.currentValue; }); } callsToStop.push(i); } else if (propertiesMap === "finish" || propertiesMap === "finishAll") { /* To get active tweens to finish immediately, we forcefully shorten their durations to 1ms so that they finish upon the next rAf tick then proceed with normal call completion logic. */ activeCall[2].duration = 1; } } }); }); } }); /* Prematurely call completeCall() on each matched active call. Pass an additional flag for "stop" to indicate that the complete callback and display:none setting should be skipped since we're completing prematurely. */ if (propertiesMap === "stop") { $.each(callsToStop, function(i, j) { completeCall(j, true); }); if (promiseData.promise) { /* Immediately resolve the promise associated with this stop call since stop runs synchronously. */ promiseData.resolver(elements); } } /* Since we're stopping, and not proceeding with queueing, exit out of Velocity. */ return getChain(); default: /* Treat a non-empty plain object as a literal properties map. */ if ($.isPlainObject(propertiesMap) && !Type.isEmptyObject(propertiesMap)) { action = "start"; /**************** Redirects ****************/ /* Check if a string matches a registered redirect (see Redirects above). */ } else if (Type.isString(propertiesMap) && Velocity.Redirects[propertiesMap]) { opts = $.extend({}, options); var durationOriginal = opts.duration, delayOriginal = opts.delay || 0; /* If the backwards option was passed in, reverse the element set so that elements animate from the last to the first. */ if (opts.backwards === true) { elements = $.extend(true, [], elements).reverse(); } /* Individually trigger the redirect for each element in the set to prevent users from having to handle iteration logic in their redirect. */ $.each(elements, function(elementIndex, element) { /* If the stagger option was passed in, successively delay each element by the stagger value (in ms). Retain the original delay value. */ if (parseFloat(opts.stagger)) { opts.delay = delayOriginal + (parseFloat(opts.stagger) * elementIndex); } else if (Type.isFunction(opts.stagger)) { opts.delay = delayOriginal + opts.stagger.call(element, elementIndex, elementsLength); } /* If the drag option was passed in, successively increase/decrease (depending on the presense of opts.backwards) the duration of each element's animation, using floors to prevent producing very short durations. */ if (opts.drag) { /* Default the duration of UI pack effects (callouts and transitions) to 1000ms instead of the usual default duration of 400ms. */ opts.duration = parseFloat(durationOriginal) || (/^(callout|transition)/.test(propertiesMap) ? 1000 : DURATION_DEFAULT); /* For each element, take the greater duration of: A) animation completion percentage relative to the original duration, B) 75% of the original duration, or C) a 200ms fallback (in case duration is already set to a low value). The end result is a baseline of 75% of the redirect's duration that increases/decreases as the end of the element set is approached. */ opts.duration = Math.max(opts.duration * (opts.backwards ? 1 - elementIndex / elementsLength : (elementIndex + 1) / elementsLength), opts.duration * 0.75, 200); } /* Pass in the call's opts object so that the redirect can optionally extend it. It defaults to an empty object instead of null to reduce the opts checking logic required inside the redirect. */ Velocity.Redirects[propertiesMap].call(element, element, opts || {}, elementIndex, elementsLength, elements, promiseData.promise ? promiseData : undefined); }); /* Since the animation logic resides within the redirect's own code, abort the remainder of this call. (The performance overhead up to this point is virtually non-existant.) */ /* Note: The jQuery call chain is kept intact by returning the complete element set. */ return getChain(); } else { var abortError = "Velocity: First argument (" + propertiesMap + ") was not a property map, a known action, or a registered redirect. Aborting."; if (promiseData.promise) { promiseData.rejecter(new Error(abortError)); } else { console.log(abortError); } return getChain(); } } /************************** Call-Wide Variables **************************/ /* A container for CSS unit conversion ratios (e.g. %, rem, and em ==> px) that is used to cache ratios across all elements being animated in a single Velocity call. Calculating unit ratios necessitates DOM querying and updating, and is therefore avoided (via caching) wherever possible. This container is call-wide instead of page-wide to avoid the risk of using stale conversion metrics across Velocity animations that are not immediately consecutively chained. */ var callUnitConversionData = { lastParent: null, lastPosition: null, lastFontSize: null, lastPercentToPxWidth: null, lastPercentToPxHeight: null, lastEmToPx: null, remToPx: null, vwToPx: null, vhToPx: null }; /* A container for all the ensuing tween data and metadata associated with this call. This container gets pushed to the page-wide Velocity.State.calls array that is processed during animation ticking. */ var call = []; /************************ Element Processing ************************/ /* Element processing consists of three parts -- data processing that cannot go stale and data processing that *can* go stale (i.e. third-party style modifications): 1) Pre-Queueing: Element-wide variables, including the element's data storage, are instantiated. Call options are prepared. If triggered, the Stop action is executed. 2) Queueing: The logic that runs once this call has reached its point of execution in the element's $.queue() stack. Most logic is placed here to avoid risking it becoming stale. 3) Pushing: Consolidation of the tween data followed by its push onto the global in-progress calls container. `elementArrayIndex` allows passing index of the element in the original array to value functions. If `elementsIndex` were used instead the index would be determined by the elements' per-element queue. */ function processElement(element, elementArrayIndex) { /************************* Part I: Pre-Queueing *************************/ /*************************** Element-Wide Variables ***************************/ var /* The runtime opts object is the extension of the current call's options and Velocity's page-wide option defaults. */ opts = $.extend({}, Velocity.defaults, options), /* A container for the processed data associated with each property in the propertyMap. (Each property in the map produces its own "tween".) */ tweensContainer = {}, elementUnitConversionData; /****************** Element Init ******************/ if (Data(element) === undefined) { Velocity.init(element); } /****************** Option: Delay ******************/ /* Since queue:false doesn't respect the item's existing queue, we avoid injecting its delay here (it's set later on). */ /* Note: Velocity rolls its own delay function since jQuery doesn't have a utility alias for $.fn.delay() (and thus requires jQuery element creation, which we avoid since its overhead includes DOM querying). */ if (parseFloat(opts.delay) && opts.queue !== false) { $.queue(element, opts.queue, function(next) { /* This is a flag used to indicate to the upcoming completeCall() function that this queue entry was initiated by Velocity. See completeCall() for further details. */ Velocity.velocityQueueEntryFlag = true; /* The ensuing queue item (which is assigned to the "next" argument that $.queue() automatically passes in) will be triggered after a setTimeout delay. The setTimeout is stored so that it can be subjected to clearTimeout() if this animation is prematurely stopped via Velocity's "stop" command. */ Data(element).delayTimer = { setTimeout: setTimeout(next, parseFloat(opts.delay)), next: next }; }); } /********************* Option: Duration *********************/ /* Support for jQuery's named durations. */ switch (opts.duration.toString().toLowerCase()) { case "fast": opts.duration = 200; break; case "normal": opts.duration = DURATION_DEFAULT; break; case "slow": opts.duration = 600; break; default: /* Remove the potential "ms" suffix and default to 1 if the user is attempting to set a duration of 0 (in order to produce an immediate style change). */ opts.duration = parseFloat(opts.duration) || 1; } /************************ Global Option: Mock ************************/ if (Velocity.mock !== false) { /* In mock mode, all animations are forced to 1ms so that they occur immediately upon the next rAF tick. Alternatively, a multiplier can be passed in to time remap all delays and durations. */ if (Velocity.mock === true) { opts.duration = opts.delay = 1; } else { opts.duration *= parseFloat(Velocity.mock) || 1; opts.delay *= parseFloat(Velocity.mock) || 1; } } /******************* Option: Easing *******************/ opts.easing = getEasing(opts.easing, opts.duration); /********************** Option: Callbacks **********************/ /* Callbacks must functions. Otherwise, default to null. */ if (opts.begin && !Type.isFunction(opts.begin)) { opts.begin = null; } if (opts.progress && !Type.isFunction(opts.progress)) { opts.progress = null; } if (opts.complete && !Type.isFunction(opts.complete)) { opts.complete = null; } /********************************* Option: Display & Visibility *********************************/ /* Refer to Velocity's documentation (VelocityJS.org/#displayAndVisibility) for a description of the display and visibility options' behavior. */ /* Note: We strictly check for undefined instead of falsiness because display accepts an empty string value. */ if (opts.display !== undefined && opts.display !== null) { opts.display = opts.display.toString().toLowerCase(); /* Users can pass in a special "auto" value to instruct Velocity to set the element to its default display value. */ if (opts.display === "auto") { opts.display = Velocity.CSS.Values.getDisplayType(element); } } if (opts.visibility !== undefined && opts.visibility !== null) { opts.visibility = opts.visibility.toString().toLowerCase(); } /********************** Option: mobileHA **********************/ /* When set to true, and if this is a mobile device, mobileHA automatically enables hardware acceleration (via a null transform hack) on animating elements. HA is removed from the element at the completion of its animation. */ /* Note: Android Gingerbread doesn't support HA. If a null transform hack (mobileHA) is in fact set, it will prevent other tranform subproperties from taking effect. */ /* Note: You can read more about the use of mobileHA in Velocity's documentation: VelocityJS.org/#mobileHA. */ opts.mobileHA = (opts.mobileHA && Velocity.State.isMobile && !Velocity.State.isGingerbread); /*********************** Part II: Queueing ***********************/ /* When a set of elements is targeted by a Velocity call, the set is broken up and each element has the current Velocity call individually queued onto it. In this way, each element's existing queue is respected; some elements may already be animating and accordingly should not have this current Velocity call triggered immediately. */ /* In each queue, tween data is processed for each animating property then pushed onto the call-wide calls array. When the last element in the set has had its tweens processed, the call array is pushed to Velocity.State.calls for live processing by the requestAnimationFrame tick. */ function buildQueue(next) { var data, lastTweensContainer; /******************* Option: Begin *******************/ /* The begin callback is fired once per call -- not once per elemenet -- and is passed the full raw DOM element set as both its context and its first argument. */ if (opts.begin && elementsIndex === 0) { /* We throw callbacks in a setTimeout so that thrown errors don't halt the execution of Velocity itself. */ try { opts.begin.call(elements, elements); } catch (error) { setTimeout(function() { throw error; }, 1); } } /***************************************** Tween Data Construction (for Scroll) *****************************************/ /* Note: In order to be subjected to chaining and animation options, scroll's tweening is routed through Velocity as if it were a standard CSS property animation. */ if (action === "scroll") { /* The scroll action uniquely takes an optional "offset" option -- specified in pixels -- that offsets the targeted scroll position. */ var scrollDirection = (/^x$/i.test(opts.axis) ? "Left" : "Top"), scrollOffset = parseFloat(opts.offset) || 0, scrollPositionCurrent, scrollPositionCurrentAlternate, scrollPositionEnd; /* Scroll also uniquely takes an optional "container" option, which indicates the parent element that should be scrolled -- as opposed to the browser window itself. This is useful for scrolling toward an element that's inside an overflowing parent element. */ if (opts.container) { /* Ensure that either a jQuery object or a raw DOM element was passed in. */ if (Type.isWrapped(opts.container) || Type.isNode(opts.container)) { /* Extract the raw DOM element from the jQuery wrapper. */ opts.container = opts.container[0] || opts.container; /* Note: Unlike other properties in Velocity, the browser's scroll position is never cached since it so frequently changes (due to the user's natural interaction with the page). */ scrollPositionCurrent = opts.container["scroll" + scrollDirection]; /* GET */ /* $.position() values are relative to the container's currently viewable area (without taking into account the container's true dimensions -- say, for example, if the container was not overflowing). Thus, the scroll end value is the sum of the child element's position *and* the scroll container's current scroll position. */ scrollPositionEnd = (scrollPositionCurrent + $(element).position()[scrollDirection.toLowerCase()]) + scrollOffset; /* GET */ /* If a value other than a jQuery object or a raw DOM element was passed in, default to null so that this option is ignored. */ } else { opts.container = null; } } else { /* If the window itself is being scrolled -- not a containing element -- perform a live scroll position lookup using the appropriate cached property names (which differ based on browser type). */ scrollPositionCurrent = Velocity.State.scrollAnchor[Velocity.State["scrollProperty" + scrollDirection]]; /* GET */ /* When scrolling the browser window, cache the alternate axis's current value since window.scrollTo() doesn't let us change only one value at a time. */ scrollPositionCurrentAlternate = Velocity.State.scrollAnchor[Velocity.State["scrollProperty" + (scrollDirection === "Left" ? "Top" : "Left")]]; /* GET */ /* Unlike $.position(), $.offset() values are relative to the browser window's true dimensions -- not merely its currently viewable area -- and therefore end values do not need to be compounded onto current values. */ scrollPositionEnd = $(element).offset()[scrollDirection.toLowerCase()] + scrollOffset; /* GET */ } /* Since there's only one format that scroll's associated tweensContainer can take, we create it manually. */ tweensContainer = { scroll: { rootPropertyValue: false, startValue: scrollPositionCurrent, currentValue: scrollPositionCurrent, endValue: scrollPositionEnd, unitType: "", easing: opts.easing, scrollData: { container: opts.container, direction: scrollDirection, alternateValue: scrollPositionCurrentAlternate } }, element: element }; if (Velocity.debug) { console.log("tweensContainer (scroll): ", tweensContainer.scroll, element); } /****************************************** Tween Data Construction (for Reverse) ******************************************/ /* Reverse acts like a "start" action in that a property map is animated toward. The only difference is that the property map used for reverse is the inverse of the map used in the previous call. Thus, we manipulate the previous call to construct our new map: use the previous map's end values as our new map's start values. Copy over all other data. */ /* Note: Reverse can be directly called via the "reverse" parameter, or it can be indirectly triggered via the loop option. (Loops are composed of multiple reverses.) */ /* Note: Reverse calls do not need to be consecutively chained onto a currently-animating element in order to operate on cached values; there is no harm to reverse being called on a potentially stale data cache since reverse's behavior is simply defined as reverting to the element's values as they were prior to the previous *Velocity* call. */ } else if (action === "reverse") { data = Data(element); /* Abort if there is no prior animation data to reverse to. */ if (!data) { return; } if (!data.tweensContainer) { /* Dequeue the element so that this queue entry releases itself immediately, allowing subsequent queue entries to run. */ $.dequeue(element, opts.queue); return; } else { /********************* Options Parsing *********************/ /* If the element was hidden via the display option in the previous call, revert display to "auto" prior to reversal so that the element is visible again. */ if (data.opts.display === "none") { data.opts.display = "auto"; } if (data.opts.visibility === "hidden") { data.opts.visibility = "visible"; } /* If the loop option was set in the previous call, disable it so that "reverse" calls aren't recursively generated. Further, remove the previous call's callback options; typically, users do not want these to be refired. */ data.opts.loop = false; data.opts.begin = null; data.opts.complete = null; /* Since we're extending an opts object that has already been extended with the defaults options object, we remove non-explicitly-defined properties that are auto-assigned values. */ if (!options.easing) { delete opts.easing; } if (!options.duration) { delete opts.duration; } /* The opts object used for reversal is an extension of the options object optionally passed into this reverse call plus the options used in the previous Velocity call. */ opts = $.extend({}, data.opts, opts); /************************************* Tweens Container Reconstruction *************************************/ /* Create a deepy copy (indicated via the true flag) of the previous call's tweensContainer. */ lastTweensContainer = $.extend(true, {}, data ? data.tweensContainer : null); /* Manipulate the previous tweensContainer by replacing its end values and currentValues with its start values. */ for (var lastTween in lastTweensContainer) { /* In addition to tween data, tweensContainers contain an element property that we ignore here. */ if (lastTweensContainer.hasOwnProperty(lastTween) && lastTween !== "element") { var lastStartValue = lastTweensContainer[lastTween].startValue; lastTweensContainer[lastTween].startValue = lastTweensContainer[lastTween].currentValue = lastTweensContainer[lastTween].endValue; lastTweensContainer[lastTween].endValue = lastStartValue; /* Easing is the only option that embeds into the individual tween data (since it can be defined on a per-property basis). Accordingly, every property's easing value must be updated when an options object is passed in with a reverse call. The side effect of this extensibility is that all per-property easing values are forcefully reset to the new value. */ if (!Type.isEmptyObject(options)) { lastTweensContainer[lastTween].easing = opts.easing; } if (Velocity.debug) { console.log("reverse tweensContainer (" + lastTween + "): " + JSON.stringify(lastTweensContainer[lastTween]), element); } } } tweensContainer = lastTweensContainer; } /***************************************** Tween Data Construction (for Start) *****************************************/ } else if (action === "start") { /************************* Value Transferring *************************/ /* If this queue entry follows a previous Velocity-initiated queue entry *and* if this entry was created while the element was in the process of being animated by Velocity, then this current call is safe to use the end values from the prior call as its start values. Velocity attempts to perform this value transfer process whenever possible in order to avoid requerying the DOM. */ /* If values aren't transferred from a prior call and start values were not forcefed by the user (more on this below), then the DOM is queried for the element's current values as a last resort. */ /* Note: Conversely, animation reversal (and looping) *always* perform inter-call value transfers; they never requery the DOM. */ data = Data(element); /* The per-element isAnimating flag is used to indicate whether it's safe (i.e. the data isn't stale) to transfer over end values to use as start values. If it's set to true and there is a previous Velocity call to pull values from, do so. */ if (data && data.tweensContainer && data.isAnimating === true) { lastTweensContainer = data.tweensContainer; } /*************************** Tween Data Calculation ***************************/ /* This function parses property data and defaults endValue, easing, and startValue as appropriate. */ /* Property map values can either take the form of 1) a single value representing the end value, or 2) an array in the form of [ endValue, [, easing] [, startValue] ]. The optional third parameter is a forcefed startValue to be used instead of querying the DOM for the element's current value. Read Velocity's docmentation to learn more about forcefeeding: VelocityJS.org/#forcefeeding */ var parsePropertyValue = function(valueData, skipResolvingEasing) { var endValue, easing, startValue; /* If we have a function as the main argument then resolve it first, in case it returns an array that needs to be split */ if (Type.isFunction(valueData)) { valueData = valueData.call(element, elementArrayIndex, elementsLength); } /* Handle the array format, which can be structured as one of three potential overloads: A) [ endValue, easing, startValue ], B) [ endValue, easing ], or C) [ endValue, startValue ] */ if (Type.isArray(valueData)) { /* endValue is always the first item in the array. Don't bother validating endValue's value now since the ensuing property cycling logic does that. */ endValue = valueData[0]; /* Two-item array format: If the second item is a number, function, or hex string, treat it as a start value since easings can only be non-hex strings or arrays. */ if ((!Type.isArray(valueData[1]) && /^[\d-]/.test(valueData[1])) || Type.isFunction(valueData[1]) || CSS.RegEx.isHex.test(valueData[1])) { startValue = valueData[1]; /* Two or three-item array: If the second item is a non-hex string or an array, treat it as an easing. */ } else if ((Type.isString(valueData[1]) && !CSS.RegEx.isHex.test(valueData[1])) || Type.isArray(valueData[1])) { easing = skipResolvingEasing ? valueData[1] : getEasing(valueData[1], opts.duration); /* Don't bother validating startValue's value now since the ensuing property cycling logic inherently does that. */ if (valueData[2] !== undefined) { startValue = valueData[2]; } } /* Handle the single-value format. */ } else { endValue = valueData; } /* Default to the call's easing if a per-property easing type was not defined. */ if (!skipResolvingEasing) { easing = easing || opts.easing; } /* If functions were passed in as values, pass the function the current element as its context, plus the element's index and the element set's size as arguments. Then, assign the returned value. */ if (Type.isFunction(endValue)) { endValue = endValue.call(element, elementArrayIndex, elementsLength); } if (Type.isFunction(startValue)) { startValue = startValue.call(element, elementArrayIndex, elementsLength); } /* Allow startValue to be left as undefined to indicate to the ensuing code that its value was not forcefed. */ return [endValue || 0, easing, startValue]; }; /* Do a quick check of property data and return if the startValue and endValue are both functions (ie, don't split red/green/blue) */ var startAndEndFunction = function(valueData) { if (Type.isArray(valueData)) { return Type.isFunction(valueData[0]) && (valueData[1] === undefined || Type.isFunction(valueData[1])); } return false; }; /* Cache RegExp as it's somewhat costly to create - but only for this iteration as it's a public value and might change */ var rxCSSListsColors; /* Cycle through each property in the map, looking for shorthand color properties (e.g. "color" as opposed to "colorRed"). Inject the corresponding colorRed, colorGreen, and colorBlue RGB component tweens into the propertiesMap (which Velocity understands) and remove the shorthand property. */ $.each(propertiesMap, function(property, value) { if (!rxCSSListsColors) { rxCSSListsColors = RegExp("^" + CSS.Lists.colors.join("$|^") + "$"); } /* Find shorthand color properties that have been passed a hex string. */ /* Don't try to fix values if both startValue and endValue are a function */ /* Would be quicker to use CSS.Lists.colors.includes() if possible */ if (rxCSSListsColors.test(CSS.Names.camelCase(property)) && !startAndEndFunction(value)) { /* Parse the value data for each shorthand. */ var valueData = parsePropertyValue(value, true), endValue = valueData[0], easing = valueData[1], startValue = valueData[2]; if (CSS.RegEx.isHex.test(endValue)) { /* Convert the hex strings into their RGB component arrays. */ var colorComponents = ["Red", "Green", "Blue"], endValueRGB = CSS.Values.hexToRgb(endValue), startValueRGB = startValue ? CSS.Values.hexToRgb(startValue) : undefined; /* Inject the RGB component tweens into propertiesMap. */ for (var i = 0; i < colorComponents.length; i++) { var dataArray = [endValueRGB[i]]; if (easing) { dataArray.push(easing); } if (startValueRGB !== undefined) { dataArray.push(startValueRGB[i]); } propertiesMap[CSS.Names.camelCase(property) + colorComponents[i]] = dataArray; } /* Remove the intermediary shorthand property entry now that we've processed it. */ delete propertiesMap[property]; } } }); /* Create a tween out of each property, and append its associated data to tweensContainer. */ for (var property in propertiesMap) { if (!propertiesMap.hasOwnProperty(property)) { continue; } /************************** Start Value Sourcing **************************/ /* Parse out endValue, easing, and startValue from the property's data. */ var valueData = parsePropertyValue(propertiesMap[property]), endValue = valueData[0], easing = valueData[1], startValue = valueData[2]; /* Now that the original property name's format has been used for the parsePropertyValue() lookup above, we force the property to its camelCase styling to normalize it for manipulation. */ property = CSS.Names.camelCase(property); /* In case this property is a hook, there are circumstances where we will intend to work on the hook's root property and not the hooked subproperty. */ var rootProperty = CSS.Hooks.getRoot(property), rootPropertyValue = false; /* Other than for the dummy tween property, properties that are not supported by the browser (and do not have an associated normalization) will inherently produce no style changes when set, so they are skipped in order to decrease animation tick overhead. Property support is determined via prefixCheck(), which returns a false flag when no supported is detected. */ /* Note: Since SVG elements have some of their properties directly applied as HTML attributes, there is no way to check for their explicit browser support, and so we skip skip this check for them. */ if ((!data || !data.isSVG) && rootProperty !== "tween" && CSS.Names.prefixCheck(rootProperty)[1] === false && CSS.Normalizations.registered[rootProperty] === undefined) { if (Velocity.debug) { console.log("Skipping [" + rootProperty + "] due to a lack of browser support."); } continue; } /* If the display option is being set to a non-"none" (e.g. "block") and opacity (filter on IE<=8) is being animated to an endValue of non-zero, the user's intention is to fade in from invisible, thus we forcefeed opacity a startValue of 0 if its startValue hasn't already been sourced by value transferring or prior forcefeeding. */ if (((opts.display !== undefined && opts.display !== null && opts.display !== "none") || (opts.visibility !== undefined && opts.visibility !== "hidden")) && /opacity|filter/.test(property) && !startValue && endValue !== 0) { startValue = 0; } /* If values have been transferred from the previous Velocity call, extract the endValue and rootPropertyValue for all of the current call's properties that were *also* animated in the previous call. */ /* Note: Value transferring can optionally be disabled by the user via the _cacheValues option. */ if (opts._cacheValues && lastTweensContainer && lastTweensContainer[property]) { if (startValue === undefined) { startValue = lastTweensContainer[property].endValue + lastTweensContainer[property].unitType; } /* The previous call's rootPropertyValue is extracted from the element's data cache since that's the instance of rootPropertyValue that gets freshly updated by the tweening process, whereas the rootPropertyValue attached to the incoming lastTweensContainer is equal to the root property's value prior to any tweening. */ rootPropertyValue = data.rootPropertyValueCache[rootProperty]; /* If values were not transferred from a previous Velocity call, query the DOM as needed. */ } else { /* Handle hooked properties. */ if (CSS.Hooks.registered[property]) { if (startValue === undefined) { rootPropertyValue = CSS.getPropertyValue(element, rootProperty); /* GET */ /* Note: The following getPropertyValue() call does not actually trigger a DOM query; getPropertyValue() will extract the hook from rootPropertyValue. */ startValue = CSS.getPropertyValue(element, property, rootPropertyValue); /* If startValue is already defined via forcefeeding, do not query the DOM for the root property's value; just grab rootProperty's zero-value template from CSS.Hooks. This overwrites the element's actual root property value (if one is set), but this is acceptable since the primary reason users forcefeed is to avoid DOM queries, and thus we likewise avoid querying the DOM for the root property's value. */ } else { /* Grab this hook's zero-value template, e.g. "0px 0px 0px black". */ rootPropertyValue = CSS.Hooks.templates[rootProperty][1]; } /* Handle non-hooked properties that haven't already been defined via forcefeeding. */ } else if (startValue === undefined) { startValue = CSS.getPropertyValue(element, property); /* GET */ } } /************************** Value Data Extraction **************************/ var separatedValue, endValueUnitType, startValueUnitType, operator = false; /* Separates a property value into its numeric value and its unit type. */ var separateValue = function(property, value) { var unitType, numericValue; numericValue = (value || "0") .toString() .toLowerCase() /* Match the unit type at the end of the value. */ .replace(/[%A-z]+$/, function(match) { /* Grab the unit type. */ unitType = match; /* Strip the unit type off of value. */ return ""; }); /* If no unit type was supplied, assign one that is appropriate for this property (e.g. "deg" for rotateZ or "px" for width). */ if (!unitType) { unitType = CSS.Values.getUnitType(property); } return [numericValue, unitType]; }; /* Separate startValue. */ separatedValue = separateValue(property, startValue); startValue = separatedValue[0]; startValueUnitType = separatedValue[1]; /* Separate endValue, and extract a value operator (e.g. "+=", "-=") if one exists. */ separatedValue = separateValue(property, endValue); endValue = separatedValue[0].replace(/^([+-\/*])=/, function(match, subMatch) { operator = subMatch; /* Strip the operator off of the value. */ return ""; }); endValueUnitType = separatedValue[1]; /* Parse float values from endValue and startValue. Default to 0 if NaN is returned. */ startValue = parseFloat(startValue) || 0; endValue = parseFloat(endValue) || 0; /*************************************** Property-Specific Value Conversion ***************************************/ /* Custom support for properties that don't actually accept the % unit type, but where pollyfilling is trivial and relatively foolproof. */ if (endValueUnitType === "%") { /* A %-value fontSize/lineHeight is relative to the parent's fontSize (as opposed to the parent's dimensions), which is identical to the em unit's behavior, so we piggyback off of that. */ if (/^(fontSize|lineHeight)$/.test(property)) { /* Convert % into an em decimal value. */ endValue = endValue / 100; endValueUnitType = "em"; /* For scaleX and scaleY, convert the value into its decimal format and strip off the unit type. */ } else if (/^scale/.test(property)) { endValue = endValue / 100; endValueUnitType = ""; /* For RGB components, take the defined percentage of 255 and strip off the unit type. */ } else if (/(Red|Green|Blue)$/i.test(property)) { endValue = (endValue / 100) * 255; endValueUnitType = ""; } } /*************************** Unit Ratio Calculation ***************************/ /* When queried, the browser returns (most) CSS property values in pixels. Therefore, if an endValue with a unit type of %, em, or rem is animated toward, startValue must be converted from pixels into the same unit type as endValue in order for value manipulation logic (increment/decrement) to proceed. Further, if the startValue was forcefed or transferred from a previous call, startValue may also not be in pixels. Unit conversion logic therefore consists of two steps: 1) Calculating the ratio of %/em/rem/vh/vw relative to pixels 2) Converting startValue into the same unit of measurement as endValue based on these ratios. */ /* Unit conversion ratios are calculated by inserting a sibling node next to the target node, copying over its position property, setting values with the target unit type then comparing the returned pixel value. */ /* Note: Even if only one of these unit types is being animated, all unit ratios are calculated at once since the overhead of batching the SETs and GETs together upfront outweights the potential overhead of layout thrashing caused by re-querying for uncalculated ratios for subsequently-processed properties. */ /* Todo: Shift this logic into the calls' first tick instance so that it's synced with RAF. */ var calculateUnitRatios = function() { /************************ Same Ratio Checks ************************/ /* The properties below are used to determine whether the element differs sufficiently from this call's previously iterated element to also differ in its unit conversion ratios. If the properties match up with those of the prior element, the prior element's conversion ratios are used. Like most optimizations in Velocity, this is done to minimize DOM querying. */ var sameRatioIndicators = { myParent: element.parentNode || document.body, /* GET */ position: CSS.getPropertyValue(element, "position"), /* GET */ fontSize: CSS.getPropertyValue(element, "fontSize") /* GET */ }, /* Determine if the same % ratio can be used. % is based on the element's position value and its parent's width and height dimensions. */ samePercentRatio = ((sameRatioIndicators.position === callUnitConversionData.lastPosition) && (sameRatioIndicators.myParent === callUnitConversionData.lastParent)), /* Determine if the same em ratio can be used. em is relative to the element's fontSize. */ sameEmRatio = (sameRatioIndicators.fontSize === callUnitConversionData.lastFontSize); /* Store these ratio indicators call-wide for the next element to compare against. */ callUnitConversionData.lastParent = sameRatioIndicators.myParent; callUnitConversionData.lastPosition = sameRatioIndicators.position; callUnitConversionData.lastFontSize = sameRatioIndicators.fontSize; /*************************** Element-Specific Units ***************************/ /* Note: IE8 rounds to the nearest pixel when returning CSS values, thus we perform conversions using a measurement of 100 (instead of 1) to give our ratios a precision of at least 2 decimal values. */ var measurement = 100, unitRatios = {}; if (!sameEmRatio || !samePercentRatio) { var dummy = data && data.isSVG ? document.createElementNS("http://www.w3.org/2000/svg", "rect") : document.createElement("div"); Velocity.init(dummy); sameRatioIndicators.myParent.appendChild(dummy); /* To accurately and consistently calculate conversion ratios, the element's cascaded overflow and box-sizing are stripped. Similarly, since width/height can be artificially constrained by their min-/max- equivalents, these are controlled for as well. */ /* Note: Overflow must be also be controlled for per-axis since the overflow property overwrites its per-axis values. */ $.each(["overflow", "overflowX", "overflowY"], function(i, property) { Velocity.CSS.setPropertyValue(dummy, property, "hidden"); }); Velocity.CSS.setPropertyValue(dummy, "position", sameRatioIndicators.position); Velocity.CSS.setPropertyValue(dummy, "fontSize", sameRatioIndicators.fontSize); Velocity.CSS.setPropertyValue(dummy, "boxSizing", "content-box"); /* width and height act as our proxy properties for measuring the horizontal and vertical % ratios. */ $.each(["minWidth", "maxWidth", "width", "minHeight", "maxHeight", "height"], function(i, property) { Velocity.CSS.setPropertyValue(dummy, property, measurement + "%"); }); /* paddingLeft arbitrarily acts as our proxy property for the em ratio. */ Velocity.CSS.setPropertyValue(dummy, "paddingLeft", measurement + "em"); /* Divide the returned value by the measurement to get the ratio between 1% and 1px. Default to 1 since working with 0 can produce Infinite. */ unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth = (parseFloat(CSS.getPropertyValue(dummy, "width", null, true)) || 1) / measurement; /* GET */ unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight = (parseFloat(CSS.getPropertyValue(dummy, "height", null, true)) || 1) / measurement; /* GET */ unitRatios.emToPx = callUnitConversionData.lastEmToPx = (parseFloat(CSS.getPropertyValue(dummy, "paddingLeft")) || 1) / measurement; /* GET */ sameRatioIndicators.myParent.removeChild(dummy); } else { unitRatios.emToPx = callUnitConversionData.lastEmToPx; unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth; unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight; } /*************************** Element-Agnostic Units ***************************/ /* Whereas % and em ratios are determined on a per-element basis, the rem unit only needs to be checked once per call since it's exclusively dependant upon document.body's fontSize. If this is the first time that calculateUnitRatios() is being run during this call, remToPx will still be set to its default value of null, so we calculate it now. */ if (callUnitConversionData.remToPx === null) { /* Default to browsers' default fontSize of 16px in the case of 0. */ callUnitConversionData.remToPx = parseFloat(CSS.getPropertyValue(document.body, "fontSize")) || 16; /* GET */ } /* Similarly, viewport units are %-relative to the window's inner dimensions. */ if (callUnitConversionData.vwToPx === null) { callUnitConversionData.vwToPx = parseFloat(window.innerWidth) / 100; /* GET */ callUnitConversionData.vhToPx = parseFloat(window.innerHeight) / 100; /* GET */ } unitRatios.remToPx = callUnitConversionData.remToPx; unitRatios.vwToPx = callUnitConversionData.vwToPx; unitRatios.vhToPx = callUnitConversionData.vhToPx; if (Velocity.debug >= 1) { console.log("Unit ratios: " + JSON.stringify(unitRatios), element); } return unitRatios; }; /******************** Unit Conversion ********************/ /* The * and / operators, which are not passed in with an associated unit, inherently use startValue's unit. Skip value and unit conversion. */ if (/[\/*]/.test(operator)) { endValueUnitType = startValueUnitType; /* If startValue and endValue differ in unit type, convert startValue into the same unit type as endValue so that if endValueUnitType is a relative unit (%, em, rem), the values set during tweening will continue to be accurately relative even if the metrics they depend on are dynamically changing during the course of the animation. Conversely, if we always normalized into px and used px for setting values, the px ratio would become stale if the original unit being animated toward was relative and the underlying metrics change during the animation. */ /* Since 0 is 0 in any unit type, no conversion is necessary when startValue is 0 -- we just start at 0 with endValueUnitType. */ } else if ((startValueUnitType !== endValueUnitType) && startValue !== 0) { /* Unit conversion is also skipped when endValue is 0, but *startValueUnitType* must be used for tween values to remain accurate. */ /* Note: Skipping unit conversion here means that if endValueUnitType was originally a relative unit, the animation won't relatively match the underlying metrics if they change, but this is acceptable since we're animating toward invisibility instead of toward visibility, which remains past the point of the animation's completion. */ if (endValue === 0) { endValueUnitType = startValueUnitType; } else { /* By this point, we cannot avoid unit conversion (it's undesirable since it causes layout thrashing). If we haven't already, we trigger calculateUnitRatios(), which runs once per element per call. */ elementUnitConversionData = elementUnitConversionData || calculateUnitRatios(); /* The following RegEx matches CSS properties that have their % values measured relative to the x-axis. */ /* Note: W3C spec mandates that all of margin and padding's properties (even top and bottom) are %-relative to the *width* of the parent element. */ var axis = (/margin|padding|left|right|width|text|word|letter/i.test(property) || /X$/.test(property) || property === "x") ? "x" : "y"; /* In order to avoid generating n^2 bespoke conversion functions, unit conversion is a two-step process: 1) Convert startValue into pixels. 2) Convert this new pixel value into endValue's unit type. */ switch (startValueUnitType) { case "%": /* Note: translateX and translateY are the only properties that are %-relative to an element's own dimensions -- not its parent's dimensions. Velocity does not include a special conversion process to account for this behavior. Therefore, animating translateX/Y from a % value to a non-% value will produce an incorrect start value. Fortunately, this sort of cross-unit conversion is rarely done by users in practice. */ startValue *= (axis === "x" ? elementUnitConversionData.percentToPxWidth : elementUnitConversionData.percentToPxHeight); break; case "px": /* px acts as our midpoint in the unit conversion process; do nothing. */ break; default: startValue *= elementUnitConversionData[startValueUnitType + "ToPx"]; } /* Invert the px ratios to convert into to the target unit. */ switch (endValueUnitType) { case "%": startValue *= 1 / (axis === "x" ? elementUnitConversionData.percentToPxWidth : elementUnitConversionData.percentToPxHeight); break; case "px": /* startValue is already in px, do nothing; we're done. */ break; default: startValue *= 1 / elementUnitConversionData[endValueUnitType + "ToPx"]; } } } /********************* Relative Values *********************/ /* Operator logic must be performed last since it requires unit-normalized start and end values. */ /* Note: Relative *percent values* do not behave how most people think; while one would expect "+=50%" to increase the property 1.5x its current value, it in fact increases the percent units in absolute terms: 50 points is added on top of the current % value. */ switch (operator) { case "+": endValue = startValue + endValue; break; case "-": endValue = startValue - endValue; break; case "*": endValue = startValue * endValue; break; case "/": endValue = startValue / endValue; break; } /************************** tweensContainer Push **************************/ /* Construct the per-property tween object, and push it to the element's tweensContainer. */ tweensContainer[property] = { rootPropertyValue: rootPropertyValue, startValue: startValue, currentValue: startValue, endValue: endValue, unitType: endValueUnitType, easing: easing }; if (Velocity.debug) { console.log("tweensContainer (" + property + "): " + JSON.stringify(tweensContainer[property]), element); } } /* Along with its property data, store a reference to the element itself onto tweensContainer. */ tweensContainer.element = element; } /***************** Call Push *****************/ /* Note: tweensContainer can be empty if all of the properties in this call's property map were skipped due to not being supported by the browser. The element property is used for checking that the tweensContainer has been appended to. */ if (tweensContainer.element) { /* Apply the "velocity-animating" indicator class. */ CSS.Values.addClass(element, "velocity-animating"); /* The call array houses the tweensContainers for each element being animated in the current call. */ call.push(tweensContainer); data = Data(element); if (data) { /* Store the tweensContainer and options if we're working on the default effects queue, so that they can be used by the reverse command. */ if (opts.queue === "") { data.tweensContainer = tweensContainer; data.opts = opts; } /* Switch on the element's animating flag. */ data.isAnimating = true; } /* Once the final element in this call's element set has been processed, push the call array onto Velocity.State.calls for the animation tick to immediately begin processing. */ if (elementsIndex === elementsLength - 1) { /* Add the current call plus its associated metadata (the element set and the call's options) onto the global call container. Anything on this call container is subjected to tick() processing. */ Velocity.State.calls.push([call, elements, opts, null, promiseData.resolver]); /* If the animation tick isn't running, start it. (Velocity shuts it off when there are no active calls to process.) */ if (Velocity.State.isTicking === false) { Velocity.State.isTicking = true; /* Start the tick loop. */ tick(); } } else { elementsIndex++; } } } /* When the queue option is set to false, the call skips the element's queue and fires immediately. */ if (opts.queue === false) { /* Since this buildQueue call doesn't respect the element's existing queue (which is where a delay option would have been appended), we manually inject the delay property here with an explicit setTimeout. */ if (opts.delay) { setTimeout(buildQueue, opts.delay); } else { buildQueue(); } /* Otherwise, the call undergoes element queueing as normal. */ /* Note: To interoperate with jQuery, Velocity uses jQuery's own $.queue() stack for queuing logic. */ } else { $.queue(element, opts.queue, function(next, clearQueue) { /* If the clearQueue flag was passed in by the stop command, resolve this call's promise. (Promises can only be resolved once, so it's fine if this is repeatedly triggered for each element in the associated call.) */ if (clearQueue === true) { if (promiseData.promise) { promiseData.resolver(elements); } /* Do not continue with animation queueing. */ return true; } /* This flag indicates to the upcoming completeCall() function that this queue entry was initiated by Velocity. See completeCall() for further details. */ Velocity.velocityQueueEntryFlag = true; buildQueue(next); }); } /********************* Auto-Dequeuing *********************/ /* As per jQuery's $.queue() behavior, to fire the first non-custom-queue entry on an element, the element must be dequeued if its queue stack consists *solely* of the current call. (This can be determined by checking for the "inprogress" item that jQuery prepends to active queue stack arrays.) Regardless, whenever the element's queue is further appended with additional items -- including $.delay()'s or even $.animate() calls, the queue's first entry is automatically fired. This behavior contrasts that of custom queues, which never auto-fire. */ /* Note: When an element set is being subjected to a non-parallel Velocity call, the animation will not begin until each one of the elements in the set has reached the end of its individually pre-existing queue chain. */ /* Note: Unfortunately, most people don't fully grasp jQuery's powerful, yet quirky, $.queue() function. Lean more here: http://stackoverflow.com/questions/1058158/can-somebody-explain-jquery-queue-to-me */ if ((opts.queue === "" || opts.queue === "fx") && $.queue(element)[0] !== "inprogress") { $.dequeue(element); } } /************************** Element Set Iteration **************************/ /* If the "nodeType" property exists on the elements variable, we're animating a single element. Place it in an array so that $.each() can iterate over it. */ $.each(elements, function(i, element) { /* Ensure each element in a set has a nodeType (is a real element) to avoid throwing errors. */ if (Type.isNode(element)) { processElement(element, i); } }); /****************** Option: Loop ******************/ /* The loop option accepts an integer indicating how many times the element should loop between the values in the current call's properties map and the element's property values prior to this call. */ /* Note: The loop option's logic is performed here -- after element processing -- because the current call needs to undergo its queue insertion prior to the loop option generating its series of constituent "reverse" calls, which chain after the current call. Two reverse calls (two "alternations") constitute one loop. */ opts = $.extend({}, Velocity.defaults, options); opts.loop = parseInt(opts.loop, 10); var reverseCallsCount = (opts.loop * 2) - 1; if (opts.loop) { /* Double the loop count to convert it into its appropriate number of "reverse" calls. Subtract 1 from the resulting value since the current call is included in the total alternation count. */ for (var x = 0; x < reverseCallsCount; x++) { /* Since the logic for the reverse action occurs inside Queueing and therefore this call's options object isn't parsed until then as well, the current call's delay option must be explicitly passed into the reverse call so that the delay logic that occurs inside *Pre-Queueing* can process it. */ var reverseOptions = { delay: opts.delay, progress: opts.progress }; /* If a complete callback was passed into this call, transfer it to the loop redirect's final "reverse" call so that it's triggered when the entire redirect is complete (and not when the very first animation is complete). */ if (x === reverseCallsCount - 1) { reverseOptions.display = opts.display; reverseOptions.visibility = opts.visibility; reverseOptions.complete = opts.complete; } animate(elements, "reverse", reverseOptions); } } /*************** Chaining ***************/ /* Return the elements back to the call chain, with wrapped elements taking precedence in case Velocity was called via the $.fn. extension. */ return getChain(); }; /* Turn Velocity into the animation function, extended with the pre-existing Velocity object. */ Velocity = $.extend(animate, Velocity); /* For legacy support, also expose the literal animate method. */ Velocity.animate = animate; /************** Timing **************/ /* Ticker function. */ var ticker = window.requestAnimationFrame || rAFShim; /* Inactive browser tabs pause rAF, which results in all active animations immediately sprinting to their completion states when the tab refocuses. To get around this, we dynamically switch rAF to setTimeout (which the browser *doesn't* pause) when the tab loses focus. We skip this for mobile devices to avoid wasting battery power on inactive tabs. */ /* Note: Tab focus detection doesn't work on older versions of IE, but that's okay since they don't support rAF to begin with. */ if (!Velocity.State.isMobile && document.hidden !== undefined) { document.addEventListener("visibilitychange", function() { /* Reassign the rAF function (which the global tick() function uses) based on the tab's focus state. */ if (document.hidden) { ticker = function(callback) { /* The tick function needs a truthy first argument in order to pass its internal timestamp check. */ return setTimeout(function() { callback(true); }, 16); }; /* The rAF loop has been paused by the browser, so we manually restart the tick. */ tick(); } else { ticker = window.requestAnimationFrame || rAFShim; } }); } /************ Tick ************/ /* Note: All calls to Velocity are pushed to the Velocity.State.calls array, which is fully iterated through upon each tick. */ function tick(timestamp) { /* An empty timestamp argument indicates that this is the first tick occurence since ticking was turned on. We leverage this metadata to fully ignore the first tick pass since RAF's initial pass is fired whenever the browser's next tick sync time occurs, which results in the first elements subjected to Velocity calls being animated out of sync with any elements animated immediately thereafter. In short, we ignore the first RAF tick pass so that elements being immediately consecutively animated -- instead of simultaneously animated by the same Velocity call -- are properly batched into the same initial RAF tick and consequently remain in sync thereafter. */ if (timestamp) { /* We normally use RAF's high resolution timestamp but as it can be significantly offset when the browser is under high stress we give the option for choppiness over allowing the browser to drop huge chunks of frames. */ var timeCurrent = Velocity.timestamp && timestamp !== true ? timestamp : (new Date()).getTime(); /******************** Call Iteration ********************/ var callsLength = Velocity.State.calls.length; /* To speed up iterating over this array, it is compacted (falsey items -- calls that have completed -- are removed) when its length has ballooned to a point that can impact tick performance. This only becomes necessary when animation has been continuous with many elements over a long period of time; whenever all active calls are completed, completeCall() clears Velocity.State.calls. */ if (callsLength > 10000) { Velocity.State.calls = compactSparseArray(Velocity.State.calls); callsLength = Velocity.State.calls.length; } /* Iterate through each active call. */ for (var i = 0; i < callsLength; i++) { /* When a Velocity call is completed, its Velocity.State.calls entry is set to false. Continue on to the next call. */ if (!Velocity.State.calls[i]) { continue; } /************************ Call-Wide Variables ************************/ var callContainer = Velocity.State.calls[i], call = callContainer[0], opts = callContainer[2], timeStart = callContainer[3], firstTick = !!timeStart, tweenDummyValue = null; /* If timeStart is undefined, then this is the first time that this call has been processed by tick(). We assign timeStart now so that its value is as close to the real animation start time as possible. (Conversely, had timeStart been defined when this call was added to Velocity.State.calls, the delay between that time and now would cause the first few frames of the tween to be skipped since percentComplete is calculated relative to timeStart.) */ /* Further, subtract 16ms (the approximate resolution of RAF) from the current time value so that the first tick iteration isn't wasted by animating at 0% tween completion, which would produce the same style value as the element's current value. */ if (!timeStart) { timeStart = Velocity.State.calls[i][3] = timeCurrent - 16; } /* The tween's completion percentage is relative to the tween's start time, not the tween's start value (which would result in unpredictable tween durations since JavaScript's timers are not particularly accurate). Accordingly, we ensure that percentComplete does not exceed 1. */ var percentComplete = Math.min((timeCurrent - timeStart) / opts.duration, 1); /********************** Element Iteration **********************/ /* For every call, iterate through each of the elements in its set. */ for (var j = 0, callLength = call.length; j < callLength; j++) { var tweensContainer = call[j], element = tweensContainer.element; /* Check to see if this element has been deleted midway through the animation by checking for the continued existence of its data cache. If it's gone, skip animating this element. */ if (!Data(element)) { continue; } var transformPropertyExists = false; /********************************** Display & Visibility Toggling **********************************/ /* If the display option is set to non-"none", set it upfront so that the element can become visible before tweening begins. (Otherwise, display's "none" value is set in completeCall() once the animation has completed.) */ if (opts.display !== undefined && opts.display !== null && opts.display !== "none") { if (opts.display === "flex") { var flexValues = ["-webkit-box", "-moz-box", "-ms-flexbox", "-webkit-flex"]; $.each(flexValues, function(i, flexValue) { CSS.setPropertyValue(element, "display", flexValue); }); } CSS.setPropertyValue(element, "display", opts.display); } /* Same goes with the visibility option, but its "none" equivalent is "hidden". */ if (opts.visibility !== undefined && opts.visibility !== "hidden") { CSS.setPropertyValue(element, "visibility", opts.visibility); } /************************ Property Iteration ************************/ /* For every element, iterate through each property. */ for (var property in tweensContainer) { /* Note: In addition to property tween data, tweensContainer contains a reference to its associated element. */ if (tweensContainer.hasOwnProperty(property) && property !== "element") { var tween = tweensContainer[property], currentValue, /* Easing can either be a pre-genereated function or a string that references a pre-registered easing on the Velocity.Easings object. In either case, return the appropriate easing *function*. */ easing = Type.isString(tween.easing) ? Velocity.Easings[tween.easing] : tween.easing; /****************************** Current Value Calculation ******************************/ /* If this is the last tick pass (if we've reached 100% completion for this tween), ensure that currentValue is explicitly set to its target endValue so that it's not subjected to any rounding. */ if (percentComplete === 1) { currentValue = tween.endValue; /* Otherwise, calculate currentValue based on the current delta from startValue. */ } else { var tweenDelta = tween.endValue - tween.startValue; currentValue = tween.startValue + (tweenDelta * easing(percentComplete, opts, tweenDelta)); /* If no value change is occurring, don't proceed with DOM updating. */ if (!firstTick && (currentValue === tween.currentValue)) { continue; } } tween.currentValue = currentValue; /* If we're tweening a fake 'tween' property in order to log transition values, update the one-per-call variable so that it can be passed into the progress callback. */ if (property === "tween") { tweenDummyValue = currentValue; } else { /****************** Hooks: Part I ******************/ var hookRoot; /* For hooked properties, the newly-updated rootPropertyValueCache is cached onto the element so that it can be used for subsequent hooks in this call that are associated with the same root property. If we didn't cache the updated rootPropertyValue, each subsequent update to the root property in this tick pass would reset the previous hook's updates to rootPropertyValue prior to injection. A nice performance byproduct of rootPropertyValue caching is that subsequently chained animations using the same hookRoot but a different hook can use this cached rootPropertyValue. */ if (CSS.Hooks.registered[property]) { hookRoot = CSS.Hooks.getRoot(property); var rootPropertyValueCache = Data(element).rootPropertyValueCache[hookRoot]; if (rootPropertyValueCache) { tween.rootPropertyValue = rootPropertyValueCache; } } /***************** DOM Update *****************/ /* setPropertyValue() returns an array of the property name and property value post any normalization that may have been performed. */ /* Note: To solve an IE<=8 positioning bug, the unit type is dropped when setting a property value of 0. */ var adjustedSetData = CSS.setPropertyValue(element, /* SET */ property, tween.currentValue + (parseFloat(currentValue) === 0 ? "" : tween.unitType), tween.rootPropertyValue, tween.scrollData); /******************* Hooks: Part II *******************/ /* Now that we have the hook's updated rootPropertyValue (the post-processed value provided by adjustedSetData), cache it onto the element. */ if (CSS.Hooks.registered[property]) { /* Since adjustedSetData contains normalized data ready for DOM updating, the rootPropertyValue needs to be re-extracted from its normalized form. ?? */ if (CSS.Normalizations.registered[hookRoot]) { Data(element).rootPropertyValueCache[hookRoot] = CSS.Normalizations.registered[hookRoot]("extract", null, adjustedSetData[1]); } else { Data(element).rootPropertyValueCache[hookRoot] = adjustedSetData[1]; } } /*************** Transforms ***************/ /* Flag whether a transform property is being animated so that flushTransformCache() can be triggered once this tick pass is complete. */ if (adjustedSetData[0] === "transform") { transformPropertyExists = true; } } } } /**************** mobileHA ****************/ /* If mobileHA is enabled, set the translate3d transform to null to force hardware acceleration. It's safe to override this property since Velocity doesn't actually support its animation (hooks are used in its place). */ if (opts.mobileHA) { /* Don't set the null transform hack if we've already done so. */ if (Data(element).transformCache.translate3d === undefined) { /* All entries on the transformCache object are later concatenated into a single transform string via flushTransformCache(). */ Data(element).transformCache.translate3d = "(0px, 0px, 0px)"; transformPropertyExists = true; } } if (transformPropertyExists) { CSS.flushTransformCache(element); } } /* The non-"none" display value is only applied to an element once -- when its associated call is first ticked through. Accordingly, it's set to false so that it isn't re-processed by this call in the next tick. */ if (opts.display !== undefined && opts.display !== "none") { Velocity.State.calls[i][2].display = false; } if (opts.visibility !== undefined && opts.visibility !== "hidden") { Velocity.State.calls[i][2].visibility = false; } /* Pass the elements and the timing data (percentComplete, msRemaining, timeStart, tweenDummyValue) into the progress callback. */ if (opts.progress) { opts.progress.call(callContainer[1], callContainer[1], percentComplete, Math.max(0, (timeStart + opts.duration) - timeCurrent), timeStart, tweenDummyValue); } /* If this call has finished tweening, pass its index to completeCall() to handle call cleanup. */ if (percentComplete === 1) { completeCall(i); } } } /* Note: completeCall() sets the isTicking flag to false when the last call on Velocity.State.calls has completed. */ if (Velocity.State.isTicking) { ticker(tick); } } /********************** Call Completion **********************/ /* Note: Unlike tick(), which processes all active calls at once, call completion is handled on a per-call basis. */ function completeCall(callIndex, isStopped) { /* Ensure the call exists. */ if (!Velocity.State.calls[callIndex]) { return false; } /* Pull the metadata from the call. */ var call = Velocity.State.calls[callIndex][0], elements = Velocity.State.calls[callIndex][1], opts = Velocity.State.calls[callIndex][2], resolver = Velocity.State.calls[callIndex][4]; var remainingCallsExist = false; /************************* Element Finalization *************************/ for (var i = 0, callLength = call.length; i < callLength; i++) { var element = call[i].element; /* If the user set display to "none" (intending to hide the element), set it now that the animation has completed. */ /* Note: display:none isn't set when calls are manually stopped (via Velocity("stop"). */ /* Note: Display gets ignored with "reverse" calls and infinite loops, since this behavior would be undesirable. */ if (!isStopped && !opts.loop) { if (opts.display === "none") { CSS.setPropertyValue(element, "display", opts.display); } if (opts.visibility === "hidden") { CSS.setPropertyValue(element, "visibility", opts.visibility); } } /* If the element's queue is empty (if only the "inprogress" item is left at position 0) or if its queue is about to run a non-Velocity-initiated entry, turn off the isAnimating flag. A non-Velocity-initiatied queue entry's logic might alter an element's CSS values and thereby cause Velocity's cached value data to go stale. To detect if a queue entry was initiated by Velocity, we check for the existence of our special Velocity.queueEntryFlag declaration, which minifiers won't rename since the flag is assigned to jQuery's global $ object and thus exists out of Velocity's own scope. */ var data = Data(element); if (opts.loop !== true && ($.queue(element)[1] === undefined || !/\.velocityQueueEntryFlag/i.test($.queue(element)[1]))) { /* The element may have been deleted. Ensure that its data cache still exists before acting on it. */ if (data) { data.isAnimating = false; /* Clear the element's rootPropertyValueCache, which will become stale. */ data.rootPropertyValueCache = {}; var transformHAPropertyExists = false; /* If any 3D transform subproperty is at its default value (regardless of unit type), remove it. */ $.each(CSS.Lists.transforms3D, function(i, transformName) { var defaultValue = /^scale/.test(transformName) ? 1 : 0, currentValue = data.transformCache[transformName]; if (data.transformCache[transformName] !== undefined && new RegExp("^\\(" + defaultValue + "[^.]").test(currentValue)) { transformHAPropertyExists = true; delete data.transformCache[transformName]; } }); /* Mobile devices have hardware acceleration removed at the end of the animation in order to avoid hogging the GPU's memory. */ if (opts.mobileHA) { transformHAPropertyExists = true; delete data.transformCache.translate3d; } /* Flush the subproperty removals to the DOM. */ if (transformHAPropertyExists) { CSS.flushTransformCache(element); } /* Remove the "velocity-animating" indicator class. */ CSS.Values.removeClass(element, "velocity-animating"); } } /********************* Option: Complete *********************/ /* Complete is fired once per call (not once per element) and is passed the full raw DOM element set as both its context and its first argument. */ /* Note: Callbacks aren't fired when calls are manually stopped (via Velocity("stop"). */ if (!isStopped && opts.complete && !opts.loop && (i === callLength - 1)) { /* We throw callbacks in a setTimeout so that thrown errors don't halt the execution of Velocity itself. */ try { opts.complete.call(elements, elements); } catch (error) { setTimeout(function() { throw error; }, 1); } } /********************** Promise Resolving **********************/ /* Note: Infinite loops don't return promises. */ if (resolver && opts.loop !== true) { resolver(elements); } /**************************** Option: Loop (Infinite) ****************************/ if (data && opts.loop === true && !isStopped) { /* If a rotateX/Y/Z property is being animated by 360 deg with loop:true, swap tween start/end values to enable continuous iterative rotation looping. (Otherise, the element would just rotate back and forth.) */ $.each(data.tweensContainer, function(propertyName, tweenContainer) { if (/^rotate/.test(propertyName) && ((parseFloat(tweenContainer.startValue) - parseFloat(tweenContainer.endValue)) % 360 === 0)) { var oldStartValue = tweenContainer.startValue; tweenContainer.startValue = tweenContainer.endValue; tweenContainer.endValue = oldStartValue; } if (/^backgroundPosition/.test(propertyName) && parseFloat(tweenContainer.endValue) === 100 && tweenContainer.unitType === "%") { tweenContainer.endValue = 0; tweenContainer.startValue = 100; } }); Velocity(element, "reverse", {loop: true, delay: opts.delay}); } /*************** Dequeueing ***************/ /* Fire the next call in the queue so long as this call's queue wasn't set to false (to trigger a parallel animation), which would have already caused the next call to fire. Note: Even if the end of the animation queue has been reached, $.dequeue() must still be called in order to completely clear jQuery's animation queue. */ if (opts.queue !== false) { $.dequeue(element, opts.queue); } } /************************ Calls Array Cleanup ************************/ /* Since this call is complete, set it to false so that the rAF tick skips it. This array is later compacted via compactSparseArray(). (For performance reasons, the call is set to false instead of being deleted from the array: http://www.html5rocks.com/en/tutorials/speed/v8/) */ Velocity.State.calls[callIndex] = false; /* Iterate through the calls array to determine if this was the final in-progress animation. If so, set a flag to end ticking and clear the calls array. */ for (var j = 0, callsLength = Velocity.State.calls.length; j < callsLength; j++) { if (Velocity.State.calls[j] !== false) { remainingCallsExist = true; break; } } if (remainingCallsExist === false) { /* tick() will detect this flag upon its next iteration and subsequently turn itself off. */ Velocity.State.isTicking = false; /* Clear the calls array so that its length is reset. */ delete Velocity.State.calls; Velocity.State.calls = []; } } /****************** Frameworks ******************/ /* Both jQuery and Zepto allow their $.fn object to be extended to allow wrapped elements to be subjected to plugin calls. If either framework is loaded, register a "velocity" extension pointing to Velocity's core animate() method. Velocity also registers itself onto a global container (window.jQuery || window.Zepto || window) so that certain features are accessible beyond just a per-element scope. This master object contains an .animate() method, which is later assigned to $.fn (if jQuery or Zepto are present). Accordingly, Velocity can both act on wrapped DOM elements and stand alone for targeting raw DOM elements. */ global.Velocity = Velocity; if (global !== window) { /* Assign the element function to Velocity's core animate() method. */ global.fn.velocity = animate; /* Assign the object function's defaults to Velocity's global defaults object. */ global.fn.velocity.defaults = Velocity.defaults; } /*********************** Packaged Redirects ***********************/ /* slideUp, slideDown */ $.each(["Down", "Up"], function(i, direction) { Velocity.Redirects["slide" + direction] = function(element, options, elementsIndex, elementsSize, elements, promiseData) { var opts = $.extend({}, options), begin = opts.begin, complete = opts.complete, inlineValues = {}, computedValues = {height: "", marginTop: "", marginBottom: "", paddingTop: "", paddingBottom: ""}; if (opts.display === undefined) { /* Show the element before slideDown begins and hide the element after slideUp completes. */ /* Note: Inline elements cannot have dimensions animated, so they're reverted to inline-block. */ opts.display = (direction === "Down" ? (Velocity.CSS.Values.getDisplayType(element) === "inline" ? "inline-block" : "block") : "none"); } opts.begin = function() { /* If the user passed in a begin callback, fire it now. */ if (elementsIndex === 0 && begin) { begin.call(elements, elements); } /* Cache the elements' original vertical dimensional property values so that we can animate back to them. */ for (var property in computedValues) { if (!computedValues.hasOwnProperty(property)) { continue; } inlineValues[property] = element.style[property]; /* For slideDown, use forcefeeding to animate all vertical properties from 0. For slideUp, use forcefeeding to start from computed values and animate down to 0. */ var propertyValue = CSS.getPropertyValue(element, property); computedValues[property] = (direction === "Down") ? [propertyValue, 0] : [0, propertyValue]; } /* Force vertical overflow content to clip so that sliding works as expected. */ inlineValues.overflow = element.style.overflow; element.style.overflow = "hidden"; }; opts.complete = function() { /* Reset element to its pre-slide inline values once its slide animation is complete. */ for (var property in inlineValues) { if (inlineValues.hasOwnProperty(property)) { element.style[property] = inlineValues[property]; } } /* If the user passed in a complete callback, fire it now. */ if (elementsIndex === elementsSize - 1) { if (complete) { complete.call(elements, elements); } if (promiseData) { promiseData.resolver(elements); } } }; Velocity(element, computedValues, opts); }; }); /* fadeIn, fadeOut */ $.each(["In", "Out"], function(i, direction) { Velocity.Redirects["fade" + direction] = function(element, options, elementsIndex, elementsSize, elements, promiseData) { var opts = $.extend({}, options), complete = opts.complete, propertiesMap = {opacity: (direction === "In") ? 1 : 0}; /* Since redirects are triggered individually for each element in the animated set, avoid repeatedly triggering callbacks by firing them only when the final element has been reached. */ if (elementsIndex !== 0) { opts.begin = null; } if (elementsIndex !== elementsSize - 1) { opts.complete = null; } else { opts.complete = function() { if (complete) { complete.call(elements, elements); } if (promiseData) { promiseData.resolver(elements); } }; } /* If a display was passed in, use it. Otherwise, default to "none" for fadeOut or the element-specific default for fadeIn. */ /* Note: We allow users to pass in "null" to skip display setting altogether. */ if (opts.display === undefined) { opts.display = (direction === "In" ? "auto" : "none"); } Velocity(this, propertiesMap, opts); }; }); return Velocity; }((window.jQuery || window.Zepto || window), window, document); })); /****************** Known Issues ******************/ /* The CSS spec mandates that the translateX/Y/Z transforms are %-relative to the element itself -- not its parent. Velocity, however, doesn't make this distinction. Thus, converting to or from the % unit with these subproperties will produce an inaccurate conversion value. The same issue exists with the cx/cy attributes of SVG circles and ellipses. */
(function(){ "use strict"; angular .module('StarterApp') .controller('LoginCtrl', function($scope, $state, User, auth, $http){ if(auth.isLoggedIn()){ console.log("success logged fucker"); auth.getuser().then(function(data){ $scope.name = data.data.name; $scope.email = data.data.email; User.getp().then(function(data){ console.log(data.data.permission); if(data.data.permission == 'admin' || data.data.permission == 'moderator'){ $scope.grantedpermission = true; }else if(data.data.permission == 'user'){ $scope.grantedpermission = false; $scope.grantedprofile = true;// Show main HTML now that data is obtained in AngularJS } else{ $scope.grantedpermission = false; $scope.grantedprofile = false;// Show main HTML now that data is obtained in AngularJS } }) }); } else { console.log('failure'); } $scope.submit = function(logg){ $scope.errorMsg = false; console.log(logg); //$http.post('/api/userss', usr) auth.login(logg).then(function(data){ console.log(data); if(data.data.success){ $scope.successMsg = data.data.message; $state.go('about'); } else { $scope.errorMsg = data.data.message; } }); } $scope.logout = function(){ auth.logout(); $state.go('login'); } }); })();
jQuery("#colspan").jqGrid({ url:'server.php?q=4', datatype: "json", colNames:['Date', 'Inv No', 'Client', 'Amount','Tax','Total','Notes'], colModel:[ {name:'invdate',index:'invdate', width:90}, { name:'id', key : true, index:'id', width:55, cellattr: function(rowId, value, rowObject, colModel, arrData) { return ' colspan=2'; }, formatter : function(value, options, rData){ return "Invoce: "+value + " - "+rData['name']; } }, {name:'name', index:'name', width:100, cellattr: function(rowId, value, rowObject, colModel, arrData) { return " style=display:none; "; } }, {name:'amount',index:'amount', width:80, align:"right"}, {name:'tax',index:'tax', width:80, align:"right"}, {name:'total',index:'total', width:80,align:"right"}, {name:'note',index:'note', width:150, sortable:false} ], rowNum:10, width:700, rowList:[10,20,30], pager: '#pcolspan', sortname: 'invdate', viewrecords: true, sortorder: "desc", jsonReader: { repeatitems : false }, caption: "Data colspan", height: '100%' }); jQuery("#colspan").jqGrid('navGrid','#pcolspan',{edit:false,add:false,del:false});
'use strict'; var app = require('../../src/app.js').app; var assert = require('assert'); describe('app', function(){ it('should contain toots', function(){ assert.ok(app !== null); assert.ok(app.toots); }); });
{ "name": "expression.js", "url": "https://github.com/gafish/expression.js.git" }
function myCalc(el, amount) { return el + amount; }
/*jslint browser: true, undef: true, white: false, laxbreak: true *//*global Ext, EmergenceEditor*/ Ext.define('EmergenceEditor.view.contextmenu.RevisionsMenu', { extend: 'Ext.menu.Menu' ,alias: 'widget.emergence-revisionsmenu' ,width: 150 ,items: [ { text: 'Open' ,action: 'open' ,icon: '/img/icons/fugue/blue-folder-horizontal-open.png' } ,{ text: 'Properties' ,action: 'properties' ,icon: '/img/icons/fugue/property-blue.png' } ,{ text: 'Compare Latest' ,action: 'compare_latest' //,icon: '' } ,{ text: 'Compare Next' ,action: 'compare_next' //,icon: '' } ,{ text: 'Compare Previous' ,action: 'compare_previous' //,icon: '' } ] });
import { GraphQLSchema } from 'meteor/nova:core'; const generateTypeDefs = () => [` scalar JSON scalar Date ${GraphQLSchema.getCollectionsSchemas()} ${GraphQLSchema.getAdditionalSchemas()} type Query { ${GraphQLSchema.queries.join('\n')} } type Mutation { ${GraphQLSchema.mutations.join('\n')} } `]; export default generateTypeDefs;
var PageName = 'suv'; var PageId = 'p6dc2bed07b354378aaba313dbdee30c6' var PageUrl = 'suv.html' document.title = 'suv'; if (top.location != self.location) { if (parent.HandleMainFrameChanged) { parent.HandleMainFrameChanged(); } } var $OnLoadVariable = ''; var $CSUM; var hasQuery = false; var query = window.location.hash.substring(1); if (query.length > 0) hasQuery = true; var vars = query.split("&"); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split("="); if (pair[0].length > 0) eval("$" + pair[0] + " = decodeURIComponent(pair[1]);"); } if (hasQuery && $CSUM != 1) { alert('Prototype Warning: The variable values were too long to pass to this page.\nIf you are using IE, using Firefox will support more data.'); } function GetQuerystring() { return '#OnLoadVariable=' + encodeURIComponent($OnLoadVariable) + '&CSUM=1'; } function PopulateVariables(value) { value = value.replace(/\[\[OnLoadVariable\]\]/g, $OnLoadVariable); value = value.replace(/\[\[PageName\]\]/g, PageName); return value; } function OnLoad(e) { } var u0 = document.getElementById('u0'); if (window.OnLoad) OnLoad();
import React from 'react' import _ from 'lodash' import Sidebar from 'src/modules/Sidebar/Sidebar' import * as common from 'test/specs/commonTests' describe('Sidebar', () => { common.isConformant(Sidebar) common.rendersChildren(Sidebar) common.hasUIClassName(Sidebar) common.propKeyOnlyToClassName(Sidebar, 'visible') common.propValueOnlyToClassName(Sidebar, 'width') common.propValueOnlyToClassName(Sidebar, 'animation') it('renders a <div /> element', () => { shallow(<Sidebar />) .should.have.tagName('div') }) it('renders children of the sidebar', () => { const wrapper = mount(<Sidebar><span /></Sidebar>) wrapper.children().at(0).should.have.tagName('span') }) it('adds direction value to className', () => { _.each(_.get(Sidebar, '_meta.props.direction'), propValue => { shallow(<Sidebar direction={propValue} />).should.have.className(propValue) }) }) })
/* Static dependencies */ /* JS dependencies */ import React from 'react'; export default class NoMatch extends React.Component { constructor (...args) { super(...args); this.state = { }; } render () { return ( <div class="text-center"> <h4>Page Not Found</h4> <h1>404</h1> </div> ); } }; NoMatch.propTypes = { };
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M13 5.08c3.06.44 5.48 2.86 5.92 5.92h3.03c-.47-4.72-4.23-8.48-8.95-8.95v3.03zM18.92 13c-.44 3.06-2.86 5.48-5.92 5.92v3.03c4.72-.47 8.48-4.23 8.95-8.95h-3.03zM11 18.92c-3.39-.49-6-3.4-6-6.92s2.61-6.43 6-6.92V2.05c-5.05.5-9 4.76-9 9.95 0 5.19 3.95 9.45 9 9.95v-3.03z" /></g></React.Fragment> , 'DonutLargeSharp');
//! moment.js locale configuration //! locale : Javanese [jv] //! author : Rony Lantip : https://github.com/lantip //! reference: http://jv.wikipedia.org/wiki/Basa_Jawa ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof define === 'function' && define.amd ? define(['../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; var jv = moment.defineLocale('jv', { months : 'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_Nopember_Desember'.split('_'), monthsShort : 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nop_Des'.split('_'), weekdays : 'Minggu_Senen_Seloso_Rebu_Kemis_Jemuwah_Septu'.split('_'), weekdaysShort : 'Min_Sen_Sel_Reb_Kem_Jem_Sep'.split('_'), weekdaysMin : 'Mg_Sn_Sl_Rb_Km_Jm_Sp'.split('_'), longDateFormat : { LT : 'HH.mm', LTS : 'HH.mm.ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY [pukul] HH.mm', LLLL : 'dddd, D MMMM YYYY [pukul] HH.mm' }, meridiemParse: /enjing|siyang|sonten|ndalu/, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'enjing') { return hour; } else if (meridiem === 'siyang') { return hour >= 11 ? hour : hour + 12; } else if (meridiem === 'sonten' || meridiem === 'ndalu') { return hour + 12; } }, meridiem : function (hours, minutes, isLower) { if (hours < 11) { return 'enjing'; } else if (hours < 15) { return 'siyang'; } else if (hours < 19) { return 'sonten'; } else { return 'ndalu'; } }, calendar : { sameDay : '[Dinten puniko pukul] LT', nextDay : '[Mbenjang pukul] LT', nextWeek : 'dddd [pukul] LT', lastDay : '[Kala wingi pukul] LT', lastWeek : 'dddd [kepengker pukul] LT', sameElse : 'L' }, relativeTime : { future : 'wonten ing %s', past : '%s ingkang kepengker', s : 'sawetawis detik', m : 'setunggal menit', mm : '%d menit', h : 'setunggal jam', hh : '%d jam', d : 'sedinten', dd : '%d dinten', M : 'sewulan', MM : '%d wulan', y : 'setaun', yy : '%d taun' }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); return jv; }));
/** @license * Angular Canvas Extensions - AngularJS module * * Allows to open images in canvas, zoom, pan, crop, resize and download image. * * https://github.com/petalvlad/angular-canvas-ext * * Copyright (c) 2014 Alex Petropavlovsky <petalvlad@gmail.com> * Released under the MIT license */ var canvasExtModule = angular.module('ap.canvas.ext', []); canvasExtModule.factory('apBrowserHelper', function () { var uagent = navigator.userAgent.toLowerCase(), browser = {}, platform = {}; platform.ios = /iphone|ipad|ipod/.test(uagent); platform.ipad = /ipad/.test(uagent); platform.android = /android/.test(uagent); platform.blackberry = /blackberry/.test(uagent); platform.windowsPhone = /iemobile/.test(uagent); platform.mobile = platform.ios || platform.android || platform.blackberry || platform.windowsPhone; platform.desktop = !platform.mobile; browser.firefox = /mozilla/.test(uagent) && /firefox/.test(uagent); browser.chrome = /webkit/.test(uagent) && /chrome/.test(uagent); browser.safari = /applewebkit/.test(uagent) && /safari/.test(uagent) && !/chrome/.test(uagent); browser.opera = /opera/.test(uagent); browser.msie = /msie/.test(uagent); browser.version = ''; if (!(browser.msie || browser.firefox || browser.chrome || browser.safari || browser.opera)) { if (/trident/.test(uagent)) { browser.msie = true; browser.version = 11; } } if (browser.version === '') { for (x in browser) { if (browser[x]) { browser.version = uagent.match(new RegExp('(' + x + ')( |/)([0-9]+)'))[3]; break; } } } return { browser: browser, platform: platform }; });canvasExtModule.factory('apImageHelper', function (apBrowserHelper) { var browser = apBrowserHelper.browser, platform = apBrowserHelper.platform; function downloadImageHandler(imageDataURI, filename, event) { var dataURI = imageDataURI; function prevent() { event.preventDefault(); return false; } if (!dataURI) { return prevent(); } if (platform.ios) { window.win = open(dataURI); return prevent(); } if (browser.msie) { var blob = dataURItoBlob(dataURI); window.navigator.msSaveOrOpenBlob(blob, filename); return prevent(); } var type = mimetypeOfDataURI(dataURI); dataURI = dataURI.replace(type, 'image/octet-stream'); event.target.href = dataURI; event.target.download = filename; return true; } function mimetypeOfDataURI(dataURI) { return dataURI.split(',')[0].split(':')[1].split(';')[0]; } function dataURItoBlob(dataURI) { var byteString; if (dataURI.split(',')[0].indexOf('base64') >= 0) { byteString = atob(dataURI.split(',')[1]); } else { byteString = unescape(dataURI.split(',')[1]); } var mimeString = mimetypeOfDataURI(dataURI); var ab = new ArrayBuffer(byteString.length); var ia = new Uint8Array(ab); for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } return new Blob([ab], { type: mimeString }); } function fileToImageDataURI(file, type, quality, callback) { if (!type) { type = file.type; } var imgSrc = URL.createObjectURL(file); if (imgSrc && imgSrc !== '') { var image = new Image(); image.onload = function () { if (platform.ios) { getImageExifOrientation(image, function (orientation) { var fixOptions = { orientation: orientation }; fixImage(image, fixOptions, function (target) { callback(canvasToDataURI(target, type, quality)); }); }); } else { var ctx = createCanvasContext(image.width, image.height); ctx.drawImage(image, 0, 0); callback(canvasToDataURI(ctx.canvas, type, quality)); } }; image.src = imgSrc; } else { callback(null); } } function getImageExifOrientation(image, callback) { EXIF.getData(image, function () { callback(EXIF.getTag(image, 'Orientation')); }); } function createCanvasContext(width, height) { var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; return canvas.getContext('2d'); } function fixImage(image, fixOptions, callback) { var mpImg = new MegaPixImage(image), canvas = createCanvasContext(image.width, image.height).canvas; mpImg.onrender = function (target) { callback(target); }; mpImg.render(canvas, fixOptions); } function copyImageData(ctx, src) { var dst = ctx.createImageData(src.width, src.height); if (dst.data.set) { dst.data.set(src.data); } else { var srcData = src.data, dstData = dst.data; for (var i = 0; i < srcData.length; ++i) { dstData[i] = srcData[i]; } } return dst; } function cropImage(image, size, offset) { var frame = { size: size, origin: { x: image.width / 2 - size.width / 2 - offset.x, y: image.height / 2 - size.height / 2 - offset.y } }; return cropImage(image, frame); } function cropImage(image, frame, maxSize, type, quality) { if (!image || !(image instanceof Image) && !(image instanceof ImageData) && !(image instanceof HTMLCanvasElement)) { return null; } var ctx = createCanvasContext(frame.size.width, frame.size.height), imageHalfWidth = image.width / 2, imageHalfHeight = image.height / 2, newImageHalfWidth = frame.size.width / 2, newImageHalfHeight = frame.size.height / 2, left = frame.origin.x, top = frame.origin.y; if (image instanceof ImageData) { var srcCtx = createCanvasContext(image.width, image.height); srcCtx.putImageData(image, 0, 0); image = srcCtx.canvas; } ctx.drawImage(image, left, top, frame.size.width, frame.size.height, 0, 0, frame.size.width, frame.size.height); if (maxSize && (frame.size.width > maxSize.width || frame.size.height > maxSize.height)) { return resizeImage(ctx.canvas, maxSize, type, quality); } return canvasData(ctx, type, quality); } function resizeImage(image, size, type, quality, fill) { if (!image || !(image instanceof Image) && !(image instanceof ImageData) && !(image instanceof HTMLCanvasElement)) { return null; } var widthScale = size.width / image.width, heightScale = size.height / image.height, scale = fill ? Math.max(widthScale, heightScale) : Math.min(widthScale, heightScale), size = { width: image.width * scale, height: image.height * scale }; var dstCtx = createCanvasContext(size.width, size.height); if (image instanceof ImageData) { var srcCtx = createCanvasContext(image.width, image.height); srcCtx.putImageData(image, 0, 0); image = srcCtx.canvas; } dstCtx.drawImage(image, 0, 0, dstCtx.canvas.width, dstCtx.canvas.height); return canvasData(dstCtx, type, quality); } function getImageOffsetLimits(image, scale, size) { var imageHalfWidth = image.width / 2, imageHalfHeight = image.height / 2, boundsHalfWidth = size.width / 2, boundsHalfHeight = size.height / 2, scaledBoundsHalfWidth = boundsHalfWidth / scale, scaledBoundsHalfHeight = boundsHalfHeight / scale; return { left: -imageHalfWidth + scaledBoundsHalfWidth, right: imageHalfWidth - scaledBoundsHalfWidth, top: -imageHalfHeight + scaledBoundsHalfHeight, bottom: imageHalfHeight - scaledBoundsHalfHeight }; } function drawImage(image, scale, offset, ctx) { var imageHalfWidth = image.width / 2, imageHalfHeight = image.height / 2, canvasHalfWidth = ctx.canvas.width / 2, canvasHalfHeight = ctx.canvas.height / 2, beforeScaleOffset = { x: (-imageHalfWidth + offset.x) * scale, y: (-imageHalfHeight + offset.y) * scale }, afterScaleOffset = { x: canvasHalfWidth / scale, y: canvasHalfHeight / scale }; ctx.canvas.width = ctx.canvas.width; // move center to the left and top corner ctx.translate(beforeScaleOffset.x, beforeScaleOffset.y); // scale ctx.scale(scale, scale); // move center back to the center ctx.translate(afterScaleOffset.x, afterScaleOffset.y); // draw image in original size ctx.drawImage(image, 0, 0, image.width, image.height); // return frame of cropped image return { size: { width: ctx.canvas.width / scale, height: ctx.canvas.height / scale }, origin: { x: imageHalfWidth - canvasHalfWidth / scale - offset.x, y: imageHalfHeight - canvasHalfHeight / scale - offset.y } }; } function snapImage(image, size, scale, offset) { var ctx = createCanvasContext(size.width, size.height); drawImage(image, scale, offset, ctx); return canvasData(ctx); } function canvasToDataURI(canvas, type, quality) { if (!type) { type = 'image/jpg'; } if (!quality) { quality = 1; } return canvas.toDataURL(type, quality); } function canvasData(ctx, type, quality) { return { dataURI: canvasToDataURI(ctx.canvas, type, quality), imageData: ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height) }; } return { downloadImageHandler: downloadImageHandler, dataURItoBlob: dataURItoBlob, fileToImageDataURI: fileToImageDataURI, copyImageData: copyImageData, cropImage: cropImage, resizeImage: resizeImage, getImageOffsetLimits: getImageOffsetLimits, drawImage: drawImage }; }); canvasExtModule.directive('apCanvas', function (apImageHelper) { return { restrict: 'A', scope: { src: '=', scale: '=?', offset: '=?', zoomable: '=?', mode: '=?', image: '=?', frame: '=?' }, link: function ($scope, element, attrs) { var canvas = element[0], ctx = canvas.getContext('2d'), previousMousePosition = null, isMoving = false, defaultScale = 1, isUpdateOffset = false, isUpdateScale = false, lastZoomDist = null; if (!$scope.scale) { $scope.scale = defaultScale; } if (!$scope.offset) { $scope.offset = { x: 0, y: 0 }; } if (!$scope.mode) { $scope.mode = 'fill'; } $scope.$watch(function () { return $scope.src; }, function (newSrc) { console.log('new src ' + newSrc); if (newSrc) { loadImage(); } else { $scope.image = null; } }); function loadImage() { var image = new Image(); image.onload = function () { $scope.image = image; $scope.$apply(); }; image.src = $scope.src; } $scope.$watch(function () { return $scope.image; }, function (newImage) { console.log('new image ' + newImage); canvas.width = canvas.width; if (newImage) { updateScale(); drawImage(); } }); function setScale(scale) { isUpdateScale = true; $scope.scale = scale; isUpdateScale = false; } function updateScale() { var image = $scope.image, widthScale = canvas.width / image.width, heightScale = canvas.height / image.height; if ($scope.mode === 'fill') { defaultScale = Math.max(widthScale, heightScale); } else if ($scope.mode === 'fit') { defaultScale = Math.min(widthScale, heightScale); } else { defaultScale = 1; } setScale(defaultScale); } function drawImage() { if (!$scope.image || isUpdateScale || isUpdateOffset) { return; } clipToBounds(); $scope.frame = apImageHelper.drawImage($scope.image, $scope.scale, $scope.offset, ctx); } function clipToBounds() { isUpdateOffset = true; var bounds = { width: canvas.width, height: canvas.height }, offsetLimits = apImageHelper.getImageOffsetLimits($scope.image, $scope.scale, bounds); if ($scope.offset.y < offsetLimits.top) { $scope.offset.y = offsetLimits.top; } if ($scope.offset.y > offsetLimits.bottom) { $scope.offset.y = offsetLimits.bottom; } if ($scope.offset.x < offsetLimits.left) { $scope.offset.x = offsetLimits.left; } if ($scope.offset.x > offsetLimits.right) { $scope.offset.x = offsetLimits.right; } isUpdateOffset = false; } if ($scope.zoomable) { function getMousePosition(e) { var rect = canvas.getBoundingClientRect(); return { x: (e.clientX - rect.left) / $scope.scale, y: (e.clientY - rect.top) / $scope.scale }; } function setIsMoving(moving, event, position) { event.preventDefault(); isMoving = moving; if (moving) { previousMousePosition = getMousePosition(position); } } function moveTo(e, position) { if (isMoving) { e.preventDefault(); var mousePosition = getMousePosition(position); $scope.offset = { x: $scope.offset.x + (mousePosition.x - previousMousePosition.x), y: $scope.offset.y + (mousePosition.y - previousMousePosition.y) }; previousMousePosition = mousePosition; $scope.$apply(); } } function zoom(e, touch1, touch2) { e.preventDefault(); var dist = Math.sqrt(Math.pow(touch2.pageX - touch1.pageX, 2) + Math.pow(touch2.pageY - touch1.pageY, 2)); if (lastZoomDist) { $scope.scale *= dist / lastZoomDist; $scope.$apply(); } lastZoomDist = dist; } function handleMouseDown(e) { setIsMoving(true, e, e); } function handleTouchStart(e) { if (e.targetTouches.length === 1) { setIsMoving(true, e, e.changedTouches[0]); } } function handleMouseUp(e) { setIsMoving(false, e); } function handleTouchEnd(e) { lastZoomDist = null; setIsMoving(false, e); } function handleMouseMove(e) { moveTo(e, e); } function handleTouchMove(e) { if (e.targetTouches.length >= 2) { var touch1 = e.targetTouches[0], touch2 = e.targetTouches[1]; if (touch1 && touch2) { zoom(e, touch1, touch2); } } else { moveTo(e, e.changedTouches[0]); } } function handleMouseWheel(e) { if (e.wheelDelta > 0) { $scope.scale *= 1.01; } else { $scope.scale /= 1.01; } } canvas.addEventListener('mousedown', handleMouseDown, false); canvas.addEventListener('mouseup', handleMouseUp, false); canvas.addEventListener('mouseleave', handleMouseUp, false); canvas.addEventListener('mousemove', handleMouseMove, false); canvas.addEventListener('mousewheel', handleMouseWheel, false); canvas.addEventListener('touchstart', handleTouchStart, false); canvas.addEventListener('touchend', handleTouchEnd, false); canvas.addEventListener('touchcancel', handleTouchEnd, false); canvas.addEventListener('touchleave', handleTouchEnd, false); canvas.addEventListener('touchmove', handleTouchMove, false); $scope.$watch(function () { return $scope.scale; }, function (newScale, oldScale) { if (newScale < defaultScale) { setScale(defaultScale); } drawImage(); }); $scope.$watch(function () { return $scope.offset; }, function (newOffset) { drawImage(); }); } } }; });canvasExtModule.directive('apFileSrc', function (apImageHelper) { return { restrict: 'A', scope: { src: '=apFileSrc', onImageSelected: '&?', onImageReady: '&?', mimeType: '=?', quality: '=?' }, link: function ($scope, element, attrs) { var updateImageSrc = function (src) { console.log('new src ' + src); $scope.src = src; $scope.$apply(); if ($scope.onImageReady) { $scope.onImageReady(); } }; element.bind('change', function (e) { console.log('file changed'); if ($scope.onImageSelected) { $scope.onImageSelected(); } var file = e.target.files.length ? e.target.files[0] : null; if (file) { apImageHelper.fileToImageDataURI(file, $scope.mimeType, $scope.quality, updateImageSrc); } }); } }; });
define({ root: ({ _widgetLabel: "Share", selectSocialNetwork: "Select following options to share the app:", email: "Email", facebook: "Facebook", googlePlus: "Google+", twitter: "Twitter", addNew: "Add new", socialMediaUrl: "Your social media URL", uploadIcon: "Upload icon", embedAppInWebsite: "Embed the app in website" }), "ar": 1, "bs": 1, "ca": 1, "cs": 1, "da": 1, "de": 1, "el": 1, "es": 1, "et": 1, "fi": 1, "fr": 1, "he": 1, "hi": 1, "hr": 1, "hu": 1, "it": 1, "id": 1, "ja": 1, "ko": 1, "lt": 1, "lv": 1, "nb": 1, "nl": 1, "pl": 1, "pt-br": 1, "pt-pt": 1, "ro": 1, "ru": 1, "sl": 1, "sr": 1, "sv": 1, "th": 1, "tr": 1, "uk": 1, "vi": 1, "zh-cn": 1, "zh-hk": 1, "zh-tw": 1 });
"use strict"; window.Freya = window.Freya || {}; $(function() { // Prevent default browser behavior for file dropping // (by default, pages have single uploading area) $(document).bind("drop dragover", function (e) { e.preventDefault(); }); });
var forOwn = require('./forOwn'); var makeIterator = require('../function/makeIterator_'); /** * Object every */ function every(obj, callback, thisObj) { callback = makeIterator(callback); var result = true; forOwn(obj, function(val, key) { // we consider any falsy values as "false" on purpose so shorthand // syntax can be used to check property existence if (!callback.call(thisObj, val, key, obj)) { result = false; return false; // break } }); return result; } module.exports = every;
/** A Suite defines a `describe` block @class Suite @namespace Primrose @extends Base @uses Primrose.BeforeEach @uses Primrose.Reportable @constructor **/ Y.namespace('Primrose').Suite = Y.Base.create('primrose:suite', Y.Base, [Y.Primrose.BeforeEach, Y.Primrose.Reportable], { /** add a spec or a suite to the suite @method add @param {Primrose.Spec|Primrose.Suite} child **/ add: function (child) { var befores = this.get('beforeList'); this.get('children').push(child); // enable bubbling child.addTarget(this); // add any beforeEach blocks to the child if (befores.length) { child.addBefores( befores ); } }, /** run the suite and children @method run **/ run: function () { // run all children Y.Array.invoke(this.get('children'), 'run'); } }, { ATTRS: { /** @attribute description @type {String} **/ description: {}, /** @attribute children @type {Array[Primrose.Spec|Primrose.Suite]} **/ children: { value: [] }, /** @attribute beforeList @type {Array[Function]} **/ beforeList: { value: [] } } });
/** * @author Rich Tibbett / https://github.com/richtr * @author mrdoob / http://mrdoob.com/ * @author Tony Parisi / http://www.tonyparisi.com/ * @author Takahiro / https://github.com/takahirox * @author Don McCurdy / https://www.donmccurdy.com */ THREE.GLTF2Loader = ( function () { function GLTF2Loader( manager ) { this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager; } GLTF2Loader.prototype = { constructor: GLTF2Loader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var path = this.path && ( typeof this.path === "string" ) ? this.path : THREE.Loader.prototype.extractUrlBase( url ); var loader = new THREE.FileLoader( scope.manager ); loader.setResponseType( 'arraybuffer' ); loader.load( url, function ( data ) { scope.parse( data, onLoad, path ); }, onProgress, onError ); }, setCrossOrigin: function ( value ) { this.crossOrigin = value; }, setPath: function ( value ) { this.path = value; }, parse: function ( data, callback, path ) { var content; var extensions = {}; var magic = convertUint8ArrayToString( new Uint8Array( data, 0, 4 ) ); if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) { extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data ); content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content; } else { content = convertUint8ArrayToString( new Uint8Array( data ) ); } var json = JSON.parse( content ); if ( json.extensionsUsed ) { if( json.extensionsUsed.indexOf( EXTENSIONS.KHR_LIGHTS ) >= 0 ) { extensions[ EXTENSIONS.KHR_LIGHTS ] = new GLTFLightsExtension( json ); } if( json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_COMMON ) >= 0 ) { extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] = new GLTFMaterialsCommonExtension( json ); } if( json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ) >= 0 ) { extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] = new GLTFMaterialsPbrSpecularGlossinessExtension(); } if ( json.extensionsUsed.indexOf( EXTENSIONS.KHR_TECHNIQUE_WEBGL ) >= 0 ) { extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ] = new GLTFTechniqueWebglExtension( json ); } } console.time( 'GLTF2Loader' ); var parser = new GLTFParser( json, extensions, { path: path || this.path, crossOrigin: this.crossOrigin } ); parser.parse( function ( scene, scenes, cameras, animations ) { console.timeEnd( 'GLTF2Loader' ); var glTF = { "scene": scene, "scenes": scenes, "cameras": cameras, "animations": animations }; callback( glTF ); } ); } }; /* GLTFREGISTRY */ function GLTFRegistry() { var objects = {}; return { get: function ( key ) { return objects[ key ]; }, add: function ( key, object ) { objects[ key ] = object; }, remove: function ( key ) { delete objects[ key ]; }, removeAll: function () { objects = {}; }, update: function ( scene, camera ) { for ( var name in objects ) { var object = objects[ name ]; if ( object.update ) { object.update( scene, camera ); } } } }; } /* GLTFSHADER */ function GLTFShader( targetNode, allNodes ) { var boundUniforms = {}; // bind each uniform to its source node var uniforms = targetNode.material.uniforms; for ( var uniformId in uniforms ) { var uniform = uniforms[ uniformId ]; if ( uniform.semantic ) { var sourceNodeRef = uniform.node; var sourceNode = targetNode; if ( sourceNodeRef ) { sourceNode = allNodes[ sourceNodeRef ]; } boundUniforms[ uniformId ] = { semantic: uniform.semantic, sourceNode: sourceNode, targetNode: targetNode, uniform: uniform }; } } this.boundUniforms = boundUniforms; this._m4 = new THREE.Matrix4(); } // Update - update all the uniform values GLTFShader.prototype.update = function ( scene, camera ) { var boundUniforms = this.boundUniforms; for ( var name in boundUniforms ) { var boundUniform = boundUniforms[ name ]; switch ( boundUniform.semantic ) { case "MODELVIEW": var m4 = boundUniform.uniform.value; m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld ); break; case "MODELVIEWINVERSETRANSPOSE": var m3 = boundUniform.uniform.value; this._m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld ); m3.getNormalMatrix( this._m4 ); break; case "PROJECTION": var m4 = boundUniform.uniform.value; m4.copy( camera.projectionMatrix ); break; case "JOINTMATRIX": var m4v = boundUniform.uniform.value; for ( var mi = 0; mi < m4v.length; mi ++ ) { // So it goes like this: // SkinnedMesh world matrix is already baked into MODELVIEW; // transform joints to local space, // then transform using joint's inverse m4v[ mi ] .getInverse( boundUniform.sourceNode.matrixWorld ) .multiply( boundUniform.targetNode.skeleton.bones[ mi ].matrixWorld ) .multiply( boundUniform.targetNode.skeleton.boneInverses[ mi ] ) .multiply( boundUniform.targetNode.bindMatrix ); } break; default : console.warn( "Unhandled shader semantic: " + boundUniform.semantic ); break; } } }; /*********************************/ /********** EXTENSIONS ***********/ /*********************************/ var EXTENSIONS = { KHR_BINARY_GLTF: 'KHR_binary_glTF', KHR_LIGHTS: 'KHR_lights', KHR_MATERIALS_COMMON: 'KHR_materials_common', KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness', KHR_TECHNIQUE_WEBGL: 'KHR_technique_webgl', }; /** * Lights Extension * * Specification: PENDING */ function GLTFLightsExtension( json ) { this.name = EXTENSIONS.KHR_LIGHTS; this.lights = {}; var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS ] ) || {}; var lights = extension.lights || {}; for ( var lightId in lights ) { var light = lights[ lightId ]; var lightNode; var color = new THREE.Color().fromArray( light.color ); switch ( light.type ) { case 'directional': lightNode = new THREE.DirectionalLight( color ); lightNode.position.set( 0, 0, 1 ); break; case 'point': lightNode = new THREE.PointLight( color ); break; case 'spot': lightNode = new THREE.SpotLight( color ); lightNode.position.set( 0, 0, 1 ); break; case 'ambient': lightNode = new THREE.AmbientLight( color ); break; } if ( lightNode ) { if ( light.constantAttenuation !== undefined ) { lightNode.intensity = light.constantAttenuation; } if ( light.linearAttenuation !== undefined ) { lightNode.distance = 1 / light.linearAttenuation; } if ( light.quadraticAttenuation !== undefined ) { lightNode.decay = light.quadraticAttenuation; } if ( light.fallOffAngle !== undefined ) { lightNode.angle = light.fallOffAngle; } if ( light.fallOffExponent !== undefined ) { console.warn( 'GLTF2Loader: light.fallOffExponent not currently supported.' ); } lightNode.name = light.name || ( 'light_' + lightId ); this.lights[ lightId ] = lightNode; } } } /** * Common Materials Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/Khronos/KHR_materials_common */ function GLTFMaterialsCommonExtension( json ) { this.name = EXTENSIONS.KHR_MATERIALS_COMMON; } GLTFMaterialsCommonExtension.prototype.getMaterialType = function ( material ) { var khrMaterial = material.extensions[ this.name ]; switch ( khrMaterial.type ) { case 'commonBlinn' : case 'commonPhong' : return THREE.MeshPhongMaterial; case 'commonLambert' : return THREE.MeshLambertMaterial; case 'commonConstant' : default : return THREE.MeshBasicMaterial; } }; GLTFMaterialsCommonExtension.prototype.extendParams = function ( materialParams, material, dependencies ) { var khrMaterial = material.extensions[ this.name ]; var keys = []; // TODO: Currently ignored: 'ambientFactor', 'ambientTexture' switch ( khrMaterial.type ) { case 'commonBlinn' : case 'commonPhong' : keys.push( 'diffuseFactor', 'diffuseTexture', 'specularFactor', 'specularTexture', 'shininessFactor' ); break; case 'commonLambert' : keys.push( 'diffuseFactor', 'diffuseTexture' ); break; case 'commonConstant' : default : break; } var materialValues = {}; keys.forEach( function( v ) { if ( khrMaterial[ v ] !== undefined ) materialValues[ v ] = khrMaterial[ v ]; } ); if ( materialValues.diffuseFactor !== undefined ) { materialParams.color = new THREE.Color().fromArray( materialValues.diffuseFactor ); materialParams.opacity = materialValues.diffuseFactor[ 3 ]; } if ( materialValues.diffuseTexture !== undefined ) { materialParams.map = dependencies.textures[ materialValues.diffuseTexture.index ]; } if ( materialValues.specularFactor !== undefined ) { materialParams.specular = new THREE.Color().fromArray( materialValues.specularFactor ); } if ( materialValues.specularTexture !== undefined ) { materialParams.specularMap = dependencies.textures[ materialValues.specularTexture.index ]; } if ( materialValues.shininessFactor !== undefined ) { materialParams.shininess = materialValues.shininessFactor; } }; /* BINARY EXTENSION */ var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF'; var BINARY_EXTENSION_HEADER_MAGIC = 'glTF'; var BINARY_EXTENSION_HEADER_LENGTH = 12; var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 }; function GLTFBinaryExtension( data ) { this.name = EXTENSIONS.KHR_BINARY_GLTF; this.content = null; this.body = null; var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH ); this.header = { magic: convertUint8ArrayToString( new Uint8Array( data.slice( 0, 4 ) ) ), version: headerView.getUint32( 4, true ), length: headerView.getUint32( 8, true ) }; if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) { throw new Error( 'GLTF2Loader: Unsupported glTF-Binary header.' ); } else if ( this.header.version < 2.0 ) { throw new Error( 'GLTF2Loader: Legacy binary file detected. Use GLTFLoader instead.' ); } var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH ); var chunkIndex = 0; while ( chunkIndex < chunkView.byteLength ) { var chunkLength = chunkView.getUint32( chunkIndex, true ); chunkIndex += 4; var chunkType = chunkView.getUint32( chunkIndex, true ); chunkIndex += 4; if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) { var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength ); this.content = convertUint8ArrayToString( contentArray ); } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) { var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex; this.body = data.slice( byteOffset, byteOffset + chunkLength ); } // Clients must ignore chunks with unknown types. chunkIndex += chunkLength; } if ( this.content === null ) { throw new Error( 'GLTF2Loader: JSON content not found.' ); } } /** * WebGL Technique Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/Khronos/KHR_technique_webgl */ function GLTFTechniqueWebglExtension( json ) { this.name = EXTENSIONS.KHR_TECHNIQUE_WEBGL; var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ] ) || {}; this.techniques = extension.techniques || {}; this.programs = extension.programs || {}; this.shaders = extension.shaders || {}; } GLTFTechniqueWebglExtension.prototype.getMaterialType = function () { return DeferredShaderMaterial; }; GLTFTechniqueWebglExtension.prototype.extendParams = function ( materialParams, material, dependencies ) { var extension = material[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ]; var technique = dependencies.techniques[ extension.technique ]; materialParams.uniforms = {}; var program = dependencies.programs[ technique.program ]; if ( program === undefined ) { return; } materialParams.fragmentShader = dependencies.shaders[ program.fragmentShader ]; if ( ! materialParams.fragmentShader ) { throw new Error( 'ERROR: Missing fragment shader definition:', program.fragmentShader ); } var vertexShader = dependencies.shaders[ program.vertexShader ]; if ( ! vertexShader ) { throw new Error( 'ERROR: Missing vertex shader definition:', program.vertexShader ); } // IMPORTANT: FIX VERTEX SHADER ATTRIBUTE DEFINITIONS materialParams.vertexShader = replaceTHREEShaderAttributes( vertexShader, technique ); var uniforms = technique.uniforms; for ( var uniformId in uniforms ) { var pname = uniforms[ uniformId ]; var shaderParam = technique.parameters[ pname ]; var ptype = shaderParam.type; if ( WEBGL_TYPE[ ptype ] ) { var pcount = shaderParam.count; var value; if ( material.values !== undefined ) value = material.values[ pname ]; var uvalue = new WEBGL_TYPE[ ptype ](); var usemantic = shaderParam.semantic; var unode = shaderParam.node; switch ( ptype ) { case WEBGL_CONSTANTS.FLOAT: uvalue = shaderParam.value; if ( pname === 'transparency' ) { materialParams.transparent = true; } if ( value !== undefined ) { uvalue = value; } break; case WEBGL_CONSTANTS.FLOAT_VEC2: case WEBGL_CONSTANTS.FLOAT_VEC3: case WEBGL_CONSTANTS.FLOAT_VEC4: case WEBGL_CONSTANTS.FLOAT_MAT3: if ( shaderParam && shaderParam.value ) { uvalue.fromArray( shaderParam.value ); } if ( value ) { uvalue.fromArray( value ); } break; case WEBGL_CONSTANTS.FLOAT_MAT2: // what to do? console.warn( 'FLOAT_MAT2 is not a supported uniform type' ); break; case WEBGL_CONSTANTS.FLOAT_MAT4: if ( pcount ) { uvalue = new Array( pcount ); for ( var mi = 0; mi < pcount; mi ++ ) { uvalue[ mi ] = new WEBGL_TYPE[ ptype ](); } if ( shaderParam && shaderParam.value ) { var m4v = shaderParam.value; uvalue.fromArray( m4v ); } if ( value ) { uvalue.fromArray( value ); } } else { if ( shaderParam && shaderParam.value ) { var m4 = shaderParam.value; uvalue.fromArray( m4 ); } if ( value ) { uvalue.fromArray( value ); } } break; case WEBGL_CONSTANTS.SAMPLER_2D: if ( value !== undefined ) { uvalue = dependencies.textures[ value ]; } else if ( shaderParam.value !== undefined ) { uvalue = dependencies.textures[ shaderParam.value ]; } else { uvalue = null; } break; } materialParams.uniforms[ uniformId ] = { value: uvalue, semantic: usemantic, node: unode }; } else { throw new Error( 'Unknown shader uniform param type: ' + ptype ); } } var states = technique.states || {}; var enables = states.enable || []; var functions = states.functions || {}; var enableCullFace = false; var enableDepthTest = false; var enableBlend = false; for ( var i = 0, il = enables.length; i < il; i ++ ) { var enable = enables[ i ]; switch ( STATES_ENABLES[ enable ] ) { case 'CULL_FACE': enableCullFace = true; break; case 'DEPTH_TEST': enableDepthTest = true; break; case 'BLEND': enableBlend = true; break; // TODO: implement case 'SCISSOR_TEST': case 'POLYGON_OFFSET_FILL': case 'SAMPLE_ALPHA_TO_COVERAGE': break; default: throw new Error( "Unknown technique.states.enable: " + enable ); } } if ( enableCullFace ) { materialParams.side = functions.cullFace !== undefined ? WEBGL_SIDES[ functions.cullFace ] : THREE.FrontSide; } else { materialParams.side = THREE.DoubleSide; } materialParams.depthTest = enableDepthTest; materialParams.depthFunc = functions.depthFunc !== undefined ? WEBGL_DEPTH_FUNCS[ functions.depthFunc ] : THREE.LessDepth; materialParams.depthWrite = functions.depthMask !== undefined ? functions.depthMask[ 0 ] : true; materialParams.blending = enableBlend ? THREE.CustomBlending : THREE.NoBlending; materialParams.transparent = enableBlend; var blendEquationSeparate = functions.blendEquationSeparate; if ( blendEquationSeparate !== undefined ) { materialParams.blendEquation = WEBGL_BLEND_EQUATIONS[ blendEquationSeparate[ 0 ] ]; materialParams.blendEquationAlpha = WEBGL_BLEND_EQUATIONS[ blendEquationSeparate[ 1 ] ]; } else { materialParams.blendEquation = THREE.AddEquation; materialParams.blendEquationAlpha = THREE.AddEquation; } var blendFuncSeparate = functions.blendFuncSeparate; if ( blendFuncSeparate !== undefined ) { materialParams.blendSrc = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 0 ] ]; materialParams.blendDst = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 1 ] ]; materialParams.blendSrcAlpha = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 2 ] ]; materialParams.blendDstAlpha = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 3 ] ]; } else { materialParams.blendSrc = THREE.OneFactor; materialParams.blendDst = THREE.ZeroFactor; materialParams.blendSrcAlpha = THREE.OneFactor; materialParams.blendDstAlpha = THREE.ZeroFactor; } }; /** * Specular-Glossiness Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/Khronos/KHR_materials_pbrSpecularGlossiness */ function GLTFMaterialsPbrSpecularGlossinessExtension() { return { name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS, getMaterialType: function () { return THREE.ShaderMaterial; }, extendParams: function ( params, material, dependencies ) { // specification // https://github.com/sbtron/glTF/tree/KHRpbrSpecGloss/extensions/Khronos/KHR_materials_pbrSpecularGlossiness var pbrSpecularGlossiness = material.extensions[ this.name ]; var shader = THREE.ShaderLib[ 'standard' ]; var uniforms = THREE.UniformsUtils.clone( shader.uniforms ); var specularMapParsFragmentChunk = [ '#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif' ].join( '\n' ); var glossinessMapParsFragmentChunk = [ '#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif' ].join( '\n' ); var specularMapFragmentChunk = [ 'vec3 specularFactor = specular;', '#ifdef USE_SPECULARMAP', ' vec4 texelSpecular = texture2D( specularMap, vUv );', ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture', ' specularFactor *= texelSpecular.rgb;', '#endif' ].join( '\n' ); var glossinessMapFragmentChunk = [ 'float glossinessFactor = glossiness;', '#ifdef USE_GLOSSINESSMAP', ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );', ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture', ' glossinessFactor *= texelGlossiness.a;', '#endif' ].join( '\n' ); var lightPhysicalFragmentChunk = [ 'PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb;', 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );', 'material.specularColor = specularFactor.rgb;', ].join( '\n' ); var fragmentShader = shader.fragmentShader .replace( '#include <specularmap_fragment>', '' ) .replace( 'uniform float roughness;', 'uniform vec3 specular;' ) .replace( 'uniform float metalness;', 'uniform float glossiness;' ) .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk ) .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk ) .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk ) .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk ) .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk ); delete uniforms.roughness; delete uniforms.metalness; delete uniforms.roughnessMap; delete uniforms.metalnessMap; uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) }; uniforms.glossiness = { value: 0.5 }; uniforms.specularMap = { value: null }; uniforms.glossinessMap = { value: null }; params.vertexShader = shader.vertexShader; params.fragmentShader = fragmentShader; params.uniforms = uniforms; params.defines = { 'STANDARD': '' }; params.color = new THREE.Color( 1.0, 1.0, 1.0 ); params.opacity = 1.0; if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) { var array = pbrSpecularGlossiness.diffuseFactor; params.color.fromArray( array ); params.opacity = array[ 3 ]; } if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) { params.map = dependencies.textures[ pbrSpecularGlossiness.diffuseTexture.index ]; } params.emissive = new THREE.Color( 0.0, 0.0, 0.0 ); params.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0; params.specular = new THREE.Color( 1.0, 1.0, 1.0 ); if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) { params.specular.fromArray( pbrSpecularGlossiness.specularFactor ); } if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) { params.glossinessMap = dependencies.textures[ pbrSpecularGlossiness.specularGlossinessTexture.index ]; params.specularMap = dependencies.textures[ pbrSpecularGlossiness.specularGlossinessTexture.index ]; } }, createMaterial: function ( params ) { // setup material properties based on MeshStandardMaterial for Specular-Glossiness var material = new THREE.ShaderMaterial( { defines: params.defines, vertexShader: params.vertexShader, fragmentShader: params.fragmentShader, uniforms: params.uniforms, fog: true, lights: true, opacity: params.opacity, transparent: params.transparent } ); material.color = params.color; material.map = params.map === undefined ? null : params.map; material.lightMap = null; material.lightMapIntensity = 1.0; material.aoMap = params.aoMap === undefined ? null : params.aoMap; material.aoMapIntensity = 1.0; material.emissive = params.emissive; material.emissiveIntensity = 1.0; material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap; material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap; material.bumpScale = 1; material.normalMap = params.normalMap === undefined ? null : params.normalMap; material.normalScale = new THREE.Vector2( 1, 1 ); material.displacementMap = null; material.displacementScale = 1; material.displacementBias = 0; material.specularMap = params.specularMap === undefined ? null : params.specularMap; material.specular = params.specular; material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap; material.glossiness = params.glossiness; material.alphaMap = null; material.envMap = params.envMap === undefined ? null : params.envMap; material.envMapIntensity = 1.0; material.refractionRatio = 0.98; material.extensions.derivatives = true; return material; }, // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer. refreshUniforms: function ( renderer, scene, camera, geometry, material, group ) { var uniforms = material.uniforms; var defines = material.defines; uniforms.opacity.value = material.opacity; uniforms.diffuse.value.copy( material.color ); uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); uniforms.map.value = material.map; uniforms.specularMap.value = material.specularMap; uniforms.alphaMap.value = material.alphaMap; uniforms.lightMap.value = material.lightMap; uniforms.lightMapIntensity.value = material.lightMapIntensity; uniforms.aoMap.value = material.aoMap; uniforms.aoMapIntensity.value = material.aoMapIntensity; // uv repeat and offset setting priorities // 1. color map // 2. specular map // 3. normal map // 4. bump map // 5. alpha map // 6. emissive map var uvScaleMap; if ( material.map ) { uvScaleMap = material.map; } else if ( material.specularMap ) { uvScaleMap = material.specularMap; } else if ( material.displacementMap ) { uvScaleMap = material.displacementMap; } else if ( material.normalMap ) { uvScaleMap = material.normalMap; } else if ( material.bumpMap ) { uvScaleMap = material.bumpMap; } else if ( material.glossinessMap ) { uvScaleMap = material.glossinessMap; } else if ( material.alphaMap ) { uvScaleMap = material.alphaMap; } else if ( material.emissiveMap ) { uvScaleMap = material.emissiveMap; } if ( uvScaleMap !== undefined ) { // backwards compatibility if ( uvScaleMap.isWebGLRenderTarget ) { uvScaleMap = uvScaleMap.texture; } var offset = uvScaleMap.offset; var repeat = uvScaleMap.repeat; uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y ); } uniforms.envMap.value = material.envMap; uniforms.envMapIntensity.value = material.envMapIntensity; uniforms.flipEnvMap.value = ( material.envMap && material.envMap.isCubeTexture ) ? -1 : 1; uniforms.refractionRatio.value = material.refractionRatio; uniforms.specular.value.copy( material.specular ); uniforms.glossiness.value = material.glossiness; uniforms.glossinessMap.value = material.glossinessMap; uniforms.emissiveMap.value = material.emissiveMap; uniforms.bumpMap.value = material.bumpMap; uniforms.normalMap.value = material.normalMap; uniforms.displacementMap.value = material.displacementMap; uniforms.displacementScale.value = material.displacementScale; uniforms.displacementBias.value = material.displacementBias; if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) { defines.USE_GLOSSINESSMAP = ''; // set USE_ROUGHNESSMAP to enable vUv defines.USE_ROUGHNESSMAP = '' } if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) { delete defines.USE_GLOSSINESSMAP; delete defines.USE_ROUGHNESSMAP; } } }; } /*********************************/ /********** INTERNALS ************/ /*********************************/ /* CONSTANTS */ var WEBGL_CONSTANTS = { FLOAT: 5126, //FLOAT_MAT2: 35674, FLOAT_MAT3: 35675, FLOAT_MAT4: 35676, FLOAT_VEC2: 35664, FLOAT_VEC3: 35665, FLOAT_VEC4: 35666, LINEAR: 9729, REPEAT: 10497, SAMPLER_2D: 35678, TRIANGLES: 4, LINES: 1, UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, VERTEX_SHADER: 35633, FRAGMENT_SHADER: 35632 }; var WEBGL_TYPE = { 5126: Number, //35674: THREE.Matrix2, 35675: THREE.Matrix3, 35676: THREE.Matrix4, 35664: THREE.Vector2, 35665: THREE.Vector3, 35666: THREE.Vector4, 35678: THREE.Texture }; var WEBGL_COMPONENT_TYPES = { 5120: Int8Array, 5121: Uint8Array, 5122: Int16Array, 5123: Uint16Array, 5125: Uint32Array, 5126: Float32Array }; var WEBGL_FILTERS = { 9728: THREE.NearestFilter, 9729: THREE.LinearFilter, 9984: THREE.NearestMipMapNearestFilter, 9985: THREE.LinearMipMapNearestFilter, 9986: THREE.NearestMipMapLinearFilter, 9987: THREE.LinearMipMapLinearFilter }; var WEBGL_WRAPPINGS = { 33071: THREE.ClampToEdgeWrapping, 33648: THREE.MirroredRepeatWrapping, 10497: THREE.RepeatWrapping }; var WEBGL_TEXTURE_FORMATS = { 6406: THREE.AlphaFormat, 6407: THREE.RGBFormat, 6408: THREE.RGBAFormat, 6409: THREE.LuminanceFormat, 6410: THREE.LuminanceAlphaFormat }; var WEBGL_TEXTURE_DATATYPES = { 5121: THREE.UnsignedByteType, 32819: THREE.UnsignedShort4444Type, 32820: THREE.UnsignedShort5551Type, 33635: THREE.UnsignedShort565Type }; var WEBGL_SIDES = { 1028: THREE.BackSide, // Culling front 1029: THREE.FrontSide // Culling back //1032: THREE.NoSide // Culling front and back, what to do? }; var WEBGL_DEPTH_FUNCS = { 512: THREE.NeverDepth, 513: THREE.LessDepth, 514: THREE.EqualDepth, 515: THREE.LessEqualDepth, 516: THREE.GreaterEqualDepth, 517: THREE.NotEqualDepth, 518: THREE.GreaterEqualDepth, 519: THREE.AlwaysDepth }; var WEBGL_BLEND_EQUATIONS = { 32774: THREE.AddEquation, 32778: THREE.SubtractEquation, 32779: THREE.ReverseSubtractEquation }; var WEBGL_BLEND_FUNCS = { 0: THREE.ZeroFactor, 1: THREE.OneFactor, 768: THREE.SrcColorFactor, 769: THREE.OneMinusSrcColorFactor, 770: THREE.SrcAlphaFactor, 771: THREE.OneMinusSrcAlphaFactor, 772: THREE.DstAlphaFactor, 773: THREE.OneMinusDstAlphaFactor, 774: THREE.DstColorFactor, 775: THREE.OneMinusDstColorFactor, 776: THREE.SrcAlphaSaturateFactor // The followings are not supported by Three.js yet //32769: CONSTANT_COLOR, //32770: ONE_MINUS_CONSTANT_COLOR, //32771: CONSTANT_ALPHA, //32772: ONE_MINUS_CONSTANT_COLOR }; var WEBGL_TYPE_SIZES = { 'SCALAR': 1, 'VEC2': 2, 'VEC3': 3, 'VEC4': 4, 'MAT2': 4, 'MAT3': 9, 'MAT4': 16 }; var PATH_PROPERTIES = { scale: 'scale', translation: 'position', rotation: 'quaternion', weights: 'morphTargetInfluences' }; var INTERPOLATION = { LINEAR: THREE.InterpolateLinear, STEP: THREE.InterpolateDiscrete }; var STATES_ENABLES = { 2884: 'CULL_FACE', 2929: 'DEPTH_TEST', 3042: 'BLEND', 3089: 'SCISSOR_TEST', 32823: 'POLYGON_OFFSET_FILL', 32926: 'SAMPLE_ALPHA_TO_COVERAGE' }; var ALPHA_MODES = { OPAQUE: 'OPAQUE', MASK: 'MASK', BLEND: 'BLEND' }; /* UTILITY FUNCTIONS */ function _each( object, callback, thisObj ) { if ( !object ) { return Promise.resolve(); } var results; var fns = []; if ( Object.prototype.toString.call( object ) === '[object Array]' ) { results = []; var length = object.length; for ( var idx = 0; idx < length; idx ++ ) { var value = callback.call( thisObj || this, object[ idx ], idx ); if ( value ) { fns.push( value ); if ( value instanceof Promise ) { value.then( function( key, value ) { results[ key ] = value; }.bind( this, idx )); } else { results[ idx ] = value; } } } } else { results = {}; for ( var key in object ) { if ( object.hasOwnProperty( key ) ) { var value = callback.call( thisObj || this, object[ key ], key ); if ( value ) { fns.push( value ); if ( value instanceof Promise ) { value.then( function( key, value ) { results[ key ] = value; }.bind( this, key )); } else { results[ key ] = value; } } } } } return Promise.all( fns ).then( function() { return results; }); } function resolveURL( url, path ) { // Invalid URL if ( typeof url !== 'string' || url === '' ) return ''; // Absolute URL http://,https://,// if ( /^(https?:)?\/\//i.test( url ) ) { return url; } // Data URI if ( /^data:.*,.*$/i.test( url ) ) { return url; } // Blob URL if ( /^blob:.*$/i.test( url ) ) { return url; } // Relative URL return ( path || '' ) + url; } function convertUint8ArrayToString( array ) { if ( window.TextDecoder !== undefined ) { return new TextDecoder().decode( array ); } // Avoid the String.fromCharCode.apply(null, array) shortcut, which // throws a "maximum call stack size exceeded" error for large arrays. var s = ''; for ( var i = 0, il = array.length; i < il; i ++ ) { s += String.fromCharCode( array[ i ] ); } return s; } // Three.js seems too dependent on attribute names so globally // replace those in the shader code function replaceTHREEShaderAttributes( shaderText, technique ) { // Expected technique attributes var attributes = {}; for ( var attributeId in technique.attributes ) { var pname = technique.attributes[ attributeId ]; var param = technique.parameters[ pname ]; var atype = param.type; var semantic = param.semantic; attributes[ attributeId ] = { type: atype, semantic: semantic }; } // Figure out which attributes to change in technique var shaderParams = technique.parameters; var shaderAttributes = technique.attributes; var params = {}; for ( var attributeId in attributes ) { var pname = shaderAttributes[ attributeId ]; var shaderParam = shaderParams[ pname ]; var semantic = shaderParam.semantic; if ( semantic ) { params[ attributeId ] = shaderParam; } } for ( var pname in params ) { var param = params[ pname ]; var semantic = param.semantic; var regEx = new RegExp( "\\b" + pname + "\\b", "g" ); switch ( semantic ) { case 'POSITION': shaderText = shaderText.replace( regEx, 'position' ); break; case 'NORMAL': shaderText = shaderText.replace( regEx, 'normal' ); break; case 'TEXCOORD_0': case 'TEXCOORD0': case 'TEXCOORD': shaderText = shaderText.replace( regEx, 'uv' ); break; case 'TEXCOORD_1': shaderText = shaderText.replace( regEx, 'uv2' ); break; case 'COLOR_0': case 'COLOR0': case 'COLOR': shaderText = shaderText.replace( regEx, 'color' ); break; case 'WEIGHTS_0': case 'WEIGHT': // WEIGHT semantic deprecated. shaderText = shaderText.replace( regEx, 'skinWeight' ); break; case 'JOINTS_0': case 'JOINT': // JOINT semantic deprecated. shaderText = shaderText.replace( regEx, 'skinIndex' ); break; } } return shaderText; } function createDefaultMaterial() { return new THREE.MeshPhongMaterial( { color: 0x00000, emissive: 0x888888, specular: 0x000000, shininess: 0, transparent: false, depthTest: true, side: THREE.FrontSide } ); } // Deferred constructor for RawShaderMaterial types function DeferredShaderMaterial( params ) { this.isDeferredShaderMaterial = true; this.params = params; } DeferredShaderMaterial.prototype.create = function () { var uniforms = THREE.UniformsUtils.clone( this.params.uniforms ); for ( var uniformId in this.params.uniforms ) { var originalUniform = this.params.uniforms[ uniformId ]; if ( originalUniform.value instanceof THREE.Texture ) { uniforms[ uniformId ].value = originalUniform.value; uniforms[ uniformId ].value.needsUpdate = true; } uniforms[ uniformId ].semantic = originalUniform.semantic; uniforms[ uniformId ].node = originalUniform.node; } this.params.uniforms = uniforms; return new THREE.RawShaderMaterial( this.params ); }; /* GLTF PARSER */ function GLTFParser( json, extensions, options ) { this.json = json || {}; this.extensions = extensions || {}; this.options = options || {}; // loader object cache this.cache = new GLTFRegistry(); } GLTFParser.prototype._withDependencies = function ( dependencies ) { var _dependencies = {}; for ( var i = 0; i < dependencies.length; i ++ ) { var dependency = dependencies[ i ]; var fnName = "load" + dependency.charAt( 0 ).toUpperCase() + dependency.slice( 1 ); var cached = this.cache.get( dependency ); if ( cached !== undefined ) { _dependencies[ dependency ] = cached; } else if ( this[ fnName ] ) { var fn = this[ fnName ](); this.cache.add( dependency, fn ); _dependencies[ dependency ] = fn; } } return _each( _dependencies, function ( dependency ) { return dependency; } ); }; GLTFParser.prototype.parse = function ( callback ) { var json = this.json; // Clear the loader cache this.cache.removeAll(); // Fire the callback on complete this._withDependencies( [ "scenes", "cameras", "animations" ] ).then( function ( dependencies ) { var scenes = []; for ( var name in dependencies.scenes ) { scenes.push( dependencies.scenes[ name ] ); } var scene = json.scene !== undefined ? dependencies.scenes[ json.scene ] : scenes[ 0 ]; var cameras = []; for ( var name in dependencies.cameras ) { var camera = dependencies.cameras[ name ]; cameras.push( camera ); } var animations = []; for ( var name in dependencies.animations ) { animations.push( dependencies.animations[ name ] ); } callback( scene, scenes, cameras, animations ); } ); }; GLTFParser.prototype.loadShaders = function () { var json = this.json; var options = this.options; var extensions = this.extensions; return this._withDependencies( [ "bufferViews" ] ).then( function ( dependencies ) { var shaders = extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ] !== undefined ? extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ].shaders : json.shaders; if ( shaders === undefined ) shaders = {}; return _each( shaders, function ( shader ) { if ( shader.bufferView !== undefined ) { var bufferView = dependencies.bufferViews[ shader.bufferView ]; var array = new Uint8Array( bufferView ); return convertUint8ArrayToString( array ); } return new Promise( function ( resolve ) { var loader = new THREE.FileLoader(); loader.setResponseType( 'text' ); loader.load( resolveURL( shader.uri, options.path ), function ( shaderText ) { resolve( shaderText ); } ); } ); } ); } ); }; GLTFParser.prototype.loadBuffers = function () { var json = this.json; var extensions = this.extensions; var options = this.options; return _each( json.buffers, function ( buffer, name ) { if ( buffer.type === 'arraybuffer' || buffer.type === undefined ) { // If present, GLB container is required to be the first buffer. if ( buffer.uri === undefined && name === 0 ) { return extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body; } return new Promise( function ( resolve ) { var loader = new THREE.FileLoader(); loader.setResponseType( 'arraybuffer' ); loader.load( resolveURL( buffer.uri, options.path ), function ( buffer ) { resolve( buffer ); } ); } ); } else { console.warn( 'THREE.GLTF2Loader: ' + buffer.type + ' buffer type is not supported' ); } } ); }; GLTFParser.prototype.loadBufferViews = function () { var json = this.json; return this._withDependencies( [ "buffers" ] ).then( function ( dependencies ) { return _each( json.bufferViews, function ( bufferView ) { var arraybuffer = dependencies.buffers[ bufferView.buffer ]; var byteLength = bufferView.byteLength || 0; var byteOffset = bufferView.byteOffset || 0; return arraybuffer.slice( byteOffset, byteOffset + byteLength ); } ); } ); }; GLTFParser.prototype.loadAccessors = function () { var json = this.json; return this._withDependencies( [ "bufferViews" ] ).then( function ( dependencies ) { return _each( json.accessors, function ( accessor ) { var arraybuffer = dependencies.bufferViews[ accessor.bufferView ]; var itemSize = WEBGL_TYPE_SIZES[ accessor.type ]; var TypedArray = WEBGL_COMPONENT_TYPES[ accessor.componentType ]; // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12. var elementBytes = TypedArray.BYTES_PER_ELEMENT; var itemBytes = elementBytes * itemSize; var byteStride = json.bufferViews[accessor.bufferView].byteStride; var array; // The buffer is not interleaved if the stride is the item size in bytes. if ( byteStride && byteStride !== itemBytes ) { // Use the full buffer if it's interleaved. array = new TypedArray( arraybuffer ); // Integer parameters to IB/IBA are in array elements, not bytes. var ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes ); return new THREE.InterleavedBufferAttribute( ib, itemSize, accessor.byteOffset / elementBytes ); } else { array = new TypedArray( arraybuffer, accessor.byteOffset, accessor.count * itemSize ); return new THREE.BufferAttribute( array, itemSize ); } } ); } ); }; GLTFParser.prototype.loadTextures = function () { var json = this.json; var options = this.options; return this._withDependencies( [ "bufferViews" ] ).then( function ( dependencies ) { return _each( json.textures, function ( texture ) { if ( texture.source !== undefined ) { return new Promise( function ( resolve ) { var source = json.images[ texture.source ]; var sourceUri = source.uri; var urlCreator; if ( source.bufferView !== undefined ) { var bufferView = dependencies.bufferViews[ source.bufferView ]; var blob = new Blob( [ bufferView ], { type: source.mimeType } ); urlCreator = window.URL || window.webkitURL; sourceUri = urlCreator.createObjectURL( blob ); } var textureLoader = THREE.Loader.Handlers.get( sourceUri ); if ( textureLoader === null ) { textureLoader = new THREE.TextureLoader(); } textureLoader.setCrossOrigin( options.crossOrigin ); textureLoader.load( resolveURL( sourceUri, options.path ), function ( _texture ) { if ( urlCreator !== undefined ) { urlCreator.revokeObjectURL( sourceUri ); } _texture.flipY = false; if ( texture.name !== undefined ) _texture.name = texture.name; _texture.format = texture.format !== undefined ? WEBGL_TEXTURE_FORMATS[ texture.format ] : THREE.RGBAFormat; if ( texture.internalFormat !== undefined && _texture.format !== WEBGL_TEXTURE_FORMATS[ texture.internalFormat ] ) { console.warn( 'THREE.GLTF2Loader: Three.js doesn\'t support texture internalFormat which is different from texture format. ' + 'internalFormat will be forced to be the same value as format.' ); } _texture.type = texture.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ texture.type ] : THREE.UnsignedByteType; var samplers = json.samplers || {}; var sampler = samplers[ texture.sampler ] || {}; _texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter; _texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.NearestMipMapLinearFilter; _texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping; _texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping; resolve( _texture ); }, undefined, function () { resolve(); } ); } ); } } ); } ); }; GLTFParser.prototype.loadMaterials = function () { var json = this.json; var extensions = this.extensions; return this._withDependencies( [ 'shaders', 'textures' ] ).then( function ( dependencies ) { return _each( json.materials, function ( material ) { var materialType; var materialParams = {}; var materialExtensions = material.extensions || {}; if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) { materialType = extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].getMaterialType( material ); extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].extendParams( materialParams, material, dependencies ); } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) { materialType = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].getMaterialType( material ); extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].extendParams( materialParams, material, dependencies ); } else if ( materialExtensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ] ) { materialType = extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ].getMaterialType( material ); extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ].extendParams( materialParams, material, dependencies ); } else if ( material.pbrMetallicRoughness !== undefined ) { // Specification: // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material materialType = THREE.MeshStandardMaterial; var metallicRoughness = material.pbrMetallicRoughness; materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 ); materialParams.opacity = 1.0; if ( Array.isArray( metallicRoughness.baseColorFactor ) ) { var array = metallicRoughness.baseColorFactor; materialParams.color.fromArray( array ); materialParams.opacity = array[ 3 ]; } if ( metallicRoughness.baseColorTexture !== undefined ) { materialParams.map = dependencies.textures[ metallicRoughness.baseColorTexture.index ]; } materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0; materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0; if ( metallicRoughness.metallicRoughnessTexture !== undefined ) { var textureIndex = metallicRoughness.metallicRoughnessTexture.index; materialParams.metalnessMap = dependencies.textures[ textureIndex ]; materialParams.roughnessMap = dependencies.textures[ textureIndex ]; } } else { materialType = THREE.MeshPhongMaterial; } if ( material.doubleSided === true ) { materialParams.side = THREE.DoubleSide; } var alphaMode = material.alphaMode || ALPHA_MODES.OPAQUE; if ( alphaMode !== ALPHA_MODES.OPAQUE ) { materialParams.transparent = true; } else { materialParams.transparent = false; } if ( material.normalTexture !== undefined ) { materialParams.normalMap = dependencies.textures[ material.normalTexture.index ]; } if ( material.occlusionTexture !== undefined ) { materialParams.aoMap = dependencies.textures[ material.occlusionTexture.index ]; } if ( material.emissiveFactor !== undefined ) { if ( materialType === THREE.MeshBasicMaterial ) { materialParams.color = new THREE.Color().fromArray( material.emissiveFactor ); } else { materialParams.emissive = new THREE.Color().fromArray( material.emissiveFactor ); } } if ( material.emissiveTexture !== undefined ) { if ( materialType === THREE.MeshBasicMaterial ) { materialParams.map = dependencies.textures[ material.emissiveTexture.index ]; } else { materialParams.emissiveMap = dependencies.textures[ material.emissiveTexture.index ]; } } var _material; if ( materialType === THREE.ShaderMaterial ) { _material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams ); } else { _material = new materialType( materialParams ); } if ( material.name !== undefined ) _material.name = material.name; return _material; } ); } ); }; GLTFParser.prototype.loadMeshes = function () { var json = this.json; return this._withDependencies( [ "accessors", "materials" ] ).then( function ( dependencies ) { return _each( json.meshes, function ( mesh ) { var group = new THREE.Group(); if ( mesh.name !== undefined ) group.name = mesh.name; if ( mesh.extras ) group.userData = mesh.extras; var primitives = mesh.primitives || []; for ( var name in primitives ) { var primitive = primitives[ name ]; var material = primitive.material !== undefined ? dependencies.materials[ primitive.material ] : createDefaultMaterial(); var geometry; var meshNode; if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === undefined ) { geometry = new THREE.BufferGeometry(); var attributes = primitive.attributes; for ( var attributeId in attributes ) { var attributeEntry = attributes[ attributeId ]; if ( attributeEntry === undefined ) return; var bufferAttribute = dependencies.accessors[ attributeEntry ]; switch ( attributeId ) { case 'POSITION': geometry.addAttribute( 'position', bufferAttribute ); break; case 'NORMAL': geometry.addAttribute( 'normal', bufferAttribute ); break; case 'TEXCOORD_0': case 'TEXCOORD0': case 'TEXCOORD': geometry.addAttribute( 'uv', bufferAttribute ); break; case 'TEXCOORD_1': geometry.addAttribute( 'uv2', bufferAttribute ); break; case 'COLOR_0': case 'COLOR0': case 'COLOR': geometry.addAttribute( 'color', bufferAttribute ); break; case 'WEIGHTS_0': case 'WEIGHT': // WEIGHT semantic deprecated. geometry.addAttribute( 'skinWeight', bufferAttribute ); break; case 'JOINTS_0': case 'JOINT': // JOINT semantic deprecated. geometry.addAttribute( 'skinIndex', bufferAttribute ); break; } } if ( primitive.indices !== undefined ) { geometry.setIndex( dependencies.accessors[ primitive.indices ] ); } if ( material.aoMap !== undefined && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) { console.log( 'GLTF2Loader: Duplicating UVs to support aoMap.' ); geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) ); } meshNode = new THREE.Mesh( geometry, material ); meshNode.castShadow = true; if ( primitive.targets !== undefined ) { var targets = primitive.targets; var morphAttributes = geometry.morphAttributes; morphAttributes.position = []; morphAttributes.normal = []; material.morphTargets = true; for ( var i = 0, il = targets.length; i < il; i ++ ) { var target = targets[ i ]; var attributeName = 'morphTarget' + i; var positionAttribute, normalAttribute; if ( target.POSITION !== undefined ) { // Three.js morph formula is // position // + weight0 * ( morphTarget0 - position ) // + weight1 * ( morphTarget1 - position ) // ... // while the glTF one is // position // + weight0 * morphTarget0 // + weight1 * morphTarget1 // ... // then adding position to morphTarget. // So morphTarget value will depend on mesh's position, then cloning attribute // for the case if attribute is shared among two or more meshes. positionAttribute = dependencies.accessors[ target.POSITION ].clone(); var position = geometry.attributes.position; for ( var j = 0, jl = positionAttribute.array.length; j < jl; j ++ ) { positionAttribute.array[ j ] += position.array[ j ]; } } else { // Copying the original position not to affect the final position. // See the formula above. positionAttribute = geometry.attributes.position.clone(); } if ( target.NORMAL !== undefined ) { material.morphNormals = true; // see target.POSITION's comment normalAttribute = dependencies.accessors[ target.NORMAL ].clone(); var normal = geometry.attributes.normal; for ( var j = 0, jl = normalAttribute.array.length; j < jl; j ++ ) { normalAttribute.array[ j ] += normal.array[ j ]; } } else { normalAttribute = geometry.attributes.normal.clone(); } // TODO: implement if ( target.TANGENT !== undefined ) { } positionAttribute.name = attributeName; normalAttribute.name = attributeName; morphAttributes.position.push( positionAttribute ); morphAttributes.normal.push( normalAttribute ); } meshNode.updateMorphTargets(); if ( mesh.weights !== undefined ) { for ( var i = 0, il = mesh.weights.length; i < il; i ++ ) { meshNode.morphTargetInfluences[ i ] = mesh.weights[ i ]; } } } } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) { geometry = new THREE.BufferGeometry(); var attributes = primitive.attributes; for ( var attributeId in attributes ) { var attributeEntry = attributes[ attributeId ]; if ( ! attributeEntry ) return; var bufferAttribute = dependencies.accessors[ attributeEntry ]; switch ( attributeId ) { case 'POSITION': geometry.addAttribute( 'position', bufferAttribute ); break; case 'COLOR_0': case 'COLOR0': case 'COLOR': geometry.addAttribute( 'color', bufferAttribute ); break; } } if ( primitive.indices !== undefined ) { geometry.setIndex( dependencies.accessors[ primitive.indices ] ); meshNode = new THREE.LineSegments( geometry, material ); } else { meshNode = new THREE.Line( geometry, material ); } } else { throw new Error( "Only triangular and line primitives are supported" ); } if ( geometry.attributes.color !== undefined ) { material.vertexColors = THREE.VertexColors; material.needsUpdate = true; } meshNode.name = ( name === "0" ? group.name : group.name + name ); if ( primitive.extras ) meshNode.userData = primitive.extras; group.add( meshNode ); } return group; } ); } ); }; GLTFParser.prototype.loadCameras = function () { var json = this.json; return _each( json.cameras, function ( camera ) { if ( camera.type == "perspective" && camera.perspective ) { var yfov = camera.perspective.yfov; var aspectRatio = camera.perspective.aspectRatio !== undefined ? camera.perspective.aspectRatio : 1; // According to COLLADA spec... // aspectRatio = xfov / yfov var xfov = yfov * aspectRatio; var _camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspectRatio, camera.perspective.znear || 1, camera.perspective.zfar || 2e6 ); if ( camera.name !== undefined ) _camera.name = camera.name; if ( camera.extras ) _camera.userData = camera.extras; return _camera; } else if ( camera.type == "orthographic" && camera.orthographic ) { var _camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, camera.orthographic.znear, camera.orthographic.zfar ); if ( camera.name !== undefined ) _camera.name = camera.name; if ( camera.extras ) _camera.userData = camera.extras; return _camera; } } ); }; GLTFParser.prototype.loadSkins = function () { var json = this.json; return this._withDependencies( [ "accessors" ] ).then( function ( dependencies ) { return _each( json.skins, function ( skin ) { var bindShapeMatrix = new THREE.Matrix4(); if ( skin.bindShapeMatrix !== undefined ) bindShapeMatrix.fromArray( skin.bindShapeMatrix ); var _skin = { bindShapeMatrix: bindShapeMatrix, joints: skin.joints, inverseBindMatrices: dependencies.accessors[ skin.inverseBindMatrices ] }; return _skin; } ); } ); }; GLTFParser.prototype.loadAnimations = function () { var json = this.json; return this._withDependencies( [ "accessors", "nodes" ] ).then( function ( dependencies ) { return _each( json.animations, function ( animation, animationId ) { var tracks = []; for ( var channelId in animation.channels ) { var channel = animation.channels[ channelId ]; var sampler = animation.samplers[ channel.sampler ]; if ( sampler ) { var target = channel.target; var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated. var input = animation.parameters !== undefined ? animation.parameters[ sampler.input ] : sampler.input; var output = animation.parameters !== undefined ? animation.parameters[ sampler.output ] : sampler.output; var inputAccessor = dependencies.accessors[ input ]; var outputAccessor = dependencies.accessors[ output ]; var node = dependencies.nodes[ name ]; if ( node ) { node.updateMatrix(); node.matrixAutoUpdate = true; var TypedKeyframeTrack; switch ( PATH_PROPERTIES[ target.path ] ) { case PATH_PROPERTIES.weights: TypedKeyframeTrack = THREE.NumberKeyframeTrack; break; case PATH_PROPERTIES.rotation: TypedKeyframeTrack = THREE.QuaternionKeyframeTrack; break; case PATH_PROPERTIES.position: case PATH_PROPERTIES.scale: default: TypedKeyframeTrack = THREE.VectorKeyframeTrack; break; } var targetName = node.name ? node.name : node.uuid; var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear; var targetNames = []; if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) { // node should be THREE.Group here but // PATH_PROPERTIES.weights(morphTargetInfluences) should be // the property of a mesh object under node. // So finding targets here. node.traverse( function ( object ) { if ( object.isMesh === true && object.material.morphTargets === true ) { targetNames.push( object.name ? object.name : object.uuid ); } } ); } else { targetNames.push( targetName ); } // KeyframeTrack.optimize() will modify given 'times' and 'values' // buffers before creating a truncated copy to keep. Because buffers may // be reused by other tracks, make copies here. for ( var i = 0, il = targetNames.length; i < il; i ++ ) { tracks.push( new TypedKeyframeTrack( targetNames[ i ] + '.' + PATH_PROPERTIES[ target.path ], THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ), THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ), interpolation ) ); } } } } var name = animation.name !== undefined ? animation.name : "animation_" + animationId; return new THREE.AnimationClip( name, undefined, tracks ); } ); } ); }; GLTFParser.prototype.loadNodes = function () { var json = this.json; var extensions = this.extensions; var scope = this; var nodes = json.nodes || []; var skins = json.skins || []; // Nothing in the node definition indicates whether it is a Bone or an // Object3D. Use the skins' joint references to mark bones. skins.forEach( function ( skin ) { skin.joints.forEach( function ( id ) { nodes[ id ].isBone = true; } ); } ); return _each( json.nodes, function ( node ) { var matrix = new THREE.Matrix4(); var _node = node.isBone === true ? new THREE.Bone() : new THREE.Object3D(); if ( node.name !== undefined ) { _node.name = THREE.PropertyBinding.sanitizeNodeName( node.name ); } if ( node.extras ) _node.userData = node.extras; if ( node.matrix !== undefined ) { matrix.fromArray( node.matrix ); _node.applyMatrix( matrix ); } else { if ( node.translation !== undefined ) { _node.position.fromArray( node.translation ); } if ( node.rotation !== undefined ) { _node.quaternion.fromArray( node.rotation ); } if ( node.scale !== undefined ) { _node.scale.fromArray( node.scale ); } } return _node; } ).then( function ( __nodes ) { return scope._withDependencies( [ "meshes", "skins", "cameras" ] ).then( function ( dependencies ) { return _each( __nodes, function ( _node, nodeId ) { var node = json.nodes[ nodeId ]; var meshes; if ( node.mesh !== undefined) { meshes = [ node.mesh ]; } else if ( node.meshes !== undefined ) { console.warn( 'GLTF2Loader: Legacy glTF file detected. Nodes may have no more than 1 mesh.' ); meshes = node.meshes; } if ( meshes !== undefined ) { for ( var meshId in meshes ) { var mesh = meshes[ meshId ]; var group = dependencies.meshes[ mesh ]; if ( group === undefined ) { console.warn( 'GLTF2Loader: Couldn\'t find node "' + mesh + '".' ); continue; } for ( var childrenId in group.children ) { var child = group.children[ childrenId ]; // clone Mesh to add to _node var originalMaterial = child.material; var originalGeometry = child.geometry; var originalUserData = child.userData; var originalName = child.name; var material; if ( originalMaterial.isDeferredShaderMaterial ) { originalMaterial = material = originalMaterial.create(); } else { material = originalMaterial; } switch ( child.type ) { case 'LineSegments': child = new THREE.LineSegments( originalGeometry, material ); break; case 'LineLoop': child = new THREE.LineLoop( originalGeometry, material ); break; case 'Line': child = new THREE.Line( originalGeometry, material ); break; default: child = new THREE.Mesh( originalGeometry, material ); } child.castShadow = true; child.userData = originalUserData; child.name = originalName; var skinEntry; if ( node.skin !== undefined ) { skinEntry = dependencies.skins[ node.skin ]; } // Replace Mesh with SkinnedMesh in library if ( skinEntry ) { var geometry = originalGeometry; material = originalMaterial; material.skinning = true; child = new THREE.SkinnedMesh( geometry, material, false ); child.castShadow = true; child.userData = originalUserData; child.name = originalName; var bones = []; var boneInverses = []; for ( var i = 0, l = skinEntry.joints.length; i < l; i ++ ) { var jointId = skinEntry.joints[ i ]; var jointNode = __nodes[ jointId ]; if ( jointNode ) { bones.push( jointNode ); var m = skinEntry.inverseBindMatrices.array; var mat = new THREE.Matrix4().fromArray( m, i * 16 ); boneInverses.push( mat ); } else { console.warn( "WARNING: joint: '" + jointId + "' could not be found" ); } } child.bind( new THREE.Skeleton( bones, boneInverses, false ), skinEntry.bindShapeMatrix ); var buildBoneGraph = function ( parentJson, parentObject, property ) { var children = parentJson[ property ]; if ( children === undefined ) return; for ( var i = 0, il = children.length; i < il; i ++ ) { var nodeId = children[ i ]; var bone = __nodes[ nodeId ]; var boneJson = json.nodes[ nodeId ]; if ( bone !== undefined && bone.isBone === true && boneJson !== undefined ) { parentObject.add( bone ); buildBoneGraph( boneJson, bone, 'children' ); } } }; buildBoneGraph( node, child, 'skeletons' ); } _node.add( child ); } } } if ( node.camera !== undefined ) { var camera = dependencies.cameras[ node.camera ]; _node.add( camera ); } if ( node.extensions && node.extensions[ EXTENSIONS.KHR_LIGHTS ] && node.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) { var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights; _node.add( lights[ node.extensions[ EXTENSIONS.KHR_LIGHTS ].light ] ); } return _node; } ); } ); } ); }; GLTFParser.prototype.loadScenes = function () { var json = this.json; var extensions = this.extensions; // scene node hierachy builder function buildNodeHierachy( nodeId, parentObject, allNodes ) { var _node = allNodes[ nodeId ]; parentObject.add( _node ); var node = json.nodes[ nodeId ]; if ( node.children ) { var children = node.children; for ( var i = 0, l = children.length; i < l; i ++ ) { var child = children[ i ]; buildNodeHierachy( child, _node, allNodes ); } } } return this._withDependencies( [ "nodes" ] ).then( function ( dependencies ) { return _each( json.scenes, function ( scene ) { var _scene = new THREE.Scene(); if ( scene.name !== undefined ) _scene.name = scene.name; if ( scene.extras ) _scene.userData = scene.extras; var nodes = scene.nodes || []; for ( var i = 0, l = nodes.length; i < l; i ++ ) { var nodeId = nodes[ i ]; buildNodeHierachy( nodeId, _scene, dependencies.nodes ); } _scene.traverse( function ( child ) { // Register raw material meshes with GLTF2Loader.Shaders if ( child.material && child.material.isRawShaderMaterial ) { child.gltfShader = new GLTFShader( child, dependencies.nodes ); child.onBeforeRender = function(renderer, scene, camera){ this.gltfShader.update(scene, camera); }; } // for Specular-Glossiness. if ( child.material && child.material.type === 'ShaderMaterial' ) { child.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms; } } ); // Ambient lighting, if present, is always attached to the scene root. if ( scene.extensions && scene.extensions[ EXTENSIONS.KHR_LIGHTS ] && scene.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) { var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights; _scene.add( lights[ scene.extensions[ EXTENSIONS.KHR_LIGHTS ].light ] ); } return _scene; } ); } ); }; return GLTF2Loader; } )();
(function($hn) { var perfData = { insertedNodeCount : 0 }, update = function(id, type, time) { if (!perfData[id]) { perfData[id] = {} } if (arguments.length == 2) { perfData[id] = arguments[1]; } else { perfData[id][type] = (perfData[id][type] ? perfData[id][type] + ',' : '') + time; } }; $hn.perf = { update: update, data: perfData }; //document.body.addEventListener('DOMNodeInserted', updateNodeCount, false); }(window.$hn)); (function($hn) { var primaryServer = $hn.url.stories, backupServer = $hn.url.storiesBackup; var server = primaryServer; var URL = { 'list' : '/news', 'item' : '/item/{id}', 'viewText' : 'http://viewtext.org/api/text?url={url}&format={format}', 'AskHn': 'https://api.thriftdb.com/api.hnsearch.com/items/_search?limit=30&sortby=create_ts+desc&weights[username]=0.1&weights[text]=1&weights[type]=0&weights[domain]=2&weights[title]=1.2&weights[url]=1&boosts[fields][points]=0.07&boosts[functions][pow(2,div(div(ms(create_ts,NOW),3600000),72))]=200&q="Ask+hn"&filter[fields][type]=submission&facet[queries][]=username:Ask&facet[queries][]=username:hn', 'ShowHn': 'https://api.thriftdb.com/api.hnsearch.com/items/_search?limit=30&sortby=create_ts+desc&weights[username]=0.1&weights[text]=1&weights[type]=0&weights[domain]=2&weights[title]=1.2&weights[url]=1&boosts[fields][points]=0.07&boosts[functions][pow(2,div(div(ms(create_ts,NOW),3600000),72))]=200&q="show+hn"&filter[fields][type]=submission&facet[queries][]=username:show&facet[queries][]=username:hn', 'top10ByDate': 'https://api.thriftdb.com/api.hnsearch.com/items/_search?filter[fields][type][]=submission&sortby=points+desc&filter[fields][create_ts][]=[{startDate}+TO+{endDate}]&limit=10' }; URL.viewText = $hn.url.readability; var getUrl = function(type) { if (type=='list' || type=='item') { return server + URL[type] } else if (type == 'AskHn' || type == 'ShowHn') { return URL[type] } else if (type == 'todayTop10' || type == 'yesterdayTop10' || type == 'weekTop10') { var startDate = new Date(), endDate; startDate.setHours(0); startDate.setMinutes(0); startDate.setSeconds(0); endDate = new Date(startDate); if (type == 'todayTop10') { endDate.setHours(24); } else if (type == 'yesterdayTop10') { startDate.setHours(-24); } else if (type == 'weekTop10') { startDate.setDate(startDate.getDate()-7); } return $hn.t(URL.top10ByDate, { 'startDate' : startDate.toISOString(), 'endDate' : endDate.toISOString() }) } }; var lastServerChangeTime; var changeServer = function(url) { console.log('change server', lastServerChangeTime, server) if (!lastServerChangeTime || lastServerChangeTime + (1000*60*20) < +new Date()) { lastServerChangeTime = +new Date(); server = (server == primaryServer ? backupServer : primaryServer); console.log(lastServerChangeTime, server) return true; } return false; }; var localData; var resetCache = function() { localData = { articles : {} }; }; resetCache(); var updateLocalData = function() { $.each(localData.list, function(index, item) { item.visitedComments = ''; item.visitedArticle = ''; if (visitedData[item.id]) { if (visitedData[item.id].a) { item.visitedArticle = 'visited'; } if (visitedData[item.id].c) { item.visitedComments = 'visited'; } } if (item.type=='job') { item.points = 'JOB'; } if (!item.user) { item.user = ''; } item.title = item.title.replace('<', '&lt;'); localData.articles[item.id] = item; }); }; var visitedData = { // id : { // 'c' : +new Date(), // 'a' : +new Date(), // }, // version: 2 }; var readLocalData = function() { console.log('readLocalData()'); var t0ls = +new Date(), localVisitedData = window.store.get('visited'), localStorageList = window.store.get('list'); $hn.perf.update('localstorage', 'read', +new Date() - t0ls); if (localVisitedData) { $.extend(true, visitedData, localVisitedData); if (!visitedData.version) { $.each(visitedData, function(i, item) { if (item.a) { item.a = item.d } if (item.c) { item.c = item.d } delete item.d; }); } visitedData.version = 2; $.each(visitedData, function(index, item) { if (index != 'version') { if (item.a < +new Date() - (1000 * 60 * 60 * 24 * 7)) { delete item.a; } if (item.c < +new Date() - (1000 * 60 * 60 * 24 * 7)) { delete item.c; } if (!item.a && !item.c) { delete visitedData[index]; } } }); saveVisitedData(); } if (localStorageList) { if (+new Date() - localStorageList.timestamp < 1000*60*5) { localData.list = localStorageList.data; updateLocalData(); } } }; var saveVisitedId = null; var saveVisitedDelayed = function() { console.log('saveVisitedDelayed()'); saveVisitedId = null; window.store.set('visited', visitedData); }; var saveVisitedData = function() { console.log('saveVisitedData()'); if (saveVisitedId) { window.clearTimeout(saveVisitedId); saveVisitedId = null; } saveVisitedId = window.setTimeout(saveVisitedDelayed, 1000); }; var addVisited = function(id, type) { if (!visitedData[id]) { visitedData[id] = {}; } visitedData[id][type] = +new Date(); saveVisitedData(); }; // window.setTimeout(readLocalData, 1); readLocalData(); var getLocalData = function() { return localData; }; var updateList = function(callback) { callback = callback || function(){}; var onSuccess = function(data) { resetCache(); $hn.perf.update('list', 'fetch', +new Date() - t0Ajax); localData.list = data; updateLocalData(); callback.apply(callback, [localData.list]); window.store.set('list', {data: localData.list, timestamp: +new Date()}); }, t0Ajax = +new Date(); $hn.ajax({ url: getUrl('list') + '?t=' + +new Date(), success: onSuccess, error: function(xhr, status) { console.log( typeof status, status, xhr); if ("ajaxError|abort".indexOf(status) > -1 && changeServer()) { updateList(callback); } } }); }; var callbackLoop = 0; var updateArticleContent = function(id, callback) { callback = callback || function(){}; if (!localData.articles[id] && callbackLoop++ < 3) { // alert('updateArticleContent(): Something went wrong! Reload??? ' + id); window.setTimeout(function(){ updateArticleContent(id, callback); }, 400); } var fallbackContent = function() { return $hn.t('<p>Oops... Something went terribly wrong... </p><p>Follow this link <a href="{url}">{url}</a> to view the article</p><br><br>', {url: localData.articles[id].url}); }, onSuccess = function(data) { $hn.perf.update(id, 'article-fetch', +new Date() - t0Ajax); var a = $('<div></div>').html(data.content || fallbackContent()); $('*', a).each(function(index, node) { if (node.className) { node.className = ''; } }); localData.articles[id].article = a.html(); callback.apply(callback, [localData.articles[id]]); }, onError = function(data) { localData.articles[id].articlecontent = fallbackContent(); callback.apply(callback, [localData.articles[id]]); }, t0Ajax = +new Date(); $hn.ajax({ url: $hn.t(URL.viewText, {url: encodeURIComponent(localData.articles[id].url), format:'jsonp'}), dataType: 'jsonp', success: onSuccess, error: onError }); }; var updateArticleComments = function(id, callback) { callback = callback || function(){}; var getLastCommentId = function(comments) { var lastCommentId; $.each(comments, function(index, item) { var tempId; if (!lastCommentId || item.id > lastCommentId) { lastCommentId = item.id; } if (item.comments && (tempId = getLastCommentId(item.comments)) && tempId > lastCommentId) { lastCommentId = tempId; } }); return lastCommentId; }; var onSuccess = function(data) { $hn.perf.update(id, 'comments-fetch', +new Date() - t0Ajax); var article = localData.articles[id]; //if (!article) { article = localData.articles[id] = data; //} //else { // article.comments = data.comments; //} if (article.url.indexOf('item')==0) { delete article.url; } if (visitedData[id] && visitedData[id].lastReadComment) { article.lastReadComment = visitedData[id].lastReadComment; } article.commentsFetchTime = +new Date(); callback.apply(callback, [article]); window.setTimeout(function() { visitedData[id].lastReadComment = getLastCommentId(article.comments); saveVisitedData(); }, 300); }, t0Ajax = +new Date(); $hn.ajax({ url: $hn.t(getUrl('item'), {id: id}), dataType: 'jsonp', success: onSuccess, error: function(xhr, status) { console.log('ajax primary server failed, try backup server: ', status, xhr); if ('error|abort'.indexOf(status) > -1 && changeServer()) { updateArticleComments(id, callback); } } }); }; var getArticles = function(callback, reload) { reload = reload || false; callback = callback || function(){}; if (!reload && localData.list) { return callback.apply(callback, [localData.list]); } updateList(callback); }; var getArticleMeta = function(id, callback) { callback = callback || function(){}; var article = localData.articles[id]; if (article) { return callback.apply(callback, [article]); } var onSuccess = function(data) { $hn.perf.update(id, 'comments-fetch', +new Date() - t0Ajax); data.commentsFetchTime = +new Date(); if (data.url.indexOf('item')==0) { delete data.url; } localData.articles[id] = data; callback.apply(callback, [data]); }, t0Ajax = +new Date(); $hn.ajax({ url: $hn.t(getUrl('item'), {id: id}), dataType: 'jsonp', success: onSuccess, error: function(xhr, status) { console.log('ajax primary server failed, try backup server: ', status, xhr); if ('error|abort'.indexOf(status) > -1 && changeServer()) { getArticleMeta(id, callback); } } }); }; var getArticleContent = function(id, callback, reload) { reload = reload || false; callback = callback || function(){}; addVisited(id, 'a'); var article = localData.articles[id]; if (!reload && article && article.content) { return callback.apply(callback, [article]); } updateArticleContent(id, callback); }; var getArticleComments = function(id, callback, reload) { reload = reload || false; callback = callback || function(){}; addVisited(id, 'c'); var article = localData.articles[id]; if (!reload && article && article.comments && article.commentsFetchTime < (+new Date() + (1000 * 60 * 5))) { return callback.apply(callback, [article]); } updateArticleComments(id, callback); }; var reformatData = function(data) { var t0Reformat = +new Date(), tempData = []; $.each(data.results, function(index, item) { item = item.item; var tempItem = { id: item.id, comments_count: item.num_comments, domain: item.domain, points: item.points, time_ago: $hn.timeAgo(+new Date(item.create_ts)), title: item.title, content: item.text || '', type: item.type, url: item.url, user: item.username, visitedArticle : '', visitedComments : '' }; if (visitedData[item.id]) { if (visitedData[item.id].c) { tempItem.visitedComments = 'visited'; } if (visitedData[item.id].a) { tempItem.visitedArticle = 'visited'; } } localData.articles[item.id] = tempItem; tempData.push(tempItem); }); $hn.perf.update('listAskHn', 'reformat', +new Date() - t0Reformat); return tempData; }; var updateArticlesByType = function(type, callback) { console.log(type); callback = callback || function(){}; var onSuccess = function(data) { $hn.perf.update('list' + type, 'fetch', +new Date() - t0Ajax); localData['list' + type] = reformatData(data); callback.apply(callback, [localData['list' + type]]); }, t0Ajax = +new Date(); $hn.ajax({ url: getUrl(type), dataType: 'jsonp', success: onSuccess }); }; var getArticlesByType = function(type, callback, reload) { reload = reload || false; callback = callback || function(){}; if (!reload && localData['list' + type]) { return callback.apply(callback, [localData['list' + type]]); } updateArticlesByType(type, callback); }; $hn.data = { getArticles: getArticles, getArticleMeta: getArticleMeta, getArticleContent: getArticleContent, getArticleComments: getArticleComments, getArticlesByType: getArticlesByType, cache: getLocalData }; }(window.$hn));
(function () { 'use strict'; angular .module('client') .constant('AUTH_EVENTS', { notAuthenticated: 'auth-not-authenticated', notAuthorized: 'auth-not-authorized', loginSuccess: 'auth-login-success', loginFailed: 'auth-login-failed', logoutSuccess: 'auth-logout-success' }); })();
/** * @providesModule Crashlytics */ 'use strict'; var { NativeModules, Platform } = require('react-native'); var SMXCrashlytics = NativeModules.SMXCrashlytics; module.exports = { crash: SMXCrashlytics.crash, throwException: SMXCrashlytics.throwException, log: function (message:string) { SMXCrashlytics.log(message); }, setUserEmail: function (email:string) { SMXCrashlytics.setUserEmail(email); }, setUserIdentifier: function (userIdentifier) { SMXCrashlytics.setUserIdentifier(userIdentifier); }, setUserName: function (userName:string) { SMXCrashlytics.setUserName(userName); }, setBool: function (key:string, value:boolean) { SMXCrashlytics.setBool(key, value); }, setNumber: function (key:string, value:number) { // This is a hack but allows us to have a standard API for both platforms if (Platform.OS === 'android') { value = value + ""; } SMXCrashlytics.setNumber(key, value); }, setString: function (key:string, value:string) { SMXCrashlytics.setString(key, value); } };
var util = require('util'); var bleno = require('bleno'); var pizza = require('./pizza'); function PizzaToppingsCharacteristic(pizza) { bleno.Characteristic.call(this, { uuid: '13333333333333333333333333330002', properties: ['read', 'write'], descriptors: [ new bleno.Descriptor({ uuid: '2901', value: 'Gets or sets the pizza toppings.' }) ] }); this.pizza = pizza; } util.inherits(PizzaToppingsCharacteristic, bleno.Characteristic); PizzaToppingsCharacteristic.prototype.onWriteRequest = function(data, offset, withoutResponse, callback) { if (offset) { callback(this.RESULT_ATTR_NOT_LONG); } else if (data.length !== 2) { callback(this.RESULT_INVALID_ATTRIBUTE_LENGTH); } else { this.pizza.toppings = data.readUInt16BE(0); callback(this.RESULT_SUCCESS); } }; PizzaToppingsCharacteristic.prototype.onReadRequest = function(offset, callback) { if (offset) { callback(this.RESULT_ATTR_NOT_LONG, null); } else { var data = new Buffer(2); data.writeUInt16BE(this.pizza.toppings, 0); callback(this.RESULT_SUCCESS, data); } }; module.exports = PizzaToppingsCharacteristic;
/* ----------------------------------------------- /* Author : Daniel Chen - danieljchen.com /* MIT license: http://opensource.org/licenses/MIT /* GitHub : github.com/cheniel/pine-schedule.js /* ----------------------------------------------- */ window.PineSchedule = {}; window.PineSchedule.load = function(dom_id, data) { if (!data.optionals) { data.optionals = {}; } var TB_DISPLAY_TYPE = { NONE: 0, ONE_LINE: 1, MULTI_LINE_FIRST: 2, MULTI_LINE_SECOND: 3, }; var DEFAULT = { TIME_BLOCK_COLOR: data.optionals.background_color, HEADER_ALIGNMENT: data.optionals.header_alignment ? data.optionals.header_alignment : "right", HEADER_FONT_SIZE: data.optionals.header_font_size ? data.optionals.header_font_size : "25px", HEADER_FONT: data.optionals.header_font ? data.optionals.header_font : "Verdana, Geneva, sans-serif", BORDERS: !!data.optionals.borders, SHOW_GRID_ON_EVENT: !!data.optionals.show_grid_on_event }; var container = d3.select(dom_id).style("font-family", DEFAULT.HEADER_FONT); var table = container.append("table"); var header = table.append("thead"); header.append("td"); header_data = header.append("td"); header_data.style("text-align", DEFAULT.HEADER_ALIGNMENT).style("font-size", DEFAULT.HEADER_FONT_SIZE); header_data.append("b").text(data.day_of_week); header_data.append("span").text(", " + data.month + " " + data.day); var data_at_time = []; data.events.forEach(function(e) { time_blocks_for_event = (e.end - e.start) / 0.5; time_block_number = 1; for (var time = e.start; time < e.end; time += 0.5) { if (time in data_at_time) { console.log("PineSchedule: skipping event " + e.name + " because overlap"); continue; } if (time_blocks_for_event < 1) { console.log("PineSchedule: skipping event " + e.name + " because duration"); continue; } time_block_display_type = TB_DISPLAY_TYPE.NONE; if (time_blocks_for_event === 1 && time_block_number === 1) { time_block_display_type = TB_DISPLAY_TYPE.ONE_LINE; } else if (time_blocks_for_event > 1 && time_block_number === 1) { time_block_display_type = TB_DISPLAY_TYPE.MULTI_LINE_FIRST; } else if (time_blocks_for_event > 1 && time_block_number === 2) { time_block_display_type = TB_DISPLAY_TYPE.MULTI_LINE_SECOND; } data_at_time[time] = { event: e, display_type: time_block_display_type }; time_block_number++; } }); var time_blocks = []; for (var t = data.range.start; t < data.range.end; t += 0.5) { d = (data_at_time[t] || {}); time_blocks.push(new TimeBlock(t, d.event, d.display_type)); } table.style("width", "100%").style("border-collapse", "collapse"); rows = table.selectAll("tr").data(time_blocks).enter().append("tr").style("height", "25px"); time_column = rows.append("td") .style("text-align", "right") .style("width", "10%") .style("border-right", "solid #D3D3D3 2px") .style("padding-right", "5px") .text(function(d) { return d.get_pretty_time(); }); values_column = rows.append("td") .style("background-color", function(d) { return d.color(); }) .style("padding-left", "5px") .html(function(d) { return d.get_displayed_info(); }); if (DEFAULT.BORDERS) { values_column.style("border-right", "solid #D3D3D3 2px"); values_column.style("border-top", function(d) { return d.get_border_top(); }); d3.select(values_column.node()).style("border-top", "solid #D3D3D3 2px"); d3.select(values_column[0][values_column.size() - 1]).style("border-bottom", "solid #D3D3D3 2px"); } function TimeBlock(time, event, display_type) { this.time = time; this.event = event; this.display_type = display_type; this.is_top_of_hour = function() { return this.time * 10 % 10 === 0; }; this.get_border_top = function() { if (DEFAULT.SHOW_GRID_ON_EVENT || !this.event || this.display_type == TB_DISPLAY_TYPE.ONE_LINE || this.display_type == TB_DISPLAY_TYPE.MULTI_LINE_FIRST) { if (this.is_top_of_hour()) { return "dotted #D3D3D3 1px"; } else { return "dashed #D3D3D3 1px"; } } }; this.get_pretty_time = function() { if (this.is_top_of_hour()) { if (this.time == 0 || this.time == 24) { return "12am" } else if (this.time == 12) { return "12pm"; } else if (this.time < 12) { return this.time + "am"; } else { return (this.time - 12) + "pm"; } } }; this.get_displayed_info = function() { if (this.event) { var time_range = this.event.hasOwnProperty("time_range") ? this.event.time_range + " | " : ""; var location = this.event.hasOwnProperty("location") ? "<i>" + this.event.location + "</i>" : ""; switch(this.display_type) { case TB_DISPLAY_TYPE.ONE_LINE: return time_range + "<b>" + this.event.name + "</b> " + location; case TB_DISPLAY_TYPE.MULTI_LINE_FIRST: return time_range + "<b>" + this.event.name + "</b>"; case TB_DISPLAY_TYPE.MULTI_LINE_SECOND: return location; } } }; this.color = function() { return this.event ? this.event.color : DEFAULT.TIME_BLOCK_COLOR; }; } };
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M10 18h4v-2h-4v2zM3 6v2h18V6H3zm3 7h12v-2H6v2z" /><path fill="none" d="M0 0h24v24H0z" /></React.Fragment> , 'FilterList');
/* global __dirname module require */ const cloneDeep = require('lodash.clonedeep'); const {copySync, ensureDirSync} = require('fs-extra'); const glob = require('glob'); const {dirname, join, normalize, relative, sep} = require('path'); // @babel/cli v7's --copy-files option does not work well together with // config-specified ignore paths, and that's a problem for embark-collective // actions since the @babel/cli invocation must be the same across all packages // in the collective; so any package in the collective that excludes src/ files // from transpilation via its package-local .babelrc.js should copy those files // into dist/, but only if they are expected to be in dist/; .babelrc.js should // also copy any non .js,.ts files into /dist // in this case we want we want to copy .ejs files function copyFiles (ignored) { const others = glob.sync( join(__dirname, 'src/**/*.*'), {ignore: [ join(__dirname, 'src/**/*.js'), join(__dirname, 'src/**/*.ts'), join(__dirname, 'src/**/*.disabled') ]} ).map(path => relative(__dirname, path)); ignored = ignored.concat(others).map(normalize); ignored .map(path => path.replace(`src${sep}`, `dist${sep}`)) .forEach((dest, index) => { ensureDirSync(dirname(join(__dirname, dest))); const source = ignored[index]; copySync(join(__dirname, source), join(__dirname, dest)); }); } module.exports = (api) => { const env = api.env(); const base = {}; const node = cloneDeep(base); if (env === 'node') { copyFiles([]); return node; } const test = cloneDeep(node); if (env === 'test') { copyFiles([]); return test; } return base; };
declare module "react-a11y-dialog" { declare type Props = { // The `role` attribute of the dialog element, either `dialog` (default) or // `alertdialog` to make it a modal (preventing closing on click outside of // ESC key). role?: "dialog" | "alertdialog", // The HTML `id` attribute of the dialog element, internally used by // a11y-dialog to manipulate the dialog. id: string, // The title of the dialog, mandatory in the document to provide context to // assistive technology. Could be hidden (while remaining accessible) with // CSS though. title: string | React$Element<*>, // A function called when the component has mounted, receiving the instance // of A11yDialog so that it can be programmatically accessed later on. // E.g.: dialogRef={(dialog) => (this.dialog = dialog)} dialogRef?: (node: HTMLDialogElement | HTMLElement) => void, // The HTML `id` attribute of the dialog’s title element, used by assistive // technologies to provide context and meaning to the dialog window. Falls // back to the `${this.props.id}-title` if not provided. titleId?: string, // The HTML `aria-label` attribute of the close button, used by assistive // technologies to provide extra meaning to the usual cross-mark. Defaults // to a generic English explanation. closeButtonLabel?: string, // The string that is the innerHTML of the close button. closeButtonContent?: string | React$Element<*>, // a11y-dialog needs one or more “targets” to disable when the dialog is open. // This prop can be one or more selector which will be passed to a11y-dialog // constructor. appRoot: string | Array<string>, // React 16 requires a container for the portal’s content to be rendered // into; this is required and needs to be an existing valid DOM node, // adjacent to the React root container of the application. dialogRoot: string, // Object of classes for each HTML element of the dialog element. Keys are: // - base // - overlay // - element // - document // - title // - closeButton // See for reference: http://edenspiekermann.github.io/a11y-dialog/#expected-dom-structure classNames?: { [key: | "base" | "overlay" | "element" | "document" | "title" | "closeButton"]: string, ... }, // Whether to render a `<dialog>` element or a `<div>` element. useDialog?: boolean, children?: React$Node, ... }; declare class Dialog extends React$Component<Props> {} declare module.exports: typeof Dialog; }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M21 1l-8.31 8.31 8.31 8.3zM4.91 4.36L3.5 5.77l6.36 6.37L1 21h17.73l2 2 1.41-1.41z" /> , 'SignalCellularOffSharp');
import prefix from './prefix' /** * Test if a keyframe at-rule should be prefixed or not * * @param {String} vendor prefix string for the current browser. * @return {String} * @api public */ export default function supportedKeyframes(key) { // Keyframes is already prefixed. e.g. key = '@-webkit-keyframes a' if (key[1] === '-') return key // No need to prefix IE/Edge. Older browsers will ignore unsupported rules. // https://caniuse.com/#search=keyframes if (prefix.js === 'ms') return key return `@${prefix.css}keyframes${key.substr(10)}` }
const webpack = require("webpack"); const path = require("path"); const packageJson = require("./package.json"); const isProduction = process.env.NODE_ENV === "production"; const moduleName = "vocabulary"; const settings = require("../../../settings.local.json"); module.exports = { entry: "./src/main.jsx", optimization: { minimize: isProduction }, output: { path: isProduction || settings.WebsitePath == "" ? path.resolve( __dirname, "../../Dnn.PersonaBar.Extensions/admin/personaBar/Dnn.Vocabularies/scripts/bundles/" ) : settings.WebsitePath + "\\DesktopModules\\Admin\\Dnn.PersonaBar\\Modules\\Dnn.Vocabularies\\scripts\\bundles\\", publicPath: isProduction ? "" : "http://localhost:8080/dist/", filename: moduleName + "-bundle.js" }, devServer: { disableHostCheck: !isProduction }, resolve: { extensions: ["*", ".js", ".json", ".jsx"], modules: [ path.resolve("./src"), // Look in src first path.resolve("./node_modules"), // Try local node_modules path.resolve("../../../node_modules") // Last fallback to workspaces node_modules ] }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, enforce: "pre", use: ["eslint-loader"] }, { test: /\.less$/, use: [ { loader: "style-loader" // creates style nodes from JS strings }, { loader: "css-loader", // translates CSS into CommonJS options: { modules: "global" } }, { loader: "less-loader" // compiles Less to CSS } ] }, { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: "babel-loader", options: { presets: ["@babel/preset-env", "@babel/preset-react"] } } }, { test: /\.(ttf|woff)$/, use: { loader: "url-loader?limit=8192" } } ] }, externals: require("@dnnsoftware/dnn-react-common/WebpackExternals"), plugins: isProduction ? [ new webpack.DefinePlugin({ VERSION: JSON.stringify(packageJson.version), "process.env": { NODE_ENV: JSON.stringify("production") } }) ] : [ new webpack.DefinePlugin({ VERSION: JSON.stringify(packageJson.version) }) ], devtool: "source-map" };
import site from '../../app'; site.controller('resultsDialogController', ($scope, $mdDialog, tournamentName, results, players, PlaceService) => { $scope.cancel = $mdDialog.cancel; $scope.tournamentName = tournamentName; $scope.results = results; $scope.players = players; $scope.nameString = (idx) => { const player = $scope.players[idx-1]; if(player.alias) return `${player.alias} (${player.name})`; return player.name; }; $scope.toOrdinal = PlaceService.getPlaceString; });
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = require('react'); var _react2 = _interopRequireDefault(_react); var canUseDom = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * Get elements owner document * * @param {ReactComponent|HTMLElement} componentOrElement * @returns {HTMLElement} */ function ownerDocument(componentOrElement) { var elem = _react2['default'].findDOMNode(componentOrElement); return elem && elem.ownerDocument || document; } function ownerWindow(componentOrElement) { var doc = ownerDocument(componentOrElement); return doc.defaultView ? doc.defaultView : doc.parentWindow; } /** * get the active element, safe in IE * @return {HTMLElement} */ function getActiveElement(componentOrElement) { var doc = ownerDocument(componentOrElement); try { return doc.activeElement || doc.body; } catch (e) { return doc.body; } } /** * Shortcut to compute element style * * @param {HTMLElement} elem * @returns {CssStyle} */ function getComputedStyles(elem) { return ownerDocument(elem).defaultView.getComputedStyle(elem, null); } /** * Get elements offset * * TODO: REMOVE JQUERY! * * @param {HTMLElement} DOMNode * @returns {{top: number, left: number}} */ function getOffset(DOMNode) { if (window.jQuery) { return window.jQuery(DOMNode).offset(); } var docElem = ownerDocument(DOMNode).documentElement; var box = { top: 0, left: 0 }; // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if (typeof DOMNode.getBoundingClientRect !== 'undefined') { box = DOMNode.getBoundingClientRect(); } return { top: box.top + window.pageYOffset - docElem.clientTop, left: box.left + window.pageXOffset - docElem.clientLeft }; } /** * Get elements position * * TODO: REMOVE JQUERY! * * @param {HTMLElement} elem * @param {HTMLElement?} offsetParent * @returns {{top: number, left: number}} */ function getPosition(elem, offsetParent) { if (window.jQuery) { return window.jQuery(elem).position(); } var offset = undefined, parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent if (getComputedStyles(elem).position === 'fixed') { // We assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { if (!offsetParent) { // Get *real* offsetParent offsetParent = offsetParentFunc(elem); } // Get correct offsets offset = getOffset(elem); if (offsetParent.nodeName !== 'HTML') { parentOffset = getOffset(offsetParent); } // Add offsetParent borders parentOffset.top += parseInt(getComputedStyles(offsetParent).borderTopWidth, 10); parentOffset.left += parseInt(getComputedStyles(offsetParent).borderLeftWidth, 10); } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - parseInt(getComputedStyles(elem).marginTop, 10), left: offset.left - parentOffset.left - parseInt(getComputedStyles(elem).marginLeft, 10) }; } /** * Get parent element * * @param {HTMLElement?} elem * @returns {HTMLElement} */ function offsetParentFunc(elem) { var docElem = ownerDocument(elem).documentElement; var offsetParent = elem.offsetParent || docElem; while (offsetParent && (offsetParent.nodeName !== 'HTML' && getComputedStyles(offsetParent).position === 'static')) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; } /** * Cross browser .contains() polyfill * @param {HTMLElement} elem * @param {HTMLElement} inner * @return {bool} */ function contains(elem, inner) { function ie8Contains(root, node) { while (node) { if (node === root) { return true; } node = node.parentNode; } return false; } return elem && elem.contains ? elem.contains(inner) : elem && elem.compareDocumentPosition ? elem === inner || !!(elem.compareDocumentPosition(inner) & 16) : ie8Contains(elem, inner); } exports['default'] = { canUseDom: canUseDom, contains: contains, ownerWindow: ownerWindow, ownerDocument: ownerDocument, getComputedStyles: getComputedStyles, getOffset: getOffset, getPosition: getPosition, activeElement: getActiveElement, offsetParent: offsetParentFunc }; module.exports = exports['default'];
/** * @fileOverview Component命名空间的入口文件 * @ignore */ /** * @class BUI.Component * <p> * <img src="../assets/img/class-common.jpg"/> * </p> * 控件基类的命名空间 */ var Component = {}; BUI.mix(Component, { Manager: require('./manage'), UIBase: require('./uibase/uibase'), View: require('./view'), Controller: require('./controller') }); function create(component, self) { var childConstructor, xclass; if (component && (xclass = component.xclass)) { if (self && !component.prefixCls) { component.prefixCls = self.get('prefixCls'); } childConstructor = Component.Manager.getConstructorByXClass(xclass); if (!childConstructor) { BUI.error('can not find class by xclass desc : ' + xclass); } component = new childConstructor(component); } return component; } /** * 根据Xclass创建对象 * @method * @static * @param {Object} component 控件的配置项或者控件 * @param {Object} self 父类实例 * @return {Object} 实例对象 */ Component.create = create; module.exports = Component;
'use strict'; const cronTasks = require('./src/cron-tasks'); module.exports = ({ env }) => ({ host: env('HOST', '0.0.0.0'), port: env.int('PORT', 1337), url: 'http://localhost:1337', cron: { enabled: true, tasks: cronTasks, }, app: { keys: env.array('APP_KEYS', ['toBeModified1', 'toBeModified2']), }, });
import sumBy from 'lodash/sumBy'; import map from 'lodash/fp/map'; import partition from 'lodash/partition'; import find from 'lodash/find'; import { ContentNodeFileSizeResource } from 'kolibri.resources'; const pluckIds = map('id'); function isDescendantOrSelf(testNode, selfNode) { return testNode.id === selfNode.id || find(testNode.path, { id: selfNode.id }); } /** * Queries the server for a ContentNode's file sizes * * @param node {Node} - (sanitized) Node, which has resource, but not file sizes * @returns {Promise<{total_file_size, on_device_file_size}>} * */ export function getContentNodeFileSize(node) { return ContentNodeFileSizeResource.fetchModel({ id: node.id }); } /** * Adds a new node to the transfer list. * * @param node {Node} - Node to be added * @param node.path {Array<String>} - path (via ids) from channel root to the Node * */ export function addNodeForTransfer(store, node) { const { included, omitted } = store.state.nodesForTransfer; // remove nodes in "omit" that are either descendants of new node or the node itself const [notToOmit, toOmit] = partition(omitted, omitNode => isDescendantOrSelf(omitNode, node)); if (notToOmit.length > 0) { store.commit('REPLACE_OMIT_LIST', toOmit); } // remove nodes in "include" that would be made redundant by the new one const [notToIncluded, toInclude] = partition(included, includeNode => isDescendantOrSelf(includeNode, node) ); if (notToIncluded.length > 0) { store.commit('REPLACE_INCLUDE_LIST', toInclude); } return getContentNodeFileSize(node).then(fileSizes => { store.commit('ADD_NODE_TO_INCLUDE_LIST', { ...node, ...fileSizes, }); }); } /** * Removes node from transfer list * * @param node {Node} - node to be removed * */ export function removeNodeForTransfer(store, node) { let promise = Promise.resolve(); const forImport = !store.getters.inExportMode; const { included, omitted } = store.state.nodesForTransfer; // remove nodes in "include" that are either descendants of the removed node or the node itself const [notToInclude, toInclude] = partition(included, includeNode => isDescendantOrSelf(includeNode, node) ); if (notToInclude.length > 0) { store.commit('REPLACE_INCLUDE_LIST', toInclude); } // if the removed node's has ancestors that are selected, the removed node gets placed in "omit" const includedAncestors = included.filter( includeNode => pluckIds(node.path).includes(includeNode.id) && node.id !== includeNode.id ); if (includedAncestors.length > 0) { // remove redundant nodes in "omit" that either descendants of the new node or the node itself const [notToOmit, toOmit] = partition(omitted, omitNode => isDescendantOrSelf(omitNode, node)); if (notToOmit.length > 0) { store.commit('REPLACE_OMIT_LIST', toOmit); } promise = getContentNodeFileSize(node) .then(fileSizes => { store.commit('ADD_NODE_TO_OMIT_LIST', { ...node, ...fileSizes, }); }) .then(() => { // loop through the ancestor list and remove any that have been completely un-selected includedAncestors.forEach(ancestor => { let omittedResources; let ancestorResources; const omittedDescendants = omitted.filter(n => pluckIds(n.path).includes(ancestor.id)); if (forImport) { // When total_resources === on_device_resources, then that node is not selectable. // So we need to compare the difference (i.e # of transferrable nodes) when // deciding whether parent is fully omitted. ancestorResources = ancestor.total_resources - ancestor.on_device_resources; omittedResources = sumBy(omittedDescendants, 'total_resources') - sumBy(omittedDescendants, 'on_device_resources'); } else { ancestorResources = ancestor.on_device_resources; omittedResources = sumBy(omittedDescendants, 'on_device_resources'); } if (ancestorResources === omittedResources) { // remove the ancestor from "include" store.commit('REPLACE_INCLUDE_LIST', included.filter(n => n.id !== ancestor.id)); // remove all desceandants from "omit" store.commit( 'REPLACE_OMIT_LIST', omitted.filter(n => !pluckIds(n.path).includes(ancestor.id)) ); } }); }); } return promise; }
'use strict'; var vfs = require('vinyl-fs'), initStream = require('../lib/initStream'), progressCallback = require('../lib/progressCallback'); describe('initStream', function () { it('should init options', function(done) { var options = { useMemoryFs: true, progress: true }, entry = vfs.src('test/fixtures/initStream/webpack.config.js'), init = initStream(options); init.on('data', function(chunk) { expect(chunk[initStream.FIELD_NAME]).toEqual({ useMemoryFs: true, progress: progressCallback }); done(); }); entry.pipe(init).resume(); }); it('should init empty options', function(done) { var entry = vfs.src('test/fixtures/initStream/webpack.config.js'), init = initStream(); init.on('data', function(chunk) { expect(chunk[initStream.FIELD_NAME]).toEqual({}); done(); }); entry.pipe(init).resume(); }); });
function controller(t) { var utils = require('../../utils'); var harvest = require('../../api/harvest')(); var tp = require('../../api/tp')(); var base = require('./_base'); function pauseAndLog(e, done) { if(e.running) { utils.log(' Stopping timer on harvest...'); harvest.TimeTracking.toggleTimer({ id: e.id }, function (err) { if(err) return utils.log.err(err); utils.log.succ(' Done.'); logTime(e, done); }); } else { utils.log(' Time is already stopped.'); logTime(e, done); } } function logTime(e, done) { if(!tp || !e.tp_task || !e.tp_task.id || !e.hours) return done(); var isBug = e.tp_task.type === 'bug'; utils.log(' Logging time on target process...'); if(isBug) { utils.log(' Bugs are configured to be logged against: ' + tp.bugTimeBehavior); } // configured to not log bug-time at all if(isBug && tp.bugTimeBehavior === 'none') { utils.log.chalk('red', ' System is configured NOT to log bug times AT ALL.'); return done(); } var getter = isBug ? tp.getBug : tp.getTask; getter.call(tp, e.tp_task.id) .then(function (tpTask) { base.captureTimeRemaining(e.hours, tpTask, function (remain) { var tpdata = { description: e.notes || '-', spent: e.hours, remain: remain, date: new Date(e.created_at).toJSON() }; function logTime_us(cb) { // bugs may be without user-story if(!tpTask.UserStory) { utils.log.chalk('red', ' This '+tpTask.ResourceType+' is not associated with a user-story. -- ignored'); return cb(); } var userStoryId = tpTask.UserStory.Id; utils.log(' Logging bug time on the user story...'); var tpusdata = { description: 'time spent on bug #' + e.tp_task.id, spent: e.hours, date: new Date(e.created_at).toJSON() }; tp.addTime(userStoryId, tpusdata) .then(function () { utils.log(' ' + tpdata.spent + 'h is logged on target process against user story #' + userStoryId); cb(); }, function (err) { utils.log.err(err); }); } function logTime_task(cb) { tp.addTime(e.tp_task.id, tpdata) .then(function () { utils.log(' ' + tpdata.spent + 'h is logged on target process against '+ e.tp_task.type +' #' + e.tp_task.id); cb(); }, function (err) { utils.log.err(err); }); } // if not bug, time is always on task if(!isBug) { return logTime_task(done); } else { if(tp.bugTimeBehavior === 'bug') { return logTime_task(done); } else if(tp.bugTimeBehavior === 'user-story') { return logTime_us(done); } else { // both return logTime_task(function () { return logTime_us(done); }); } } }); }, function (err) { utils.log.err('An error occured while fetching task from target process.' + err); }); } function finish(e, done) { if(!e) return utils.log.err('No timer could be found.'); if(e.finished) return utils.log.err('This time is already marked as finished.'); utils.log('❯ finishing time:', e.id); pauseAndLog(e, function () { if(!e.tp_task) { utils.log(' Time is not associated with a target-process task.'); return done(); } utils.log(' Marking time as finished on harvest...'); var model = { id: e.id, notes: e.full_notes + '\n' + harvest.prefixes.finishedPrefix }; harvest.TimeTracking.update(model, function (err) { if(err) return utils.log.err(err); utils.log.succ(' Done.'); done(); }); }); } function finishAll(list) { var item = list.pop(); if(!item) return; finish(item, function () { finishAll(list); }); } var d = t.d || t.date; var offset = +(t.o || t.offset); if (!d && offset) d = new Date().addDays(-offset); base.selectTime(d, function (i) { return !i.finished; }, finishAll, t.all); } require('dastoor').builder .node('onetime.time.finish', { terminal: true, controller: controller }) .help({ description: 'finish a timesheet', options: [{ name: '-d, --date', description: 'date of the timesheet. e.g. 2015-07-01' }, { name: '-o, --offfset', description: 'date offset relative to today. e.g. 1 for yesterday' }, { name: '--all', description: 'finished all unfinished times' }] });
var _ = module.exports = {}; var slice = [].slice, o2str = ({}).toString; // merge o2's properties to Object o1. _.extend = function(o1, o2, override){ for(var i in o2) if(override || o1[i] === undefined){ o1[i] = o2[i] } return o1; } _.slice = function(arr, index){ return slice.call(arr, index); } _.typeOf = function typeOf (o) { return o == null ? String(o) : o2str.call(o).slice(8, -1).toLowerCase(); } //strict eql _.eql = function(o1, o2){ var t1 = _.typeOf(o1), t2 = _.typeOf(o2); if( t1 !== t2) return false; if(t1 === 'object'){ // only check the first's properties for(var i in o1){ // Immediately return if a mismatch is found. if( o1[i] !== o2[i] ) return false; } return true; } return o1 === o2; } // small emitter _.emitable = (function(){ function norm(ev){ var eventAndNamespace = (ev||'').split(':'); return {event: eventAndNamespace[0], namespace: eventAndNamespace[1]} } var API = { once: function(event, fn){ var callback = function(){ fn.apply(this, arguments) this.off(event, callback) } return this.on(event, callback) }, on: function(event, fn) { if(typeof event === 'object'){ for (var i in event) { this.on(i, event[i]); } return this; } var ne = norm(event); event=ne.event; if(event && typeof fn === 'function' ){ var handles = this._handles || (this._handles = {}), calls = handles[event] || (handles[event] = []); fn._ns = ne.namespace; calls.push(fn); } return this; }, off: function(event, fn) { var ne = norm(event); event = ne.event; if(!event || !this._handles) this._handles = {}; var handles = this._handles , calls; if (calls = handles[event]) { if (!fn && !ne.namespace) { handles[event] = []; }else{ for (var i = 0, len = calls.length; i < len; i++) { if ( (!fn || fn === calls[i]) && (!ne.namespace || calls[i]._ns === ne.namespace) ) { calls.splice(i, 1); return this; } } } } return this; }, emit: function(event){ var ne = norm(event); event = ne.event; var args = _.slice(arguments, 1), handles = this._handles, calls; if (!handles || !(calls = handles[event])) return this; for (var i = 0, len = calls.length; i < len; i++) { var fn = calls[i]; if( !ne.namespace || fn._ns === ne.namespace ) fn.apply(this, args) } return this; } } return function(obj){ obj = typeof obj == "function" ? obj.prototype : obj; return _.extend(obj, API) } })(); _.bind = function(fn, context){ return function(){ return fn.apply(context, arguments); } } var rDbSlash = /\/+/g, // double slash rEndSlash = /\/$/; // end slash _.cleanPath = function (path){ return ("/" + path).replace( rDbSlash,"/" ).replace( rEndSlash, "" ) || "/"; } // normalize the path function normalizePath(path) { // means is from // (?:\:([\w-]+))?(?:\(([^\/]+?)\))|(\*{2,})|(\*(?!\*)))/g var preIndex = 0; var keys = []; var index = 0; var matches = ""; path = _.cleanPath(path); var regStr = path // :id(capture)? | (capture) | ** | * .replace(/\:([\w-]+)(?:\(([^\/]+?)\))?|(?:\(([^\/]+)\))|(\*{2,})|(\*(?!\*))/g, function(all, key, keyformat, capture, mwild, swild, startAt) { // move the uncaptured fragment in the path if(startAt > preIndex) matches += path.slice(preIndex, startAt); preIndex = startAt + all.length; if( key ){ matches += "(" + key + ")"; keys.push(key) return "("+( keyformat || "[\\w-]+")+")"; } matches += "(" + index + ")"; keys.push( index++ ); if( capture ){ // sub capture detect return "(" + capture + ")"; } if(mwild) return "(.*)"; if(swild) return "([^\\/]*)"; }) if(preIndex !== path.length) matches += path.slice(preIndex) return { regexp: new RegExp("^" + regStr +"/?$"), keys: keys, matches: matches || path } } _.log = function(msg, type){ typeof console !== "undefined" && console[type || "log"](msg) } _.isPromise = function( obj ){ return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; } _.normalize = normalizePath;
// Generated by CoffeeScript 1.7.1 (function() { var Directory, File, getClangFlagsCompDB, getClangFlagsDotClangComplete, getFileContents, path, readFileSync, _ref; path = require('path'); readFileSync = require('fs').readFileSync; _ref = require('pathwatcher'), File = _ref.File, Directory = _ref.Directory; module.exports = { getClangFlags: function(fileName) { var flags; flags = getClangFlagsCompDB(fileName); if (flags) { getClangFlagsDotClangComplete(fileName); } return flags; }, activate: function(state) {} }; getFileContents = function(startFile, fileName) { var args, contents, error, searchDir, searchFile, searchFilePath, thisDir; searchDir = path.dirname(startFile); args = []; while (searchDir.length) { searchFilePath = path.join(searchDir, fileName); searchFile = new File(searchFilePath); if (searchFile.exists()) { contents = ""; try { contents = readFileSync(searchFilePath, 'utf8'); return contents; } catch (_error) { error = _error; console.log("clang-flags for " + fileName + " couldn't read file " + searchFilePath); console.log(error); } return nil; } thisDir = new Directory(searchDir); if (thisDir.isRoot()) { break; } searchDir = thisDir.getParent().getPath(); } return nil; }; getClangFlagsCompDB = function(fileName) { var args, compDB, compDBContents; compDBContents = getFileContents(fileName, "compile_commands.json"); args = 0; if (compDBContents.length > 0) { compDB = JSON.parse(compDBContents); } return args; }; getClangFlagsDotClangComplete = function(fileName) { var args, clangCompleteContents; clangCompleteContents = getFileContents(fileName, ".clang_complete"); args = []; if (clangCompleteContents.length > 0) { args = clangCompleteContents.split("\n"); args = args.concat(["-working-directory=" + searchDir]); } return args; }; }).call(this);
var System = require('../../entities/systems/System'); var BoundingBox = require('../../renderer/bounds/BoundingBox'); /** * Calculates and updates all boundings on entities with both transform, meshrenderer and meshdata components * @extends System */ function BoundingUpdateSystem() { System.call(this, 'BoundingUpdateSystem', ['TransformComponent', 'MeshRendererComponent', 'MeshDataComponent']); this._worldBound = new BoundingBox(); this._computeWorldBound = null; } BoundingUpdateSystem.prototype = Object.create(System.prototype); BoundingUpdateSystem.prototype.constructor = BoundingUpdateSystem; BoundingUpdateSystem.prototype.process = function (entities) { var l = entities.length; if (l === 0) { this._computeWorldBound = null; return; } for (var i = 0; i < l; i++) { var entity = entities[i]; var meshDataComponent = entity.meshDataComponent; var transformComponent = entity.transformComponent; var meshRendererComponent = entity.meshRendererComponent; transformComponent.sync(); if (meshDataComponent.modelBoundDirty) { meshDataComponent.computeBoundFromPoints(); meshRendererComponent.updateBounds(meshDataComponent.modelBound, transformComponent.worldTransform); } else if (meshRendererComponent._worldBoundDirty) { meshRendererComponent.updateBounds(meshDataComponent.modelBound, transformComponent.worldTransform); } } if (this._computeWorldBound && this._computeWorldBound instanceof Function) { //this._worldBound = new BoundingSphere(new Vector3(0, 0, 0), 0); // optional for including the center of the scene into the world bound // generally we don't want particle systems to end up in our world bound computing since they have huge world bounds and can mess up stuff for (var i = 0; i < l; i++) { if (!entities[i].particleComponent) { this._worldBound = entities[i].meshRendererComponent.worldBound.clone(); break; } } for (; i < l; i++) { if (!entities[i].particleComponent) { var mrc = entities[i].meshRendererComponent; this._worldBound = this._worldBound.merge(mrc.worldBound); } } this._computeWorldBound(this._worldBound); this._computeWorldBound = null; } }; // function named get actually does a set BoundingUpdateSystem.prototype.getWorldBound = function (callback) { this._computeWorldBound = callback; }; BoundingUpdateSystem.prototype.deleted = function (entity) { if (entity.meshRendererComponent) { entity.meshRendererComponent.worldBound = new BoundingBox(); } }; module.exports = BoundingUpdateSystem;
exports.getInstanceId = function(success, error) { if (typeof success === 'function') { success(); } }; exports.getToken = function(success, error) { if (typeof success === 'function') { success(); } }; exports.onNotificationOpen = function(success, error) { }; exports.onTokenRefresh = function(success, error) { }; exports.grantPermission = function(success, error) { if (typeof success === 'function') { success(); } }; exports.setBadgeNumber = function(number, success, error) { if (typeof success === 'function') { success(); } }; exports.getBadgeNumber = function(success, error) { if (typeof success === 'function') { success(); } }; exports.subscribe = function(topic, success, error) { if (typeof success === 'function') { success(); } }; exports.unsubscribe = function(topic, success, error) { if (typeof success === 'function') { success(); } }; exports.logEvent = function(name, params, success, error) { if (typeof success === 'function') { success(); } }; exports.setScreenName = function(name, success, error) { if (typeof success === 'function') { success(); } }; exports.setUserId = function(id, success, error) { if (typeof success === 'function') { success(); } }; exports.setUserProperty = function(name, value, success, error) { if (typeof success === 'function') { success(); } }; exports.activateFetched = function (success, error) { if (typeof success === 'function') { success(); } }; exports.fetch = function (cacheExpirationSeconds, success, error) { if (typeof success === 'function') { success(); } }; exports.getByteArray = function (key, namespace, success, error) { if (typeof success === 'function') { success(); } }; exports.getValue = function (key, namespace, success, error) { if (typeof success === 'function') { success(); } }; exports.getInfo = function (success, error) { if (typeof success === 'function') { success(); } }; exports.setConfigSettings = function (settings, success, error) { if (typeof success === 'function') { success(); } }; exports.setDefaults = function (defaults, namespace, success, error) { if (typeof success === 'function') { success(); } };
Sidebars.Properties.Geometry.IcosahedronGeometry = function ( signals, object ) { var container = new UI.Panel(); var geometry = object.geometry; // radius var radiusRow = new UI.Panel(); var radius = new UI.Number( geometry.parameters.radius ).onChange( update ); radiusRow.add( new UI.Text( 'Radius' ).setWidth( '90px' ) ); radiusRow.add( radius ); container.add( radiusRow ); // detail var detailRow = new UI.Panel(); var detail = new UI.Integer( geometry.parameters.detail ).setRange( 0, Infinity ).onChange( update ); detailRow.add( new UI.Text( 'Detail' ).setWidth( '90px' ) ); detailRow.add( detail ); container.add( detailRow ); // function update() { delete object.__webglInit; // TODO: Remove hack (WebGLRenderer refactoring) object.geometry.dispose(); object.geometry = new THREE.IcosahedronGeometry( radius.getValue(), detail.getValue() ); object.geometry.buffersNeedUpdate = true; object.geometry.computeBoundingSphere(); signals.objectChanged.dispatch( object ); } return container; }
var mysql = require('./mysqlQueryBuilder'); module.exports = function(){ mysql.call(this); };
'use strict'; angular.module('liveJudgingAdmin.main', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/', { templateUrl: 'modules/main/main.html', controller: 'MainCtrl' }); }]) /*.controller('MainCtrl', ['$location', '$route', '$routeParams', '$scope', function($location, $route, $routeParams, $scope) { $scope.$on('$routeChangeSuccess', function() { $scope.currentPath = $location.path(); }); }]);*/ .controller('MainCtrl', [function() { }]);
// @flow // import eventDispatcher from './utils/dispatch-event'; import { cancelEvent, getTouches, detectDoubleTap, calcScale } from './utils/handle-event'; import scaleElement from './utils/handle-element'; import { isWithin, calcNewScale, addOffset, getInitialScale, getScaleFactor, getZoomFactor, getTouchCenter } from './utils/handle-pinch'; import { drag, sanitizeOffset } from './utils/handle-drag'; import defaults from './defaults'; const first = (items: Array<Object>) => items[0]; const setTarget = (el, opts) => ( el.querySelector(opts.target ? `img${opts.target}` : 'img') ); const pinchIt = (targets: string | Object, options: Object = {}) => { // private variable cache let element = null; let scaling; let lastScale = 1; let startTouches; let zoomFactor = 1; let offset = { x: 0, y: 0 }; let lastZoomCenter: Object = {}; let lastDragPosition: Object = {}; // Base configuration for the pinch instance const opts = {...defaults, ...options}; const { on, dispatch } = eventDispatcher(); /** * dispatchPinchEvent - Shorthand method for creating events * * @param { String } phase * @param { String } type * @param { Object } details * @return { Void } **/ const dispatchPinchEvent = (eventName: string, phase: string, data: Object = {}): void => { dispatch(eventName, Object.assign(data, { phase })); }; const resetGlobals = (/* opts */): void => { scaling = undefined; lastScale = 1; startTouches = null; zoomFactor = 1; lastZoomCenter = {}; lastDragPosition = {}; offset = { x: 0, y: 0 }; }; /** * Set scaling if we are using more then one finger * and captures our first punch point * * private * @param { Object } e the event from our eventlistener */ const onTouchstart = (e: TouchEvent) => { dispatchPinchEvent('touchstart', 'before', e); const { target, currentTarget } = e; scaling = (e.touches.length === 2); startTouches = Array.from(e.touches); lastScale = 1; if (detectDoubleTap(e) && target instanceof HTMLElement && currentTarget instanceof HTMLElement) { const image = currentTarget.querySelector('img'); scaleElement(target, image, 1, { x: 0, y: 0 }, opts.snapBackSpeed, opts.ease); resetGlobals(); } dispatchPinchEvent('touchstart', 'after', e); }; const onTouchmove = (e: TouchEvent) => { dispatchPinchEvent('touchmove', 'before', e); const { currentTarget, target, touches } = e; if ((!scaling || !startTouches) && zoomFactor > 1) { cancelEvent(e); const touch = first(getTouches(currentTarget, Array.from(touches))); const dragOffset = drag(touch, lastDragPosition, offset, zoomFactor); offset = sanitizeOffset(target, dragOffset, zoomFactor); lastDragPosition = touch; } else if (scaling && startTouches) { cancelEvent(e); // a relative scale factor is used const touchCenter = getTouchCenter(getTouches(e.currentTarget, Array.from(touches))); const newScale = calcScale(e.currentTarget, startTouches, Array.from(touches)); const scaleValue = calcNewScale(newScale, lastScale); const scale = getScaleFactor(scaleValue, zoomFactor, opts); zoomFactor = getZoomFactor(scaleValue, zoomFactor, opts); offset = addOffset(offset, { x: (scale - 1) * (touchCenter.x + offset.x), y: (scale - 1) * (touchCenter.y + offset.y) }); lastScale = newScale; offset = drag(touchCenter, lastZoomCenter, offset, zoomFactor); lastZoomCenter = touchCenter; } if (target instanceof HTMLElement && currentTarget instanceof HTMLElement) { const image = currentTarget.querySelector('img'); scaleElement(target, image, zoomFactor, offset, 0, opts.ease); } dispatchPinchEvent('touchmove', 'after', e); }; const onTouchend = (e: TouchEvent) => { dispatchPinchEvent('touchend', 'before', e); const { target, currentTarget } = e; if (zoomFactor && !isWithin(zoomFactor, opts) && currentTarget instanceof HTMLElement) { const image = currentTarget.querySelector('img'); const isLessThan = (getInitialScale(target, image) * zoomFactor < opts.minScale); const lastZoom = zoomFactor; zoomFactor = isLessThan ? opts.minScale : opts.maxScale; const scaleValue = calcNewScale(zoomFactor, lastZoom); const scale = getScaleFactor(scaleValue, zoomFactor, opts); offset = addOffset(offset, { x: (scale - 1) * (lastZoomCenter.x + offset.x), y: (scale - 1) * (lastZoomCenter.y + offset.y) }); offset = sanitizeOffset(e.target, offset, zoomFactor); scaleElement(target, image, zoomFactor, offset, opts.snapBackSpeed, opts.ease); } lastScale = 1; lastDragPosition = {}; lastZoomCenter = {}; dispatchPinchEvent('touchend', 'after', e); }; const attachEvents = (el: HTMLElement) => { el.addEventListener('touchstart', onTouchstart); el.addEventListener('touchmove', onTouchmove); el.addEventListener('touchend', onTouchend); }; const detachhEvents = (el: HTMLElement) => { el.removeEventListener('touchstart', onTouchstart); el.removeEventListener('touchmove', onTouchmove); el.removeEventListener('touchend', onTouchend); }; /** * public * reset function: * @param { Number } duration * @param { String } easing * @return { Void } */ const reset = (opt: Object = {}): void => { if (!element) return; const image = setTarget(element, opts); if (!image) return; const { snapBackSpeed, easing } = Object.assign({}, opts, opt); scaleElement(element, image, 1, { x: 0, y: 0 }, snapBackSpeed, easing); resetGlobals(); }; /** * public * destroy function: called to gracefully destroy the lory instance * @return { Void } */ const destroy = (opt: Object = {}): void => { dispatchPinchEvent('destroy', 'before', {}); if (!element) return; reset(opt); // remove event listeners detachhEvents(element); element = null; resetGlobals(); dispatchPinchEvent('destroy', 'after', {}); }; /** * setup - Init function * * @param { String, Object } * @return { Void } **/ const setup = (target: string | HTMLElement): void => { if (element) destroy(); dispatchPinchEvent('init', 'before', {}); // resolve target // pinchit allows for both a node or a string to be passed switch (typeof target) { case 'object': element = target; break; case 'string': element = document.querySelector(target); break; default: element = null; console.warn('missing target, either pass an node or a string'); } if (element) { attachEvents(element); } dispatchPinchEvent('init', 'after', {}); }; // trigger initial setup setup(targets); return { setup, reset, destroy, element, on, }; }; export default pinchIt;
import {combineCssRule, combineJsRule} from './htmlRules'; export default {combineCssRule, combineJsRule};
/* Formatblock * Is used to insert block level elements * It tries to solve the case that some block elements should not contain other block level elements (h1-6, p, ...) * */ (function(wysihtml) { var dom = wysihtml.dom, // When the caret is within a H1 and the H4 is invoked, the H1 should turn into H4 // instead of creating a H4 within a H1 which would result in semantically invalid html UNNESTABLE_BLOCK_ELEMENTS = "h1, h2, h3, h4, h5, h6, p, pre", BLOCK_ELEMENTS = "h1, h2, h3, h4, h5, h6, p, pre, div, blockquote", INLINE_ELEMENTS = "b, big, i, small, tt, abbr, acronym, cite, code, dfn, em, kbd, strong, samp, var, a, bdo, br, q, span, sub, sup, button, label, textarea, input, select, u"; function correctOptionsForSimilarityCheck(options) { return { nodeName: options.nodeName || null, className: (!options.classRegExp) ? options.className || null : null, classRegExp: options.classRegExp || null, styleProperty: options.styleProperty || null }; } function getRangeNode(node, offset) { if (node.nodeType === 3) { return node; } else { return node.childNodes[offset] || node; } } // Returns if node is a line break function isBr(n) { return n && n.nodeType === 1 && n.nodeName === "BR"; } // Is block level element function isBlock(n, composer) { return n && n.nodeType === 1 && composer.win.getComputedStyle(n).display === "block"; } // Returns if node is the rangy selection bookmark element (that must not be taken into account in most situatons and is removed on selection restoring) function isBookmark(n) { return n && n.nodeType === 1 && n.classList.contains('rangySelectionBoundary'); } // Is line breaking node function isLineBreaking(n, composer) { return isBr(n) || isBlock(n, composer); } // Removes empty block level elements function cleanup(composer, newBlockElements) { wysihtml.dom.removeInvisibleSpaces(composer.element); var container = composer.element, allElements = container.querySelectorAll(BLOCK_ELEMENTS), noEditQuery = composer.config.classNames.uneditableContainer + ([""]).concat(BLOCK_ELEMENTS.split(',')).join(", " + composer.config.classNames.uneditableContainer + ' '), uneditables = container.querySelectorAll(noEditQuery), elements = wysihtml.lang.array(allElements).without(uneditables), // Lets not touch uneditable elements and their contents nbIdx; for (var i = elements.length; i--;) { if (elements[i].innerHTML.replace(/[\uFEFF]/g, '') === "" && (newBlockElements.length === 0 || elements[i] !== newBlockElements[newBlockElements.length - 1])) { // If cleanup removes some new block elements. remove them from newblocks array too nbIdx = wysihtml.lang.array(newBlockElements).indexOf(elements[i]); if (nbIdx > -1) { newBlockElements.splice(nbIdx, 1); } elements[i].parentNode.removeChild(elements[i]); } } return newBlockElements; } function defaultNodeName(composer) { return composer.config.useLineBreaks ? "DIV" : "P"; } // The outermost un-nestable block element parent of from node function findOuterBlock(node, container, allBlocks) { var n = node, block = null; while (n && container && n !== container) { if (n.nodeType === 1 && n.matches(allBlocks ? BLOCK_ELEMENTS : UNNESTABLE_BLOCK_ELEMENTS)) { block = n; } n = n.parentNode; } return block; } // Clone for splitting the inner inline element out of its parent inline elements context // For example if selection is in bold and italic, clone the outer nodes and wrap these around content and return function cloneOuterInlines(node, container) { var n = node, innerNode, parentNode, el = null, el2; while (n && container && n !== container) { if (n.nodeType === 1 && n.matches(INLINE_ELEMENTS)) { parentNode = n; if (el === null) { el = n.cloneNode(false); innerNode = el; } else { el2 = n.cloneNode(false); el2.appendChild(el); el = el2; } } n = n.parentNode; } return { parent: parentNode, outerNode: el, innerNode: innerNode }; } // Formats an element according to options nodeName, className, styleProperty, styleValue // If element is not defined, creates new element // if opotions is null, remove format instead function applyOptionsToElement(element, options, composer) { if (!element) { element = composer.doc.createElement(options.nodeName || defaultNodeName(composer)); // Add invisible space as otherwise webkit cannot set selection or range to it correctly element.appendChild(composer.doc.createTextNode(wysihtml.INVISIBLE_SPACE)); } if (options.nodeName && element.nodeName !== options.nodeName) { element = dom.renameElement(element, options.nodeName); } // Remove similar classes before applying className if (options.classRegExp) { element.className = element.className.replace(options.classRegExp, ""); } if (options.className) { element.classList.add(options.className); } if (options.styleProperty && typeof options.styleValue !== "undefined") { element.style[wysihtml.browser.fixStyleKey(options.styleProperty)] = options.styleValue; } return element; } // Unsets element properties by options // If nodename given and matches current element, element is unwrapped or converted to default node (depending on presence of class and style attributes) function removeOptionsFromElement(element, options, composer) { var style, classes, prevNode = element.previousSibling, nextNode = element.nextSibling, unwrapped = false; if (options.styleProperty) { element.style[wysihtml.browser.fixStyleKey(options.styleProperty)] = ''; } if (options.className) { element.classList.remove(options.className); } if (options.classRegExp) { element.className = element.className.replace(options.classRegExp, ""); } // Clean up blank class attribute if (element.getAttribute('class') !== null && element.getAttribute('class').trim() === "") { element.removeAttribute('class'); } if (options.nodeName && element.nodeName.toLowerCase() === options.nodeName.toLowerCase()) { style = element.getAttribute('style'); if (!style || style.trim() === '') { dom.unwrap(element); unwrapped = true; } else { element = dom.renameElement(element, defaultNodeName(composer)); } } // Clean up blank style attribute if (element.getAttribute('style') !== null && element.getAttribute('style').trim() === "") { element.removeAttribute('style'); } if (unwrapped) { applySurroundingLineBreaks(prevNode, nextNode, composer); } } // Unwraps block level elements from inside content // Useful as not all block level elements can contain other block-levels function unwrapBlocksFromContent(element) { var blocks = element.querySelectorAll(BLOCK_ELEMENTS) || [], // Find unnestable block elements in extracted contents nextEl, prevEl; for (var i = blocks.length; i--;) { nextEl = wysihtml.dom.domNode(blocks[i]).next({nodeTypes: [1,3], ignoreBlankTexts: true}), prevEl = wysihtml.dom.domNode(blocks[i]).prev({nodeTypes: [1,3], ignoreBlankTexts: true}); if (nextEl && nextEl.nodeType !== 1 && nextEl.nodeName !== 'BR') { if ((blocks[i].innerHTML || blocks[i].nodeValue || '').trim() !== '') { blocks[i].parentNode.insertBefore(blocks[i].ownerDocument.createElement('BR'), nextEl); } } if (nextEl && nextEl.nodeType !== 1 && nextEl.nodeName !== 'BR') { if ((blocks[i].innerHTML || blocks[i].nodeValue || '').trim() !== '') { blocks[i].parentNode.insertBefore(blocks[i].ownerDocument.createElement('BR'), nextEl); } } wysihtml.dom.unwrap(blocks[i]); } } // Fix ranges that visually cover whole block element to actually cover the block function fixRangeCoverage(range, composer) { var node, start = range.startContainer, end = range.endContainer; // If range has only one childNode and it is end to end the range, extend the range to contain the container element too // This ensures the wrapper node is modified and optios added to it if (start && start.nodeType === 1 && start === end) { if (start.firstChild === start.lastChild && range.endOffset === 1) { if (start !== composer.element && start.nodeName !== 'LI' && start.nodeName !== 'TD') { range.setStartBefore(start); range.setEndAfter(end); } } return; } // If range starts outside of node and ends inside at textrange and covers the whole node visually, extend end to cover the node end too if (start && start.nodeType === 1 && end.nodeType === 3) { if (start.firstChild === end && range.endOffset === end.data.length) { if (start !== composer.element && start.nodeName !== 'LI' && start.nodeName !== 'TD') { range.setEndAfter(start); } } return; } // If range ends outside of node and starts inside at textrange and covers the whole node visually, extend start to cover the node start too if (end && end.nodeType === 1 && start.nodeType === 3) { if (end.firstChild === start && range.startOffset === 0) { if (end !== composer.element && end.nodeName !== 'LI' && end.nodeName !== 'TD') { range.setStartBefore(end); } } return; } // If range covers a whole textnode and the textnode is the only child of node, extend range to node if (start && start.nodeType === 3 && start === end && start.parentNode.childNodes.length === 1) { if (range.endOffset == end.data.length && range.startOffset === 0) { node = start.parentNode; if (node !== composer.element && node.nodeName !== 'LI' && node.nodeName !== 'TD') { range.setStartBefore(node); range.setEndAfter(node); } } return; } } // Scans ranges array for insertion points that are not allowed to insert block tags fixes/splits illegal ranges // Some places do not allow block level elements inbetween (inside ul and outside li) // TODO: might need extending for other nodes besides li (maybe dd,dl,dt) function fixNotPermittedInsertionPoints(ranges) { var newRanges = [], lis, j, maxj, tmpRange, rangePos, closestLI; for (var i = 0, maxi = ranges.length; i < maxi; i++) { // Fixes range start and end positions if inside UL or OL element (outside of LI) if (ranges[i].startContainer.nodeType === 1 && ranges[i].startContainer.matches('ul, ol')) { ranges[i].setStart(ranges[i].startContainer.childNodes[ranges[i].startOffset], 0); } if (ranges[i].endContainer.nodeType === 1 && ranges[i].endContainer.matches('ul, ol')) { closestLI = ranges[i].endContainer.childNodes[Math.max(ranges[i].endOffset - 1, 0)]; if (closestLI.childNodes) { ranges[i].setEnd(closestLI, closestLI.childNodes.length); } } // Get all LI eleemnts in selection (fully or partially covered) // And make sure ranges are either inside LI or outside UL/OL // Split and add new ranges as needed to cover same range content // TODO: Needs improvement to accept DL, DD, DT lis = ranges[i].getNodes([1], function(node) { return node.nodeName === "LI"; }); if (lis.length > 0) { for (j = 0, maxj = lis.length; j < maxj; j++) { rangePos = ranges[i].compareNode(lis[j]); // Fixes start of range that crosses LI border if (rangePos === ranges[i].NODE_AFTER || rangePos === ranges[i].NODE_INSIDE) { // Range starts before and ends inside the node tmpRange = ranges[i].cloneRange(); closestLI = wysihtml.dom.domNode(lis[j]).prev({nodeTypes: [1]}); if (closestLI) { tmpRange.setEnd(closestLI, closestLI.childNodes.length); } else if (lis[j].closest('ul, ol')) { tmpRange.setEndBefore(lis[j].closest('ul, ol')); } else { tmpRange.setEndBefore(lis[j]); } newRanges.push(tmpRange); ranges[i].setStart(lis[j], 0); } // Fixes end of range that crosses li border if (rangePos === ranges[i].NODE_BEFORE || rangePos === ranges[i].NODE_INSIDE) { // Range starts inside the node and ends after node tmpRange = ranges[i].cloneRange(); tmpRange.setEnd(lis[j], lis[j].childNodes.length); newRanges.push(tmpRange); // Find next LI in list and if present set range to it, else closestLI = wysihtml.dom.domNode(lis[j]).next({nodeTypes: [1]}); if (closestLI) { ranges[i].setStart(closestLI, 0); } else if (lis[j].closest('ul, ol')) { ranges[i].setStartAfter(lis[j].closest('ul, ol')); } else { ranges[i].setStartAfter(lis[j]); } } } newRanges.push(ranges[i]); } else { newRanges.push(ranges[i]); } } return newRanges; } // Return options object with nodeName set if original did not have any // Node name is set to local or global default function getOptionsWithNodename(options, defaultName, composer) { var correctedOptions = (options) ? wysihtml.lang.object(options).clone(true) : null; if (correctedOptions) { correctedOptions.nodeName = correctedOptions.nodeName || defaultName || defaultNodeName(composer); } return correctedOptions; } // Injects document fragment to range ensuring outer elements are split to a place where block elements are allowed to be inserted // Also wraps empty clones of split parent tags around fragment to keep formatting // If firstOuterBlock is given assume that instead of finding outer (useful for solving cases of some blocks are allowed into others while others are not) function injectFragmentToRange(fragment, range, composer, firstOuterBlock) { var rangeStartContainer = range.startContainer, firstOuterBlock = firstOuterBlock || findOuterBlock(rangeStartContainer, composer.element, true), outerInlines, first, last, prev, next; if (firstOuterBlock) { // If selection starts inside un-nestable block, split-escape the unnestable point and insert node between first = fragment.firstChild; last = fragment.lastChild; composer.selection.splitElementAtCaret(firstOuterBlock, fragment); next = wysihtml.dom.domNode(last).next({nodeTypes: [1,3], ignoreBlankTexts: true}); prev = wysihtml.dom.domNode(first).prev({nodeTypes: [1,3], ignoreBlankTexts: true}); if (first && !isLineBreaking(first, composer) && prev && !isLineBreaking(prev, composer)) { first.parentNode.insertBefore(composer.doc.createElement('br'), first); } if (last && !isLineBreaking(last, composer) && next && !isLineBreaking(next, composer)) { next.parentNode.insertBefore(composer.doc.createElement('br'), next); } } else { // Ensure node does not get inserted into an inline where it is not allowed outerInlines = cloneOuterInlines(rangeStartContainer, composer.element); if (outerInlines.outerNode && outerInlines.innerNode && outerInlines.parent) { if (fragment.childNodes.length === 1) { while(fragment.firstChild.firstChild) { outerInlines.innerNode.appendChild(fragment.firstChild.firstChild); } fragment.firstChild.appendChild(outerInlines.outerNode); } composer.selection.splitElementAtCaret(outerInlines.parent, fragment); } else { var fc = fragment.firstChild, lc = fragment.lastChild; range.insertNode(fragment); // restore range position as it might get lost in webkit sometimes range.setStartBefore(fc); range.setEndAfter(lc); } } } // Removes all block formatting from range function clearRangeBlockFromating(range, closestBlockName, composer) { var r = range.cloneRange(), prevNode = getRangeNode(r.startContainer, r.startOffset).previousSibling, nextNode = getRangeNode(r.endContainer, r.endOffset).nextSibling, content = r.extractContents(), fragment = composer.doc.createDocumentFragment(), children, blocks, first = true; while(content.firstChild) { // Iterate over all selection content first level childNodes if (content.firstChild.nodeType === 1 && content.firstChild.matches(BLOCK_ELEMENTS)) { // If node is a block element // Split block formating and add new block to wrap caret unwrapBlocksFromContent(content.firstChild); children = wysihtml.dom.unwrap(content.firstChild); // Add line break before if needed if (children.length > 0) { if ( (fragment.lastChild && (fragment.lastChild.nodeType !== 1 || !isLineBreaking(fragment.lastChild, composer))) || (!fragment.lastChild && prevNode && (prevNode.nodeType !== 1 || isLineBreaking(prevNode, composer))) ){ fragment.appendChild(composer.doc.createElement('BR')); } } for (var c = 0, cmax = children.length; c < cmax; c++) { fragment.appendChild(children[c]); } // Add line break after if needed if (children.length > 0) { if (fragment.lastChild.nodeType !== 1 || !isLineBreaking(fragment.lastChild, composer)) { if (nextNode || fragment.lastChild !== content.lastChild) { fragment.appendChild(composer.doc.createElement('BR')); } } } } else { fragment.appendChild(content.firstChild); } first = false; } blocks = wysihtml.lang.array(fragment.childNodes).get(); injectFragmentToRange(fragment, r, composer); return blocks; } // When block node is inserted, look surrounding nodes and remove surplous linebreak tags (as block format breaks line itself) function removeSurroundingLineBreaks(prevNode, nextNode, composer) { var prevPrev = prevNode && wysihtml.dom.domNode(prevNode).prev({nodeTypes: [1,3], ignoreBlankTexts: true}); if (isBr(nextNode)) { nextNode.parentNode.removeChild(nextNode); } if (isBr(prevNode) && (!prevPrev || prevPrev.nodeType !== 1 || composer.win.getComputedStyle(prevPrev).display !== "block")) { prevNode.parentNode.removeChild(prevNode); } } function applySurroundingLineBreaks(prevNode, nextNode, composer) { var prevPrev; if (prevNode && isBookmark(prevNode)) { prevNode = prevNode.previousSibling; } if (nextNode && isBookmark(nextNode)) { nextNode = nextNode.nextSibling; } prevPrev = prevNode && prevNode.previousSibling; if (prevNode && (prevNode.nodeType !== 1 || (composer.win.getComputedStyle(prevNode).display !== "block" && !isBr(prevNode))) && prevNode.parentNode) { prevNode.parentNode.insertBefore(composer.doc.createElement('br'), prevNode.nextSibling); } if (nextNode && (nextNode.nodeType !== 1 || composer.win.getComputedStyle(nextNode).display !== "block") && nextNode.parentNode) { nextNode.parentNode.insertBefore(composer.doc.createElement('br'), nextNode); } } var isWhitespaceBefore = function (textNode, offset) { var str = textNode.data ? textNode.data.slice(0, offset) : ""; return (/^\s*$/).test(str); } var isWhitespaceAfter = function (textNode, offset) { var str = textNode.data ? textNode.data.slice(offset) : ""; return (/^\s*$/).test(str); } var trimBlankTextsAndBreaks = function(fragment) { if (fragment) { while (fragment.firstChild && fragment.firstChild.nodeType === 3 && (/^\s*$/).test(fragment.firstChild.data) && fragment.lastChild !== fragment.firstChild) { fragment.removeChild(fragment.firstChild); } while (fragment.lastChild && fragment.lastChild.nodeType === 3 && (/^\s*$/).test(fragment.lastChild.data) && fragment.lastChild !== fragment.firstChild) { fragment.removeChild(fragment.lastChild); } if (fragment.firstChild && fragment.firstChild.nodeType === 1 && fragment.firstChild.nodeName === "BR" && fragment.lastChild !== fragment.firstChild) { fragment.removeChild(fragment.firstChild); } if (fragment.lastChild && fragment.lastChild.nodeType === 1 && fragment.lastChild.nodeName === "BR" && fragment.lastChild !== fragment.firstChild) { fragment.removeChild(fragment.lastChild); } } } // Wrap the range with a block level element // If element is one of unnestable block elements (ex: h2 inside h1), split nodes and insert between so nesting does not occur function wrapRangeWithElement(range, options, closestBlockName, composer) { var similarOptions = options ? correctOptionsForSimilarityCheck(options) : null, r = range.cloneRange(), rangeStartContainer = r.startContainer, startNode = getRangeNode(r.startContainer, r.startOffset), endNode = getRangeNode(r.endContainer, r.endOffset), prevNode = (r.startContainer === startNode && startNode.nodeType === 3 && !isWhitespaceBefore(startNode, r.startOffset)) ? startNode : wysihtml.dom.domNode(startNode).prev({nodeTypes: [1,3], ignoreBlankTexts: true}), nextNode = ( ( r.endContainer.nodeType === 1 && r.endContainer.childNodes[r.endOffset] === endNode && ( endNode.nodeType === 1 || !isWhitespaceAfter(endNode, r.endOffset) && !wysihtml.dom.domNode(endNode).is.rangyBookmark() ) ) || ( r.endContainer === endNode && endNode.nodeType === 3 && !isWhitespaceAfter(endNode, r.endOffset) ) ) ? endNode : wysihtml.dom.domNode(endNode).next({nodeTypes: [1,3], ignoreBlankTexts: true}), content = r.extractContents(), fragment = composer.doc.createDocumentFragment(), similarOuterBlock = similarOptions ? wysihtml.dom.getParentElement(rangeStartContainer, similarOptions, null, composer.element) : null, splitAllBlocks = !closestBlockName || !options || (options.nodeName === "BLOCKQUOTE" && closestBlockName === "BLOCKQUOTE"), firstOuterBlock = similarOuterBlock || findOuterBlock(rangeStartContainer, composer.element, splitAllBlocks), // The outermost un-nestable block element parent of selection start wrapper, blocks, children, firstc, lastC; if (wysihtml.dom.domNode(nextNode).is.rangyBookmark()) { endNode = nextNode; nextNode = endNode.nextSibling; } trimBlankTextsAndBreaks(content); if (options && options.nodeName === "BLOCKQUOTE") { // If blockquote is to be inserted no quessing just add it as outermost block on line or selection var tmpEl = applyOptionsToElement(null, options, composer); tmpEl.appendChild(content); fragment.appendChild(tmpEl); blocks = [tmpEl]; } else { if (!content.firstChild) { // IF selection is caret (can happen if line is empty) add format around tag fragment.appendChild(applyOptionsToElement(null, options, composer)); } else { while(content.firstChild) { // Iterate over all selection content first level childNodes if (content.firstChild.nodeType == 1 && content.firstChild.matches(BLOCK_ELEMENTS)) { // If node is a block element // Escape(split) block formatting at caret applyOptionsToElement(content.firstChild, options, composer); if (content.firstChild.matches(UNNESTABLE_BLOCK_ELEMENTS)) { unwrapBlocksFromContent(content.firstChild); } fragment.appendChild(content.firstChild); } else { // Wrap subsequent non-block nodes inside new block element wrapper = applyOptionsToElement(null, getOptionsWithNodename(options, closestBlockName, composer), composer); while(content.firstChild && (content.firstChild.nodeType !== 1 || !content.firstChild.matches(BLOCK_ELEMENTS))) { if (content.firstChild.nodeType == 1 && wrapper.matches(UNNESTABLE_BLOCK_ELEMENTS)) { unwrapBlocksFromContent(content.firstChild); } wrapper.appendChild(content.firstChild); } fragment.appendChild(wrapper); } } } blocks = wysihtml.lang.array(fragment.childNodes).get(); } injectFragmentToRange(fragment, r, composer, firstOuterBlock); removeSurroundingLineBreaks(prevNode, nextNode, composer); // Fix webkit madness by inserting linebreak rangy after cursor marker to blank last block // (if it contains rangy bookmark, so selection can be restored later correctly) if (blocks.length > 0 && ( typeof blocks[blocks.length - 1].lastChild === "undefined" || wysihtml.dom.domNode(blocks[blocks.length - 1].lastChild).is.rangyBookmark() ) ) { blocks[blocks.length - 1].appendChild(composer.doc.createElement('br')); } return blocks; } // Find closest block level element function getParentBlockNodeName(element, composer) { var parentNode = wysihtml.dom.getParentElement(element, { query: BLOCK_ELEMENTS }, null, composer.element); return (parentNode) ? parentNode.nodeName : null; } // Expands caret to cover the closest block that: // * cannot contain other block level elements (h1-6,p, etc) // * Has the same nodeName that is to be inserted // * has insertingNodeName // * is DIV if insertingNodeName is not present // // If nothing found selects the current line function expandCaretToBlock(composer, insertingNodeName) { var parent = wysihtml.dom.getParentElement(composer.selection.getOwnRanges()[0].startContainer, { query: UNNESTABLE_BLOCK_ELEMENTS + ', ' + (insertingNodeName ? insertingNodeName.toLowerCase() : 'div'), }, null, composer.element), range; if (parent) { range = composer.selection.createRange(); range.selectNode(parent); composer.selection.setSelection(range); } else if (!composer.isEmpty()) { composer.selection.selectLine(); } } // Set selection to begin inside first created block element (beginning of it) and end inside (and after content) of last block element // TODO: Checking nodetype might be unnescescary as nodes inserted by formatBlock are nodetype 1 anyway function selectElements(newBlockElements, composer) { var range = composer.selection.createRange(), lastEl = newBlockElements[newBlockElements.length - 1], lastOffset = (lastEl.nodeType === 1 && lastEl.childNodes) ? lastEl.childNodes.length | 0 : lastEl.length || 0; range.setStart(newBlockElements[0], 0); range.setEnd(lastEl, lastOffset); range.select(); } // Get all ranges from selection (takes out uneditables and out of editor parts) and apply format to each // Return created/modified block level elements // Method can be either "apply" or "remove" function formatSelection(method, composer, options) { var ranges = composer.selection.getOwnRanges(), newBlockElements = [], closestBlockName; // Some places do not allow block level elements inbetween (inside ul and outside li, inside table and outside of td/th) ranges = fixNotPermittedInsertionPoints(ranges); for (var i = ranges.length; i--;) { fixRangeCoverage(ranges[i], composer); closestBlockName = getParentBlockNodeName(ranges[i].startContainer, composer); if (method === "remove") { newBlockElements = newBlockElements.concat(clearRangeBlockFromating(ranges[i], closestBlockName, composer)); } else { newBlockElements = newBlockElements.concat(wrapRangeWithElement(ranges[i], options, closestBlockName, composer)); } } return newBlockElements; } // If properties is passed as a string, look for tag with that tagName/query function parseOptions(options) { if (typeof options === "string") { options = { nodeName: options.toUpperCase() }; } return options; } function caretIsOnEmptyLine(composer) { var caretInfo; if (composer.selection.isCollapsed()) { caretInfo = composer.selection.getNodesNearCaret(); if (caretInfo && caretInfo.caretNode) { if ( // caret is allready breaknode wysihtml.dom.domNode(caretInfo.caretNode).is.lineBreak() || // caret is textnode (caretInfo.caretNode.nodeType === 3 && caretInfo.textOffset === 0 && (!caretInfo.prevNode || wysihtml.dom.domNode(caretInfo.prevNode).is.lineBreak())) || // Caret is temprorary rangy selection marker (caretInfo.caretNode.nodeType === 1 && caretInfo.caretNode.classList.contains('rangySelectionBoundary') && (!caretInfo.prevNode || wysihtml.dom.domNode(caretInfo.prevNode).is.lineBreak() || wysihtml.dom.domNode(caretInfo.prevNode).is.block()) && (!caretInfo.nextNode || wysihtml.dom.domNode(caretInfo.nextNode).is.lineBreak() || wysihtml.dom.domNode(caretInfo.nextNode).is.block()) ) ) { return true; } } } return false; } wysihtml.commands.formatBlock = { exec: function(composer, command, options) { options = parseOptions(options); var newBlockElements = [], ranges, range, bookmark, state, closestBlockName; // Find if current format state is active if options.toggle is set as true // In toggle case active state elemets are formatted instead of working directly on selection if (options && options.toggle) { state = this.state(composer, command, options); } if (state) { // Remove format from state nodes if toggle set and state on and selection is collapsed bookmark = rangy.saveSelection(composer.win); for (var j = 0, jmax = state.length; j < jmax; j++) { removeOptionsFromElement(state[j], options, composer); } } else { // If selection is caret expand it to cover nearest suitable block element or row if none found if (composer.selection.isCollapsed()) { bookmark = rangy.saveSelection(composer.win); if (caretIsOnEmptyLine(composer)) { composer.selection.selectLine(); } else { expandCaretToBlock(composer, options && options.nodeName ? options.nodeName.toUpperCase() : undefined); } } if (options) { newBlockElements = formatSelection("apply", composer, options); } else { // Options == null means block formatting should be removed from selection newBlockElements = formatSelection("remove", composer); } } // Remove empty block elements that may be left behind // Also remove them from new blocks list newBlockElements = cleanup(composer, newBlockElements); // Restore selection if (bookmark) { rangy.restoreSelection(bookmark); } else { selectElements(newBlockElements, composer); } }, // Removes all block formatting from selection remove: function(composer, command, options) { options = parseOptions(options); var newBlockElements, bookmark; // If selection is caret expand it to cover nearest suitable block element or row if none found if (composer.selection.isCollapsed()) { bookmark = rangy.saveSelection(composer.win); expandCaretToBlock(composer, options && options.nodeName ? options.nodeName.toUpperCase() : undefined); } newBlockElements = formatSelection("remove", composer); newBlockElements = cleanup(composer, newBlockElements); // Restore selection if (bookmark) { rangy.restoreSelection(bookmark); } else { selectElements(newBlockElements, composer); } }, // If options as null is passed returns status describing all block level elements state: function(composer, command, options) { options = parseOptions(options); var nodes = composer.selection.filterElements((function (element) { // Finds matching elements inside selection return wysihtml.dom.domNode(element).test(options || { query: BLOCK_ELEMENTS }); }).bind(this)), parentNodes = composer.selection.getSelectedOwnNodes(), parent; // Finds matching elements that are parents of selection and adds to nodes list for (var i = 0, maxi = parentNodes.length; i < maxi; i++) { parent = dom.getParentElement(parentNodes[i], options || { query: BLOCK_ELEMENTS }, null, composer.element); if (parent && nodes.indexOf(parent) === -1) { nodes.push(parent); } } return (nodes.length === 0) ? false : nodes; } }; })(wysihtml);
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M12.5 10c0-1.65-1.35-3-3-3s-3 1.35-3 3 1.35 3 3 3 3-1.35 3-3zm-3 1c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zM16 13c1.11 0 2-.89 2-2 0-1.11-.89-2-2-2-1.11 0-2.01.89-2 2 0 1.11.89 2 2 2z" /><path d="M11.99 2.01c-5.52 0-10 4.48-10 10s4.48 10 10 10 10-4.48 10-10-4.48-10-10-10zM5.84 17.12c.68-.54 2.27-1.11 3.66-1.11.07 0 .15.01.23.01.24-.64.67-1.29 1.3-1.86-.56-.1-1.09-.16-1.53-.16-1.3 0-3.39.45-4.73 1.43-.5-1.04-.78-2.2-.78-3.43 0-4.41 3.59-8 8-8s8 3.59 8 8c0 1.2-.27 2.34-.75 3.37-1-.59-2.36-.87-3.24-.87-1.52 0-4.5.81-4.5 2.7v2.78c-2.27-.13-4.29-1.21-5.66-2.86z" /></React.Fragment> , 'SupervisedUserCircleOutlined');
System.register([], function($__export) { "use strict"; var testUtil, benchpress; function runClickBenchmark(config) { var buttons = config.buttons.map(function(selector) { return $(selector); }); config.work = function() { buttons.forEach(function(button) { button.click(); }); }; return runBenchmark(config); } function runBenchmark(config) { return getScaleFactor(browser.params.benchmark.scaling).then(function(scaleFactor) { var description = {}; var urlParams = []; var microIterations = config.microIterations || 0; var params = config.params || []; if (microIterations) { params = params.concat([{ name: 'iterations', value: microIterations, scale: 'linear' }]); } params.forEach(function(param) { var name = param.name; var value = applyScaleFactor(param.value, scaleFactor, param.scale); urlParams.push(name + '=' + value); description[name] = value; }); var url = encodeURI(config.url + '?' + urlParams.join('&')); browser.get(url); return benchpressRunner.sample({ id: config.id, execute: config.work, prepare: config.prepare, microIterations: microIterations, bindings: [benchpress.bind(benchpress.Options.SAMPLE_DESCRIPTION).toValue(description)] }); }); } function getScaleFactor(possibleScalings) { return browser.executeScript('return navigator.userAgent').then(function(userAgent) { var scaleFactor = 1; possibleScalings.forEach(function(entry) { if (userAgent.match(entry.userAgent)) { scaleFactor = entry.value; } }); return scaleFactor; }); } function applyScaleFactor(value, scaleFactor, method) { if (method === 'log2') { return value + Math.log2(scaleFactor); } else if (method === 'sqrt') { return value * Math.sqrt(scaleFactor); } else if (method === 'linear') { return value * scaleFactor; } else { return value; } } return { setters: [], execute: function() { testUtil = require('./e2e_util'); benchpress = require('benchpress/benchpress'); module.exports = { runClickBenchmark: runClickBenchmark, runBenchmark: runBenchmark, verifyNoBrowserErrors: testUtil.verifyNoBrowserErrors }; } }; }); //# sourceMappingURL=src/test_lib/perf_util.map //# sourceMappingURL=../../src/test_lib/perf_util.js.map
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S9.3.1_A15; * @section: 9.3.1, 15.7.1; * @assertion: The MV of SignedInteger ::: - DecimalDigits is the negative of the MV of DecimalDigits; * @description: Compare -Number('1234567890') with ('-1234567890'); */ // CHECK#1 if (+("-1234567890") !== -Number("1234567890")) { $ERROR('#1: +("-1234567890") === -Number("1234567890")'); }
'use strict'; const assert = require('./../../assert'); const common = require('./../../common'); let battle; describe('Desolate Land', function () { afterEach(function () { battle.destroy(); }); it('should activate the Desolate Land weather upon switch-in', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Groudon", ability: 'desolateland', moves: ['helpinghand']}]}); battle.setPlayer('p2', {team: [{species: "Abra", ability: 'magicguard', moves: ['teleport']}]}); assert.ok(battle.field.isWeather('desolateland')); }); it('should increase the damage (not the basePower) of Fire-type attacks', function () { battle = common.createBattle(); battle.randomizer = dmg => dmg; // max damage battle.setPlayer('p1', {team: [{species: 'Ninetales', ability: 'desolateland', moves: ['incinerate']}]}); battle.setPlayer('p2', {team: [{species: 'Cryogonal', ability: 'levitate', moves: ['splash']}]}); const attacker = battle.p1.active[0]; const defender = battle.p2.active[0]; assert.hurtsBy(defender, 152, () => battle.makeChoices('move incinerate', 'move splash')); const move = Dex.getMove('incinerate'); const basePower = battle.runEvent('BasePower', attacker, defender, move, move.basePower, true); assert.strictEqual(basePower, move.basePower); }); it('should cause Water-type attacks to fail', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Groudon", ability: 'desolateland', moves: ['helpinghand']}]}); battle.setPlayer('p2', {team: [{species: "Blastoise", ability: 'torrent', moves: ['surf']}]}); battle.makeChoices('move helpinghand', 'move surf'); assert.fullHP(battle.p1.active[0]); }); it('should not cause Water-type Status moves to fail', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Groudon", ability: 'desolateland', moves: ['helpinghand']}]}); battle.setPlayer('p2', {team: [{species: "Blastoise", ability: 'torrent', moves: ['soak']}]}); const soakTarget = battle.p1.active[0]; assert.sets(() => soakTarget.getTypes().join('/'), 'Water', () => battle.makeChoices('move helpinghand', 'move soak')); }); it('should prevent moves and abilities from setting the weather to Sunny Day, Rain Dance, Sandstorm, or Hail', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Groudon", ability: 'desolateland', moves: ['helpinghand']}]}); battle.setPlayer('p2', {team: [ {species: "Abra", ability: 'magicguard', moves: ['teleport']}, {species: "Kyogre", ability: 'drizzle', moves: ['raindance']}, {species: "Groudon", ability: 'drought', moves: ['sunnyday']}, {species: "Tyranitar", ability: 'sandstream', moves: ['sandstorm']}, {species: "Abomasnow", ability: 'snowwarning', moves: ['hail']}, ]}); for (let i = 2; i <= 5; i++) { battle.makeChoices('move helpinghand', 'switch ' + i); assert.ok(battle.field.isWeather('desolateland')); battle.makeChoices('move helpinghand', 'move 1'); assert.ok(battle.field.isWeather('desolateland')); } }); it('should be treated as Sunny Day for any forme, move or ability that requires it', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Groudon", ability: 'desolateland', moves: ['helpinghand', 'solarbeam']}]}); battle.setPlayer('p2', {team: [ {species: "Castform", ability: 'forecast', moves: ['weatherball']}, {species: "Cherrim", ability: 'flowergift', moves: ['growth']}, {species: "Charizard", ability: 'solarpower', moves: ['roost']}, {species: "Venusaur", ability: 'chlorophyll', moves: ['growth']}, {species: "Toxicroak", ability: 'dryskin', moves: ['bulkup']}, ]}); battle.onEvent('Hit', battle.format, (target, pokemon, move) => { if (move.id === 'weatherball') { assert.strictEqual(move.type, 'Fire'); } }); const myActive = battle.p2.active; battle.makeChoices('move helpinghand', 'move weatherball'); assert.species(myActive[0], 'Castform-Sunny'); battle.makeChoices('move helpinghand', 'switch 2'); assert.species(myActive[0], 'Cherrim-Sunshine'); battle.makeChoices('move helpinghand', 'switch 3'); assert.false.fullHP(myActive[0], "Charizard should be hurt by Solar Power"); battle.makeChoices('move solarbeam', 'switch 4'); assert.strictEqual(myActive[0].getStat('spe'), 2 * myActive[0].storedStats['spe'], "Venusaur's speed should be doubled by Chlorophyll"); assert.false.fullHP(myActive[0], "Solar Beam should skip its charge turn"); battle.makeChoices('move helpinghand', 'switch 5'); assert.false.fullHP(myActive[0], "Toxicroak should be hurt by Dry Skin"); }); it('should cause the Desolate Land weather to fade if it switches out and no other Desolate Land Pokemon are active', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [ {species: "Groudon", ability: 'desolateland', moves: ['helpinghand']}, {species: "Ho-Oh", ability: 'pressure', moves: ['roost']}, ]}); battle.setPlayer('p2', {team: [{species: "Lugia", ability: 'pressure', moves: ['roost']}]}); assert.sets(() => battle.field.isWeather('desolateland'), false, () => battle.makeChoices('switch 2', 'move roost')); }); it('should not cause the Desolate Land weather to fade if it switches out and another Desolate Land Pokemon is active', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [ {species: "Groudon", ability: 'desolateland', moves: ['helpinghand']}, {species: "Ho-Oh", ability: 'pressure', moves: ['roost']}, ]}); battle.setPlayer('p2', {team: [{species: "Groudon", ability: 'desolateland', moves: ['bulkup']}]}); assert.constant(() => battle.field.isWeather('desolateland'), () => battle.makeChoices('switch 2', 'move bulkup')); }); it('should cause the Desolate Land weather to fade if its ability is suppressed and no other Desolate Land Pokemon are active', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Groudon", ability: 'desolateland', moves: ['helpinghand']}]}); battle.setPlayer('p2', {team: [{species: "Lugia", ability: 'pressure', moves: ['gastroacid']}]}); assert.sets(() => battle.field.isWeather('desolateland'), false, () => battle.makeChoices('move helpinghand', 'move gastroacid')); }); it('should not cause the Desolate Land weather to fade if its ability is suppressed and another Desolate Land Pokemon is active', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Groudon", ability: 'desolateland', moves: ['helpinghand']}]}); battle.setPlayer('p2', {team: [{species: "Groudon", ability: 'desolateland', moves: ['gastroacid']}]}); assert.constant(() => battle.field.isWeather('desolateland'), () => battle.makeChoices('move helpinghand', 'move gastroacid')); }); it('should cause the Desolate Land weather to fade if its ability is changed and no other Desolate Land Pokemon are active', function () { battle = common.createBattle(); battle.setPlayer('p1', {team: [{species: "Groudon", ability: 'desolateland', moves: ['helpinghand']}]}); battle.setPlayer('p2', {team: [{species: "Lugia", ability: 'pressure', moves: ['entrainment']}]}); assert.sets(() => battle.field.isWeather('desolateland'), false, () => battle.makeChoices('move helpinghand', 'move entrainment')); }); });
'use strict'; describe('Controller: ExploreRebirthDetailCtrl', function () { // load the controller's module beforeEach(module('tbsApp')); var ExploreRebirthDetailCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); ExploreRebirthDetailCtrl = $controller('ExploreRebirthDetailCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
/* global window, document */ export default function (id, config = {}) { gtag('js', new Date()); gtag('config', id, config); // https://developers.google.com/analytics/devguides/collection/gtagjs/ getScript(`https://www.googletagmanager.com/gtag/js?id=${id}`); } export function gtag() { let {dataLayer} = window; if (!dataLayer) { dataLayer = window.dataLayer = []; } dataLayer.push(arguments); } export function getScript(src) { const script = document.createElement('script'); script.src = src; script.async = true; document.head.appendChild(script); }
'use strict'; function regist() { var form = document.getElementById('regForm'); var inputs = document.getElementsByClassName('registration__input'); form.addEventListener('submit', submitForm); Array.prototype.forEach.call(inputs, function(input) { input.addEventListener('change', checkValidation); }); function submitForm(e) { e.preventDefault(); var formInputStates = []; var formData = {}; //collect states of all inputs in formInputStates array Array.prototype.forEach.call(inputs, function(input) { var state = checkValidation(input); formInputStates.push(state); //collect values to formData object formData[convertType(input.type)] = input.value; }); //if every input is valid - set general formState equals true var formState = Array.prototype.every.call(formInputStates, function(item) { return item == true; }); //send formData if all items are valid if (formState) { pushData(formData); clearInputs(inputs); } } function pushData(data) { var regWrap = document.getElementById('registration'); var json = JSON.stringify(data); var request = new XMLHttpRequest(); request.open('post', '/', true); request.setRequestHeader('Content-Type', 'application/json'); request.onreadystatechange = function() { if (request.readyState == 4 && request.status == 200) { regWrap.innerHTML = '<div class="regist-resp">' + request.responseText + '</div>'; } if (request.status == 500) { regWrap.innerHTML = '<div class="regist-resp">Registration failed...</div>'; } } request.send(json); } function clearInputs(items) { Array.prototype.forEach.call(items, function(item) { item.value = ''; }); } //collector of existing error messages var errors = {}; function checkValidation(e) { var input = e.target || e; var label = input.nextSibling; var errorSpan = label.nextSibling; var emptyInpErr = 'This field is required'; //store original if (errorSpan.innerHTML !== emptyInpErr) { errors[input.id] = errorSpan.innerHTML; } var bool = isValid(input); if (bool) { errorSpan.classList.add('invisible'); input.classList.remove('registration__input--invalid'); label.classList.remove('registration__input--invalid'); } else { if (!input.value) { errorSpan.innerHTML = emptyInpErr; } else { errorSpan.innerHTML = errors[input.id]; } errorSpan.classList.remove('invisible'); input.classList.add('registration__input--invalid'); label.classList.add('registration__input--invalid'); } return bool; } function isValid(input) { var type = input.getAttribute('type'); var patterns = { tel:/^([0-9\(\)\/\+ \-]{3,20})$/, email: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*([,;]\s*\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*/, text: /^[a-zA-Z_ -]{3,50}$/ }; var isValid = new RegExp(patterns[type]).test(input.value); return isValid; } function convertType(type) { var convert = { tel: 'Phone', email: 'E-mail', text: 'Name' } return convert[type]; } } module.exports = regist;
/// import editor.js /// import core/browser.js /// import core/dom/dom.js /// import core/dom/dtd.js /// import core/dom/domUtils.js /// import core/dom/Range.js /** * @class UM.dom.Selection Selection类 */ (function () { function getBoundaryInformation (range, start) { var getIndex = domUtils.getNodeIndex range = range.duplicate() range.collapse(start) var parent = range.parentElement() // 如果节点里没有子节点,直接退出 if (!parent.hasChildNodes()) { return {container: parent, offset: 0} } var siblings = parent.children, child, testRange = range.duplicate(), startIndex = 0, endIndex = siblings.length - 1, index = -1, distance while (startIndex <= endIndex) { index = Math.floor((startIndex + endIndex) / 2) child = siblings[index] testRange.moveToElementText(child) var position = testRange.compareEndPoints('StartToStart', range) if (position > 0) { endIndex = index - 1 } else if (position < 0) { startIndex = index + 1 } else { // trace:1043 return {container: parent, offset: getIndex(child)} } } if (index == -1) { testRange.moveToElementText(parent) testRange.setEndPoint('StartToStart', range) distance = testRange.text.replace(/(\r\n|\r)/g, '\n').length siblings = parent.childNodes if (!distance) { child = siblings[siblings.length - 1] return {container: child, offset: child.nodeValue.length} } var i = siblings.length while (distance > 0) { distance -= siblings[ --i ].nodeValue.length } return {container: siblings[i], offset: -distance} } testRange.collapse(position > 0) testRange.setEndPoint(position > 0 ? 'StartToStart' : 'EndToStart', range) distance = testRange.text.replace(/(\r\n|\r)/g, '\n').length if (!distance) { return dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName] ? {container: parent, offset: getIndex(child) + (position > 0 ? 0 : 1)} : {container: child, offset: position > 0 ? 0 : child.childNodes.length} } while (distance > 0) { try { var pre = child child = child[position > 0 ? 'previousSibling' : 'nextSibling'] distance -= child.nodeValue.length } catch (e) { return {container: parent, offset: getIndex(pre)} } } return {container: child, offset: position > 0 ? -distance : child.nodeValue.length + distance} } /** * 将ieRange转换为Range对象 * @param {Range} ieRange ieRange对象 * @param {Range} range Range对象 * @return {Range} range 返回转换后的Range对象 */ function transformIERangeToRange (ieRange, range) { if (ieRange.item) { range.selectNode(ieRange.item(0)) } else { var bi = getBoundaryInformation(ieRange, true) range.setStart(bi.container, bi.offset) if (ieRange.compareEndPoints('StartToEnd', ieRange) != 0) { bi = getBoundaryInformation(ieRange, false) range.setEnd(bi.container, bi.offset) } } return range } /** * 获得ieRange * @param {Selection} sel Selection对象 * @return {ieRange} 得到ieRange */ function _getIERange (sel, txtRange) { var ieRange // ie下有可能报错 try { ieRange = sel.getNative(txtRange).createRange() } catch (e) { return null } var el = ieRange.item ? ieRange.item(0) : ieRange.parentElement() if ((el.ownerDocument || el) === sel.document) { return ieRange } return null } var Selection = dom.Selection = function (doc, body) { var me = this me.document = doc me.body = body if (browser.ie9below) { $(body).on('beforedeactivate', function () { me._bakIERange = me.getIERange() }).on('activate', function () { try { var ieNativRng = _getIERange(me) if ((!ieNativRng || !me.rangeInBody(ieNativRng)) && me._bakIERange) { me._bakIERange.select() } } catch (ex) { } me._bakIERange = null }) } } Selection.prototype = { hasNativeRange: function () { var rng if (!browser.ie || browser.ie9above) { var nativeSel = this.getNative() if (!nativeSel.rangeCount) { return false } rng = nativeSel.getRangeAt(0) } else { rng = _getIERange(this) } return this.rangeInBody(rng) }, /** * 获取原生seleciton对象 * @public * @function * @name UM.dom.Selection.getNative * @return {Selection} 获得selection对象 */ getNative: function (txtRange) { var doc = this.document try { return !doc ? null : browser.ie9below || txtRange ? doc.selection : domUtils.getWindow(doc).getSelection() } catch (e) { return null } }, /** * 获得ieRange * @public * @function * @name UM.dom.Selection.getIERange * @return {ieRange} 返回ie原生的Range */ getIERange: function (txtRange) { var ieRange = _getIERange(this, txtRange) if (!ieRange || !this.rangeInBody(ieRange, txtRange)) { if (this._bakIERange) { return this._bakIERange } } return ieRange }, rangeInBody: function (rng, txtRange) { var node = browser.ie9below || txtRange ? rng.item ? rng.item() : rng.parentElement() : rng.startContainer return node === this.body || domUtils.inDoc(node, this.body) }, /** * 缓存当前选区的range和选区的开始节点 * @public * @function * @name UM.dom.Selection.cache */ cache: function () { this.clear() this._cachedRange = this.getRange() this._cachedStartElement = this.getStart() this._cachedStartElementPath = this.getStartElementPath() }, getStartElementPath: function () { if (this._cachedStartElementPath) { return this._cachedStartElementPath } var start = this.getStart() if (start) { return domUtils.findParents(start, true, null, true) } return [] }, /** * 清空缓存 * @public * @function * @name UM.dom.Selection.clear */ clear: function () { this._cachedStartElementPath = this._cachedRange = this._cachedStartElement = null }, /** * 编辑器是否得到了选区 */ isFocus: function () { return this.hasNativeRange() }, /** * 获取选区对应的Range * @public * @function * @name UM.dom.Selection.getRange * @returns {UM.dom.Range} 得到Range对象 */ getRange: function () { var me = this function optimze (range) { var child = me.body.firstChild, collapsed = range.collapsed while (child && child.firstChild) { range.setStart(child, 0) child = child.firstChild } if (!range.startContainer) { range.setStart(me.body, 0) } if (collapsed) { range.collapse(true) } } if (me._cachedRange != null) { return this._cachedRange } var range = new dom.Range(me.document, me.body) if (browser.ie9below) { var nativeRange = me.getIERange() if (nativeRange && this.rangeInBody(nativeRange)) { try { transformIERangeToRange(nativeRange, range) } catch (e) { optimze(range) } } else { optimze(range) } } else { var sel = me.getNative() if (sel && sel.rangeCount && me.rangeInBody(sel.getRangeAt(0))) { var firstRange = sel.getRangeAt(0) var lastRange = sel.getRangeAt(sel.rangeCount - 1) range.setStart(firstRange.startContainer, firstRange.startOffset).setEnd(lastRange.endContainer, lastRange.endOffset) if (range.collapsed && domUtils.isBody(range.startContainer) && !range.startOffset) { optimze(range) } } else { // trace:1734 有可能已经不在dom树上了,标识的节点 if (this._bakRange && (this._bakRange.startContainer === this.body || domUtils.inDoc(this._bakRange.startContainer, this.body))) { return this._bakRange } optimze(range) } } return this._bakRange = range }, /** * 获取开始元素,用于状态反射 * @public * @function * @name UM.dom.Selection.getStart * @return {Element} 获得开始元素 */ getStart: function () { if (this._cachedStartElement) { return this._cachedStartElement } var range = browser.ie9below ? this.getIERange() : this.getRange(), tmpRange, start, tmp, parent if (browser.ie9below) { if (!range) { // todo 给第一个值可能会有问题 return this.document.body.firstChild } // control元素 if (range.item) { return range.item(0) } tmpRange = range.duplicate() // 修正ie下<b>x</b>[xx] 闭合后 <b>x|</b>xx tmpRange.text.length > 0 && tmpRange.moveStart('character', 1) tmpRange.collapse(1) start = tmpRange.parentElement() parent = tmp = range.parentElement() while (tmp = tmp.parentNode) { if (tmp == start) { start = parent break } } } else { start = range.startContainer if (start.nodeType == 1 && start.hasChildNodes()) { start = start.childNodes[Math.min(start.childNodes.length - 1, range.startOffset)] } if (start.nodeType == 3) { return start.parentNode } } return start }, /** * 得到选区中的文本 * @public * @function * @name UM.dom.Selection.getText * @return {String} 选区中包含的文本 */ getText: function () { var nativeSel, nativeRange if (this.isFocus() && (nativeSel = this.getNative())) { nativeRange = browser.ie9below ? nativeSel.createRange() : nativeSel.getRangeAt(0) return browser.ie9below ? nativeRange.text : nativeRange.toString() } return '' } } })()
'use strict'; var util = require('util'); var path = require('path'); var yeoman = require('yeoman-generator'); var fs = require('fs'); var path = require('path'); var Yui3Generator = module.exports = function Yui3Generator(args, options, config) { yeoman.generators.Base.apply(this, arguments); //TODO : use // - https://github.com/yeoman/generator/wiki/base#baseusage // - https://github.com/yeoman/generator/wiki/base#basedefaultfor // if (args.length < 1) { // this.log.write('Usage : yo yui3 <project_name> [--!config]'); // process.exit(1); // } this.args = args }; util.inherits(Yui3Generator, yeoman.generators.Base); Yui3Generator.prototype.create = function create() { if (this.options["config-file-only"]) { this.projectName = path.basename(process.cwd()) this.copy('.generator-yui3.json','.generator-yui3.json'); this.copy('.generator-yui3.example.json', '.generator-yui3.example.json'); } else { this.projectName = this._.slugify(this.args[0]); var config_file = this._.isUndefined(this.options['no-config']) ? true : !! this.options['no-config'], gitignore = this._.isUndefined(this.options['gitignore']) ? false : !! this.options['gitignore']; if (gitignore && config_file) { this._appendToGitignore(); } this.log.info("Init " + this.projectName + ' scaffold'); this.log.info('init project with' + (config_file ? '' : 'out') + ' config file'); this.mkdir(this.projectName); if (config_file) { this.copy('.generator-yui3.json', this.projectName + '/.generator-yui3.json'); this.copy('.generator-yui3.example.json', this.projectName + '/.generator-yui3.example.json'); } this.mkdir(this.projectName + '/src/' + this.projectName + '-loader'); this.directory('project/src/projectName-loader/scripts', this.projectName + '/src/' + this.projectName + '-loader/scripts'); this.directory('project/src/projectName-loader/template', this.projectName + '/src/' + this.projectName + '-loader/template'); this.mkdir(this.projectName + '/src/' + this.projectName + '-loader/js'); this.copy('project/src/projectName-loader/js/projectName.js', this.projectName + '/src/' + this.projectName + '-loader/js/' + this.projectName + '.js'); this.copy('project/src/projectName-loader/build.json', this.projectName + '/src/' + this.projectName + '-loader/build.json'); } }; Yui3Generator.prototype._appendToGitignore = function() { if (fs.existsSync(path.resolve('./.gitignore'))) { var gitignore = fs.readFileSync(path.resolve('./.gitignore'), { encoding : 'utf-8' }), entries = gitignore.split('\n'); if (!!!~entries.indexOf('.generator-yui3.json')) { entries.push('.generator-yui3.json'); } fs.writeFileSync('.gitignore', entries.join('\n')); this.log.info('.gitignore updated !'); } else { this.log.error('no .gitignore file found..'); } } /** * @method tests * */ Yui3Generator.prototype._loader = function _loader() { this.mkdir(this.projectName + '/src/' + this.projectName + '-loader/tests'); this.mkdir(this.projectName + '/src/' + this.projectName + '-loader/scripts'); this.template("loader/tests/_common.js", this.projectName + '/src/' + this.projectName + '-loader/tests/' +"common.js" ); };
//>>built define("dijit/form/_FormWidgetMixin","dojo/_base/array dojo/_base/declare dojo/dom-attr dojo/dom-style dojo/_base/lang dojo/mouse dojo/on dojo/sniff dojo/window ../a11y".split(" "),function(h,k,c,l,e,p,f,d,m,n){return k("dijit.form._FormWidgetMixin",null,{name:"",alt:"",value:"",type:"text","aria-label":"focusNode",tabIndex:"0",_setTabIndexAttr:"focusNode",disabled:!1,intermediateChanges:!1,scrollOnFocus:!0,_setIdAttr:"focusNode",_setDisabledAttr:function(a){this._set("disabled",a);/^(button|input|select|textarea|optgroup|option|fieldset)$/i.test(this.focusNode.tagName)? c.set(this.focusNode,"disabled",a):this.focusNode.setAttribute("aria-disabled",a?"true":"false");this.valueNode&&c.set(this.valueNode,"disabled",a);a?(this._set("hovering",!1),this._set("active",!1),a="tabIndex"in this.attributeMap?this.attributeMap.tabIndex:"_setTabIndexAttr"in this?this._setTabIndexAttr:"focusNode",h.forEach(e.isArray(a)?a:[a],function(a){a=this[a];d("webkit")||n.hasDefaultTabStop(a)?a.setAttribute("tabIndex","-1"):a.removeAttribute("tabIndex")},this)):""!=this.tabIndex&&this.set("tabIndex", this.tabIndex)},_onFocus:function(a){if("mouse"==a&&this.isFocusable())var b=this.own(f(this.focusNode,"focus",function(){g.remove();b.remove()}))[0],c=d("pointer-events")?"pointerup":d("MSPointer")?"MSPointerUp":d("touch-events")?"touchend, mouseup":"mouseup",g=this.own(f(this.ownerDocumentBody,c,e.hitch(this,function(a){g.remove();b.remove();this.focused&&("touchend"==a.type?this.defer("focus"):this.focus())})))[0];this.scrollOnFocus&&this.defer(function(){m.scrollIntoView(this.domNode)});this.inherited(arguments)}, isFocusable:function(){return!this.disabled&&this.focusNode&&"none"!=l.get(this.domNode,"display")},focus:function(){if(!this.disabled&&this.focusNode.focus)try{this.focusNode.focus()}catch(a){}},compare:function(a,b){return"number"==typeof a&&"number"==typeof b?isNaN(a)&&isNaN(b)?0:a-b:a>b?1:a<b?-1:0},onChange:function(){},_onChangeActive:!1,_handleOnChange:function(a,b){if(void 0==this._lastValueReported&&(null===b||!this._onChangeActive))this._resetValue=this._lastValueReported=a;this._pendingOnChange= this._pendingOnChange||typeof a!=typeof this._lastValueReported||0!=this.compare(a,this._lastValueReported);if((this.intermediateChanges||b||void 0===b)&&this._pendingOnChange)this._lastValueReported=a,this._pendingOnChange=!1,this._onChangeActive&&(this._onChangeHandle&&this._onChangeHandle.remove(),this._onChangeHandle=this.defer(function(){this._onChangeHandle=null;this.onChange(a)}))},create:function(){this.inherited(arguments);this._onChangeActive=!0},destroy:function(){this._onChangeHandle&& (this._onChangeHandle.remove(),this.onChange(this._lastValueReported));this.inherited(arguments)}})});
"use strict"; // this is the entry point for your library module.exports = example; function example() { return "This is an example function"; } //# sourceMappingURL=index.js.map
version https://git-lfs.github.com/spec/v1 oid sha256:21e5ce04c541ad61b998aa39fbf679734cbb63373edb17ae79bfa33741b4cb47 size 8716
/* * Copyright 2013-2015 Hewlett-Packard Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ define([ 'settings/js/widgets/optional-database-widget', 'test/server-widget-test-utils', 'jasmine-jquery' ], function(DatabaseWidget, serverUtils) { describe('Optional database widget', function() { function testDatabaseCheckbox(initialConfig) { it('should use the username for the database name when the checkbox is checked', function() { var $checkbox = this.widget.$('input[type="checkbox"]'); var $username = this.widget.$('input[name="username"]'); var $database = this.widget.$('input[name="database"]'); var datasourceConfig = _.defaults({ username: 'postgres', url: 'jdbc:postgresql://myHost:123/postgres' }, initialConfig.datasource); this.widget.updateConfig(_.defaults({ datasource: datasourceConfig }, initialConfig)); expect($checkbox).toHaveProp('checked', true); expect($username).toHaveValue('postgres'); expect($database).toHaveValue('postgres'); $checkbox.prop('checked', false).trigger('change'); $username.val('myUser').trigger('change'); $database.val('siteadmin').trigger('change'); expect($username).toHaveValue('myUser'); expect($database).toHaveValue('siteadmin'); $checkbox.prop('checked', true).trigger('change'); expect($username).toHaveValue('myUser'); expect($database).toHaveValue('myUser'); }); it('should fail client side validation on empty database', function() { var $database = this.widget.$('input[name="database"]'); $database.val(''); expect(this.widget.validateInputs()).toBe(false); }); } describe('when it has an enabled widget', function() { var initialConfig = { enabled: true, datasource: { platform: 'postgres', hibernateDialect: 'org.hibernate.dialect.PostgreSQL82Dialect', driverClassName: 'org.postgresql.Driver', url: 'jdbc:postgresql://myHost:123/myDatabase', password: '', passwordRedacted: true, username: 'user' } }; beforeEach(function() { serverUtils.standardBeforeEach.call(this, { WidgetConstructor: DatabaseWidget, constructorOptions: _.extend({ databaseType: 'postgres', strings: serverUtils.strings }, serverUtils.defaultOptions), initialConfig: initialConfig }); }); serverUtils.testDisablableServerShouldValidateFunction.call(this, {initialConfig: initialConfig}); it('should display the correct config', function() { expect(this.widget.$('input[name=host]')).toHaveValue('myHost'); expect(this.widget.$('input[name=port]')).toHaveValue('123'); expect(this.widget.$('input[name=database]')).toHaveValue('myDatabase'); expect(this.widget.$('input[name=username]')).toHaveValue('user'); expect(this.widget.enableView.enabled).toBeTruthy(); var passwordViewArgs = this.widget.passwordView.updateConfig.calls.mostRecent().args[0]; expect(passwordViewArgs.password).toEqual(''); expect(passwordViewArgs.passwordRedacted).toBeTruthy(); }); it('should return the correct config', function() { expect(this.widget.getConfig()).toEqual(initialConfig) }); testDatabaseCheckbox.call(this, initialConfig); }); }); });