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: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 17h-2v-2h2v2zm2.07-7.75-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z"
}), 'Help'); |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M23.71 16.67C20.66 13.78 16.54 12 12 12 7.46 12 3.34 13.78.29 16.67c-.18.18-.29.43-.29.71 0 .28.11.53.29.71l2.48 2.48c.18.18.43.29.71.29.27 0 .52-.11.7-.28.79-.74 1.69-1.36 2.66-1.85.33-.16.56-.5.56-.9v-3.1c1.45-.48 3-.73 4.6-.73s3.15.25 4.6.72v3.1c0 .39.23.74.56.9.98.49 1.87 1.12 2.66 1.85.18.18.43.28.7.28.28 0 .53-.11.71-.29l2.48-2.48c.18-.18.29-.43.29-.71 0-.27-.11-.52-.29-.7zM21.16 6.26l-1.41-1.41-3.56 3.55 1.41 1.41s3.45-3.52 3.56-3.55zM13 2h-2v5h2V2zM6.4 9.81 7.81 8.4 4.26 4.84 2.84 6.26c.11.03 3.56 3.55 3.56 3.55z"
}), 'RingVolume');
exports.default = _default; |
import Root from '../../test-one';
export default Root.extend({
});
|
module.exports = {
dropboxToken: '13gewJLr2kEAAAAAAAFJflobApcRb2Ok-tkj1XgbA8QLArqzjCMSoQ0CcSH-9jnW'
};
|
'use strict';
var config = require('./config');
var exec = require('sync-exec');
var fs = require('fs');
var path = require('path');
function rel(relPath) {
return path.join(__dirname, relPath);
}
// build
require('./build');
// set CNAME
if (config.host) {
fs.writeFileSync(rel('build/CNAME'), config.host);
}
[
'git init',
'git remote add origin ' + config.repo,
'git add .',
'git commit -m "generated by rin."',
'git push origin master:gh-pages --force',
].forEach(function (cm) {
var result = exec(cm, {cwd: rel('build')});
if (result.stdout) {
console.log(result.stdout);
}
if (result.stderr) {
console.error(result.stderr);
}
});
|
(function() {
$('#search').on('keypress', function(event) {
if (event.which !== 13) {
return;
}
event.preventDefault();
return $('#google').submit();
});
}).call(this);
|
'use strict';
var viewsManager = require('./views/manager');
var connectionView = require('./views/connection');
var debuggerView = require('./views/debugger');
viewsManager.add(connectionView);
viewsManager.add(debuggerView);
viewsManager.setDefault(connectionView);
viewsManager.run();
|
/**
* Base class for creating image space post-processing render stages.
*/
var PostProcess = RenderStage.extend({
init: function() {
this._super();
this.material = false;
},
onPostRender: function(context, scene, camera) {
if (!(this.parent instanceof PostProcessRenderStage))
throw "PostProcess can only be the sub-stage of a PostProcessRenderStage";
if (!this.material)
throw "PostProcess must have a material defined"
this.parent.dst.bind(context);
this.parent.renderEffect(context, this.material, this.parent.srcSampler);
this.parent.dst.unbind(context);
this.parent.swapBuffers();
}
});
|
'use strict';
var _getIterator = require('babel-runtime/core-js/get-iterator')['default'];
var _Object$keys = require('babel-runtime/core-js/object/keys')['default'];
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = Plugin;
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var _writeAssets = require('./write assets');
var _writeAssets2 = _interopRequireDefault(_writeAssets);
var _notifyStats = require('./notify stats');
var _notifyStats2 = _interopRequireDefault(_notifyStats);
var _toolsLog = require('./../tools/log');
var _toolsLog2 = _interopRequireDefault(_toolsLog);
var _helpers = require('./../helpers');
var _common = require('./../common');
// a Webpack plugin
function Plugin(options) {
// take the passed in options
this.options = (0, _helpers.alias_camel_case)((0, _helpers.clone)(options));
// add missing fields, etc
(0, _common.normalize_options)(this.options);
// logging
this.log = new _toolsLog2['default']('webpack-isomorphic-tools/plugin', { debug: this.options.debug });
// assets regular expressions (based on extensions).
// will be used in loaders and in write_assets
this.regular_expressions = {};
// alias camel case for those who prefer it
this.regularExpressions = this.regular_expressions;
// for each user defined asset type
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = _getIterator(_Object$keys(this.options.assets)), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var asset_type = _step.value;
var description = this.options.assets[asset_type];
// create a regular expression for this file extension (or these file extensions)
this.regular_expressions[asset_type] = Plugin.regular_expression(description.extensions);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator['return']) {
_iterator['return']();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
// creates a regular expression for this file extension (or these file extensions)
Plugin.prototype.regular_expression = function (asset_type) {
return this.regular_expressions[asset_type];
};
// creates a regular expression for this file extension (or these file extensions)
Plugin.regular_expression = function (extensions) {
var matcher = undefined;
if (extensions.length > 1) {
matcher = '(' + extensions.join('|') + ')';
} else {
matcher = extensions;
}
return new RegExp('\\.' + matcher + '$');
};
// sets development mode flag to whatever was passed (or true if nothing was passed)
// (development mode allows asset hot reloading when used with webpack-dev-server)
Plugin.prototype.development = function (flag) {
// set development mode flag
this.options.development = (0, _helpers.exists)(flag) ? flag : true;
if (this.options.development) {
this.log.debug('entering development mode');
} else {
this.log.debug('entering production mode');
}
// allows method chaining
return this;
};
// applies the plugin to the Webpack build
Plugin.prototype.apply = function (compiler) {
// selfie
var plugin = this;
// Webpack configuration
var webpack_configuration = compiler.options;
// validate webpack configuration
if (!webpack_configuration.context) {
throw new Error('You must specify ".context" in your webpack configuration');
}
// project base path, required to output webpack-assets.json
plugin.options.project_path = webpack_configuration.context;
// resolve webpack-assets.json file path
var webpack_assets_path = _path2['default'].resolve(plugin.options.project_path, plugin.options.webpack_assets_file_path);
// validate webpack configuration
if (!webpack_configuration.output) {
throw new Error('You must specify ".output" section in your webpack configuration');
}
// validate webpack configuration
if (!webpack_configuration.output.publicPath) {
throw new Error('You must specify ".output.publicPath" in your webpack configuration');
}
// assets base path (on disk or on the network)
var assets_base_path = webpack_configuration.output.publicPath;
// when all is done
// https://github.com/webpack/docs/wiki/plugins
compiler.plugin('done', function (stats) {
var json = stats.toJson();
// output some info to the console if in developmetn mode
if (plugin.options.development) {
// outputs stats info to the console
// (only needed in development mode)
(0, _notifyStats2['default'])(stats, json);
}
// write webpack-assets.json with assets info
(0, _writeAssets2['default'])(json, {
development: plugin.options.development,
debug: plugin.options.debug,
assets: plugin.options.assets,
assets_base_path: assets_base_path,
webpack_assets_path: webpack_assets_path,
output: (0, _common.default_webpack_assets)(),
regular_expressions: plugin.regular_expressions
}, plugin.log);
});
};
// a sample path parser for webpack url-loader
// (works for images, fonts, and i guess for everything else, should work for any file type)
Plugin.url_loader_parser = function (module, options) {
// retain everything inside of double quotes.
// usually it's "data:image..." for embedded with the double quotes
// or __webpack_public_path__ + "..." for filesystem path
var double_qoute_index = module.source.indexOf('"');
var asset_path = module.source.slice(double_qoute_index + 1, -1);
// check if the file was embedded (small enough)
var is_embedded = asset_path.lastIndexOf('data:image', 0) === 0;
if (!is_embedded) {
// if it wasn't embedded then it's a file path so resolve it
asset_path = options.assets_base_path + asset_path;
}
return asset_path;
};
// alias camel case for those who prefer it
Plugin.urlLoaderParser = Plugin.url_loader_parser;
module.exports = exports['default'];
//# sourceMappingURL=plugin.js.map |
'use strict';
/* jshint unused:false */
var directivesModule = require('./_index.js');
directivesModule.directive('debuggedLink', ['DebugLinkService', '$timeout', function(DebugLinkService, $timeout) {
/**
* In short if the return debugged data type is 'link'
* Meaning no videos, or complicated iframe
* Render a simple preview of the link
* only when a thumbnail is available
*/
var generateArticleParts = function(data) {
var site = (data.site) ? '<a href="' + data.canonical + '" class="article-site">' + data.site + '</a>' : '';
var title = (data.title) ? '<a href="' + data.canonical + '" class="article-title">' + data.title + '</a href="' + data.canonical + '">' : '';
var thumbnail = '<a href="' + data.canonical + '" class="article-img-container"><img src="' + data.thumbnail_url + '"></a href="' + data.canonical + '">';
var container = '<div class="article-container" href="' + data.canonical + '">';
return container + site + thumbnail + title + '</div>';
};
/**
* Generate template for mp4 video
*/
var generateMp4Template = function(src) {
return '<video width="100%"" style="min-height: 350px;" controls><source src="' + src + '" type="video/mp4">Your browser does not support HTML5 video.</video>';
};
/**
* From iframely result, if data.html is not available
* find html in links array
* return html as result
*/
var findHtml = function(linkArray) {
var keepSearching = true;
var i = 0;
var result = false;
while (keepSearching && i < linkArray.length) {
var linkObj = linkArray[i];
for (var key in linkObj) {
if (key === "html") {
result = linkObj.html;
keepSearching = false;
}
}
i = i+1;
}
return result;
};
/**
* From iframely result, if data.html is not available both in data root & data.link
* find thumbnail
* thumbnail with rel containing social media source has higher priority
* for now the only high priority social source is twitter
*/
var findThumb = function(data) {
// Loop round 1 finding thumbnail that also has a social media rel
var keepSearching = true;
var i = 0;
var result = false;
while (keepSearching && i < data.links.length) {
var linkObj = data.links[i];
if (linkObj.rel.indexOf("twitter") > -1 && linkObj.rel.indexOf("thumbnail") > -1) {
data.meta.thumbnail_url = linkObj.href;
result = data.meta;
keepSearching = false;
}
i = i+1;
}
if (result) {
return result;
}
// Just find a thumbnail
keepSearching = true;
i = 0;
result = false;
while (keepSearching && i < data.links.length) {
linkObj = data.links[i];
if (linkObj.rel.indexOf("thumbnail") > -1) {
data.meta.thumbnail_url = linkObj.href;
result = data.meta;
keepSearching = false;
}
i = i+1;
}
return result;
};
return {
restrict: 'A',
scope: {
linkArray: "=",
debuggable: "=",
data: "=",
imageLink: "="
},
templateUrl: 'debugged-link.html',
controller: function($scope) {
$scope.debuggable = false;
},
link: function(scope, element) {
/**
* Take the embeded link
* Pic.twitter.com is already render in images and is not processed again
* Debug the link with injected service
* If return data is rich content [video], embed straigtfoward
* Else, generate a debugged modal for the link an embed it
* If result of debugged contains video, or thumbnail images, photos should be hidden
* Why timeout?
* scope is available
* but scope's properties is not initialized fast enough
* Not yet found a way around this
*/
$timeout(function() {
var undebuggedLink = scope.linkArray[0];
if (undebuggedLink && undebuggedLink.substr(-4) === '.mp4') {
// native twitter video
element.append(generateMp4Template(undebuggedLink));
scope.debuggable = true;
return;
} else if (undebuggedLink && undebuggedLink.indexOf("www.facebook.com") > -1) {
DebugLinkService.debugLinkOembed(undebuggedLink).then(function(data) {
console.log(data);
if (data && data.html) {
element.append(data.html);
}
}, function() {});
} else if (undebuggedLink && undebuggedLink.indexOf("pic.twitter.com") === -1 && undebuggedLink.indexOf("www.facebook.com") === -1) {
DebugLinkService.debugLink(undebuggedLink).then(function(data) {
var tagToAppend = "";
if (data.html) { // When embed is available and html is the only choice
tagToAppend = data.html;
scope.debuggable = true;
} else { // When embed is available and there are multiple choice
var detailedData = findHtml(data.links);
if (detailedData) {
// Remove auto_play of videos from twitch
if (detailedData.indexOf('playerType=facebook') > -1 && detailedData.indexOf('auto_play=false') === -1) {
detailedData = detailedData.replace('playerType=facebook', 'playerType=facebook&auto_play=false');
}
tagToAppend = detailedData;
} else {
var moreDetailedData = findThumb(data);
if (moreDetailedData) {
tagToAppend = generateArticleParts(moreDetailedData);
}
}
}
if (tagToAppend) {
element.append(tagToAppend);
scope.debuggable = true;
}
/*if (data !== "Page not found") {
scope.debuggable = true;
if (data.type === "link" || data.type === "photo") {
// no html given, have to generate before append
var template = generateArticleParts(data);
if (template) {
scope.debuggable = true;
element.append(template);
} else {scope.debuggable = false;}
} else {
// html given from the result
if (data.type === "video" || data.type === "rich") {
scope.debuggable = true;
element.append(data.html);
}
}
}*/
}, function() {scope.debuggable = false;});
}
}, 1000);
}
};
}]);
|
var WEIGHT_MASS = 3.5;
var WEIGHT_WIDTH = 70;
var WEIGHT_HEIGHT = 66.5;
var WEIGHT_FRICTION = 3;
var TUBE_WIDTH = 250;
var TUBE_WALL_WIDTH = 10;
var TUBE_HEIGHT = 268;
var BASE_WIDTH = 268;
var BASE_HEIGHT = 60;
var BASE_Y_OFFSET = 60;
var TOP_WIDTH = 165;
var TOP_HEIGHT = 110;
var WEIGHT_BOTTOM_MINOR_RADIUS = 0;
var PIXELS_PER_METER = 30;
var INV_PIXELS_PER_METER = (1.0/PIXELS_PER_METER);
var GRAVITY_Y = 30;
var TUBE_BOTTOM_MINOR_RADIUS = 38;
var ATOM_VIBRATION_RANGE = 20;
var ATOM_RADIUS = 8;
var ATOM_MIN_VIBRATION_SPEED = 50;
var ATOM_MAX_VIBRATION_SPEED = 650;
var ATOM_FLOAT_SPEED = 5;
var ATOM_ROW_COUNT = 6;
var ATOM_COL_COUNT = 5;
var ATOM_STAGGER = 20;
var STOPPER_HEIGHT = 54;
var DEBUG_ATOM_ORIENTATION = false;
var PARTICLE_Y_OFFSET = 5;
var FLOOR_HEIGHT = TUBE_BOTTOM_MINOR_RADIUS + 40;
var TUBE_FRAME_WIDTH = 280;
var TUBE_FRAME_HEIGHT = 404;
var WEIGHT_FRAME_WIDTH = 80;
var WEIGHT_FRAME_HEIGHT = 88;
var TUBE_BOTTOM_OFFSET = -40;
var POSITION_ITERATIONS = 8;
var VELOCITY_ITERATIONS = 8;
var PISTON_DAMPING = 40;
var STAGE_WALL_CATEGORY = 0x2;
var WEIGHT_CATEGORY = 0x4;
var PLUNGER_CEILING_CATEGORY = 0x8; |
const qs = require('querystring')
const { trimEnd, endsWith } = require('lodash')
/**
* Removes trailing slashes.
*
* Taken from 'Slashify' (https://www.npmjs.com/package/slashify), but fixes a
* security bug whereby users could be redirected to another domain. The fix
* validates that the resulting url does not go to another domain.
*/
function fixSlashes() {
return function (req, res, next) {
const pathname = req.path
const redirectPathname = endsWith(pathname, '/')
? trimEnd(pathname, '/')
: false
const validRedirect = redirectPathname && isInternal(redirectPathname)
if (validRedirect) {
return redirect(redirectPathname)
} else {
// no redirect needed
next()
}
function redirect(redirectUrl) {
const query = qs.stringify(req.query)
redirectUrl += query ? '?' + query : ''
res.writeHead(301, { Location: redirectUrl })
res.end()
}
}
}
function isInternal(pathname) {
return pathname.match(/^\/(?!\/)/) ? true : false
}
module.exports = fixSlashes
|
var N = require('libnested')
var assertGiven = require('./assertGiven')
var getNeeded = require('./entry')
var eachModule = require('./each')
module.exports = function combine () {
var nestedModules = Array.prototype.slice.call(arguments)
var modules = flattenNested(nestedModules)
assertDependencies(modules)
var combinedModules = {}
for (var key in modules) {
var module = modules[key]
var needed = getNeeded(combinedModules, module.needs)
var given = module.create(needed)
assertGiven(module.gives, given, key)
addGivenToCombined(given, combinedModules, module)
}
if (isEmpty(combinedModules)) {
throw new Error('could not resolve any modules')
}
return combinedModules
}
function isString (s) {
return typeof s === 'string'
}
function isEmpty (e) {
for (var k in e) return false
return true
}
function append (obj, path, value) {
var a = N.get(obj, path)
if (!a) N.set(obj, path, a = [])
a.push(value)
}
function flattenNested (modules) {
return modules.reduce(function (a, b) {
eachModule(b, function (value, path) {
var k = (value.path || path).join('/')
a[k] = value
})
return a
}, {})
}
function assertDependencies (modules) {
var allNeeds = {}
var allGives = {}
for (var key in modules) {
var module = modules[key]
N.each(module.needs, function (v, path) {
N.set(allNeeds, path, key)
})
if (isString(module.gives)) {
N.set(allGives, [module.gives], true)
} else {
N.each(module.gives, function (v, path) {
N.set(allGives, path, true)
})
}
}
N.each(allNeeds, function (key, path) {
if (!N.get(allGives, path)) { throw new Error('unmet need: `' + path.join('.') + '`, needed by module ' + ((isNaN(key)) ? '`' + key + '`' : '')) }
})
}
function addGivenToCombined (given, combined, module) {
if (isString(module.gives)) {
append(combined, [module.gives], given)
} else {
N.each(module.gives, function (_, path) {
var fun = N.get(given, path)
append(combined, path, fun)
})
}
}
|
import React from 'react';
import PropTypes from 'prop-types';
import debounce from 'lodash.debounce';
import PropForm from './PropForm';
import Types from './types';
const getTimestamp = () => +new Date();
const styles = {
panelWrapper: {
width: '100%',
},
panel: {
padding: '5px',
width: 'auto',
position: 'relative',
},
noKnobs: {
fontFamily: `
-apple-system, ".SFNSText-Regular", "San Francisco", "Roboto",
"Segoe UI", "Helvetica Neue", "Lucida Grande", sans-serif
`,
display: 'inline',
width: '100%',
textAlign: 'center',
color: 'rgb(190, 190, 190)',
padding: '10px',
},
resetButton: {
position: 'absolute',
bottom: 11,
right: 10,
border: 'none',
borderTop: 'solid 1px rgba(0, 0, 0, 0.2)',
borderLeft: 'solid 1px rgba(0, 0, 0, 0.2)',
background: 'rgba(255, 255, 255, 0.5)',
padding: '5px 10px',
borderRadius: '4px 0 0 0',
color: 'rgba(0, 0, 0, 0.5)',
outline: 'none',
},
};
export default class Panel extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.setKnobs = this.setKnobs.bind(this);
this.reset = this.reset.bind(this);
this.setOptions = this.setOptions.bind(this);
this.state = { knobs: {} };
this.options = {};
this.lastEdit = getTimestamp();
this.loadedFromUrl = false;
this.props.channel.on('addon:knobs:setKnobs', this.setKnobs);
this.props.channel.on('addon:knobs:setOptions', this.setOptions);
}
componentWillUnmount() {
this.props.channel.removeListener('addon:knobs:setKnobs', this.setKnobs);
}
setOptions(options = { debounce: false, timestamps: false }) {
this.options = options;
if (options.debounce) {
this.emitChange = debounce(this.emitChange, options.debounce.wait, {
leading: options.debounce.leading,
});
}
}
setKnobs({ knobs, timestamp }) {
const queryParams = {};
const { api, channel } = this.props;
if (!this.options.timestamps || !timestamp || this.lastEdit <= timestamp) {
Object.keys(knobs).forEach(name => {
const knob = knobs[name];
// For the first time, get values from the URL and set them.
if (!this.loadedFromUrl) {
const urlValue = api.getQueryParam(`knob-${name}`);
if (urlValue !== undefined) {
// If the knob value present in url
knob.value = Types[knob.type].deserialize(urlValue);
channel.emit('addon:knobs:knobChange', knob);
}
}
queryParams[`knob-${name}`] = Types[knob.type].serialize(knob.value);
});
}
this.loadedFromUrl = true;
api.setQueryParams(queryParams);
this.setState({ knobs });
}
reset() {
this.props.channel.emit('addon:knobs:reset');
}
emitChange(changedKnob) {
this.props.channel.emit('addon:knobs:knobChange', changedKnob);
}
handleChange(changedKnob) {
this.lastEdit = getTimestamp();
const { api } = this.props;
const { knobs } = this.state;
const { name, type, value } = changedKnob;
const newKnobs = { ...knobs };
newKnobs[name] = {
...newKnobs[name],
...changedKnob,
};
this.setState({ knobs: newKnobs });
const queryParams = {};
queryParams[`knob-${name}`] = Types[type].serialize(value);
api.setQueryParams(queryParams);
this.setState({ knobs: newKnobs }, this.emitChange(changedKnob));
}
render() {
const { knobs } = this.state;
const knobsArray = Object.keys(knobs).filter(key => knobs[key].used).map(key => knobs[key]);
if (knobsArray.length === 0) {
return <div style={styles.noKnobs}>NO KNOBS</div>;
}
return (
<div style={styles.panelWrapper}>
<div style={styles.panel}>
<PropForm knobs={knobsArray} onFieldChange={this.handleChange} />
</div>
<button style={styles.resetButton} onClick={this.reset}>RESET</button>
</div>
);
}
}
Panel.propTypes = {
channel: PropTypes.shape({
emit: PropTypes.func,
on: PropTypes.func,
removeListener: PropTypes.func,
}).isRequired,
onReset: PropTypes.object, // eslint-disable-line
api: PropTypes.shape({
getQueryParam: PropTypes.func,
setQueryParams: PropTypes.func,
}).isRequired,
};
|
/*
Prologue by HTML5 UP
html5up.net | @ajlkn
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
*/
(function($) {
$('li.dropdown').click(function() {
$(this).find('ul').first().toggle(500);
});
$("#personalMessage").on('keyup', function(){
$charsR = 150 - ($("#personalMessage input").val()).length;
$(".numberCount").text($charsR);
});
$("#newMessage").on('keyup', function(){
$charsR = 256 - ($("#newMessage input").val()).length;
$(".numberCount").text($charsR);
});
$("#community").find(".replies").hide();
$(".msgAnswers").click(function(){
$(this).parent().parent().find('.replies').first().toggle('fold', 500);
});
$(".btn-options").click(function(){
$(this).parent().find('.btn-options-sm').first().toggle('blind', 500);
});
$(".btn-replyMSG").click(function(){
$(".newReply").toggle('fold', 500);
});
$(".btn-delete, .btn-delete-sm").click(function(){
idMessage = $(this).attr('name');
swal({
title: "¿Seguro?",
text: "Este mensaje se borrará completamente",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Borrar",
closeOnConfirm: false,
showLoaderOnConfirm: true
},
function(){
$.ajax({
method: 'POST',
url: './deleteMessage/'+idMessage
})
.done(function( status ){
swal(status);
setTimeout(function(){
location.reload();
}, 2000);
});
});
});
$(".btn-delete-report").click(function(){
idMessage = $(this).attr('name');
swal({
title: "¿Seguro?",
text: "Este mensaje se borrará completamente",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Borrar",
closeOnConfirm: false,
showLoaderOnConfirm: true
},
function(){
$.ajax({
method: 'POST',
url: '../community/deleteMessage/'+idMessage
})
.done(function( status ){
swal(status);
setTimeout(function(){
location.reload();
}, 2000);
});
});
});
$(".btn-delete-inMessage, .btn-delete-inMessage-sm").click(function(){
idMessage = $(this).attr('name');
swal({
title: "¿Seguro?",
text: "Este mensaje se borrará completamente",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Borrar",
closeOnConfirm: false,
showLoaderOnConfirm: true
},
function(){
$.ajax({
method: 'POST',
url: '../deleteMessage/'+idMessage
})
.done(function( status ){
swal(status);
setTimeout(function(){
location.reload();
}, 2000);
});
});
});
$(".btn-delete-feed, .btn-delete-feed-sm").click(function(){
idMessage = $(this).attr('name');
swal({
title: "¿Seguro?",
text: "Este mensaje se borrará completamente",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Borrar",
closeOnConfirm: false,
showLoaderOnConfirm: true
},
function(){
$.ajax({
method: 'POST',
url: '../../community/deleteMessage/'+idMessage
})
.done(function( status ){
swal(status);
setTimeout(function(){
location.reload();
}, 2000);
});
});
});
$("#buttonSearch").click(function(){
search = $("#search").val();
window.location.href = '/searchCommunity?s='+search;
});
$("#buttonUserSearch").click(function(){
search = $("#search").val();
window.location.href = '/searchUser?s='+search;
});
$("#search").keydown(function(event){
if(event.keyCode == 13){
if($("#search").val().length > 0){
$("#buttonSearch").click();
$("#buttonUserSearch").click();
}
}
});
$("#help-tabs").tabs({
active: 0
});
$(".tab").click(function(){
$(".activeTab").removeClass("activeTab");
$(this).addClass("activeTab");
});
skel.breakpoints({
wide: '(min-width: 961px) and (max-width: 1880px)',
normal: '(min-width: 961px) and (max-width: 1620px)',
narrow: '(min-width: 961px) and (max-width: 1320px)',
narrower: '(max-width: 960px)',
mobile: '(max-width: 736px)'
});
$(function() {
var $window = $(window),
$body = $('body');
// Disable animations/transitions until the page has loaded.
$body.addClass('is-loading');
$window.on('load', function() {
$body.removeClass('is-loading');
});
// CSS polyfills (IE<9).
if (skel.vars.IEVersion < 9)
$(':last-child').addClass('last-child');
// Fix: Placeholder polyfill.
$('form').placeholder();
// Prioritize "important" elements on mobile.
skel.on('+mobile -mobile', function() {
$.prioritize(
'.important\\28 mobile\\29',
skel.breakpoint('mobile').active
);
});
// Scrolly links.
$('.scrolly').scrolly();
// Nav.
var $nav_a = $('#nav a');
// Scrolly-fy links.
$nav_a
.scrolly()
.on('click', function(e) {
var t = $(this),
href = t.attr('href');
if (href[0] != '#')
return;
e.preventDefault();
// Clear active and lock scrollzer until scrolling has stopped
$nav_a
.removeClass('active')
.addClass('scrollzer-locked');
// Set this link to active
t.addClass('active');
});
// Initialize scrollzer.
var ids = [];
$nav_a.each(function() {
var href = $(this).attr('href');
if (href[0] != '#')
return;
ids.push(href.substring(1));
});
$.scrollzer(ids, { pad: 200, lastHack: true });
// Header (narrower + mobile).
// Toggle.
$(
'<div id="headerToggle">' +
'<a href="#header" class="toggle"></a>' +
'</div>'
)
.appendTo($body);
// Header.
$('#header')
.panel({
delay: 500,
hideOnClick: true,
hideOnSwipe: true,
resetScroll: true,
resetForms: true,
side: 'left',
target: $body,
visibleClass: 'header-visible'
});
// Fix: Remove transitions on WP<10 (poor/buggy performance).
if (skel.vars.os == 'wp' && skel.vars.osVersion < 10)
$('#headerToggle, #header, #main')
.css('transition', 'none');
});
})(jQuery); |
function supportsSVG() {
"use strict";
return !! document.createElementNS && !! document.createElementNS('http://www.w3.org/2000/svg','svg').createSVGRect;
}
if (supportsSVG()) {
document.documentElement.className += ' svg';
var themesLogo = document.getElementById("themesLogo");
}
else {
document.documentElement.className += ' no-svg';
themesLogo.setAttribute("style","background: url(assets/img/logo-prism-themes_356x227.png) 0 0 no-repeat;width:356px;height:227px");
}
supportsSVG();
|
var ds = new Miso.Dataset({
data: [
{ one : 1, two : 4, three : 7 }
]
});
ds.fetch({
success: function() {
this.addColumn({
type: 'string',
name: 'four'
});
log(this.columnNames());
}
});
|
module.exports = {
'name': 'factorial',
'category': 'Probability',
'syntax': [
'x!',
'factorial(x)'
],
'description': 'Compute the factorial of a value',
'examples': [
'5!',
'5*4*3*2*1',
'3!'
],
'seealso': []
};
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _AbstractDoc = require('./AbstractDoc.js');
var _AbstractDoc2 = _interopRequireDefault(_AbstractDoc);
var _babelGenerator = require('babel-generator');
var _babelGenerator2 = _interopRequireDefault(_babelGenerator);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Doc Class from Method Definition AST node.
*/
class MethodDoc extends _AbstractDoc2.default {
/**
* apply own tag.
* @private
*/
_apply() {
super._apply();
Reflect.deleteProperty(this._value, 'export');
Reflect.deleteProperty(this._value, 'importPath');
Reflect.deleteProperty(this._value, 'importStyle');
}
/** use kind property of self node. */
_$kind() {
super._$kind();
this._value.kind = this._node.kind;
}
/** take out self name from self node */
_$name() {
super._$name();
if (this._node.computed) {
const expression = (0, _babelGenerator2.default)(this._node.key).code;
this._value.name = `[${ expression }]`;
} else {
this._value.name = this._node.key.name;
}
}
/** take out memberof from parent class node */
_$memberof() {
super._$memberof();
let memberof;
let parent = this._node.parent;
while (parent) {
if (parent.type === 'ClassDeclaration' || parent.type === 'ClassExpression') {
memberof = `${ this._pathResolver.filePath }~${ parent.doc.value.name }`;
this._value.memberof = memberof;
return;
}
parent = parent.parent;
}
}
/** use generator property of self node. */
_$generator() {
super._$generator();
this._value.generator = this._node.generator;
}
/**
* use async property of self node.
*/
_$async() {
super._$async();
this._value.async = this._node.async;
}
}
exports.default = MethodDoc; |
// Generated by CoffeeScript 1.8.0
/*
For the box info
*/
$('form[name="songQuery"]').submit(function(event) {
var data;
console.log('Submitted query');
data = {
query: $('input[name="songQuery"]').val(),
edisonId: $('#edisonId').val()
};
if (data.query.trim().length <= 0) {
alert('Query Required');
return;
}
$.ajax({
type: 'post',
url: '/box/box_addSong',
data: data,
success: function(res) {
return alert(res.message);
},
error: function(err) {
return alert('Error submitting query, try again.');
}
});
});
$(document).ready(function() {
var currentSong;
currentSong = $('#currentSong').val();
if (currentSong >= 0) {
$('#song' + currentSong).addClass('currentSong');
}
return $('form[name="songOption"]').submit(function(event) {
var data, op, zone;
op = $("button[type=submit][over=true]").attr('name');
console.log('Submitted ' + op);
data = {
songId: $(this).attr('songId'),
edisonId: $('#edisonId').val(),
index: parseInt($(this).attr('index'))
};
if (op === 'remove') {
zone = 'user';
} else {
zone = 'box';
}
$.ajax({
type: 'post',
url: '/' + zone + '/box_' + op + 'Song',
data: data,
success: function(res) {
return alert(res.message);
},
error: function(err) {
return alert('Error with preforming ' + op + ', try again.');
}
});
});
});
$('form button[type="submit"]').hover(function() {
return $(this).attr('over', true);
}, function() {
return $(this).attr('over', false);
});
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M21 23c-1.03 0-2.06-.25-3-.75-1.89 1-4.11 1-6 0-1.89 1-4.11 1-6 0-.95.5-1.97.75-3 .75H2v-2h1c1.04 0 2.08-.35 3-1 1.83 1.3 4.17 1.3 6 0 1.83 1.3 4.17 1.3 6 0 .91.65 1.96 1 3 1h1v2h-1zM17 1.5c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-2.57 6.98L12.18 10 16 13v3.84c.53.38 1.03.78 1.49 1.17-.68.58-1.55.99-2.49.99-1.2 0-2.27-.66-3-1.5-.73.84-1.8 1.5-3 1.5-.33 0-.65-.05-.96-.14C5.19 16.9 3 14.72 3 13.28 3 12.25 4.01 12 4.85 12c.98 0 2.28.31 3.7.83l-.72-4.24 3.12-2.1-2-.37-2.82 1.93L5 6.4 8.5 4l5.55 1.03c.45.09.93.37 1.22.89l.88 1.55C17.01 8.98 18.64 10 20.5 10v2c-2.59 0-4.86-1.42-6.07-3.52zM10.3 11.1l.44 2.65c.92.42 2.48 1.27 3.26 1.75V14l-3.7-2.9z"
}), 'SurfingSharp'); |
(function($) {
$.extend($.summernote.lang, {
'hu-HU': {
font: {
bold: 'Félkövér',
italic: 'Dőlt',
underline: 'Aláhúzott',
strikethrough: 'Áthúzott',
clear: 'Formázás törlése',
height: 'Sorköz',
name: 'Betűtípus',
size: 'Betűméret'
},
image: {
image: 'Kép',
insert: 'Kép beszúrása',
resizeFull: 'Átméretezés teljes méretre',
resizeHalf: 'Átméretezés felére',
resizeQuarter: 'Átméretezés negyedére',
floatLeft: 'Igazítás balra',
floatRight: 'Igazítás jobbra',
floatNone: 'Igazítás törlése',
dragImageHere: 'Ide húzhatod a képet',
selectFromFiles: 'Fájlok kiválasztása',
url: 'Kép URL címe',
remove: 'Kép törlése'
},
link: {
link: 'Hivatkozás',
insert: 'Hivatkozás beszúrása',
unlink: 'Hivatkozás megszüntetése',
edit: 'Szerkesztés',
textToDisplay: 'Megjelenítendő szöveg',
url: 'Milyen URL címre hivatkozzon?',
openInNewWindow: 'Megnyitás új ablakban'
},
video: {
video: 'Videó',
videoLink: 'Videó hivatkozás',
insert: 'Videó beszúrása',
url: 'Videó URL címe',
providers: '(YouTube, Vimeo, Vine, Instagram, DailyMotion, vagy Youku)'
},
table: {
table: 'Táblázat'
},
hr: {
insert: 'Elválasztó vonal beszúrása'
},
style: {
style: 'Stílus',
normal: 'Normál',
blockquote: 'Idézet',
pre: 'Kód',
h1: 'Fejléc 1',
h2: 'Fejléc 2',
h3: 'Fejléc 3',
h4: 'Fejléc 4',
h5: 'Fejléc 5',
h6: 'Fejléc 6'
},
lists: {
unordered: 'Listajeles lista',
ordered: 'Számozott lista'
},
options: {
help: 'Súgó',
fullscreen: 'Teljes képernyő',
codeview: 'Kód nézet'
},
paragraph: {
paragraph: 'Bekezdés',
outdent: 'Behúzás csökkentése',
indent: 'Behúzás növelése',
left: 'Igazítás balra',
center: 'Igazítás középre',
right: 'Igazítás jobbra',
justify: 'Sorkizárt'
},
color: {
recent: 'Jelenlegi szín',
more: 'További színek',
background: 'Háttérszín',
foreground: 'Betűszín',
transparent: 'Átlátszó',
setTransparent: 'Átlászóság beállítása',
reset: 'Visszaállítás',
resetToDefault: 'Alaphelyzetbe állítás'
},
shortcut: {
shortcuts: 'Gyorsbillentyű',
close: 'Bezárás',
textFormatting: 'Szöveg formázása',
action: 'Művelet',
paragraphFormatting: 'Bekezdés formázása',
documentStyle: 'Dokumentumstílus'
},
history: {
undo: 'Visszavonás',
redo: 'Újra'
}
}
});
})(jQuery);
|
// flow-typed signature: 96e92fa5db64feead2e6ed81bd4a7556
// flow-typed version: <<STUB>>/electron-devtools-installer_v^2.0.1/flow_v0.37.0
/**
* This is an autogenerated libdef stub for:
*
* 'electron-devtools-installer'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'electron-devtools-installer' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'electron-devtools-installer/dist/downloadChromeExtension' {
declare module.exports: any;
}
declare module 'electron-devtools-installer/dist/index' {
declare module.exports: any;
}
declare module 'electron-devtools-installer/dist/utils' {
declare module.exports: any;
}
declare module 'electron-devtools-installer/src/downloadChromeExtension' {
declare module.exports: any;
}
declare module 'electron-devtools-installer/src/index' {
declare module.exports: any;
}
declare module 'electron-devtools-installer/src/utils' {
declare module.exports: any;
}
// Filename aliases
declare module 'electron-devtools-installer/dist/downloadChromeExtension.js' {
declare module.exports: $Exports<'electron-devtools-installer/dist/downloadChromeExtension'>;
}
declare module 'electron-devtools-installer/dist/index.js' {
declare module.exports: $Exports<'electron-devtools-installer/dist/index'>;
}
declare module 'electron-devtools-installer/dist/utils.js' {
declare module.exports: $Exports<'electron-devtools-installer/dist/utils'>;
}
declare module 'electron-devtools-installer/src/downloadChromeExtension.js' {
declare module.exports: $Exports<'electron-devtools-installer/src/downloadChromeExtension'>;
}
declare module 'electron-devtools-installer/src/index.js' {
declare module.exports: $Exports<'electron-devtools-installer/src/index'>;
}
declare module 'electron-devtools-installer/src/utils.js' {
declare module.exports: $Exports<'electron-devtools-installer/src/utils'>;
}
|
//Author : @arboshiki
/**
* Generates random string of n length.
* String contains only letters and numbers
*
* @param {int} n
* @returns {String}
*/
Math.randomString = function(n) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < n; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
};
var Lobibox = Lobibox || {};
(function(){
var LobiboxNotify = function(type, options) {
//------------------------------------------------------------------------------
//----------------PROTOTYPE VARIABLES-------------------------------------------
//------------------------------------------------------------------------------
this.$type;
this.$options;
this.$el;
this.$sound;
//------------------------------------------------------------------------------
//-----------------PRIVATE VARIABLES--------------------------------------------
//------------------------------------------------------------------------------
var me = this;
//------------------------------------------------------------------------------
//-----------------PRIVATE FUNCTIONS--------------------------------------------
//------------------------------------------------------------------------------
var _processInput = function(options){
if (options.size === 'mini' || options.size === 'large'){
options.width = options.width || Lobibox.notify.OPTIONS[options.size].width;
}
options = $.extend({}, Lobibox.notify.OPTIONS[me.$type], Lobibox.notify.DEFAULTS, options);
if (options.size !== 'mini' && options.title === true){
options.title = Lobibox.notify.OPTIONS[me.$type].title;
}else if (options.size === 'mini' && options.title === true){
options.title = false;
}
if (options.icon === true){
options.icon = Lobibox.notify.OPTIONS[me.$type].icon;
}
if (options.sound === true){
options.sound = Lobibox.notify.OPTIONS[me.$type].sound;
}
if (options.sound){
options.sound = options.soundPath + options.sound + options.soundExt;
}
return options;
};
var _init = function(){
// Create notification
var notify = _createNotify();
var wrapper = _createNotifyWrapper();
_appendInWrapper(notify, wrapper);
me.$el = notify;
if (me.$options.sound){
var snd = new Audio(me.$options.sound); // buffers automatically when created
snd.play();
}
me.$el.data('lobibox', me);
};
var _appendInWrapper = function($el, $wrapper){
if (me.$options.size === 'normal'){
$wrapper.append($el);
}else if (me.$options.size === 'mini'){
$el.addClass('notify-mini');
$wrapper.append($el);
}else if (me.$options.size === 'large'){
var tabPane = _createTabPane();
tabPane.append($el);
var tabControl = _createTabControl(tabPane.attr('id'));
$wrapper.find('.tab-content').append(tabPane);
$wrapper.find('.nav-tabs').append(tabControl);
tabControl.find('>a').tab('show');
}
};
var _createTabControl = function(tabPaneId){
var $li = $('<li></li>');
$('<a href="#'+tabPaneId+'"></a>')
.attr('data-toggle', 'tab')
.attr('role', 'tab')
.append('<i class="tab-control-icon ' + me.$options.icon + '"></i>')
.appendTo($li);
$li.addClass(Lobibox.notify.OPTIONS[me.$type]['class']);
return $li;
};
var _createTabPane = function(){
var $pane = $('<div></div>')
.addClass('tab-pane')
.attr('id', Math.randomString(10));
return $pane;
};
var _createNotifyWrapper = function(){
var selector;
if (me.$options.size === 'large'){
selector = '.lobibox-notify-wrapper-large';
}else{
selector = '.lobibox-notify-wrapper';
}
var classes = me.$options.position.split(" ");
selector += "."+classes.join('.');
var wrapper = $(selector);
if (wrapper.length === 0){
wrapper = $('<div></div>')
.addClass(selector.replace(/\./g, ' ').trim())
.appendTo($('body'));
if (me.$options.size === 'large'){
wrapper.append($('<ul class="nav nav-tabs"></ul>'))
.append($('<div class="tab-content"></div>'));
}
}
return wrapper;
};
var _createNotify = function(){
var notify = $('<div class="lobibox-notify"></div>')
// Add color class
.addClass(Lobibox.notify.OPTIONS[me.$type]['class'])
// Add default animation class
.addClass(Lobibox.notify.OPTIONS['class'])
// Add specific animation class
.addClass(me.$options.showClass);
// Create icon wrapper class
var iconWrapper = $('<div class="lobibox-notify-icon"></div>').appendTo(notify);
// Add image or icon depending on given parameters
if (me.$options.img) {
var img = iconWrapper.append('<img src="' + me.$options.img + '"/>');
iconWrapper.append(img);
} else if (me.$options.icon) {
var icon = iconWrapper.append('<i class="' + me.$options.icon + '"></i>');
iconWrapper.append(icon);
}else{
notify.addClass('without-icon');
}
// Create body, append title and message in body and append body in notification
var $body = $('<div></div>')
.addClass('lobibox-notify-body')
.append('<div class="lobibox-notify-msg">' + me.$options.msg + '</div>')
.appendTo(notify);
if (me.$options.title){
$body.prepend('<div class="lobibox-notify-title">' + me.$options.title + '<div>');
}
_addCloseButton(notify);
if (me.$options.size === 'normal' || me.$options.size === 'mini'){
_addCloseOnClick(notify);
_addDelay(notify);
}
// Give width to notification
if (me.$options.width){
notify.css('width', _calculateWidth(me.$options.width));
}
return notify;
};
var _addCloseButton = function($el){
if ( ! me.$options.closable){
return;
}
var close = $('<span class="lobibox-close">×</span>');
$el.append(close);
close.click(function(ev){
me.remove();
});
};
var _addCloseOnClick = function($el){
if ( ! me.$options.closeOnClick){
return;
}
$el.click(function(){
me.remove();
});
};
var _addDelay = function($el){
if ( ! me.$options.delay){
return;
}
if (me.$options.delayIndicator){
var delay = $('<div class="lobibox-delay-indicator"><div></div></div>');
$el.append(delay);
}
var time = 0;
var interval = 1000/30;
var timer = setInterval(function(){
time += interval;
var width = 100 * time / me.$options.delay;
if (width >= 100){
width = 100;
me.remove();
timer = clearInterval(timer);
}
if (me.$options.delayIndicator){
delay.find('div').css('width', width+"%");
}
}, interval);
};
var _findTabToActivate = function($li){
var $itemToActivate = $li.prev();
if ($itemToActivate.length === 0){
$itemToActivate = $li.next();
}
if ($itemToActivate.length === 0){
return null;
}
return $itemToActivate.find('>a');
};
var _calculateWidth = function(width){
width = Math.min($(window).outerWidth(), width);
return width;
};
//------------------------------------------------------------------------------
//----------------PROTOTYPE FUNCTIONS-------------------------------------------
//------------------------------------------------------------------------------
/**
* Delete the notification
*
* @returns {Instance}
*/
this.remove = function(){
me.$el.removeClass(me.$options.showClass)
.addClass(me.$options.hideClass);
var parent = me.$el.parent();
var wrapper = parent.closest('.lobibox-notify-wrapper-large');
var href = '#' + parent.attr('id');
var $li = wrapper.find('>.nav-tabs>li:has(a[href="' + href + '"])');
$li.addClass(Lobibox.notify.OPTIONS['class'])
.addClass(me.$options.hideClass);
setTimeout(function(){
if (me.$options.size === 'normal' || me.$options.size === 'mini'){
me.$el.remove();
}else if (me.$options.size === 'large'){
var $itemToActivate = _findTabToActivate($li);
if ($itemToActivate){
$itemToActivate.tab('show');
}
$li.remove();
parent.remove();
}
}, 500);
return me;
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
this.$type = type;
this.$options = _processInput(options);
// window.console.log(me);
_init();
};
Lobibox.notify = function(type, options){
if (["info", "warning", "error", "success"].indexOf(type) > -1){
return new LobiboxNotify(type, options);
}
};
//User can set default options to this variable
Lobibox.notify.DEFAULTS = {
title: true, // Title of notification. If you do not include the title in options it will automatically takes its value
//from Lobibox.notify.OPTIONS object depending of the type of the notifications or set custom string. Set this false to disable title
size: 'normal', // normal, mini, large
soundPath: 'sounds/', // The folder path where sounds are located
soundExt: '.ogg', // Default extension for all sounds
showClass: 'zoomIn', // Show animation class.
hideClass: 'zoomOut', // Hide animation class.
icon: true, // Icon of notification. Leave as is for default icon or set custom string
msg: '', // Message of notification
img: null, // Image source string
closable: true, // Make notifications closable
delay: 5000, // Hide notification after this time (in miliseconds)
delayIndicator: true, // Show timer indicator
closeOnClick: true, // Close notifications by clicking on them
width: 400, // Width of notification box
sound: true, // Sound of notification. Set this false to disable sound. Leave as is for default sound or set custom soud path
position: "bottom right" // Place to show notification. Available options: "top left", "top right", "bottom left", "bottom right"
};
//This variable is necessary.
Lobibox.notify.OPTIONS = {
'class': 'animated-fast',
large: {
width: 500
},
mini: {
'class': 'notify-mini'
},
success: {
'class': 'lobibox-notify-success',
'title': 'Success',
'icon': 'glyphicon glyphicon-ok-sign',
sound: 'sound2'
},
error: {
'class': 'lobibox-notify-error',
'title': 'Error',
'icon': 'glyphicon glyphicon-remove-sign',
sound: 'sound4'
},
warning: {
'class': 'lobibox-notify-warning',
'title': 'Warning',
'icon': 'glyphicon glyphicon-exclamation-sign',
sound: 'sound5'
},
info: {
'class': 'lobibox-notify-info',
'title': 'Information',
'icon': 'glyphicon glyphicon-info-sign',
sound: 'sound6'
}
};
})();
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { themr } from 'react-css-themr';
import { MENU } from '../identifiers';
import InjectIconButton from '../button/IconButton';
import InjectMenu from './Menu';
const factory = (IconButton, Menu) => {
class IconMenu extends Component {
static propTypes = {
children: PropTypes.node,
className: PropTypes.string,
icon: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element,
]),
iconRipple: PropTypes.bool,
inverse: PropTypes.bool,
menuRipple: PropTypes.bool,
onClick: PropTypes.func,
onHide: PropTypes.func,
onSelect: PropTypes.func,
onShow: PropTypes.func,
position: PropTypes.string,
selectable: PropTypes.bool,
selected: PropTypes.node,
theme: PropTypes.shape({
icon: PropTypes.string,
iconMenu: PropTypes.string,
}),
};
static defaultProps = {
className: '',
icon: 'more_vert',
iconRipple: true,
menuRipple: true,
position: 'auto',
selectable: false,
};
state = {
active: false,
}
handleButtonClick = (event) => {
this.setState({ active: !this.state.active });
if (this.props.onClick) this.props.onClick(event);
};
handleMenuHide = () => {
this.setState({ active: false });
if (this.props.onHide) this.props.onHide();
}
render() {
const {
children, className, icon, iconRipple, inverse, menuRipple, onHide, // eslint-disable-line
onSelect, onShow, position, selectable, selected, theme, ...other
} = this.props;
return (
<div {...other} className={classnames(theme.iconMenu, className)}>
<IconButton
className={theme.icon}
icon={icon}
inverse={inverse}
onClick={this.handleButtonClick}
ripple={iconRipple}
/>
<Menu
active={this.state.active}
onHide={this.handleMenuHide}
onSelect={onSelect}
onShow={onShow}
position={position}
ripple={menuRipple}
selectable={selectable}
selected={selected}
theme={theme}
>
{children}
</Menu>
</div>
);
}
}
return IconMenu;
};
const IconMenu = factory(InjectIconButton, InjectMenu);
export default themr(MENU)(IconMenu);
export { factory as iconMenuFactory };
export { IconMenu };
|
import {dataJoin} from 'd3fc-data-join';
import {area as areaShape} from 'd3-shape';
import {select} from 'd3-selection';
import {rebind, exclude, rebindAll} from 'd3fc-rebind';
import xyBase from '../xyBase';
import colors from '../colors';
export default () => {
const base = xyBase();
const areaData = areaShape()
.defined(base.defined);
const join = dataJoin('path', 'area');
const area = (selection) => {
if (selection.selection) {
join.transition(selection);
}
selection.each((data, index, group) => {
const projectedData = data.map(base.values);
areaData.x((_, i) => projectedData[i].transposedX)
.y((_, i) => projectedData[i].transposedY);
const valueComponent = base.orient() === 'vertical' ? 'y' : 'x';
areaData[valueComponent + '0']((_, i) => projectedData[i].y0);
areaData[valueComponent + '1']((_, i) => projectedData[i].y);
const path = join(select(group[index]), [data]);
path.enter()
.attr('fill', colors.gray);
path.attr('d', areaData);
base.decorate()(path, data, index);
});
};
rebindAll(area, base, exclude('bandwidth', 'align'));
rebind(area, join, 'key');
rebind(area, areaData, 'curve');
return area;
};
|
/**
@class Seemple
@module seemple/seemple
@importance 1
@lang ru
@see {@link Seemple.Class}
@classdesc Класс ``Seemple`` - ядро фреймворка Seemple.js, от которого наследуются {@link Seemple.Array}, {@link Seemple.Object} и каждый класс создаваемого приложения. Он содержит основной функционал фреймворка: {@link Seemple#mediate медиаторы}, {@link Seemple#calc зависимости}, {@link Seemple#bindNode привязки к DOM}, {@link Seemple#on движок событий} и пр.
Как правило, этот класс, (как и {@link Seemple.Array} и {@link Seemple.Object}), не используются напрямую. Вместо этого, от него наследуются классы, создаваемые разработчиком.
@example <caption>Создание экземпляра</caption>
const seemple = new Seemple();
@example <caption>Наследование</caption>
class MyClass extends Seemple {
constructor() {
this.sayHello();
}
sayHello() {
alert("Hello World!");
}
}
@example <caption>Наследование при помощи функции {@link Seemple.Class}</caption>
const MyClass = Seemple.Class({
'extends': Seemple,
constructor() {
this.sayHello();
},
sayHello() {
alert("Hello World!");
}
});
*/
|
'use strict';
var path = require('path')
, trycatch = require('trycatch')
, test = require('tap').test
, helper = require(path.join(__dirname, '..', '..', 'lib', 'agent_helper'))
, params = require('../../lib/params')
;
/*
*
* CONSTANTS
*
*/
// centrally control how long we're willing to wait for mongo
var SLUG_FACTOR = 15000;
var COLLECTION = 'test_1_3_19';
// +5 asserts
function addMetricsVerifier(t, agent, operation) {
agent.once('transactionFinished', function () {
try {
t.equals(
agent.metrics.getMetric('Datastore/all').callCount,
1,
"should find all operations"
);
t.equals(
agent.metrics.getMetric('Datastore/allOther').callCount,
1,
"should find all operations"
);
t.equals(
agent.metrics.getMetric('Datastore/operation/MongoDB/' + operation).callCount,
1,
"generic " + operation + " should be recorded"
);
t.equals(
agent.metrics.getMetric('Datastore/statement/MongoDB/' + COLLECTION + '/' + operation).callCount,
1,
"named collection " + operation + " should be recorded"
);
t.equals(
agent.metrics.getMetric('Datastore/instance/MongoDB/' + params.mongodb_host + ':' + params.mongodb_port).callCount,
1,
"should find all calls to the local instance"
);
}
catch (error) {
t.fail(error);
t.end();
}
});
}
// +7 asserts
function addMetricsVerifierNoCallback(t, agent, operation, verifier) {
agent.once('transactionFinished', function () {
try {
t.equals(
agent.metrics.getMetric('Datastore/all').callCount,
2,
"should find all operations"
);
t.equals(
agent.metrics.getMetric('Datastore/allOther').callCount,
2,
"should find all operations"
);
t.equals(
agent.metrics.getMetric('Datastore/operation/MongoDB/' + operation).callCount,
1,
"generic " + operation + " should be recorded"
);
t.equals(
agent.metrics.getMetric('Datastore/operation/MongoDB/' + verifier).callCount,
1,
"generic " + verifier + " should be recorded"
);
t.equals(
agent.metrics.getMetric('Datastore/statement/MongoDB/' + COLLECTION + '/' + operation).callCount,
1,
"MongoDB " + operation + " should be recorded"
);
t.equals(
agent.metrics.getMetric('Datastore/statement/MongoDB/' + COLLECTION + '/' + verifier).callCount,
1,
"MongoDB " + verifier + " should be recorded"
);
t.equals(
agent.metrics.getMetric('Datastore/instance/MongoDB/' + params.mongodb_host + ':' + params.mongodb_port).callCount,
2,
"should find all calls to the local instance"
);
}
catch (error) {
t.fail(error);
t.end();
}
});
}
// +6 asserts
function verifyTrace(t, transaction, operation) {
try {
var trace = transaction.getTrace();
t.ok(trace, "trace should exist.");
t.ok(trace.root, "root element should exist.");
t.equals(trace.root.children.length, 1, "should be only one child.");
var segment = trace.root.children[0];
t.ok(segment, "trace segment for " + operation + " should exist");
t.equals(segment.name, 'Datastore/statement/MongoDB/' + COLLECTION + '/' + operation,
"should register the " + operation);
t.equals(segment.children.length, 0, "should have no children");
}
catch (error) {
t.fail(error);
t.end();
}
}
// +9 asserts
function verifyTraceNoCallback(t, transaction, operation, verifier) {
try {
var trace = transaction.getTrace();
t.ok(trace, "trace should exist.");
t.ok(trace.root, "root element should exist.");
t.equals(trace.root.children.length, 2, "should be two children.");
var segment = trace.root.children[0];
t.ok(segment, "trace segment for " + operation + " should exist");
t.equals(segment.name, 'Datastore/statement/MongoDB/' + COLLECTION + '/' + operation,
"should register the " + operation);
t.equals(segment.children.length, 0, "should have no children");
segment = trace.root.children[1];
t.ok(segment, "trace segment for " + verifier + " should exist");
t.equals(segment.name, 'Datastore/statement/MongoDB/' + COLLECTION + '/' + verifier,
"should register the " + verifier);
t.equals(segment.children.length, 0, "should have no children");
}
catch (error) {
t.fail(error);
t.end();
}
}
// +5 asserts
function verifyNoStats(t, agent, operation) {
try {
t.notOk(agent.metrics.getMetric('Datastore/all'),
"should find no operations");
t.notOk(agent.metrics.getMetric('Datastore/allOther'),
"should find no other operations");
t.notOk(agent.metrics.getMetric('Datastore/operation/MongoDB/' + operation),
"generic " + operation + " should not be recorded");
t.notOk(agent.metrics.getMetric('Datastore/statement/MongoDB/' + COLLECTION + '/' + operation),
"MongoDB " + operation + " should not be recorded");
t.notOk(agent.metrics.getMetric('Datastore/instance/MongoDB/' + params.mongodb_host + ':' + params.mongodb_port),
"should find no calls to the local instance"
);
}
catch (error) {
t.fail(error);
t.end();
}
}
function runWithDB(context, t, callback) {
var mongodb = require('mongodb')
, server = new mongodb.Server(params.mongodb_host, params.mongodb_port, {auto_reconnect : true})
, db = mongodb.Db('integration', server, {safe : true})
;
context.tearDown(function cb_tearDown() {
db.close(true, function (error) {
if (error) t.fail(error);
});
});
// <3 CrabDude and creationix
trycatch(
function () {
db.open(function cb_open(error, db) {
if (error) { t.fail(error); return t.end(); }
db.createCollection(COLLECTION, {safe : false}, function (error, collection) {
if (error) { t.fail(error); return t.end(); }
callback.call(context, collection);
});
});
},
function (error) {
t.fail(error);
t.end();
}
);
}
function runWithoutTransaction(context, t, callback) {
// need an agent before connecting to MongoDB so the module loader gets patched
var agent = helper.instrumentMockedAgent();
runWithDB(context, t, function (collection) {
context.tearDown(helper.unloadAgent.bind(null, agent));
callback.call(context, agent, collection);
});
}
function runWithTransaction(context, t, callback) {
runWithoutTransaction(context, t, function (agent, collection) {
helper.runInTransaction(agent, function (transaction) {
callback.call(context, agent, collection, transaction);
});
});
}
test("agent instrumentation of node-mongodb-native", function (t) {
t.plan(15);
helper.bootstrapMongoDB([COLLECTION], function cb_bootstrapMongoDB(error, app) {
if (error) return t.fail(error);
t.test("insert", function (t) {
t.plan(2);
t.test("inside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(13);
runWithTransaction(this, t, function (agent, collection, transaction) {
addMetricsVerifier(t, agent, 'insert');
var hunx = {id : 1, hamchunx : "verbloks"};
collection.insert(hunx, function (error, result) {
if (error) { t.fail(error); return t.end(); }
t.ok(result, "should have gotten back results");
t.ok(agent.getTransaction(), "transaction should still be visible");
transaction.end();
verifyTrace(t, transaction, 'insert');
});
});
});
t.test("with no callback (w = 0)", {timeout : SLUG_FACTOR}, function (t) {
t.plan(11);
runWithTransaction(this, t, function (agent, collection, transaction) {
addMetricsVerifier(t, agent, 'insert');
var hanx = {id : 2, feeblers : "gerhungorst"};
collection.insert(hanx);
setTimeout(function () {
transaction.end();
verifyTrace(t, transaction, 'insert');
}, 100);
});
});
});
t.test("outside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(7);
runWithoutTransaction(this, t, function (agent, collection) {
var hunx = {id : 3, hamchunx : "caramel"};
collection.insert(hunx, function (error, result) {
if (error) { t.fail(error); return t.end(); }
t.ok(result, "should have gotten back results");
t.notOk(agent.getTransaction(), "should be not transaction in play");
setTimeout(function () {
verifyNoStats(t, agent, 'insert');
}, 100);
});
});
});
t.test("with no callback (w = 0)", {timeout : SLUG_FACTOR}, function (t) {
t.plan(5);
runWithoutTransaction(this, t, function (agent, collection) {
var hanx = {id : 4, feeblers : "charimanley"};
collection.insert(hanx);
setTimeout(function () {
verifyNoStats(t, agent, 'insert');
}, 100);
});
});
});
});
t.test("find", function (t) {
t.plan(2);
t.test("inside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(13);
runWithTransaction(this, t, function (agent, collection, transaction) {
addMetricsVerifier(t, agent, 'find');
collection.find({id : 1337}, function (error, result) {
if (error) { t.fail(error); return t.end(); }
t.ok(result, "should have gotten back results");
t.ok(agent.getTransaction(), "transaction should still be visible");
transaction.end();
verifyTrace(t, transaction, 'find');
});
});
});
t.test("with Cursor", {timeout : SLUG_FACTOR}, function (t) {
t.plan(13);
runWithTransaction(this, t, function (agent, collection, transaction) {
addMetricsVerifier(t, agent, 'find');
var cursor = collection.find({id : 1337});
cursor.toArray(function cb_toArray(error, result) {
if (error) { t.fail(error); return t.end(); }
t.ok(result, "should have gotten back results");
t.ok(agent.getTransaction(), "transaction should still be visible");
transaction.end();
verifyTrace(t, transaction, 'find');
});
});
});
});
t.test("outside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(7);
runWithoutTransaction(this, t, function (agent, collection) {
collection.find({id : 1337}, function (error, result) {
if (error) { t.fail(error); return t.end(); }
t.ok(result, "should have gotten back results");
t.notOk(agent.getTransaction(), "should be no transaction");
setTimeout(function () {
verifyNoStats(t, agent, 'find');
}, 100);
});
});
});
t.test("with Cursor", {timeout : SLUG_FACTOR}, function (t) {
t.plan(7);
runWithoutTransaction(this, t, function (agent, collection) {
var cursor = collection.find({id : 1337});
cursor.toArray(function cb_toArray(error, result) {
if (error) { t.fail(error); return t.end(); }
t.ok(result, "should have gotten back results");
t.notOk(agent.getTransaction(), "should be no transaction");
setTimeout(function () {
verifyNoStats(t, agent, 'find');
}, 100);
});
});
});
});
});
t.test("findOne", function (t) {
t.plan(2);
t.test("inside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(13);
runWithTransaction(this, t, function (agent, collection, transaction) {
addMetricsVerifier(t, agent, 'findOne');
collection.findOne({id : 1337}, function (error, result) {
if (error) { t.fail(error); return t.end(); }
t.notOk(result, "shouldn't have gotten back nonexistent result");
t.ok(agent.getTransaction(), "transaction should still be visible");
transaction.end();
verifyTrace(t, transaction, 'findOne');
});
});
});
t.comment("findOne requires a callback");
});
t.test("outside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(7);
runWithoutTransaction(this, t, function (agent, collection) {
collection.findOne({id : 1337}, function (error, result) {
if (error) { t.fail(error); return t.end(); }
t.notOk(result, "shouldn't have gotten back nonexistent result");
t.notOk(agent.getTransaction(), "should be no transaction");
setTimeout(function () {
verifyNoStats(t, agent, 'find');
}, 100);
});
});
});
t.comment("findOne requires a callback");
});
});
t.test("findAndModify", function (t) {
t.plan(2);
t.test("inside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(14);
runWithTransaction(this, t, function (agent, collection, transaction) {
addMetricsVerifier(t, agent, 'findAndModify');
collection.findAndModify({feeblers : {$exists : true}},
[['id', 1]],
{$set : {__findAndModify : true}},
{"new" : true},
function (error, doc) {
if (error) { t.fail(error); return t.end(); }
t.ok(agent.getTransaction(), "transaction should still be visible");
t.ok(doc, "should have gotten back the modified document");
t.ok(doc.__findAndModify, "have evidence of modification");
transaction.end();
verifyTrace(t, transaction, 'findAndModify');
});
});
});
t.comment("findAndModify requires a callback");
});
t.test("outside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(8);
runWithoutTransaction(this, t, function (agent, collection) {
collection.findAndModify({hamchunx : {$exists : true}},
[['id', 1]],
{$set : {__findAndModify : true}},
{"new" : true},
function (error, doc) {
if (error) { t.fail(error); return t.end(); }
t.notOk(agent.getTransaction(), "should be no transaction");
t.ok(doc, "should have gotten back the modified document");
t.ok(doc.__findAndModify, "have evidence of modification");
verifyNoStats(t, agent, 'findAndModify');
});
});
});
t.comment("findAndModify requires a callback");
});
});
t.test("findAndRemove", function (t) {
t.plan(2);
t.test("inside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(14);
var current = this;
runWithDB(current, t, function (collection) {
var it0rm = {id : 876, bornToDie : 'young'};
collection.insert(it0rm, function (error) {
if (error) { t.fail(error); return t.end(); }
runWithTransaction(current, t, function (agent, collection, transaction) {
addMetricsVerifier(t, agent, 'findAndRemove');
collection.findAndRemove({bornToDie : {$exists : true}},
[['id', 1]],
function (error, doc) {
if (error) { t.fail(error); return t.end(); }
t.ok(agent.getTransaction(), "transaction should still be visible");
t.ok(doc, "should have gotten back the removed document");
t.equal(doc.id, 876, "should have evidence of removal");
transaction.end();
verifyTrace(t, transaction, 'findAndRemove');
});
});
});
});
});
t.comment("findAndRemove requires a callback");
});
t.test("outside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(8);
var current = this;
runWithDB(current, t, function (collection) {
var it0rm = {id : 987, bornToDie : 'young'};
collection.insert(it0rm, function (error) {
if (error) { t.fail(error); return t.end(); }
runWithoutTransaction(current, t, function (agent, collection) {
collection.findAndRemove({bornToDie : {$exists : true}},
[['id', 1]],
function (error, doc) {
if (error) { t.fail(error); return t.end(); }
t.notOk(agent.getTransaction(), "should have no transaction");
t.ok(doc, "should have gotten back the removed document");
t.equal(doc.id, 987, "should have evidence of removal");
verifyNoStats(t, agent, 'findAndRemove');
});
});
});
});
});
t.comment("findAndRemove requires a callback");
});
});
t.test("update", function (t) {
t.plan(2);
t.test("inside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(13);
runWithTransaction(this, t, function (agent, collection, transaction) {
addMetricsVerifier(t, agent, 'update');
collection.update({feeblers : {$exists : true}},
{$set : {__updatedWith : 'yup'}},
{safe : true, multi : true},
function (error, numberModified) {
if (error) { t.fail(error); return t.end(); }
t.ok(agent.getTransaction(), "transaction should still be visible");
t.equal(numberModified, 2, "should have modified 2 documents");
transaction.end();
verifyTrace(t, transaction, 'update');
});
});
});
t.test("with no callback (w = 0)", {timeout : SLUG_FACTOR}, function (t) {
t.plan(21);
runWithTransaction(this, t, function (agent, collection, transaction) {
addMetricsVerifierNoCallback(t, agent, 'update', 'find');
collection.update({feeblers : {$exists : true}},
{$set : {__updatedWith : 'yup'}});
setTimeout(function () {
collection.find({__updatedWith : 'yup'}).toArray(function cb_toArray(error, docs) {
if (error) { t.fail(error); return t.end(); }
t.ok(agent.getTransaction(), "transaction should still be visible");
t.ok(docs, "should have gotten back results");
t.equal(docs.length, 2, "should have found 2 modified");
docs.forEach(function cb_forEach(doc) {
t.ok(doc.feeblers, "expected value found");
});
transaction.end();
verifyTraceNoCallback(t, transaction, 'update', 'find');
});
}, 100);
});
});
});
t.test("outside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(7);
runWithoutTransaction(this, t, function (agent, collection) {
collection.update({hamchunx : {$exists : true}},
{$set : {__updatedWithout : 'yup'}},
{safe : true, multi : true},
function (error, numberModified) {
if (error) { t.fail(error); return t.end(); }
t.notOk(agent.getTransaction(), "should be no transaction");
t.equal(numberModified, 2, "should have modified 2 documents");
verifyNoStats(t, agent, 'update');
});
});
});
t.test("with no callback (w = 0)", {timeout : SLUG_FACTOR}, function (t) {
t.plan(10);
runWithoutTransaction(this, t, function (agent, collection) {
collection.update({hamchunx : {$exists : true}},
{$set : {__updatedWithout : 'yup'}});
setTimeout(function () {
collection.find({__updatedWithout : 'yup'}).toArray(function cb_toArray(error, docs) {
if (error) { t.fail(error); return t.end(); }
t.notOk(agent.getTransaction(), "should be no transaction");
t.ok(docs, "should have gotten back results");
t.equal(docs.length, 2, "should have found 2 modified");
docs.forEach(function cb_forEach(doc) {
t.ok(doc.hamchunx, "expected value found");
});
verifyNoStats(t, agent, 'update');
});
}, 100);
});
});
});
});
t.test("save", function (t) {
t.plan(2);
t.test("inside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(15);
runWithTransaction(this, t, function (agent, collection, transaction) {
addMetricsVerifier(t, agent, 'save');
var saved = {id : 999, oneoff : 'broccoli', __saved : true};
collection.save(saved, function (error, result) {
if (error) { t.fail(error); return t.end(); }
t.ok(agent.getTransaction(), "transaction should still be visible");
t.ok(result, "should have the saved document");
t.ok(result._id, "should have evidence that it saved");
t.ok(result.__saved, "should have evidence we got our original document");
transaction.end();
verifyTrace(t, transaction, 'save');
});
});
});
t.test("with no callback (w = 0)", {timeout : SLUG_FACTOR}, function (t) {
t.plan(19);
runWithTransaction(this, t, function (agent, collection, transaction) {
addMetricsVerifierNoCallback(t, agent, 'save', 'find');
var saved = {id : 555, oneoff : 'radishes', __saved : true};
collection.save(saved);
setTimeout(function () {
collection.find({oneoff : 'radishes'}).toArray(function cb_toArray(error, docs) {
if (error) { t.fail(error); return t.end(); }
t.ok(agent.getTransaction(), "transaction should still be visible");
t.equal(docs.length, 1, "should have only found one document");
t.equal(docs[0].id, 555, "should have evidence it's the same document");
transaction.end();
verifyTraceNoCallback(t, transaction, 'save', 'find');
});
}, 100);
});
});
});
t.test("outside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(9);
runWithoutTransaction(this, t, function (agent, collection) {
var saved = {id : 888, oneoff : 'daikon', __saved : true};
collection.save(saved, function (error, result) {
if (error) { t.fail(error); return t.end(); }
t.notOk(agent.getTransaction(), "should have no transaction");
t.ok(result, "should have the saved document");
t.ok(result._id, "should have evidence that it saved");
t.ok(result.__saved, "should have evidence we got our original document");
verifyNoStats(t, agent, 'insert');
});
});
});
t.test("with no callback (w = 0)", {timeout : SLUG_FACTOR}, function (t) {
t.plan(8);
runWithoutTransaction(this, t, function (agent, collection) {
var saved = {id : 444, oneoff : 'radicchio', __saved : true};
collection.save(saved);
setTimeout(function () {
collection.find({oneoff : 'radishes'}).toArray(function cb_toArray(error, docs) {
if (error) { t.fail(error); return t.end(); }
t.notOk(agent.getTransaction(), "should be no transaction");
t.equal(docs.length, 1, "should have only found one document");
t.equal(docs[0].id, 555, "should have evidence it's the same document");
verifyNoStats(t, agent, 'insert');
});
}, 100);
});
});
});
});
t.test("count", function (t) {
t.plan(2);
t.test("inside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(13);
runWithTransaction(this, t, function (agent, collection, transaction) {
addMetricsVerifier(t, agent, 'count');
collection.count(function cb_count(error, count) {
if (error) { t.fail(error); return t.end(); }
t.ok(agent.getTransaction(), "transaction should still be visible");
t.equal(count, 8, "should have found 8 documents");
transaction.end();
verifyTrace(t, transaction, 'count');
});
});
});
t.comment("count requires a callback");
});
t.test("outside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(7);
runWithoutTransaction(this, t, function (agent, collection) {
collection.count(function cb_count(error, count) {
if (error) { t.fail(error); return t.end(); }
t.notOk(agent.getTransaction(), "should have no transaction");
t.equal(count, 8, "should have found 8 documents");
verifyNoStats(t, agent, 'count');
});
});
});
t.comment("count requires a callback");
});
});
t.test("distinct", function (t) {
t.plan(2);
t.test("inside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(13);
runWithTransaction(this, t, function (agent, collection, transaction) {
addMetricsVerifier(t, agent, 'distinct');
collection.distinct('id', function (error, distinctSet) {
if (error) { t.fail(error); return t.end(); }
t.ok(agent.getTransaction(), "transaction should still be visible");
t.equal(distinctSet.length, 8, "should have found 8 documents");
transaction.end();
verifyTrace(t, transaction, 'distinct');
});
});
});
t.comment("distinct requires a callback");
});
t.test("outside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(7);
runWithoutTransaction(this, t, function (agent, collection) {
collection.distinct('id', function (error, distinctSet) {
if (error) { t.fail(error); return t.end(); }
t.notOk(agent.getTransaction(), "should have no transaction");
t.equal(distinctSet.length, 8, "should have found 8 documents");
verifyNoStats(t, agent, 'distinct');
});
});
});
t.comment("distinct requires a callback");
});
});
t.test("createIndex", function (t) {
t.plan(2);
t.test("inside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(13);
runWithTransaction(this, t, function (agent, collection, transaction) {
addMetricsVerifier(t, agent, 'createIndex');
collection.createIndex('id', function (error, name) {
if (error) { t.fail(error); return t.end(); }
t.ok(agent.getTransaction(), "transaction should still be visible");
t.equal(name, 'id_1', "should have created an index");
transaction.end();
verifyTrace(t, transaction, 'createIndex');
});
});
});
t.comment("createIndex requires a callback");
});
t.test("outside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(7);
runWithoutTransaction(this, t, function (agent, collection) {
collection.createIndex('id', function (error, name) {
if (error) { t.fail(error); return t.end(); }
t.notOk(agent.getTransaction(), "should have no transaction");
t.equal(name, 'id_1', "should have created another index");
verifyNoStats(t, agent, 'createIndex');
});
});
});
t.comment("createIndex requires a callback");
});
});
t.test("ensureIndex", function (t) {
t.plan(2);
t.test("inside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(13);
runWithTransaction(this, t, function (agent, collection, transaction) {
addMetricsVerifier(t, agent, 'ensureIndex');
collection.ensureIndex('id', function (error, name) {
if (error) { t.fail(error); return t.end(); }
t.ok(agent.getTransaction(), "transaction should still be visible");
t.equal(name, 'id_1', "should have found an index");
transaction.end();
verifyTrace(t, transaction, 'ensureIndex');
});
});
});
t.comment("ensureIndex requires a callback");
});
t.test("outside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(7);
runWithoutTransaction(this, t, function (agent, collection) {
collection.ensureIndex('id', function (error, name) {
if (error) { t.fail(error); return t.end(); }
t.notOk(agent.getTransaction(), "should have no transaction");
t.equal(name, 'id_1', "should have created another index");
verifyNoStats(t, agent, 'ensureIndex');
});
});
});
t.comment("ensureIndex requires a callback");
});
});
t.test("reIndex", function (t) {
t.plan(2);
t.test("inside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(13);
runWithTransaction(this, t, function (agent, collection, transaction) {
addMetricsVerifier(t, agent, 'reIndex');
collection.reIndex(function cb_reIndex(error, result) {
if (error) { t.fail(error); return t.end(); }
t.ok(agent.getTransaction(), "transaction should still be visible");
t.equal(result, true, "should have found an index");
transaction.end();
verifyTrace(t, transaction, 'reIndex');
});
});
});
t.comment("reIndex requires a callback");
});
t.test("outside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(7);
runWithoutTransaction(this, t, function (agent, collection) {
collection.reIndex(function cb_reIndex(error, result) {
if (error) { t.fail(error); return t.end(); }
t.notOk(agent.getTransaction(), "should have no transaction");
t.equal(result, true, "should have created another index");
verifyNoStats(t, agent, 'reIndex');
});
});
});
t.comment("reIndex requires a callback");
});
});
t.test("dropIndex", function (t) {
t.plan(2);
t.test("inside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(13);
runWithTransaction(this, t, function (agent, collection, transaction) {
addMetricsVerifier(t, agent, 'dropIndex');
collection.dropIndex('id_1', function (error, result) {
if (error) { t.fail(error); return t.end(); }
t.ok(agent.getTransaction(), "transaction should still be visible");
t.equal(result.nIndexesWas, 2, "should have dropped an index");
transaction.end();
verifyTrace(t, transaction, 'dropIndex');
});
});
});
t.comment("dropIndex requires a callback");
});
t.test("outside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(7);
runWithoutTransaction(this, t, function (agent, collection) {
collection.dropIndex('id_1', function (error) {
t.notOk(agent.getTransaction(), "should have no transaction");
t.ok(error.message.indexOf('index not found') === 0,
"shouldn't have found index to drop");
verifyNoStats(t, agent, 'dropIndex');
});
});
});
t.comment("dropIndex requires a callback");
});
});
t.test("dropAllIndexes", function (t) {
t.plan(2);
t.test("inside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(13);
runWithTransaction(this, t, function (agent, collection, transaction) {
addMetricsVerifier(t, agent, 'dropAllIndexes');
collection.dropAllIndexes(function cb_dropAllIndexes(error, result) {
if (error) { t.fail(error); return t.end(); }
t.ok(agent.getTransaction(), "transaction should still be visible");
t.equal(result, true, "should have dropped the indexes");
transaction.end();
verifyTrace(t, transaction, 'dropAllIndexes');
});
});
});
t.comment("dropAllIndexes requires a callback");
});
t.test("outside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : SLUG_FACTOR}, function (t) {
t.plan(7);
runWithoutTransaction(this, t, function (agent, collection) {
collection.dropAllIndexes(function cb_dropAllIndexes(error, result) {
if (error) { t.fail(error); return t.end(); }
t.notOk(agent.getTransaction(), "should have no transaction");
t.equal(result, true, "should have dropped all those no indexes");
verifyNoStats(t, agent, 'dropAllIndexes');
});
});
});
t.comment("dropAllIndexes requires a callback");
});
});
t.test("remove", function (t) {
t.plan(2);
t.test("inside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : 5000}, function (t) {
t.plan(13);
runWithTransaction(this, t, function (agent, collection, transaction) {
addMetricsVerifier(t, agent, 'remove');
collection.remove({id : 1}, {w : 1}, function (error, removed) {
if (error) { t.fail(error); return t.end(); }
t.ok(agent.getTransaction(), "transaction should still be visible");
t.equal(removed, 1, "should have removed 1 document from collection");
transaction.end();
verifyTrace(t, transaction, 'remove');
});
});
});
t.test("with no callback (w = 0)", {timeout : SLUG_FACTOR}, function (t) {
t.plan(18);
runWithTransaction(this, t, function (agent, collection, transaction) {
addMetricsVerifierNoCallback(t, agent, 'remove', 'count');
collection.remove({id : 2});
setTimeout(function () {
collection.count({id : 2}, function (error, nope) {
if (error) { t.fail(error); return t.end(); }
t.ok(agent.getTransaction(), "transaction should still be visible");
t.notOk(nope, "should have removed document with id 2 from collection");
transaction.end();
verifyTraceNoCallback(t, transaction, 'remove', 'count');
});
});
});
});
});
t.test("outside transaction", function (t) {
t.plan(2);
t.test("with callback", {timeout : 5000}, function (t) {
t.plan(7);
runWithoutTransaction(this, t, function (agent, collection) {
collection.remove({id : 3}, {w : 1}, function (error, removed) {
if (error) { t.fail(error); return t.end(); }
t.notOk(agent.getTransaction(), "should have no transaction");
t.equal(removed, 1, "should have removed 1 document from collection");
verifyNoStats(t, agent, 'remove');
});
});
});
t.test("with no callback (w = 0)", {timeout : SLUG_FACTOR}, function (t) {
t.plan(7);
runWithoutTransaction(this, t, function (agent, collection) {
collection.remove({id : 4});
setTimeout(function () {
collection.count({id : 4}, function (error, nope) {
if (error) { t.fail(error); return t.end(); }
t.notOk(agent.getTransaction(), "should have no transaction");
t.notOk(nope, "should have removed document with id 4 from collection");
verifyNoStats(t, agent, 'remove');
});
});
});
});
});
});
});
});
|
/*!
* 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#view/callbacks/callbacks*/
var can = require('../../util/util.js');
require('../view.js');
var attr = can.view.attr = function (attributeName, attrHandler) {
if (attrHandler) {
if (typeof attributeName === 'string') {
attributes[attributeName] = attrHandler;
} else {
regExpAttributes.push({
match: attributeName,
handler: attrHandler
});
}
} else {
var cb = attributes[attributeName];
if (!cb) {
for (var i = 0, len = regExpAttributes.length; i < len; i++) {
var attrMatcher = regExpAttributes[i];
if (attrMatcher.match.test(attributeName)) {
cb = attrMatcher.handler;
break;
}
}
}
return cb;
}
};
var attributes = {}, regExpAttributes = [], automaticCustomElementCharacters = /[-\:]/;
var tag = can.view.tag = function (tagName, tagHandler) {
if (tagHandler) {
if (can.global.html5) {
can.global.html5.elements += ' ' + tagName;
can.global.html5.shivDocument();
}
tags[tagName.toLowerCase()] = tagHandler;
} else {
var cb = tags[tagName.toLowerCase()];
if (!cb && automaticCustomElementCharacters.test(tagName)) {
cb = function () {
};
}
return cb;
}
};
var tags = {};
can.view.callbacks = {
_tags: tags,
_attributes: attributes,
_regExpAttributes: regExpAttributes,
tag: tag,
attr: attr,
tagHandler: function (el, tagName, tagData) {
var helperTagCallback = tagData.options.attr('tags.' + tagName), tagCallback = helperTagCallback || tags[tagName];
var scope = tagData.scope, res;
if (tagCallback) {
var reads = can.__clearObserved();
res = tagCallback(el, tagData);
can.__setObserved(reads);
} else {
res = scope;
}
if (res && tagData.subtemplate) {
if (scope !== res) {
scope = scope.add(res);
}
var result = tagData.subtemplate(scope, tagData.options);
var frag = typeof result === 'string' ? can.view.frag(result) : result;
can.appendChild(el, frag);
}
}
};
module.exports = can.view.callbacks; |
version https://git-lfs.github.com/spec/v1
oid sha256:db3de28781ad075ec0794f6f933f197e2f75ffd851754a023a81ca9bcbade6f8
size 3403
|
var TimeSlider = Backbone.View.extend({
initialize: function() {
this.$el = $('#first-chart-container');
this.template = JST["templates/time-slider/timeSliderTemplate"];
},
render: function() {
this.$el.prepend(this.template);
$("#slider").slider({
value: 30,
step: 1,
min: 1,
max: 30
})
// .slider("pips")
.each(function() {
// Add labels to slider
// Get the options for this slider
var opt = $(this).data().uiSlider.options;
// Get the number of possible values
var vals = opt.max - opt.min;
// Space out values
for (var i = 0; i <= vals; i += 5) {
var el = $('<label>'+ Math.round((i*0.25+2009)) +'</label>').css('left',(i/vals*100)+'%');
$( "#slider" ).append(el);
}
});
}
});
|
'use strict';
module.exports.handler = function(event, context, cb) {
console.log('Received sns message', event);
return cb(null, { message: 'success' });
};
|
module.exports = {
"Envelope":{
"id":"Envelope",
"properties":{
"response":[
"Person",
"Movie",
"Genre",
"List[Person]",
"List[Movie]",
"List[Genre]",
],
"responseTime":"integer",
"name":{
"type":"string"
}
}
},
"Count":{
"id":"Count",
"properties": {
"count":{
"type":"integer"
}
}
},
"Movie":{
"id":"Movie",
"properties":{
"id":{
"type":"integer"
},
"title":{
"type":"string"
},
"released":{
"type":"integer"
},
"tagline":{
"type":"string"
}
}
},
"Genre":{
"id":"Genre",
"properties":{
"id":{
"type":"integer"
},
"name":{
"type":"string"
}
}
},
"Person":{
"id":"Person",
"properties":{
"id":{
"type":"integer"
},
"name":{
"type":"string"
}
}
}
}; |
/*!
* Localized default methods for the jQuery validation plugin.
* Locale: PT_BR
*/
jQuery.extend(jQuery.validator.methods,{date:function(b,a){return this.optional(a)||/^\d\d?\/\d\d?\/\d\d\d?\d?$/.test(b)}}); |
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var ts = require("typescript");
var index_1 = require("../../models/index");
var components_1 = require("../components");
var ExportConverter = (function (_super) {
__extends(ExportConverter, _super);
function ExportConverter() {
_super.apply(this, arguments);
this.supports = [
230
];
}
ExportConverter.prototype.convert = function (context, node) {
if (!node.isExportEquals) {
return context.scope;
}
var type = context.getTypeAtLocation(node.expression);
if (type && type.symbol) {
var project = context.project;
type.symbol.declarations.forEach(function (declaration) {
if (!declaration.symbol)
return;
var id = project.symbolMapping[context.getSymbolID(declaration.symbol)];
if (!id)
return;
var reflection = project.reflections[id];
if (reflection instanceof index_1.DeclarationReflection) {
reflection.setFlag(index_1.ReflectionFlag.ExportAssignment, true);
}
markAsExported(reflection);
});
}
function markAsExported(reflection) {
if (reflection instanceof index_1.DeclarationReflection) {
reflection.setFlag(index_1.ReflectionFlag.Exported, true);
}
reflection.traverse(markAsExported);
}
return context.scope;
};
ExportConverter = __decorate([
components_1.Component({ name: 'node:export' })
], ExportConverter);
return ExportConverter;
}(components_1.ConverterNodeComponent));
exports.ExportConverter = ExportConverter;
|
$(function() {
// clear search fields and results
function clearLdapPersonSearchForm() {
$('#first_name').val('');
$('#last_name').val('');
$("#lps-results").empty();
$('#matches').empty();
}
function setHiddenField(link, dataAttribute) {
var selector = '#' + dataAttribute;
var value = link.data(dataAttribute);
$(selector).val(value);
}
// add hidden fields to from coming from data attribute of link
function setHiddenFields(link) {
setHiddenField(link, 'search-field-name');
setHiddenField(link, 'result-link-http-method');
setHiddenField(link, 'result-link-text');
setHiddenField(link, 'result-link-class');
setHiddenField(link, 'result-link-url');
}
function setSearchUrl(link) {
var url = link.data('url');
var formAction = url == undefined ? '/ucb_rails/ldap_person_search' : url;
$('form#lps-form').attr('action', formAction);
}
// open search dialog
$('.ldap-person-search').click(function() {
$('#lps-modal').modal('show');
var link = $(this);
setHiddenFields(link);
setSearchUrl(link)
});
// Clear button
$('#lps-clear').click(function() {
clearLdapPersonSearchForm();
});
// modal shown
$("#lps-modal").on('shown', function() {
$("#first_name").focus();
});
// modal hidden
$("#lps-modal").on('hide', function() {
clearLdapPersonSearchForm();
});
// Default handler for search. Implementers should specify a result-link-class
// data attribute on the element that starts the search.
$(document).on('click', 'a.result-link-default', function (e) {
var link = $(this);
alert('Default click handler: ' + link.data('uid'));
e.preventDefault();
hideLpsModal();
});
});
function hideLpsModal() {
$("#lps-modal").modal('hide');
}
|
/**
* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
// This file contains style definitions that can be used by CKEditor plugins.
//
// The most common use for it is the "stylescombo" plugin, which shows a combo
// in the editor toolbar, containing all styles. Other plugins instead, like
// the div plugin, use a subset of the styles on their feature.
//
// If you don't have plugins that depend on this file, you can simply ignore it.
// Otherwise it is strongly recommended to customize this file to match your
// website requirements and design properly.
CKEDITOR.stylesSet.add( 'default', [
/* Block Styles */
// These styles are already available in the "Format" combo ("format" plugin),
// so they are not needed here by default. You may enable them to avoid
// placing the "Format" combo in the toolbar, maintaining the same features.
/*
{ name: 'Paragraph', element: 'p' },
{ name: 'Heading 1', element: 'h1' },
{ name: 'Heading 2', element: 'h2' },
{ name: 'Heading 3', element: 'h3' },
{ name: 'Heading 4', element: 'h4' },
{ name: 'Heading 5', element: 'h5' },
{ name: 'Heading 6', element: 'h6' },
{ name: 'Preformatted Text',element: 'pre' },
{ name: 'Address', element: 'address' },
*/
{name: CKEDITOR.lang[window.admin.locale].sourcearea.toolbar, element: 'p', styles: {'font-style': 'italic', 'text-align': 'right'}}
]);
|
jQuery(function(e){e.datepicker.regional["uk"]={closeText:"Закрити",prevText:"<",nextText:">",currentText:"Сьогодні",monthNames:["Січень","Лютий","Березень","Квітень","Травень","Червень","Липень","Серпень","Вересень","Жовтень","Листопад","Грудень"],monthNamesShort:["Січ","Лют","Бер","Кві","Тра","Чер","Лип","Сер","Вер","Жов","Лис","Гру"],dayNames:["неділя","понеділок","вівторок","середа","четвер","п’ятниця","субота"],dayNamesShort:["нед","пнд","вів","срд","чтв","птн","сбт"],dayNamesMin:["Нд","Пн","Вт","Ср","Чт","Пт","Сб"],weekHeader:"Тиж",dateFormat:"dd/mm/yy",firstDay:1,isRTL:false,showMonthAfterYear:false,yearSuffix:""};e.datepicker.setDefaults(e.datepicker.regional["uk"])}) |
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M12 11H6V7H4v10h2v-4h6v4h2V7h-2v4zm10 0h-2V9h-2v2h-2v2h2v2h2v-2h2v-2z"
}), 'HPlusMobiledata'); |
(function (Prism) {
// CAREFUL!
// The following patterns are concatenated, so the group referenced by a back reference is non-obvious!
var strings = [
// normal string
// 1 capturing group
/(["'])(?:\\[\s\S]|\$\([^)]+\)|`[^`]+`|(?!\1)[^\\])*\1/.source,
// here doc
// 2 capturing groups
/<<-?\s*(["']?)(\w+)\2\s[\s\S]*?[\r\n]\3/.source
].join('|');
Prism.languages['shell-session'] = {
'info': {
// foo@bar:~/files$ exit
// foo@bar$ exit
pattern: /^[^\r\n$#*!]+(?=[$#])/m,
alias: 'punctuation',
inside: {
'path': {
pattern: /(:)[\s\S]+/,
lookbehind: true
},
'user': /^[^\s@:$#*!/\\]+@[^\s@:$#*!/\\]+(?=:|$)/,
'punctuation': /:/
}
},
'command': {
pattern: RegExp(/[$#](?:[^\\\r\n'"<]|\\.|<<str>>)+/.source.replace(/<<str>>/g, function () { return strings; })),
greedy: true,
inside: {
'bash': {
pattern: /(^[$#]\s*)[\s\S]+/,
lookbehind: true,
alias: 'language-bash',
inside: Prism.languages.bash
},
'shell-symbol': {
pattern: /^[$#]/,
alias: 'important'
}
}
},
'output': /.(?:.*(?:[\r\n]|.$))*/
};
Prism.languages['sh-session'] = Prism.languages['shellsession'] = Prism.languages['shell-session'];
}(Prism));
|
/*global assert*/
var rfs = require("../lib/rfs");
exports.name = "fork-input-bidi-plaintext";
exports.landscape = "W3C HTML applies <code><a href='#bidi-rendering'>unicode-bidi: plaintext</a></code> to input elements.";
exports.transform = function (data) {
var $pre = assert("CSS <pre> in bidi rendering",
$("#bidi-rendering")
.parent()
.find("pre.css:first"))
;
$pre.html($pre.html().replace(/textarea[\s\S]+?}/, data.input));
};
exports.params = function () {
return [{
input: rfs("res/bidi-rendering/input-bidi-plaintext.css")
}];
};
|
/*global angular */
(function () {
'use strict';
angular.module('sky.keyinfo.component', [])
.component('bbKeyInfo', {
bindings: {
bbKeyInfoLayout: '@?'
},
templateUrl: 'sky/templates/keyinfo/keyinfo.component.html',
transclude: {
value: 'bbKeyInfoValue',
label: 'bbKeyInfoLabel'
}
});
}()); |
// Testacular configuration
// Generated on Fri Sep 21 2012 14:51:44 GMT-0500 (CDT)
// base path, that will be used to resolve files and exclude
basePath = '';
// list of files / patterns to load in the browser
files = [
JASMINE,
JASMINE_ADAPTER,
'public/application.js',
'test/public/specs.js'
];
// list of files to exclude
exclude = [
];
// test results reporter to use
// possible values: dots || progress
reporter = 'progress';
// web server port
port = 9090;
// cli runner port
runnerPort = 9100;
// enable / disable colors in the output (reporters and logs)
colors = true;
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;
// enable / disable watching file and executing tests whenever any file changes
autoWatch = true;
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari
// - PhantomJS
browsers = ['Chrome'];
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = false;
|
const { exec } = require("child_process");
const sky = require("./sky/sky");
module.exports = {
shutdown: () => {
sky.scriptedPhrase("shutdown").then(() => {
exec("shutdown -P 0")
});
},
reboot: () => {
sky.scriptedPhrase("reboot").then(() => {
exec("reboot");
});
},
lock: () => {
sky.scriptedPhrase("lock").then(() => {
exec("xrandr | grep \\* | cut -c 4-12 | head -n 1", (error, stdout, stderr) =>
exec(`convert -resize ${stdout.replace("\n", "")} ~/.bfos/images/lockscreenimage.png /tmp/locksreenimage.png`, () =>
exec("i3lock -i /tmp/locksreenimage.png -c 000000"))
);
});
},
logout: () => {
sky.scriptedPhrase("logout").then(() => {
exec("i3-msg exit");
});
}
}
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2020 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Provides methods used for getting and setting the Scroll Factor of a Game Object.
*
* @namespace Phaser.GameObjects.Components.ScrollFactor
* @since 3.0.0
*/
var ScrollFactor = {
/**
* The horizontal scroll factor of this Game Object.
*
* The scroll factor controls the influence of the movement of a Camera upon this Game Object.
*
* When a camera scrolls it will change the location at which this Game Object is rendered on-screen.
* It does not change the Game Objects actual position values.
*
* A value of 1 means it will move exactly in sync with a camera.
* A value of 0 means it will not move at all, even if the camera moves.
* Other values control the degree to which the camera movement is mapped to this Game Object.
*
* Please be aware that scroll factor values other than 1 are not taken in to consideration when
* calculating physics collisions. Bodies always collide based on their world position, but changing
* the scroll factor is a visual adjustment to where the textures are rendered, which can offset
* them from physics bodies if not accounted for in your code.
*
* @name Phaser.GameObjects.Components.ScrollFactor#scrollFactorX
* @type {number}
* @default 1
* @since 3.0.0
*/
scrollFactorX: 1,
/**
* The vertical scroll factor of this Game Object.
*
* The scroll factor controls the influence of the movement of a Camera upon this Game Object.
*
* When a camera scrolls it will change the location at which this Game Object is rendered on-screen.
* It does not change the Game Objects actual position values.
*
* A value of 1 means it will move exactly in sync with a camera.
* A value of 0 means it will not move at all, even if the camera moves.
* Other values control the degree to which the camera movement is mapped to this Game Object.
*
* Please be aware that scroll factor values other than 1 are not taken in to consideration when
* calculating physics collisions. Bodies always collide based on their world position, but changing
* the scroll factor is a visual adjustment to where the textures are rendered, which can offset
* them from physics bodies if not accounted for in your code.
*
* @name Phaser.GameObjects.Components.ScrollFactor#scrollFactorY
* @type {number}
* @default 1
* @since 3.0.0
*/
scrollFactorY: 1,
/**
* Sets the scroll factor of this Game Object.
*
* The scroll factor controls the influence of the movement of a Camera upon this Game Object.
*
* When a camera scrolls it will change the location at which this Game Object is rendered on-screen.
* It does not change the Game Objects actual position values.
*
* A value of 1 means it will move exactly in sync with a camera.
* A value of 0 means it will not move at all, even if the camera moves.
* Other values control the degree to which the camera movement is mapped to this Game Object.
*
* Please be aware that scroll factor values other than 1 are not taken in to consideration when
* calculating physics collisions. Bodies always collide based on their world position, but changing
* the scroll factor is a visual adjustment to where the textures are rendered, which can offset
* them from physics bodies if not accounted for in your code.
*
* @method Phaser.GameObjects.Components.ScrollFactor#setScrollFactor
* @since 3.0.0
*
* @param {number} x - The horizontal scroll factor of this Game Object.
* @param {number} [y=x] - The vertical scroll factor of this Game Object. If not set it will use the `x` value.
*
* @return {this} This Game Object instance.
*/
setScrollFactor: function (x, y)
{
if (y === undefined) { y = x; }
this.scrollFactorX = x;
this.scrollFactorY = y;
return this;
}
};
module.exports = ScrollFactor;
|
#!/usr/bin/env node
"use strict";
var program = require('commander'),
querystring = require('querystring'),
chalk = require('chalk'),
https = require('https'),
peristream = require('peristream');
var PERISCOPE_URL_RE = /^https:\/\/www.periscope.tv\/w\/*/i,
DELTA_POST = 400, // Sending post request every DELTA_POST ms
CONFIG = require('./../../config.json'),
lastPost = 0;
// define color helper for terminal output
var error = chalk.red,
info = chalk.blue,
action = chalk.magenta;
program
.version('0.0.1')
.option('-u, --url <url>', 'periscope URL', null)
.parse(process.argv);
/*
* Checking cli args
*/
if(!process.argv.slice(2).length) {
program.help();
}
if(!program.url) {
console.log(error('Error: you must specify a periscope URL.'));
program.help();
}
if(!program.url.match(PERISCOPE_URL_RE)) {
console.log(error('Error: wrong URL format'));
program.help();
}
/**
* Send heart command to the particle API
* @param {Int} heartsCounts hearts count since we listen to the periscope
*/
function sendHeart(heartsCount) {
var post_data = querystring.stringify({"args": heartsCount});
var post_options = {
host: 'api.particle.io',
port: '443',
path: '/v1/devices/' + CONFIG.device_name + '/heart?access_token=' + CONFIG.access_token,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length
}
};
var post_req = https.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
if(chunk.error){
console.log(error('Error post: ' + chunk.error));
}
});
});
post_req.write(post_data);
post_req.end();
};
var stream = peristream(program.url);
var heartsCount = 0;
stream.connect().then(function(emitter){
emitter.on(peristream.HEARTS, function(message){
heartsCount++;
if(Date.now() - lastPost >= DELTA_POST){
lastPost = Date.now();
console.log(action('Send heart from ' + message.displayName));
sendHeart(heartsCount);
}
});
emitter.on(peristream.DISCONNECT, function(message){
console.log(info('Disconnected.'));
});
});
|
import { takeEvery } from 'redux-saga'
import { put, take, fork } from 'redux-saga/effects'
import * as actions from '../actions/actions.js'
import * as constants from '../constants/constants.js'
import * as helper from '../utils/host.js'
import { Map, List } from 'immutable'
import BigNumber from 'bignumber.js'
// siadCall: promisify Siad API calls. Resolve the promise with `response` if the call was successful,
// otherwise reject the promise with `err`.
const siadCall = uri =>
new Promise((resolve, reject) => {
SiaAPI.call(uri, (err, response) => {
if (err) {
reject(err)
} else {
resolve(response)
}
})
})
const fetchStorageFiles = () =>
new Promise((resolve, reject) => {
siadCall({
url: '/host/storage',
method: 'GET'
})
.then(fetchedFiles => {
resolve(
List(
(fetchedFiles.folders || []).map(file =>
Map({
path: file.path,
size: new BigNumber(file.capacity).times('1e-9').toString(),
free: new BigNumber(file.capacityremaining)
.times('1e-9')
.toString()
})
)
)
)
})
.catch(reject)
})
function * announceHost (action) {
try {
yield put(actions.showAnnounceDialog(action.address))
const closeAction = yield take(constants.HIDE_ANNOUNCE_DIALOG)
if (closeAction.address !== '') {
// If size is zero just hide the dialog.
yield siadCall({
url: '/host/announce',
timeout: 30000, // 30 second timeout for host announcement
method: 'POST',
qs: { netaddress: closeAction.address }
})
}
} catch (e) {
SiaAPI.showError({ title: 'Error Announcing Host', content: e.message })
}
}
// bytesToStorage converts a BigNumber of GB to a valid size of storage, in
// bytes, rounded to the nearest 256MiB (64 * SectorSize).
const bytesToStorageBytes = async bytes => {
const settings = await siadCall('/host')
const roundedBytes = bytes.minus(
bytes.modulo(64 * settings.externalsettings.sectorsize)
)
if (roundedBytes.isNegative()) {
return '0'
}
return roundedBytes.toString()
}
function * addFolder (action) {
try {
yield siadCall({
url: '/host/storage/folders/add',
method: 'POST',
timeout: 1.7e8, // two day timeout for adding storage folders
qs: {
path: action.folder.get('path'),
size: action.folder.get('size') // bytes
}
})
yield put(actions.fetchData())
} catch (e) {
SiaAPI.showError({ title: 'Error Adding Folder', content: e.message })
}
}
function * addFolderAskPathSize () {
const newLocation = helper.chooseFileLocation()
if (newLocation) {
try {
yield put(
actions.showResizeDialog(Map({ path: newLocation, size: 50 }), true)
)
const closeAction = yield take(constants.HIDE_RESIZE_DIALOG)
const bytes = new BigNumber(closeAction.folder.get('size')).times(1e9)
const roundedBytes = yield bytesToStorageBytes(bytes)
if (closeAction.folder.get('size')) {
yield put(
actions.addFolder(
Map({
path: newLocation,
size: roundedBytes
})
)
)
}
} catch (e) {
SiaAPI.showError({ title: 'Error Adding Folder', content: e.message })
}
}
}
function * removeFolder (action) {
try {
yield siadCall({
url: '/host/storage/folders/remove',
timeout: 1.7e8, // two day timeout for removing storage folders
method: 'POST',
qs: {
path: action.folder.get('path')
}
})
yield put(actions.fetchData())
} catch (e) {
SiaAPI.showError({ title: 'Error Removing Folder', content: e.message })
}
}
function * resizeFolder (action) {
try {
yield put(actions.showResizeDialog(action.folder, action.ignoreInitial))
const closeAction = yield take(constants.HIDE_RESIZE_DIALOG)
const bytes = new BigNumber(closeAction.folder.get('size')).times(1e9)
const roundedBytes = yield bytesToStorageBytes(bytes)
if (closeAction.folder.get('size')) {
// If size is zero just hide the dialog.
yield siadCall({
url: '/host/storage/folders/resize',
timeout: 1.7e8, // two day timeout for resizing storage folders
method: 'POST',
qs: {
path: closeAction.folder.get('path'),
newsize: roundedBytes
}
})
yield put(actions.fetchData())
}
} catch (e) {
SiaAPI.showError({ title: 'Error Resizing Folder', content: e.message })
}
}
function * pushSettings (action) {
try {
yield siadCall({
url: '/host',
method: 'POST',
qs: {
acceptingcontracts: action.settings.get('acceptingContracts'),
maxduration: helper
.weeksToBlocks(action.settings.get('maxduration'))
.toString(),
collateral: helper
.SCTBMonthToHastingsByteBlock(action.settings.get('collateral'))
.toString(),
minstorageprice: helper
.SCTBMonthToHastingsByteBlock(action.settings.get('storageprice'))
.toString(), // bytes->TB, blocks -> month
mindownloadbandwidthprice: helper
.SCTBToHastingsByte(action.settings.get('downloadbandwidthprice'))
.toString()
}
})
yield put(actions.fetchData())
} catch (e) {
SiaAPI.showError({ title: 'Error Updating Settings', content: e.message })
}
}
const parseSettings = hostData =>
Map({
maxduration: helper
.blocksToWeeks(hostData.externalsettings.maxduration)
.toFixed(0),
collateral: helper
.hastingsByteBlockToSCTBMonth(hostData.externalsettings.collateral)
.toFixed(0),
storageprice: helper
.hastingsByteBlockToSCTBMonth(hostData.externalsettings.storageprice)
.toFixed(0),
downloadbandwidthprice: helper
.hastingsByteToSCTB(hostData.externalsettings.downloadbandwidthprice)
.toString(),
acceptingContracts: hostData.externalsettings.acceptingcontracts
})
// parseExpectedRevenue takes a host's `financialmetrics` object and returns
// the sum total expected revenue from contract compensation, storage revenue,
// and bandwidth revenue.
const parseExpectedRevenue = financialmetrics => {
const storagerevenue = new BigNumber(financialmetrics.potentialstoragerevenue)
const bwrevenue = new BigNumber(
financialmetrics.potentialdownloadbandwidthrevenue
).add(financialmetrics.potentialuploadbandwidthrevenue)
const contractrevenue = new BigNumber(
financialmetrics.potentialcontractcompensation
)
return storagerevenue.add(bwrevenue).add(contractrevenue)
}
// parseRevenue takes a host's `financialmetrics` object and returns the sum
// total earned revenue.
const parseRevenue = financialmetrics => {
const storagerevenue = new BigNumber(financialmetrics.storagerevenue)
const bwrevenue = new BigNumber(
financialmetrics.downloadbandwidthrevenue
).add(financialmetrics.uploadbandwidthrevenue)
const contractrevenue = new BigNumber(financialmetrics.contractcompensation)
return storagerevenue.add(bwrevenue).add(contractrevenue)
}
// updateSettingsSaga watches for updateSettings actions and performs any async
// tasks required.
function * updateSettingsSaga (action) {
try {
const res = yield siadCall({
url: '/host/estimatescore',
method: 'GET',
qs: {
maxduration: helper
.weeksToBlocks(action.settings.get('maxduration'))
.toString(),
collateral: helper
.SCTBMonthToHastingsByteBlock(action.settings.get('collateral'))
.toString(),
minstorageprice: helper
.SCTBMonthToHastingsByteBlock(action.settings.get('storageprice'))
.toString(),
mindownloadbandwidthprice: helper
.SCTBToHastingsByte(action.settings.get('downloadbandwidthprice'))
.toString()
}
})
const conversionRate = (() => {
const rate = new BigNumber(res.conversionrate.toString())
if (rate.gt(50)) {
return '>50'
}
return rate.round(2).toString()
})()
yield put(actions.setEstimatedScore(res.estimatedscore, conversionRate))
} catch (e) {
console.error(e.toString())
}
}
function * fetchData () {
try {
const updatedData = yield siadCall({ url: '/host' })
const walletUnlocked = yield siadCall({ url: '/wallet' })
const data = Map({
numContracts: updatedData.financialmetrics.contractcount,
storage: new BigNumber(updatedData.externalsettings.totalstorage)
.minus(new BigNumber(updatedData.externalsettings.remainingstorage))
.toString(),
earned: SiaAPI.hastingsToSiacoins(
parseRevenue(updatedData.financialmetrics)
)
.round(2)
.toString(),
expected: SiaAPI.hastingsToSiacoins(
parseExpectedRevenue(updatedData.financialmetrics)
)
.round(2)
.toString(),
files: yield fetchStorageFiles(),
walletLocked: !walletUnlocked.unlocked,
walletsize: walletUnlocked.confirmedsiacoinbalance
})
const modals = Map({
defaultAnnounceAddress: updatedData.externalsettings.netaddress
})
const settings = parseSettings(updatedData)
yield put(actions.fetchDataSuccess(data, settings, modals))
} catch (e) {
console.error('error fetching host data: ' + e.toString())
}
}
function * requestDefaultSettingsSaga () {
try {
const hostData = yield siadCall('/host')
yield put(actions.receiveDefaultSettings(parseSettings(hostData)))
const res = yield siadCall({
url: '/host/estimatescore',
method: 'GET'
})
yield put(
actions.setEstimatedScore(
res.estimatedscore,
new BigNumber(res.conversionrate).round(2).toString()
)
)
} catch (e) {
console.error('error fetching defaults: ' + e.toString())
}
}
// hostStatusSaga pulls the host's connectability and working status from the
// api and sets the UI's state accordingly.
function * hostStatusSaga () {
try {
const hostData = yield siadCall('/host')
yield put(
actions.setHostStatus(
hostData.connectabilitystatus,
hostData.workingstatus
)
)
} catch (e) {
console.error('error fetching host status: ' + e.toString())
}
}
function * pushSettingsListener () {
yield * takeEvery(constants.PUSH_SETTINGS, pushSettings)
}
function * fetchSettingsListener () {
yield * takeEvery(constants.FETCH_DATA, fetchData)
}
function * addFolderListener () {
yield * takeEvery(constants.ADD_FOLDER, addFolder)
}
function * addFolderAskListener () {
yield * takeEvery(constants.ADD_FOLDER_ASK, addFolderAskPathSize)
}
function * removeFolderListener () {
yield * takeEvery(constants.REMOVE_FOLDER, removeFolder)
}
function * resizeFolderListener () {
yield * takeEvery(constants.RESIZE_FOLDER, resizeFolder)
}
function * announceHostListener () {
yield * takeEvery(constants.ANNOUNCE_HOST, announceHost)
}
function * requestDefaultsListener () {
yield * takeEvery(
constants.REQUEST_DEFAULT_SETTINGS,
requestDefaultSettingsSaga
)
}
function * hostStatusListener () {
yield * takeEvery(constants.GET_HOST_STATUS, hostStatusSaga)
}
function * updateSettingsListener () {
yield * takeEvery(constants.UPDATE_SETTINGS, updateSettingsSaga)
}
export default function * initSaga () {
yield [
fork(pushSettingsListener),
fork(fetchSettingsListener),
fork(addFolderListener),
fork(addFolderAskListener),
fork(removeFolderListener),
fork(resizeFolderListener),
fork(announceHostListener),
fork(requestDefaultsListener),
fork(hostStatusListener),
fork(updateSettingsListener)
]
}
|
function onDeleteButtonClicked(){
var cities = document.getElementsByClassName('city');
if(cities.length > 0){
cities[0].remove();
}else{
document.getElementById('count').innerHTML = 'No city to remove!';
}
}
function onShuffleButtonClicked(){
//var seq = ['london','paris','tokyo','beijing'];
//shuffle(seq);
var london = document.getElementById('london');
var paris = document.getElementById('paris');
var tokyo = document.getElementById('tokyo');
var beijing = document.getElementById('beijing');
var cities = [london,paris,tokyo,beijing];
shuffle(cities);
var cityNames = [];
for(var i in cities){
cityNames.push(cities[i].id);
cities[cities.length-1].parentNode.insertBefore(cities[i],cities[cities.length-1]);
}
//document.getElementById('count').innerHTML = cityNames;
}
function minimize(){
var gui = require('nw.gui');
var win = gui.Window.get();
win.minimize();
}
function close2(){
var gui = require('nw.gui');
var win = gui.Window.get();
win.close();
}
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex ;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function allowDrop(ev) {
ev.preventDefault();
}
function drop(ev) {
ev.preventDefault();
var dragId = ev.dataTransfer.getData("text");
var dropId = ev.currentTarget.id;
var elementToDrag = document.getElementById(dragId);
var elementToDrop = document.getElementById(dropId);
var cities = document.getElementsByClassName('city');
var direction;
for(var i in cities){
if(cities[i].id == elementToDrop.id){
direction = 'right';
break;
}
if(cities[i].id == elementToDrag.id){
direction = 'left';
break;
}
}
if(direction == 'left'){
elementToDrop.parentNode.insertBefore(elementToDrag, elementToDrop.nextElementSibling);
}else{
elementToDrop.parentNode.insertBefore(elementToDrag, elementToDrop);
}
}
|
export function fetchWelcomeText() {
return {
type: "FETCH_WELCOME_TEXT_FULFILLED",
payload: {
welcomeText: "Develope UI-Elements with React"
}
}
} |
import appEvents from '../service/appEvents.js';
import eventify from 'ngraph.events';
import scene from '../store/scene.js';
import qs from 'qs';
var defaultConfig = {
pos: {x : 0, y: 0, z: 0 },
lookAt: {x: 0, y: 0, z: 0, w: 1},
showLinks: true,
maxVisibleDistance: 150,
scale: 1.75,
manifestVersion: 0
};
export default appConfig();
function appConfig() {
var hashConfig = parseFromHash(window.location.hash);
var hashUpdate; // async hash update id
var api = {
getCameraPosition: getCameraPosition,
getCameraLookAt: getCameraLookAt,
getShowLinks: getShowLinks,
getScaleFactor: getScaleFactor,
getMaxVisibleEdgeLength: getMaxVisibleEdgeLength,
setCameraConfig: setCameraConfig,
setShowLinks: setShowLinks,
getManifestVersion: getManifestVersion,
setManifestVersion: setManifestVersion
};
appEvents.toggleLinks.on(toggleLinks);
appEvents.queryChanged.on(queryChanged);
eventify(api);
return api;
function getScaleFactor() {
return hashConfig.scale;
}
function getManifestVersion() {
return hashConfig.manifestVersion;
}
function getMaxVisibleEdgeLength() {
return hashConfig.maxVisibleDistance * hashConfig.maxVisibleDistance * hashConfig.scale;
}
function getCameraPosition() {
return hashConfig.pos;
}
function toggleLinks() {
setShowLinks(!hashConfig.showLinks);
}
function getCameraLookAt() {
return hashConfig.lookAt;
}
function getShowLinks() {
return hashConfig.showLinks;
}
function queryChanged() {
var currentHashConfig = parseFromHash(window.location.hash);
var cameraChanged = !same(currentHashConfig.pos, hashConfig.pos) ||
!same(currentHashConfig.lookAt, hashConfig.lookAt);
var showLinksChanged = hashConfig.showLinks !== currentHashConfig.showLinks;
if (cameraChanged) {
setCameraConfig(currentHashConfig.pos, currentHashConfig.lookAt);
api.fire('camera');
}
if (showLinksChanged) {
setShowLinks(currentHashConfig.showLinks);
}
setManifestVersion(currentHashConfig.manifestVersion);
}
function setShowLinks(linksVisible) {
if (linksVisible === hashConfig.showLinks) return;
hashConfig.showLinks = linksVisible;
api.fire('showLinks');
updateHash();
}
function setManifestVersion(version) {
if (version === hashConfig.manifestVersion) return;
hashConfig.manifestVersion = version;
updateHash();
var name = scene.getGraphName();
appEvents.downloadGraphRequested.fire(name);
}
function setCameraConfig(pos, lookAt) {
if (same(pos, hashConfig.pos) &&
same(lookAt, hashConfig.lookAt) &&
lookAt.w === hashConfig.lookAt.w) return;
hashConfig.pos.x = pos.x;
hashConfig.pos.y = pos.y;
hashConfig.pos.z = pos.z;
hashConfig.lookAt.x = lookAt.x;
hashConfig.lookAt.y = lookAt.y;
hashConfig.lookAt.z = lookAt.z;
hashConfig.lookAt.w = lookAt.w;
updateHash();
}
function updateHash() {
var name = scene.getGraphName();
var pos = hashConfig.pos;
var lookAt = hashConfig.lookAt;
var hash = '#/galaxy/' + name +
'?cx=' + Math.round(pos.x) +
'&cy=' + Math.round(pos.y) +
'&cz=' + Math.round(pos.z) +
'&lx=' + lookAt.x.toFixed(4) +
'&ly=' + lookAt.y.toFixed(4) +
'&lz=' + lookAt.z.toFixed(4) +
'&lw=' + lookAt.w.toFixed(4) +
'&ml=' + hashConfig.maxVisibleDistance +
'&s=' + hashConfig.scale +
'&l=' + (hashConfig.showLinks ? '1' : '0') +
'&v=' + hashConfig.manifestVersion;
setHash(hash);
}
function setHash(hash) {
// I noticed Chrome address string becomes very slow if we update URL too
// often. Thus, I'm adding small throttling here.
if (hashUpdate) {
window.clearTimeout(hashUpdate);
}
hashUpdate = setTimeout(function() {
if (window.history) {
window.history.replaceState(undefined, undefined, hash);
} else {
window.location.replace(hash);
}
hashUpdate = null;
}, 400);
}
function same(v1, v2) {
if (!v1 || !v2) return false;
return v1.x === v2.x &&
v1.y === v2.y &&
v1.z === v2.z;
}
function parseFromHash(hash) {
if (!hash) {
return defaultConfig;
}
var query = qs.parse(hash.split('?')[1]);
var pos = {
x: query.cx || 0,
y: query.cy || 0,
z: query.cz || 0
};
var lookAt = {
x: query.lx || 0,
y: query.ly || 0,
z: query.lz || 0,
w: getNumber(query.lw || 1)
};
var showLinks = (query.l === '1');
return {
pos: normalize(pos),
lookAt: normalize(lookAt),
showLinks: showLinks,
maxVisibleDistance: getNumber(query.ml, defaultConfig.maxVisibleDistance),
scale: getNumber(query.s, defaultConfig.scale),
manifestVersion: query.v || defaultConfig.manifestVersion
};
}
}
function normalize(v) {
if (!v) return v;
v.x = getNumber(v.x);
v.y = getNumber(v.y);
v.z = getNumber(v.z);
return v;
}
function getNumber(x, defaultValue) {
if (defaultValue === undefined) defaultValue = 0;
x = parseFloat(x);
if (isNaN(x)) return defaultValue;
return x;
}
|
/**
* @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'filetools', 'es', {
loadError: 'Ha ocurrido un error durante la lectura del archivo.',
networkError: 'Error de red ocurrido durante carga de archivo.',
httpError404: 'Un error HTTP ha ocurrido durante la carga del archivo (404: Archivo no encontrado).',
httpError403: 'Un error HTTP ha ocurrido durante la carga del archivo (403: Prohibido).',
httpError: 'Error HTTP ocurrido durante la carga del archivo (Estado del error: %1).',
noUrlError: 'URL cargada no está definida.',
responseError: 'Respueta del servidor incorrecta.'
} );
|
"use strict";
var _getPrototypeOf = require("babel-runtime/core-js/object/get-prototype-of");
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn");
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require("babel-runtime/helpers/inherits");
var _inherits3 = _interopRequireDefault(_inherits2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Node_1 = require('./Node');
var SelfClosingNode = function (_Node_1$Node) {
(0, _inherits3.default)(SelfClosingNode, _Node_1$Node);
function SelfClosingNode() {
(0, _classCallCheck3.default)(this, SelfClosingNode);
return (0, _possibleConstructorReturn3.default)(this, (SelfClosingNode.__proto__ || (0, _getPrototypeOf2.default)(SelfClosingNode)).apply(this, arguments));
}
return SelfClosingNode;
}(Node_1.Node);
exports.SelfClosingNode = SelfClosingNode; |
var bubu ={ s64:"713",s65:"2442",s11:"3227",s12:"2234",s13:"8159",s14:"3504",s15:"3318",s21:"5371",s22:"4448",s23:"4954",s31:"4465",s32:"9525",s33:"6300",s34:"6306",s35:"4666",s36:"5466",s37:"11388",s41:"11547",s42:"8823",s43:"8204",s44:"10078",s45:"5459",s46:"1240",s50:"2804",s51:"8409",s52:"2732",s53:"2923",s54:"71",s61:"5387",s62:"3075",s63:"547" };
var title = "2004年教育程度-高中";
var unit = "人";
function getColor(d) {
return d > 10000 ? '#800026' :
d > 8300 ? '#BD0026' :
d > 5500 ? '#E31A1C' :
d > 4700 ? '#FC4E2A' :
d > 3400 ? '#FD8D3C' :
d > 2900 ? '#FEB24C' :
d > 2000 ? '#FED976' :
d > 70 ? '#FFEDA0' :
d < 0 ? '#000000' :
'#000000';
}
var vgrades = [70, 2000, 2900, 3400, 4700, 5500, 8300, 10000]; |
/**
@module ember
@submodule ember-htmlbars
*/
import Ember from "ember-metal/core"; // Ember.assert
import { dasherize } from "ember-template-compiler/system/string";
/**
An HTMLBars AST transformation that replaces all instances of
{{bind-attr}} helpers with the equivalent HTMLBars-style bound
attributes. For example
```handlebars
<div {{bind-attr class=":foo some.path:bar"}}></div>
```
becomes
```handlebars
<div class="foo {{if some.path "bar" ""}}></div>
```
@class TransformBindAttrToAttributes
@private
*/
function TransformBindAttrToAttributes() {
// set later within HTMLBars to the syntax package
this.syntax = null;
}
/**
@private
@method transform
@param {AST} The AST to be transformed.
*/
TransformBindAttrToAttributes.prototype.transform = function TransformBindAttrToAttributes_transform(ast) {
var plugin = this;
var walker = new this.syntax.Walker();
walker.visit(ast, function(node) {
if (node.type === 'ElementNode') {
for (var i = 0; i < node.modifiers.length; i++) {
var modifier = node.modifiers[i];
if (isBindAttrModifier(modifier)) {
node.modifiers.splice(i--, 1);
plugin.assignAttrs(node, modifier.hash);
}
}
}
});
return ast;
};
TransformBindAttrToAttributes.prototype.assignAttrs = function assignAttrs(element, hash) {
var pairs = hash.pairs;
for (var i = 0; i < pairs.length; i++) {
var name = pairs[i].key;
var value = pairs[i].value;
assertAttrNameIsUnused(element, name);
var attr = this.syntax.builders.attr(name, this.transformValue(name, value));
element.attributes.push(attr);
}
};
TransformBindAttrToAttributes.prototype.transformValue = function transformValue(name, value) {
var b = this.syntax.builders;
if (name === 'class') {
switch (value.type) {
case 'StringLiteral':
return this.parseClasses(value.value);
case 'PathExpression':
return this.parseClasses(value.original);
case 'SubExpression':
return b.mustache(value.path, value.params, value.hash);
default:
Ember.assert("Unsupported attribute value type: " + value.type);
}
} else {
switch (value.type) {
case 'StringLiteral':
return b.mustache(b.path(value.value));
case 'PathExpression':
return b.mustache(value);
case 'SubExpression':
return b.mustache(value.path, value.params, value.hash);
default:
Ember.assert("Unsupported attribute value type: " + value.type);
}
}
};
TransformBindAttrToAttributes.prototype.parseClasses = function parseClasses(value) {
var b = this.syntax.builders;
var concat = b.concat();
var classes = value.split(' ');
for (var i = 0; i < classes.length; i++) {
if (i > 0) {
concat.parts.push(b.string(' '));
}
var concatPart = this.parseClass(classes[i]);
concat.parts.push(concatPart);
}
return concat;
};
TransformBindAttrToAttributes.prototype.parseClass = function parseClass(value) {
var b = this.syntax.builders;
var parts = value.split(':');
switch (parts.length) {
case 1:
// Before: {{bind-attr class="view.fooBar ..."}}
// After: class="{{-bind-attr-class view.fooBar "foo-bar"}} ..."
return b.sexpr(b.path('-bind-attr-class'), [
b.path(parts[0]),
b.string(dasherizeLastKey(parts[0]))
]);
case 2:
if (parts[0] === '') {
// Before: {{bind-attr class=":foo ..."}}
// After: class="foo ..."
return b.string(parts[1]);
} else {
// Before: {{bind-attr class="some.path:foo ..."}}
// After: class="{{if some.path "foo" ""}} ..."
return b.sexpr(b.path('if'), [
b.path(parts[0]),
b.string(parts[1]),
b.string('')
]);
}
break;
case 3:
// Before: {{bind-attr class="some.path:foo:bar ..."}}
// After: class="{{if some.path "foo" "bar"}} ..."
return b.sexpr(b.path('if'), [
b.path(parts[0]),
b.string(parts[1]),
b.string(parts[2])
]);
default:
Ember.assert("Unsupported bind-attr class syntax: `" + value + "`");
}
};
function isBindAttrModifier(modifier) {
var name = modifier.path.original;
if (name === 'bind-attr' || name === 'bindAttr') {
Ember.deprecate(
'The `' + name + '` helper is deprecated in favor of ' +
'HTMLBars-style bound attributes'
);
return true;
} else {
return false;
}
}
function assertAttrNameIsUnused(element, name) {
for (var i = 0; i < element.attributes.length; i++) {
var attr = element.attributes[i];
if (attr.name === name) {
if (name === 'class') {
Ember.assert(
'You cannot set `class` manually and via `{{bind-attr}}` helper ' +
'on the same element. Please use `{{bind-attr}}`\'s `:static-class` ' +
'syntax instead.'
);
} else {
Ember.assert(
'You cannot set `' + name + '` manually and via `{{bind-attr}}` ' +
'helper on the same element.'
);
}
}
}
}
function dasherizeLastKey(path) {
var parts = path.split('.');
return dasherize(parts[parts.length - 1]);
}
export default TransformBindAttrToAttributes;
|
const DrawCard = require('../../drawcard.js');
class Halder extends DrawCard {
setupCardAbilities(ability) {
this.action({
title: 'Kneel a location or attachment',
cost: ability.costs.kneel(card => (
card.isFaction('thenightswatch') &&
(card.getType() === 'attachment' || card.getType() === 'location')
)),
target: {
cardCondition: card => card.isFaction('thenightswatch') && card.getType() === 'character'
},
handler: (context) => {
this.game.addMessage('{0} uses {1} and kneels {2} to give {3} +1 STR until the end of the phase', this.controller, this, context.costs.kneel, context.target);
this.untilEndOfPhase(ability => ({
match: context.target,
effect: ability.effects.modifyStrength(1)
}));
}
});
}
}
Halder.code = '02065';
module.exports = Halder;
|
var helpers = function(swig){};
module.exports = helpers; |
mainApp.controller('mainController', function($scope) {
});
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zM4 12c0-4.4 3.6-8 8-8 1.8 0 3.5.6 4.9 1.7L5.7 16.9C4.6 15.5 4 13.8 4 12zm8 8c-1.8 0-3.5-.6-4.9-1.7L18.3 7.1C19.4 8.5 20 10.2 20 12c0 4.4-3.6 8-8 8z"
}), 'DoNotDisturbAlt');
exports.default = _default; |
'use strict';
const bundleTypes = {
UMD_DEV: 'UMD_DEV',
UMD_PROD: 'UMD_PROD',
UMD_PROFILING: 'UMD_PROFILING',
NODE_DEV: 'NODE_DEV',
NODE_PROD: 'NODE_PROD',
NODE_PROFILING: 'NODE_PROFILING',
FB_WWW_DEV: 'FB_WWW_DEV',
FB_WWW_PROD: 'FB_WWW_PROD',
FB_WWW_PROFILING: 'FB_WWW_PROFILING',
RN_OSS_DEV: 'RN_OSS_DEV',
RN_OSS_PROD: 'RN_OSS_PROD',
RN_OSS_PROFILING: 'RN_OSS_PROFILING',
RN_FB_DEV: 'RN_FB_DEV',
RN_FB_PROD: 'RN_FB_PROD',
RN_FB_PROFILING: 'RN_FB_PROFILING',
};
const {
UMD_DEV,
UMD_PROD,
UMD_PROFILING,
NODE_DEV,
NODE_PROD,
NODE_PROFILING,
FB_WWW_DEV,
FB_WWW_PROD,
FB_WWW_PROFILING,
RN_OSS_DEV,
RN_OSS_PROD,
RN_OSS_PROFILING,
RN_FB_DEV,
RN_FB_PROD,
RN_FB_PROFILING,
} = bundleTypes;
const moduleTypes = {
// React
ISOMORPHIC: 'ISOMORPHIC',
// Individual renderers. They bundle the reconciler. (e.g. ReactDOM)
RENDERER: 'RENDERER',
// Helper packages that access specific renderer's internals. (e.g. TestUtils)
RENDERER_UTILS: 'RENDERER_UTILS',
// Standalone reconciler for third-party renderers.
RECONCILER: 'RECONCILER',
// Non-Fiber implementations like SSR and Shallow renderers.
NON_FIBER_RENDERER: 'NON_FIBER_RENDERER',
};
const {
ISOMORPHIC,
RENDERER,
RENDERER_UTILS,
RECONCILER,
NON_FIBER_RENDERER,
} = moduleTypes;
const bundles = [
/******* Isomorphic *******/
{
bundleTypes: [
UMD_DEV,
UMD_PROD,
UMD_PROFILING,
NODE_DEV,
NODE_PROD,
FB_WWW_DEV,
FB_WWW_PROD,
FB_WWW_PROFILING,
],
moduleType: ISOMORPHIC,
entry: 'react',
global: 'React',
externals: [],
},
/******* React JSX Runtime *******/
{
bundleTypes: [
NODE_DEV,
NODE_PROD,
NODE_PROFILING,
// TODO: use on WWW.
],
moduleType: ISOMORPHIC,
entry: 'react/jsx-runtime',
global: 'JSXRuntime',
externals: ['react'],
},
/******* React JSX DEV Runtime *******/
{
bundleTypes: [
NODE_DEV,
NODE_PROD,
NODE_PROFILING,
FB_WWW_DEV,
FB_WWW_PROD,
FB_WWW_PROFILING,
],
moduleType: ISOMORPHIC,
entry: 'react/jsx-dev-runtime',
global: 'JSXDEVRuntime',
externals: ['react'],
},
/******* React Cache (experimental, new) *******/
{
bundleTypes: [NODE_DEV, NODE_PROD, NODE_PROFILING],
moduleType: ISOMORPHIC,
entry: 'react/unstable-cache',
global: 'ReactCache',
externals: ['react'],
},
/******* React Fetch Browser (experimental, new) *******/
{
bundleTypes: [
NODE_DEV,
NODE_PROD,
NODE_PROFILING,
FB_WWW_DEV,
FB_WWW_PROD,
FB_WWW_PROFILING,
],
moduleType: ISOMORPHIC,
entry: 'react-fetch/index.browser',
global: 'ReactFetch',
externals: ['react'],
},
/******* React Fetch Node (experimental, new) *******/
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: ISOMORPHIC,
entry: 'react-fetch/index.node',
global: 'ReactFetch',
externals: ['react', 'http', 'https'],
},
/******* React DOM *******/
{
bundleTypes: [
UMD_DEV,
UMD_PROD,
UMD_PROFILING,
NODE_DEV,
NODE_PROD,
NODE_PROFILING,
FB_WWW_DEV,
FB_WWW_PROD,
FB_WWW_PROFILING,
],
moduleType: RENDERER,
entry: 'react-dom',
global: 'ReactDOM',
externals: ['react'],
},
/******* React DOM - www - Uses forked reconciler *******/
{
moduleType: RENDERER,
bundleTypes: [FB_WWW_DEV, FB_WWW_PROD, FB_WWW_PROFILING],
entry: 'react-dom',
global: 'ReactDOMForked',
enableNewReconciler: true,
externals: ['react'],
},
/******* Test Utils *******/
{
moduleType: RENDERER_UTILS,
bundleTypes: [FB_WWW_DEV, NODE_DEV, NODE_PROD, UMD_DEV, UMD_PROD],
entry: 'react-dom/test-utils',
global: 'ReactTestUtils',
externals: ['react', 'react-dom'],
},
/******* React DOM - www - Testing *******/
{
moduleType: RENDERER,
bundleTypes: [FB_WWW_DEV, FB_WWW_PROD],
entry: 'react-dom/testing',
global: 'ReactDOMTesting',
externals: ['react'],
},
/******* React DOM Server *******/
{
bundleTypes: [
UMD_DEV,
UMD_PROD,
NODE_DEV,
NODE_PROD,
FB_WWW_DEV,
FB_WWW_PROD,
],
moduleType: NON_FIBER_RENDERER,
entry: 'react-dom/server.browser',
global: 'ReactDOMServer',
externals: ['react'],
babel: opts =>
Object.assign({}, opts, {
plugins: opts.plugins.concat([
[require.resolve('@babel/plugin-transform-classes'), {loose: true}],
]),
}),
},
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: NON_FIBER_RENDERER,
entry: 'react-dom/server.node',
externals: ['react', 'stream'],
babel: opts =>
Object.assign({}, opts, {
plugins: opts.plugins.concat([
[require.resolve('@babel/plugin-transform-classes'), {loose: true}],
]),
}),
},
/******* React DOM Fizz Server *******/
{
bundleTypes: [NODE_DEV, NODE_PROD, UMD_DEV, UMD_PROD],
moduleType: RENDERER,
entry: 'react-dom/unstable-fizz.browser',
global: 'ReactDOMFizzServer',
externals: ['react', 'react-dom/server'],
},
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: RENDERER,
entry: 'react-dom/unstable-fizz.node',
global: 'ReactDOMFizzServer',
externals: ['react', 'react-dom/server'],
},
/******* React Transport DOM Server Webpack *******/
{
bundleTypes: [NODE_DEV, NODE_PROD, UMD_DEV, UMD_PROD],
moduleType: RENDERER,
entry: 'react-transport-dom-webpack/server.browser',
global: 'ReactTransportDOMServer',
externals: ['react', 'react-dom/server'],
},
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: RENDERER,
entry: 'react-transport-dom-webpack/server.node',
global: 'ReactTransportDOMServer',
externals: ['react', 'react-dom/server'],
},
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: RENDERER,
entry: 'react-transport-dom-webpack/server-runtime',
global: 'ReactTransportDOMServerRuntime',
externals: ['react'],
},
/******* React Transport DOM Client Webpack *******/
{
bundleTypes: [NODE_DEV, NODE_PROD, UMD_DEV, UMD_PROD],
moduleType: RENDERER,
entry: 'react-transport-dom-webpack',
global: 'ReactTransportDOMClient',
externals: ['react'],
},
/******* React Transport DOM Webpack Plugin *******/
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: RENDERER_UTILS,
entry: 'react-transport-dom-webpack/plugin',
global: 'ReactFlightWebpackPlugin',
externals: [],
babel: opts =>
Object.assign({}, opts, {
// Include JSX
presets: opts.presets.concat([
require.resolve('@babel/preset-react'),
require.resolve('@babel/preset-flow'),
]),
plugins: opts.plugins.concat([
[require.resolve('@babel/plugin-transform-classes'), {loose: true}],
]),
}),
},
/******* React Transport DOM Server Relay *******/
{
bundleTypes: [FB_WWW_DEV, FB_WWW_PROD],
moduleType: RENDERER,
entry: 'react-transport-dom-relay/server',
global: 'ReactFlightDOMRelayServer',
externals: [
'react',
'react-dom/server',
'ReactFlightDOMRelayServerIntegration',
],
},
{
bundleTypes: [FB_WWW_DEV, FB_WWW_PROD],
moduleType: RENDERER,
entry: 'react-transport-dom-relay/server-runtime',
global: 'ReactFlightDOMRelayServerRuntime',
externals: ['react', 'ReactFlightDOMRelayServerIntegration'],
},
/******* React DOM Flight Client Relay *******/
{
bundleTypes: [FB_WWW_DEV, FB_WWW_PROD],
moduleType: RENDERER,
entry: 'react-transport-dom-relay',
global: 'ReactFlightDOMRelayClient',
externals: ['react', 'ReactFlightDOMRelayClientIntegration'],
},
/******* React ART *******/
{
bundleTypes: [
UMD_DEV,
UMD_PROD,
NODE_DEV,
NODE_PROD,
FB_WWW_DEV,
FB_WWW_PROD,
],
moduleType: RENDERER,
entry: 'react-art',
global: 'ReactART',
externals: ['react'],
babel: opts =>
Object.assign({}, opts, {
// Include JSX
presets: opts.presets.concat([
require.resolve('@babel/preset-react'),
require.resolve('@babel/preset-flow'),
]),
plugins: opts.plugins.concat([
[require.resolve('@babel/plugin-transform-classes'), {loose: true}],
]),
}),
},
/******* React Native *******/
{
bundleTypes: [RN_FB_DEV, RN_FB_PROD, RN_FB_PROFILING],
moduleType: RENDERER,
entry: 'react-native-renderer',
global: 'ReactNativeRenderer',
externals: ['react-native'],
babel: opts =>
Object.assign({}, opts, {
plugins: opts.plugins.concat([
[require.resolve('@babel/plugin-transform-classes'), {loose: true}],
]),
}),
},
{
bundleTypes: [RN_OSS_DEV, RN_OSS_PROD, RN_OSS_PROFILING],
moduleType: RENDERER,
entry: 'react-native-renderer',
global: 'ReactNativeRenderer',
externals: ['react-native'],
babel: opts =>
Object.assign({}, opts, {
plugins: opts.plugins.concat([
[require.resolve('@babel/plugin-transform-classes'), {loose: true}],
]),
}),
},
/******* React Native Fabric *******/
{
bundleTypes: [RN_FB_DEV, RN_FB_PROD, RN_FB_PROFILING],
moduleType: RENDERER,
entry: 'react-native-renderer/fabric',
global: 'ReactFabric',
externals: ['react-native'],
babel: opts =>
Object.assign({}, opts, {
plugins: opts.plugins.concat([
[require.resolve('@babel/plugin-transform-classes'), {loose: true}],
]),
}),
},
{
bundleTypes: [RN_OSS_DEV, RN_OSS_PROD, RN_OSS_PROFILING],
moduleType: RENDERER,
entry: 'react-native-renderer/fabric',
global: 'ReactFabric',
externals: ['react-native'],
babel: opts =>
Object.assign({}, opts, {
plugins: opts.plugins.concat([
[require.resolve('@babel/plugin-transform-classes'), {loose: true}],
]),
}),
},
/******* React Test Renderer *******/
{
bundleTypes: [FB_WWW_DEV, NODE_DEV, NODE_PROD, UMD_DEV, UMD_PROD],
moduleType: RENDERER,
entry: 'react-test-renderer',
global: 'ReactTestRenderer',
externals: ['react', 'scheduler', 'scheduler/unstable_mock'],
babel: opts =>
Object.assign({}, opts, {
plugins: opts.plugins.concat([
[require.resolve('@babel/plugin-transform-classes'), {loose: true}],
]),
}),
},
{
bundleTypes: [UMD_DEV, UMD_PROD],
moduleType: NON_FIBER_RENDERER,
entry: 'react-test-renderer/shallow',
global: 'ReactShallowRenderer',
externals: ['react', 'scheduler', 'scheduler/unstable_mock'],
babel: opts =>
Object.assign({}, opts, {
plugins: opts.plugins.concat([
[require.resolve('@babel/plugin-transform-classes'), {loose: true}],
]),
}),
},
/******* React Noop Renderer (used for tests) *******/
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: RENDERER,
entry: 'react-noop-renderer',
global: 'ReactNoopRenderer',
externals: ['react', 'scheduler', 'scheduler/unstable_mock', 'expect'],
},
/******* React Noop Persistent Renderer (used for tests) *******/
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: RENDERER,
entry: 'react-noop-renderer/persistent',
global: 'ReactNoopRendererPersistent',
externals: ['react', 'scheduler', 'expect'],
},
/******* React Noop Server Renderer (used for tests) *******/
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: RENDERER,
entry: 'react-noop-renderer/server',
global: 'ReactNoopRendererServer',
externals: ['react', 'scheduler', 'expect'],
},
/******* React Noop Flight Server (used for tests) *******/
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: RENDERER,
entry: 'react-noop-renderer/flight-server',
global: 'ReactNoopFlightServer',
externals: [
'react',
'scheduler',
'expect',
'react-noop-renderer/flight-modules',
],
},
/******* React Noop Flight Client (used for tests) *******/
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: RENDERER,
entry: 'react-noop-renderer/flight-client',
global: 'ReactNoopFlightClient',
externals: [
'react',
'scheduler',
'expect',
'react-noop-renderer/flight-modules',
],
},
/******* React Reconciler *******/
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: RECONCILER,
entry: 'react-reconciler',
global: 'ReactReconciler',
externals: ['react'],
},
/******* React Server *******/
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: RECONCILER,
entry: 'react-server',
global: 'ReactServer',
externals: ['react'],
},
/******* React Flight Server *******/
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: RECONCILER,
entry: 'react-server/flight',
global: 'ReactFlightServer',
externals: ['react'],
},
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: RENDERER,
entry: 'react-server/flight-server-runtime',
global: 'ReactFlightServerRuntime',
externals: ['react'],
},
/******* React Flight Client *******/
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: RECONCILER,
entry: 'react-client/flight',
global: 'ReactFlightClient',
externals: ['react'],
},
/******* Reflection *******/
{
moduleType: RENDERER_UTILS,
bundleTypes: [NODE_DEV, NODE_PROD],
entry: 'react-reconciler/reflection',
global: 'ReactFiberTreeReflection',
externals: [],
},
/******* React Is *******/
{
bundleTypes: [
NODE_DEV,
NODE_PROD,
FB_WWW_DEV,
FB_WWW_PROD,
UMD_DEV,
UMD_PROD,
],
moduleType: ISOMORPHIC,
entry: 'react-is',
global: 'ReactIs',
externals: [],
},
/******* React Debug Tools *******/
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: ISOMORPHIC,
entry: 'react-debug-tools',
global: 'ReactDebugTools',
externals: [],
},
/******* React Cache (experimental, old) *******/
{
// This is only used by our own tests.
// We can delete it later.
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: ISOMORPHIC,
entry: 'react-cache',
global: 'ReactCacheOld',
externals: ['react', 'scheduler'],
},
/******* createComponentWithSubscriptions *******/
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: ISOMORPHIC,
entry: 'create-subscription',
global: 'createSubscription',
externals: ['react'],
babel: opts =>
Object.assign({}, opts, {
plugins: opts.plugins.concat([
[require.resolve('@babel/plugin-transform-classes'), {loose: true}],
]),
}),
},
/******* Hook for managing subscriptions safely *******/
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: ISOMORPHIC,
entry: 'use-subscription',
global: 'useSubscription',
externals: ['react'],
},
/******* React Scheduler (experimental) *******/
{
bundleTypes: [
NODE_DEV,
NODE_PROD,
FB_WWW_DEV,
FB_WWW_PROD,
FB_WWW_PROFILING,
],
moduleType: ISOMORPHIC,
entry: 'scheduler',
global: 'Scheduler',
externals: [],
},
/******* React Scheduler Mock (experimental) *******/
{
bundleTypes: [
UMD_DEV,
UMD_PROD,
NODE_DEV,
NODE_PROD,
FB_WWW_DEV,
FB_WWW_PROD,
],
moduleType: ISOMORPHIC,
entry: 'scheduler/unstable_mock',
global: 'SchedulerMock',
externals: [],
},
/******* Jest React (experimental) *******/
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: ISOMORPHIC,
entry: 'jest-react',
global: 'JestReact',
externals: [],
},
/******* ESLint Plugin for Hooks *******/
{
// TODO: it's awkward to create a bundle for this but if we don't, the package
// won't get copied. We also can't create just DEV bundle because it contains a
// NODE_ENV check inside. We should probably tweak our build process to allow
// "raw" packages that don't get bundled.
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: ISOMORPHIC,
entry: 'eslint-plugin-react-hooks',
global: 'ESLintPluginReactHooks',
externals: [],
},
/******* React Fresh *******/
{
bundleTypes: [NODE_DEV, NODE_PROD],
moduleType: ISOMORPHIC,
entry: 'react-refresh/babel',
global: 'ReactFreshBabelPlugin',
externals: [],
},
{
bundleTypes: [NODE_DEV, NODE_PROD, FB_WWW_DEV],
moduleType: ISOMORPHIC,
entry: 'react-refresh/runtime',
global: 'ReactFreshRuntime',
externals: [],
},
{
bundleTypes: [
FB_WWW_DEV,
FB_WWW_PROD,
FB_WWW_PROFILING,
NODE_DEV,
NODE_PROD,
NODE_PROFILING,
],
moduleType: ISOMORPHIC,
entry: 'scheduler/tracing',
global: 'SchedulerTracing',
externals: [],
},
/******* React Events (experimental) *******/
{
bundleTypes: [
UMD_DEV,
UMD_PROD,
NODE_DEV,
NODE_PROD,
FB_WWW_DEV,
FB_WWW_PROD,
],
moduleType: NON_FIBER_RENDERER,
entry: 'react-interactions/events/context-menu',
global: 'ReactEventsContextMenu',
externals: ['react'],
},
{
bundleTypes: [
UMD_DEV,
UMD_PROD,
NODE_DEV,
NODE_PROD,
FB_WWW_DEV,
FB_WWW_PROD,
],
moduleType: NON_FIBER_RENDERER,
entry: 'react-interactions/events/deprecated-focus',
global: 'ReactEventsFocus',
externals: ['react'],
},
{
bundleTypes: [
UMD_DEV,
UMD_PROD,
NODE_DEV,
NODE_PROD,
FB_WWW_DEV,
FB_WWW_PROD,
],
moduleType: NON_FIBER_RENDERER,
entry: 'react-interactions/events/hover',
global: 'ReactEventsHover',
externals: ['react'],
},
{
bundleTypes: [
UMD_DEV,
UMD_PROD,
NODE_DEV,
NODE_PROD,
FB_WWW_DEV,
FB_WWW_PROD,
],
moduleType: NON_FIBER_RENDERER,
entry: 'react-interactions/events/keyboard',
global: 'ReactEventsKeyboard',
externals: ['react'],
},
{
bundleTypes: [
UMD_DEV,
UMD_PROD,
NODE_DEV,
NODE_PROD,
FB_WWW_DEV,
FB_WWW_PROD,
],
moduleType: NON_FIBER_RENDERER,
entry: 'react-interactions/events/press-legacy',
global: 'ReactEventsPressLegacy',
externals: ['react'],
},
];
const fbBundleExternalsMap = {
'react-interactions/events/focus': 'ReactEventsFocus',
'react-interactions/events/keyboard': 'ReactEventsKeyboard',
'react-interactions/events/tap': 'ReactEventsTap',
};
// Based on deep-freeze by substack (public domain)
function deepFreeze(o) {
Object.freeze(o);
Object.getOwnPropertyNames(o).forEach(function(prop) {
if (
o[prop] !== null &&
(typeof o[prop] === 'object' || typeof o[prop] === 'function') &&
!Object.isFrozen(o[prop])
) {
deepFreeze(o[prop]);
}
});
return o;
}
// Don't accidentally mutate config as part of the build
deepFreeze(bundles);
deepFreeze(bundleTypes);
deepFreeze(moduleTypes);
module.exports = {
fbBundleExternalsMap,
bundleTypes,
moduleTypes,
bundles,
};
|
'use strict';
import { patchOption } from './patch';
import { configManager } from './configManager';
import { downloadTheme,
streamTheme,
backupTheme } from './interface';
import { checkPackageVersion } from './cli/packageVersion';
import { startBrowser,
startBrowserSync } from './tools/browser';
import InsalesApi from 'insales';
import { createDir,
reloadDir,
zippedDir } from './file-system/dir';
import { _watch,
watcher,
closeWatcher,
triggerFile,
uploadAssets } from './file-system/watch';
import { initAssets,
pushTheme,
pullTheme,
diffLocalAssets } from './file-system/assets';
import { getAsset,
getAssets,
updateListThemes,
updateteAssets,
uploadAsset,
removeAsset,
editAsset } from './request/asset';
import { getPaths } from './paths';
import { logManager } from './logger/logManager';
import { setQueueAsset } from './request/assetManager';
const EventEmitter = require('events').EventEmitter;
import clc from 'cli-color';
const log_edit = clc.xterm(40);
const log_error = clc.xterm(9);
const log_warn = clc.xterm(221);
const log_notice = clc.xterm(33);
const log_remove = clc.xterm(196);
const log_white = clc.xterm(254);
const log_label = clc.xterm(81);
const log_text = clc.xterm(254);
const log_start = clc.xterm(129);
class InSalesUploader {
constructor(options){
this.options = patchOption(options);
this.eventEmitter = new EventEmitter();
this.conf = new configManager(this);
this.logManager = new logManager(this);
this.paths = getPaths(this.options);
this.assets = {};
this.state = {};
this.downloadList = [];
this.queueList = [];
this.queueInWork = [];
this.inWork = false;
}
startBrowser(url, options) {
return startBrowser(url, options);
}
openBrowser() {
const _options = Object.assign({}, this.options.tools.openBrowser);
_options.launch = true;
return startBrowser(this.options.themeUrl, _options);
}
startBrowserSync() {
return startBrowserSync(this.options.themeUrl, this.options, this.paths);
}
upload(param) {
return uploadAssets(this.conf, this.state, param);
}
initAssets() {
return initAssets(this.paths);
}
diffLocalAssets() {
return diffLocalAssets(this.conf, this.state);
}
pushTheme() {
return pushTheme(this.conf, this.state);
}
pullTheme() {
return Promise.all([pullTheme(this.conf, this.state)]);
}
download () {
return Promise.all([downloadTheme(this.conf, this.state)]);
}
stream () {
return Promise.all([streamTheme(this.conf, this.state)]);
}
start () {
return downloadTheme(this.conf, this.state).then(()=>{
streamTheme(this.conf, this.state)
})
}
stopStream () {
return Promise.all([closeWatcher(this.conf, this.state)]);
}
triggerFile(event, _path) {
return Promise.all([triggerFile(this.conf, this.state, event, _path)]);
}
_backup (_settings) {
return backupTheme(this.conf, this.state, _settings)
}
backup () {
return Promise.all([
this._backup()
])
}
backupToZip () {
return Promise.all([
this._backup({zip: true})
])
}
}
export default options => new InSalesUploader(options);
|
var fs = require('fs');
var Vert = fs.readFileSync(__dirname + '/glsl/Diffuse.vert', 'utf8');
var Frag = fs.readFileSync(__dirname + '/glsl/Diffuse.frag', 'utf8');
module.exports = function(ctx) {
return ctx.createProgram(Vert, Frag);
}
module.exports.Vert = Vert;
module.exports.Frag = Frag;
|
/*
* Apache 2.0 License
*
* Copyright (c) Sebastian Katzer 2017
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://opensource.org/licenses/Apache-2.0/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*/
var exec = require('cordova/exec'),
channel = require('cordova/channel');
// Defaults
exports._defaults = {
actions : [],
attachments : [],
autoClear : true,
badge : null,
channel : null,
channelDescription: null,
clock : true,
color : null,
data : null,
defaults : 0,
foreground : null,
group : null,
groupSummary : false,
icon : null,
id : 0,
launch : true,
led : true,
lockscreen : true,
mediaSession : null,
number : 0,
priority : 0,
progressBar : false,
silent : false,
smallIcon : 'res://icon',
sound : true,
sticky : false,
summary : null,
text : '',
timeoutAfter : false,
title : '',
trigger : { type : 'calendar' },
vibrate : false,
wakeup : true,
when : 0
};
// Event listener
exports._listener = {};
/**
* Check permission to show notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.hasPermission = function (callback, scope) {
this._exec('check', null, callback, scope);
};
/**
* Request permission to show notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.requestPermission = function (callback, scope) {
this._exec('request', null, callback, scope);
};
/**
* Schedule notifications.
*
* @param [ Array ] notifications The notifications to schedule.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
* @param [ Object ] args Optional flags how to schedule.
*
* @return [ Void ]
*/
exports.schedule = function (msgs, callback, scope, args) {
var fn = function (granted) {
var toasts = this._toArray(msgs);
if (!granted && callback) {
callback.call(scope || this, false);
return;
}
for (var i = 0, len = toasts.length; i < len; i++) {
var toast = toasts[i];
this._mergeWithDefaults(toast);
this._convertProperties(toast);
}
this._exec('schedule', toasts, callback, scope);
};
if (args && args.skipPermission) {
fn.call(this, true);
} else {
this.requestPermission(fn, this);
}
};
/**
* Schedule notifications.
*
* @param [ Array ] notifications The notifications to schedule.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
* @param [ Object ] args Optional flags how to schedule.
*
* @return [ Void ]
*/
exports.update = function (msgs, callback, scope, args) {
var fn = function(granted) {
var toasts = this._toArray(msgs);
if (!granted && callback) {
callback.call(scope || this, false);
return;
}
for (var i = 0, len = toasts.length; i < len; i++) {
this._convertProperties(toasts[i]);
}
this._exec('update', toasts, callback, scope);
};
if (args && args.skipPermission) {
fn.call(this, true);
} else {
this.requestPermission(fn, this);
}
};
/**
* Clear the specified notifications by id.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.clear = function (ids, callback, scope) {
ids = this._toArray(ids);
ids = this._convertIds(ids);
this._exec('clear', ids, callback, scope);
};
/**
* Clear all triggered notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.clearAll = function (callback, scope) {
this._exec('clearAll', null, callback, scope);
};
/**
* Clear the specified notifications by id.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.cancel = function (ids, callback, scope) {
ids = this._toArray(ids);
ids = this._convertIds(ids);
this._exec('cancel', ids, callback, scope);
};
/**
* Cancel all scheduled notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.cancelAll = function (callback, scope) {
this._exec('cancelAll', null, callback, scope);
};
/**
* Check if a notification is present.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.isPresent = function (id, callback, scope) {
var fn = this._createCallbackFn(callback, scope);
this.getType(id, function (type) {
fn(type != 'unknown');
});
};
/**
* Check if a notification is scheduled.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.isScheduled = function (id, callback, scope) {
this.hasType(id, 'scheduled', callback, scope);
};
/**
* Check if a notification was triggered.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.isTriggered = function (id, callback, scope) {
this.hasType(id, 'triggered', callback, scope);
};
/**
* Check if a notification has a given type.
*
* @param [ Int ] id The ID of the notification.
* @param [ String ] type The type of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.hasType = function (id, type, callback, scope) {
var fn = this._createCallbackFn(callback, scope);
this.getType(id, function (type2) {
fn(type == type2);
});
};
/**
* Get the type (triggered, scheduled) for the notification.
*
* @param [ Int ] id The ID of the notification.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getType = function (id, callback, scope) {
this._exec('type', id, callback, scope);
};
/**
* List of all notification ids.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getIds = function (callback, scope) {
this._exec('ids', 0, callback, scope);
};
/**
* List of all scheduled notification IDs.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getScheduledIds = function (callback, scope) {
this._exec('ids', 1, callback, scope);
};
/**
* List of all triggered notification IDs.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getTriggeredIds = function (callback, scope) {
this._exec('ids', 2, callback, scope);
};
/**
* List of local notifications specified by id.
* If called without IDs, all notification will be returned.
*
* @param [ Array<Int> ] ids The IDs of the notifications.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.get = function () {
var args = Array.apply(null, arguments);
if (typeof args[0] == 'function') {
args.unshift([]);
}
var ids = args[0],
callback = args[1],
scope = args[2];
if (!Array.isArray(ids)) {
this._exec('notification', Number(ids), callback, scope);
return;
}
ids = this._convertIds(ids);
this._exec('notifications', [3, ids], callback, scope);
};
/**
* List for all notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.getAll = function (callback, scope) {
this._exec('notifications', 0, callback, scope);
};
/**
* List of all scheduled notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*/
exports.getScheduled = function (callback, scope) {
this._exec('notifications', 1, callback, scope);
};
/**
* List of all triggered notifications.
*
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*/
exports.getTriggered = function (callback, scope) {
this._exec('notifications', 2, callback, scope);
};
/**
* Add an group of actions by id.
*
* @param [ String ] id The Id of the group.
* @param [ Array] actions The action config settings.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.addActions = function (id, actions, callback, scope) {
this._exec('actions', [0, id, actions], callback, scope);
};
/**
* Remove an group of actions by id.
*
* @param [ String ] id The Id of the group.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.removeActions = function (id, callback, scope) {
this._exec('actions', [1, id], callback, scope);
};
/**
* Check if a group of actions is defined.
*
* @param [ String ] id The Id of the group.
* @param [ Function ] callback The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.hasActions = function (id, callback, scope) {
this._exec('actions', [2, id], callback, scope);
};
/**
* The (platform specific) default settings.
*
* @return [ Object ]
*/
exports.getDefaults = function () {
var map = Object.assign({}, this._defaults);
for (var key in map) {
if (Array.isArray(map[key])) {
map[key] = Array.from(map[key]);
} else
if (Object.prototype.isPrototypeOf(map[key])) {
map[key] = Object.assign({}, map[key]);
}
}
return map;
};
/**
* Overwrite default settings.
*
* @param [ Object ] newDefaults New default values.
*
* @return [ Void ]
*/
exports.setDefaults = function (newDefaults) {
Object.assign(this._defaults, newDefaults);
};
/**
* Register callback for given event.
*
* @param [ String ] event The name of the event.
* @param [ Function ] callback The function to be exec as callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Void ]
*/
exports.on = function (event, callback, scope) {
var type = typeof callback;
if (type !== 'function' && type !== 'string')
return;
if (!this._listener[event]) {
this._listener[event] = [];
}
var item = [callback, scope || window];
this._listener[event].push(item);
};
/**
* Unregister callback for given event.
*
* @param [ String ] event The name of the event.
* @param [ Function ] callback The function to be exec as callback.
*
* @return [ Void ]
*/
exports.un = function (event, callback) {
var listener = this._listener[event];
if (!listener)
return;
for (var i = 0; i < listener.length; i++) {
var fn = listener[i][0];
if (fn == callback) {
listener.splice(i, 1);
break;
}
}
};
/**
* Fire the event with given arguments.
*
* @param [ String ] event The event's name.
* @param [ *Array] args The callback's arguments.
*
* @return [ Void]
*/
exports.fireEvent = function (event) {
var args = Array.apply(null, arguments).slice(1),
listener = this._listener[event];
if (!listener)
return;
if (args[0] && typeof args[0].data === 'string') {
args[0].data = JSON.parse(args[0].data);
}
for (var i = 0; i < listener.length; i++) {
var fn = listener[i][0],
scope = listener[i][1];
if (typeof fn !== 'function') {
fn = scope[fn];
}
fn.apply(scope, args);
}
};
/**
* Fire queued events once the device is ready and all listeners are registered.
*
* @return [ Void ]
*/
exports.fireQueuedEvents = function() {
exports._exec('ready');
};
/**
* Merge custom properties with the default values.
*
* @param [ Object ] options Set of custom values.
*
* @retrun [ Object ]
*/
exports._mergeWithDefaults = function (options) {
var values = this.getDefaults();
if (values.hasOwnProperty('sticky')) {
options.sticky = this._getValueFor(options, 'sticky', 'ongoing');
}
if (options.sticky && options.autoClear !== true) {
options.autoClear = false;
}
Object.assign(values, options);
for (var key in values) {
if (values[key] !== null) {
options[key] = values[key];
} else {
delete options[key];
}
if (!this._defaults.hasOwnProperty(key)) {
console.warn('Unknown property: ' + key);
}
}
options.meta = {
plugin: 'cordova-plugin-local-notification',
version: '0.9-beta.3'
};
return options;
};
/**
* Convert the passed values to their required type.
*
* @param [ Object ] options Properties to convert for.
*
* @return [ Object ] The converted property list
*/
exports._convertProperties = function (options) {
var parseToInt = function (prop, options) {
if (isNaN(options[prop])) {
console.warn(prop + ' is not a number: ' + options[prop]);
return this._defaults[prop];
} else {
return Number(options[prop]);
}
};
if (options.id) {
options.id = parseToInt('id', options);
}
if (options.title) {
options.title = options.title.toString();
}
if (options.badge) {
options.badge = parseToInt('badge', options);
}
if (options.defaults) {
options.defaults = parseToInt('defaults', options);
}
if (options.smallIcon && !options.smallIcon.match(/^res:/)) {
console.warn('Property "smallIcon" must be of kind res://...');
}
if (typeof options.timeoutAfter === 'boolean') {
options.timeoutAfter = options.timeoutAfter ? 3600000 : null;
}
if (options.timeoutAfter) {
options.timeoutAfter = parseToInt('timeoutAfter', options);
}
options.data = JSON.stringify(options.data);
this._convertPriority(options);
this._convertTrigger(options);
this._convertActions(options);
this._convertProgressBar(options);
return options;
};
/**
* Convert the passed values for the priority to their required type.
*
* @param [ Map ] options Set of custom values.
*
* @return [ Map ] Interaction object with trigger spec.
*/
exports._convertPriority = function (options) {
var prio = options.priority || options.prio || 0;
if (typeof prio === 'string') {
prio = { min: -2, low: -1, high: 1, max: 2 }[prio] || 0;
}
if (options.foreground === true) {
prio = Math.max(prio, 1);
}
if (options.foreground === false) {
prio = Math.min(prio, 0);
}
options.priority = prio;
return options;
};
/**
* Convert the passed values to their required type, modifying them
* directly for Android and passing the converted list back for iOS.
*
* @param [ Map ] options Set of custom values.
*
* @return [ Map ] Interaction object with category & actions.
*/
exports._convertActions = function (options) {
var actions = [];
if (!options.actions || typeof options.actions === 'string')
return options;
for (var i = 0, len = options.actions.length; i < len; i++) {
var action = options.actions[i];
if (!action.id) {
console.warn('Action with title ' + action.title + ' ' +
'has no id and will not be added.');
continue;
}
action.id = action.id.toString();
actions.push(action);
}
options.actions = actions;
return options;
};
/**
* Convert the passed values for the trigger to their required type.
*
* @param [ Map ] options Set of custom values.
*
* @return [ Map ] Interaction object with trigger spec.
*/
exports._convertTrigger = function (options) {
var trigger = options.trigger || {},
date = this._getValueFor(trigger, 'at', 'firstAt', 'date');
var dateToNum = function (date) {
var num = typeof date == 'object' ? date.getTime() : date;
return Math.round(num);
};
if (!options.trigger)
return;
if (!trigger.type) {
trigger.type = trigger.center ? 'location' : 'calendar';
}
var isCal = trigger.type == 'calendar';
if (isCal && !date) {
date = this._getValueFor(options, 'at', 'firstAt', 'date');
}
if (isCal && !trigger.every && options.every) {
trigger.every = options.every;
}
if (isCal && (trigger.in || trigger.every)) {
date = null;
}
if (isCal && date) {
trigger.at = dateToNum(date);
}
if (isCal && trigger.firstAt) {
trigger.firstAt = dateToNum(trigger.firstAt);
}
if (isCal && trigger.before) {
trigger.before = dateToNum(trigger.before);
}
if (isCal && trigger.after) {
trigger.after = dateToNum(trigger.after);
}
if (!trigger.count && device.platform == 'windows') {
trigger.count = trigger.every ? 5 : 1;
}
if (trigger.count && device.platform == 'iOS') {
console.warn('trigger: { count: } is not supported on iOS.');
}
if (!isCal) {
trigger.notifyOnEntry = !!trigger.notifyOnEntry;
trigger.notifyOnExit = trigger.notifyOnExit === true;
trigger.radius = trigger.radius || 5;
trigger.single = !!trigger.single;
}
if (!isCal || trigger.at) {
delete trigger.every;
}
delete options.every;
delete options.at;
delete options.firstAt;
delete options.date;
options.trigger = trigger;
return options;
};
/**
* Convert the passed values for the progressBar to their required type.
*
* @param [ Map ] options Set of custom values.
*
* @return [ Map ] Interaction object with trigger spec.
*/
exports._convertProgressBar = function (options) {
var isAndroid = device.platform == 'Android',
cfg = options.progressBar;
if (cfg === undefined)
return;
if (typeof cfg === 'boolean') {
cfg = options.progressBar = { enabled: cfg };
}
if (typeof cfg.enabled !== 'boolean') {
cfg.enabled = !!(cfg.value || cfg.maxValue || cfg.indeterminate !== null);
}
cfg.value = cfg.value || 0;
if (isAndroid) {
cfg.maxValue = cfg.maxValue || 100;
cfg.indeterminate = !!cfg.indeterminate;
}
cfg.enabled = !!cfg.enabled;
if (cfg.enabled && options.clock === true) {
options.clock = 'chronometer';
}
return options;
};
/**
* Create a callback function to get executed within a specific scope.
*
* @param [ Function ] fn The function to be exec as the callback.
* @param [ Object ] scope The callback function's scope.
*
* @return [ Function ]
*/
exports._createCallbackFn = function (fn, scope) {
if (typeof fn != 'function')
return;
return function () {
fn.apply(scope || this, arguments);
};
};
/**
* Convert the IDs to numbers.
*
* @param [ Array ] ids
*
* @return [ Array<Number> ]
*/
exports._convertIds = function (ids) {
var convertedIds = [];
for (var i = 0, len = ids.length; i < len; i++) {
convertedIds.push(Number(ids[i]));
}
return convertedIds;
};
/**
* First found value for the given keys.
*
* @param [ Object ] options Object with key-value properties.
* @param [ *Array<String> ] keys List of keys.
*
* @return [ Object ]
*/
exports._getValueFor = function (options) {
var keys = Array.apply(null, arguments).slice(1);
for (var i = 0, key = keys[i], len = keys.length; i < len; key = keys[++i]) {
if (options.hasOwnProperty(key)) {
return options[key];
}
}
return null;
};
/**
* Convert a value to an array.
*
* @param [ Object ] obj Any kind of object.
*
* @return [ Array ] An array with the object as first item.
*/
exports._toArray = function (obj) {
return Array.isArray(obj) ? Array.from(obj) : [obj];
};
/**
* Execute the native counterpart.
*
* @param [ String ] action The name of the action.
* @param [ Array ] args Array of arguments.
* @param [ Function] callback The callback function.
* @param [ Object ] scope The scope for the function.
*
* @return [ Void ]
*/
exports._exec = function (action, args, callback, scope) {
var fn = this._createCallbackFn(callback, scope),
params = [];
if (Array.isArray(args)) {
params = args;
} else if (args != null) {
params.push(args);
}
exec(fn, null, 'LocalNotification', action, params);
};
/**
* Set the launch details if the app was launched by clicking on a toast.
*
* @return [ Void ]
*/
exports._setLaunchDetails = function () {
exports._exec('launch', null, function (details) {
if (details) {
exports.launchDetails = details;
}
});
};
// Polyfill for Object.assign
if (typeof Object.assign != 'function') {
Object.assign = function(target) {
'use strict';
if (target == null) {
throw new TypeError('Cannot convert undefined or null to object');
}
target = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source != null) {
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
}
return target;
};
}
// Polyfill for Array.from
// Production steps of ECMA-262, Edition 6, 22.1.2.1
// Reference: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.from
if (!Array.from) {
Array.from = (function () {
var toStr = Object.prototype.toString;
var isCallable = function (fn) {
return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
};
var toInteger = function (value) {
var number = Number(value);
if (isNaN(number)) { return 0; }
if (number === 0 || !isFinite(number)) { return number; }
return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
};
var maxSafeInteger = Math.pow(2, 53) - 1;
var toLength = function (value) {
var len = toInteger(value);
return Math.min(Math.max(len, 0), maxSafeInteger);
};
// The length property of the from method is 1.
return function from(arrayLike/*, mapFn, thisArg */) {
// 1. Let C be the this value.
var C = this;
// 2. Let items be ToObject(arrayLike).
var items = Object(arrayLike);
// 3. ReturnIfAbrupt(items).
if (arrayLike == null) {
throw new TypeError("Array.from requires an array-like object - not null or undefined");
}
// 4. If mapfn is undefined, then let mapping be false.
var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
var T;
if (typeof mapFn !== 'undefined') {
// 5. else
// 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
if (!isCallable(mapFn)) {
throw new TypeError('Array.from: when provided, the second argument must be a function');
}
// 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (arguments.length > 2) {
T = arguments[2];
}
}
// 10. Let lenValue be Get(items, "length").
// 11. Let len be ToLength(lenValue).
var len = toLength(items.length);
// 13. If IsConstructor(C) is true, then
// 13. a. Let A be the result of calling the [[Construct]] internal method of C with an argument list containing the single item len.
// 14. a. Else, Let A be ArrayCreate(len).
var A = isCallable(C) ? Object(new C(len)) : new Array(len);
// 16. Let k be 0.
var k = 0;
// 17. Repeat, while k < len… (also steps a - h)
var kValue;
while (k < len) {
kValue = items[k];
if (mapFn) {
A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
} else {
A[k] = kValue;
}
k += 1;
}
// 18. Let putStatus be Put(A, "length", len, true).
A.length = len;
// 20. Return A.
return A;
};
}());
}
// Called after 'deviceready' event
channel.deviceready.subscribe(function () {
if (!window.skipLocalNotificationReady) {
exports.fireQueuedEvents();
}
});
// Called before 'deviceready' event
channel.onCordovaReady.subscribe(function () {
channel.onCordovaInfoReady.subscribe(function () {
exports._setLaunchDetails();
});
});
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M15 6c1.1 0 2 .9 2 2 0 .99-.73 1.82-1.67 1.97l-2.31-2.31C13.19 6.72 14.01 6 15 6m0-2c-2.21 0-4 1.79-4 4 0 .18.03.35.05.52l3.43 3.43c.17.02.34.05.52.05 2.21 0 4-1.79 4-4s-1.79-4-4-4zm1.69 10.16L22.53 20H23v-2c0-2.14-3.56-3.5-6.31-3.84zm-3.68 1.97L14.88 18H9c.08-.24.88-1.01 2.91-1.57l1.1-.3M1.41 1.71 0 3.12l4 4V10H1v2h3v3h2v-3h2.88l2.51 2.51C9.19 15.11 7 16.3 7 18v2h9.88l4 4 1.41-1.41L1.41 1.71zM6 10v-.88l.88.88H6z"
}), 'PersonAddDisabledOutlined');
exports.default = _default; |
import ButtonSelect from 'ember-button-select/components/button-select';
export default ButtonSelect;
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.myBundle = {})));
}(this, (function (exports) { 'use strict';
var x = {foo: 'bar'};
delete x.foo;
delete globalVariable.foo;
exports.x = x;
Object.defineProperty(exports, '__esModule', { value: true });
})));
|
var script=$("script.abp").get(-1);if(script){for(var query=script.src.replace(/^[^\?]+\??/,"").split("&"),params={},i=0;i<query.length;i++){var param=query[i].split("=");params[param[0]]=param[1]}1==params.ch?usesABP=!0:2==params.ch&&(usesABP=!1)}
//# sourceMappingURL=px.js.map |
define(["exports", "foo"], function (_exports, _foo) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "bar", {
enumerable: true,
get: function () {
return _foo.bar;
}
});
Object.defineProperty(_exports, "foo", {
enumerable: true,
get: function () {
return _foo.foo;
}
});
});
|
// Copyright, 2013-2014, by Tomas Korcak. <korczis@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
(function () {
'use strict';
var define = require('amdefine')(module);
/**
* Array of modules this one depends on.
* @type {Array}
*/
var deps = [
"../core",
"util",
"optimist"
];
define(deps, function (Core, util, Optimist) {
/**
* Command Line Interface
* @type {CliModule}
*/
var exports = module.exports = function Cli(resolver) {
// Call super constructor
Cli.super_.call(this, resolver);
this.argsInstance = Optimist;
};
util.inherits(exports, Core);
/**
* CLI arguments - passed from user's code
* @type {null}
*/
exports.prototype.argsInstance = null;
/**
* Setups CLI - assigns options
* @param options
*/
exports.prototype.args = function() {
return this.argsInstance;
};
});
}()); |
import { isObject, isFunction } from 'utils/is';
import { warnOnceIfDebug } from 'utils/log';
import { splitKeypath } from 'shared/keypaths';
import resolveReference from 'src/view/resolvers/resolveReference';
import Observer from './observe/Observer';
import PatternObserver from './observe/Pattern';
import ArrayObserver from './observe/Array';
import { keys } from 'utils/object';
export default function observe(keypath, callback, options) {
const observers = [];
let map;
let opts;
if (isObject(keypath)) {
map = keypath;
opts = callback || {};
} else {
if (isFunction(keypath)) {
map = { '': keypath };
opts = callback || {};
} else {
map = {};
map[keypath] = callback;
opts = options || {};
}
}
let silent = false;
keys(map).forEach(keypath => {
const callback = map[keypath];
const caller = function(...args) {
if (silent) return;
return callback.apply(this, args);
};
let keypaths = keypath.split(' ');
if (keypaths.length > 1) keypaths = keypaths.filter(k => k);
keypaths.forEach(keypath => {
opts.keypath = keypath;
const observer = createObserver(this, keypath, caller, opts);
if (observer) observers.push(observer);
});
});
// add observers to the Ractive instance, so they can be
// cancelled on ractive.teardown()
this._observers.push.apply(this._observers, observers);
return {
cancel: () => observers.forEach(o => o.cancel()),
isSilenced: () => silent,
silence: () => (silent = true),
resume: () => (silent = false)
};
}
function createObserver(ractive, keypath, callback, options) {
const keys = splitKeypath(keypath);
let wildcardIndex = keys.indexOf('*');
if (!~wildcardIndex) wildcardIndex = keys.indexOf('**');
options.fragment = options.fragment || ractive.fragment;
let model;
if (!options.fragment) {
model = ractive.viewmodel.joinKey(keys[0]);
} else {
// .*.whatever relative wildcard is a special case because splitkeypath doesn't handle the leading .
if (~keys[0].indexOf('.*')) {
model = options.fragment.findContext();
wildcardIndex = 0;
keys[0] = keys[0].slice(1);
} else {
model =
wildcardIndex === 0
? options.fragment.findContext()
: resolveReference(options.fragment, keys[0]);
}
}
// the model may not exist key
if (!model) model = ractive.viewmodel.joinKey(keys[0]);
if (!~wildcardIndex) {
model = model.joinAll(keys.slice(1));
if (options.array) {
return new ArrayObserver(ractive, model, callback, options);
} else {
return new Observer(ractive, model, callback, options);
}
} else {
const double = keys.indexOf('**');
if (~double) {
if (double + 1 !== keys.length || ~keys.indexOf('*')) {
warnOnceIfDebug(
`Recursive observers may only specify a single '**' at the end of the path.`
);
return;
}
}
model = model.joinAll(keys.slice(1, wildcardIndex));
return new PatternObserver(ractive, model, keys.slice(wildcardIndex), callback, options);
}
}
|
// URL parsing and validation
// RPC to server (endpoint, arguments)
// see if RPC requires password
// prompt for password
// send RPC with or without password as required
var qs = require('querystring');
var files = require('./fs/files.js');
var httpHelpers = require('./utils/http-helpers.js');
var buildmessage = require('./buildmessage.js');
var config = require('./config.js');
var auth = require('./auth.js');
var utils = require('./utils/utils.js');
var _ = require('underscore');
var Future = require('fibers/future');
var stats = require('./stats.js');
var Console = require('./console.js').Console;
// Make a synchronous RPC to the "classic" MDG deploy API. The deploy
// API has the following contract:
//
// - Parameters are always sent in the query string.
// - A tarball can be sent in the body (when deploying an app).
// - On success, all calls return HTTP 200. Those that return a value
// either return a JSON payload or a plaintext payload and the
// Content-Type header is set appropriately.
// - On failure, calls return some non-200 HTTP status code and
// provide a human-readable error message in the body.
// - URLs are of the form "/[operation]/[site]".
// - Body encodings are always utf8.
// - Meteor Accounts auth is possible using first-party MDG cookies
// (rather than OAuth).
//
// Options include:
// - method: GET, POST, or DELETE. default GET
// - operation: "info", "logs", "mongo", "deploy", "authorized-apps"
// - site: site name
// - expectPayload: an array of key names. if present, then we expect
// the server to return JSON content on success and to return an
// object with all of these key names.
// - expectMessage: if true, then we expect the server to return text
// content on success.
// - bodyStream: if provided, a stream to use as the request body
// - any other parameters accepted by the node 'request' module, for example
// 'qs' to set query string parameters
//
// Waits until server responds, then returns an object with the
// following keys:
//
// - statusCode: HTTP status code, or null if the server couldn't be
// contacted
// - payload: if successful, and the server returned a JSON body, the
// parsed JSON body
// - message: if successful, and the server returned a text body, the
// body as a string
// - errorMessage: if unsuccessful, a human-readable error message,
// derived from either a transport-level exception, the response
// body, or a generic 'try again later' message, as appropriate
var deployRpc = function (options) {
var genericError = "Server error (please try again later)";
options = _.clone(options);
options.headers = _.clone(options.headers || {});
if (options.headers.cookie)
throw new Error("sorry, can't combine cookie headers yet");
// XXX: Reintroduce progress for upload
try {
var result = httpHelpers.request(_.extend(options, {
url: config.getDeployUrl() + '/' + options.operation +
(options.site ? ('/' + options.site) : ''),
method: options.method || 'GET',
bodyStream: options.bodyStream,
useAuthHeader: true,
encoding: 'utf8' // Hack, but good enough for the deploy server..
}));
} catch (e) {
return {
statusCode: null,
errorMessage: "Connection error (" + e.message + ")"
};
}
var response = result.response;
var body = result.body;
var ret = { statusCode: response.statusCode };
if (response.statusCode !== 200) {
ret.errorMessage = body.length > 0 ? body : genericError;
return ret;
}
var contentType = response.headers["content-type"] || '';
if (contentType === "application/json; charset=utf-8") {
try {
ret.payload = JSON.parse(body);
} catch (e) {
ret.errorMessage = genericError;
return ret;
}
} else if (contentType === "text/plain; charset=utf-8") {
ret.message = body;
}
var hasAllExpectedKeys = _.all(_.map(
options.expectPayload || [], function (key) {
return ret.payload && _.has(ret.payload, key);
}));
if ((options.expectPayload && ! _.has(ret, 'payload')) ||
(options.expectMessage && ! _.has(ret, 'message')) ||
! hasAllExpectedKeys) {
delete ret.payload;
delete ret.message;
ret.errorMessage = genericError;
}
return ret;
};
// Just like deployRpc, but also presents authentication. It will
// prompt the user for a password, or use a Meteor Accounts
// credential, as necessary.
//
// Additional options (beyond deployRpc):
//
// - preflight: if true, do everything but the actual RPC. The only
// other necessary option is 'site'. On failure, returns an object
// with errorMessage (just like deployRpc). On success, returns an
// object without an errorMessage key and with possible keys
// 'protection' (value either 'password' or 'account') and
// 'authorized' (true if the current user is an authorized user on
// this app).
// - promptIfAuthFails: if true, then we think we are logged in with the
// accounts server but our authentication actually fails, then prompt
// the user to log in with a username and password and then resend the
// RPC.
var authedRpc = function (options) {
var rpcOptions = _.clone(options);
var preflight = rpcOptions.preflight;
delete rpcOptions.preflight;
// Fetch auth info
var infoResult = deployRpc({
operation: 'info',
site: rpcOptions.site,
expectPayload: []
});
if (infoResult.statusCode === 401 && rpcOptions.promptIfAuthFails) {
// Our authentication didn't validate, so prompt the user to log in
// again, and resend the RPC if the login succeeds.
var username = Console.readLine({
prompt: "Username: ",
stream: process.stderr
});
var loginOptions = {
username: username,
suppressErrorMessage: true
};
if (auth.doInteractivePasswordLogin(loginOptions)) {
return authedRpc(options);
} else {
return {
statusCode: 403,
errorMessage: "login failed."
};
}
}
if (infoResult.statusCode === 404) {
// Doesn't exist, therefore not protected.
return preflight ? { } : deployRpc(rpcOptions);
}
if (infoResult.errorMessage)
return infoResult;
var info = infoResult.payload;
if (! _.has(info, 'protection')) {
// Not protected.
//
// XXX should prompt the user to claim the app (only if deploying?)
return preflight ? { } : deployRpc(rpcOptions);
}
if (info.protection === "password") {
if (preflight) {
return { protection: info.protection };
}
// Password protected. Read a password, hash it, and include the
// hashed password as a query parameter when doing the RPC.
var password;
password = Console.readLine({
echo: false,
prompt: "Password: ",
stream: process.stderr
});
// Hash the password so we never send plaintext over the
// wire. Doesn't actually make us more secure, but it means we
// won't leak a user's password, which they might use on other
// sites too.
var crypto = require('crypto');
var hash = crypto.createHash('sha1');
hash.update('S3krit Salt!');
hash.update(password);
password = hash.digest('hex');
rpcOptions = _.clone(rpcOptions);
rpcOptions.qs = _.clone(rpcOptions.qs || {});
rpcOptions.qs.password = password;
return deployRpc(rpcOptions);
}
if (info.protection === "account") {
if (! _.has(info, 'authorized')) {
// Absence of this implies that we are not an authorized user on
// this app
if (preflight) {
return { protection: info.protection };
} else {
return {
statusCode: null,
errorMessage: auth.isLoggedIn() ?
// XXX better error message (probably need to break out of
// the 'errorMessage printed with brief prefix' pattern)
"Not an authorized user on this site" :
"Not logged in"
};
}
}
// Sweet, we're an authorized user.
if (preflight) {
return {
protection: info.protection,
authorized: info.authorized
};
} else {
return deployRpc(rpcOptions);
}
}
return {
statusCode: null,
errorMessage: "You need a newer version of Meteor to work with this site"
};
};
// When the user is trying to do something with a legacy
// password-protected app, instruct them to claim it with 'meteor
// claim'.
var printLegacyPasswordMessage = function (site) {
Console.error(
"\nThis site was deployed with an old version of Meteor that used " +
"site passwords instead of user accounts. Now we have a much better " +
"system, Meteor developer accounts.");
Console.error();
Console.error("If this is your site, please claim it into your account with");
Console.error(
Console.command("meteor claim " + site),
Console.options({ indent: 2 }));
};
// When the user is trying to do something with an app that they are not
// authorized for, instruct them to get added via 'meteor authorized
// --add' or switch accounts.
var printUnauthorizedMessage = function () {
var username = auth.loggedInUsername();
Console.error("Sorry, that site belongs to a different user.");
if (username) {
Console.error("You are currently logged in as " + username + ".");
}
Console.error();
Console.error(
"Either have the site owner use " +
Console.command("'meteor authorized --add'") + " to add you as an " +
"authorized developer for the site, or switch to an authorized account " +
"with " + Console.command("'meteor login'") + ".");
};
// Take a proposed sitename for deploying to. If it looks
// syntactically good, canonicalize it (this essentially means
// stripping 'http://' or a trailing '/' if present) and return it. If
// not, print an error message to stderr and return null.
var canonicalizeSite = function (site) {
// There are actually two different bugs here. One is that the meteor deploy
// server does not support apps whose total site length is greater than 63
// (because of how it generates Mongo database names); that can be fixed on
// the server. After that, this check will be too strong, but we still will
// want to check that each *component* of the hostname is at most 63
// characters (url.parse will do something very strange if a component is
// larger than 63, which is the maximum legal length).
if (site.length > 63) {
Console.error(
"The maximum hostname length currently supported is 63 characters: " +
site + " is too long. " +
"Please try again with a shorter URL for your site.");
return false;
}
var url = site;
if (!url.match(':\/\/'))
url = 'http://' + url;
var parsed = require('url').parse(url);
if (! parsed.hostname) {
Console.info(
"Please specify a domain to connect to, such as www.example.com or " +
"http://www.example.com/");
return false;
}
if (parsed.pathname != '/' || parsed.hash || parsed.query) {
Console.info(
"Sorry, Meteor does not yet support specific path URLs, such as " +
Console.url("http://www.example.com/blog") + " . Please specify the root of a domain.");
return false;
}
return parsed.hostname;
};
// Run the bundler and deploy the result. Print progress
// messages. Return a command exit code.
//
// Options:
// - projectContext: the ProjectContext for the app
// - site: site to deploy as
// - settingsFile: file from which to read deploy settings (undefined
// to leave unchanged from previous deploy of the app, if any)
// - recordPackageUsage: (defaults to true) if set to false, don't
// send information about packages used by this app to the package
// stats server.
// - buildOptions: the 'buildOptions' argument to the bundler
var bundleAndDeploy = function (options) {
if (options.recordPackageUsage === undefined)
options.recordPackageUsage = true;
var site = canonicalizeSite(options.site);
if (! site)
return 1;
// We should give a username/password prompt if the user was logged in
// but the credentials are expired, unless the user is logged in but
// doesn't have a username (in which case they should hit the email
// prompt -- a user without a username shouldn't be given a username
// prompt). There's an edge case where things happen in the following
// order: user creates account, user sets username, credential expires
// or is revoked, user comes back to deploy again. In that case,
// they'll get an email prompt instead of a username prompt because
// the command-line tool didn't have time to learn about their
// username before the credential was expired.
auth.pollForRegistrationCompletion({
noLogout: true
});
var promptIfAuthFails = (auth.loggedInUsername() !== null);
// Check auth up front, rather than after the (potentially lengthy)
// bundling process.
var preflight = authedRpc({
site: site,
preflight: true,
promptIfAuthFails: promptIfAuthFails
});
if (preflight.errorMessage) {
Console.error("Error deploying application: " + preflight.errorMessage);
return 1;
}
if (preflight.protection === "password") {
printLegacyPasswordMessage(site);
Console.error("If it's not your site, please try a different name!");
return 1;
} else if (preflight.protection === "account" &&
! preflight.authorized) {
printUnauthorizedMessage();
return 1;
}
var buildDir = files.mkdtemp('build_tar');
var bundlePath = files.pathJoin(buildDir, 'bundle');
Console.info('Deploying to ' + site + '.');
var settings = null;
var messages = buildmessage.capture({
title: "preparing to deploy",
rootPath: process.cwd()
}, function () {
if (options.settingsFile)
settings = files.getSettings(options.settingsFile);
});
if (! messages.hasMessages()) {
var bundler = require('./isobuild/bundler.js');
var bundleResult = bundler.bundle({
projectContext: options.projectContext,
outputPath: bundlePath,
buildOptions: options.buildOptions
});
if (bundleResult.errors)
messages = bundleResult.errors;
}
if (messages.hasMessages()) {
Console.info("\nErrors prevented deploying:");
Console.info(messages.formatMessages());
return 1;
}
if (options.recordPackageUsage) {
stats.recordPackages({
what: "sdk.deploy",
projectContext: options.projectContext,
site: site
});
}
var result = buildmessage.enterJob({ title: "uploading" }, function () {
return authedRpc({
method: 'POST',
operation: 'deploy',
site: site,
qs: settings !== null ? {settings: settings} : {},
bodyStream: files.createTarGzStream(files.pathJoin(buildDir, 'bundle')),
expectPayload: ['url'],
preflightPassword: preflight.preflightPassword
});
});
if (result.errorMessage) {
Console.error("\nError deploying application: " + result.errorMessage);
return 1;
}
var deployedAt = require('url').parse(result.payload.url);
var hostname = deployedAt.hostname;
Console.info('Now serving at http://' + hostname);
if (! hostname.match(/meteor\.com$/)) {
var dns = require('dns');
dns.resolve(hostname, 'CNAME', function (err, cnames) {
if (err || cnames[0] !== 'origin.meteor.com') {
dns.resolve(hostname, 'A', function (err, addresses) {
if (err || addresses[0] !== '107.22.210.133') {
Console.info('-------------');
Console.info(
"You've deployed to a custom domain.",
"Please be sure to CNAME your hostname",
"to origin.meteor.com, or set an A record to 107.22.210.133.");
Console.info('-------------');
}
});
}
});
}
return 0;
};
var deleteApp = function (site) {
site = canonicalizeSite(site);
if (! site)
return 1;
var result = authedRpc({
method: 'DELETE',
operation: 'deploy',
site: site,
promptIfAuthFails: true
});
if (result.errorMessage) {
Console.error("Couldn't delete application: " + result.errorMessage);
return 1;
}
Console.info("Deleted.");
return 0;
};
// Helper that does a preflight request to check auth, and prints the
// appropriate error message if auth fails or if this is a legacy
// password-protected app. If auth succeeds, then it runs the actual
// RPC. 'site' and 'operation' are the site and operation for the
// RPC. 'what' is a string describing the operation, for use in error
// messages. Returns the result of the RPC if successful, or null
// otherwise (including if auth failed or if the user is not authorized
// for this site).
var checkAuthThenSendRpc = function (site, operation, what) {
var preflight = authedRpc({
operation: operation,
site: site,
preflight: true,
promptIfAuthFails: true
});
if (preflight.errorMessage) {
Console.error("Couldn't " + what + ": " + preflight.errorMessage);
return null;
}
if (preflight.protection === "password") {
printLegacyPasswordMessage(site);
return null;
} else if (preflight.protection === "account" &&
! preflight.authorized) {
if (! auth.isLoggedIn()) {
// Maybe the user is authorized for this app but not logged in
// yet, so give them a login prompt.
var loginResult = auth.doUsernamePasswordLogin({ retry: true });
if (loginResult) {
// Once we've logged in, retry the whole operation. We need to
// do the preflight request again instead of immediately moving
// on to the real RPC because we don't yet know if the newly
// logged-in user is authorized for this app, and if they
// aren't, then we want to print the nice unauthorized error
// message.
return checkAuthThenSendRpc(site, operation, what);
} else {
// Shouldn't ever get here because we set the retry flag on the
// login, but just in case.
Console.error(
"\nYou must be logged in to " + what + " for this app. Use " +
Console.command("'meteor login'") + "to log in.");
Console.error();
Console.error(
"If you don't have a Meteor developer account yet, you can quickly " +
"create one at www.meteor.com.");
return null;
}
} else { // User is logged in but not authorized for this app
Console.error();
printUnauthorizedMessage();
return null;
}
}
// User is authorized for the app; go ahead and do the actual RPC.
var result = authedRpc({
operation: operation,
site: site,
expectMessage: true,
promptIfAuthFails: true
});
if (result.errorMessage) {
Console.error("Couldn't " + what + ": " + result.errorMessage);
return null;
}
return result;
};
// On failure, prints a message to stderr and returns null. Otherwise,
// returns a temporary authenticated Mongo URL allowing access to this
// site's database.
var temporaryMongoUrl = function (site) {
site = canonicalizeSite(site);
if (! site)
// canonicalizeSite printed an error
return null;
var result = checkAuthThenSendRpc(site, 'mongo', 'open a mongo connection');
if (result !== null) {
return result.message;
} else {
return null;
}
};
var logs = function (site) {
site = canonicalizeSite(site);
if (! site)
return 1;
var result = checkAuthThenSendRpc(site, 'logs', 'view logs');
if (result === null) {
return 1;
} else {
Console.info(result.message);
auth.maybePrintRegistrationLink({ leadingNewline: true });
return 0;
}
};
var listAuthorized = function (site) {
site = canonicalizeSite(site);
if (! site)
return 1;
var result = deployRpc({
operation: 'info',
site: site,
expectPayload: []
});
if (result.errorMessage) {
Console.error("Couldn't get authorized users list: " + result.errorMessage);
return 1;
}
var info = result.payload;
if (! _.has(info, 'protection')) {
Console.info("<anyone>");
return 0;
}
if (info.protection === "password") {
Console.info("<password>");
return 0;
}
if (info.protection === "account") {
if (! _.has(info, 'authorized')) {
Console.error("Couldn't get authorized users list: " +
"You are not authorized");
return 1;
}
Console.info((auth.loggedInUsername() || "<you>"));
_.each(info.authorized, function (username) {
if (username)
// Current username rules don't let you register anything that we might
// want to split over multiple lines (ex: containing a space), but we
// don't want confusion if we ever change some implementation detail.
Console.rawInfo(username + "\n");
});
return 0;
}
};
// action is "add" or "remove"
var changeAuthorized = function (site, action, username) {
site = canonicalizeSite(site);
if (! site)
// canonicalizeSite will have already printed an error
return 1;
var result = authedRpc({
method: 'POST',
operation: 'authorized',
site: site,
qs: action === "add" ? { add: username } : { remove: username },
promptIfAuthFails: true
});
if (result.errorMessage) {
Console.error("Couldn't change authorized users: " + result.errorMessage);
return 1;
}
Console.info(site + ": " +
(action === "add" ? "added " : "removed ")
+ username);
return 0;
};
var claim = function (site) {
site = canonicalizeSite(site);
if (! site)
// canonicalizeSite will have already printed an error
return 1;
// Check to see if it's even a claimable site, so that we can print
// a more appropriate message than we'd get if we called authedRpc
// straight away (at a cost of an extra REST call)
var infoResult = deployRpc({
operation: 'info',
site: site
});
if (infoResult.statusCode === 404) {
Console.error(
"There isn't a site deployed at that address. Use " +
Console.command("'meteor deploy'") + " " +
"if you'd like to deploy your app here.");
return 1;
}
if (infoResult.payload && infoResult.payload.protection === "account") {
if (infoResult.payload.authorized)
Console.error("That site already belongs to you.\n");
else
Console.error("Sorry, that site belongs to someone else.\n");
return 1;
}
if (infoResult.payload &&
infoResult.payload.protection === "password") {
Console.info(
"To claim this site and transfer it to your account, enter the",
"site password one last time.");
Console.info();
}
var result = authedRpc({
method: 'POST',
operation: 'claim',
site: site,
promptIfAuthFails: true
});
if (result.errorMessage) {
auth.pollForRegistrationCompletion();
if (! auth.loggedInUsername() &&
auth.registrationUrl()) {
Console.error(
"You need to set a password on your Meteor developer account before",
"you can claim sites. You can do that here in under a minute:");
Console.error(Console.url(auth.registrationUrl()));
Console.error();
} else {
Console.error("Couldn't claim site: " + result.errorMessage);
}
return 1;
}
Console.info(site + ": " + "successfully transferred to your account.");
Console.info();
Console.info("Show authorized users with:");
Console.info(
Console.command("meteor authorized " + site),
Console.options({ indent: 2 }));
Console.info();
Console.info("Add authorized users with:");
Console.info(
Console.command("meteor authorized " + site + " --add <username>"),
Console.options({ indent: 2 }));
Console.info();
Console.info("Remove authorized users with:");
Console.info(
Console.command("meteor authorized " + site + " --remove <username>"),
Console.options({ indent: 2 }));
Console.info();
return 0;
};
var listSites = function () {
var result = deployRpc({
method: "GET",
operation: "authorized-apps",
promptIfAuthFails: true,
expectPayload: ["sites"]
});
if (result.errorMessage) {
Console.error("Couldn't list sites: " + result.errorMessage);
return 1;
}
if (! result.payload ||
! result.payload.sites ||
! result.payload.sites.length) {
Console.info("You don't have any sites yet.");
} else {
result.payload.sites.sort();
_.each(result.payload.sites, function (site) {
Console.info(site);
});
}
return 0;
};
exports.bundleAndDeploy = bundleAndDeploy;
exports.deleteApp = deleteApp;
exports.temporaryMongoUrl = temporaryMongoUrl;
exports.logs = logs;
exports.listAuthorized = listAuthorized;
exports.changeAuthorized = changeAuthorized;
exports.claim = claim;
exports.listSites = listSites;
|
/* eslint-disable max-len, no-var */
var progressiveReveal = require('../../../../frontend/toolkit/assets/javascript/progressive-reveal');
var $ = require('jquery');
describe('Progressive Reveal', function () {
it('exports a function', function () {
progressiveReveal.should.be.a('function');
});
describe('checkbox', function () {
beforeEach(function () {
$('#test-container').append('<form />');
$('form').append('<label for="check">');
$('form').append('<div id="check-toggle" class="reveal js-hidden">');
});
describe('single', function () {
beforeEach(function () {
$('label').append('<input type="checkbox" id="check" name="check" data-toggle="check-toggle">CheckBox');
progressiveReveal();
});
it('show toggle content when checked', function () {
$('#check').click();
$('#check-toggle').hasClass('js-hidden').should.not.be.ok;
});
it('hide toggle content when unchecked', function () {
$('#check').click();
$('#check').click();
$('#check-toggle').hasClass('js-hidden').should.be.ok;
});
});
describe('with hidden text input', function () {
beforeEach(function () {
$('label').append('<input type="checkbox" id="check" name="check" aria-controls="textbox-panel">CheckBox');
$('form').append('<div id="textbox-panel" class="reveal js-hidden" aria-hidden="true">');
$('div').append('<input type="text" id="textbox">');
progressiveReveal();
});
it('reveals text input', function () {
$('#check').click();
($('#textbox-panel').attr('aria-hidden') === 'false').should.be.ok;
});
it('focuses on text input', function () {
$('#check').click();
(document.activeElement.id === 'textbox').should.be.ok;
});
});
describe('with hidden textarea', function () { // todo
beforeEach(function () {
$('label').append('<input type="checkbox" id="check" name="check" aria-controls="textbox-panel">CheckBox');
$('form').append('<div id="textbox-panel" class="reveal js-hidden" aria-hidden="true">');
$('div').append('<textarea id="textbox">');
progressiveReveal();
});
it('reveals text input', function () {
$('#check').click();
($('#textbox-panel').attr('aria-hidden') === 'false').should.be.ok;
});
it('focuses on text input', function () {
$('#check').click();
(document.activeElement.id === 'textbox').should.be.ok;
});
});
describe('parent panel', function () {
beforeEach(function () {
$('form').append('<div id="check-toggle-panel">');
$('label').append('<input type="checkbox" id="check" name="check" data-toggle="check-toggle">CheckBox');
progressiveReveal();
});
it('should have added the js-hidden class', function () {
$('#check-toggle-panel').hasClass('js-hidden').should.be.ok;
});
it('should show #check-toggle-panel if present', function () {
$('#check').click();
$('#check-toggle-panel').hasClass('js-hidden').should.not.be.ok;
});
it('should not show #show-toggle', function () {
$('#check').click();
$('#check-toggle').hasClass('js-hidden').should.be.ok;
});
});
describe('pre-selected', function () {
beforeEach(function () {
$('label').append('<input type="checkbox" id="check" name="check" data-toggle="check-toggle" checked>CheckBox');
progressiveReveal();
});
it('show toggle content when checkbox is pre-selected', function () {
$('#check-toggle').hasClass('js-hidden').should.not.be.ok;
});
});
describe('multiple checkbox', function () {
beforeEach(function () {
// first checkbox has toggle content
$('label').append('<input type="checkbox" id="check" name="check" data-toggle="check-toggle">CheckBox');
// second checkbox has no toggle content
$('form').append('<label for="check-other">');
$('label[for=check-other]').append('<input type="checkbox" id="check-other" name="check-other">');
// third checkbox has toggle content
$('form').append('<label for="check-another">');
$('label[for=check-another]').append('<input type="checkbox" id="check-another" name="check-another" data-toggle="check-another-toggle">');
$('form').append('<div id="check-another-toggle" class="reveal js-hidden">');
progressiveReveal();
});
it('only show toggle content for the particular checkbox', function () {
$('#check').click();
$('#check-toggle').hasClass('js-hidden').should.not.be.ok;
$('#check-another-toggle').hasClass('js-hidden').should.be.ok;
});
it('do nothing when a checkbox is checked that doesn\'t have toggle content', function () {
$('#check-other').click();
$('#check-toggle').hasClass('js-hidden').should.be.ok;
$('#check-another-toggle').hasClass('js-hidden').should.be.ok;
});
});
});
describe('radio', function () {
beforeEach(function () {
$('#test-container').append('<form />');
$('form').append('<label for="radio1">');
$('form').append('<div id="radio1-toggle" class="reveal js-hidden">');
});
describe('pre-selected', function () {
beforeEach(function () {
$('label').append('<input type="radio" name="group1" id="radio1" data-toggle="radio1-toggle" checked>Radio 1');
progressiveReveal();
});
it('shows toggle content', function () {
$('#radio1-toggle').hasClass('js-hidden').should.not.be.ok;
});
});
describe('clicked twice consecutively', function () {
beforeEach(function () {
$('label').append('<input type="radio" name="group1" id="radio1" data-toggle="radio1-toggle">');
progressiveReveal();
});
it('make no change', function () {
$('#radio1').click();
$('#radio1-toggle').hasClass('js-hidden').should.not.be.ok;
$('#radio1').click();
$('#radio1-toggle').hasClass('js-hidden').should.not.be.ok;
});
});
describe('radio groups', function () {
beforeEach(function () {
$('label').append('<input type="radio" name="group1" id="radio1" data-toggle="radio1-toggle">');
$('form').append('<label for="radio2">');
$('label[for=radio2]').append('<input type="radio" name="group1" id="radio2" data-toggle="radio2-toggle">');
$('form').append('<div id="radio2-toggle" class="reveal js-hidden">');
});
describe('with as many toggles as radios', function () {
beforeEach(function () {
progressiveReveal();
});
it('show content when checked', function () {
$('#radio1').click();
$('#radio1-toggle').hasClass('js-hidden').should.not.be.ok;
$('#radio2-toggle').hasClass('js-hidden').should.be.ok;
});
it('show new content and hide old content if another radio is checked', function () {
$('#radio1').click();
$('#radio2').click();
$('#radio1-toggle').hasClass('js-hidden').should.be.ok;
$('#radio2-toggle').hasClass('js-hidden').should.not.be.ok;
});
});
describe('with fewer toggles than radios and more than one group', function () {
beforeEach(function () {
// group 1
$('form').append('<label for="radio3">');
$('label[for=radio3]').append('<input type="radio" name="group1" id="radio3">');
// group 2
$('form').append('<label for="radio4">');
$('label[for=radio4]').append('<input type="radio" name="group2" id="radio4" data-toggle="radio4-toggle">');
$('form').append('<div id="radio4-toggle" class="reveal js-hidden">');
progressiveReveal();
});
it('show nothing if no associated toggle content', function () {
$('#radio3').click();
$('#radio1-toggle').hasClass('js-hidden').should.be.ok;
$('#radio2-toggle').hasClass('js-hidden').should.be.ok;
});
it('hide content if another radio is checked', function () {
$('#radio1').click();
$('#radio1-toggle').hasClass('js-hidden').should.not.be.ok;
$('#radio3').click();
$('#radio1-toggle').hasClass('js-hidden').should.be.ok;
$('#radio2-toggle').hasClass('js-hidden').should.be.ok;
});
it('shouldn\'t interfere with other radio groups', function () {
$('#radio1').click();
$('#radio4').click();
$('#radio1-toggle').hasClass('js-hidden').should.not.be.ok;
$('#radio4-toggle').hasClass('js-hidden').should.not.be.ok;
});
});
describe('multiple radios toggling the same id', function () {
beforeEach(function () {
$('form').append('<label for="radio3">');
$('label[for=radio3]').append('<input type="radio" name="group1" id="radio3" data-toggle="radio1-toggle">');
progressiveReveal();
});
it('show content when checked', function () {
$('#radio1').click();
$('#radio1-toggle').hasClass('js-hidden').should.not.be.ok;
$('#radio2-toggle').hasClass('js-hidden').should.be.ok;
});
it('show new content and hide old content if another radio is checked', function () {
$('#radio1').click();
$('#radio2').click();
$('#radio1-toggle').hasClass('js-hidden').should.be.ok;
$('#radio2-toggle').hasClass('js-hidden').should.not.be.ok;
});
it('show content for all radios referencing that id', function () {
$('#radio1').click();
$('#radio1-toggle').hasClass('js-hidden').should.not.be.ok;
$('#radio2-toggle').hasClass('js-hidden').should.be.ok;
$('#radio2').click();
$('#radio2-toggle').hasClass('js-hidden').should.not.be.ok;
$('#radio1-toggle').hasClass('js-hidden').should.be.ok;
$('#radio3').click();
$('#radio1-toggle').hasClass('js-hidden').should.not.be.ok;
$('#radio2-toggle').hasClass('js-hidden').should.be.ok;
$('#radio1').click();
$('#radio1-toggle').hasClass('js-hidden').should.not.be.ok;
$('#radio2-toggle').hasClass('js-hidden').should.be.ok;
});
});
});
});
});
|
import omit from 'lodash/fp/omit'
import mapProps from 'recompose/mapProps'
export default keys => mapProps(props => omit(keys, props))
|
import Promise from 'bluebird';
import glob from 'glob';
export default function (path, server) {
return new Promise(function (resolve, reject) {
glob(path, { ignore: '**/__test__/**' }, function (err, files) {
if (err) return reject(err);
var modules = files.map(require);
modules.forEach(function (fn) {
fn(server);
});
resolve(modules);
});
});
};
|
/**
* Module dependencies.
*/
var express = require('express');
var ejs = require('ejs');
var http = require('http');
var path = require('path');
var routes = require('./routes');
var app = express()
// 静态文件目录
var staticDir = path.join(__dirname, 'public');
dbPool = require('./core/db');
db = undefined;
dbPool.getConn(function (dbConn) {
db = dbConn;
console.log("db conn success");
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.engine("html", ejs.__express);
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.json());
app.use(express.urlencoded());
console.log(path.join(__dirname, 'public'))
app.use('/public', express.static(staticDir));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
//添加路由
routes(app);
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
});
|
// file: bwipp/channelcode.js
//
// This code was automatically generated from:
// Barcode Writer in Pure PostScript - Version 2015-03-24
//
// Copyright (c) 2011-2015 Mark Warren
// Copyright (c) 2004-2014 Terry Burton
//
// See the LICENSE file in the bwip-js root directory
// for the extended copyright notice.
// BEGIN channelcode
if (!BWIPJS.bwipp["raiseerror"] && BWIPJS.increfs("channelcode", "raiseerror")) {
BWIPJS.load("bwipp/raiseerror.js");
}
if (!BWIPJS.bwipp["renlinear"] && BWIPJS.increfs("channelcode", "renlinear")) {
BWIPJS.load("bwipp/renlinear.js");
}
BWIPJS.bwipp["channelcode"]=function() {
function $f0(){
return -1;
}
function $f1(){
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.ptr--;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f2(){
this.stk[this.ptr++]=true;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f3(){
var a=/^\s*([^\s]+)(\s+.*)?$/.exec(this.stk[this.ptr-1]);
if (a) {
this.stk[this.ptr-1]=BWIPJS.psstring(a[2]===undefined?"":a[2]);
this.stk[this.ptr++]=BWIPJS.psstring(a[1]);
this.stk[this.ptr++]=true;
} else {
this.stk[this.ptr-1]=false;
}
this.stk[this.ptr++]=false;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring)
this.stk[this.ptr-2]=this.stk[this.ptr-2].toString()==this.stk[this.ptr-1];
else this.stk[this.ptr-2]=this.stk[this.ptr-2]==this.stk[this.ptr-1];
this.ptr--;
this.stk[this.ptr++]=$f0;
var t0=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t0.call(this)==-1) return -1;
}
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
if (typeof(this.stk[this.ptr-1].length)!=="number") throw "length: invalid: " + BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr-1]=this.stk[this.ptr-1].length;
this.stk[this.ptr-1]=BWIPJS.psstring(this.stk[this.ptr-1]);
var t=this.stk[this.ptr-2].toString();
this.stk[this.ptr-1].assign(0,t);
this.stk[this.ptr-2]=this.stk[this.ptr-1].subset(0,t.length);
this.ptr--;
this.stk[this.ptr++]=BWIPJS.psstring("=");
var h=this.stk[this.ptr-2];
var t=h.indexOf(this.stk[this.ptr-1]);
if (t==-1) {
this.stk[this.ptr-1]=false;
} else {
this.stk[this.ptr-2]=h.subset(t+this.stk[this.ptr-1].length);
this.stk[this.ptr-1]=h.subset(t,this.stk[this.ptr-1].length);
this.stk[this.ptr++]=h.subset(0,t);
this.stk[this.ptr++]=true;
}
this.stk[this.ptr++]=true;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring)
this.stk[this.ptr-2]=this.stk[this.ptr-2].toString()==this.stk[this.ptr-1];
else this.stk[this.ptr-2]=this.stk[this.ptr-2]==this.stk[this.ptr-1];
this.ptr--;
this.stk[this.ptr++]=$f1;
this.stk[this.ptr++]=$f2;
var t1=this.stk[--this.ptr];
var t2=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t2.call(this)==-1) return -1;
} else {
if (t1.call(this)==-1) return -1;
}
}
function $f4(){
this.stk[this.ptr++]=1;
this.stk[this.ptr-1]={};
this.dict=this.stk[--this.ptr]; this.dstk.push(this.dict);
var t=this.dstk.get("options");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=$f3;
var t3=this.stk[--this.ptr];
while (true) {
if (t3.call(this)==-1) break;
}
this.stk[this.ptr++]=this.dict;
this.dstk.pop(); this.dict=this.dstk[this.dstk.length-1];
this.stk[this.ptr++]="options";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f5(){
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f6(){
this.stk[this.ptr++]="bwipp.channelcodeBadLength";
this.stk[this.ptr++]=BWIPJS.psstring("Channel Code must be 2 to 7 digits");
var t=this.dstk.get("raiseerror");
this.stk[this.ptr++]=t;
var t=this.stk[--this.ptr];
if (t instanceof Function) t.call(this); else this.eval(t);
}
function $f7(){
this.stk[this.ptr++]="bwipp.channelcodeBadCharacter";
this.stk[this.ptr++]=BWIPJS.psstring("Channel Code must contain only digits");
var t=this.dstk.get("raiseerror");
this.stk[this.ptr++]=t;
var t=this.stk[--this.ptr];
if (t instanceof Function) t.call(this); else this.eval(t);
}
function $f8(){
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
this.stk[this.ptr++]=48;
this.stk[this.ptr-2]=this.stk[this.ptr-2]<this.stk[this.ptr-1]; this.ptr--;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.stk[this.ptr++]=57;
this.stk[this.ptr-2]=this.stk[this.ptr-2]>this.stk[this.ptr-1]; this.ptr--;
if (typeof(this.stk[this.ptr-1])=="boolean") this.stk[this.ptr-2]=this.stk[this.ptr-2]||this.stk[this.ptr-1];
else this.stk[this.ptr-2]=this.stk[this.ptr-2]|this.stk[this.ptr-1];
this.ptr--;
this.stk[this.ptr++]=$f7;
var t9=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t9.call(this)==-1) return -1;
}
}
function $f9(){
this.stk[this.ptr++]="bwipp.channelcodeTooBig";
this.stk[this.ptr++]=BWIPJS.psstring("The Channel Code value is too big for the number of channels");
var t=this.dstk.get("raiseerror");
this.stk[this.ptr++]=t;
var t=this.stk[--this.ptr];
if (t instanceof Function) t.call(this); else this.eval(t);
}
function $f10(){
this.stk[this.ptr++]=1;
}
function $f11(){
this.stk[this.ptr++]=2;
}
function $f12(){
var t=this.dstk.get("b");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=3;
if (this.stk[this.ptr-1] >= this.ptr) throw "index: underflow";
this.stk[this.ptr-1]=this.stk[this.ptr-2-this.stk[this.ptr-1]];
this.stk[this.ptr++]=2;
if (this.stk[this.ptr-1] >= this.ptr) throw "index: underflow";
this.stk[this.ptr-1]=this.stk[this.ptr-2-this.stk[this.ptr-1]];
if (this.stk[this.ptr-3] instanceof BWIPJS.psstring || this.stk[this.ptr-3] instanceof BWIPJS.psarray)
this.stk[this.ptr-3].set(this.stk[this.ptr-2], this.stk[this.ptr-1]);
else this.stk[this.ptr-3][this.stk[this.ptr-2].toString()]=this.stk[this.ptr-1];
this.ptr-=3;
this.stk[this.ptr++]=3;
if (this.stk[this.ptr-1] >= this.ptr) throw "index: underflow";
this.stk[this.ptr-1]=this.stk[this.ptr-2-this.stk[this.ptr-1]];
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=4;
if (this.stk[this.ptr-1] >= this.ptr) throw "index: underflow";
this.stk[this.ptr-1]=this.stk[this.ptr-2-this.stk[this.ptr-1]];
this.stk[this.ptr++]=3;
if (this.stk[this.ptr-1] >= this.ptr) throw "index: underflow";
this.stk[this.ptr-1]=this.stk[this.ptr-2-this.stk[this.ptr-1]];
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
var t=this.dstk.get("nexts");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
}
function $f13(){
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
this.stk[this.ptr++]=1;
this.stk[this.ptr++]=4;
if (this.stk[this.ptr-1] >= this.ptr) throw "index: underflow";
this.stk[this.ptr-1]=this.stk[this.ptr-2-this.stk[this.ptr-1]];
this.stk[this.ptr++]=$f12;
var t20=this.stk[--this.ptr];
var t18=this.stk[--this.ptr];
var t17=this.stk[--this.ptr];
var t16=this.stk[--this.ptr];
for (var t19=t16; t17<0 ? t19>=t18 : t19<=t18; t19+=t17) {
this.stk[this.ptr++]=t19;
if (t20.call(this)==-1) break;
}
}
function $f14(){
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
var t=this.dstk.get("s");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
var t=this.dstk.get("b");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
}
function $f15(){
this.stk[this.ptr++]="out";
this.stk[this.ptr++]=Infinity;
this.stk[this.ptr++]=3;
this.stk[this.ptr++]=1;
this.stk[this.ptr++]=10;
this.stk[this.ptr++]=$f14;
var t25=this.stk[--this.ptr];
var t23=this.stk[--this.ptr];
var t22=this.stk[--this.ptr];
var t21=this.stk[--this.ptr];
for (var t24=t21; t22<0 ? t24>=t23 : t24<=t23; t24+=t22) {
this.stk[this.ptr++]=t24;
if (t25.call(this)==-1) break;
}
for (var i = this.ptr-1; i >= 0 && this.stk[i] !== Infinity; i--) ;
if (i < 0) throw "array: underflow";
var t = this.stk.splice(i+1, this.ptr-1-i);
this.ptr = i;
this.stk[this.ptr++]=BWIPJS.psarray(t);
this.stk[this.ptr++]=0;
var t=this.dstk.get("chan");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=2;
this.stk[this.ptr-2]=this.stk[this.ptr-2]*this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr-3]=this.stk[this.ptr-3].subset(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=2;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f16(){
var t=this.dstk.get("b");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=2;
if (this.stk[this.ptr-1] >= this.ptr) throw "index: underflow";
this.stk[this.ptr-1]=this.stk[this.ptr-2-this.stk[this.ptr-1]];
this.stk[this.ptr++]=4;
if (this.stk[this.ptr-1] >= this.ptr) throw "index: underflow";
this.stk[this.ptr-1]=this.stk[this.ptr-2-this.stk[this.ptr-1]];
if (this.stk[this.ptr-3] instanceof BWIPJS.psstring || this.stk[this.ptr-3] instanceof BWIPJS.psarray)
this.stk[this.ptr-3].set(this.stk[this.ptr-2], this.stk[this.ptr-1]);
else this.stk[this.ptr-3][this.stk[this.ptr-2].toString()]=this.stk[this.ptr-1];
this.ptr-=3;
var t=this.dstk.get("value");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("target");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring)
this.stk[this.ptr-2]=this.stk[this.ptr-2].toString()==this.stk[this.ptr-1];
else this.stk[this.ptr-2]=this.stk[this.ptr-2]==this.stk[this.ptr-1];
this.ptr--;
this.stk[this.ptr++]=$f15;
var t26=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t26.call(this)==-1) return -1;
}
this.stk[this.ptr++]="value";
var t=this.dstk.get("value");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f17(){
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
this.stk[this.ptr++]=3;
if (this.stk[this.ptr-1] >= this.ptr) throw "index: underflow";
this.stk[this.ptr-1]=this.stk[this.ptr-2-this.stk[this.ptr-1]];
this.stk[this.ptr-2]=this.stk[this.ptr-2]<=this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=$f16;
var t27=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t27.call(this)==-1) return -1;
}
}
function $f18(){
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
var t=this.dstk.get("s");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
var t=this.dstk.get("b");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
var t=this.dstk.get("s");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
var t=this.dstk.get("b");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.stk[this.ptr++]=2;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=4;
this.stk[this.ptr-2]=this.stk[this.ptr-2]>this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=$f10;
this.stk[this.ptr++]=$f11;
var t14=this.stk[--this.ptr];
var t15=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t15.call(this)==-1) return -1;
} else {
if (t14.call(this)==-1) return -1;
}
this.stk[this.ptr++]=1;
if (this.stk[this.ptr-1] >= this.ptr) throw "index: underflow";
this.stk[this.ptr-1]=this.stk[this.ptr-2-this.stk[this.ptr-1]];
var t=this.dstk.get("chan");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=2;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr-2]=this.stk[this.ptr-2]<this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=$f13;
this.stk[this.ptr++]=$f17;
var t28=this.stk[--this.ptr];
var t29=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t29.call(this)==-1) return -1;
} else {
if (t28.call(this)==-1) return -1;
}
this.ptr--;
this.ptr--;
this.ptr--;
this.ptr--;
}
function $f19(){
this.stk[this.ptr++]=1;
}
function $f20(){
this.stk[this.ptr++]=1;
if (this.stk[this.ptr-1] >= this.ptr) throw "index: underflow";
this.stk[this.ptr-1]=this.stk[this.ptr-2-this.stk[this.ptr-1]];
}
function $f21(){
var t=this.dstk.get("s");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=2;
if (this.stk[this.ptr-1] >= this.ptr) throw "index: underflow";
this.stk[this.ptr-1]=this.stk[this.ptr-2-this.stk[this.ptr-1]];
this.stk[this.ptr++]=2;
if (this.stk[this.ptr-1] >= this.ptr) throw "index: underflow";
this.stk[this.ptr-1]=this.stk[this.ptr-2-this.stk[this.ptr-1]];
if (this.stk[this.ptr-3] instanceof BWIPJS.psstring || this.stk[this.ptr-3] instanceof BWIPJS.psarray)
this.stk[this.ptr-3].set(this.stk[this.ptr-2], this.stk[this.ptr-1]);
else this.stk[this.ptr-3][this.stk[this.ptr-2].toString()]=this.stk[this.ptr-1];
this.ptr-=3;
this.stk[this.ptr++]=2;
if (this.stk[this.ptr-1] >= this.ptr) throw "index: underflow";
this.stk[this.ptr-1]=this.stk[this.ptr-2-this.stk[this.ptr-1]];
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=3;
if (this.stk[this.ptr-1] >= this.ptr) throw "index: underflow";
this.stk[this.ptr-1]=this.stk[this.ptr-2-this.stk[this.ptr-1]];
this.stk[this.ptr++]=2;
if (this.stk[this.ptr-1] >= this.ptr) throw "index: underflow";
this.stk[this.ptr-1]=this.stk[this.ptr-2-this.stk[this.ptr-1]];
var t=this.dstk.get("nextb");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
}
function $f22(){
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
var t=this.dstk.get("chan");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=2;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr-2]=this.stk[this.ptr-2]<this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=$f19;
this.stk[this.ptr++]=$f20;
var t30=this.stk[--this.ptr];
var t31=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t31.call(this)==-1) return -1;
} else {
if (t30.call(this)==-1) return -1;
}
this.stk[this.ptr++]=1;
this.stk[this.ptr++]=3;
if (this.stk[this.ptr-1] >= this.ptr) throw "index: underflow";
this.stk[this.ptr-1]=this.stk[this.ptr-2-this.stk[this.ptr-1]];
this.stk[this.ptr++]=$f21;
var t36=this.stk[--this.ptr];
var t34=this.stk[--this.ptr];
var t33=this.stk[--this.ptr];
var t32=this.stk[--this.ptr];
for (var t35=t32; t33<0 ? t35>=t34 : t35<=t34; t35+=t33) {
this.stk[this.ptr++]=t35;
if (t36.call(this)==-1) break;
}
this.ptr--;
this.ptr--;
this.ptr--;
}
function $f23(){
this.stk[this.ptr++]="chan";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="target";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="value";
this.stk[this.ptr++]=0;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="out";
this.stk[this.ptr++]=-1;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="b";
this.stk[this.ptr++]=BWIPJS.psarray([1,1,1,0,0,0,0,0,0,0,0]);
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="s";
this.stk[this.ptr++]=BWIPJS.psarray([0,1,1,0,0,0,0,0,0,0,0]);
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
var t=this.dstk.get("chan");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
this.stk[this.ptr++]=3;
var t=this.dstk.get("nexts");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("out");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
}
function $f24(){
this.stk[this.ptr++]=BWIPJS.psarray([1,1,1,1,1]);
}
function $f25(){
this.stk[this.ptr++]=BWIPJS.psarray([1,1,1,1,1,1,1,1,1]);
}
function $f26(){
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
var t=this.dstk.get("data");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
var t=this.dstk.get("mod23");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
this.stk[this.ptr-2]=this.stk[this.ptr-2]*this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
}
function $f27(){
this.stk[this.ptr++]="mod23";
this.stk[this.ptr++]=Infinity;
this.stk[this.ptr++]=BWIPJS.psarray([]);
this.stk[this.ptr++]=BWIPJS.psarray([]);
this.stk[this.ptr++]=BWIPJS.psarray([13,12,4,9,3,1]);
this.stk[this.ptr++]=BWIPJS.psarray([13,2,12,3,18,16,4,1]);
this.stk[this.ptr++]=BWIPJS.psarray([11,16,17,8,20,4,10,2,5,1]);
this.stk[this.ptr++]=BWIPJS.psarray([1,4,16,18,3,12,2,8,9,13,6,1]);
this.stk[this.ptr++]=BWIPJS.psarray([20,16,22,13,15,12,5,4,8,9,21,3,7,1]);
this.stk[this.ptr++]=BWIPJS.psarray([2,6,18,8,1,3,9,4,12,13,16,2,6,18,8,1]);
for (var i = this.ptr-1; i >= 0 && this.stk[i] !== Infinity; i--) ;
if (i < 0) throw "array: underflow";
var t = this.stk.splice(i+1, this.ptr-1-i);
this.ptr = i;
this.stk[this.ptr++]=BWIPJS.psarray(t);
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]=0;
this.stk[this.ptr++]=0;
this.stk[this.ptr++]=1;
var t=this.dstk.get("data");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (typeof(this.stk[this.ptr-1].length)!=="number") throw "length: invalid: " + BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr-1]=this.stk[this.ptr-1].length;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=$f26;
var t43=this.stk[--this.ptr];
var t41=this.stk[--this.ptr];
var t40=this.stk[--this.ptr];
var t39=this.stk[--this.ptr];
for (var t42=t39; t40<0 ? t42>=t41 : t42<=t41; t42+=t40) {
this.stk[this.ptr++]=t42;
if (t43.call(this)==-1) break;
}
this.stk[this.ptr++]=23;
this.stk[this.ptr-2]=this.stk[this.ptr-2]%this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=3;
var t=this.dstk.get("encode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]="check";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f28(){
this.stk[this.ptr++]="i";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
var t=this.dstk.get("txt");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("i");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=Infinity;
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("i");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-3]=this.stk[this.ptr-3].subset(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=2;
this.stk[this.ptr++]=0;
this.stk[this.ptr++]=0;
this.stk[this.ptr++]=BWIPJS.psstring("");
this.stk[this.ptr++]=0;
for (var i = this.ptr-1; i >= 0 && this.stk[i] !== Infinity; i--) ;
if (i < 0) throw "array: underflow";
var t = this.stk.splice(i+1, this.ptr-1-i);
this.ptr = i;
this.stk[this.ptr++]=BWIPJS.psarray(t);
if (this.stk[this.ptr-3] instanceof BWIPJS.psstring || this.stk[this.ptr-3] instanceof BWIPJS.psarray)
this.stk[this.ptr-3].set(this.stk[this.ptr-2], this.stk[this.ptr-1]);
else this.stk[this.ptr-3][this.stk[this.ptr-2].toString()]=this.stk[this.ptr-1];
this.ptr-=3;
}
function $f29(){
var t=this.dstk.get("height");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
}
function $f30(){
this.stk[this.ptr++]=0;
}
this.stk[this.ptr++]=20;
this.stk[this.ptr-1]={};
this.dict=this.stk[--this.ptr]; this.dstk.push(this.dict);
this.stk[this.ptr++]="options";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="barcode";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="dontdraw";
this.stk[this.ptr++]=false;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="shortfinder";
this.stk[this.ptr++]=false;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="includetext";
this.stk[this.ptr++]=false;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="includecheck";
this.stk[this.ptr++]=false;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="height";
this.stk[this.ptr++]=1;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
var t=this.dstk.get("options");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr-1]=BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr++]="stringtype";
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring)
this.stk[this.ptr-2]=this.stk[this.ptr-2].toString()==this.stk[this.ptr-1];
else this.stk[this.ptr-2]=this.stk[this.ptr-2]==this.stk[this.ptr-1];
this.ptr--;
this.stk[this.ptr++]=$f4;
var t4=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t4.call(this)==-1) return -1;
}
var t=this.dstk.get("options");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=$f5;
var t7=this.stk[--this.ptr];
var t6=this.stk[--this.ptr];
for (t5 in t6) {
if (t6 instanceof BWIPJS.psstring || t6 instanceof BWIPJS.psarray) {
if (t5.charCodeAt(0) > 57) continue;
this.stk[this.ptr++]=t6.get(t5);
} else {
this.stk[this.ptr++]=t5;
this.stk[this.ptr++]=t6[t5];
}
if (t7.call(this)==-1) break;
}
this.stk[this.ptr++]="height";
var t=this.dstk.get("height");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr-1]=parseFloat(this.stk[this.ptr-1]);
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (typeof(this.stk[this.ptr-1].length)!=="number") throw "length: invalid: " + BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr-1]=this.stk[this.ptr-1].length;
this.stk[this.ptr++]=2;
this.stk[this.ptr-2]=this.stk[this.ptr-2]<this.stk[this.ptr-1]; this.ptr--;
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (typeof(this.stk[this.ptr-1].length)!=="number") throw "length: invalid: " + BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr-1]=this.stk[this.ptr-1].length;
this.stk[this.ptr++]=7;
this.stk[this.ptr-2]=this.stk[this.ptr-2]>this.stk[this.ptr-1]; this.ptr--;
if (typeof(this.stk[this.ptr-1])=="boolean") this.stk[this.ptr-2]=this.stk[this.ptr-2]||this.stk[this.ptr-1];
else this.stk[this.ptr-2]=this.stk[this.ptr-2]|this.stk[this.ptr-1];
this.ptr--;
this.stk[this.ptr++]=$f6;
var t8=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t8.call(this)==-1) return -1;
}
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=$f8;
var t12=this.stk[--this.ptr];
var t11=this.stk[--this.ptr];
for (t10 in t11) {
if (t11 instanceof BWIPJS.psstring || t11 instanceof BWIPJS.psarray) {
if (t10.charCodeAt(0) > 57) continue;
this.stk[this.ptr++]=t11.get(t10);
} else {
this.stk[this.ptr++]=t10;
this.stk[this.ptr++]=t11[t10];
}
if (t12.call(this)==-1) break;
}
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr-1]=parseInt(this.stk[this.ptr-1],10);
this.stk[this.ptr++]=BWIPJS.psarray([26,292,3493,44072,576688,7742862]);
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (typeof(this.stk[this.ptr-1].length)!=="number") throw "length: invalid: " + BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr-1]=this.stk[this.ptr-1].length;
this.stk[this.ptr++]=2;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
this.stk[this.ptr-2]=this.stk[this.ptr-2]>this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=$f9;
var t13=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t13.call(this)==-1) return -1;
}
this.stk[this.ptr++]="nextb";
this.stk[this.ptr++]=$f18;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="nexts";
this.stk[this.ptr++]=$f22;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="encode";
this.stk[this.ptr++]=$f23;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="barlen";
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (typeof(this.stk[this.ptr-1].length)!=="number") throw "length: invalid: " + BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr-1]=this.stk[this.ptr-1].length;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="finder";
var t=this.dstk.get("shortfinder");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=$f24;
this.stk[this.ptr++]=$f25;
var t37=this.stk[--this.ptr];
var t38=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t38.call(this)==-1) return -1;
} else {
if (t37.call(this)==-1) return -1;
}
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="data";
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr-1]=parseInt(this.stk[this.ptr-1],10);
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
var t=this.dstk.get("encode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="check";
this.stk[this.ptr++]=BWIPJS.psarray([]);
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
var t=this.dstk.get("includecheck");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=$f27;
var t44=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t44.call(this)==-1) return -1;
}
this.stk[this.ptr++]="sbs";
this.stk[this.ptr++]=Infinity;
var t=this.dstk.get("finder");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-1];
for (var i = 0; i < t.length; i++) this.stk[this.ptr-1+i]=t.get(i);
this.ptr += t.length;
this.stk[this.ptr-1]=t;
this.ptr--;
var t=this.dstk.get("data");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-1];
for (var i = 0; i < t.length; i++) this.stk[this.ptr-1+i]=t.get(i);
this.ptr += t.length;
this.stk[this.ptr-1]=t;
this.ptr--;
var t=this.dstk.get("check");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-1];
for (var i = 0; i < t.length; i++) this.stk[this.ptr-1+i]=t.get(i);
this.ptr += t.length;
this.stk[this.ptr-1]=t;
this.ptr--;
for (var i = this.ptr-1; i >= 0 && this.stk[i] !== Infinity; i--) ;
if (i < 0) throw "array: underflow";
var t = this.stk.splice(i+1, this.ptr-1-i);
this.ptr = i;
this.stk[this.ptr++]=BWIPJS.psarray(t);
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="txt";
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr-1]=BWIPJS.psarray(this.stk[this.ptr-1]);
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]=0;
this.stk[this.ptr++]=1;
var t=this.dstk.get("barlen");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=$f28;
var t49=this.stk[--this.ptr];
var t47=this.stk[--this.ptr];
var t46=this.stk[--this.ptr];
var t45=this.stk[--this.ptr];
for (var t48=t45; t46<0 ? t48>=t47 : t48<=t47; t48+=t46) {
this.stk[this.ptr++]=t48;
if (t49.call(this)==-1) break;
}
this.stk[this.ptr++]=Infinity;
this.stk[this.ptr++]="ren";
var t=this.dstk.get("renlinear");
this.stk[this.ptr++]=t;
this.stk[this.ptr++]="sbs";
var t=this.dstk.get("sbs");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]="bhs";
this.stk[this.ptr++]=Infinity;
var t=this.dstk.get("sbs");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (typeof(this.stk[this.ptr-1].length)!=="number") throw "length: invalid: " + BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr-1]=this.stk[this.ptr-1].length;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=2;
this.stk[this.ptr-2]=Math.floor(this.stk[this.ptr-2]/this.stk[this.ptr-1]); this.ptr--;
this.stk[this.ptr++]=$f29;
var t52=this.stk[--this.ptr];
var t50=this.stk[--this.ptr];
for (var t51=0; t51<t50; t51++) {
if (t52.call(this)==-1) break;
}
for (var i = this.ptr-1; i >= 0 && this.stk[i] !== Infinity; i--) ;
if (i < 0) throw "array: underflow";
var t = this.stk.splice(i+1, this.ptr-1-i);
this.ptr = i;
this.stk[this.ptr++]=BWIPJS.psarray(t);
this.stk[this.ptr++]="bbs";
this.stk[this.ptr++]=Infinity;
var t=this.dstk.get("sbs");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (typeof(this.stk[this.ptr-1].length)!=="number") throw "length: invalid: " + BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr-1]=this.stk[this.ptr-1].length;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=2;
this.stk[this.ptr-2]=Math.floor(this.stk[this.ptr-2]/this.stk[this.ptr-1]); this.ptr--;
this.stk[this.ptr++]=$f30;
var t55=this.stk[--this.ptr];
var t53=this.stk[--this.ptr];
for (var t54=0; t54<t53; t54++) {
if (t55.call(this)==-1) break;
}
for (var i = this.ptr-1; i >= 0 && this.stk[i] !== Infinity; i--) ;
if (i < 0) throw "array: underflow";
var t = this.stk.splice(i+1, this.ptr-1-i);
this.ptr = i;
this.stk[this.ptr++]=BWIPJS.psarray(t);
this.stk[this.ptr++]="txt";
var t=this.dstk.get("txt");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]="textxalign";
this.stk[this.ptr++]=BWIPJS.psstring("center");
this.stk[this.ptr++]="opt";
var t=this.dstk.get("options");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t = {};
for (var i = this.ptr-1; i >= 1 && this.stk[i] !== Infinity; i-=2) {
if (this.stk[i-1] === Infinity) throw "dict: malformed stack";
t[this.stk[i-1]]=this.stk[i];
}
if (i < 0 || this.stk[i]!==Infinity) throw "dict: underflow";
this.ptr = i;
this.stk[this.ptr++]=t;
var t=this.dstk.get("dontdraw");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (typeof(this.stk[this.ptr-1])=="boolean") this.stk[this.ptr-1]=!this.stk[this.ptr-1];
else this.stk[this.ptr-1]=~this.stk[this.ptr-1];
var t=this.dstk.get("renlinear");
this.stk[this.ptr++]=t;
var t56=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t56.call(this)==-1) return -1;
}
this.dstk.pop(); this.dict=this.dstk[this.dstk.length-1];
psstptr = this.ptr;
}
BWIPJS.decrefs("channelcode");
// END OF channelcode
|
'use strict';
/**
* Storage内容仓库模块
* @module zrender/Storage
* @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
* @author errorrik (errorrik@gmail.com)
* @author pissang (https://github.com/pissang/)
*/
var util = require('./core/util');
var env = require('./core/env');
var Group = require('./container/Group');
// Use timsort because in most case elements are partially sorted
// https://jsfiddle.net/pissang/jr4x7mdm/8/
var timsort = require('./core/timsort');
function shapeCompareFunc(a, b) {
if (a.zlevel === b.zlevel) {
if (a.z === b.z) {
// if (a.z2 === b.z2) {
// // FIXME Slow has renderidx compare
// // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
// // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
// return a.__renderidx - b.__renderidx;
// }
return a.z2 - b.z2;
}
return a.z - b.z;
}
return a.zlevel - b.zlevel;
}
/**
* 内容仓库 (M)
* @alias module:zrender/Storage
* @constructor
*/
var Storage = function () {
// 所有常规形状,id索引的map
this._elements = {};
this._roots = [];
this._displayList = [];
this._displayListLen = 0;
};
Storage.prototype = {
constructor: Storage,
/**
* @param {Function} cb
*
*/
traverse: function (cb, context) {
for (var i = 0; i < this._roots.length; i++) {
this._roots[i].traverse(cb, context);
}
},
/**
* 返回所有图形的绘制队列
* @param {boolean} [update=false] 是否在返回前更新该数组
* @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
*
* 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
* @return {Array.<module:zrender/graphic/Displayable>}
*/
getDisplayList: function (update, includeIgnore) {
includeIgnore = includeIgnore || false;
if (update) {
this.updateDisplayList(includeIgnore);
}
return this._displayList;
},
/**
* 更新图形的绘制队列。
* 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
* 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
* @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
*/
updateDisplayList: function (includeIgnore) {
this._displayListLen = 0;
var roots = this._roots;
var displayList = this._displayList;
for (var i = 0, len = roots.length; i < len; i++) {
this._updateAndAddDisplayable(roots[i], null, includeIgnore);
}
displayList.length = this._displayListLen;
// for (var i = 0, len = displayList.length; i < len; i++) {
// displayList[i].__renderidx = i;
// }
// displayList.sort(shapeCompareFunc);
env.canvasSupported && timsort(displayList, shapeCompareFunc);
},
_updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
if (el.ignore && !includeIgnore) {
return;
}
el.beforeUpdate();
if (el.__dirty) {
el.update();
}
el.afterUpdate();
var clipPath = el.clipPath;
if (clipPath) {
// clipPath 的变换是基于 group 的变换
clipPath.parent = el;
clipPath.updateTransform();
// FIXME 效率影响
if (clipPaths) {
clipPaths = clipPaths.slice();
clipPaths.push(clipPath);
}
else {
clipPaths = [clipPath];
}
}
if (el.isGroup) {
var children = el._children;
for (var i = 0; i < children.length; i++) {
var child = children[i];
// Force to mark as dirty if group is dirty
// FIXME __dirtyPath ?
if (el.__dirty) {
child.__dirty = true;
}
this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
}
// Mark group clean here
el.__dirty = false;
}
else {
el.__clipPaths = clipPaths;
this._displayList[this._displayListLen++] = el;
}
},
/**
* 添加图形(Shape)或者组(Group)到根节点
* @param {module:zrender/Element} el
*/
addRoot: function (el) {
// Element has been added
if (this._elements[el.id]) {
return;
}
if (el instanceof Group) {
el.addChildrenToStorage(this);
}
this.addToMap(el);
this._roots.push(el);
},
/**
* 删除指定的图形(Shape)或者组(Group)
* @param {string|Array.<string>} [elId] 如果为空清空整个Storage
*/
delRoot: function (elId) {
if (elId == null) {
// 不指定elId清空
for (var i = 0; i < this._roots.length; i++) {
var root = this._roots[i];
if (root instanceof Group) {
root.delChildrenFromStorage(this);
}
}
this._elements = {};
this._roots = [];
this._displayList = [];
this._displayListLen = 0;
return;
}
if (elId instanceof Array) {
for (var i = 0, l = elId.length; i < l; i++) {
this.delRoot(elId[i]);
}
return;
}
var el;
if (typeof(elId) == 'string') {
el = this._elements[elId];
}
else {
el = elId;
}
var idx = util.indexOf(this._roots, el);
if (idx >= 0) {
this.delFromMap(el.id);
this._roots.splice(idx, 1);
if (el instanceof Group) {
el.delChildrenFromStorage(this);
}
}
},
addToMap: function (el) {
if (el instanceof Group) {
el.__storage = this;
}
el.dirty(false);
this._elements[el.id] = el;
return this;
},
get: function (elId) {
return this._elements[elId];
},
delFromMap: function (elId) {
var elements = this._elements;
var el = elements[elId];
if (el) {
delete elements[elId];
if (el instanceof Group) {
el.__storage = null;
}
}
return this;
},
/**
* 清空并且释放Storage
*/
dispose: function () {
this._elements =
this._renderList =
this._roots = null;
},
displayableSortFunc: shapeCompareFunc
};
module.exports = Storage;
|
/**
* Blockly Demo: Storage
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Loading and saving blocks with localStorage and cloud storage.
* @author q.neutron@gmail.com (Quynh Neutron)
*/
'use strict';
// Create a namespace.
var BlocklyStorage = {};
/**
* Backup code blocks to localStorage.
* @private
*/
BlocklyStorage.backupBlocks_ = function() {
if ('localStorage' in window) {
var xml = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
// Gets the current URL, not including the hash.
var url = window.location.href.split('#')[0];
window.localStorage.setItem(url, Blockly.Xml.domToText(xml));
}
};
/**
* Bind the localStorage backup function to the unload event.
*/
BlocklyStorage.backupOnUnload = function() {
window.addEventListener('unload', BlocklyStorage.backupBlocks_, false);
};
/**
* Restore code blocks from localStorage.
*/
BlocklyStorage.restoreBlocks = function() {
var url = window.location.href.split('#')[0];
if ('localStorage' in window && window.localStorage[url]) {
var xml = Blockly.Xml.textToDom(window.localStorage[url]);
Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, xml);
}
};
/**
* Save blocks to database and return a link containing key to XML.
*/
BlocklyStorage.link = function() {
var xml = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
var data = Blockly.Xml.domToText(xml);
BlocklyStorage.makeRequest_('/storage', 'xml', data);
};
/**
* Retrieve XML text from database using given key.
* @param {string} key Key to XML, obtained from href.
*/
BlocklyStorage.retrieveXml = function(key) {
var xml = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
BlocklyStorage.makeRequest_('/storage', 'key', key);
};
/**
* Global reference to current AJAX request.
* @type XMLHttpRequest
* @private
*/
BlocklyStorage.httpRequest_ = null;
/**
* Fire a new AJAX request.
* @param {string} url URL to fetch.
* @param {string} name Name of parameter.
* @param {string} content Content of parameter.
* @private
*/
BlocklyStorage.makeRequest_ = function(url, name, content) {
if (BlocklyStorage.httpRequest_) {
// AJAX call is in-flight.
BlocklyStorage.httpRequest_.abort();
}
BlocklyStorage.httpRequest_ = new XMLHttpRequest();
BlocklyStorage.httpRequest_.name = name;
BlocklyStorage.httpRequest_.onreadystatechange =
BlocklyStorage.handleRequest_;
BlocklyStorage.httpRequest_.open('POST', url);
BlocklyStorage.httpRequest_.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
BlocklyStorage.httpRequest_.send(name + '=' + encodeURIComponent(content));
};
/**
* Callback function for AJAX call.
* @private
*/
BlocklyStorage.handleRequest_ = function() {
if (BlocklyStorage.httpRequest_.readyState == 4) {
if (BlocklyStorage.httpRequest_.status != 200) {
window.alert(BlocklyStorage.HTTPREQUEST_ERROR +
'httpRequest_.status: ' + BlocklyStorage.httpRequest_.status);
} else {
var data = BlocklyStorage.httpRequest_.responseText.trim();
if (BlocklyStorage.httpRequest_.name == 'xml') {
window.location.hash = data;
window.alert(BlocklyStorage.LINK_ALERT + window.location.href);
} else if (BlocklyStorage.httpRequest_.name == 'key') {
if (!data.length) {
window.alert(BlocklyStorage.HASH_ERROR.replace('%1',
window.location.hash));
} else {
BlocklyStorage.loadXml_(data);
}
}
BlocklyStorage.monitorChanges_();
}
BlocklyStorage.httpRequest_ = null;
}
};
/**
* Start monitoring the workspace. If a change is made that changes the XML,
* clear the key from the URL. Stop monitoring the workspace once such a
* change is detected.
* @private
*/
BlocklyStorage.monitorChanges_ = function() {
var startXmlDom = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
var startXmlText = Blockly.Xml.domToText(startXmlDom);
var canvas = Blockly.mainWorkspace.getCanvas();
function change() {
var xmlDom = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
var xmlText = Blockly.Xml.domToText(xmlDom);
if (startXmlText != xmlText) {
window.location.hash = '';
Blockly.removeChangeListener(bindData);
}
}
var bindData = Blockly.addChangeListener(change);
};
/**
* Load blocks from XML.
* @param {string} xml Text representation of XML.
* @private
*/
BlocklyStorage.loadXml_ = function(xml) {
try {
xml = Blockly.Xml.textToDom(xml);
} catch (e) {
window.alert(BlocklyStorage.XML_ERROR + xml);
return;
}
// Clear the workspace to avoid merge.
Blockly.mainWorkspace.clear();
Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, xml);
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:370aa4c5fff83a07e3fa5ad7fee43ee16e9489a09e16dc9d6aa1d19688d5da1f
size 1057
|
var notify = require("gulp-notify")
module.exports = function (errorObject, callback) {
notify.onError(errorObject.toString().split(': ').join(':\n')).apply(this, arguments)
// Keep gulp from hanging on this task
if (typeof this.emit === 'function') this.emit('end')
}
|
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _property = require('../property');
var _property2 = _interopRequireDefault(_property);
var _form_actions = require('../form_actions');
var _form_actions2 = _interopRequireDefault(_form_actions);
var _underscore = require('underscore');
var _underscore2 = _interopRequireDefault(_underscore);
var AutoListItem = (function (_React$Component) {
_inherits(AutoListItem, _React$Component);
function AutoListItem() {
var _this = this;
_classCallCheck(this, AutoListItem);
_get(Object.getPrototypeOf(AutoListItem.prototype), 'constructor', this).apply(this, arguments);
this.removeChild = function (ev) {
_form_actions2['default'].removeChildFromList({ listId: _this.props.name, itemIndex: _this.props.itemIndex });
};
}
_createClass(AutoListItem, [{
key: 'render',
value: function render() {
var _this2 = this;
var children = undefined;
var _props = this.props;
var properties = _props.properties;
var name = _props.name;
var rowClass = _props.rowClass;
var removeButton = _react2['default'].cloneElement(this.props.removeButton, {
onClick: this.removeChild
});
children = _underscore2['default'].map(properties, function (value, key) {
return _react2['default'].createElement(_property2['default'], _extends({}, _this2.props, value, {
key: key,
name: key,
onBlur: _this2.props.onBlur,
onChange: _this2.props.onChange,
hideLabel: _this2.props.header
}));
});
return _react2['default'].createElement(
'div',
{ key: name, name: name, className: rowClass },
children,
removeButton
);
}
}]);
return AutoListItem;
})(_react2['default'].Component);
exports['default'] = AutoListItem;
module.exports = exports['default']; |
/*
* /MathJax/jax/output/HTML-CSS/fonts/STIX/IntegralsSm/Regular/Main.js
*
* Copyright (c) 2009-2013 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS.STIXIntegralsSm={directory:"IntegralsSm/Regular",family:"STIXIntegralsSm",Ranges:[[32,32,"All"],[160,160,"All"],[8747,8755,"All"],[10763,10780,"All"]],8747:[690,189,496,41,552],8750:[690,189,560,41,552]};MathJax.OutputJax["HTML-CSS"].initFont("STIXIntegralsSm");MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/IntegralsSm/Regular/Main.js");
|
import Route from '@ember/routing/route';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
import VisualizationsRouteMixin from 'ilios-common/mixins/course-visualizations-route';
export default Route.extend(AuthenticatedRouteMixin, VisualizationsRouteMixin, {
});
|
// WIZARD ===============================================================================
jQuery(function($) {
// Basic wizard with validation
$("#survey_container").wizard({
stepsWrapper: "#wrapped",
submit: ".submit",
beforeSelect: function( event, state ) {
var inputs = $(this).wizard('state').step.find(':input');
return !inputs.length || !!inputs.valid();
}
}).validate({
errorPlacement: function(error, element) {
if ( element.is(':radio') || element.is(':checkbox') ) {
error.insertBefore( element.next() );
} else {
error.insertAfter( element );
}
}
});
// progress bar
$("#progressbar").progressbar();
$("#survey_container").wizard({
afterSelect: function( event, state ) {
$("#progressbar").progressbar("value", state.percentComplete);
$("#location").text("(" + state.stepsComplete + "/" + state.stepsPossible + ")");
}
});
});
// OHTER ===============================================================================
$(document).ready(function(){
//Check and radio input styles
$('input.check_radio').iCheck({
checkboxClass: 'icheckbox_square-aero',
radioClass: 'iradio_square-aero'
});
//Pace holder
$('input, textarea').placeholder();
});
|
"use strict";
var _ = require('underscore');
var Cell = (function () {
function Cell(value, row, column, dataSet, isPopOver) {
this.value = value;
this.row = row;
this.column = column;
this.dataSet = dataSet;
this.newValue = '';
this.isVisible = true;
this.parsedValue = ' ';
this.isPopover = false;
this.type = "";
this.newValue = value;
this.isPopover = isPopOver;
}
Cell.prototype.getData = function () {
return this.value;
};
Cell.prototype.getValue = function () {
var valid = this.column.getValuePrepareFunction() instanceof Function;
var prepare = valid ? this.column.getValuePrepareFunction() : Cell.PREPARE;
var parseValue;
if (_.isArray(this.value)) {
if (this.value.length > 0) {
var lengthStr = this.value.length;
this.parsedValue = lengthStr + (this.value.length > 1 ? ' mesages' : ' message');
}
return prepare.call(null, this.parsedValue);
}
return prepare.call(null, this.value);
};
Cell.prototype.getColumn = function () {
return this.column;
};
Cell.prototype.getRow = function () {
return this.row;
};
Cell.PREPARE = function (value) { return value; };
return Cell;
}());
exports.Cell = Cell;
//# sourceMappingURL=cell.js.map |
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
(function(){function g(a,b,g,h,j,n,l,o){for(var p=a.config,k=new CKEDITOR.style(l),c=j.split(";"),j=[],f={},d=0;d<c.length;d++){var e=c[d];if(e){var e=e.split("/"),m={},i=c[d]=e[0];m[g]=j[d]=e[1]||i;f[i]=new CKEDITOR.style(l,m);f[i]._.definition.name=i}else c.splice(d--,1)}a.ui.addRichCombo(b,{label:h.label,title:h.panelTitle,toolbar:"styles,"+o,allowedContent:k,requiredContent:k,panel:{css:[CKEDITOR.skin.getPath("editor")].concat(p.contentsCss),multiSelect:!1,attributes:{"aria-label":h.panelTitle}},
init:function(){this.startGroup(h.panelTitle);for(var a=0;a<c.length;a++){var b=c[a];this.add(b,f[b].buildPreview(),b)}},onClick:function(b){a.focus();a.fire("saveSnapshot");var c=f[b];a[this.getValue()==b?"removeStyle":"applyStyle"](c);a.fire("saveSnapshot")},onRender:function(){a.on("selectionChange",function(a){for(var b=this.getValue(),a=a.data.path.elements,c=0,d;c<a.length;c++){d=a[c];for(var e in f)if(f[e].checkElementMatch(d,!0)){e!=b&&this.setValue(e);return}}this.setValue("",n)},this)},
refresh:function(){a.activeFilter.check(k)||this.setState(CKEDITOR.TRISTATE_DISABLED)}})}CKEDITOR.plugins.add("font",{requires:"richcombo",lang:"af,ar,bg,bn,bs,ca,cs,cy,da,de,el,en,en-au,en-ca,en-gb,eo,es,et,eu,fa,fi,fo,fr,fr-ca,gl,gu,he,hi,hr,hu,id,is,it,ja,ka,km,ko,ku,lt,lv,mk,mn,ms,nb,nl,no,pl,pt,pt-br,ro,ru,si,sk,sl,sq,sr,sr-latn,sv,th,tr,ug,uk,vi,zh,zh-cn",init:function(a){var b=a.config;g(a,"Font","family",a.lang.font,b.font_names,b.font_defaultLabel,b.font_style,30);g(a,"FontSize","size",a.lang.font.fontSize,
b.fontSize_sizes,b.fontSize_defaultLabel,b.fontSize_style,40)}})})();CKEDITOR.config.font_names="Arial/Arial, Helvetica, sans-serif;Comic Sans MS/Comic Sans MS, cursive;Courier New/Courier New, Courier, monospace;Georgia/Georgia, serif;Lucida Sans Unicode/Lucida Sans Unicode, Lucida Grande, sans-serif;Tahoma/Tahoma, Geneva, sans-serif;Times New Roman/Times New Roman, Times, serif;Trebuchet MS/Trebuchet MS, Helvetica, sans-serif;Verdana/Verdana, Geneva, sans-serif";
CKEDITOR.config.font_defaultLabel="";CKEDITOR.config.font_style={element:"span",styles:{"font-family":"#(family)"},overrides:[{element:"font",attributes:{face:null}}]};CKEDITOR.config.fontSize_sizes="8/8px;9/9px;10/10px;11/11px;12/12px;14/14px;16/16px;18/18px;20/20px;22/22px;24/24px;26/26px;28/28px;36/36px;48/48px;72/72px";CKEDITOR.config.fontSize_defaultLabel="";CKEDITOR.config.fontSize_style={element:"span",styles:{"font-size":"#(size)"},overrides:[{element:"font",attributes:{size:null}}]}; |
/* jshint expr:true */
import { expect } from 'chai';
import {
describeComponent,
it
} from 'ember-mocha';
import hbs from 'htmlbars-inline-precompile';
describeComponent(
'shell/window/status-bar',
'Integration: ShellWindowStatusBarComponent',
{
integration: true
},
function() {
it('renders', function() {
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
// Template block usage:
// this.render(hbs`
// {{#shell/window/status-bar}}
// template content
// {{/shell/window/status-bar}}
// `);
this.render(hbs`{{shell/window/status-bar}}`);
expect(this.$()).to.have.length(1);
});
}
);
|
/**
* Copyright 2013-2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule ReactCompositeComponent
*/
"use strict";
var ReactComponent = require("./ReactComponent");
var ReactContext = require("./ReactContext");
var ReactCurrentOwner = require("./ReactCurrentOwner");
var ReactErrorUtils = require("./ReactErrorUtils");
var ReactOwner = require("./ReactOwner");
var ReactPerf = require("./ReactPerf");
var ReactPropTransferer = require("./ReactPropTransferer");
var ReactPropTypeLocations = require("./ReactPropTypeLocations");
var ReactPropTypeLocationNames = require("./ReactPropTypeLocationNames");
var ReactUpdates = require("./ReactUpdates");
var instantiateReactComponent = require("./instantiateReactComponent");
var invariant = require("./invariant");
var keyMirror = require("./keyMirror");
var merge = require("./merge");
var mixInto = require("./mixInto");
var monitorCodeUse = require("./monitorCodeUse");
var objMap = require("./objMap");
var shouldUpdateReactComponent = require("./shouldUpdateReactComponent");
var warning = require("./warning");
/**
* Policies that describe methods in `ReactCompositeComponentInterface`.
*/
var SpecPolicy = keyMirror({
/**
* These methods may be defined only once by the class specification or mixin.
*/
DEFINE_ONCE: null,
/**
* These methods may be defined by both the class specification and mixins.
* Subsequent definitions will be chained. These methods must return void.
*/
DEFINE_MANY: null,
/**
* These methods are overriding the base ReactCompositeComponent class.
*/
OVERRIDE_BASE: null,
/**
* These methods are similar to DEFINE_MANY, except we assume they return
* objects. We try to merge the keys of the return values of all the mixed in
* functions. If there is a key conflict we throw.
*/
DEFINE_MANY_MERGED: null
});
var injectedMixins = [];
/**
* Composite components are higher-level components that compose other composite
* or native components.
*
* To create a new type of `ReactCompositeComponent`, pass a specification of
* your new class to `React.createClass`. The only requirement of your class
* specification is that you implement a `render` method.
*
* var MyComponent = React.createClass({
* render: function() {
* return <div>Hello World</div>;
* }
* });
*
* The class specification supports a specific protocol of methods that have
* special meaning (e.g. `render`). See `ReactCompositeComponentInterface` for
* more the comprehensive protocol. Any other properties and methods in the
* class specification will available on the prototype.
*
* @interface ReactCompositeComponentInterface
* @internal
*/
var ReactCompositeComponentInterface = {
/**
* An array of Mixin objects to include when defining your component.
*
* @type {array}
* @optional
*/
mixins: SpecPolicy.DEFINE_MANY,
/**
* An object containing properties and methods that should be defined on
* the component's constructor instead of its prototype (static methods).
*
* @type {object}
* @optional
*/
statics: SpecPolicy.DEFINE_MANY,
/**
* Definition of prop types for this component.
*
* @type {object}
* @optional
*/
propTypes: SpecPolicy.DEFINE_MANY,
/**
* Definition of context types for this component.
*
* @type {object}
* @optional
*/
contextTypes: SpecPolicy.DEFINE_MANY,
/**
* Definition of context types this component sets for its children.
*
* @type {object}
* @optional
*/
childContextTypes: SpecPolicy.DEFINE_MANY,
// ==== Definition methods ====
/**
* Invoked when the component is mounted. Values in the mapping will be set on
* `this.props` if that prop is not specified (i.e. using an `in` check).
*
* This method is invoked before `getInitialState` and therefore cannot rely
* on `this.state` or use `this.setState`.
*
* @return {object}
* @optional
*/
getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED,
/**
* Invoked once before the component is mounted. The return value will be used
* as the initial value of `this.state`.
*
* getInitialState: function() {
* return {
* isOn: false,
* fooBaz: new BazFoo()
* }
* }
*
* @return {object}
* @optional
*/
getInitialState: SpecPolicy.DEFINE_MANY_MERGED,
/**
* @return {object}
* @optional
*/
getChildContext: SpecPolicy.DEFINE_MANY_MERGED,
/**
* Uses props from `this.props` and state from `this.state` to render the
* structure of the component.
*
* No guarantees are made about when or how often this method is invoked, so
* it must not have side effects.
*
* render: function() {
* var name = this.props.name;
* return <div>Hello, {name}!</div>;
* }
*
* @return {ReactComponent}
* @nosideeffects
* @required
*/
render: SpecPolicy.DEFINE_ONCE,
// ==== Delegate methods ====
/**
* Invoked when the component is initially created and about to be mounted.
* This may have side effects, but any external subscriptions or data created
* by this method must be cleaned up in `componentWillUnmount`.
*
* @optional
*/
componentWillMount: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component has been mounted and has a DOM representation.
* However, there is no guarantee that the DOM node is in the document.
*
* Use this as an opportunity to operate on the DOM when the component has
* been mounted (initialized and rendered) for the first time.
*
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidMount: SpecPolicy.DEFINE_MANY,
/**
* Invoked before the component receives new props.
*
* Use this as an opportunity to react to a prop transition by updating the
* state using `this.setState`. Current props are accessed via `this.props`.
*
* componentWillReceiveProps: function(nextProps, nextContext) {
* this.setState({
* likesIncreasing: nextProps.likeCount > this.props.likeCount
* });
* }
*
* NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop
* transition may cause a state change, but the opposite is not true. If you
* need it, you are probably looking for `componentWillUpdate`.
*
* @param {object} nextProps
* @optional
*/
componentWillReceiveProps: SpecPolicy.DEFINE_MANY,
/**
* Invoked while deciding if the component should be updated as a result of
* receiving new props, state and/or context.
*
* Use this as an opportunity to `return false` when you're certain that the
* transition to the new props/state/context will not require a component
* update.
*
* shouldComponentUpdate: function(nextProps, nextState, nextContext) {
* return !equal(nextProps, this.props) ||
* !equal(nextState, this.state) ||
* !equal(nextContext, this.context);
* }
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @return {boolean} True if the component should update.
* @optional
*/
shouldComponentUpdate: SpecPolicy.DEFINE_ONCE,
/**
* Invoked when the component is about to update due to a transition from
* `this.props`, `this.state` and `this.context` to `nextProps`, `nextState`
* and `nextContext`.
*
* Use this as an opportunity to perform preparation before an update occurs.
*
* NOTE: You **cannot** use `this.setState()` in this method.
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @param {ReactReconcileTransaction} transaction
* @optional
*/
componentWillUpdate: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component's DOM representation has been updated.
*
* Use this as an opportunity to operate on the DOM when the component has
* been updated.
*
* @param {object} prevProps
* @param {?object} prevState
* @param {?object} prevContext
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidUpdate: SpecPolicy.DEFINE_MANY,
/**
* Invoked when the component is about to be removed from its parent and have
* its DOM representation destroyed.
*
* Use this as an opportunity to deallocate any external resources.
*
* NOTE: There is no `componentDidUnmount` since your component will have been
* destroyed by that point.
*
* @optional
*/
componentWillUnmount: SpecPolicy.DEFINE_MANY,
// ==== Advanced methods ====
/**
* Updates the component's currently mounted DOM representation.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @internal
* @overridable
*/
updateComponent: SpecPolicy.OVERRIDE_BASE
};
/**
* Mapping from class specification keys to special processing functions.
*
* Although these are declared like instance properties in the specification
* when defining classes using `React.createClass`, they are actually static
* and are accessible on the constructor instead of the prototype. Despite
* being static, they must be defined outside of the "statics" key under
* which all other static methods are defined.
*/
var RESERVED_SPEC_KEYS = {
displayName: function(ConvenienceConstructor, displayName) {
ConvenienceConstructor.componentConstructor.displayName = displayName;
},
mixins: function(ConvenienceConstructor, mixins) {
if (mixins) {
for (var i = 0; i < mixins.length; i++) {
mixSpecIntoComponent(ConvenienceConstructor, mixins[i]);
}
}
},
childContextTypes: function(ConvenienceConstructor, childContextTypes) {
var Constructor = ConvenienceConstructor.componentConstructor;
validateTypeDef(
Constructor,
childContextTypes,
ReactPropTypeLocations.childContext
);
Constructor.childContextTypes = merge(
Constructor.childContextTypes,
childContextTypes
);
},
contextTypes: function(ConvenienceConstructor, contextTypes) {
var Constructor = ConvenienceConstructor.componentConstructor;
validateTypeDef(
Constructor,
contextTypes,
ReactPropTypeLocations.context
);
Constructor.contextTypes = merge(Constructor.contextTypes, contextTypes);
},
propTypes: function(ConvenienceConstructor, propTypes) {
var Constructor = ConvenienceConstructor.componentConstructor;
validateTypeDef(
Constructor,
propTypes,
ReactPropTypeLocations.prop
);
Constructor.propTypes = merge(Constructor.propTypes, propTypes);
},
statics: function(ConvenienceConstructor, statics) {
mixStaticSpecIntoComponent(ConvenienceConstructor, statics);
}
};
function validateTypeDef(Constructor, typeDef, location) {
for (var propName in typeDef) {
if (typeDef.hasOwnProperty(propName)) {
("production" !== process.env.NODE_ENV ? invariant(
typeof typeDef[propName] == 'function',
'%s: %s type `%s` is invalid; it must be a function, usually from ' +
'React.PropTypes.',
Constructor.displayName || 'ReactCompositeComponent',
ReactPropTypeLocationNames[location],
propName
) : invariant(typeof typeDef[propName] == 'function'));
}
}
}
function validateMethodOverride(proto, name) {
var specPolicy = ReactCompositeComponentInterface[name];
// Disallow overriding of base class methods unless explicitly allowed.
if (ReactCompositeComponentMixin.hasOwnProperty(name)) {
("production" !== process.env.NODE_ENV ? invariant(
specPolicy === SpecPolicy.OVERRIDE_BASE,
'ReactCompositeComponentInterface: You are attempting to override ' +
'`%s` from your class specification. Ensure that your method names ' +
'do not overlap with React methods.',
name
) : invariant(specPolicy === SpecPolicy.OVERRIDE_BASE));
}
// Disallow defining methods more than once unless explicitly allowed.
if (proto.hasOwnProperty(name)) {
("production" !== process.env.NODE_ENV ? invariant(
specPolicy === SpecPolicy.DEFINE_MANY ||
specPolicy === SpecPolicy.DEFINE_MANY_MERGED,
'ReactCompositeComponentInterface: You are attempting to define ' +
'`%s` on your component more than once. This conflict may be due ' +
'to a mixin.',
name
) : invariant(specPolicy === SpecPolicy.DEFINE_MANY ||
specPolicy === SpecPolicy.DEFINE_MANY_MERGED));
}
}
function validateLifeCycleOnReplaceState(instance) {
var compositeLifeCycleState = instance._compositeLifeCycleState;
("production" !== process.env.NODE_ENV ? invariant(
instance.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING,
'replaceState(...): Can only update a mounted or mounting component.'
) : invariant(instance.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING));
("production" !== process.env.NODE_ENV ? invariant(compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE,
'replaceState(...): Cannot update during an existing state transition ' +
'(such as within `render`). This could potentially cause an infinite ' +
'loop so it is forbidden.'
) : invariant(compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE));
("production" !== process.env.NODE_ENV ? invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING,
'replaceState(...): Cannot update while unmounting component. This ' +
'usually means you called setState() on an unmounted component.'
) : invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING));
}
/**
* Custom version of `mixInto` which handles policy validation and reserved
* specification keys when building `ReactCompositeComponent` classses.
*/
function mixSpecIntoComponent(ConvenienceConstructor, spec) {
("production" !== process.env.NODE_ENV ? invariant(
!isValidClass(spec),
'ReactCompositeComponent: You\'re attempting to ' +
'use a component class as a mixin. Instead, just use a regular object.'
) : invariant(!isValidClass(spec)));
("production" !== process.env.NODE_ENV ? invariant(
!ReactComponent.isValidComponent(spec),
'ReactCompositeComponent: You\'re attempting to ' +
'use a component as a mixin. Instead, just use a regular object.'
) : invariant(!ReactComponent.isValidComponent(spec)));
var Constructor = ConvenienceConstructor.componentConstructor;
var proto = Constructor.prototype;
for (var name in spec) {
var property = spec[name];
if (!spec.hasOwnProperty(name)) {
continue;
}
validateMethodOverride(proto, name);
if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
RESERVED_SPEC_KEYS[name](ConvenienceConstructor, property);
} else {
// Setup methods on prototype:
// The following member methods should not be automatically bound:
// 1. Expected ReactCompositeComponent methods (in the "interface").
// 2. Overridden methods (that were mixed in).
var isCompositeComponentMethod = name in ReactCompositeComponentInterface;
var isInherited = name in proto;
var markedDontBind = property && property.__reactDontBind;
var isFunction = typeof property === 'function';
var shouldAutoBind =
isFunction &&
!isCompositeComponentMethod &&
!isInherited &&
!markedDontBind;
if (shouldAutoBind) {
if (!proto.__reactAutoBindMap) {
proto.__reactAutoBindMap = {};
}
proto.__reactAutoBindMap[name] = property;
proto[name] = property;
} else {
if (isInherited) {
// For methods which are defined more than once, call the existing
// methods before calling the new property.
if (ReactCompositeComponentInterface[name] ===
SpecPolicy.DEFINE_MANY_MERGED) {
proto[name] = createMergedResultFunction(proto[name], property);
} else {
proto[name] = createChainedFunction(proto[name], property);
}
} else {
proto[name] = property;
}
}
}
}
}
function mixStaticSpecIntoComponent(ConvenienceConstructor, statics) {
if (!statics) {
return;
}
for (var name in statics) {
var property = statics[name];
if (!statics.hasOwnProperty(name)) {
return;
}
var isInherited = name in ConvenienceConstructor;
var result = property;
if (isInherited) {
var existingProperty = ConvenienceConstructor[name];
var existingType = typeof existingProperty;
var propertyType = typeof property;
("production" !== process.env.NODE_ENV ? invariant(
existingType === 'function' && propertyType === 'function',
'ReactCompositeComponent: You are attempting to define ' +
'`%s` on your component more than once, but that is only supported ' +
'for functions, which are chained together. This conflict may be ' +
'due to a mixin.',
name
) : invariant(existingType === 'function' && propertyType === 'function'));
result = createChainedFunction(existingProperty, property);
}
ConvenienceConstructor[name] = result;
ConvenienceConstructor.componentConstructor[name] = result;
}
}
/**
* Merge two objects, but throw if both contain the same key.
*
* @param {object} one The first object, which is mutated.
* @param {object} two The second object
* @return {object} one after it has been mutated to contain everything in two.
*/
function mergeObjectsWithNoDuplicateKeys(one, two) {
("production" !== process.env.NODE_ENV ? invariant(
one && two && typeof one === 'object' && typeof two === 'object',
'mergeObjectsWithNoDuplicateKeys(): Cannot merge non-objects'
) : invariant(one && two && typeof one === 'object' && typeof two === 'object'));
objMap(two, function(value, key) {
("production" !== process.env.NODE_ENV ? invariant(
one[key] === undefined,
'mergeObjectsWithNoDuplicateKeys(): ' +
'Tried to merge two objects with the same key: %s',
key
) : invariant(one[key] === undefined));
one[key] = value;
});
return one;
}
/**
* Creates a function that invokes two functions and merges their return values.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createMergedResultFunction(one, two) {
return function mergedResult() {
var a = one.apply(this, arguments);
var b = two.apply(this, arguments);
if (a == null) {
return b;
} else if (b == null) {
return a;
}
return mergeObjectsWithNoDuplicateKeys(a, b);
};
}
/**
* Creates a function that invokes two functions and ignores their return vales.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createChainedFunction(one, two) {
return function chainedFunction() {
one.apply(this, arguments);
two.apply(this, arguments);
};
}
if ("production" !== process.env.NODE_ENV) {
var unmountedPropertyWhitelist = {
constructor: true,
construct: true,
isOwnedBy: true, // should be deprecated but can have code mod (internal)
type: true,
props: true,
// currently private but belong on the descriptor and are valid for use
// inside the framework:
__keyValidated__: true,
_owner: true,
_currentContext: true
};
var componentInstanceProperties = {
__keyValidated__: true,
__keySetters: true,
_compositeLifeCycleState: true,
_currentContext: true,
_defaultProps: true,
_instance: true,
_lifeCycleState: true,
_mountDepth: true,
_owner: true,
_pendingCallbacks: true,
_pendingContext: true,
_pendingForceUpdate: true,
_pendingOwner: true,
_pendingProps: true,
_pendingState: true,
_renderedComponent: true,
_rootNodeID: true,
context: true,
props: true,
refs: true,
state: true,
// These are known instance properties coming from other sources
_pendingQueries: true,
_queryPropListeners: true,
queryParams: true
};
var hasWarnedOnComponentType = {};
var warningStackCounter = 0;
var issueMembraneWarning = function(instance, key) {
var isWhitelisted = unmountedPropertyWhitelist.hasOwnProperty(key);
if (warningStackCounter > 0 || isWhitelisted) {
return;
}
var name = instance.constructor.displayName || 'Unknown';
var owner = ReactCurrentOwner.current;
var ownerName = (owner && owner.constructor.displayName) || 'Unknown';
var warningKey = key + '|' + name + '|' + ownerName;
if (hasWarnedOnComponentType.hasOwnProperty(warningKey)) {
// We have already warned for this combination. Skip it this time.
return;
}
hasWarnedOnComponentType[warningKey] = true;
var context = owner ? ' in ' + ownerName + '.' : ' at the top level.';
var staticMethodExample = '<' + name + ' />.type.' + key + '(...)';
monitorCodeUse('react_descriptor_property_access', { component: name });
console.warn(
'Invalid access to component property "' + key + '" on ' + name +
context + ' See http://fb.me/react-warning-descriptors .' +
' Use a static method instead: ' + staticMethodExample
);
};
var wrapInMembraneFunction = function(fn, thisBinding) {
if (fn.__reactMembraneFunction && fn.__reactMembraneSelf === thisBinding) {
return fn.__reactMembraneFunction;
}
return fn.__reactMembraneFunction = function() {
/**
* By getting this function, you've already received a warning. The
* internals of this function will likely cause more warnings. To avoid
* Spamming too much we disable any warning triggered inside of this
* stack.
*/
warningStackCounter++;
try {
// If the this binding is unchanged, we defer to the real component.
// This is important to keep some referential integrity in the
// internals. E.g. owner equality check.
var self = this === thisBinding ? this.__realComponentInstance : this;
return fn.apply(self, arguments);
} finally {
warningStackCounter--;
}
};
};
var defineMembraneProperty = function(membrane, prototype, key) {
Object.defineProperty(membrane, key, {
configurable: false,
enumerable: true,
get: function() {
if (this === membrane) {
// We're allowed to access the prototype directly.
return prototype[key];
}
issueMembraneWarning(this, key);
var realValue = this.__realComponentInstance[key];
// If the real value is a function, we need to provide a wrapper that
// disables nested warnings. The properties type and constructors are
// expected to the be constructors and therefore is often use with an
// equality check and we shouldn't try to rebind those.
if (typeof realValue === 'function' &&
key !== 'type' &&
key !== 'constructor') {
return wrapInMembraneFunction(realValue, this);
}
return realValue;
},
set: function(value) {
if (this === membrane) {
// We're allowed to set a value on the prototype directly.
prototype[key] = value;
return;
}
issueMembraneWarning(this, key);
this.__realComponentInstance[key] = value;
}
});
};
/**
* Creates a membrane prototype which wraps the original prototype. If any
* property is accessed in an unmounted state, a warning is issued.
*
* @param {object} prototype Original prototype.
* @return {object} The membrane prototype.
* @private
*/
var createMountWarningMembrane = function(prototype) {
var membrane = {};
var key;
for (key in prototype) {
defineMembraneProperty(membrane, prototype, key);
}
// These are properties that goes into the instance but not the prototype.
// We can create the membrane on the prototype even though this will
// result in a faulty hasOwnProperty check it's better perf.
for (key in componentInstanceProperties) {
if (componentInstanceProperties.hasOwnProperty(key) &&
!(key in prototype)) {
defineMembraneProperty(membrane, prototype, key);
}
}
return membrane;
};
/**
* Creates a membrane constructor which wraps the component that gets mounted.
*
* @param {function} constructor Original constructor.
* @return {function} The membrane constructor.
* @private
*/
var createDescriptorProxy = function(constructor) {
try {
var ProxyConstructor = function() {
this.__realComponentInstance = new constructor();
// We can only safely pass through known instance variables. Unknown
// expandos are not safe. Use the real mounted instance to avoid this
// problem if it blows something up.
Object.freeze(this);
};
ProxyConstructor.prototype = createMountWarningMembrane(
constructor.prototype
);
return ProxyConstructor;
} catch(x) {
// In IE8 define property will fail on non-DOM objects. If anything in
// the membrane creation fails, we'll bail out and just use the plain
// constructor without warnings.
return constructor;
}
};
}
/**
* `ReactCompositeComponent` maintains an auxiliary life cycle state in
* `this._compositeLifeCycleState` (which can be null).
*
* This is different from the life cycle state maintained by `ReactComponent` in
* `this._lifeCycleState`. The following diagram shows how the states overlap in
* time. There are times when the CompositeLifeCycle is null - at those times it
* is only meaningful to look at ComponentLifeCycle alone.
*
* Top Row: ReactComponent.ComponentLifeCycle
* Low Row: ReactComponent.CompositeLifeCycle
*
* +-------+------------------------------------------------------+--------+
* | UN | MOUNTED | UN |
* |MOUNTED| | MOUNTED|
* +-------+------------------------------------------------------+--------+
* | ^--------+ +------+ +------+ +------+ +--------^ |
* | | | | | | | | | | | |
* | 0--|MOUNTING|-0-|RECEIV|-0-|RECEIV|-0-|RECEIV|-0-| UN |--->0 |
* | | | |PROPS | | PROPS| | STATE| |MOUNTING| |
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | +--------+ +------+ +------+ +------+ +--------+ |
* | | | |
* +-------+------------------------------------------------------+--------+
*/
var CompositeLifeCycle = keyMirror({
/**
* Components in the process of being mounted respond to state changes
* differently.
*/
MOUNTING: null,
/**
* Components in the process of being unmounted are guarded against state
* changes.
*/
UNMOUNTING: null,
/**
* Components that are mounted and receiving new props respond to state
* changes differently.
*/
RECEIVING_PROPS: null,
/**
* Components that are mounted and receiving new state are guarded against
* additional state changes.
*/
RECEIVING_STATE: null
});
/**
* @lends {ReactCompositeComponent.prototype}
*/
var ReactCompositeComponentMixin = {
/**
* Base constructor for all composite component.
*
* @param {?object} initialProps
* @param {*} children
* @final
* @internal
*/
construct: function(initialProps, children) {
// Children can be either an array or more than one argument
ReactComponent.Mixin.construct.apply(this, arguments);
ReactOwner.Mixin.construct.apply(this, arguments);
this.state = null;
this._pendingState = null;
this.context = null;
this._currentContext = ReactContext.current;
this._pendingContext = null;
// The descriptor that was used to instantiate this component. Will be
// set by the instantiator instead of the constructor since this
// constructor is currently used by both instances and descriptors.
this._descriptor = null;
this._compositeLifeCycleState = null;
},
/**
* Components in the intermediate state now has cyclic references. To avoid
* breaking JSON serialization we expose a custom JSON format.
* @return {object} JSON compatible representation.
* @internal
* @final
*/
toJSON: function() {
return { type: this.type, props: this.props };
},
/**
* Checks whether or not this composite component is mounted.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function() {
return ReactComponent.Mixin.isMounted.call(this) &&
this._compositeLifeCycleState !== CompositeLifeCycle.MOUNTING;
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {number} mountDepth number of components in the owner hierarchy
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: ReactPerf.measure(
'ReactCompositeComponent',
'mountComponent',
function(rootID, transaction, mountDepth) {
ReactComponent.Mixin.mountComponent.call(
this,
rootID,
transaction,
mountDepth
);
this._compositeLifeCycleState = CompositeLifeCycle.MOUNTING;
this.context = this._processContext(this._currentContext);
this._defaultProps = this.getDefaultProps ? this.getDefaultProps() : null;
this.props = this._processProps(this.props);
if (this.__reactAutoBindMap) {
this._bindAutoBindMethods();
}
this.state = this.getInitialState ? this.getInitialState() : null;
("production" !== process.env.NODE_ENV ? invariant(
typeof this.state === 'object' && !Array.isArray(this.state),
'%s.getInitialState(): must return an object or null',
this.constructor.displayName || 'ReactCompositeComponent'
) : invariant(typeof this.state === 'object' && !Array.isArray(this.state)));
this._pendingState = null;
this._pendingForceUpdate = false;
if (this.componentWillMount) {
this.componentWillMount();
// When mounting, calls to `setState` by `componentWillMount` will set
// `this._pendingState` without triggering a re-render.
if (this._pendingState) {
this.state = this._pendingState;
this._pendingState = null;
}
}
this._renderedComponent = instantiateReactComponent(
this._renderValidatedComponent()
);
// Done with mounting, `setState` will now trigger UI changes.
this._compositeLifeCycleState = null;
var markup = this._renderedComponent.mountComponent(
rootID,
transaction,
mountDepth + 1
);
if (this.componentDidMount) {
transaction.getReactMountReady().enqueue(this, this.componentDidMount);
}
return markup;
}
),
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function() {
this._compositeLifeCycleState = CompositeLifeCycle.UNMOUNTING;
if (this.componentWillUnmount) {
this.componentWillUnmount();
}
this._compositeLifeCycleState = null;
this._defaultProps = null;
this._renderedComponent.unmountComponent();
this._renderedComponent = null;
ReactComponent.Mixin.unmountComponent.call(this);
// Some existing components rely on this.props even after they've been
// destroyed (in event handlers).
// TODO: this.props = null;
// TODO: this.state = null;
},
/**
* Sets a subset of the state. Always use this or `replaceState` to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* @param {object} partialState Next partial state to be merged with state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
setState: function(partialState, callback) {
("production" !== process.env.NODE_ENV ? invariant(
typeof partialState === 'object' || partialState == null,
'setState(...): takes an object of state variables to update.'
) : invariant(typeof partialState === 'object' || partialState == null));
if ("production" !== process.env.NODE_ENV) {
("production" !== process.env.NODE_ENV ? warning(
partialState != null,
'setState(...): You passed an undefined or null state object; ' +
'instead, use forceUpdate().'
) : null);
}
// Merge with `_pendingState` if it exists, otherwise with existing state.
this.replaceState(
merge(this._pendingState || this.state, partialState),
callback
);
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {object} completeState Next state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
replaceState: function(completeState, callback) {
validateLifeCycleOnReplaceState(this);
this._pendingState = completeState;
ReactUpdates.enqueueUpdate(this, callback);
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`, and asserts that they are valid.
*
* @param {object} context
* @return {?object}
* @private
*/
_processContext: function(context) {
var maskedContext = null;
var contextTypes = this.constructor.contextTypes;
if (contextTypes) {
maskedContext = {};
for (var contextName in contextTypes) {
maskedContext[contextName] = context[contextName];
}
if ("production" !== process.env.NODE_ENV) {
this._checkPropTypes(
contextTypes,
maskedContext,
ReactPropTypeLocations.context
);
}
}
return maskedContext;
},
/**
* @param {object} currentContext
* @return {object}
* @private
*/
_processChildContext: function(currentContext) {
var childContext = this.getChildContext && this.getChildContext();
var displayName = this.constructor.displayName || 'ReactCompositeComponent';
if (childContext) {
("production" !== process.env.NODE_ENV ? invariant(
typeof this.constructor.childContextTypes === 'object',
'%s.getChildContext(): childContextTypes must be defined in order to ' +
'use getChildContext().',
displayName
) : invariant(typeof this.constructor.childContextTypes === 'object'));
if ("production" !== process.env.NODE_ENV) {
this._checkPropTypes(
this.constructor.childContextTypes,
childContext,
ReactPropTypeLocations.childContext
);
}
for (var name in childContext) {
("production" !== process.env.NODE_ENV ? invariant(
name in this.constructor.childContextTypes,
'%s.getChildContext(): key "%s" is not defined in childContextTypes.',
displayName,
name
) : invariant(name in this.constructor.childContextTypes));
}
return merge(currentContext, childContext);
}
return currentContext;
},
/**
* Processes props by setting default values for unspecified props and
* asserting that the props are valid. Does not mutate its argument; returns
* a new props object with defaults merged in.
*
* @param {object} newProps
* @return {object}
* @private
*/
_processProps: function(newProps) {
var props = merge(newProps);
var defaultProps = this._defaultProps;
for (var propName in defaultProps) {
if (typeof props[propName] === 'undefined') {
props[propName] = defaultProps[propName];
}
}
if ("production" !== process.env.NODE_ENV) {
var propTypes = this.constructor.propTypes;
if (propTypes) {
this._checkPropTypes(propTypes, props, ReactPropTypeLocations.prop);
}
}
return props;
},
/**
* Assert that the props are valid
*
* @param {object} propTypes Map of prop name to a ReactPropType
* @param {object} props
* @param {string} location e.g. "prop", "context", "child context"
* @private
*/
_checkPropTypes: function(propTypes, props, location) {
var componentName = this.constructor.displayName;
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
propTypes[propName](props, propName, componentName, location);
}
}
},
performUpdateIfNecessary: function() {
var compositeLifeCycleState = this._compositeLifeCycleState;
// Do not trigger a state transition if we are in the middle of mounting or
// receiving props because both of those will already be doing this.
if (compositeLifeCycleState === CompositeLifeCycle.MOUNTING ||
compositeLifeCycleState === CompositeLifeCycle.RECEIVING_PROPS) {
return;
}
ReactComponent.Mixin.performUpdateIfNecessary.call(this);
},
/**
* If any of `_pendingProps`, `_pendingState`, or `_pendingForceUpdate` is
* set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
_performUpdateIfNecessary: function(transaction) {
if (this._pendingProps == null &&
this._pendingState == null &&
this._pendingContext == null &&
!this._pendingForceUpdate) {
return;
}
var nextFullContext = this._pendingContext || this._currentContext;
var nextContext = this._processContext(nextFullContext);
this._pendingContext = null;
var nextProps = this.props;
if (this._pendingProps != null) {
nextProps = this._processProps(this._pendingProps);
this._pendingProps = null;
this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_PROPS;
if (this.componentWillReceiveProps) {
this.componentWillReceiveProps(nextProps, nextContext);
}
}
this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_STATE;
// Unlike props, state, and context, we specifically don't want to set
// _pendingOwner to null here because it's possible for a component to have
// a null owner, so we instead make `this._owner === this._pendingOwner`
// mean that there's no owner change pending.
var nextOwner = this._pendingOwner;
var nextState = this._pendingState || this.state;
this._pendingState = null;
try {
if (this._pendingForceUpdate ||
!this.shouldComponentUpdate ||
this.shouldComponentUpdate(nextProps, nextState, nextContext)) {
this._pendingForceUpdate = false;
// Will set `this.props`, `this.state` and `this.context`.
this._performComponentUpdate(
nextProps,
nextOwner,
nextState,
nextFullContext,
nextContext,
transaction
);
} else {
// If it's determined that a component should not update, we still want
// to set props and state.
this.props = nextProps;
this._owner = nextOwner;
this.state = nextState;
this._currentContext = nextFullContext;
this.context = nextContext;
}
} finally {
this._compositeLifeCycleState = null;
}
},
/**
* Merges new props and state, notifies delegate methods of update and
* performs update.
*
* @param {object} nextProps Next object to set as properties.
* @param {?ReactComponent} nextOwner Next component to set as owner
* @param {?object} nextState Next object to set as state.
* @param {?object} nextFullContext Next object to set as _currentContext.
* @param {?object} nextContext Next object to set as context.
* @param {ReactReconcileTransaction} transaction
* @private
*/
_performComponentUpdate: function(
nextProps,
nextOwner,
nextState,
nextFullContext,
nextContext,
transaction
) {
var prevProps = this.props;
var prevOwner = this._owner;
var prevState = this.state;
var prevContext = this.context;
if (this.componentWillUpdate) {
this.componentWillUpdate(nextProps, nextState, nextContext);
}
this.props = nextProps;
this._owner = nextOwner;
this.state = nextState;
this._currentContext = nextFullContext;
this.context = nextContext;
this.updateComponent(
transaction,
prevProps,
prevOwner,
prevState,
prevContext
);
if (this.componentDidUpdate) {
transaction.getReactMountReady().enqueue(
this,
this.componentDidUpdate.bind(this, prevProps, prevState, prevContext)
);
}
},
receiveComponent: function(nextComponent, transaction) {
if (nextComponent === this._descriptor) {
// Since props and context are immutable after the component is
// mounted, we can do a cheap identity compare here to determine
// if this is a superfluous reconcile.
return;
}
// Update the descriptor that was last used by this component instance
this._descriptor = nextComponent;
this._pendingContext = nextComponent._currentContext;
ReactComponent.Mixin.receiveComponent.call(
this,
nextComponent,
transaction
);
},
/**
* Updates the component's currently mounted DOM representation.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @param {object} prevProps
* @param {?ReactComponent} prevOwner
* @param {?object} prevState
* @param {?object} prevContext
* @internal
* @overridable
*/
updateComponent: ReactPerf.measure(
'ReactCompositeComponent',
'updateComponent',
function(transaction, prevProps, prevOwner, prevState, prevContext) {
ReactComponent.Mixin.updateComponent.call(
this,
transaction,
prevProps,
prevOwner
);
var prevComponentInstance = this._renderedComponent;
var nextComponent = this._renderValidatedComponent();
if (shouldUpdateReactComponent(prevComponentInstance, nextComponent)) {
prevComponentInstance.receiveComponent(nextComponent, transaction);
} else {
// These two IDs are actually the same! But nothing should rely on that.
var thisID = this._rootNodeID;
var prevComponentID = prevComponentInstance._rootNodeID;
prevComponentInstance.unmountComponent();
this._renderedComponent = instantiateReactComponent(nextComponent);
var nextMarkup = this._renderedComponent.mountComponent(
thisID,
transaction,
this._mountDepth + 1
);
ReactComponent.BackendIDOperations.dangerouslyReplaceNodeWithMarkupByID(
prevComponentID,
nextMarkup
);
}
}
),
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldUpdateComponent`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
forceUpdate: function(callback) {
var compositeLifeCycleState = this._compositeLifeCycleState;
("production" !== process.env.NODE_ENV ? invariant(
this.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING,
'forceUpdate(...): Can only force an update on mounted or mounting ' +
'components.'
) : invariant(this.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING));
("production" !== process.env.NODE_ENV ? invariant(
compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE &&
compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING,
'forceUpdate(...): Cannot force an update while unmounting component ' +
'or during an existing state transition (such as within `render`).'
) : invariant(compositeLifeCycleState !== CompositeLifeCycle.RECEIVING_STATE &&
compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING));
this._pendingForceUpdate = true;
ReactUpdates.enqueueUpdate(this, callback);
},
/**
* @private
*/
_renderValidatedComponent: ReactPerf.measure(
'ReactCompositeComponent',
'_renderValidatedComponent',
function() {
var renderedComponent;
var previousContext = ReactContext.current;
ReactContext.current = this._processChildContext(this._currentContext);
ReactCurrentOwner.current = this;
try {
renderedComponent = this.render();
} finally {
ReactContext.current = previousContext;
ReactCurrentOwner.current = null;
}
("production" !== process.env.NODE_ENV ? invariant(
ReactComponent.isValidComponent(renderedComponent),
'%s.render(): A valid ReactComponent must be returned. You may have ' +
'returned null, undefined, an array, or some other invalid object.',
this.constructor.displayName || 'ReactCompositeComponent'
) : invariant(ReactComponent.isValidComponent(renderedComponent)));
return renderedComponent;
}
),
/**
* @private
*/
_bindAutoBindMethods: function() {
for (var autoBindKey in this.__reactAutoBindMap) {
if (!this.__reactAutoBindMap.hasOwnProperty(autoBindKey)) {
continue;
}
var method = this.__reactAutoBindMap[autoBindKey];
this[autoBindKey] = this._bindAutoBindMethod(ReactErrorUtils.guard(
method,
this.constructor.displayName + '.' + autoBindKey
));
}
},
/**
* Binds a method to the component.
*
* @param {function} method Method to be bound.
* @private
*/
_bindAutoBindMethod: function(method) {
var component = this;
var boundMethod = function() {
return method.apply(component, arguments);
};
if ("production" !== process.env.NODE_ENV) {
boundMethod.__reactBoundContext = component;
boundMethod.__reactBoundMethod = method;
boundMethod.__reactBoundArguments = null;
var componentName = component.constructor.displayName;
var _bind = boundMethod.bind;
boundMethod.bind = function(newThis ) {var args=Array.prototype.slice.call(arguments,1);
// User is trying to bind() an autobound method; we effectively will
// ignore the value of "this" that the user is trying to use, so
// let's warn.
if (newThis !== component && newThis !== null) {
monitorCodeUse('react_bind_warning', { component: componentName });
console.warn(
'bind(): React component methods may only be bound to the ' +
'component instance. See ' + componentName
);
} else if (!args.length) {
monitorCodeUse('react_bind_warning', { component: componentName });
console.warn(
'bind(): You are binding a component method to the component. ' +
'React does this for you automatically in a high-performance ' +
'way, so you can safely remove this call. See ' + componentName
);
return boundMethod;
}
var reboundMethod = _bind.apply(boundMethod, arguments);
reboundMethod.__reactBoundContext = component;
reboundMethod.__reactBoundMethod = method;
reboundMethod.__reactBoundArguments = args;
return reboundMethod;
};
}
return boundMethod;
}
};
var ReactCompositeComponentBase = function() {};
mixInto(ReactCompositeComponentBase, ReactComponent.Mixin);
mixInto(ReactCompositeComponentBase, ReactOwner.Mixin);
mixInto(ReactCompositeComponentBase, ReactPropTransferer.Mixin);
mixInto(ReactCompositeComponentBase, ReactCompositeComponentMixin);
/**
* Checks if a value is a valid component constructor.
*
* @param {*}
* @return {boolean}
* @public
*/
function isValidClass(componentClass) {
return componentClass instanceof Function &&
'componentConstructor' in componentClass &&
componentClass.componentConstructor instanceof Function;
}
/**
* Module for creating composite components.
*
* @class ReactCompositeComponent
* @extends ReactComponent
* @extends ReactOwner
* @extends ReactPropTransferer
*/
var ReactCompositeComponent = {
LifeCycle: CompositeLifeCycle,
Base: ReactCompositeComponentBase,
/**
* Creates a composite component class given a class specification.
*
* @param {object} spec Class specification (which must define `render`).
* @return {function} Component constructor function.
* @public
*/
createClass: function(spec) {
var Constructor = function() {};
Constructor.prototype = new ReactCompositeComponentBase();
Constructor.prototype.constructor = Constructor;
var DescriptorConstructor = Constructor;
var ConvenienceConstructor = function(props, children) {
var descriptor = new DescriptorConstructor();
descriptor.construct.apply(descriptor, arguments);
return descriptor;
};
ConvenienceConstructor.componentConstructor = Constructor;
Constructor.ConvenienceConstructor = ConvenienceConstructor;
ConvenienceConstructor.originalSpec = spec;
injectedMixins.forEach(
mixSpecIntoComponent.bind(null, ConvenienceConstructor)
);
mixSpecIntoComponent(ConvenienceConstructor, spec);
("production" !== process.env.NODE_ENV ? invariant(
Constructor.prototype.render,
'createClass(...): Class specification must implement a `render` method.'
) : invariant(Constructor.prototype.render));
if ("production" !== process.env.NODE_ENV) {
if (Constructor.prototype.componentShouldUpdate) {
monitorCodeUse(
'react_component_should_update_warning',
{ component: spec.displayName }
);
console.warn(
(spec.displayName || 'A component') + ' has a method called ' +
'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
'The name is phrased as a question because the function is ' +
'expected to return a value.'
);
}
}
// Expose the convience constructor on the prototype so that it can be
// easily accessed on descriptors. E.g. <Foo />.type === Foo.type and for
// static methods like <Foo />.type.staticMethod();
// This should not be named constructor since this may not be the function
// that created the descriptor, and it may not even be a constructor.
ConvenienceConstructor.type = Constructor;
Constructor.prototype.type = Constructor;
// Reduce time spent doing lookups by setting these on the prototype.
for (var methodName in ReactCompositeComponentInterface) {
if (!Constructor.prototype[methodName]) {
Constructor.prototype[methodName] = null;
}
}
if ("production" !== process.env.NODE_ENV) {
// In DEV the convenience constructor generates a proxy to another
// instance around it to warn about access to properties on the
// descriptor.
DescriptorConstructor = createDescriptorProxy(Constructor);
}
return ConvenienceConstructor;
},
isValidClass: isValidClass,
injection: {
injectMixin: function(mixin) {
injectedMixins.push(mixin);
}
}
};
module.exports = ReactCompositeComponent;
|
OIMO.Quat = function( s, x, y, z){
this.s=( s !== undefined ) ? s : 1;
this.x=x || 0;
this.y=y || 0;
this.z=z || 0;
};
OIMO.Quat.prototype = {
constructor: OIMO.Quat,
init:function(s,x,y,z){
this.s=( s !== undefined ) ? s : 1;
this.x=x || 0;
this.y=y || 0;
this.z=z || 0;
return this;
},
add:function(q1,q2){
this.s=q1.s+q2.s;
this.x=q1.x+q2.x;
this.y=q1.y+q2.y;
this.z=q1.z+q2.z;
return this;
},
addTime: function(v,t){
var os=this.s;
var ox=this.x;
var oy=this.y;
var oz=this.z;
t*=0.5;
var s=(-v.x*ox-v.y*oy-v.z*oz)*t;
var x=(v.x*os+v.y*oz-v.z*oy)*t;
var y=(-v.x*oz+v.y*os+v.z*ox)*t;
var z=(v.x*oy-v.y*ox+v.z*os)*t;
os+=s; ox+=x; oy+=y; oz+=z;
s=1/Math.sqrt(os*os+ox*ox+oy*oy+oz*oz);
this.s=os*s;
this.x=ox*s;
this.y=oy*s;
this.z=oz*s;
return this;
},
sub:function(q1,q2){
this.s=q1.s-q2.s;
this.x=q1.x-q2.x;
this.y=q1.y-q2.y;
this.z=q1.z-q2.z;
return this;
},
scale:function(q,s){
this.s=q.s*s;
this.x=q.x*s;
this.y=q.y*s;
this.z=q.z*s;
return this;
},
mul:function(q1,q2){
var s=q1.s*q2.s-q1.x*q2.x-q1.y*q2.y-q1.z*q2.z;
var x=q1.s*q2.x+q1.x*q2.s+q1.y*q2.z-q1.z*q2.y;
var y=q1.s*q2.y-q1.x*q2.z+q1.y*q2.s+q1.z*q2.x;
var z=q1.s*q2.z+q1.x*q2.y-q1.y*q2.x+q1.z*q2.s;
this.s=s;
this.x=x;
this.y=y;
this.z=z;
return this;
},
normalize:function(q){
var len=Math.sqrt(q.s*q.s+q.x*q.x+q.y*q.y+q.z*q.z);
if(len>0)len=1/len;
this.s=q.s*len;
this.x=q.x*len;
this.y=q.y*len;
this.z=q.z*len;
return this;
},
invert:function(q){
this.s=-q.s;
this.x=-q.x;
this.y=-q.y;
this.z=-q.z;
return this;
},
length:function(){
return Math.sqrt(this.s*this.s+this.x*this.x+this.y*this.y+this.z*this.z);
},
copy:function(q){
this.s=q.s;
this.x=q.x;
this.y=q.y;
this.z=q.z;
return this;
},
clone:function(q){
return new OIMO.Quat(this.s,this.x,this.y,this.z);
},
toString:function(){
return"Quat["+this.s.toFixed(4)+", ("+this.x.toFixed(4)+", "+this.y.toFixed(4)+", "+this.z.toFixed(4)+")]";
}
}
// for three easy export
OIMO.Quaternion = function ( x, y, z, w ) {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
this.w = ( w !== undefined ) ? w : 1;
};
OIMO.Quaternion.prototype = {
constructor: OIMO.Quaternion,
setFromRotationMatrix: function ( m ) {
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
var te = m.elements,
m11 = te[ 0 ], m12 = te[ 1 ], m13 = te[ 2 ],
m21 = te[ 3 ], m22 = te[ 4 ], m23 = te[ 5 ],
m31 = te[ 6 ], m32 = te[ 7 ], m33 = te[ 8 ],
trace = m11 + m22 + m33,
s;
if ( trace > 0 ) {
s = 0.5 / Math.sqrt( trace + 1.0 );
this.w = 0.25 / s;
this.x = ( m32 - m23 ) * s;
this.y = ( m13 - m31 ) * s;
this.z = ( m21 - m12 ) * s;
} else if ( m11 > m22 && m11 > m33 ) {
s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
this.w = ( m32 - m23 ) / s;
this.x = 0.25 * s;
this.y = ( m12 + m21 ) / s;
this.z = ( m13 + m31 ) / s;
} else if ( m22 > m33 ) {
s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
this.w = ( m13 - m31 ) / s;
this.x = ( m12 + m21 ) / s;
this.y = 0.25 * s;
this.z = ( m23 + m32 ) / s;
} else {
s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
this.w = ( m21 - m12 ) / s;
this.x = ( m13 + m31 ) / s;
this.y = ( m23 + m32 ) / s;
this.z = 0.25 * s;
}
//this.onChangeCallback();
return this;
}
} |
var express = require('express');
var config = require('./config/config');
var app = express();
require('./config/express')(app, config, function () {
require('./config/routes')(app);
app.listen(config.port);
console.log("> Application Running #", config.port);
}); |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {AnyNativeEvent} from '../events/PluginModuleType';
import type {Container, SuspenseInstance} from '../client/ReactDOMHostConfig';
import type {DOMEventName} from '../events/DOMEventNames';
import type {EventSystemFlags} from './EventSystemFlags';
import type {FiberRoot} from 'react-reconciler/src/ReactInternalTypes';
import type {EventPriority} from 'react-reconciler/src/ReactEventPriorities';
import {
enableSelectiveHydration,
enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay,
} from 'shared/ReactFeatureFlags';
import {
unstable_scheduleCallback as scheduleCallback,
unstable_NormalPriority as NormalPriority,
} from 'scheduler';
import {
getNearestMountedFiber,
getContainerFromFiber,
getSuspenseInstanceFromFiber,
} from 'react-reconciler/src/ReactFiberTreeReflection';
import {
findInstanceBlockingEvent,
return_targetInst,
} from './ReactDOMEventListener';
import {setReplayingEvent, resetReplayingEvent} from './CurrentReplayingEvent';
import {dispatchEventForPluginEventSystem} from './DOMPluginEventSystem';
import {
getInstanceFromNode,
getClosestInstanceFromNode,
} from '../client/ReactDOMComponentTree';
import {HostRoot, SuspenseComponent} from 'react-reconciler/src/ReactWorkTags';
import {isHigherEventPriority} from 'react-reconciler/src/ReactEventPriorities';
let _attemptSynchronousHydration: (fiber: Object) => void;
export function setAttemptSynchronousHydration(fn: (fiber: Object) => void) {
_attemptSynchronousHydration = fn;
}
export function attemptSynchronousHydration(fiber: Object) {
_attemptSynchronousHydration(fiber);
}
let attemptDiscreteHydration: (fiber: Object) => void;
export function setAttemptDiscreteHydration(fn: (fiber: Object) => void) {
attemptDiscreteHydration = fn;
}
let attemptContinuousHydration: (fiber: Object) => void;
export function setAttemptContinuousHydration(fn: (fiber: Object) => void) {
attemptContinuousHydration = fn;
}
let attemptHydrationAtCurrentPriority: (fiber: Object) => void;
export function setAttemptHydrationAtCurrentPriority(
fn: (fiber: Object) => void,
) {
attemptHydrationAtCurrentPriority = fn;
}
let getCurrentUpdatePriority: () => EventPriority;
export function setGetCurrentUpdatePriority(fn: () => EventPriority) {
getCurrentUpdatePriority = fn;
}
let attemptHydrationAtPriority: <T>(priority: EventPriority, fn: () => T) => T;
export function setAttemptHydrationAtPriority(
fn: <T>(priority: EventPriority, fn: () => T) => T,
) {
attemptHydrationAtPriority = fn;
}
// TODO: Upgrade this definition once we're on a newer version of Flow that
// has this definition built-in.
type PointerEvent = Event & {
pointerId: number,
relatedTarget: EventTarget | null,
...
};
type QueuedReplayableEvent = {|
blockedOn: null | Container | SuspenseInstance,
domEventName: DOMEventName,
eventSystemFlags: EventSystemFlags,
nativeEvent: AnyNativeEvent,
targetContainers: Array<EventTarget>,
|};
let hasScheduledReplayAttempt = false;
// The queue of discrete events to be replayed.
const queuedDiscreteEvents: Array<QueuedReplayableEvent> = [];
// Indicates if any continuous event targets are non-null for early bailout.
const hasAnyQueuedContinuousEvents: boolean = false;
// The last of each continuous event type. We only need to replay the last one
// if the last target was dehydrated.
let queuedFocus: null | QueuedReplayableEvent = null;
let queuedDrag: null | QueuedReplayableEvent = null;
let queuedMouse: null | QueuedReplayableEvent = null;
// For pointer events there can be one latest event per pointerId.
const queuedPointers: Map<number, QueuedReplayableEvent> = new Map();
const queuedPointerCaptures: Map<number, QueuedReplayableEvent> = new Map();
// We could consider replaying selectionchange and touchmoves too.
type QueuedHydrationTarget = {|
blockedOn: null | Container | SuspenseInstance,
target: Node,
priority: EventPriority,
|};
const queuedExplicitHydrationTargets: Array<QueuedHydrationTarget> = [];
export function hasQueuedDiscreteEvents(): boolean {
return queuedDiscreteEvents.length > 0;
}
export function hasQueuedContinuousEvents(): boolean {
return hasAnyQueuedContinuousEvents;
}
const discreteReplayableEvents: Array<DOMEventName> = [
'mousedown',
'mouseup',
'touchcancel',
'touchend',
'touchstart',
'auxclick',
'dblclick',
'pointercancel',
'pointerdown',
'pointerup',
'dragend',
'dragstart',
'drop',
'compositionend',
'compositionstart',
'keydown',
'keypress',
'keyup',
'input',
'textInput', // Intentionally camelCase
'copy',
'cut',
'paste',
'click',
'change',
'contextmenu',
'reset',
'submit',
];
export function isDiscreteEventThatRequiresHydration(
eventType: DOMEventName,
): boolean {
return discreteReplayableEvents.indexOf(eventType) > -1;
}
function createQueuedReplayableEvent(
blockedOn: null | Container | SuspenseInstance,
domEventName: DOMEventName,
eventSystemFlags: EventSystemFlags,
targetContainer: EventTarget,
nativeEvent: AnyNativeEvent,
): QueuedReplayableEvent {
return {
blockedOn,
domEventName,
eventSystemFlags,
nativeEvent,
targetContainers: [targetContainer],
};
}
export function queueDiscreteEvent(
blockedOn: null | Container | SuspenseInstance,
domEventName: DOMEventName,
eventSystemFlags: EventSystemFlags,
targetContainer: EventTarget,
nativeEvent: AnyNativeEvent,
): void {
if (enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay) {
return;
}
const queuedEvent = createQueuedReplayableEvent(
blockedOn,
domEventName,
eventSystemFlags,
targetContainer,
nativeEvent,
);
queuedDiscreteEvents.push(queuedEvent);
if (enableSelectiveHydration) {
if (queuedDiscreteEvents.length === 1) {
// If this was the first discrete event, we might be able to
// synchronously unblock it so that preventDefault still works.
while (queuedEvent.blockedOn !== null) {
const fiber = getInstanceFromNode(queuedEvent.blockedOn);
if (fiber === null) {
break;
}
attemptSynchronousHydration(fiber);
if (queuedEvent.blockedOn === null) {
// We got unblocked by hydration. Let's try again.
replayUnblockedEvents();
// If we're reblocked, on an inner boundary, we might need
// to attempt hydrating that one.
continue;
} else {
// We're still blocked from hydration, we have to give up
// and replay later.
break;
}
}
}
}
}
// Resets the replaying for this type of continuous event to no event.
export function clearIfContinuousEvent(
domEventName: DOMEventName,
nativeEvent: AnyNativeEvent,
): void {
switch (domEventName) {
case 'focusin':
case 'focusout':
queuedFocus = null;
break;
case 'dragenter':
case 'dragleave':
queuedDrag = null;
break;
case 'mouseover':
case 'mouseout':
queuedMouse = null;
break;
case 'pointerover':
case 'pointerout': {
const pointerId = ((nativeEvent: any): PointerEvent).pointerId;
queuedPointers.delete(pointerId);
break;
}
case 'gotpointercapture':
case 'lostpointercapture': {
const pointerId = ((nativeEvent: any): PointerEvent).pointerId;
queuedPointerCaptures.delete(pointerId);
break;
}
}
}
function accumulateOrCreateContinuousQueuedReplayableEvent(
existingQueuedEvent: null | QueuedReplayableEvent,
blockedOn: null | Container | SuspenseInstance,
domEventName: DOMEventName,
eventSystemFlags: EventSystemFlags,
targetContainer: EventTarget,
nativeEvent: AnyNativeEvent,
): QueuedReplayableEvent {
if (
existingQueuedEvent === null ||
existingQueuedEvent.nativeEvent !== nativeEvent
) {
const queuedEvent = createQueuedReplayableEvent(
blockedOn,
domEventName,
eventSystemFlags,
targetContainer,
nativeEvent,
);
if (blockedOn !== null) {
const fiber = getInstanceFromNode(blockedOn);
if (fiber !== null) {
// Attempt to increase the priority of this target.
attemptContinuousHydration(fiber);
}
}
return queuedEvent;
}
// If we have already queued this exact event, then it's because
// the different event systems have different DOM event listeners.
// We can accumulate the flags, and the targetContainers, and
// store a single event to be replayed.
existingQueuedEvent.eventSystemFlags |= eventSystemFlags;
const targetContainers = existingQueuedEvent.targetContainers;
if (
targetContainer !== null &&
targetContainers.indexOf(targetContainer) === -1
) {
targetContainers.push(targetContainer);
}
return existingQueuedEvent;
}
export function queueIfContinuousEvent(
blockedOn: null | Container | SuspenseInstance,
domEventName: DOMEventName,
eventSystemFlags: EventSystemFlags,
targetContainer: EventTarget,
nativeEvent: AnyNativeEvent,
): boolean {
// These set relatedTarget to null because the replayed event will be treated as if we
// moved from outside the window (no target) onto the target once it hydrates.
// Instead of mutating we could clone the event.
switch (domEventName) {
case 'focusin': {
const focusEvent = ((nativeEvent: any): FocusEvent);
queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(
queuedFocus,
blockedOn,
domEventName,
eventSystemFlags,
targetContainer,
focusEvent,
);
return true;
}
case 'dragenter': {
const dragEvent = ((nativeEvent: any): DragEvent);
queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(
queuedDrag,
blockedOn,
domEventName,
eventSystemFlags,
targetContainer,
dragEvent,
);
return true;
}
case 'mouseover': {
const mouseEvent = ((nativeEvent: any): MouseEvent);
queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(
queuedMouse,
blockedOn,
domEventName,
eventSystemFlags,
targetContainer,
mouseEvent,
);
return true;
}
case 'pointerover': {
const pointerEvent = ((nativeEvent: any): PointerEvent);
const pointerId = pointerEvent.pointerId;
queuedPointers.set(
pointerId,
accumulateOrCreateContinuousQueuedReplayableEvent(
queuedPointers.get(pointerId) || null,
blockedOn,
domEventName,
eventSystemFlags,
targetContainer,
pointerEvent,
),
);
return true;
}
case 'gotpointercapture': {
const pointerEvent = ((nativeEvent: any): PointerEvent);
const pointerId = pointerEvent.pointerId;
queuedPointerCaptures.set(
pointerId,
accumulateOrCreateContinuousQueuedReplayableEvent(
queuedPointerCaptures.get(pointerId) || null,
blockedOn,
domEventName,
eventSystemFlags,
targetContainer,
pointerEvent,
),
);
return true;
}
}
return false;
}
// Check if this target is unblocked. Returns true if it's unblocked.
function attemptExplicitHydrationTarget(
queuedTarget: QueuedHydrationTarget,
): void {
// TODO: This function shares a lot of logic with findInstanceBlockingEvent.
// Try to unify them. It's a bit tricky since it would require two return
// values.
const targetInst = getClosestInstanceFromNode(queuedTarget.target);
if (targetInst !== null) {
const nearestMounted = getNearestMountedFiber(targetInst);
if (nearestMounted !== null) {
const tag = nearestMounted.tag;
if (tag === SuspenseComponent) {
const instance = getSuspenseInstanceFromFiber(nearestMounted);
if (instance !== null) {
// We're blocked on hydrating this boundary.
// Increase its priority.
queuedTarget.blockedOn = instance;
attemptHydrationAtPriority(queuedTarget.priority, () => {
attemptHydrationAtCurrentPriority(nearestMounted);
});
return;
}
} else if (tag === HostRoot) {
const root: FiberRoot = nearestMounted.stateNode;
if (root.isDehydrated) {
queuedTarget.blockedOn = getContainerFromFiber(nearestMounted);
// We don't currently have a way to increase the priority of
// a root other than sync.
return;
}
}
}
}
queuedTarget.blockedOn = null;
}
export function queueExplicitHydrationTarget(target: Node): void {
if (enableSelectiveHydration) {
// TODO: This will read the priority if it's dispatched by the React
// event system but not native events. Should read window.event.type, like
// we do for updates (getCurrentEventPriority).
const updatePriority = getCurrentUpdatePriority();
const queuedTarget: QueuedHydrationTarget = {
blockedOn: null,
target: target,
priority: updatePriority,
};
let i = 0;
for (; i < queuedExplicitHydrationTargets.length; i++) {
// Stop once we hit the first target with lower priority than
if (
!isHigherEventPriority(
updatePriority,
queuedExplicitHydrationTargets[i].priority,
)
) {
break;
}
}
queuedExplicitHydrationTargets.splice(i, 0, queuedTarget);
if (i === 0) {
attemptExplicitHydrationTarget(queuedTarget);
}
}
}
function attemptReplayContinuousQueuedEvent(
queuedEvent: QueuedReplayableEvent,
): boolean {
if (queuedEvent.blockedOn !== null) {
return false;
}
const targetContainers = queuedEvent.targetContainers;
while (targetContainers.length > 0) {
const targetContainer = targetContainers[0];
const nextBlockedOn = findInstanceBlockingEvent(
queuedEvent.domEventName,
queuedEvent.eventSystemFlags,
targetContainer,
queuedEvent.nativeEvent,
);
if (nextBlockedOn === null) {
if (enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay) {
const nativeEvent = queuedEvent.nativeEvent;
const nativeEventClone = new nativeEvent.constructor(
nativeEvent.type,
(nativeEvent: any),
);
setReplayingEvent(nativeEventClone);
nativeEvent.target.dispatchEvent(nativeEventClone);
resetReplayingEvent();
} else {
setReplayingEvent(queuedEvent.nativeEvent);
dispatchEventForPluginEventSystem(
queuedEvent.domEventName,
queuedEvent.eventSystemFlags,
queuedEvent.nativeEvent,
return_targetInst,
targetContainer,
);
resetReplayingEvent();
}
} else {
// We're still blocked. Try again later.
const fiber = getInstanceFromNode(nextBlockedOn);
if (fiber !== null) {
attemptContinuousHydration(fiber);
}
queuedEvent.blockedOn = nextBlockedOn;
return false;
}
// This target container was successfully dispatched. Try the next.
targetContainers.shift();
}
return true;
}
function attemptReplayContinuousQueuedEventInMap(
queuedEvent: QueuedReplayableEvent,
key: number,
map: Map<number, QueuedReplayableEvent>,
): void {
if (attemptReplayContinuousQueuedEvent(queuedEvent)) {
map.delete(key);
}
}
function replayUnblockedEvents() {
hasScheduledReplayAttempt = false;
if (!enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay) {
// First replay discrete events.
while (queuedDiscreteEvents.length > 0) {
const nextDiscreteEvent = queuedDiscreteEvents[0];
if (nextDiscreteEvent.blockedOn !== null) {
// We're still blocked.
// Increase the priority of this boundary to unblock
// the next discrete event.
const fiber = getInstanceFromNode(nextDiscreteEvent.blockedOn);
if (fiber !== null) {
attemptDiscreteHydration(fiber);
}
break;
}
const targetContainers = nextDiscreteEvent.targetContainers;
while (targetContainers.length > 0) {
const targetContainer = targetContainers[0];
const nextBlockedOn = findInstanceBlockingEvent(
nextDiscreteEvent.domEventName,
nextDiscreteEvent.eventSystemFlags,
targetContainer,
nextDiscreteEvent.nativeEvent,
);
if (nextBlockedOn === null) {
// This whole function is in !enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay,
// so we don't need the new replay behavior code branch.
setReplayingEvent(nextDiscreteEvent.nativeEvent);
dispatchEventForPluginEventSystem(
nextDiscreteEvent.domEventName,
nextDiscreteEvent.eventSystemFlags,
nextDiscreteEvent.nativeEvent,
return_targetInst,
targetContainer,
);
resetReplayingEvent();
} else {
// We're still blocked. Try again later.
nextDiscreteEvent.blockedOn = nextBlockedOn;
break;
}
// This target container was successfully dispatched. Try the next.
targetContainers.shift();
}
if (nextDiscreteEvent.blockedOn === null) {
// We've successfully replayed the first event. Let's try the next one.
queuedDiscreteEvents.shift();
}
}
}
// Next replay any continuous events.
if (queuedFocus !== null && attemptReplayContinuousQueuedEvent(queuedFocus)) {
queuedFocus = null;
}
if (queuedDrag !== null && attemptReplayContinuousQueuedEvent(queuedDrag)) {
queuedDrag = null;
}
if (queuedMouse !== null && attemptReplayContinuousQueuedEvent(queuedMouse)) {
queuedMouse = null;
}
queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);
queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);
}
function scheduleCallbackIfUnblocked(
queuedEvent: QueuedReplayableEvent,
unblocked: Container | SuspenseInstance,
) {
if (queuedEvent.blockedOn === unblocked) {
queuedEvent.blockedOn = null;
if (!hasScheduledReplayAttempt) {
hasScheduledReplayAttempt = true;
// Schedule a callback to attempt replaying as many events as are
// now unblocked. This first might not actually be unblocked yet.
// We could check it early to avoid scheduling an unnecessary callback.
scheduleCallback(NormalPriority, replayUnblockedEvents);
}
}
}
export function retryIfBlockedOn(
unblocked: Container | SuspenseInstance,
): void {
// Mark anything that was blocked on this as no longer blocked
// and eligible for a replay.
if (queuedDiscreteEvents.length > 0) {
scheduleCallbackIfUnblocked(queuedDiscreteEvents[0], unblocked);
// This is a exponential search for each boundary that commits. I think it's
// worth it because we expect very few discrete events to queue up and once
// we are actually fully unblocked it will be fast to replay them.
for (let i = 1; i < queuedDiscreteEvents.length; i++) {
const queuedEvent = queuedDiscreteEvents[i];
if (queuedEvent.blockedOn === unblocked) {
queuedEvent.blockedOn = null;
}
}
}
if (queuedFocus !== null) {
scheduleCallbackIfUnblocked(queuedFocus, unblocked);
}
if (queuedDrag !== null) {
scheduleCallbackIfUnblocked(queuedDrag, unblocked);
}
if (queuedMouse !== null) {
scheduleCallbackIfUnblocked(queuedMouse, unblocked);
}
const unblock = queuedEvent =>
scheduleCallbackIfUnblocked(queuedEvent, unblocked);
queuedPointers.forEach(unblock);
queuedPointerCaptures.forEach(unblock);
for (let i = 0; i < queuedExplicitHydrationTargets.length; i++) {
const queuedTarget = queuedExplicitHydrationTargets[i];
if (queuedTarget.blockedOn === unblocked) {
queuedTarget.blockedOn = null;
}
}
while (queuedExplicitHydrationTargets.length > 0) {
const nextExplicitTarget = queuedExplicitHydrationTargets[0];
if (nextExplicitTarget.blockedOn !== null) {
// We're still blocked.
break;
} else {
attemptExplicitHydrationTarget(nextExplicitTarget);
if (nextExplicitTarget.blockedOn === null) {
// We're unblocked.
queuedExplicitHydrationTargets.shift();
}
}
}
}
|
#!/usr/bin/env node
// Imports
const {readFileSync, writeFileSync} = require('fs');
const {join, resolve} = require('path');
// Constants
const CI_PREVIEW = process.env.CI_PREVIEW;
const PR_NUMBER = process.env.CIRCLE_PR_NUMBER || process.env.CIRCLE_PULL_REQUEST_NUMBER;
const SHORT_SHA = process.env.SHORT_GIT_HASH;
const SRC_DIR = resolve(__dirname, '../src');
const DIST_DIR = resolve(__dirname, '../dist/ngrx.io', CI_PREVIEW ? `pr${PR_NUMBER}-${SHORT_SHA}` : '');
// Run
_main(process.argv.slice(2));
// Functions - Definitions
function _main() {
const srcIndexPath = join(DIST_DIR, 'index.html');
const src404BodyPath = join(SRC_DIR, '404-body.html');
const dst404PagePath = join(DIST_DIR, '404.html');
const srcIndexContent = readFileSync(srcIndexPath, 'utf8');
const src404BodyContent = readFileSync(src404BodyPath, 'utf8');
const dst404PageContent = srcIndexContent.replace(/<body>[\s\S]+<\/body>/, src404BodyContent);
if (dst404PageContent === srcIndexContent) {
throw new Error(
'Failed to generate \'404.html\'. ' +
'The content of \'index.html\' does not match the expected pattern.');
}
writeFileSync(dst404PagePath, dst404PageContent);
}
|
import Node from './node';
export default function Ternary(yes, no) {
this.yes = yes;
this.no = no;
}
Ternary.prototype[Node.isExpressionOrIdentifierSymbol] = true;
Ternary.prototype.get_value = function () { return this; };
|
/**
* Owl2 carousel2
* @version 2.0.0
* @author Bartosz Wojciechowski
* @license The MIT License (MIT)
* @todo Lazy Load Icon
* @todo prevent animationend bubling
* @todo itemsScaleUp
* @todo Test Zepto
* @todo stagePadding calculate wrong active classes
*/
;(function($, window, document, undefined) {
var drag, state, e;
/**
* Template for status information about drag and touch events.
* @private
*/
drag = {
start: 0,
startX: 0,
startY: 0,
current: 0,
currentX: 0,
currentY: 0,
offsetX: 0,
offsetY: 0,
distance: null,
startTime: 0,
endTime: 0,
updatedX: 0,
targetEl: null
};
/**
* Template for some status informations.
* @private
*/
state = {
isTouch: false,
isScrolling: false,
isSwiping: false,
direction: false,
inMotion: false
};
/**
* Event functions references.
* @private
*/
e = {
_onDragStart: null,
_onDragMove: null,
_onDragEnd: null,
_transitionEnd: null,
_resizer: null,
_responsiveCall: null,
_goToLoop: null,
_checkVisibile: null
};
/**
* Creates a carousel2.
* @class The Owl2 Carousel.
* @public
* @param {HTMLElement|jQuery} element - The element to create the carousel2 for.
* @param {Object} [options] - The options
*/
function Owl2(element, options) {
/**
* Current settings for the carousel2.
* @public
*/
this.settings = null;
/**
* Current options set by the caller including defaults.
* @public
*/
this.options = $.extend({}, Owl2.Defaults, options);
/**
* Plugin element.
* @public
*/
this.$element = $(element);
/**
* Caches informations about drag and touch events.
*/
this.drag = $.extend({}, drag);
/**
* Caches some status informations.
* @protected
*/
this.state = $.extend({}, state);
/**
* @protected
* @todo Must be documented
*/
this.e = $.extend({}, e);
/**
* References to the running plugins of this carousel2.
* @protected
*/
this._plugins = {};
/**
* Currently suppressed events to prevent them from beeing retriggered.
* @protected
*/
this._supress = {};
/**
* Absolute current position.
* @protected
*/
this._current = null;
/**
* Animation speed in milliseconds.
* @protected
*/
this._speed = null;
/**
* Coordinates of all items in pixel.
* @todo The name of this member is missleading.
* @protected
*/
this._coordinates = [];
/**
* Current breakpoint.
* @todo Real media queries would be nice.
* @protected
*/
this._breakpoint = null;
/**
* Current width of the plugin element.
*/
this._width = null;
/**
* All real items.
* @protected
*/
this._items = [];
/**
* All cloned items.
* @protected
*/
this._clones = [];
/**
* Merge values of all items.
* @todo Maybe this could be part of a plugin.
* @protected
*/
this._mergers = [];
/**
* Invalidated parts within the update process.
* @protected
*/
this._invalidated = {};
/**
* Ordered list of workers for the update process.
* @protected
*/
this._pipe = [];
$.each(Owl2.Plugins, $.proxy(function(key, plugin) {
this._plugins[key[0].toLowerCase() + key.slice(1)]
= new plugin(this);
}, this));
$.each(Owl2.Pipe, $.proxy(function(priority, worker) {
this._pipe.push({
'filter': worker.filter,
'run': $.proxy(worker.run, this)
});
}, this));
this.setup();
this.initialize();
}
/**
* Default options for the carousel2.
* @public
*/
Owl2.Defaults = {
items: 3,
loop: false,
center: false,
mouseDrag: true,
touchDrag: true,
pullDrag: true,
freeDrag: false,
margin: 0,
stagePadding: 0,
merge: false,
mergeFit: true,
autoWidth: false,
startPosition: 0,
rtl: false,
smartSpeed: 250,
fluidSpeed: false,
dragEndSpeed: false,
responsive: {},
responsiveRefreshRate: 200,
responsiveBaseElement: window,
responsiveClass: false,
fallbackEasing: 'swing',
info: false,
nestedItemSelector: false,
itemElement: 'div',
stageElement: 'div',
// Classes and Names
themeClass: 'owl2-theme',
baseClass: 'owl2-carousel',
itemClass: 'owl2-item',
centerClass: 'center',
activeClass: 'active'
};
/**
* Enumeration for width.
* @public
* @readonly
* @enum {String}
*/
Owl2.Width = {
Default: 'default',
Inner: 'inner',
Outer: 'outer'
};
/**
* Contains all registered plugins.
* @public
*/
Owl2.Plugins = {};
/**
* Update pipe.
*/
Owl2.Pipe = [ {
filter: [ 'width', 'items', 'settings' ],
run: function(cache) {
cache.current = this._items && this._items[this.relative(this._current)];
}
}, {
filter: [ 'items', 'settings' ],
run: function() {
var cached = this._clones,
clones = this.$stage.children('.cloned');
if (clones.length !== cached.length || (!this.settings.loop && cached.length > 0)) {
this.$stage.children('.cloned').remove();
this._clones = [];
}
}
}, {
filter: [ 'items', 'settings' ],
run: function() {
var i, n,
clones = this._clones,
items = this._items,
delta = this.settings.loop ? clones.length - Math.max(this.settings.items * 2, 4) : 0;
if(items.length == 1)
return;
for (i = 0, n = Math.abs(delta / 2); i < n; i++) {
if (delta > 0) {
this.$stage.children().eq(items.length + clones.length - 1).remove();
clones.pop();
this.$stage.children().eq(0).remove();
clones.pop();
} else {
clones.push(clones.length / 2);
this.$stage.append(items[clones[clones.length - 1]].clone().addClass('cloned'));
clones.push(items.length - 1 - (clones.length - 1) / 2);
this.$stage.prepend(items[clones[clones.length - 1]].clone().addClass('cloned'));
}
}
}
}, {
filter: [ 'width', 'items', 'settings' ],
run: function() {
var rtl = (this.settings.rtl ? 1 : -1),
width = (this.width() / this.settings.items).toFixed(3),
coordinate = 0, merge, i, n;
this._coordinates = [];
for (i = 0, n = this._clones.length + this._items.length; i < n; i++) {
merge = this._mergers[this.relative(i)];
merge = (this.settings.mergeFit && Math.min(merge, this.settings.items)) || merge;
coordinate += (this.settings.autoWidth ? this._items[this.relative(i)].width() + this.settings.margin : width * merge) * rtl;
this._coordinates.push(coordinate);
}
}
}, {
filter: [ 'width', 'items', 'settings' ],
run: function() {
var i, n, width = (this.width() / this.settings.items).toFixed(3), css = {
'width': Math.abs(this._coordinates[this._coordinates.length - 1]) + this.settings.stagePadding * 2,
'padding-left': this.settings.stagePadding || '',
'padding-right': this.settings.stagePadding || ''
};
this.$stage.css(css);
css = { 'width': this.settings.autoWidth ? 'auto' : width - this.settings.margin };
css[this.settings.rtl ? 'margin-left' : 'margin-right'] = this.settings.margin;
if (!this.settings.autoWidth && $.grep(this._mergers, function(v) { return v > 1 }).length > 0) {
for (i = 0, n = this._coordinates.length; i < n; i++) {
css.width = Math.abs(this._coordinates[i]) - Math.abs(this._coordinates[i - 1] || 0) - this.settings.margin;
this.$stage.children().eq(i).css(css);
}
} else {
this.$stage.children().css(css);
}
}
}, {
filter: [ 'width', 'items', 'settings' ],
run: function(cache) {
cache.current && this.reset(this.$stage.children().index(cache.current));
}
}, {
filter: [ 'position' ],
run: function() {
this.animate(this.coordinates(this._current));
}
}, {
filter: [ 'width', 'position', 'items', 'settings' ],
run: function() {
var rtl = this.settings.rtl ? 1 : -1,
padding = this.settings.stagePadding * 2,
begin = this.coordinates(this.current()) + padding,
end = begin + this.width() * rtl,
inner, outer, matches = [], i, n;
for (i = 0, n = this._coordinates.length; i < n; i++) {
inner = this._coordinates[i - 1] || 0;
outer = Math.abs(this._coordinates[i]) + padding * rtl;
if ((this.op(inner, '<=', begin) && (this.op(inner, '>', end)))
|| (this.op(outer, '<', begin) && this.op(outer, '>', end))) {
matches.push(i);
}
}
this.$stage.children('.' + this.settings.activeClass).removeClass(this.settings.activeClass);
this.$stage.children(':eq(' + matches.join('), :eq(') + ')').addClass(this.settings.activeClass);
if (this.settings.center) {
this.$stage.children('.' + this.settings.centerClass).removeClass(this.settings.centerClass);
this.$stage.children().eq(this.current()).addClass(this.settings.centerClass);
}
}
} ];
/**
* Initializes the carousel2.
* @protected
*/
Owl2.prototype.initialize = function() {
this.trigger('initialize');
this.$element
.addClass(this.settings.baseClass)
.addClass(this.settings.themeClass)
.toggleClass('owl2-rtl', this.settings.rtl);
// check support
this.browserSupport();
if (this.settings.autoWidth && this.state.imagesLoaded !== true) {
var imgs, nestedSelector, width;
imgs = this.$element.find('img');
nestedSelector = this.settings.nestedItemSelector ? '.' + this.settings.nestedItemSelector : undefined;
width = this.$element.children(nestedSelector).width();
if (imgs.length && width <= 0) {
this.preloadAutoWidthImages(imgs);
return false;
}
}
this.$element.addClass('owl2-loading');
// create stage
this.$stage = $('<' + this.settings.stageElement + ' class="owl2-stage"/>')
.wrap('<div class="owl2-stage-outer">');
// append stage
this.$element.append(this.$stage.parent());
// append content
this.replace(this.$element.children().not(this.$stage.parent()));
// set view width
this._width = this.$element.width();
// update view
this.refresh();
this.$element.removeClass('owl2-loading').addClass('owl2-loaded');
// attach generic events
this.eventsCall();
// attach generic events
this.internalEvents();
// attach custom control events
this.addTriggerableEvents();
this.trigger('initialized');
};
/**
* Setups the current settings.
* @todo Remove responsive classes. Why should adaptive designs be brought into IE8?
* @todo Support for media queries by using `matchMedia` would be nice.
* @public
*/
Owl2.prototype.setup = function() {
var viewport = this.viewport(),
overwrites = this.options.responsive,
match = -1,
settings = null;
if (!overwrites) {
settings = $.extend({}, this.options);
} else {
$.each(overwrites, function(breakpoint) {
if (breakpoint <= viewport && breakpoint > match) {
match = Number(breakpoint);
}
});
settings = $.extend({}, this.options, overwrites[match]);
delete settings.responsive;
// responsive class
if (settings.responsiveClass) {
this.$element.attr('class', function(i, c) {
return c.replace(/\b owl2-responsive-\S+/g, '');
}).addClass('owl2-responsive-' + match);
}
}
if (this.settings === null || this._breakpoint !== match) {
this.trigger('change', { property: { name: 'settings', value: settings } });
this._breakpoint = match;
this.settings = settings;
this.invalidate('settings');
this.trigger('changed', { property: { name: 'settings', value: this.settings } });
}
};
/**
* Updates option logic if necessery.
* @protected
*/
Owl2.prototype.optionsLogic = function() {
// Toggle Center class
this.$element.toggleClass('owl2-center', this.settings.center);
// if items number is less than in body
if (this.settings.loop && this._items.length < this.settings.items) {
this.settings.loop = false;
}
if (this.settings.autoWidth) {
this.settings.stagePadding = false;
this.settings.merge = false;
}
};
/**
* Prepares an item before add.
* @todo Rename event parameter `content` to `item`.
* @protected
* @returns {jQuery|HTMLElement} - The item container.
*/
Owl2.prototype.prepare = function(item) {
var event = this.trigger('prepare', { content: item });
if (!event.data) {
event.data = $('<' + this.settings.itemElement + '/>')
.addClass(this.settings.itemClass).append(item)
}
this.trigger('prepared', { content: event.data });
return event.data;
};
/**
* Updates the view.
* @public
*/
Owl2.prototype.update = function() {
var i = 0,
n = this._pipe.length,
filter = $.proxy(function(p) { return this[p] }, this._invalidated),
cache = {};
while (i < n) {
if (this._invalidated.all || $.grep(this._pipe[i].filter, filter).length > 0) {
this._pipe[i].run(cache);
}
i++;
}
this._invalidated = {};
};
/**
* Gets the width of the view.
* @public
* @param {Owl2.Width} [dimension=Owl2.Width.Default] - The dimension to return.
* @returns {Number} - The width of the view in pixel.
*/
Owl2.prototype.width = function(dimension) {
dimension = dimension || Owl2.Width.Default;
switch (dimension) {
case Owl2.Width.Inner:
case Owl2.Width.Outer:
return this._width;
default:
return this._width - this.settings.stagePadding * 2 + this.settings.margin;
}
};
/**
* Refreshes the carousel2 primarily for adaptive purposes.
* @public
*/
Owl2.prototype.refresh = function() {
if (this._items.length === 0) {
return false;
}
var start = new Date().getTime();
this.trigger('refresh');
this.setup();
this.optionsLogic();
// hide and show methods helps here to set a proper widths,
// this prevents scrollbar to be calculated in stage width
this.$stage.addClass('owl2-refresh');
this.update();
this.$stage.removeClass('owl2-refresh');
this.state.orientation = window.orientation;
this.watchVisibility();
this.trigger('refreshed');
};
/**
* Save internal event references and add event based functions.
* @protected
*/
Owl2.prototype.eventsCall = function() {
// Save events references
this.e._onDragStart = $.proxy(function(e) {
this.onDragStart(e);
}, this);
this.e._onDragMove = $.proxy(function(e) {
this.onDragMove(e);
}, this);
this.e._onDragEnd = $.proxy(function(e) {
this.onDragEnd(e);
}, this);
this.e._onResize = $.proxy(function(e) {
this.onResize(e);
}, this);
this.e._transitionEnd = $.proxy(function(e) {
this.transitionEnd(e);
}, this);
this.e._preventClick = $.proxy(function(e) {
this.preventClick(e);
}, this);
};
/**
* Checks window `resize` event.
* @protected
*/
Owl2.prototype.onThrottledResize = function() {
window.clearTimeout(this.resizeTimer);
this.resizeTimer = window.setTimeout(this.e._onResize, this.settings.responsiveRefreshRate);
};
/**
* Checks window `resize` event.
* @protected
*/
Owl2.prototype.onResize = function() {
if (!this._items.length) {
return false;
}
if (this._width === this.$element.width()) {
return false;
}
if (this.trigger('resize').isDefaultPrevented()) {
return false;
}
this._width = this.$element.width();
this.invalidate('width');
this.refresh();
this.trigger('resized');
};
/**
* Checks for touch/mouse drag event type and add run event handlers.
* @protected
*/
Owl2.prototype.eventsRouter = function(event) {
var type = event.type;
if (type === "mousedown" || type === "touchstart") {
this.onDragStart(event);
} else if (type === "mousemove" || type === "touchmove") {
this.onDragMove(event);
} else if (type === "mouseup" || type === "touchend") {
this.onDragEnd(event);
} else if (type === "touchcancel") {
this.onDragEnd(event);
}
};
/**
* Checks for touch/mouse drag options and add necessery event handlers.
* @protected
*/
Owl2.prototype.internalEvents = function() {
var isTouch = isTouchSupport(),
isTouchIE = isTouchSupportIE();
if (this.settings.mouseDrag){
this.$stage.on('mousedown', $.proxy(function(event) { this.eventsRouter(event) }, this));
this.$stage.on('dragstart', function() { return false });
this.$stage.get(0).onselectstart = function() { return false };
} else {
this.$element.addClass('owl2-text-select-on');
}
if (this.settings.touchDrag && !isTouchIE){
this.$stage.on('touchstart touchcancel', $.proxy(function(event) { this.eventsRouter(event) }, this));
}
// catch transitionEnd event
if (this.transitionEndVendor) {
this.on(this.$stage.get(0), this.transitionEndVendor, this.e._transitionEnd, false);
}
// responsive
if (this.settings.responsive !== false) {
this.on(window, 'resize', $.proxy(this.onThrottledResize, this));
}
};
/**
* Handles touchstart/mousedown event.
* @protected
* @param {Event} event - The event arguments.
*/
Owl2.prototype.onDragStart = function(event) {
var ev, isTouchEvent, pageX, pageY, animatedPos;
ev = event.originalEvent || event || window.event;
// prevent right click
if (ev.which === 3 || this.state.isTouch) {
return false;
}
if (ev.type === 'mousedown') {
this.$stage.addClass('owl2-grab');
}
this.trigger('drag');
this.drag.startTime = new Date().getTime();
this.speed(0);
this.state.isTouch = true;
this.state.isScrolling = false;
this.state.isSwiping = false;
this.drag.distance = 0;
pageX = getTouches(ev).x;
pageY = getTouches(ev).y;
// get stage position left
this.drag.offsetX = this.$stage.position().left;
this.drag.offsetY = this.$stage.position().top;
if (this.settings.rtl) {
this.drag.offsetX = this.$stage.position().left + this.$stage.width() - this.width()
+ this.settings.margin;
}
// catch position // ie to fix
if (this.state.inMotion && this.support3d) {
animatedPos = this.getTransformProperty();
this.drag.offsetX = animatedPos;
this.animate(animatedPos);
this.state.inMotion = true;
} else if (this.state.inMotion && !this.support3d) {
this.state.inMotion = false;
return false;
}
this.drag.startX = pageX - this.drag.offsetX;
this.drag.startY = pageY - this.drag.offsetY;
this.drag.start = pageX - this.drag.startX;
this.drag.targetEl = ev.target || ev.srcElement;
this.drag.updatedX = this.drag.start;
// to do/check
// prevent links and images dragging;
if (this.drag.targetEl.tagName === "IMG" || this.drag.targetEl.tagName === "A") {
this.drag.targetEl.draggable = false;
}
$(document).on('mousemove.owl.dragEvents mouseup.owl.dragEvents touchmove.owl.dragEvents touchend.owl.dragEvents', $.proxy(function(event) {this.eventsRouter(event)},this));
};
/**
* Handles the touchmove/mousemove events.
* @todo Simplify
* @protected
* @param {Event} event - The event arguments.
*/
Owl2.prototype.onDragMove = function(event) {
var ev, isTouchEvent, pageX, pageY, minValue, maxValue, pull;
if (!this.state.isTouch) {
return;
}
if (this.state.isScrolling) {
return;
}
ev = event.originalEvent || event || window.event;
pageX = getTouches(ev).x;
pageY = getTouches(ev).y;
// Drag Direction
this.drag.currentX = pageX - this.drag.startX;
this.drag.currentY = pageY - this.drag.startY;
this.drag.distance = this.drag.currentX - this.drag.offsetX;
// Check move direction
if (this.drag.distance < 0) {
this.state.direction = this.settings.rtl ? 'right' : 'left';
} else if (this.drag.distance > 0) {
this.state.direction = this.settings.rtl ? 'left' : 'right';
}
// Loop
if (this.settings.loop) {
if (this.op(this.drag.currentX, '>', this.coordinates(this.minimum())) && this.state.direction === 'right') {
this.drag.currentX -= (this.settings.center && this.coordinates(0)) - this.coordinates(this._items.length);
} else if (this.op(this.drag.currentX, '<', this.coordinates(this.maximum())) && this.state.direction === 'left') {
this.drag.currentX += (this.settings.center && this.coordinates(0)) - this.coordinates(this._items.length);
}
} else {
// pull
minValue = this.settings.rtl ? this.coordinates(this.maximum()) : this.coordinates(this.minimum());
maxValue = this.settings.rtl ? this.coordinates(this.minimum()) : this.coordinates(this.maximum());
pull = this.settings.pullDrag ? this.drag.distance / 5 : 0;
this.drag.currentX = Math.max(Math.min(this.drag.currentX, minValue + pull), maxValue + pull);
}
// Lock browser if swiping horizontal
if ((this.drag.distance > 8 || this.drag.distance < -8)) {
if (ev.preventDefault !== undefined) {
ev.preventDefault();
} else {
ev.returnValue = false;
}
this.state.isSwiping = true;
}
this.drag.updatedX = this.drag.currentX;
// Lock Owl2 if scrolling
if ((this.drag.currentY > 16 || this.drag.currentY < -16) && this.state.isSwiping === false) {
this.state.isScrolling = true;
this.drag.updatedX = this.drag.start;
}
this.animate(this.drag.updatedX);
};
/**
* Handles the touchend/mouseup events.
* @protected
*/
Owl2.prototype.onDragEnd = function(event) {
var compareTimes, distanceAbs, closest;
if (!this.state.isTouch) {
return;
}
if (event.type === 'mouseup') {
this.$stage.removeClass('owl2-grab');
}
this.trigger('dragged');
// prevent links and images dragging;
this.drag.targetEl.removeAttribute("draggable");
// remove drag event listeners
this.state.isTouch = false;
this.state.isScrolling = false;
this.state.isSwiping = false;
// to check
if (this.drag.distance === 0 && this.state.inMotion !== true) {
this.state.inMotion = false;
return false;
}
// prevent clicks while scrolling
this.drag.endTime = new Date().getTime();
compareTimes = this.drag.endTime - this.drag.startTime;
distanceAbs = Math.abs(this.drag.distance);
// to test
if (distanceAbs > 3 || compareTimes > 300) {
this.removeClick(this.drag.targetEl);
}
closest = this.closest(this.drag.updatedX);
this.speed(this.settings.dragEndSpeed || this.settings.smartSpeed);
this.current(closest);
this.invalidate('position');
this.update();
// if pullDrag is off then fire transitionEnd event manually when stick
// to border
if (!this.settings.pullDrag && this.drag.updatedX === this.coordinates(closest)) {
this.transitionEnd();
}
this.drag.distance = 0;
$(document).off('.owl.dragEvents');
};
/**
* Attaches `preventClick` to disable link while swipping.
* @protected
* @param {HTMLElement} [target] - The target of the `click` event.
*/
Owl2.prototype.removeClick = function(target) {
this.drag.targetEl = target;
$(target).on('click.preventClick', this.e._preventClick);
// to make sure click is removed:
window.setTimeout(function() {
$(target).off('click.preventClick');
}, 300);
};
/**
* Suppresses click event.
* @protected
* @param {Event} ev - The event arguments.
*/
Owl2.prototype.preventClick = function(ev) {
if (ev.preventDefault) {
ev.preventDefault();
} else {
ev.returnValue = false;
}
if (ev.stopPropagation) {
ev.stopPropagation();
}
$(ev.target).off('click.preventClick');
};
/**
* Catches stage position while animate (only CSS3).
* @protected
* @returns
*/
Owl2.prototype.getTransformProperty = function() {
var transform, matrix3d;
transform = window.getComputedStyle(this.$stage.get(0), null).getPropertyValue(this.vendorName + 'transform');
// var transform = this.$stage.css(this.vendorName + 'transform')
transform = transform.replace(/matrix(3d)?\(|\)/g, '').split(',');
matrix3d = transform.length === 16;
return matrix3d !== true ? transform[4] : transform[12];
};
/**
* Gets absolute position of the closest item for a coordinate.
* @todo Setting `freeDrag` makes `closest` not reusable. See #165.
* @protected
* @param {Number} coordinate - The coordinate in pixel.
* @return {Number} - The absolute position of the closest item.
*/
Owl2.prototype.closest = function(coordinate) {
var position = -1, pull = 30, width = this.width(), coordinates = this.coordinates();
if (!this.settings.freeDrag) {
// check closest item
$.each(coordinates, $.proxy(function(index, value) {
if (coordinate > value - pull && coordinate < value + pull) {
position = index;
} else if (this.op(coordinate, '<', value)
&& this.op(coordinate, '>', coordinates[index + 1] || value - width)) {
position = this.state.direction === 'left' ? index + 1 : index;
}
return position === -1;
}, this));
}
if (!this.settings.loop) {
// non loop boundries
if (this.op(coordinate, '>', coordinates[this.minimum()])) {
position = coordinate = this.minimum();
} else if (this.op(coordinate, '<', coordinates[this.maximum()])) {
position = coordinate = this.maximum();
}
}
return position;
};
/**
* Animates the stage.
* @public
* @param {Number} coordinate - The coordinate in pixels.
*/
Owl2.prototype.animate = function(coordinate) {
this.trigger('translate');
this.state.inMotion = this.speed() > 0;
if (this.support3d) {
this.$stage.css({
transform: 'translate3d(' + coordinate + 'px' + ',0px, 0px)',
transition: (this.speed() / 1000) + 's'
});
} else if (this.state.isTouch) {
this.$stage.css({
left: coordinate + 'px'
});
} else {
this.$stage.animate({
left: coordinate
}, this.speed() / 1000, this.settings.fallbackEasing, $.proxy(function() {
if (this.state.inMotion) {
this.transitionEnd();
}
}, this));
}
};
/**
* Sets the absolute position of the current item.
* @public
* @param {Number} [position] - The new absolute position or nothing to leave it unchanged.
* @returns {Number} - The absolute position of the current item.
*/
Owl2.prototype.current = function(position) {
if (position === undefined) {
return this._current;
}
if (this._items.length === 0) {
return undefined;
}
position = this.normalize(position);
if (this._current !== position) {
var event = this.trigger('change', { property: { name: 'position', value: position } });
if (event.data !== undefined) {
position = this.normalize(event.data);
}
this._current = position;
this.invalidate('position');
this.trigger('changed', { property: { name: 'position', value: this._current } });
}
return this._current;
};
/**
* Invalidates the given part of the update routine.
* @param {String} part - The part to invalidate.
*/
Owl2.prototype.invalidate = function(part) {
this._invalidated[part] = true;
}
/**
* Resets the absolute position of the current item.
* @public
* @param {Number} position - The absolute position of the new item.
*/
Owl2.prototype.reset = function(position) {
position = this.normalize(position);
if (position === undefined) {
return;
}
this._speed = 0;
this._current = position;
this.suppress([ 'translate', 'translated' ]);
this.animate(this.coordinates(position));
this.release([ 'translate', 'translated' ]);
};
/**
* Normalizes an absolute or a relative position for an item.
* @public
* @param {Number} position - The absolute or relative position to normalize.
* @param {Boolean} [relative=false] - Whether the given position is relative or not.
* @returns {Number} - The normalized position.
*/
Owl2.prototype.normalize = function(position, relative) {
var n = (relative ? this._items.length : this._items.length + this._clones.length);
if (!$.isNumeric(position) || n < 1) {
return undefined;
}
if (this._clones.length) {
position = ((position % n) + n) % n;
} else {
position = Math.max(this.minimum(relative), Math.min(this.maximum(relative), position));
}
return position;
};
/**
* Converts an absolute position for an item into a relative position.
* @public
* @param {Number} position - The absolute position to convert.
* @returns {Number} - The converted position.
*/
Owl2.prototype.relative = function(position) {
position = this.normalize(position);
position = position - this._clones.length / 2;
return this.normalize(position, true);
};
/**
* Gets the maximum position for an item.
* @public
* @param {Boolean} [relative=false] - Whether to return an absolute position or a relative position.
* @returns {Number}
*/
Owl2.prototype.maximum = function(relative) {
var maximum, width, i = 0, coordinate,
settings = this.settings;
if (relative) {
return this._items.length - 1;
}
if (!settings.loop && settings.center) {
maximum = this._items.length - 1;
} else if (!settings.loop && !settings.center) {
maximum = this._items.length - settings.items;
} else if (settings.loop || settings.center) {
maximum = this._items.length + settings.items;
} else if (settings.autoWidth || settings.merge) {
revert = settings.rtl ? 1 : -1;
width = this.$stage.width() - this.$element.width();
while (coordinate = this.coordinates(i)) {
if (coordinate * revert >= width) {
break;
}
maximum = ++i;
}
} else {
throw 'Can not detect maximum absolute position.'
}
return maximum;
};
/**
* Gets the minimum position for an item.
* @public
* @param {Boolean} [relative=false] - Whether to return an absolute position or a relative position.
* @returns {Number}
*/
Owl2.prototype.minimum = function(relative) {
if (relative) {
return 0;
}
return this._clones.length / 2;
};
/**
* Gets an item at the specified relative position.
* @public
* @param {Number} [position] - The relative position of the item.
* @return {jQuery|Array.<jQuery>} - The item at the given position or all items if no position was given.
*/
Owl2.prototype.items = function(position) {
if (position === undefined) {
return this._items.slice();
}
position = this.normalize(position, true);
return this._items[position];
};
/**
* Gets an item at the specified relative position.
* @public
* @param {Number} [position] - The relative position of the item.
* @return {jQuery|Array.<jQuery>} - The item at the given position or all items if no position was given.
*/
Owl2.prototype.mergers = function(position) {
if (position === undefined) {
return this._mergers.slice();
}
position = this.normalize(position, true);
return this._mergers[position];
};
/**
* Gets the absolute positions of clones for an item.
* @public
* @param {Number} [position] - The relative position of the item.
* @returns {Array.<Number>} - The absolute positions of clones for the item or all if no position was given.
*/
Owl2.prototype.clones = function(position) {
var odd = this._clones.length / 2,
even = odd + this._items.length,
map = function(index) { return index % 2 === 0 ? even + index / 2 : odd - (index + 1) / 2 };
if (position === undefined) {
return $.map(this._clones, function(v, i) { return map(i) });
}
return $.map(this._clones, function(v, i) { return v === position ? map(i) : null });
};
/**
* Sets the current animation speed.
* @public
* @param {Number} [speed] - The animation speed in milliseconds or nothing to leave it unchanged.
* @returns {Number} - The current animation speed in milliseconds.
*/
Owl2.prototype.speed = function(speed) {
if (speed !== undefined) {
this._speed = speed;
}
return this._speed;
};
/**
* Gets the coordinate of an item.
* @todo The name of this method is missleanding.
* @public
* @param {Number} position - The absolute position of the item within `minimum()` and `maximum()`.
* @returns {Number|Array.<Number>} - The coordinate of the item in pixel or all coordinates.
*/
Owl2.prototype.coordinates = function(position) {
var coordinate = null;
if (position === undefined) {
return $.map(this._coordinates, $.proxy(function(coordinate, index) {
return this.coordinates(index);
}, this));
}
if (this.settings.center) {
coordinate = this._coordinates[position];
coordinate += (this.width() - coordinate + (this._coordinates[position - 1] || 0)) / 2 * (this.settings.rtl ? -1 : 1);
} else {
coordinate = this._coordinates[position - 1] || 0;
}
return coordinate;
};
/**
* Calculates the speed for a translation.
* @protected
* @param {Number} from - The absolute position of the start item.
* @param {Number} to - The absolute position of the target item.
* @param {Number} [factor=undefined] - The time factor in milliseconds.
* @returns {Number} - The time in milliseconds for the translation.
*/
Owl2.prototype.duration = function(from, to, factor) {
return Math.min(Math.max(Math.abs(to - from), 1), 6) * Math.abs((factor || this.settings.smartSpeed));
};
/**
* Slides to the specified item.
* @public
* @param {Number} position - The position of the item.
* @param {Number} [speed] - The time in milliseconds for the transition.
*/
Owl2.prototype.to = function(position, speed) {
if (this.settings.loop) {
var distance = position - this.relative(this.current()),
revert = this.current(),
before = this.current(),
after = this.current() + distance,
direction = before - after < 0 ? true : false,
items = this._clones.length + this._items.length;
if (after < this.settings.items && direction === false) {
revert = before + this._items.length;
this.reset(revert);
} else if (after >= items - this.settings.items && direction === true) {
revert = before - this._items.length;
this.reset(revert);
}
window.clearTimeout(this.e._goToLoop);
this.e._goToLoop = window.setTimeout($.proxy(function() {
this.speed(this.duration(this.current(), revert + distance, speed));
this.current(revert + distance);
this.update();
}, this), 30);
} else {
this.speed(this.duration(this.current(), position, speed));
this.current(position);
this.update();
}
};
/**
* Slides to the next item.
* @public
* @param {Number} [speed] - The time in milliseconds for the transition.
*/
Owl2.prototype.next = function(speed) {
speed = speed || false;
this.to(this.relative(this.current()) + 1, speed);
};
/**
* Slides to the previous item.
* @public
* @param {Number} [speed] - The time in milliseconds for the transition.
*/
Owl2.prototype.prev = function(speed) {
speed = speed || false;
this.to(this.relative(this.current()) - 1, speed);
};
/**
* Handles the end of an animation.
* @protected
* @param {Event} event - The event arguments.
*/
Owl2.prototype.transitionEnd = function(event) {
// if css2 animation then event object is undefined
if (event !== undefined) {
event.stopPropagation();
// Catch only owl2-stage transitionEnd event
if ((event.target || event.srcElement || event.originalTarget) !== this.$stage.get(0)) {
return false;
}
}
this.state.inMotion = false;
this.trigger('translated');
};
/**
* Gets viewport width.
* @protected
* @return {Number} - The width in pixel.
*/
Owl2.prototype.viewport = function() {
var width;
if (this.options.responsiveBaseElement !== window) {
width = $(this.options.responsiveBaseElement).width();
} else if (window.innerWidth) {
width = window.innerWidth;
} else if (document.documentElement && document.documentElement.clientWidth) {
width = document.documentElement.clientWidth;
} else {
throw 'Can not detect viewport width.';
}
return width;
};
/**
* Replaces the current content.
* @public
* @param {HTMLElement|jQuery|String} content - The new content.
*/
Owl2.prototype.replace = function(content) {
this.$stage.empty();
this._items = [];
if (content) {
content = (content instanceof jQuery) ? content : $(content);
}
if (this.settings.nestedItemSelector) {
content = content.find('.' + this.settings.nestedItemSelector);
}
content.filter(function() {
return this.nodeType === 1;
}).each($.proxy(function(index, item) {
item = this.prepare(item);
this.$stage.append(item);
this._items.push(item);
this._mergers.push(item.find('[data-merge]').andSelf('[data-merge]').attr('data-merge') * 1 || 1);
}, this));
this.reset($.isNumeric(this.settings.startPosition) ? this.settings.startPosition : 0);
this.invalidate('items');
};
/**
* Adds an item.
* @todo Use `item` instead of `content` for the event arguments.
* @public
* @param {HTMLElement|jQuery|String} content - The item content to add.
* @param {Number} [position] - The relative position at which to insert the item otherwise the item will be added to the end.
*/
Owl2.prototype.add = function(content, position) {
position = position === undefined ? this._items.length : this.normalize(position, true);
this.trigger('add', { content: content, position: position });
if (this._items.length === 0 || position === this._items.length) {
this.$stage.append(content);
this._items.push(content);
this._mergers.push(content.find('[data-merge]').andSelf('[data-merge]').attr('data-merge') * 1 || 1);
} else {
this._items[position].before(content);
this._items.splice(position, 0, content);
this._mergers.splice(position, 0, content.find('[data-merge]').andSelf('[data-merge]').attr('data-merge') * 1 || 1);
}
this.invalidate('items');
this.trigger('added', { content: content, position: position });
};
/**
* Removes an item by its position.
* @todo Use `item` instead of `content` for the event arguments.
* @public
* @param {Number} position - The relative position of the item to remove.
*/
Owl2.prototype.remove = function(position) {
position = this.normalize(position, true);
if (position === undefined) {
return;
}
this.trigger('remove', { content: this._items[position], position: position });
this._items[position].remove();
this._items.splice(position, 1);
this._mergers.splice(position, 1);
this.invalidate('items');
this.trigger('removed', { content: null, position: position });
};
/**
* Adds triggerable events.
* @protected
*/
Owl2.prototype.addTriggerableEvents = function() {
var handler = $.proxy(function(callback, event) {
return $.proxy(function(e) {
if (e.relatedTarget !== this) {
this.suppress([ event ]);
callback.apply(this, [].slice.call(arguments, 1));
this.release([ event ]);
}
}, this);
}, this);
$.each({
'next': this.next,
'prev': this.prev,
'to': this.to,
'destroy': this.destroy,
'refresh': this.refresh,
'replace': this.replace,
'add': this.add,
'remove': this.remove
}, $.proxy(function(event, callback) {
this.$element.on(event + '.owl.carousel2', handler(callback, event + '.owl.carousel2'));
}, this));
};
/**
* Watches the visibility of the carousel2 element.
* @protected
*/
Owl2.prototype.watchVisibility = function() {
// test on zepto
if (!isElVisible(this.$element.get(0))) {
this.$element.addClass('owl2-hidden');
window.clearInterval(this.e._checkVisibile);
this.e._checkVisibile = window.setInterval($.proxy(checkVisible, this), 500);
}
function isElVisible(el) {
return el.offsetWidth > 0 && el.offsetHeight > 0;
}
function checkVisible() {
if (isElVisible(this.$element.get(0))) {
this.$element.removeClass('owl2-hidden');
this.refresh();
window.clearInterval(this.e._checkVisibile);
}
}
};
/**
* Preloads images with auto width.
* @protected
* @todo Still to test
*/
Owl2.prototype.preloadAutoWidthImages = function(imgs) {
var loaded, that, $el, img;
loaded = 0;
that = this;
imgs.each(function(i, el) {
$el = $(el);
img = new Image();
img.onload = function() {
loaded++;
$el.attr('src', img.src);
$el.css('opacity', 1);
if (loaded >= imgs.length) {
that.state.imagesLoaded = true;
that.initialize();
}
};
img.src = $el.attr('src') || $el.attr('data-src') || $el.attr('data-src-retina');
});
};
/**
* Destroys the carousel2.
* @public
*/
Owl2.prototype.destroy = function() {
if (this.$element.hasClass(this.settings.themeClass)) {
this.$element.removeClass(this.settings.themeClass);
}
if (this.settings.responsive !== false) {
$(window).off('resize.owl.carousel2');
}
if (this.transitionEndVendor) {
this.off(this.$stage.get(0), this.transitionEndVendor, this.e._transitionEnd);
}
for ( var i in this._plugins) {
this._plugins[i].destroy();
}
if (this.settings.mouseDrag || this.settings.touchDrag) {
this.$stage.off('mousedown touchstart touchcancel');
$(document).off('.owl.dragEvents');
this.$stage.get(0).onselectstart = function() {};
this.$stage.off('dragstart', function() { return false });
}
// remove event handlers in the ".owl.carousel2" namespace
this.$element.off('.owl');
this.$stage.children('.cloned').remove();
this.e = null;
this.$element.removeData('owlCarousel2');
this.$stage.children().contents().unwrap();
this.$stage.children().unwrap();
this.$stage.unwrap();
};
/**
* Operators to calculate right-to-left and left-to-right.
* @protected
* @param {Number} [a] - The left side operand.
* @param {String} [o] - The operator.
* @param {Number} [b] - The right side operand.
*/
Owl2.prototype.op = function(a, o, b) {
var rtl = this.settings.rtl;
switch (o) {
case '<':
return rtl ? a > b : a < b;
case '>':
return rtl ? a < b : a > b;
case '>=':
return rtl ? a <= b : a >= b;
case '<=':
return rtl ? a >= b : a <= b;
default:
break;
}
};
/**
* Attaches to an internal event.
* @protected
* @param {HTMLElement} element - The event source.
* @param {String} event - The event name.
* @param {Function} listener - The event handler to attach.
* @param {Boolean} capture - Wether the event should be handled at the capturing phase or not.
*/
Owl2.prototype.on = function(element, event, listener, capture) {
if (element.addEventListener) {
element.addEventListener(event, listener, capture);
} else if (element.attachEvent) {
element.attachEvent('on' + event, listener);
}
};
/**
* Detaches from an internal event.
* @protected
* @param {HTMLElement} element - The event source.
* @param {String} event - The event name.
* @param {Function} listener - The attached event handler to detach.
* @param {Boolean} capture - Wether the attached event handler was registered as a capturing listener or not.
*/
Owl2.prototype.off = function(element, event, listener, capture) {
if (element.removeEventListener) {
element.removeEventListener(event, listener, capture);
} else if (element.detachEvent) {
element.detachEvent('on' + event, listener);
}
};
/**
* Triggers an public event.
* @protected
* @param {String} name - The event name.
* @param {*} [data=null] - The event data.
* @param {String} [namespace=.owl.carousel2] - The event namespace.
* @returns {Event} - The event arguments.
*/
Owl2.prototype.trigger = function(name, data, namespace) {
var status = {
item: { count: this._items.length, index: this.current() }
}, handler = $.camelCase(
$.grep([ 'on', name, namespace ], function(v) { return v })
.join('-').toLowerCase()
), event = $.Event(
[ name, 'owl', namespace || 'carousel2' ].join('.').toLowerCase(),
$.extend({ relatedTarget: this }, status, data)
);
if (!this._supress[name]) {
$.each(this._plugins, function(name, plugin) {
if (plugin.onTrigger) {
plugin.onTrigger(event);
}
});
this.$element.trigger(event);
if (this.settings && typeof this.settings[handler] === 'function') {
this.settings[handler].apply(this, event);
}
}
return event;
};
/**
* Suppresses events.
* @protected
* @param {Array.<String>} events - The events to suppress.
*/
Owl2.prototype.suppress = function(events) {
$.each(events, $.proxy(function(index, event) {
this._supress[event] = true;
}, this));
}
/**
* Releases suppressed events.
* @protected
* @param {Array.<String>} events - The events to release.
*/
Owl2.prototype.release = function(events) {
$.each(events, $.proxy(function(index, event) {
delete this._supress[event];
}, this));
}
/**
* Checks the availability of some browser features.
* @protected
*/
Owl2.prototype.browserSupport = function() {
this.support3d = isPerspective();
if (this.support3d) {
this.transformVendor = isTransform();
// take transitionend event name by detecting transition
var endVendors = [ 'transitionend', 'webkitTransitionEnd', 'transitionend', 'oTransitionEnd' ];
this.transitionEndVendor = endVendors[isTransition()];
// take vendor name from transform name
this.vendorName = this.transformVendor.replace(/Transform/i, '');
this.vendorName = this.vendorName !== '' ? '-' + this.vendorName.toLowerCase() + '-' : '';
}
this.state.orientation = window.orientation;
};
/**
* Get touch/drag coordinats.
* @private
* @param {event} - mousedown/touchstart event
* @returns {object} - Contains X and Y of current mouse/touch position
*/
function getTouches(event) {
if (event.touches !== undefined) {
return {
x: event.touches[0].pageX,
y: event.touches[0].pageY
};
}
if (event.touches === undefined) {
if (event.pageX !== undefined) {
return {
x: event.pageX,
y: event.pageY
};
}
if (event.pageX === undefined) {
return {
x: event.clientX,
y: event.clientY
};
}
}
}
/**
* Checks for CSS support.
* @private
* @param {Array} array - The CSS properties to check for.
* @returns {Array} - Contains the supported CSS property name and its index or `false`.
*/
function isStyleSupported(array) {
var p, s, fake = document.createElement('div'), list = array;
for (p in list) {
s = list[p];
if (typeof fake.style[s] !== 'undefined') {
fake = null;
return [ s, p ];
}
}
return [ false ];
}
/**
* Checks for CSS transition support.
* @private
* @todo Realy bad design
* @returns {Number}
*/
function isTransition() {
return isStyleSupported([ 'transition', 'WebkitTransition', 'MozTransition', 'OTransition' ])[1];
}
/**
* Checks for CSS transform support.
* @private
* @returns {String} The supported property name or false.
*/
function isTransform() {
return isStyleSupported([ 'transform', 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform' ])[0];
}
/**
* Checks for CSS perspective support.
* @private
* @returns {String} The supported property name or false.
*/
function isPerspective() {
return isStyleSupported([ 'perspective', 'webkitPerspective', 'MozPerspective', 'OPerspective', 'MsPerspective' ])[0];
}
/**
* Checks wether touch is supported or not.
* @private
* @returns {Boolean}
*/
function isTouchSupport() {
return 'ontouchstart' in window || !!(navigator.msMaxTouchPoints);
}
/**
* Checks wether touch is supported or not for IE.
* @private
* @returns {Boolean}
*/
function isTouchSupportIE() {
return window.navigator.msPointerEnabled;
}
/**
* The jQuery Plugin for the Owl2 Carousel
* @public
*/
$.fn.owlCarousel2 = function(options) {
return this.each(function() {
if (!$(this).data('owlCarousel2')) {
$(this).data('owlCarousel2', new Owl2(this, options));
}
});
};
/**
* The constructor for the jQuery Plugin
* @public
*/
$.fn.owlCarousel2.Constructor = Owl2;
})(window.Zepto || window.jQuery, window, document);
/**
* Lazy Plugin
* @version 2.0.0
* @author Bartosz Wojciechowski
* @license The MIT License (MIT)
*/
;(function($, window, document, undefined) {
/**
* Creates the lazy plugin.
* @class The Lazy Plugin
* @param {Owl2} carousel2 - The Owl2 Carousel
*/
var Lazy = function(carousel2) {
/**
* Reference to the core.
* @protected
* @type {Owl2}
*/
this._core = carousel2;
/**
* Already loaded items.
* @protected
* @type {Array.<jQuery>}
*/
this._loaded = [];
/**
* Event handlers.
* @protected
* @type {Object}
*/
this._handlers = {
'initialized.owl.carousel2 change.owl.carousel2': $.proxy(function(e) {
if (!e.namespace) {
return;
}
if (!this._core.settings || !this._core.settings.lazyLoad) {
return;
}
if ((e.property && e.property.name == 'position') || e.type == 'initialized') {
var settings = this._core.settings,
n = (settings.center && Math.ceil(settings.items / 2) || settings.items),
i = ((settings.center && n * -1) || 0),
position = ((e.property && e.property.value) || this._core.current()) + i,
clones = this._core.clones().length,
load = $.proxy(function(i, v) { this.load(v) }, this);
while (i++ < n) {
this.load(clones / 2 + this._core.relative(position));
clones && $.each(this._core.clones(this._core.relative(position++)), load);
}
}
}, this)
};
// set the default options
this._core.options = $.extend({}, Lazy.Defaults, this._core.options);
// register event handler
this._core.$element.on(this._handlers);
}
/**
* Default options.
* @public
*/
Lazy.Defaults = {
lazyLoad: false
}
/**
* Loads all resources of an item at the specified position.
* @param {Number} position - The absolute position of the item.
* @protected
*/
Lazy.prototype.load = function(position) {
var $item = this._core.$stage.children().eq(position),
$elements = $item && $item.find('.owl2-lazy');
if (!$elements || $.inArray($item.get(0), this._loaded) > -1) {
return;
}
$elements.each($.proxy(function(index, element) {
var $element = $(element), image,
url = (window.devicePixelRatio > 1 && $element.attr('data-src-retina')) || $element.attr('data-src');
this._core.trigger('load', { element: $element, url: url }, 'lazy');
if ($element.is('img')) {
$element.one('load.owl.lazy', $.proxy(function() {
$element.css('opacity', 1);
this._core.trigger('loaded', { element: $element, url: url }, 'lazy');
}, this)).attr('src', url);
} else {
image = new Image();
image.onload = $.proxy(function() {
$element.css({
'background-image': 'url(' + url + ')',
'opacity': '1'
});
this._core.trigger('loaded', { element: $element, url: url }, 'lazy');
}, this);
image.src = url;
}
}, this));
this._loaded.push($item.get(0));
}
/**
* Destroys the plugin.
* @public
*/
Lazy.prototype.destroy = function() {
var handler, property;
for (handler in this.handlers) {
this._core.$element.off(handler, this.handlers[handler]);
}
for (property in Object.getOwnPropertyNames(this)) {
typeof this[property] != 'function' && (this[property] = null);
}
}
$.fn.owlCarousel2.Constructor.Plugins.Lazy = Lazy;
})(window.Zepto || window.jQuery, window, document);
/**
* AutoHeight Plugin
* @version 2.0.0
* @author Bartosz Wojciechowski
* @license The MIT License (MIT)
*/
;(function($, window, document, undefined) {
/**
* Creates the auto height plugin.
* @class The Auto Height Plugin
* @param {Owl2} carousel2 - The Owl2 Carousel
*/
var AutoHeight = function(carousel2) {
/**
* Reference to the core.
* @protected
* @type {Owl2}
*/
this._core = carousel2;
/**
* All event handlers.
* @protected
* @type {Object}
*/
this._handlers = {
'initialized.owl.carousel2': $.proxy(function() {
if (this._core.settings.autoHeight) {
this.update();
}
}, this),
'changed.owl.carousel2': $.proxy(function(e) {
if (this._core.settings.autoHeight && e.property.name == 'position'){
this.update();
}
}, this),
'loaded.owl.lazy': $.proxy(function(e) {
if (this._core.settings.autoHeight && e.element.closest('.' + this._core.settings.itemClass)
=== this._core.$stage.children().eq(this._core.current())) {
this.update();
}
}, this)
};
// set default options
this._core.options = $.extend({}, AutoHeight.Defaults, this._core.options);
// register event handlers
this._core.$element.on(this._handlers);
};
/**
* Default options.
* @public
*/
AutoHeight.Defaults = {
autoHeight: false,
autoHeightClass: 'owl2-height'
};
/**
* Updates the view.
*/
AutoHeight.prototype.update = function() {
this._core.$stage.parent()
.height(this._core.$stage.children().eq(this._core.current()).height())
.addClass(this._core.settings.autoHeightClass);
};
AutoHeight.prototype.destroy = function() {
var handler, property;
for (handler in this._handlers) {
this._core.$element.off(handler, this._handlers[handler]);
}
for (property in Object.getOwnPropertyNames(this)) {
typeof this[property] != 'function' && (this[property] = null);
}
};
$.fn.owlCarousel2.Constructor.Plugins.AutoHeight = AutoHeight;
})(window.Zepto || window.jQuery, window, document);
/**
* Video Plugin
* @version 2.0.0
* @author Bartosz Wojciechowski
* @license The MIT License (MIT)
*/
;(function($, window, document, undefined) {
/**
* Creates the video plugin.
* @class The Video Plugin
* @param {Owl2} carousel2 - The Owl2 Carousel
*/
var Video = function(carousel2) {
/**
* Reference to the core.
* @protected
* @type {Owl2}
*/
this._core = carousel2;
/**
* Cache all video URLs.
* @protected
* @type {Object}
*/
this._videos = {};
/**
* Current playing item.
* @protected
* @type {jQuery}
*/
this._playing = null;
/**
* Whether this is in fullscreen or not.
* @protected
* @type {Boolean}
*/
this._fullscreen = false;
/**
* All event handlers.
* @protected
* @type {Object}
*/
this._handlers = {
'resize.owl.carousel2': $.proxy(function(e) {
if (this._core.settings.video && !this.isInFullScreen()) {
e.preventDefault();
}
}, this),
'refresh.owl.carousel2 changed.owl.carousel2': $.proxy(function(e) {
if (this._playing) {
this.stop();
}
}, this),
'prepared.owl.carousel2': $.proxy(function(e) {
var $element = $(e.content).find('.owl2-video');
if ($element.length) {
$element.css('display', 'none');
this.fetch($element, $(e.content));
}
}, this)
};
// set default options
this._core.options = $.extend({}, Video.Defaults, this._core.options);
// register event handlers
this._core.$element.on(this._handlers);
this._core.$element.on('click.owl.video', '.owl2-video-play-icon', $.proxy(function(e) {
this.play(e);
}, this));
};
/**
* Default options.
* @public
*/
Video.Defaults = {
video: false,
videoHeight: false,
videoWidth: false
};
/**
* Gets the video ID and the type (YouTube/Vimeo only).
* @protected
* @param {jQuery} target - The target containing the video data.
* @param {jQuery} item - The item containing the video.
*/
Video.prototype.fetch = function(target, item) {
var type = target.attr('data-vimeo-id') ? 'vimeo' : 'youtube',
id = target.attr('data-vimeo-id') || target.attr('data-youtube-id'),
width = target.attr('data-width') || this._core.settings.videoWidth,
height = target.attr('data-height') || this._core.settings.videoHeight,
url = target.attr('href');
if (url) {
id = url.match(/(http:|https:|)\/\/(player.|www.)?(vimeo\.com|youtu(be\.com|\.be|be\.googleapis\.com))\/(video\/|embed\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/);
if (id[3].indexOf('youtu') > -1) {
type = 'youtube';
} else if (id[3].indexOf('vimeo') > -1) {
type = 'vimeo';
} else {
throw new Error('Video URL not supported.');
}
id = id[6];
} else {
throw new Error('Missing video URL.');
}
this._videos[url] = {
type: type,
id: id,
width: width,
height: height
};
item.attr('data-video', url);
this.thumbnail(target, this._videos[url]);
};
/**
* Creates video thumbnail.
* @protected
* @param {jQuery} target - The target containing the video data.
* @param {Object} info - The video info object.
* @see `fetch`
*/
Video.prototype.thumbnail = function(target, video) {
var tnLink,
icon,
path,
dimensions = video.width && video.height ? 'style="width:' + video.width + 'px;height:' + video.height + 'px;"' : '',
customTn = target.find('img'),
srcType = 'src',
lazyClass = '',
settings = this._core.settings,
create = function(path) {
icon = '<div class="owl2-video-play-icon"></div>';
if (settings.lazyLoad) {
tnLink = '<div class="owl2-video-tn ' + lazyClass + '" ' + srcType + '="' + path + '"></div>';
} else {
tnLink = '<div class="owl2-video-tn" style="opacity:1;background-image:url(' + path + ')"></div>';
}
target.after(tnLink);
target.after(icon);
};
// wrap video content into owl2-video-wrapper div
target.wrap('<div class="owl2-video-wrapper"' + dimensions + '></div>');
if (this._core.settings.lazyLoad) {
srcType = 'data-src';
lazyClass = 'owl2-lazy';
}
// custom thumbnail
if (customTn.length) {
create(customTn.attr(srcType));
customTn.remove();
return false;
}
if (video.type === 'youtube') {
path = "http://img.youtube.com/vi/" + video.id + "/hqdefault.jpg";
create(path);
} else if (video.type === 'vimeo') {
$.ajax({
type: 'GET',
url: 'http://vimeo.com/api/v2/video/' + video.id + '.json',
jsonp: 'callback',
dataType: 'jsonp',
success: function(data) {
path = data[0].thumbnail_large;
create(path);
}
});
}
};
/**
* Stops the current video.
* @public
*/
Video.prototype.stop = function() {
this._core.trigger('stop', null, 'video');
this._playing.find('.owl2-video-frame').remove();
this._playing.removeClass('owl2-video-playing');
this._playing = null;
};
/**
* Starts the current video.
* @public
* @param {Event} ev - The event arguments.
*/
Video.prototype.play = function(ev) {
this._core.trigger('play', null, 'video');
if (this._playing) {
this.stop();
}
var target = $(ev.target || ev.srcElement),
item = target.closest('.' + this._core.settings.itemClass),
video = this._videos[item.attr('data-video')],
width = video.width || '100%',
height = video.height || this._core.$stage.height(),
html, wrap;
if (video.type === 'youtube') {
html = '<iframe width="' + width + '" height="' + height + '" src="http://www.youtube.com/embed/'
+ video.id + '?autoplay=1&v=' + video.id + '" frameborder="0" allowfullscreen></iframe>';
} else if (video.type === 'vimeo') {
html = '<iframe src="http://player.vimeo.com/video/' + video.id + '?autoplay=1" width="' + width
+ '" height="' + height
+ '" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
}
item.addClass('owl2-video-playing');
this._playing = item;
wrap = $('<div style="height:' + height + 'px; width:' + width + 'px" class="owl2-video-frame">'
+ html + '</div>');
target.after(wrap);
};
/**
* Checks whether an video is currently in full screen mode or not.
* @todo Bad style because looks like a readonly method but changes members.
* @protected
* @returns {Boolean}
*/
Video.prototype.isInFullScreen = function() {
// if Vimeo Fullscreen mode
var element = document.fullscreenElement || document.mozFullScreenElement
|| document.webkitFullscreenElement;
if (element && $(element).parent().hasClass('owl2-video-frame')) {
this._core.speed(0);
this._fullscreen = true;
}
if (element && this._fullscreen && this._playing) {
return false;
}
// comming back from fullscreen
if (this._fullscreen) {
this._fullscreen = false;
return false;
}
// check full screen mode and window orientation
if (this._playing) {
if (this._core.state.orientation !== window.orientation) {
this._core.state.orientation = window.orientation;
return false;
}
}
return true;
};
/**
* Destroys the plugin.
*/
Video.prototype.destroy = function() {
var handler, property;
this._core.$element.off('click.owl.video');
for (handler in this._handlers) {
this._core.$element.off(handler, this._handlers[handler]);
}
for (property in Object.getOwnPropertyNames(this)) {
typeof this[property] != 'function' && (this[property] = null);
}
};
$.fn.owlCarousel2.Constructor.Plugins.Video = Video;
})(window.Zepto || window.jQuery, window, document);
/**
* Animate Plugin
* @version 2.0.0
* @author Bartosz Wojciechowski
* @license The MIT License (MIT)
*/
;(function($, window, document, undefined) {
/**
* Creates the animate plugin.
* @class The Navigation Plugin
* @param {Owl2} scope - The Owl2 Carousel
*/
var Animate = function(scope) {
this.core = scope;
this.core.options = $.extend({}, Animate.Defaults, this.core.options);
this.swapping = true;
this.previous = undefined;
this.next = undefined;
this.handlers = {
'change.owl.carousel2': $.proxy(function(e) {
if (e.property.name == 'position') {
this.previous = this.core.current();
this.next = e.property.value;
}
}, this),
'drag.owl.carousel2 dragged.owl.carousel2 translated.owl.carousel2': $.proxy(function(e) {
this.swapping = e.type == 'translated';
}, this),
'translate.owl.carousel2': $.proxy(function(e) {
if (this.swapping && (this.core.options.animateOut || this.core.options.animateIn)) {
this.swap();
}
}, this)
};
this.core.$element.on(this.handlers);
};
/**
* Default options.
* @public
*/
Animate.Defaults = {
animateOut: false,
animateIn: false
};
/**
* Toggles the animation classes whenever an translations starts.
* @protected
* @returns {Boolean|undefined}
*/
Animate.prototype.swap = function() {
if (this.core.settings.items !== 1 || !this.core.support3d) {
return;
}
this.core.speed(0);
var left,
clear = $.proxy(this.clear, this),
previous = this.core.$stage.children().eq(this.previous),
next = this.core.$stage.children().eq(this.next),
incoming = this.core.settings.animateIn,
outgoing = this.core.settings.animateOut;
if (this.core.current() === this.previous) {
return;
}
if (outgoing) {
left = this.core.coordinates(this.previous) - this.core.coordinates(this.next);
previous.css( { 'left': left + 'px' } )
.addClass('animated owl2-animated-out')
.addClass(outgoing)
.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', clear);
}
if (incoming) {
next.addClass('animated owl2-animated-in')
.addClass(incoming)
.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', clear);
}
};
Animate.prototype.clear = function(e) {
$(e.target).css( { 'left': '' } )
.removeClass('animated owl2-animated-out owl2-animated-in')
.removeClass(this.core.settings.animateIn)
.removeClass(this.core.settings.animateOut);
this.core.transitionEnd();
}
/**
* Destroys the plugin.
* @public
*/
Animate.prototype.destroy = function() {
var handler, property;
for (handler in this.handlers) {
this.core.$element.off(handler, this.handlers[handler]);
}
for (property in Object.getOwnPropertyNames(this)) {
typeof this[property] != 'function' && (this[property] = null);
}
};
$.fn.owlCarousel2.Constructor.Plugins.Animate = Animate;
})(window.Zepto || window.jQuery, window, document);
/**
* Autoplay Plugin
* @version 2.0.0
* @author Bartosz Wojciechowski
* @license The MIT License (MIT)
*/
;(function($, window, document, undefined) {
/**
* Creates the autoplay plugin.
* @class The Autoplay Plugin
* @param {Owl2} scope - The Owl2 Carousel
*/
var Autoplay = function(scope) {
this.core = scope;
this.core.options = $.extend({}, Autoplay.Defaults, this.core.options);
this.handlers = {
'translated.owl.carousel2 refreshed.owl.carousel2': $.proxy(function() {
this.autoplay();
}, this),
'play.owl.autoplay': $.proxy(function(e, t, s) {
this.play(t, s);
}, this),
'stop.owl.autoplay': $.proxy(function() {
this.stop();
}, this),
'mouseover.owl.autoplay': $.proxy(function() {
if (this.core.settings.autoplayHoverPause) {
this.pause();
}
}, this),
'mouseleave.owl.autoplay': $.proxy(function() {
if (this.core.settings.autoplayHoverPause) {
this.autoplay();
}
}, this)
};
this.core.$element.on(this.handlers);
};
/**
* Default options.
* @public
*/
Autoplay.Defaults = {
autoplay: false,
autoplayTimeout: 5000,
autoplayHoverPause: false,
autoplaySpeed: false
};
/**
* @protected
* @todo Must be documented.
*/
Autoplay.prototype.autoplay = function() {
if (this.core.options.autoplay) {
this.core.settings.autoplay = true;
}
if (this.core.settings.autoplay && !this.core.state.videoPlay) {
window.clearInterval(this.interval);
this.interval = window.setInterval($.proxy(function() {
this.play();
}, this), this.core.settings.autoplayTimeout);
} else {
window.clearInterval(this.interval);
}
};
/**
* Starts the autoplay.
* @public
* @param {Number} [timeout] - ...
* @param {Number} [speed] - ...
* @returns {Boolean|undefined} - ...
* @todo Must be documented.
*/
Autoplay.prototype.play = function(timeout, speed) {
// if tab is inactive - doesnt work in <IE10
if (this.core.options.autoplay) {
this.core.settings.autoplay = true;
}
if (document.hidden === true) {
return;
}
if (this.core.state.isTouch || this.core.state.isScrolling
|| this.core.state.isSwiping || this.core.state.inMotion) {
return;
}
if (this.core.settings.autoplay === false) {
window.clearInterval(this.interval);
return;
}
this.core.next(this.core.settings.autoplaySpeed);
};
/**
* Stops the autoplay.
* @public
*/
Autoplay.prototype.stop = function() {
if (this.core.options.autoplay) {
this.core.settings.autoplay = false;
}
window.clearInterval(this.interval);
};
/**
* Pauses the autoplay.
* @public
*/
Autoplay.prototype.pause = function() {
if (this.core.options.autoplay) {
this.core.settings.autoplay = false;
}
window.clearInterval(this.interval);
};
/**
* Destroys the plugin.
*/
Autoplay.prototype.destroy = function() {
var handler, property;
window.clearInterval(this.interval);
for (handler in this.handlers) {
this.core.$element.off(handler, this.handlers[handler]);
}
for (property in Object.getOwnPropertyNames(this)) {
typeof this[property] != 'function' && (this[property] = null);
}
};
$.fn.owlCarousel2.Constructor.Plugins.autoplay = Autoplay;
})(window.Zepto || window.jQuery, window, document);
/**
* Navigation Plugin
* @version 2.0.0
* @author Artus Kolanowski
* @license The MIT License (MIT)
*/
;(function($, window, document, undefined) {
'use strict';
/**
* Creates the navigation plugin.
* @class The Navigation Plugin
* @param {Owl2} carousel2 - The Owl2 Carousel.
*/
var Navigation = function(carousel2) {
/**
* Reference to the core.
* @protected
* @type {Owl2}
*/
this._core = carousel2;
/**
* Indicates whether the plugin is initialized or not.
* @protected
* @type {Boolean}
*/
this._initialized = false;
/**
* The current paging indexes.
* @protected
* @type {Array}
*/
this._pages = [];
/**
* All DOM elements of the user interface.
* @protected
* @type {Object}
*/
this._controls = {};
/**
* Markup for an indicator.
* @protected
* @type {Array.<String>}
*/
this._templates = [];
/**
* The carousel2 element.
* @type {jQuery}
*/
this.$element = this._core.$element;
/**
* Overridden methods of the carousel2.
* @protected
* @type {Object}
*/
this._overrides = {
next: this._core.next,
prev: this._core.prev,
to: this._core.to
};
/**
* All event handlers.
* @protected
* @type {Object}
*/
this._handlers = {
'prepared.owl.carousel2': $.proxy(function(e) {
if (this._core.settings.dotsData) {
this._templates.push($(e.content).find('[data-dot]').andSelf('[data-dot]').attr('data-dot'));
}
}, this),
'add.owl.carousel2': $.proxy(function(e) {
if (this._core.settings.dotsData) {
this._templates.splice(e.position, 0, $(e.content).find('[data-dot]').andSelf('[data-dot]').attr('data-dot'));
}
}, this),
'remove.owl.carousel2 prepared.owl.carousel2': $.proxy(function(e) {
if (this._core.settings.dotsData) {
this._templates.splice(e.position, 1);
}
}, this),
'change.owl.carousel2': $.proxy(function(e) {
if (e.property.name == 'position') {
if (!this._core.state.revert && !this._core.settings.loop && this._core.settings.navRewind) {
var current = this._core.current(),
maximum = this._core.maximum(),
minimum = this._core.minimum();
e.data = e.property.value > maximum
? current >= maximum ? minimum : maximum
: e.property.value < minimum ? maximum : e.property.value;
}
}
}, this),
'changed.owl.carousel2': $.proxy(function(e) {
if (e.property.name == 'position') {
this.draw();
}
}, this),
'refreshed.owl.carousel2': $.proxy(function() {
if (!this._initialized) {
this.initialize();
this._initialized = true;
}
this._core.trigger('refresh', null, 'navigation');
this.update();
this.draw();
this._core.trigger('refreshed', null, 'navigation');
}, this)
};
// set default options
this._core.options = $.extend({}, Navigation.Defaults, this._core.options);
// register event handlers
this.$element.on(this._handlers);
}
/**
* Default options.
* @public
* @todo Rename `slideBy` to `navBy`
*/
Navigation.Defaults = {
nav: false,
navRewind: true,
navText: [ 'prev', 'next' ],
navSpeed: false,
navElement: 'div',
navContainer: false,
navContainerClass: 'owl2-nav',
navClass: [ 'owl2-prev', 'owl2-next' ],
slideBy: 1,
dotClass: 'owl2-dot',
dotsClass: 'owl2-dots',
dots: true,
dotsEach: false,
dotData: false,
dotsSpeed: false,
dotsContainer: false,
controlsClass: 'owl2-controls'
}
/**
* Initializes the layout of the plugin and extends the carousel2.
* @protected
*/
Navigation.prototype.initialize = function() {
var $container, override,
options = this._core.settings;
// create the indicator template
if (!options.dotsData) {
this._templates = [ $('<div>')
.addClass(options.dotClass)
.append($('<span>'))
.prop('outerHTML') ];
}
// create controls container if needed
if (!options.navContainer || !options.dotsContainer) {
this._controls.$container = $('<div>')
.addClass(options.controlsClass)
.appendTo(this.$element);
}
// create DOM structure for absolute navigation
this._controls.$indicators = options.dotsContainer ? $(options.dotsContainer)
: $('<div>').hide().addClass(options.dotsClass).appendTo(this._controls.$container);
this._controls.$indicators.on('click', 'div', $.proxy(function(e) {
var index = $(e.target).parent().is(this._controls.$indicators)
? $(e.target).index() : $(e.target).parent().index();
e.preventDefault();
this.to(index, options.dotsSpeed);
}, this));
// create DOM structure for relative navigation
$container = options.navContainer ? $(options.navContainer)
: $('<div>').addClass(options.navContainerClass).prependTo(this._controls.$container);
this._controls.$next = $('<' + options.navElement + '>');
this._controls.$previous = this._controls.$next.clone();
this._controls.$previous
.addClass(options.navClass[0])
.html(options.navText[0])
.hide()
.prependTo($container)
.on('click', $.proxy(function(e) {
this.prev(options.navSpeed);
}, this));
this._controls.$next
.addClass(options.navClass[1])
.html(options.navText[1])
.hide()
.appendTo($container)
.on('click', $.proxy(function(e) {
this.next(options.navSpeed);
}, this));
// override public methods of the carousel2
for (override in this._overrides) {
this._core[override] = $.proxy(this[override], this);
}
}
/**
* Destroys the plugin.
* @protected
*/
Navigation.prototype.destroy = function() {
var handler, control, property, override;
for (handler in this._handlers) {
this.$element.off(handler, this._handlers[handler]);
}
for (control in this._controls) {
this._controls[control].remove();
}
for (override in this.overides) {
this._core[override] = this._overrides[override];
}
for (property in Object.getOwnPropertyNames(this)) {
typeof this[property] != 'function' && (this[property] = null);
}
}
/**
* Updates the internal state.
* @protected
*/
Navigation.prototype.update = function() {
var i, j, k,
options = this._core.settings,
lower = this._core.clones().length / 2,
upper = lower + this._core.items().length,
size = options.center || options.autoWidth || options.dotData
? 1 : options.dotsEach || options.items;
if (options.slideBy !== 'page') {
options.slideBy = Math.min(options.slideBy, options.items);
}
if (options.dots || options.slideBy == 'page') {
this._pages = [];
for (i = lower, j = 0, k = 0; i < upper; i++) {
if (j >= size || j === 0) {
this._pages.push({
start: i - lower,
end: i - lower + size - 1
});
j = 0, ++k;
}
j += this._core.mergers(this._core.relative(i));
}
}
}
/**
* Draws the user interface.
* @todo The option `dotData` wont work.
* @protected
*/
Navigation.prototype.draw = function() {
var difference, i, html = '',
options = this._core.settings,
$items = this._core.$stage.children(),
index = this._core.relative(this._core.current());
if (options.nav && !options.loop && !options.navRewind) {
this._controls.$previous.toggleClass('disabled', index <= 0);
this._controls.$next.toggleClass('disabled', index >= this._core.maximum());
}
this._controls.$previous.toggle(options.nav);
this._controls.$next.toggle(options.nav);
if (options.dots) {
difference = this._pages.length - this._controls.$indicators.children().length;
if (options.dotData && difference !== 0) {
for (i = 0; i < this._controls.$indicators.children().length; i++) {
html += this._templates[this._core.relative(i)];
}
this._controls.$indicators.html(html);
} else if (difference > 0) {
html = new Array(difference + 1).join(this._templates[0]);
this._controls.$indicators.append(html);
} else if (difference < 0) {
this._controls.$indicators.children().slice(difference).remove();
}
this._controls.$indicators.find('.active').removeClass('active');
this._controls.$indicators.children().eq($.inArray(this.current(), this._pages)).addClass('active');
}
this._controls.$indicators.toggle(options.dots);
}
/**
* Extends event data.
* @protected
* @param {Event} event - The event object which gets thrown.
*/
Navigation.prototype.onTrigger = function(event) {
var settings = this._core.settings;
event.page = {
index: $.inArray(this.current(), this._pages),
count: this._pages.length,
size: settings && (settings.center || settings.autoWidth || settings.dotData
? 1 : settings.dotsEach || settings.items)
};
}
/**
* Gets the current page position of the carousel2.
* @protected
* @returns {Number}
*/
Navigation.prototype.current = function() {
var index = this._core.relative(this._core.current());
return $.grep(this._pages, function(o) {
return o.start <= index && o.end >= index;
}).pop();
}
/**
* Gets the current succesor/predecessor position.
* @protected
* @returns {Number}
*/
Navigation.prototype.getPosition = function(successor) {
var position, length,
options = this._core.settings;
if (options.slideBy == 'page') {
position = $.inArray(this.current(), this._pages);
length = this._pages.length;
successor ? ++position : --position;
position = this._pages[((position % length) + length) % length].start;
} else {
position = this._core.relative(this._core.current());
length = this._core.items().length;
successor ? position += options.slideBy : position -= options.slideBy;
}
return position;
}
/**
* Slides to the next item or page.
* @public
* @param {Number} [speed=false] - The time in milliseconds for the transition.
*/
Navigation.prototype.next = function(speed) {
$.proxy(this._overrides.to, this._core)(this.getPosition(true), speed);
}
/**
* Slides to the previous item or page.
* @public
* @param {Number} [speed=false] - The time in milliseconds for the transition.
*/
Navigation.prototype.prev = function(speed) {
$.proxy(this._overrides.to, this._core)(this.getPosition(false), speed);
}
/**
* Slides to the specified item or page.
* @public
* @param {Number} position - The position of the item or page.
* @param {Number} [speed] - The time in milliseconds for the transition.
* @param {Boolean} [standard=false] - Whether to use the standard behaviour or not.
*/
Navigation.prototype.to = function(position, speed, standard) {
var length;
if (!standard) {
length = this._pages.length;
$.proxy(this._overrides.to, this._core)(this._pages[((position % length) + length) % length].start, speed);
} else {
$.proxy(this._overrides.to, this._core)(position, speed);
}
}
$.fn.owlCarousel2.Constructor.Plugins.Navigation = Navigation;
})(window.Zepto || window.jQuery, window, document);
/**
* Hash Plugin
* @version 2.0.0
* @author Artus Kolanowski
* @license The MIT License (MIT)
*/
;(function($, window, document, undefined) {
'use strict';
/**
* Creates the hash plugin.
* @class The Hash Plugin
* @param {Owl2} carousel2 - The Owl2 Carousel
*/
var Hash = function(carousel2) {
/**
* Reference to the core.
* @protected
* @type {Owl2}
*/
this._core = carousel2;
/**
* Hash table for the hashes.
* @protected
* @type {Object}
*/
this._hashes = {};
/**
* The carousel2 element.
* @type {jQuery}
*/
this.$element = this._core.$element;
/**
* All event handlers.
* @protected
* @type {Object}
*/
this._handlers = {
'initialized.owl.carousel2': $.proxy(function() {
if (this._core.settings.startPosition == 'URLHash') {
$(window).trigger('hashchange.owl.navigation');
}
}, this),
'prepared.owl.carousel2': $.proxy(function(e) {
var hash = $(e.content).find('[data-hash]').andSelf('[data-hash]').attr('data-hash');
this._hashes[hash] = e.content;
}, this)
};
// set default options
this._core.options = $.extend({}, Hash.Defaults, this._core.options);
// register the event handlers
this.$element.on(this._handlers);
// register event listener for hash navigation
$(window).on('hashchange.owl.navigation', $.proxy(function() {
var hash = window.location.hash.substring(1),
items = this._core.$stage.children(),
position = this._hashes[hash] && items.index(this._hashes[hash]) || 0;
if (!hash) {
return false;
}
this._core.to(position, false, true);
}, this));
}
/**
* Default options.
* @public
*/
Hash.Defaults = {
URLhashListener: false
}
/**
* Destroys the plugin.
* @public
*/
Hash.prototype.destroy = function() {
var handler, property;
$(window).off('hashchange.owl.navigation');
for (handler in this._handlers) {
this._core.$element.off(handler, this._handlers[handler]);
}
for (property in Object.getOwnPropertyNames(this)) {
typeof this[property] != 'function' && (this[property] = null);
}
}
$.fn.owlCarousel2.Constructor.Plugins.Hash = Hash;
})(window.Zepto || window.jQuery, window, document); |
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([ 'module', 'angular' ], function (module, angular) {
module.exports = factory(angular);
});
} else if (typeof module === 'object') {
module.exports = factory(require('angular'));
} else {
if (!root.mp) {
root.mp = {};
}
root.mp.datePicker = factory(root.angular);
}
}(this, function (angular) {
'use strict';
return angular.module('mp.datePicker', []).directive('datePicker', [ '$window', '$locale', function ($window, $locale) {
// Introduce custom elements for IE8
$window.document.createElement('date-picker');
var tmpl = ''
+ '<div class="angular-date-picker">'
+ ' <div class="_month">'
+ ' <button type="button" class="_previous" ng-click="changeMonthBy(-1)">«</button>'
+ ' <span>{{ months[month] }}</span> {{ year }}'
+ ' <button type="button" class="_next" ng-click="changeMonthBy(1)">»</button>'
+ ' </div>'
+ ' <div class="_days" ng-click="pickDay($event)">'
+ ' <div class="_day-of-week" ng-repeat="dayOfWeek in daysOfWeek" title="{{ dayOfWeek.fullName }}">{{ dayOfWeek.formattedDay || dayOfWeek.firstLetter }}</div>'
+ ' <div class="_day -padding" ng-repeat="day in leadingDays" data-month-offset="-1" ng-class="{ \'-disabled\': day.disabled }">{{ day.day }}</div>'
+ ' <div class="_day" ng-repeat="day in days" ng-class="{ \'-disabled\': day.disabled, \'-selected\': (day.day === selectedDay), \'-today\': (day.day === today) }">{{ day.day }}</div>'
+ ' <div class="_day -padding" ng-repeat="day in trailingDays" data-month-offset="1" ng-class="{ \'-disabled\': day.disabled }">{{ day.day }}</div>'
+ ' </div>'
+ '</div>'
;
return {
restrict: 'AE',
template: tmpl,
replace: true,
require: '?ngModel',
scope: {
onDateSelected: '&',
formatDate: '=', // @todo breaking change: change to & to allow use of date filter directly
parseDate: '=', // @todo change to &
allowDate: '=',
formatDayOfWeek: '='
},
link: function ($scope, $element, $attributes, ngModel) {
var selectedDate = null,
days = [], // Slices of this are used for ngRepeat
months = $locale.DATETIME_FORMATS.STANDALONEMONTH.slice(0),
daysOfWeek = [],
firstDayOfWeek = typeof $locale.DATETIME_FORMATS.FIRSTDAYOFWEEK === 'number'
? ($locale.DATETIME_FORMATS.FIRSTDAYOFWEEK + 1) % 7
: 0;
for (var i = 1; i <= 31; i++) {
days.push(i);
}
for (var i = 0; i < 7; i++) {
var day = $locale.DATETIME_FORMATS.DAY[(i + firstDayOfWeek) % 7];
daysOfWeek.push({
fullName: day,
firstLetter: day.substr(0, 1),
formattedDay: $scope.formatDayOfWeek(day)
});
}
$scope.months = months;
$scope.daysOfWeek = daysOfWeek;
function setYearAndMonth(date) {
$scope.year = date.getFullYear();
$scope.month = date.getMonth();
var now = new Date();
$scope.today = now.getFullYear() === $scope.year && now.getMonth() === $scope.month
? now.getDate()
: null;
$scope.selectedDay = selectedDate
&& selectedDate.getFullYear() === $scope.year
&& selectedDate.getMonth() === $scope.month
? selectedDate.getDate()
: null;
var firstDayOfMonth = new Date($scope.year, $scope.month, 1),
lastDayOfMonth = new Date($scope.year, $scope.month + 1, 0),
lastDayOfPreviousMonth = new Date($scope.year, $scope.month, 0),
daysInMonth = lastDayOfMonth.getDate(),
daysInLastMonth = lastDayOfPreviousMonth.getDate(),
dayOfWeek = firstDayOfMonth.getDay(),
leadingDays = (dayOfWeek - firstDayOfWeek + 7) % 7 || 7, // Ensure there are always leading days to give context
checkIfDateIsAllowed = $scope.allowDate !== undefined && typeof $scope.allowDate === 'function';
$scope.leadingDays = days.slice(- leadingDays - (31 - daysInLastMonth), daysInLastMonth);
$scope.days = days.slice(0, daysInMonth);
// Ensure a total of 6 rows to maintain height consistency
$scope.trailingDays = days.slice(0, 6 * 7 - (leadingDays + daysInMonth));
// Add disabled property to days
$scope.leadingDays = getDaysWithDisabledProperty($scope.leadingDays, -1);
$scope.days = getDaysWithDisabledProperty($scope.days, 0);
$scope.trailingDays = getDaysWithDisabledProperty($scope.trailingDays, 1);
function getDaysWithDisabledProperty(days, monthOffset) {
return days.map(function(day) {
if (!checkIfDateIsAllowed) {
return {day: day, disabled: false};
}
return {day: day, disabled: !$scope.allowDate(new Date($scope.year, $scope.month + monthOffset, day))};
});
}
}
// Default to current year and month
setYearAndMonth(new Date());
if (ngModel) {
ngModel.$render = function () {
selectedDate = ngModel.$viewValue
? $scope.parseDate
? $scope.parseDate(ngModel.$viewValue)
: new Date(ngModel.$viewValue)
: null;
if (selectedDate && !isNaN(selectedDate)) {
setYearAndMonth(selectedDate);
} else {
// Bad input, stay on current year and month, but reset selected date
$scope.selectedDay = null;
}
};
}
$scope.changeMonthBy = function (amount) {
var date = new Date($scope.year, $scope.month + amount, 1);
setYearAndMonth(date);
};
$scope.pickDay = function (evt) {
var target = angular.element(evt.target);
if (target.hasClass('_day')) {
var monthOffset = target.attr('data-month-offset');
if (monthOffset) {
$scope.changeMonthBy(parseInt(monthOffset, 10));
}
var day = parseInt(target.text(), 10);
$scope.selectedDay = day;
selectedDate = new Date($scope.year, $scope.month, day);
if (ngModel) {
ngModel.$setViewValue(
$scope.formatDate
? $scope.formatDate(selectedDate)
: selectedDate.toLocaleDateString()
);
}
$scope.onDateSelected();
}
};
}
};
}])
.name; // pass back as dependency name
})); |
angular.module('ippon').controller('HomePageController',['$scope','$stateParams',
function($scope,$stateParams){
}]);
|
import extend from 'extend'
import rump from 'rump'
import webpack from './webpack'
import {aliases, glob, loaders} from './file'
const dropConsoleKey = 'drop_console',
dropDebuggerKey = 'drop_debugger',
{configs} = rump
rebuild()
export function rebuild() {
configs.main.globs = extend(true, {build: {
scripts: glob,
tests: `**/${glob.replace(/^\*\./, '*_test.')}`,
}}, configs.main.globs)
configs.main.paths = extend(true, {
source: {scripts: 'scripts'},
destination: {scripts: 'scripts'},
}, configs.main.paths)
configs.main.scripts = extend(true, {
aliases: [...aliases],
loaders: [...loaders],
minify: configs.main.environment === 'production',
sourceMap: configs.main.environment === 'development',
macros: {
'process.env.NODE_ENV': JSON.stringify(configs.main.environment),
},
}, configs.main.scripts)
configs.main.scripts.uglifyjs = extend(true, {
output: {comments: false},
compress: {[dropConsoleKey]: true, [dropDebuggerKey]: true},
}, configs.main.scripts.uglifyjs)
configs.main.scripts.webpack = webpack()
}
|
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Module dependencies.
var util = require('util');
var extend = require('extend');
var _ = require('underscore');
var azureCommon = require('./../../common/common.core');
var azureutil = azureCommon.util;
var validate = azureCommon.validate;
var SR = azureCommon.SR;
var StorageServiceClient = azureCommon.StorageServiceClient;
var SharedKeyTable = require('./internal/sharedkeytable');
var RequestHandler = require('./internal/requesthandler');
var TableQuery = require('./tablequery');
var WebResource = azureCommon.WebResource;
var Constants = azureCommon.Constants;
var QueryStringConstants = Constants.QueryStringConstants;
var HeaderConstants = Constants.HeaderConstants;
var TableConstants = Constants.TableConstants;
var RequestLocationMode = Constants.RequestLocationMode;
// Models requires
var TableResult = require('./models/tableresult');
var entityResult = require('./models/entityresult');
var BatchResult = require('./models/batchresult');
var ServiceStatsParser = azureCommon.ServiceStatsParser;
var AclResult = azureCommon.AclResult;
var TableUtilities = require('./tableutilities');
/**
* Creates a new TableService object.
* If no connection string or storageaccount and storageaccesskey are provided,
* the AZURE_STORAGE_CONNECTION_STRING or AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY environment variables will be used.
* @class
* The TableService object allows you to peform management operations with the Microsoft Azure Table Service.
* The Table Service stores data in rows of key-value pairs. A table is composed of multiple rows, and each row
* contains key-value pairs. There is no schema, so each row in a table may store a different set of keys.
*
* For more information on the Table Service, as well as task focused information on using it from a Node.js application, see
* [How to Use the Table Service from Node.js](http://azure.microsoft.com/en-us/documentation/articles/storage-nodejs-how-to-use-table-storage/).
* The following defaults can be set on the Table service.
* defaultTimeoutIntervalInMs The default timeout interval, in milliseconds, to use for request made via the Table service.
* defaultClientRequestTimeoutInMs The default timeout of client requests, in milliseconds, to use for the request made via the Table service.
* defaultMaximumExecutionTimeInMs The default maximum execution time across all potential retries, for requests made via the Table service.
* defaultLocationMode The default location mode for requests made via the Table service.
* defaultPayloadFormat The default payload format for requests made via the Table service.
* useNagleAlgorithm Determines whether the Nagle algorithm is used for requests made via the Table service.; true to use the
* Nagle algorithm; otherwise, false. The default value is false.
* @constructor
* @extends {StorageServiceClient}
*
* @param {string} [storageAccountOrConnectionString] The storage account or the connection string.
* @param {string} [storageAccessKey] The storage access key.
* @param {string|object} [host] The host address. To define primary only, pass a string.
* Otherwise 'host.primaryHost' defines the primary host and 'host.secondaryHost' defines the secondary host.
* @param {string} [sasToken] The Shared Access Signature token.
* @param {string} [endpointSuffix] The endpoint suffix.
*/
function TableService(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix) {
var storageServiceSettings = StorageServiceClient.getStorageSettings(storageAccountOrConnectionString, storageAccessKey, host, sasToken, endpointSuffix);
TableService['super_'].call(this,
storageServiceSettings._name,
storageServiceSettings._key,
storageServiceSettings._tableEndpoint,
storageServiceSettings._usePathStyleUri,
storageServiceSettings._sasToken);
if (this.anonymous) {
throw new Error(SR.ANONYMOUS_ACCESS_BLOBSERVICE_ONLY);
}
if(this.storageAccount && this.storageAccessKey) {
this.storageCredentials = new SharedKeyTable(this.storageAccount, this.storageAccessKey, this.usePathStyleUri);
}
this.defaultPayloadFormat = TableUtilities.PayloadFormat.MINIMAL_METADATA;
}
util.inherits(TableService, StorageServiceClient);
// Table service methods
/**
* Gets the service stats for a storage account’s Table service.
*
* @this {TableService}
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `[result]{@link ServiceStats}` will contain the stats.
* `response` will contain information related to this operation.
*/
TableService.prototype.getServiceStats = function (optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('getServiceStats', function (v) {
v.callback(callback);
});
var options = extend(true, {}, userOptions);
options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
var webResource = WebResource.get()
.withQueryOption(QueryStringConstants.COMP, 'stats')
.withQueryOption(QueryStringConstants.RESTYPE, 'service');
var processResponseCallback = function (responseObject, next) {
responseObject.serviceStatsResult = null;
if (!responseObject.error) {
responseObject.serviceStatsResult = ServiceStatsParser.parse(responseObject.response.body.StorageServiceStats);
}
// function to be called after all filters
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.serviceStatsResult, returnObject.response);
};
// call the first filter
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Gets the properties of a storage account’s Table service, including Azure Storage Analytics.
*
* @this {TableService}
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `[result]{@link ServiceProperties}` will contain the properties.
* `response` will contain information related to this operation.
*/
TableService.prototype.getServiceProperties = function (optionsOrCallback, callback) {
return this.getAccountServiceProperties(optionsOrCallback, callback);
};
/**
* Sets the properties of a storage account’s Table service, including Azure Storage Analytics.
* You can also use this operation to set the default request version for all incoming requests that do not have a version specified.
*
* @this {TableService}
* @param {object} serviceProperties The service properties.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback `error` will contain information if an error occurs;
* `response` will contain information related to this operation.
*/
TableService.prototype.setServiceProperties = function (serviceProperties, optionsOrCallback, callback) {
return this.setAccountServiceProperties(serviceProperties, optionsOrCallback, callback);
};
/**
* Lists a segment containing a collection of table items under the specified account.
*
* @this {TableService}
* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object} [options] The create options or callback function.
* @param {int} [options.maxResults] Specifies the maximum number of tables to return per call to Azure ServiceClient.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {string} [options.payloadFormat] The payload format to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain `entries` and `continuationToken`.
* `entries` gives a list of tables and the `continuationToken` is used for the next listing operation.
* `response` will contain information related to this operation.
*/
TableService.prototype.listTablesSegmented = function (currentToken, optionsOrCallback, callback) {
this.listTablesSegmentedWithPrefix(null /* prefix */, currentToken, optionsOrCallback, callback);
};
/**
* Lists a segment containing a collection of table items under the specified account.
*
* @this {TableService}
* @param {string} prefix The prefix of the table name.
* @param {object} currentToken A continuation token returned by a previous listing operation. Please use 'null' or 'undefined' if this is the first operation.
* @param {object} [options] The create options or callback function.
* @param {int} [options.maxResults] Specifies the maximum number of tables to return per call to Azure ServiceClient.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {string} [options.payloadFormat] The payload format to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain `entries` and `continuationToken`.
* `entries` gives a list of tables and the `continuationToken` is used for the next listing operation.
* `response` will contain information related to this operation.
*/
TableService.prototype.listTablesSegmentedWithPrefix = function (prefix, currentToken, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('listTables', function (v) {
v.callback(callback);
});
var options = extend(true, {}, userOptions);
options.payloadFormat = options.payloadFormat || this.defaultPayloadFormat;
var webResource = WebResource.get(TableConstants.TABLE_SERVICE_TABLE_NAME);
RequestHandler.setTableRequestHeadersAndBody(webResource, null, options.payloadFormat);
if(!azureutil.objectIsNull(currentToken)) {
webResource.withQueryOption(TableConstants.NEXT_TABLE_NAME, currentToken.nextTableName);
}
if(!azureutil.objectIsNull(prefix)) {
var query = new TableQuery()
.where(TableConstants.TABLE_NAME + ' >= ?', prefix)
.and(TableConstants.TABLE_NAME + ' < ?', prefix + '{');
webResource.withQueryOption(QueryStringConstants.FILTER, query.toQueryObject().$filter);
}
if(!azureutil.objectIsNull(options.maxResults)) {
var query = new TableQuery().top(options.maxResults);
webResource.withQueryOption(QueryStringConstants.TOP, query.toQueryObject().$top);
}
options.requestLocationMode = azureutil.getNextListingLocationMode(currentToken);
var processResponseCallback = function (responseObject, next) {
responseObject.listTablesResult = null;
if (!responseObject.error) {
responseObject.listTablesResult = {
entries: null,
continuationToken: null
};
responseObject.listTablesResult.entries = TableResult.parse(responseObject.response);
if (responseObject.response.headers[TableConstants.CONTINUATION_NEXT_TABLE_NAME] &&
!azureutil.objectIsEmpty(responseObject.response.headers[TableConstants.CONTINUATION_NEXT_TABLE_NAME])) {
responseObject.listTablesResult.continuationToken = {
nextTableName: null,
targetLocation: null
};
responseObject.listTablesResult.continuationToken.nextTableName = responseObject.response.headers[TableConstants.CONTINUATION_NEXT_TABLE_NAME];
responseObject.listTablesResult.continuationToken.targetLocation = responseObject.targetLocation;
}
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.listTablesResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
// Table Methods
/**
* Gets the table's ACL.
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the ACL information for the table. See `[AccessPolicy]{@link AccessPolicy}` for detailed information.
* `response` will contain information related to this operation.
*/
TableService.prototype.getTableAcl = function (table, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('getTableAcl', function (v) {
v.string(table, 'table');
v.tableNameIsValid(table);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
options.requestLocationMode = Constants.RequestLocationMode.PRIMARY_OR_SECONDARY;
var webResource = WebResource.get(table)
.withQueryOption(QueryStringConstants.COMP, 'acl');
var processResponseCallback = function (responseObject, next) {
responseObject.tableResult = null;
if (!responseObject.error) {
responseObject.tableResult = new TableResult(table);
responseObject.tableResult.signedIdentifiers = AclResult.parse(responseObject.response.body);
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.tableResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Updates the table's ACL.
*
* @this {TableService}
* @param {string} table The table name.
* @param {Object.<string, AccessPolicy>} signedIdentifiers The table ACL settings. See `[AccessPolicy]{@link AccessPolicy}` for detailed information.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain information for the table.
* `response` will contain information related to this operation.
*/
TableService.prototype.setTableAcl = function (table, signedIdentifiers, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('setTableAcl', function (v) {
v.string(table, 'table');
v.tableNameIsValid(table);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var policies = null;
if (signedIdentifiers) {
if(_.isArray(signedIdentifiers)) {
throw new TypeError(SR.INVALID_SIGNED_IDENTIFIERS);
}
policies = AclResult.serialize(signedIdentifiers);
}
var webResource = WebResource.put(table)
.withQueryOption(QueryStringConstants.COMP, 'acl')
.withHeader(HeaderConstants.CONTENT_LENGTH, !azureutil.objectIsNull(policies) ? Buffer.byteLength(policies) : 0)
.withBody(policies);
var processResponseCallback = function (responseObject, next) {
responseObject.tableResult = null;
if (!responseObject.error) {
// SetTableAcl doesn't actually return anything in the response
responseObject.tableResult = new TableResult(table);
if (signedIdentifiers) {
responseObject.tableResult.signedIdentifiers = signedIdentifiers;
}
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.tableResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, webResource.body, options, processResponseCallback);
};
/**
* Retrieves a shared access signature token.
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} sharedAccessPolicy The shared access policy.
* @param {string} [sharedAccessPolicy.Id] The signed identifier.
* @param {object} [sharedAccessPolicy.AccessPolicy.Permissions] The permission type.
* @param {date|string} [sharedAccessPolicy.AccessPolicy.Start] The time at which the Shared Access Signature becomes valid (The UTC value will be used).
* @param {date|string} [sharedAccessPolicy.AccessPolicy.Expiry] The time at which the Shared Access Signature becomes expired (The UTC value will be used).
* @param {string} [sharedAccessPolicy.AccessPolicy.IPAddressOrRange] An IP address or a range of IP addresses from which to accept requests. When specifying a range, note that the range is inclusive.
* @param {string} [sharedAccessPolicy.AccessPolicy.Protocols] The protocols permitted for a request made with the account SAS.
* Possible values are both HTTPS and HTTP (https,http) or HTTPS only (https). The default value is https,http.
* @param {string} [sharedAccessPolicy.AccessPolicy.StartPk] The starting Partition Key for which the SAS will be valid.
* @param {string} [sharedAccessPolicy.AccessPolicy.EndPk] The ending Partition Key for which the SAS will be valid.
* @param {string} [sharedAccessPolicy.AccessPolicy.StartRk] The starting Row Key for which the SAS will be valid.
* @param {string} [sharedAccessPolicy.AccessPolicy.EndRk] The ending Row Key for which the SAS will be valid.
* @return {object} An object with the shared access signature.
*/
TableService.prototype.generateSharedAccessSignature = function (table, sharedAccessPolicy) {
// check if the TableService is able to generate a shared access signature
if (!this.storageCredentials || !this.storageCredentials.generateSignedQueryString) {
throw new Error(SR.CANNOT_CREATE_SAS_WITHOUT_ACCOUNT_KEY);
}
validate.validateArgs('generateSharedAccessSignature', function (v) {
v.string(table, 'table');
v.tableNameIsValid(table);
v.object(sharedAccessPolicy, 'sharedAccessPolicy');
});
var lowerCasedTableName = table.toLowerCase();
return this.storageCredentials.generateSignedQueryString(Constants.ServiceType.Table, lowerCasedTableName, sharedAccessPolicy, null, { tableName: lowerCasedTableName });
};
/**
* Checks whether or not a table exists on the service.
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the table information including `exists` boolean member.
* `response` will contain information related to this operation.
*/
TableService.prototype.doesTableExist = function (table, optionsOrCallback, callback) {
this._doesTableExist(table, false, optionsOrCallback, callback);
};
/**
* Creates a new table within a storage account.
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the new table information.
* `response` will contain information related to this operation.
*/
TableService.prototype.createTable = function (table, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('createTable', function (v) {
v.string(table, 'table');
v.tableNameIsValid(table);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var tableDescriptor = TableResult.serialize(table);
var webResource = WebResource.post('Tables')
.withHeader(HeaderConstants.PREFER, HeaderConstants.PREFER_NO_CONTENT);
RequestHandler.setTableRequestHeadersAndBody(webResource, tableDescriptor, this.defaultPayloadFormat);
var processResponseCallback = function (responseObject, next) {
responseObject.tableResponse = {};
responseObject.tableResponse.isSuccessful = responseObject.error ? false : true;
responseObject.tableResponse.statusCode = responseObject.response.statusCode;
if (!responseObject.error) {
responseObject.tableResponse.TableName = table;
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.tableResponse, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, webResource.body, options, processResponseCallback);
};
/**
* Creates a new table within a storage account if it does not exists.
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* `result` will contain the table information including `created` boolean member
* `response` will contain information related to this operation.
*
* @example
* var azure = require('azure-storage');
* var tableService = azure.createTableService();
* tableService.createTableIfNotExists('tasktable', function(error) {
* if(!error) {
* // Table created or exists
* }
* });
*/
TableService.prototype.createTableIfNotExists = function (table, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('createTableIfNotExists', function (v) {
v.string(table, 'table');
v.tableNameIsValid(table);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var self = this;
self._doesTableExist(table, true, options, function(error, result, response) {
var exists = result.exists;
result.created = false;
delete result.exists;
if (error) {
callback(error, result, response);
} else if (exists) {
response.isSuccessful = true;
callback(error, result, response);
} else {
self.createTable(table, options, function(createError, createResult, response) {
if (!createError) {
createResult.created = true;
}
else if (createError && createError.statusCode === Constants.HttpConstants.HttpResponseCodes.Conflict && createError.code === Constants.TableErrorCodeStrings.TABLE_ALREADY_EXISTS) {
createError = null;
createResult.created = false;
createResult.isSuccessful = true;
}
callback(createError, createResult, response);
});
}
});
};
/**
* Deletes a table from a storage account.
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback `error` will contain information if an error occurs;
* `response` will contain information related to this operation.
*/
TableService.prototype.deleteTable = function (table, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('deleteTable', function (v) {
v.string(table, 'table');
v.tableNameIsValid(table);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var webResource = WebResource.del('Tables(\'' + table + '\')');
RequestHandler.setTableRequestHeadersAndBody(webResource, null, this.defaultPayloadFormat);
var processResponseCallback = function (responseObject, next) {
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Deletes a table from a storage account, if it exists.
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* `result` will be `true` if table was deleted, false otherwise
* `response` will contain information related to this operation.
*/
TableService.prototype.deleteTableIfExists = function (table, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('deleteTableIfExists', function (v) {
v.string(table, 'table');
v.tableNameIsValid(table);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
var self = this;
self._doesTableExist(table, true, options, function(error, result, response) {
if (error) {
callback(error, result.exists, response);
} else if (!result.exists) {
response.isSuccessful = true;
callback(error, false, response);
} else {
self.deleteTable(table, options, function(deleteError, deleteResponse) {
var deleted;
if (!deleteError) {
deleted = true;
} else if (deleteError && deleteError.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound && deleteError.code === Constants.StorageErrorCodeStrings.RESOURCE_NOT_FOUND) {
deleted = false;
deleteError = null;
deleteResponse.isSuccessful = true;
}
callback(deleteError, deleted, deleteResponse);
});
}
});
};
// Table Entity Methods
/**
* Queries data in a table. To retrieve a single entity by partition key and row key, use retrieve entity.
*
* @this {TableService}
* @param {string} table The table name.
* @param {TableQuery} tableQuery The query to perform. Use null, undefined, or new TableQuery() to get all of the entities in the table.
* @param {object} currentToken A continuation token returned by a previous listing operation.
* Please use 'null' or 'undefined' if this is the first operation.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {string} [options.payloadFormat] The payload format to use for the request.
* @param {bool} [options.autoResolveProperties] If true, guess at all property types.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {Function(entity)} [options.entityResolver] The entity resolver. Given a single entity returned by the query, returns a modified object which is added to
* the entities array.
* @param {TableService~propertyResolver} [options.propertyResolver] The property resolver. Given the partition key, row key, property name, property value,
* and the property Edm type if given by the service, returns the Edm type of the property.
* @param {TableService~queryResponse} callback `error` will contain information if an error occurs;
* otherwise `entities` will contain the entities returned by the query.
* If more matching entities exist, and could not be returned,
* `queryResultContinuation` will contain a continuation token that can be used
* to retrieve the next set of results.
* `response` will contain information related to this operation.
*
* The logic for returning entity types can get complicated. Here is the algorithm used:
* ```
* var propertyType;
*
* if (propertyResovler) { // If the caller provides a propertyResolver in the options, use it
* propertyType = propertyResolver(partitionKey, rowKey, propertyName, propertyValue, propertyTypeFromService);
* } else if (propertyTypeFromService) { // If the service provides us a property type, use it. See below for an explanation of when this will and won't occur.
* propertyType = propertyTypeFromService;
* } else if (autoResolveProperties) { // If options.autoResolveProperties is set to true
* if (javascript type is string) { // See below for an explanation of how and why autoResolveProperties works as it does.
* propertyType = 'Edm.String';
* } else if (javascript type is boolean) {
* propertyType = 'Edm.Boolean';
* }
* }
*
* if (propertyType) {
* // Set the property type on the property.
* } else {
* // Property gets no EdmType.
* }
* ```
* Notes:
*
* * The service only provides a type if JsonFullMetadata or JsonMinimalMetadata is used, and if the type is Int64, Guid, Binary, or DateTime.
* * Explanation of autoResolveProperties:
* * String gets correctly resolved to 'Edm.String'.
* * Int64, Guid, Binary, and DateTime all get resolved to 'Edm.String.' This only happens if JsonNoMetadata is used (otherwise the service will provide the propertyType in a prior step).
* * Boolean gets correctly resolved to 'Edm.Boolean'.
* * For both Int32 and Double, no type information is returned, even in the case of autoResolveProperties = true. This is due to an
* inability to distinguish between the two in certain cases.
*
* @example
* var azure = require('azure-storage');
* var tableService = azure.createTableService();
* // tasktable should already exist and have entities
*
* // returns all entities in tasktable, and a continuation token for the next page of results if necessary
* tableService.queryEntities('tasktable', null, null \/*currentToken*\/, function(error, result) {
* if(!error) {
* var entities = result.entities;
* // do stuff with the returned entities if there are any
* }
* });
*
* // returns field1 and field2 of the entities in tasktable, and a continuation token for the next page of results if necessary
* var tableQuery = new TableQuery().select('field1', 'field2');
* tableService.queryEntities('tasktable', tableQuery, null \/*currentToken*\/, function(error, result) {
* if(!error) {
* var entities = result.entities;
* // do stuff with the returned entities if there are any
* }
* });
*/
TableService.prototype.queryEntities = function (table, tableQuery, currentToken, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('queryEntities', function (v) {
v.string(table, 'table');
v.callback(callback);
});
var options = extend(true, {}, userOptions);
options.payloadFormat = options.payloadFormat || this.defaultPayloadFormat;
var webResource = WebResource.get(table);
RequestHandler.setTableRequestHeadersAndBody(webResource, null, options.payloadFormat);
if (tableQuery) {
var queryString = tableQuery.toQueryObject();
Object.keys(queryString).forEach(function (queryStringName) {
webResource.withQueryOption(queryStringName, queryString[queryStringName]);
});
}
if(!azureutil.objectIsNull(currentToken)) {
webResource.withQueryOption(TableConstants.NEXT_PARTITION_KEY, currentToken.nextPartitionKey);
webResource.withQueryOption(TableConstants.NEXT_ROW_KEY, currentToken.nextRowKey);
}
options.requestLocationMode = azureutil.getNextListingLocationMode(currentToken);
var processResponseCallback = function (responseObject, next) {
responseObject.queryEntitiesResult = null;
if (!responseObject.error) {
responseObject.queryEntitiesResult = {
entries: null,
continuationToken: null
};
// entries
responseObject.queryEntitiesResult.entries = entityResult.parseQuery(responseObject.response, options.autoResolveProperties, options.propertyResolver, options.entityResolver);
// continuation token
var continuationToken = {
nextPartitionKey: responseObject.response.headers[TableConstants.CONTINUATION_NEXT_PARTITION_KEY],
nextRowKey: responseObject.response.headers[TableConstants.CONTINUATION_NEXT_ROW_KEY],
targetLocation: responseObject.targetLocation
};
if (!azureutil.IsNullOrEmptyOrUndefinedOrWhiteSpace(continuationToken.nextPartitionKey)) {
responseObject.queryEntitiesResult.continuationToken = continuationToken;
}
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.queryEntitiesResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Retrieves an entity from a table.
*
* @this {TableService}
* @param {string} table The table name.
* @param {string} partitionKey The partition key.
* @param {string} rowKey The row key.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {string} [options.payloadFormat] The payload format to use for the request.
* @param {bool} [options.autoResolveProperties] If true, guess at all property types.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {TableService~propertyResolver} [options.propertyResolver] The property resolver. Given the partition key, row key, property name, property value,
* and the property Edm type if given by the service, returns the Edm type of the property.
* @param {Function(entity)} [options.entityResolver] The entity resolver. Given the single entity returned by the query, returns a modified object.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will be the matching entity.
* `response` will contain information related to this operation.
*
* The logic for returning entity types can get complicated. Here is the algorithm used:
* ```
* var propertyType;
*
* if (propertyResovler) { // If the caller provides a propertyResolver in the options, use it
* propertyType = propertyResolver(partitionKey, rowKey, propertyName, propertyValue, propertyTypeFromService);
* } else if (propertyTypeFromService) { // If the service provides us a property type, use it. See below for an explanation of when this will and won't occur.
* propertyType = propertyTypeFromService;
* } else if (autoResolveProperties) { // If options.autoResolveProperties is set to true
* if (javascript type is string) { // See below for an explanation of how and why autoResolveProperties works as it does.
* propertyType = 'Edm.String';
* } else if (javascript type is boolean) {
* propertyType = 'Edm.Boolean';
* }
* }
*
* if (propertyType) {
* // Set the property type on the property.
* } else {
* // Property gets no EdmType.
* }
* ```
* Notes:
*
* * The service only provides a type if JsonFullMetadata or JsonMinimalMetadata is used, and if the type is Int64, Guid, Binary, or DateTime.
* * Explanation of autoResolveProperties:
* * String gets correctly resolved to 'Edm.String'.
* * Int64, Guid, Binary, and DateTime all get resolved to 'Edm.String.' This only happens if JsonNoMetadata is used (otherwise the service will provide the propertyType in a prior step).
* * Boolean gets correctly resolved to 'Edm.Boolean'.
* * For both Int32 and Double, no type information is returned, even in the case of autoResolveProperties = true. This is due to an
* inability to distinguish between the two in certain cases.
*
* @example
* var azure = require('azure-storage');
* var tableService = azure.createTableService();
* tableService.retrieveEntity('tasktable', 'tasksSeattle', '1', function(error, serverEntity) {
* if(!error) {
* // Entity available in serverEntity variable
* }
* });
*/
TableService.prototype.retrieveEntity = function (table, partitionKey, rowKey, optionsOrCallback, callback) {
var entityDescriptor = { PartitionKey: {_: partitionKey, $: 'Edm.String'},
RowKey: {_: rowKey, $: 'Edm.String'},
};
validate.validateArgs('retrieveEntity', function (v) {
v.stringAllowEmpty(partitionKey, 'partitionKey');
v.stringAllowEmpty(rowKey, 'rowKey');
});
this._performEntityOperation(TableConstants.Operations.RETRIEVE, table, entityDescriptor, optionsOrCallback, callback);
};
/**
* Inserts a new entity into a table.
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} entityDescriptor The entity descriptor.
* @param {object} [options] The request options.
* @param {string} [options.echoContent] Whether or not to return the entity upon a successful insert. Default to false.
* @param {string} [options.payloadFormat] The payload format to use in the response, if options.echoContent is true.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {TableService~propertyResolver} [options.propertyResolver] The property resolver. Only applied if echoContent is true. Given the partition key, row key, property name,
* property value, and the property Edm type if given by the service, returns the Edm type of the property.
* @param {Function(entity)} [options.entityResolver] The entity resolver. Only applied if echoContent is true. Given the single entity returned by the insert, returns
* a modified object.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the entity information.
* `response` will contain information related to this operation.
*
* @example
* var azure = require('azure-storage');
* var tableService = azure.createTableService();
* var task1 = {
* PartitionKey : {'_': 'tasksSeattle', '$':'Edm.String'},
* RowKey: {'_': '1', '$':'Edm.String'},
* Description: {'_': 'Take out the trash', '$':'Edm.String'},
* DueDate: {'_': new Date(2011, 12, 14, 12), '$':'Edm.DateTime'}
* };
* tableService.insertEntity('tasktable', task1, function(error) {
* if(!error) {
* // Entity inserted
* }
* });
*/
TableService.prototype.insertEntity = function (table, entityDescriptor, optionsOrCallback, callback) {
this._performEntityOperation(TableConstants.Operations.INSERT, table, entityDescriptor, optionsOrCallback, callback);
};
/**
* Inserts or updates a new entity into a table.
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} entityDescriptor The entity descriptor.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the entity information.
* `response` will contain information related to this operation.
*/
TableService.prototype.insertOrReplaceEntity = function (table, entityDescriptor, optionsOrCallback, callback) {
this._performEntityOperation(TableConstants.Operations.INSERT_OR_REPLACE, table, entityDescriptor, optionsOrCallback, callback);
};
/**
* Replaces an existing entity within a table. To replace conditionally based on etag, set entity['.metadata']['etag'].
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} entityDescriptor The entity descriptor.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the entity information.
* `response` will contain information related to this operation.
*/
TableService.prototype.replaceEntity = function (table, entityDescriptor, optionsOrCallback, callback) {
this._performEntityOperation(TableConstants.Operations.REPLACE, table, entityDescriptor, optionsOrCallback, callback);
};
/**
* Updates an existing entity within a table by merging new property values into the entity. To merge conditionally based on etag, set entity['.metadata']['etag'].
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} entityDescriptor The entity descriptor.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the entity information.
* response` will contain information related to this operation.
*/
TableService.prototype.mergeEntity = function (table, entityDescriptor, optionsOrCallback, callback) {
this._performEntityOperation(TableConstants.Operations.MERGE, table, entityDescriptor, optionsOrCallback, callback);
};
/**
* Inserts or updates an existing entity within a table by merging new property values into the entity.
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} entityDescriptor The entity descriptor.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain the entity information.
* `response` will contain information related to this operation.
*/
TableService.prototype.insertOrMergeEntity = function (table, entityDescriptor, optionsOrCallback, callback) {
this._performEntityOperation(TableConstants.Operations.INSERT_OR_MERGE, table, entityDescriptor, optionsOrCallback, callback);
};
/**
* Deletes an entity within a table. To delete conditionally based on etag, set entity['.metadata']['etag'].
*
* @this {TableService}
* @param {string} table The table name.
* @param {object} entityDescriptor The entity descriptor.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResponse} callback `error` will contain information if an error occurs;
* `response` will contain information related to this operation.
*/
TableService.prototype.deleteEntity = function (table, entityDescriptor, optionsOrCallback, callback) {
this._performEntityOperation(TableConstants.Operations.DELETE, table, entityDescriptor, optionsOrCallback, callback);
};
/**
* Executes the operations in the batch.
*
* @this {TableService}
* @param {string} table The table name.
* @param {TableBatch} batch The table batch to execute.
* @param {object} [options] The create options or callback function.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `result` will contain responses for each operation executed in the batch;
* `result.entity` will contain the entity information for each operation executed.
* `result.response` will contain the response for each operations executed.
* `response` will contain information related to this operation.
*/
TableService.prototype.executeBatch = function (table, batch, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('executeBatch', function (v) {
v.string(table, 'table');
v.tableNameIsValid(table);
v.object(batch, 'batch');
v.callback(callback);
});
if(!batch.hasOperations()) {
throw new Error(SR.EMPTY_BATCH);
}
var options = extend(true, {}, userOptions);
var batchResult = new BatchResult(this, table, batch.operations);
var webResource = batchResult.constructWebResource();
var body = batchResult.serialize();
webResource.withBody(body);
webResource.withHeader(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(body, 'utf8'));
var processResponseCallback = function (responseObject, next) {
var responseObjects = batchResult.parse(responseObject);
var noError = true;
// if the batch was unsuccesful, there will be a single response indicating the error
if (responseObjects && responseObjects.length > 0) {
responseObjects.forEach(function(item){
if(noError && !item.response.isSuccessful){
responseObject = item;
noError = false;
}
});
}
if (noError) {
responseObject.operationResponses = responseObjects;
}
var finalCallback = function (returnObject) {
// perform final callback
callback(returnObject.error, returnObject.operationResponses, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, webResource.body, options, processResponseCallback);
};
// Private methods
/**
* Checks whether or not a table exists on the service.
* @ignore
*
* @this {TableService}
* @param {string} table The table name.
* @param {string} primaryOnly If true, the request will be executed against the primary storage location.
* @param {object} [options] The request options.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {Function(error, result, response)} callback `error` will contain information if an error occurs;
* otherwise `result` will contain
* the table information including `exists` boolean member.
* `response` will contain information related to this operation.
*/
TableService.prototype._doesTableExist = function (table, primaryOnly, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('doesTableExist', function (v) {
v.string(table, 'table');
v.tableNameIsValid(table);
v.callback(callback);
});
var options = extend(true, {}, userOptions);
if(primaryOnly === false) {
options.requestLocationMode = RequestLocationMode.PRIMARY_OR_SECONDARY;
}
var webResource = WebResource.get('Tables(\'' + table + '\')');
webResource.withHeader(HeaderConstants.ACCEPT, this.defaultPayloadFormat);
var processResponseCallback = function (responseObject, next) {
responseObject.tableResult = {};
responseObject.tableResult.isSuccessful = responseObject.error ? false : true;
responseObject.tableResult.statusCode = responseObject.response === null || responseObject.response === undefined ? undefined : responseObject.response.statusCode;
responseObject.tableResult.TableName = table;
if(!responseObject.error){
responseObject.tableResult.exists = true;
} else if (responseObject.error && responseObject.error.statusCode === Constants.HttpConstants.HttpResponseCodes.NotFound) {
responseObject.error = null;
responseObject.tableResult.exists = false;
responseObject.response.isSuccessful = true;
}
var finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.tableResult, returnObject.response);
};
next(responseObject, finalCallback);
};
this.performRequest(webResource, null, options, processResponseCallback);
};
/**
* Performs a table operation.
*
* @this {TableService}
* @param {string} operation The operation to perform.
* @param {string} table The table name.
* @param {object} entityDescriptor The entity descriptor.
* @param {object} [options] The create options or callback function.
* @param {string} [options.echoContent] Whether or not to return the entity upon a successful insert. Default to false.
* @param {string} [options.payloadFormat] The payload format to use for the request.
* @param {LocationMode} [options.locationMode] Specifies the location mode used to decide which location the request should be sent to.
* Please see StorageUtilities.LocationMode for the possible values.
* @param {int} [options.timeoutIntervalInMs] The server timeout interval, in milliseconds, to use for the request.
* @param {int} [options.clientRequestTimeoutInMs] The timeout of client requests, in milliseconds, to use for the request.
* @param {int} [options.maximumExecutionTimeInMs] The maximum execution time, in milliseconds, across all potential retries, to use when making this request.
* The maximum execution time interval begins at the time that the client begins building the request. The maximum
* execution time is checked intermittently while performing requests, and before executing retries.
* @param {string} [options.clientRequestId] A string that represents the client request ID with a 1KB character limit.
* @param {bool} [options.useNagleAlgorithm] Determines whether the Nagle algorithm is used; true to use the Nagle algorithm; otherwise, false.
* The default value is false.
* @param {errorOrResult} callback `error` will contain information if an error occurs;
* otherwise `entity` will contain the entity information.
* `response` will contain information related to this operation.
* @ignore
*/
TableService.prototype._performEntityOperation = function (operation, table, entityDescriptor, optionsOrCallback, callback) {
var userOptions;
azureutil.normalizeArgs(optionsOrCallback, callback, function (o, c) { userOptions = o; callback = c; });
validate.validateArgs('entityOperation', function (v) {
v.string(table, 'table');
v.tableNameIsValid(table);
v.object(entityDescriptor, 'entityDescriptor');
if(typeof entityDescriptor.PartitionKey !== 'string') {
v.object(entityDescriptor.PartitionKey, 'entityDescriptor.PartitionKey');
v.stringAllowEmpty(entityDescriptor.PartitionKey._, 'entityDescriptor.PartitionKey._');
}
if(typeof entityDescriptor.RowKey !== 'string') {
v.object(entityDescriptor.RowKey, 'entityDescriptor.RowKey');
v.stringAllowEmpty(entityDescriptor.RowKey._, 'entityDescriptor.RowKey._');
}
v.callback(callback);
});
var options = extend(true, {}, userOptions);
options.payloadFormat = options.payloadFormat || this.defaultPayloadFormat;
var webResource = RequestHandler.constructEntityWebResource(operation, table, entityDescriptor, options);
var processResponseCallback = function (responseObject, next) {
var finalCallback;
if (operation === TableConstants.Operations.DELETE) {
finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.response);
};
} else {
responseObject.entityResponse = null;
if (!responseObject.error) {
responseObject.entityResponse = entityResult.parseEntity(responseObject.response, options.autoResolveProperties, options.propertyResolver, options.entityResolver);
}
finalCallback = function (returnObject) {
callback(returnObject.error, returnObject.entityResponse, returnObject.response);
};
}
next(responseObject, finalCallback);
};
this.performRequest(webResource, webResource.body, options, processResponseCallback);
};
/**
* Retrieves a table URL.
*
* @param {string} table The table name.
* @param {string} [sasToken] The Shared Access Signature token.
* @param {boolean} [primary] A boolean representing whether to use the primary or the secondary endpoint.
* @return {string} The formatted URL string.
* @example
* var azure = require('azure-storage');
* var tableService = azure.createTableService();
* var sharedAccessPolicy = {
* AccessPolicy: {
* Permissions: azure.TableUtilities.SharedAccessPermissions.QUERY,
* Start: startDate,
* Expiry: expiryDate
* },
* };
*
* var sasToken = tableService.generateSharedAccessSignature(table, sharedAccessPolicy);
* var sasUrl = tableService.getUrl(table, sasToken);
*/
TableService.prototype.getUrl = function (table, sasToken, primary) {
validate.validateArgs('getUrl', function (v) {
v.string(table, 'table');
v.tableNameIsValid(table);
});
return this._getUrl(table, sasToken, primary);
};
/**
* Given the partition key, row key, property name, property value,
* and the property Edm type if given by the service, returns the Edm type of the property.
* @typedef {function} TableService~propertyResolver
* @param {object} pk The partition key.
* @param {object} rk The row key.
* @param {string} name The property name.
* @param {object} value The property value.
* @param {string} type The EDM type.
*/
/**
* Returns entities matched by a query.
* @callback TableService~queryResponse
* @param {object} error If an error occurs, the error information.
* @param {object} entities The entities returned by the query.
* @param {object} queryResultContinuation If more matching entities exist, and could not be returned,
* a continuation token that can be used to retrieve more results.
* @param {object} response Information related to this operation.
*/
module.exports = TableService; |
var searchData=
[
['open',['open',['../interface_p_b_smartcard.html#aaab14c5d3c8b1e8b088168bdbd473ebd',1,'PBSmartcard']]],
['openwithdisabledbackgroundmanagement',['openWithDisabledBackgroundManagement',['../interface_p_b_smartcard.html#a14b46dcb5d5235536ee5117e508631a7',1,'PBSmartcard']]]
];
|
/*!
SerializeJSON jQuery plugin.
https://github.com/marioizquierdo/jquery.serializeJSON
version 2.8.1 (Dec, 2016)
Copyright (c) 2012, 2017 Mario Izquierdo
Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*/
(function (factory) {
if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') { // Node/CommonJS
var jQuery = require('jquery');
module.exports = factory(jQuery);
} else { // Browser globals (zepto supported)
factory(window.jQuery || window.Zepto || window.$); // Zepto supported on browsers as well
}
}(function ($) {
"use strict";
// jQuery('form').serializeJSON()
$.fn.serializeJSON = function (options) {
var f, $form, opts, formAsArray, serializedObject, name, value, parsedValue, _obj, nameWithNoType, type, keys, skipFalsy;
f = $.serializeJSON;
$form = this; // NOTE: the set of matched elements is most likely a form, but it could also be a group of inputs
opts = f.setupOpts(options); // calculate values for options {parseNumbers, parseBoolens, parseNulls, ...} with defaults
// Use native `serializeArray` function to get an array of {name, value} objects.
formAsArray = $form.serializeArray();
f.readCheckboxUncheckedValues(formAsArray, opts, $form); // add objects to the array from unchecked checkboxes if needed
// Convert the formAsArray into a serializedObject with nested keys
serializedObject = {};
$.each(formAsArray, function (i, obj) {
name = obj.name; // original input name
value = obj.value; // input value
_obj = f.extractTypeAndNameWithNoType(name);
nameWithNoType = _obj.nameWithNoType; // input name with no type (i.e. "foo:string" => "foo")
type = _obj.type; // type defined from the input name in :type colon notation
if (!type) type = f.attrFromInputWithName($form, name, 'data-value-type');
f.validateType(name, type, opts); // make sure that the type is one of the valid types if defined
if (type !== 'skip') { // ignore inputs with type 'skip'
keys = f.splitInputNameIntoKeysArray(nameWithNoType);
parsedValue = f.parseValue(value, name, type, opts); // convert to string, number, boolean, null or customType
skipFalsy = !parsedValue && f.shouldSkipFalsy($form, name, nameWithNoType, type, opts); // ignore falsy inputs if specified
if (!skipFalsy) {
f.deepSet(serializedObject, keys, parsedValue, opts);
}
}
});
return serializedObject;
};
// Use $.serializeJSON as namespace for the auxiliar functions
// and to define defaults
$.serializeJSON = {
defaultOptions: {
checkboxUncheckedValue: undefined, // to include that value for unchecked checkboxes (instead of ignoring them)
parseNumbers: false, // convert values like "1", "-2.33" to 1, -2.33
parseBooleans: false, // convert "true", "false" to true, false
parseNulls: false, // convert "null" to null
parseAll: false, // all of the above
parseWithFunction: null, // to use custom parser, a function like: function(val){ return parsed_val; }
skipFalsyValuesForTypes: [], // skip serialization of falsy values for listed value types
skipFalsyValuesForFields: [], // skip serialization of falsy values for listed field names
customTypes: {}, // override defaultTypes
defaultTypes: {
"string": function(str) { return String(str); },
"number": function(str) { return Number(str); },
"boolean": function(str) { var falses = ["false", "null", "undefined", "", "0"]; return falses.indexOf(str) === -1; },
"null": function(str) { var falses = ["false", "null", "undefined", "", "0"]; return falses.indexOf(str) === -1 ? str : null; },
"array": function(str) { return JSON.parse(str); },
"object": function(str) { return JSON.parse(str); },
"auto": function(str) { return $.serializeJSON.parseValue(str, null, null, {parseNumbers: true, parseBooleans: true, parseNulls: true}); }, // try again with something like "parseAll"
"skip": null // skip is a special type that makes it easy to ignore elements
},
useIntKeysAsArrayIndex: false // name="foo[2]" value="v" => {foo: [null, null, "v"]}, instead of {foo: ["2": "v"]}
},
// Merge option defaults into the options
setupOpts: function(options) {
var opt, validOpts, defaultOptions, optWithDefault, parseAll, f;
f = $.serializeJSON;
if (options == null) { options = {}; } // options ||= {}
defaultOptions = f.defaultOptions || {}; // defaultOptions
// Make sure that the user didn't misspell an option
validOpts = ['checkboxUncheckedValue', 'parseNumbers', 'parseBooleans', 'parseNulls', 'parseAll', 'parseWithFunction', 'skipFalsyValuesForTypes', 'skipFalsyValuesForFields', 'customTypes', 'defaultTypes', 'useIntKeysAsArrayIndex']; // re-define because the user may override the defaultOptions
for (opt in options) {
if (validOpts.indexOf(opt) === -1) {
throw new Error("serializeJSON ERROR: invalid option '" + opt + "'. Please use one of " + validOpts.join(', '));
}
}
// Helper to get the default value for this option if none is specified by the user
optWithDefault = function(key) { return (options[key] !== false) && (options[key] !== '') && (options[key] || defaultOptions[key]); };
// Return computed options (opts to be used in the rest of the script)
parseAll = optWithDefault('parseAll');
return {
checkboxUncheckedValue: optWithDefault('checkboxUncheckedValue'),
parseNumbers: parseAll || optWithDefault('parseNumbers'),
parseBooleans: parseAll || optWithDefault('parseBooleans'),
parseNulls: parseAll || optWithDefault('parseNulls'),
parseWithFunction: optWithDefault('parseWithFunction'),
skipFalsyValuesForTypes: optWithDefault('skipFalsyValuesForTypes'),
skipFalsyValuesForFields: optWithDefault('skipFalsyValuesForFields'),
typeFunctions: $.extend({}, optWithDefault('defaultTypes'), optWithDefault('customTypes')),
useIntKeysAsArrayIndex: optWithDefault('useIntKeysAsArrayIndex')
};
},
// Given a string, apply the type or the relevant "parse" options, to return the parsed value
parseValue: function(valStr, inputName, type, opts) {
var f, parsedVal;
f = $.serializeJSON;
parsedVal = valStr; // if no parsing is needed, the returned value will be the same
if (opts.typeFunctions && type && opts.typeFunctions[type]) { // use a type if available
parsedVal = opts.typeFunctions[type](valStr);
} else if (opts.parseNumbers && f.isNumeric(valStr)) { // auto: number
parsedVal = Number(valStr);
} else if (opts.parseBooleans && (valStr === "true" || valStr === "false")) { // auto: boolean
parsedVal = (valStr === "true");
} else if (opts.parseNulls && valStr == "null") { // auto: null
parsedVal = null;
}
if (opts.parseWithFunction && !type) { // custom parse function (apply after previous parsing options, but not if there's a specific type)
parsedVal = opts.parseWithFunction(parsedVal, inputName);
}
return parsedVal;
},
isObject: function(obj) { return obj === Object(obj); }, // is it an Object?
isUndefined: function(obj) { return obj === void 0; }, // safe check for undefined values
isValidArrayIndex: function(val) { return /^[0-9]+$/.test(String(val)); }, // 1,2,3,4 ... are valid array indexes
isNumeric: function(obj) { return obj - parseFloat(obj) >= 0; }, // taken from jQuery.isNumeric implementation. Not using jQuery.isNumeric to support old jQuery and Zepto versions
optionKeys: function(obj) { if (Object.keys) { return Object.keys(obj); } else { var key, keys = []; for(key in obj){ keys.push(key); } return keys;} }, // polyfill Object.keys to get option keys in IE<9
// Fill the formAsArray object with values for the unchecked checkbox inputs,
// using the same format as the jquery.serializeArray function.
// The value of the unchecked values is determined from the opts.checkboxUncheckedValue
// and/or the data-unchecked-value attribute of the inputs.
readCheckboxUncheckedValues: function (formAsArray, opts, $form) {
var selector, $uncheckedCheckboxes, $el, uncheckedValue, f, name;
if (opts == null) { opts = {}; }
f = $.serializeJSON;
selector = 'input[type=checkbox][name]:not(:checked):not([disabled])';
$uncheckedCheckboxes = $form.find(selector).add($form.filter(selector));
$uncheckedCheckboxes.each(function (i, el) {
// Check data attr first, then the option
$el = $(el);
uncheckedValue = $el.attr('data-unchecked-value');
if (uncheckedValue == null) {
uncheckedValue = opts.checkboxUncheckedValue;
}
// If there's an uncheckedValue, push it into the serialized formAsArray
if (uncheckedValue != null) {
if (el.name && el.name.indexOf("[][") !== -1) { // identify a non-supported
throw new Error("serializeJSON ERROR: checkbox unchecked values are not supported on nested arrays of objects like '"+el.name+"'. See https://github.com/marioizquierdo/jquery.serializeJSON/issues/67");
}
formAsArray.push({name: el.name, value: uncheckedValue});
}
});
},
// Returns and object with properties {name_without_type, type} from a given name.
// The type is null if none specified. Example:
// "foo" => {nameWithNoType: "foo", type: null}
// "foo:boolean" => {nameWithNoType: "foo", type: "boolean"}
// "foo[bar]:null" => {nameWithNoType: "foo[bar]", type: "null"}
extractTypeAndNameWithNoType: function(name) {
var match;
if (match = name.match(/(.*):([^:]+)$/)) {
return {nameWithNoType: match[1], type: match[2]};
} else {
return {nameWithNoType: name, type: null};
}
},
// Check if this input should be skipped when it has a falsy value,
// depending on the options to skip values by name or type, and the data-skip-falsy attribute.
shouldSkipFalsy: function($form, name, nameWithNoType, type, opts) {
var f = $.serializeJSON;
var skipFromDataAttr = f.attrFromInputWithName($form, name, 'data-skip-falsy');
if (skipFromDataAttr != null) {
return skipFromDataAttr !== 'false'; // any value is true, except if explicitly using 'false'
}
var optForFields = opts.skipFalsyValuesForFields;
if (optForFields && (optForFields.indexOf(nameWithNoType) !== -1 || optForFields.indexOf(name) !== -1)) {
return true;
}
var optForTypes = opts.skipFalsyValuesForTypes;
if (type == null) type = 'string'; // assume fields with no type are targeted as string
if (optForTypes && optForTypes.indexOf(type) !== -1) {
return true
}
return false;
},
// Finds the first input in $form with this name, and get the given attr from it.
// Returns undefined if no input or no attribute was found.
attrFromInputWithName: function($form, name, attrName) {
var escapedName, selector, $input, attrValue;
escapedName = name.replace(/(:|\.|\[|\]|\s)/g,'\\$1'); // every non-standard character need to be escaped by \\
selector = '[name="' + escapedName + '"]';
$input = $form.find(selector).add($form.filter(selector)); // NOTE: this returns only the first $input element if multiple are matched with the same name (i.e. an "array[]"). So, arrays with different element types specified through the data-value-type attr is not supported.
return $input.attr(attrName);
},
// Raise an error if the type is not recognized.
validateType: function(name, type, opts) {
var validTypes, f;
f = $.serializeJSON;
validTypes = f.optionKeys(opts ? opts.typeFunctions : f.defaultOptions.defaultTypes);
if (!type || validTypes.indexOf(type) !== -1) {
return true;
} else {
throw new Error("serializeJSON ERROR: Invalid type " + type + " found in input name '" + name + "', please use one of " + validTypes.join(', '));
}
},
// Split the input name in programatically readable keys.
// Examples:
// "foo" => ['foo']
// "[foo]" => ['foo']
// "foo[inn][bar]" => ['foo', 'inn', 'bar']
// "foo[inn[bar]]" => ['foo', 'inn', 'bar']
// "foo[inn][arr][0]" => ['foo', 'inn', 'arr', '0']
// "arr[][val]" => ['arr', '', 'val']
splitInputNameIntoKeysArray: function(nameWithNoType) {
var keys, f;
f = $.serializeJSON;
keys = nameWithNoType.split('['); // split string into array
keys = $.map(keys, function (key) { return key.replace(/\]/g, ''); }); // remove closing brackets
if (keys[0] === '') { keys.shift(); } // ensure no opening bracket ("[foo][inn]" should be same as "foo[inn]")
return keys;
},
// Set a value in an object or array, using multiple keys to set in a nested object or array:
//
// deepSet(obj, ['foo'], v) // obj['foo'] = v
// deepSet(obj, ['foo', 'inn'], v) // obj['foo']['inn'] = v // Create the inner obj['foo'] object, if needed
// deepSet(obj, ['foo', 'inn', '123'], v) // obj['foo']['arr']['123'] = v //
//
// deepSet(obj, ['0'], v) // obj['0'] = v
// deepSet(arr, ['0'], v, {useIntKeysAsArrayIndex: true}) // arr[0] = v
// deepSet(arr, [''], v) // arr.push(v)
// deepSet(obj, ['arr', ''], v) // obj['arr'].push(v)
//
// arr = [];
// deepSet(arr, ['', v] // arr => [v]
// deepSet(arr, ['', 'foo'], v) // arr => [v, {foo: v}]
// deepSet(arr, ['', 'bar'], v) // arr => [v, {foo: v, bar: v}]
// deepSet(arr, ['', 'bar'], v) // arr => [v, {foo: v, bar: v}, {bar: v}]
//
deepSet: function (o, keys, value, opts) {
var key, nextKey, tail, lastIdx, lastVal, f;
if (opts == null) { opts = {}; }
f = $.serializeJSON;
if (f.isUndefined(o)) { throw new Error("ArgumentError: param 'o' expected to be an object or array, found undefined"); }
if (!keys || keys.length === 0) { throw new Error("ArgumentError: param 'keys' expected to be an array with least one element"); }
key = keys[0];
// Only one key, then it's not a deepSet, just assign the value.
if (keys.length === 1) {
if (key === '') {
o.push(value); // '' is used to push values into the array (assume o is an array)
} else {
o[key] = value; // other keys can be used as object keys or array indexes
}
// With more keys is a deepSet. Apply recursively.
} else {
nextKey = keys[1];
// '' is used to push values into the array,
// with nextKey, set the value into the same object, in object[nextKey].
// Covers the case of ['', 'foo'] and ['', 'var'] to push the object {foo, var}, and the case of nested arrays.
if (key === '') {
lastIdx = o.length - 1; // asume o is array
lastVal = o[lastIdx];
if (f.isObject(lastVal) && (f.isUndefined(lastVal[nextKey]) || keys.length > 2)) { // if nextKey is not present in the last object element, or there are more keys to deep set
key = lastIdx; // then set the new value in the same object element
} else {
key = lastIdx + 1; // otherwise, point to set the next index in the array
}
}
// '' is used to push values into the array "array[]"
if (nextKey === '') {
if (f.isUndefined(o[key]) || !$.isArray(o[key])) {
o[key] = []; // define (or override) as array to push values
}
} else {
if (opts.useIntKeysAsArrayIndex && f.isValidArrayIndex(nextKey)) { // if 1, 2, 3 ... then use an array, where nextKey is the index
if (f.isUndefined(o[key]) || !$.isArray(o[key])) {
o[key] = []; // define (or override) as array, to insert values using int keys as array indexes
}
} else { // for anything else, use an object, where nextKey is going to be the attribute name
if (f.isUndefined(o[key]) || !f.isObject(o[key])) {
o[key] = {}; // define (or override) as object, to set nested properties
}
}
}
// Recursively set the inner object
tail = keys.slice(1);
f.deepSet(o[key], tail, value, opts);
}
}
};
})); |
var gzippo = require('gzippo');
var express = require('express');
var app = express();
//app.use(express.logger('dev'));
app.use(gzippo.staticGzip("" + __dirname + "/dist"));
app.listen(process.env.PORT || 5000); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.