code stringlengths 2 1.05M |
|---|
// eslint-disable-next-line
import { getContext, onDestroy } from 'svelte';
export const getReactiveContext = (name, setValue) => {
const ctx = getContext(name);
if (!ctx) return undefined;
const { value, subscribe, unsubscribe } = ctx;
subscribe(setValue);
onDestroy(() => {
unsubscribe(setValue);
});
return value;
};
|
Package.describe({
summary: "Firebase wrapper for Meteor"
});
Npm.depends({ "firebase": "0.6.15" });
Package.on_use(function(api) {
if (api.export) api.export('Firebase', 'server');
api.add_files('firebase.js', 'server');
});
|
var _ = require("underscore");
var util = require("util");
var EventEmitter = require("events").EventEmitter;
var assert = require("assert");
function WatchDog() {
this._subscriber = {};
this._counter = 0;
this._current_time = new Date();
this._visit_subscriber_b = this._visit_subscriber.bind(this);
this._timer = null;
}
util.inherits(WatchDog, EventEmitter);
/**
* returns the number of subscribers using the WatchDog object.
* @property subscriberCount
* @type {Number}
*/
WatchDog.prototype.__defineGetter__("subscriberCount", function () {
return Object.keys(this._subscriber).length;
});
function has_expired(watchDogData, currentTime) {
var elapsed_time = currentTime - watchDogData.last_seen;
return elapsed_time > watchDogData.timeout;
}
function _start_timer() {
assert(this._timer === null, "start timer called ?");
this._timer = setInterval(this._visit_subscriber_b, 1000);
}
function _stop_timer() {
assert(this._timer !== null, "_stop_timer already called ?");
clearInterval(this._timer);
this._timer = null;
}
WatchDog.prototype._visit_subscriber = function () {
var self = this;
self._current_time = new Date();
var expired_subscribers = _.filter(self._subscriber, function (watchDogData) {
watchDogData.visitCount += 1;
return has_expired(watchDogData, self._current_time);
});
//xx console.log("_visit_subscriber", _.map(expired_subscribers, _.property("key")));
if (expired_subscribers.length) {
self.emit("timeout", expired_subscribers);
}
expired_subscribers.forEach(function (subscriber) {
self.removeSubscriber(subscriber.subscriber);
subscriber.subscriber.watchdogReset();
});
self._current_time = new Date();
};
function keepAliveFunc() {
var self = this;
assert(self._watchDog instanceof WatchDog);
assert(_.isNumber(self._watchDogData.key));
self._watchDogData.last_seen = new Date();
}
/**
* add a subscriber to the WatchDog.
* @method addSubscriber
*
* add a subscriber to the WatchDog.
*
* This method modifies the subscriber be adding a
* new method to it called 'keepAlive'
* The subscriber must also provide a "watchdogReset". watchdogReset will be called
* if the subscriber failed to call keepAlive withing the timeout period.
* @param subscriber
* @param timeout
* @return {number}
*/
WatchDog.prototype.addSubscriber = function (subscriber, timeout) {
var self = this;
self._current_time = new Date();
timeout = timeout || 1000;
assert(_.isNumber(timeout), " invalid timeout ");
assert(_.isFunction(subscriber.watchdogReset), " the subscriber must provide a watchdogReset method ");
assert(!_.isFunction(subscriber.keepAlive));
self._counter += 1;
var key = self._counter;
subscriber._watchDog = self;
subscriber._watchDogData = {
key: key,
subscriber: subscriber,
timeout: timeout,
last_seen: self._current_time,
visitCount: 0
};
self._subscriber[key] = subscriber._watchDogData;
subscriber.keepAlive = keepAliveFunc.bind(subscriber);
// start timer when the first subscriber comes in
if (self.subscriberCount === 1) {
assert(self._timer === null);
_start_timer.call(self);
}
return key;
};
WatchDog.prototype.removeSubscriber = function (subscriber) {
if (!subscriber._watchDog) {
return; // already removed !!!
}
assert(subscriber._watchDog instanceof WatchDog);
assert(_.isNumber(subscriber._watchDogData.key));
assert(_.isFunction(subscriber.keepAlive));
assert(this._subscriber.hasOwnProperty(subscriber._watchDogData.key));
delete this._subscriber[subscriber._watchDogData.key];
delete subscriber._watchDog;
delete subscriber._watchDogData;
delete subscriber.keepAlive;
// delete timer when the last subscriber comes out
//xx console.log("xxxx WatchDog.prototype.removeSubscriber ",this.subscriberCount );
if (this.subscriberCount === 0) {
_stop_timer.call(this);
}
};
WatchDog.prototype.shutdown = function () {
assert(this._timer === null && Object.keys(this._subscriber).length === 0, " leaking subscriber in watchdog");
};
exports.WatchDog = WatchDog;
|
var initStart = process.hrtime();
var Browscap = require('browscap-js');
var browscap = new Browscap();
// Trigger a parse to force cache loading
browscap.getBrowser('Test String');
var initTime = process.hrtime(initStart)[1] / 1000000000;
var browscapPackage = require(require('path').dirname(
require.resolve('browscap-js')
) + '/../package.json');
var version = browscapPackage.version;
var benchmark = false;
var benchmarkPos = process.argv.indexOf('--benchmark');
if (benchmarkPos >= 0) {
process.argv.splice(benchmarkPos, 1);
benchmark = true;
}
var lineReader = require('readline').createInterface({
input: require('fs').createReadStream(process.argv[2])
});
var output = {
results: [],
parse_time: 0,
init_time: initTime,
memory_used: 0,
version: version
};
lineReader.on('line', function(line) {
if (line === '') {
return;
}
var start = process.hrtime();
var browser = browscap.getBrowser(line);
var end = process.hrtime(start)[1] / 1000000000;
output.parse_time += end;
if (benchmark) {
return;
}
var result = {
useragent: line,
parsed: {
browser: {
name: browser.Browser,
version: browser.Version
},
platform: {
name: browser.Platform,
version: browser.Platform_Version
},
device: {
name: browser.Device_Name,
brand: browser.Device_Maker,
type: browser.Device_Type,
ismobile: browser.isMobileDevice ? true : false
}
},
time: end
};
output.results.push(result);
});
lineReader.on('close', function() {
output.memory_used = process.memoryUsage().heapUsed;
console.log(JSON.stringify(output, null, 2));
});
|
// Converts fonts config from the client (sent when user clicks Download button)
// into a config suitable for the font builder.
//
// Client config structure:
//
// name:
// css_prefix_text:
// css_use_suffix:
// hinting:
// glyphs:
// - uid:
// src: fontname
// code: codepoint
// css:
//
// For custom icons
//
// selected: flag
// svg:
// - path:
// width:
// - ...
//
// Resulting builder config:
//
// font:
// fontname:
// fullname:
// familyname:
// copyright:
// ascent:
// descent:
// weight:
//
// meta:
// columns:
// css_prefix_text:
// css_use_suffix:
//
// glyphs:
// - src:
// from: codepoint
// code: codepoint
// css:
// css-ext:
//
// - ...
//
// fonts_list:
// -
// font:
// meta:
//
'use strict';
const _ = require('lodash');
const svgpath = require('svgpath');
const fontConfigs = require('../../../../lib/embedded_fonts/server_config');
function collectGlyphsInfo(clientConfig) {
let result = [];
let scale = clientConfig.units_per_em / 1000;
_.forEach(clientConfig.glyphs, glyph => {
let sp;
if (glyph.src === 'custom_icons') {
// for custom glyphs use only selected ones
if (!glyph.selected) return;
sp = svgpath(glyph.svg.path)
.scale(scale, -scale)
.translate(0, clientConfig.ascent)
.abs().round(0).rel();
result.push({
src: glyph.src,
uid: glyph.uid,
code: glyph.code,
css: glyph.css,
width: +(glyph.svg.width * scale).toFixed(1),
d: sp.toString(),
segments: sp.segments.length
});
return;
}
// For exmbedded fonts take pregenerated info
let glyphEmbedded = fontConfigs.uids[glyph.uid];
if (!glyphEmbedded) return;
sp = svgpath(glyphEmbedded.svg.d)
.scale(scale, -scale)
.translate(0, clientConfig.ascent)
.abs().round(0).rel();
result.push({
src: glyphEmbedded.fontname,
uid: glyph.uid,
code: glyph.code || glyphEmbedded.code,
css: glyph.css || glyphEmbedded.css,
'css-ext': glyphEmbedded['css-ext'],
width: +(glyphEmbedded.svg.width * scale).toFixed(1),
d: sp.toString(),
segments: sp.segments.length
});
});
// Sort result by original codes.
result.sort((a, b) => a.code - b.code);
return result;
}
// collect fonts metadata required to build license info
function collectFontsInfo(glyphs) {
let result = [];
_(glyphs).map('src').uniq().forEach(fontname => {
let font = fontConfigs.fonts[fontname];
let meta = fontConfigs.metas[fontname];
if (font && meta) {
result.push({ font, meta });
}
});
return result;
}
module.exports = function fontConfig(clientConfig) {
let fontname, glyphsInfo, fontsInfo;
//
// Patch broken data to fix original config
//
if (clientConfig.fullname === 'undefined') { delete clientConfig.fullname; }
if (clientConfig.copyright === 'undefined') { delete clientConfig.copyright; }
//
// Fill default values, until replace `revalidator` with something better
// That's required for old `config.json`-s.
//
clientConfig.css_use_suffix = Boolean(clientConfig.css_use_suffix);
clientConfig.css_prefix_text = clientConfig.css_prefix_text || 'icon-';
clientConfig.hinting = (clientConfig.hinting !== false);
clientConfig.units_per_em = +clientConfig.units_per_em || 1000;
clientConfig.ascent = +clientConfig.ascent || 850;
//
// Start creating builder config
//
if (!_.isEmpty(clientConfig.name)) {
fontname = String(clientConfig.name).replace(/[^a-z0-9\-_]+/g, '-');
} else {
fontname = 'fontello';
}
glyphsInfo = collectGlyphsInfo(clientConfig);
fontsInfo = collectFontsInfo(glyphsInfo);
if (_.isEmpty(glyphsInfo)) return null;
let defaultCopyright = 'Copyright (C) ' + new Date().getFullYear() + ' by original authors @ fontello.com';
return {
font: {
fontname,
fullname: fontname,
// !!! IMPORTANT for IE6-8 !!!
// due bug, EOT requires `familyname` begins `fullname`
// https://github.com/fontello/fontello/issues/73?source=cc#issuecomment-7791793
familyname: fontname,
copyright: !_.isEmpty(fontsInfo) ? defaultCopyright : (clientConfig.copyright || defaultCopyright),
ascent: clientConfig.ascent,
descent: clientConfig.ascent - clientConfig.units_per_em,
weight: 400
},
hinting: clientConfig.hinting !== false,
meta: {
columns: 4, // Used by the demo page.
// Set defaults if fields not exists in config
css_prefix_text: clientConfig.css_prefix_text || 'icon-',
css_use_suffix: Boolean(clientConfig.css_use_suffix)
},
glyphs: glyphsInfo,
fonts_list: fontsInfo
};
};
|
var config = require('./../config/config');
var log4js = require('log4js');
var env = process.env.NODE_ENV || "development";
log4js.configure({
appenders: [
{type: 'console'},
{
type: 'file',
filename: 'logs/cat.log',
category: 'cat'
}
]
});
var logger = log4js.getLogger('cat');
logger.setLevel(config.debug ? 'DEBUG' : 'ERROR');
module.exports = logger;
|
module.exports =
{
mode: "01",
pid: "80",
name: "pidsupp8",
description: "PIDs supported 81-A0",
min: 0,
max: 0,
unit: "Bit Encoded",
bytes: 4,
convertToUseful: function( byteA, byteB, byteC, byteD )
{
return String( byteA ) + String( byteB ) + String( byteC ) + String( byteD );
}
}; |
let util = require('../../util');
let Hammer = require('../../module/hammer');
let hammerUtil = require('../../hammerUtil');
/**
* clears the toolbar div element of children
*
* @private
*/
class ManipulationSystem {
constructor(body, canvas, selectionHandler) {
this.body = body;
this.canvas = canvas;
this.selectionHandler = selectionHandler;
this.editMode = false;
this.manipulationDiv = undefined;
this.editModeDiv = undefined;
this.closeDiv = undefined;
this.manipulationHammers = [];
this.temporaryUIFunctions = {};
this.temporaryEventFunctions = [];
this.touchTime = 0;
this.temporaryIds = {nodes: [], edges:[]};
this.guiEnabled = false;
this.inMode = false;
this.selectedControlNode = undefined;
this.options = {};
this.defaultOptions = {
enabled: false,
initiallyActive: false,
addNode: true,
addEdge: true,
editNode: undefined,
editEdge: true,
deleteNode: true,
deleteEdge: true,
controlNodeStyle:{
shape:'dot',
size:6,
color: {background: '#ff0000', border: '#3c3c3c', highlight: {background: '#07f968', border: '#3c3c3c'}},
borderWidth: 2,
borderWidthSelected: 2
}
};
util.extend(this.options, this.defaultOptions);
this.body.emitter.on('destroy', () => {this._clean();});
this.body.emitter.on('_dataChanged',this._restore.bind(this));
this.body.emitter.on('_resetData', this._restore.bind(this));
}
/**
* If something changes in the data during editing, switch back to the initial datamanipulation state and close all edit modes.
* @private
*/
_restore() {
if (this.inMode !== false) {
if (this.options.initiallyActive === true) {
this.enableEditMode();
}
else {
this.disableEditMode();
}
}
}
/**
* Set the Options
* @param options
*/
setOptions(options, allOptions, globalOptions) {
if (allOptions !== undefined) {
if (allOptions.locale !== undefined) {this.options.locale = allOptions.locale} else {this.options.locale = globalOptions.locale;}
if (allOptions.locales !== undefined) {this.options.locales = allOptions.locales} else {this.options.locales = globalOptions.locales;}
}
if (options !== undefined) {
if (typeof options === 'boolean') {
this.options.enabled = options;
}
else {
this.options.enabled = true;
util.deepExtend(this.options, options);
}
if (this.options.initiallyActive === true) {
this.editMode = true;
}
this._setup();
}
}
/**
* Enable or disable edit-mode. Draws the DOM required and cleans up after itself.
*
* @private
*/
toggleEditMode() {
if (this.editMode === true) {
this.disableEditMode();
}
else {
this.enableEditMode();
}
}
enableEditMode() {
this.editMode = true;
this._clean();
if (this.guiEnabled === true) {
this.manipulationDiv.style.display = 'block';
this.closeDiv.style.display = 'block';
this.editModeDiv.style.display = 'none';
this.showManipulatorToolbar();
}
}
disableEditMode() {
this.editMode = false;
this._clean();
if (this.guiEnabled === true) {
this.manipulationDiv.style.display = 'none';
this.closeDiv.style.display = 'none';
this.editModeDiv.style.display = 'block';
this._createEditButton();
}
}
/**
* Creates the main toolbar. Removes functions bound to the select event. Binds all the buttons of the toolbar.
*
* @private
*/
showManipulatorToolbar() {
// restore the state of any bound functions or events, remove control nodes, restore physics
this._clean();
// reset global letiables
this.manipulationDOM = {};
// if the gui is enabled, draw all elements.
if (this.guiEnabled === true) {
// a _restore will hide these menus
this.editMode = true;
this.manipulationDiv.style.display = 'block';
this.closeDiv.style.display = 'block';
let selectedNodeCount = this.selectionHandler._getSelectedNodeCount();
let selectedEdgeCount = this.selectionHandler._getSelectedEdgeCount();
let selectedTotalCount = selectedNodeCount + selectedEdgeCount;
let locale = this.options.locales[this.options.locale];
let needSeperator = false;
if (this.options.addNode !== false) {
this._createAddNodeButton(locale);
needSeperator = true;
}
if (this.options.addEdge !== false) {
if (needSeperator === true) {
this._createSeperator(1);
} else {
needSeperator = true;
}
this._createAddEdgeButton(locale);
}
if (selectedNodeCount === 1 && typeof this.options.editNode === 'function') {
if (needSeperator === true) {
this._createSeperator(2);
} else {
needSeperator = true;
}
this._createEditNodeButton(locale);
}
else if (selectedEdgeCount === 1 && selectedNodeCount === 0 && this.options.editEdge !== false) {
if (needSeperator === true) {
this._createSeperator(3);
} else {
needSeperator = true;
}
this._createEditEdgeButton(locale);
}
// remove buttons
if (selectedTotalCount !== 0) {
if (selectedNodeCount === 1 && this.options.deleteNode !== false) {
if (needSeperator === true) {
this._createSeperator(4);
}
this._createDeleteButton(locale);
}
else if (selectedNodeCount === 0 && this.options.deleteEdge !== false) {
if (needSeperator === true) {
this._createSeperator(4);
}
this._createDeleteButton(locale);
}
}
// bind the close button
this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this));
// refresh this bar based on what has been selected
this._temporaryBindEvent('select', this.showManipulatorToolbar.bind(this));
}
// redraw to show any possible changes
this.body.emitter.emit('_redraw');
}
/**
* Create the toolbar for adding Nodes
*
* @private
*/
addNodeMode() {
// when using the gui, enable edit mode if it wasnt already.
if (this.editMode !== true) {
this.enableEditMode();
}
// restore the state of any bound functions or events, remove control nodes, restore physics
this._clean();
this.inMode = 'addNode';
if (this.guiEnabled === true) {
let locale = this.options.locales[this.options.locale];
this.manipulationDOM = {};
this._createBackButton(locale);
this._createSeperator();
this._createDescription(locale['addDescription'] || this.options.locales['en']['addDescription']);
// bind the close button
this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this));
}
this._temporaryBindEvent('click', this._performAddNode.bind(this));
}
/**
* call the bound function to handle the editing of the node. The node has to be selected.
*
* @private
*/
editNodeMode() {
// when using the gui, enable edit mode if it wasnt already.
if (this.editMode !== true) {
this.enableEditMode();
}
// restore the state of any bound functions or events, remove control nodes, restore physics
this._clean();
this.inMode = 'editNode';
if (typeof this.options.editNode === 'function') {
let node = this.selectionHandler._getSelectedNode();
if (node.isCluster !== true) {
let data = util.deepExtend({}, node.options, true);
data.x = node.x;
data.y = node.y;
if (this.options.editNode.length === 2) {
this.options.editNode(data, (finalizedData) => {
if (finalizedData !== null && finalizedData !== undefined && this.inMode === 'delete') { // if for whatever reason the mode has changes (due to dataset change) disregard the callback) {
this.body.data.nodes.update(finalizedData);
this.showManipulatorToolbar();
}
});
}
else {
throw new Error('The function for edit does not support two arguments (data, callback)');
}
}
else {
alert(this.options.locales[this.options.locale]['editClusterError'] || this.options.locales['en']['editClusterError']);
}
}
else {
throw new Error('No function has been configured to handle the editing of nodes.');
}
}
/**
* create the toolbar to connect nodes
*
* @private
*/
addEdgeMode() {
// when using the gui, enable edit mode if it wasnt already.
if (this.editMode !== true) {
this.enableEditMode();
}
// restore the state of any bound functions or events, remove control nodes, restore physics
this._clean();
this.inMode = 'addEdge';
if (this.guiEnabled === true) {
let locale = this.options.locales[this.options.locale];
this.manipulationDOM = {};
this._createBackButton(locale);
this._createSeperator();
this._createDescription(locale['edgeDescription'] || this.options.locales['en']['edgeDescription']);
// bind the close button
this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this));
}
// temporarily overload functions
this._temporaryBindUI('onTouch', this._handleConnect.bind(this));
this._temporaryBindUI('onDragEnd', this._finishConnect.bind(this));
this._temporaryBindUI('onDrag', this._dragControlNode.bind(this));
this._temporaryBindUI('onRelease', this._finishConnect.bind(this));
this._temporaryBindUI('onDragStart', () => {});
this._temporaryBindUI('onHold', () => {});
}
/**
* create the toolbar to edit edges
*
* @private
*/
editEdgeMode() {
// when using the gui, enable edit mode if it wasnt already.
if (this.editMode !== true) {
this.enableEditMode();
}
// restore the state of any bound functions or events, remove control nodes, restore physics
this._clean();
this.inMode = 'editEdge';
if (this.guiEnabled === true) {
let locale = this.options.locales[this.options.locale];
this.manipulationDOM = {};
this._createBackButton(locale);
this._createSeperator();
this._createDescription(locale['editEdgeDescription'] || this.options.locales['en']['editEdgeDescription']);
// bind the close button
this._bindHammerToDiv(this.closeDiv, this.toggleEditMode.bind(this));
}
this.edgeBeingEditedId = this.selectionHandler.getSelectedEdges()[0];
let edge = this.body.edges[this.edgeBeingEditedId];
// create control nodes
let controlNodeFrom = this._getNewTargetNode(edge.from.x, edge.from.y);
let controlNodeTo = this._getNewTargetNode(edge.to.x, edge.to.y);
this.temporaryIds.nodes.push(controlNodeFrom.id);
this.temporaryIds.nodes.push(controlNodeTo.id);
this.body.nodes[controlNodeFrom.id] = controlNodeFrom;
this.body.nodeIndices.push(controlNodeFrom.id);
this.body.nodes[controlNodeTo.id] = controlNodeTo;
this.body.nodeIndices.push(controlNodeTo.id);
// temporarily overload UI functions, cleaned up automatically because of _temporaryBindUI
this._temporaryBindUI('onTouch', this._controlNodeTouch.bind(this)); // used to get the position
this._temporaryBindUI('onTap', () => {}); // disabled
this._temporaryBindUI('onHold', () => {}); // disabled
this._temporaryBindUI('onDragStart', this._controlNodeDragStart.bind(this));// used to select control node
this._temporaryBindUI('onDrag', this._controlNodeDrag.bind(this)); // used to drag control node
this._temporaryBindUI('onDragEnd', this._controlNodeDragEnd.bind(this)); // used to connect or revert control nodes
this._temporaryBindUI('onMouseMove', () => {}); // disabled
// create function to position control nodes correctly on movement
// automatically cleaned up because we use the temporary bind
this._temporaryBindEvent('beforeDrawing', (ctx) => {
let positions = edge.edgeType.findBorderPositions(ctx);
if (controlNodeFrom.selected === false) {
controlNodeFrom.x = positions.from.x;
controlNodeFrom.y = positions.from.y;
}
if (controlNodeTo.selected === false) {
controlNodeTo.x = positions.to.x;
controlNodeTo.y = positions.to.y;
}
});
this.body.emitter.emit('_redraw');
}
/**
* delete everything in the selection
*
* @private
*/
deleteSelected() {
// when using the gui, enable edit mode if it wasnt already.
if (this.editMode !== true) {
this.enableEditMode();
}
// restore the state of any bound functions or events, remove control nodes, restore physics
this._clean();
this.inMode = 'delete';
let selectedNodes = this.selectionHandler.getSelectedNodes();
let selectedEdges = this.selectionHandler.getSelectedEdges();
let deleteFunction = undefined;
if (selectedNodes.length > 0) {
for (let i = 0; i < selectedNodes.length; i++) {
if (this.body.nodes[selectedNodes[i]].isCluster === true) {
alert(this.options.locales[this.options.locale]['deleteClusterError'] || this.options.locales['en']['deleteClusterError']);
return;
}
}
if (typeof this.options.deleteNode === 'function') {
deleteFunction = this.options.deleteNode;
}
}
else if (selectedEdges.length > 0) {
if (typeof this.options.deleteEdge === 'function') {
deleteFunction = this.options.deleteEdge;
}
}
if (typeof deleteFunction === 'function') {
let data = {nodes: selectedNodes, edges: selectedEdges};
if (deleteFunction.length === 2) {
deleteFunction(data, (finalizedData) => {
if (finalizedData !== null && finalizedData !== undefined && this.inMode === 'delete') { // if for whatever reason the mode has changes (due to dataset change) disregard the callback) {
this.body.data.edges.remove(finalizedData.edges);
this.body.data.nodes.remove(finalizedData.nodes);
this.body.emitter.emit('startSimulation');
this.showManipulatorToolbar();
}
});
}
else {
throw new Error('The function for delete does not support two arguments (data, callback)')
}
}
else {
this.body.data.edges.remove(selectedEdges);
this.body.data.nodes.remove(selectedNodes);
this.body.emitter.emit('startSimulation');
this.showManipulatorToolbar();
}
}
//********************************************** PRIVATE ***************************************//
/**
* draw or remove the DOM
* @private
*/
_setup() {
if (this.options.enabled === true) {
// Enable the GUI
this.guiEnabled = true;
this._createWrappers();
if (this.editMode === false) {
this._createEditButton();
}
else {
this.showManipulatorToolbar();
}
}
else {
this._removeManipulationDOM();
// disable the gui
this.guiEnabled = false;
}
}
/**
* create the div overlays that contain the DOM
* @private
*/
_createWrappers() {
// load the manipulator HTML elements. All styling done in css.
if (this.manipulationDiv === undefined) {
this.manipulationDiv = document.createElement('div');
this.manipulationDiv.className = 'vis-manipulation';
if (this.editMode === true) {
this.manipulationDiv.style.display = 'block';
}
else {
this.manipulationDiv.style.display = 'none';
}
this.canvas.frame.appendChild(this.manipulationDiv);
}
// container for the edit button.
if (this.editModeDiv === undefined) {
this.editModeDiv = document.createElement('div');
this.editModeDiv.className = 'vis-edit-mode';
if (this.editMode === true) {
this.editModeDiv.style.display = 'none';
}
else {
this.editModeDiv.style.display = 'block';
}
this.canvas.frame.appendChild(this.editModeDiv);
}
// container for the close div button
if (this.closeDiv === undefined) {
this.closeDiv = document.createElement('div');
this.closeDiv.className = 'vis-close';
this.closeDiv.style.display = this.manipulationDiv.style.display;
this.canvas.frame.appendChild(this.closeDiv);
}
}
/**
* generate a new target node. Used for creating new edges and editing edges
* @param x
* @param y
* @returns {*}
* @private
*/
_getNewTargetNode(x,y) {
let controlNodeStyle = util.deepExtend({}, this.options.controlNodeStyle);
controlNodeStyle.id = 'targetNode' + util.randomUUID();
controlNodeStyle.hidden = false;
controlNodeStyle.physics = false;
controlNodeStyle.x = x;
controlNodeStyle.y = y;
return this.body.functions.createNode(controlNodeStyle);
}
/**
* Create the edit button
*/
_createEditButton() {
// restore everything to it's original state (if applicable)
this._clean();
// reset the manipulationDOM
this.manipulationDOM = {};
// empty the editModeDiv
util.recursiveDOMDelete(this.editModeDiv);
// create the contents for the editMode button
let locale = this.options.locales[this.options.locale];
let button = this._createButton('editMode', 'vis-button vis-edit vis-edit-mode', locale['edit'] || this.options.locales['en']['edit']);
this.editModeDiv.appendChild(button);
// bind a hammer listener to the button, calling the function toggleEditMode.
this._bindHammerToDiv(button, this.toggleEditMode.bind(this));
}
/**
* this function cleans up after everything this module does. Temporary elements, functions and events are removed, physics restored, hammers removed.
* @private
*/
_clean() {
// not in mode
this.inMode = false;
// _clean the divs
if (this.guiEnabled === true) {
util.recursiveDOMDelete(this.editModeDiv);
util.recursiveDOMDelete(this.manipulationDiv);
// removes all the bindings and overloads
this._cleanManipulatorHammers();
}
// remove temporary nodes and edges
this._cleanupTemporaryNodesAndEdges();
// restore overloaded UI functions
this._unbindTemporaryUIs();
// remove the temporaryEventFunctions
this._unbindTemporaryEvents();
// restore the physics if required
this.body.emitter.emit('restorePhysics');
}
/**
* Each dom element has it's own hammer. They are stored in this.manipulationHammers. This cleans them up.
* @private
*/
_cleanManipulatorHammers() {
// _clean hammer bindings
if (this.manipulationHammers.length != 0) {
for (let i = 0; i < this.manipulationHammers.length; i++) {
this.manipulationHammers[i].destroy();
}
this.manipulationHammers = [];
}
}
/**
* Remove all DOM elements created by this module.
* @private
*/
_removeManipulationDOM() {
// removes all the bindings and overloads
this._clean();
// empty the manipulation divs
util.recursiveDOMDelete(this.manipulationDiv);
util.recursiveDOMDelete(this.editModeDiv);
util.recursiveDOMDelete(this.closeDiv);
// remove the manipulation divs
this.canvas.frame.removeChild(this.manipulationDiv);
this.canvas.frame.removeChild(this.editModeDiv);
this.canvas.frame.removeChild(this.closeDiv);
// set the references to undefined
this.manipulationDiv = undefined;
this.editModeDiv = undefined;
this.closeDiv = undefined;
}
/**
* create a seperator line. the index is to differentiate in the manipulation dom
* @param index
* @private
*/
_createSeperator(index = 1) {
this.manipulationDOM['seperatorLineDiv' + index] = document.createElement('div');
this.manipulationDOM['seperatorLineDiv' + index].className = 'vis-separator-line';
this.manipulationDiv.appendChild(this.manipulationDOM['seperatorLineDiv' + index]);
}
// ---------------------- DOM functions for buttons --------------------------//
_createAddNodeButton(locale) {
let button = this._createButton('addNode', 'vis-button vis-add', locale['addNode'] || this.options.locales['en']['addNode']);
this.manipulationDiv.appendChild(button);
this._bindHammerToDiv(button, this.addNodeMode.bind(this));
}
_createAddEdgeButton(locale) {
let button = this._createButton('addEdge', 'vis-button vis-connect', locale['addEdge'] || this.options.locales['en']['addEdge']);
this.manipulationDiv.appendChild(button);
this._bindHammerToDiv(button, this.addEdgeMode.bind(this));
}
_createEditNodeButton(locale) {
let button = this._createButton('editNodeMode', 'vis-button vis-edit', locale['editNode'] || this.options.locales['en']['editNode']);
this.manipulationDiv.appendChild(button);
this._bindHammerToDiv(button, this.editNodeMode.bind(this));
}
_createEditEdgeButton(locale) {
let button = this._createButton('editEdge', 'vis-button vis-edit', locale['editEdge'] || this.options.locales['en']['editEdge']);
this.manipulationDiv.appendChild(button);
this._bindHammerToDiv(button, this.editEdgeMode.bind(this));
}
_createDeleteButton(locale) {
let button = this._createButton('delete', 'vis-button vis-delete', locale['del'] || this.options.locales['en']['del']);
this.manipulationDiv.appendChild(button);
this._bindHammerToDiv(button, this.deleteSelected.bind(this));
}
_createBackButton(locale) {
let button = this._createButton('back', 'vis-button vis-back', locale['back'] || this.options.locales['en']['back']);
this.manipulationDiv.appendChild(button);
this._bindHammerToDiv(button, this.showManipulatorToolbar.bind(this));
}
_createButton(id, className, label, labelClassName = 'vis-label') {
this.manipulationDOM[id+'Div'] = document.createElement('div');
this.manipulationDOM[id+'Div'].className = className;
this.manipulationDOM[id+'Label'] = document.createElement('div');
this.manipulationDOM[id+'Label'].className = labelClassName;
this.manipulationDOM[id+'Label'].innerHTML = label;
this.manipulationDOM[id+'Div'].appendChild(this.manipulationDOM[id+'Label']);
return this.manipulationDOM[id+'Div'];
}
_createDescription(label) {
this.manipulationDiv.appendChild(
this._createButton('description', 'vis-button vis-none', label)
);
}
// -------------------------- End of DOM functions for buttons ------------------------------//
/**
* this binds an event until cleanup by the clean functions.
* @param event
* @param newFunction
* @private
*/
_temporaryBindEvent(event, newFunction) {
this.temporaryEventFunctions.push({event:event, boundFunction:newFunction});
this.body.emitter.on(event, newFunction);
}
/**
* this overrides an UI function until cleanup by the clean function
* @param UIfunctionName
* @param newFunction
* @private
*/
_temporaryBindUI(UIfunctionName, newFunction) {
if (this.body.eventListeners[UIfunctionName] !== undefined) {
this.temporaryUIFunctions[UIfunctionName] = this.body.eventListeners[UIfunctionName];
this.body.eventListeners[UIfunctionName] = newFunction;
}
else {
throw new Error('This UI function does not exist. Typo? You tried: ' + UIfunctionName + ' possible are: ' + JSON.stringify(Object.keys(this.body.eventListeners)));
}
}
/**
* Restore the overridden UI functions to their original state.
*
* @private
*/
_unbindTemporaryUIs() {
for (let functionName in this.temporaryUIFunctions) {
if (this.temporaryUIFunctions.hasOwnProperty(functionName)) {
this.body.eventListeners[functionName] = this.temporaryUIFunctions[functionName];
delete this.temporaryUIFunctions[functionName];
}
}
this.temporaryUIFunctions = {};
}
/**
* Unbind the events created by _temporaryBindEvent
* @private
*/
_unbindTemporaryEvents() {
for (let i = 0; i < this.temporaryEventFunctions.length; i++) {
let eventName = this.temporaryEventFunctions[i].event;
let boundFunction = this.temporaryEventFunctions[i].boundFunction;
this.body.emitter.off(eventName, boundFunction);
}
this.temporaryEventFunctions = [];
}
/**
* Bind an hammer instance to a DOM element.
* @param domElement
* @param funct
*/
_bindHammerToDiv(domElement, boundFunction) {
let hammer = new Hammer(domElement, {});
hammerUtil.onTouch(hammer, boundFunction);
this.manipulationHammers.push(hammer);
}
/**
* Neatly clean up temporary edges and nodes
* @private
*/
_cleanupTemporaryNodesAndEdges() {
// _clean temporary edges
for (let i = 0; i < this.temporaryIds.edges.length; i++) {
this.body.edges[this.temporaryIds.edges[i]].disconnect();
delete this.body.edges[this.temporaryIds.edges[i]];
let indexTempEdge = this.body.edgeIndices.indexOf(this.temporaryIds.edges[i]);
if (indexTempEdge !== -1) {this.body.edgeIndices.splice(indexTempEdge,1);}
}
// _clean temporary nodes
for (let i = 0; i < this.temporaryIds.nodes.length; i++) {
delete this.body.nodes[this.temporaryIds.nodes[i]];
let indexTempNode = this.body.nodeIndices.indexOf(this.temporaryIds.nodes[i]);
if (indexTempNode !== -1) {this.body.nodeIndices.splice(indexTempNode,1);}
}
this.temporaryIds = {nodes: [], edges: []};
}
// ------------------------------------------ EDIT EDGE FUNCTIONS -----------------------------------------//
/**
* the touch is used to get the position of the initial click
* @param event
* @private
*/
_controlNodeTouch(event) {
this.selectionHandler.unselectAll();
this.lastTouch = this.body.functions.getPointer(event.center);
this.lastTouch.translation = util.extend({},this.body.view.translation); // copy the object
}
/**
* the drag start is used to mark one of the control nodes as selected.
* @param event
* @private
*/
_controlNodeDragStart(event) {
let pointer = this.lastTouch;
let pointerObj = this.selectionHandler._pointerToPositionObject(pointer);
let from = this.body.nodes[this.temporaryIds.nodes[0]];
let to = this.body.nodes[this.temporaryIds.nodes[1]];
let edge = this.body.edges[this.edgeBeingEditedId];
this.selectedControlNode = undefined;
let fromSelect = from.isOverlappingWith(pointerObj);
let toSelect = to.isOverlappingWith(pointerObj);
if (fromSelect === true) {
this.selectedControlNode = from;
edge.edgeType.from = from;
}
else if (toSelect === true) {
this.selectedControlNode = to;
edge.edgeType.to = to;
}
this.body.emitter.emit('_redraw');
}
/**
* dragging the control nodes or the canvas
* @param event
* @private
*/
_controlNodeDrag(event) {
this.body.emitter.emit('disablePhysics');
let pointer = this.body.functions.getPointer(event.center);
let pos = this.canvas.DOMtoCanvas(pointer);
if (this.selectedControlNode !== undefined) {
this.selectedControlNode.x = pos.x;
this.selectedControlNode.y = pos.y;
}
else {
// if the drag was not started properly because the click started outside the network div, start it now.
let diffX = pointer.x - this.lastTouch.x;
let diffY = pointer.y - this.lastTouch.y;
this.body.view.translation = {x:this.lastTouch.translation.x + diffX, y:this.lastTouch.translation.y + diffY};
}
this.body.emitter.emit('_redraw');
}
/**
* connecting or restoring the control nodes.
* @param event
* @private
*/
_controlNodeDragEnd(event) {
let pointer = this.body.functions.getPointer(event.center);
let pointerObj = this.selectionHandler._pointerToPositionObject(pointer);
let edge = this.body.edges[this.edgeBeingEditedId];
let overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj);
let node = undefined;
for (let i = overlappingNodeIds.length-1; i >= 0; i--) {
if (overlappingNodeIds[i] !== this.selectedControlNode.id) {
node = this.body.nodes[overlappingNodeIds[i]];
break;
}
}
// perform the connection
if (node !== undefined && this.selectedControlNode !== undefined) {
if (node.isCluster === true) {
alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError'])
}
else {
let from = this.body.nodes[this.temporaryIds.nodes[0]];
if (this.selectedControlNode.id === from.id) {
this._performEditEdge(node.id, edge.to.id);
}
else {
this._performEditEdge(edge.from.id, node.id);
}
}
}
else {
edge.updateEdgeType();
this.body.emitter.emit('restorePhysics');
}
this.body.emitter.emit('_redraw');
}
// ------------------------------------ END OF EDIT EDGE FUNCTIONS -----------------------------------------//
// ------------------------------------------- ADD EDGE FUNCTIONS -----------------------------------------//
/**
* the function bound to the selection event. It checks if you want to connect a cluster and changes the description
* to walk the user through the process.
*
* @private
*/
_handleConnect(event) {
// check to avoid double fireing of this function.
if (new Date().valueOf() - this.touchTime > 100) {
this.lastTouch = this.body.functions.getPointer(event.center);
this.lastTouch.translation = util.extend({},this.body.view.translation); // copy the object
let pointer = this.lastTouch;
let node = this.selectionHandler.getNodeAt(pointer);
if (node !== undefined) {
if (node.isCluster === true) {
alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError'])
}
else {
// create a node the temporary line can look at
let targetNode = this._getNewTargetNode(node.x,node.y);
this.body.nodes[targetNode.id] = targetNode;
this.body.nodeIndices.push(targetNode.id);
// create a temporary edge
let connectionEdge = this.body.functions.createEdge({
id: 'connectionEdge' + util.randomUUID(),
from: node.id,
to: targetNode.id,
physics: false,
smooth: {
enabled: true,
dynamic: false,
type: 'continuous',
roundness: 0.5
}
});
this.body.edges[connectionEdge.id] = connectionEdge;
this.body.edgeIndices.push(connectionEdge.id);
this.temporaryIds.nodes.push(targetNode.id);
this.temporaryIds.edges.push(connectionEdge.id);
}
}
this.touchTime = new Date().valueOf();
}
}
_dragControlNode(event) {
let pointer = this.body.functions.getPointer(event.center);
if (this.temporaryIds.nodes[0] !== undefined) {
let targetNode = this.body.nodes[this.temporaryIds.nodes[0]]; // there is only one temp node in the add edge mode.
targetNode.x = this.canvas._XconvertDOMtoCanvas(pointer.x);
targetNode.y = this.canvas._YconvertDOMtoCanvas(pointer.y);
this.body.emitter.emit('_redraw');
}
else {
let diffX = pointer.x - this.lastTouch.x;
let diffY = pointer.y - this.lastTouch.y;
this.body.view.translation = {x:this.lastTouch.translation.x + diffX, y:this.lastTouch.translation.y + diffY};
}
}
/**
* Connect the new edge to the target if one exists, otherwise remove temp line
* @param event
* @private
*/
_finishConnect(event) {
let pointer = this.body.functions.getPointer(event.center);
let pointerObj = this.selectionHandler._pointerToPositionObject(pointer);
// remember the edge id
let connectFromId = undefined;
if (this.temporaryIds.edges[0] !== undefined) {
connectFromId = this.body.edges[this.temporaryIds.edges[0]].fromId;
}
// get the overlapping node but NOT the temporary node;
let overlappingNodeIds = this.selectionHandler._getAllNodesOverlappingWith(pointerObj);
let node = undefined;
for (let i = overlappingNodeIds.length-1; i >= 0; i--) {
// if the node id is NOT a temporary node, accept the node.
if (this.temporaryIds.nodes.indexOf(overlappingNodeIds[i]) === -1) {
node = this.body.nodes[overlappingNodeIds[i]];
break;
}
}
// clean temporary nodes and edges.
this._cleanupTemporaryNodesAndEdges();
// perform the connection
if (node !== undefined) {
if (node.isCluster === true) {
alert(this.options.locales[this.options.locale]['createEdgeError'] || this.options.locales['en']['createEdgeError']);
}
else {
if (this.body.nodes[connectFromId] !== undefined && this.body.nodes[node.id] !== undefined) {
this._performAddEdge(connectFromId, node.id);
}
}
}
this.body.emitter.emit('_redraw');
}
// --------------------------------------- END OF ADD EDGE FUNCTIONS -------------------------------------//
// ------------------------------ Performing all the actual data manipulation ------------------------//
/**
* Adds a node on the specified location
*/
_performAddNode(clickData) {
let defaultData = {
id: util.randomUUID(),
x: clickData.pointer.canvas.x,
y: clickData.pointer.canvas.y,
label: 'new'
};
if (typeof this.options.addNode === 'function') {
if (this.options.addNode.length === 2) {
this.options.addNode(defaultData, (finalizedData) => {
if (finalizedData !== null && finalizedData !== undefined && this.inMode === 'addNode') { // if for whatever reason the mode has changes (due to dataset change) disregard the callback
this.body.data.nodes.add(finalizedData);
this.showManipulatorToolbar();
}
});
}
else {
throw new Error('The function for add does not support two arguments (data,callback)');
this.showManipulatorToolbar();
}
}
else {
this.body.data.nodes.add(defaultData);
this.showManipulatorToolbar();
}
}
/**
* connect two nodes with a new edge.
*
* @private
*/
_performAddEdge(sourceNodeId, targetNodeId) {
let defaultData = {from: sourceNodeId, to: targetNodeId};
if (typeof this.options.addEdge === 'function') {
if (this.options.addEdge.length === 2) {
this.options.addEdge(defaultData, (finalizedData) => {
if (finalizedData !== null && finalizedData !== undefined && this.inMode === 'addEdge') { // if for whatever reason the mode has changes (due to dataset change) disregard the callback
this.body.data.edges.add(finalizedData);
this.selectionHandler.unselectAll();
this.showManipulatorToolbar();
}
});
}
else {
throw new Error('The function for connect does not support two arguments (data,callback)');
}
}
else {
this.body.data.edges.add(defaultData);
this.selectionHandler.unselectAll();
this.showManipulatorToolbar();
}
}
/**
* connect two nodes with a new edge.
*
* @private
*/
_performEditEdge(sourceNodeId, targetNodeId) {
let defaultData = {id: this.edgeBeingEditedId, from: sourceNodeId, to: targetNodeId};
if (typeof this.options.editEdge === 'function') {
if (this.options.editEdge.length === 2) {
this.options.editEdge(defaultData, (finalizedData) => {
if (finalizedData === null || finalizedData === undefined || this.inMode !== 'editEdge') { // if for whatever reason the mode has changes (due to dataset change) disregard the callback) {
this.body.edges[defaultData.id].updateEdgeType();
this.body.emitter.emit('_redraw');
}
else {
this.body.data.edges.update(finalizedData);
this.selectionHandler.unselectAll();
this.showManipulatorToolbar();
}
});
}
else {
throw new Error('The function for edit does not support two arguments (data, callback)');
}
}
else {
this.body.data.edges.update(defaultData);
this.selectionHandler.unselectAll();
this.showManipulatorToolbar();
}
}
}
export default ManipulationSystem;
|
/*!
* MockJax - jQuery Plugin to Mock Ajax requests
*
* Version: 1.4.0
* Released: 2011-02-04
* Source: http://github.com/appendto/jquery-mockjax
* Docs: http://enterprisejquery.com/2010/07/mock-your-ajax-requests-with-mockjax-for-rapid-development
* Plugin: mockjax
* Author: Jonathan Sharp (http://jdsharp.com)
* License: MIT,GPL
*
* Copyright (c) 2010 appendTo LLC.
* Dual licensed under the MIT or GPL licenses.
* http://appendto.com/open-source-licenses
*/
(function($) {
var _ajax = $.ajax,
mockHandlers = [];
function parseXML(xml) {
if ( window['DOMParser'] == undefined && window.ActiveXObject ) {
DOMParser = function() { };
DOMParser.prototype.parseFromString = function( xmlString ) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML( xmlString );
return doc;
};
}
try {
var xmlDoc = ( new DOMParser() ).parseFromString( xml, 'text/xml' );
if ( $.isXMLDoc( xmlDoc ) ) {
var err = $('parsererror', xmlDoc);
if ( err.length == 1 ) {
throw('Error: ' + $(xmlDoc).text() );
}
} else {
throw('Unable to parse XML');
}
} catch( e ) {
var msg = ( e.name == undefined ? e : e.name + ': ' + e.message );
$(document).trigger('xmlParseError', [ msg ]);
return undefined;
}
return xmlDoc;
}
$.extend({
ajax: function(origSettings) {
var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings),
mock = false;
// Iterate over our mock handlers (in registration order) until we find
// one that is willing to intercept the request
$.each(mockHandlers, function(k, v) {
if ( !mockHandlers[k] ) {
return;
}
var m = null;
// If the mock was registered with a function, let the function decide if we
// want to mock this request
if ( $.isFunction(mockHandlers[k]) ) {
m = mockHandlers[k](s);
} else {
m = mockHandlers[k];
// Inspect the URL of the request and check if the mock handler's url
// matches the url for this ajax request
if ( $.isFunction(m.url.test) ) {
// The user provided a regex for the url, test it
if ( !m.url.test( s.url ) ) {
m = null;
}
} else {
// Look for a simple wildcard '*' or a direct URL match
var star = m.url.indexOf('*');
if ( ( m.url != '*' && m.url != s.url && star == -1 ) ||
( star > -1 && m.url.substr(0, star) != s.url.substr(0, star) ) ) {
// The url we tested did not match the wildcard *
m = null;
}
}
if ( m ) {
// Inspect the data submitted in the request (either POST body or GET query string)
if ( m.data && s.data ) {
var identical = false;
// Deep inspect the identity of the objects
(function ident(mock, live) {
// Test for situations where the data is a querystring (not an object)
if (typeof live === 'string') {
// Querystring may be a regex
identical = $.isFunction( mock.test ) ? mock.test(live) : mock == live;
return identical;
}
$.each(mock, function(k, v) {
if ( live[k] === undefined ) {
identical = false;
return false;
} else {
identical = true;
if ( typeof live[k] == 'object' ) {
return ident(mock[k], live[k]);
} else {
if ( $.isFunction( mock[k].test ) ) {
identical = mock[k].test(live[k]);
} else {
identical = ( mock[k] == live[k] );
}
return identical;
}
}
});
})(m.data, s.data);
// They're not identical, do not mock this request
if ( identical == false ) {
m = null;
}
}
// Inspect the request type
if ( m && m.type && m.type != s.type ) {
// The request type doesn't match (GET vs. POST)
m = null;
}
}
}
if ( m ) {
mock = true;
// Handle console logging
var c = $.extend({}, $.mockjaxSettings, m);
if ( c.log && $.isFunction(c.log) ) {
c.log('MOCK ' + s.type.toUpperCase() + ': ' + s.url, $.extend({}, s));
}
var jsre = /=\?(&|$)/, jsc = (new Date()).getTime();
// Handle JSONP Parameter Callbacks, we need to replicate some of the jQuery core here
// because there isn't an easy hook for the cross domain script tag of jsonp
if ( s.dataType === "jsonp" ) {
if ( s.type.toUpperCase() === "GET" ) {
if ( !jsre.test( s.url ) ) {
s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
}
} else if ( !s.data || !jsre.test(s.data) ) {
s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
}
s.dataType = "json";
}
// Build temporary JSONP function
if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
jsonp = s.jsonpCallback || ("jsonp" + jsc++);
// Replace the =? sequence both in the query string and the data
if ( s.data ) {
s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
}
s.url = s.url.replace(jsre, "=" + jsonp + "$1");
// We need to make sure
// that a JSONP style response is executed properly
s.dataType = "script";
// Handle JSONP-style loading
window[ jsonp ] = window[ jsonp ] || function( tmp ) {
data = tmp;
success();
complete();
// Garbage collect
window[ jsonp ] = undefined;
try {
delete window[ jsonp ];
} catch(e) {}
if ( head ) {
head.removeChild( script );
}
};
}
var rurl = /^(\w+:)?\/\/([^\/?#]+)/,
parts = rurl.exec( s.url ),
remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
// Test if we are going to create a script tag (if so, intercept & mock)
if ( s.dataType === "script" && s.type.toUpperCase() === "GET" && remote ) {
// Synthesize the mock request for adding a script tag
var callbackContext = origSettings && origSettings.context || s;
function success() {
// If a local callback was specified, fire it and pass it the data
if ( s.success ) {
s.success.call( callbackContext, ( m.response ? m.response.toString() : m.responseText || ''), status, {} );
}
// Fire the global callback
if ( s.global ) {
trigger( "ajaxSuccess", [{}, s] );
}
}
function complete() {
// Process result
if ( s.complete ) {
s.complete.call( callbackContext, {} , status );
}
// The request was completed
if ( s.global ) {
trigger( "ajaxComplete", [{}, s] );
}
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active ) {
jQuery.event.trigger( "ajaxStop" );
}
}
function trigger(type, args) {
(s.context ? jQuery(s.context) : jQuery.event).trigger(type, args);
}
if ( m.response && $.isFunction(m.response) ) {
m.response(origSettings);
} else {
$.globalEval(m.responseText);
}
success();
complete();
return false;
}
_ajax.call($, $.extend(true, {}, origSettings, {
// Mock the XHR object
xhr: function() {
// Extend with our default mockjax settings
m = $.extend({}, $.mockjaxSettings, m);
if ( m.contentType ) {
m.headers['content-type'] = m.contentType;
}
// Return our mock xhr object
return {
status: m.status,
readyState: 1,
open: function() { },
send: function() {
// This is a substitute for < 1.4 which lacks $.proxy
var process = (function(that) {
return function() {
return (function() {
// The request has returned
this.status = m.status;
this.readyState = 4;
// We have an executable function, call it to give
// the mock handler a chance to update it's data
if ( $.isFunction(m.response) ) {
m.response(origSettings);
}
// Copy over our mock to our xhr object before passing control back to
// jQuery's onreadystatechange callback
if ( s.dataType == 'json' && ( typeof m.responseText == 'object' ) ) {
this.responseText = JSON.stringify(m.responseText);
} else if ( s.dataType == 'xml' ) {
if ( typeof m.responseXML == 'string' ) {
this.responseXML = parseXML(m.responseXML);
} else {
this.responseXML = m.responseXML;
}
} else {
this.responseText = m.responseText;
}
// jQuery < 1.4 doesn't have onreadystate change for xhr
if ( $.isFunction(this.onreadystatechange) ) {
this.onreadystatechange( m.isTimeout ? 'timeout' : undefined );
}
}).apply(that);
};
})(this);
if ( m.proxy ) {
// We're proxying this request and loading in an external file instead
_ajax({
global: false,
url: m.proxy,
type: m.proxyType,
data: m.data,
dataType: s.dataType,
complete: function(xhr, txt) {
m.responseXML = xhr.responseXML;
m.responseText = xhr.responseText;
if (m.responseTime == 0) {
process();
} else {
this.responseTimer = setTimeout(process, m.responseTime || 0);
}
}
});
} else {
// type == 'POST' || 'GET' || 'DELETE'
if ( s.async === false ) {
// TODO: Blocking delay
process();
} else if(m.responseTime == 0) {
process();
} else {
this.responseTimer = setTimeout(process, m.responseTime || 50);
}
}
},
abort: function() {
clearTimeout(this.responseTimer);
},
setRequestHeader: function() { },
getResponseHeader: function(header) {
// 'Last-modified', 'Etag', 'content-type' are all checked by jQuery
if ( m.headers && m.headers[header] ) {
// Return arbitrary headers
return m.headers[header];
} else if ( header.toLowerCase() == 'last-modified' ) {
return m.lastModified || (new Date()).toString();
} else if ( header.toLowerCase() == 'etag' ) {
return m.etag || '';
} else if ( header.toLowerCase() == 'content-type' ) {
return m.contentType || 'text/plain';
}
},
getAllResponseHeaders: function() {
var headers = '';
$.each(m.headers, function(k, v) {
headers += k + ': ' + v + "\n";
});
return headers;
}
};
}
}));
return false;
}
});
// We don't have a mock request, trigger a normal request
if ( !mock ) {
return _ajax.apply($, arguments);
} else {
return mock;
}
}
});
$.mockjaxSettings = {
//url: null,
//type: 'GET',
log: function(msg) {
window['console'] && window.console.log && window.console.log(msg);
},
status: 200,
responseTime: 500,
isTimeout: false,
contentType: 'text/plain',
response: '',
responseText: '',
responseXML: '',
proxy: '',
proxyType: 'GET',
lastModified: null,
etag: '',
headers: {
etag: 'IJF@H#@923uf8023hFO@I#H#',
'content-type' : 'text/plain'
}
};
$.mockjax = function(settings) {
var i = mockHandlers.length;
mockHandlers[i] = settings;
return i;
};
$.mockjaxClear = function(i) {
if ( arguments.length == 1 ) {
mockHandlers[i] = null;
} else {
mockHandlers = [];
}
};
})(jQuery);
|
'use strict';
module.exports = function c() {}; |
module.exports = {
defaultProps: {
unit: 'px'
}
}; |
define("dgrid/extensions/ColumnHider", ["dojo/_base/declare", "dojo/has", "dojo/on", "../util/misc", "put-selector/put", "dojo/i18n!./nls/columnHider", "xstyle/css!../css/extensions/ColumnHider.css"],
function(declare, has, listen, miscUtil, put, i18n){
/*
* Column Hider plugin for dgrid
* Originally contributed by TRT 2011-09-28
*
* A dGrid plugin that attaches a menu to a dgrid, along with a way of opening it,
* that will allow you to show and hide columns. A few caveats:
*
* 1. Menu placement is entirely based on CSS definitions.
* 2. If you want columns initially hidden, you must add "hidden: true" to your
* column definition.
* 3. This implementation does NOT support ColumnSet, and has not been tested
* with multi-subrow records.
* 4. Column show/hide is controlled via straight up HTML checkboxes. If you
* are looking for something more fancy, you'll probably need to use this
* definition as a template to write your own plugin.
*
*/
var activeGrid, // references grid for which the menu is currently open
bodyListener, // references pausable event handler for body mousedown
// Need to handle old IE specially for checkbox listener and for attribute.
hasIE = has("ie"),
hasIEQuirks = hasIE && has("quirks"),
forAttr = hasIE < 8 || hasIEQuirks ? "htmlFor" : "for";
function getColumnIdFromCheckbox(cb, grid){
// Given one of the checkboxes from the hider menu,
// return the id of the corresponding column.
// (e.g. gridIDhere-hider-menu-check-colIDhere -> colIDhere)
return cb.id.substr(grid.id.length + 18);
}
return declare(null, {
// hiderMenuNode: DOMNode
// The node for the menu to show/hide columns.
hiderMenuNode: null,
// hiderToggleNode: DOMNode
// The node for the toggler to open the menu.
hiderToggleNode: null,
// i18nColumnHider: Object
// This object contains all of the internationalized strings for
// the ColumnHider extension as key/value pairs.
i18nColumnHider: i18n,
// _hiderMenuOpened: Boolean
// Records the current open/closed state of the menu.
_hiderMenuOpened: false,
// _columnHiderRules: Object
// Hash containing handles returned from addCssRule.
_columnHiderRules: null,
// _columnHiderCheckboxes: Object
// Hash containing checkboxes generated for menu items.
_columnHiderCheckboxes: null,
_renderHiderMenuEntries: function(){
// summary:
// Iterates over subRows for the sake of adding items to the
// column hider menu.
var subRows = this.subRows,
first = true,
srLength, cLength, sr, c, checkbox;
delete this._columnHiderFirstCheckbox;
for(sr = 0, srLength = subRows.length; sr < srLength; sr++){
for(c = 0, cLength = subRows[sr].length; c < cLength; c++){
this._renderHiderMenuEntry(subRows[sr][c]);
if(first){
first = false;
this._columnHiderFirstCheckbox =
this._columnHiderCheckboxes[subRows[sr][c].id];
}
}
}
},
_renderHiderMenuEntry: function(col){
var id = col.id,
div, checkId, checkbox;
if(col.hidden){
// Hidden state is true; hide the column.
this._hideColumn(id);
}
// Allow cols to opt out of the hider (e.g. for selector column).
if(col.unhidable){ return; }
// Create the checkbox and label for each column selector.
div = put("div.dgrid-hider-menu-row");
checkId = this.domNode.id + "-hider-menu-check-" + id;
this._columnHiderCheckboxes[id] = checkbox = put(div, "input#" + checkId +
".dgrid-hider-menu-check.hider-menu-check-" + id + "[type=checkbox]");
put(div, "label.dgrid-hider-menu-label.hider-menu-label" + id +
"[" + forAttr + "=" + checkId + "]", col.label || col.field || "");
put(this.hiderMenuNode, div);
if(!col.hidden){
// Hidden state is false; checkbox should be initially checked.
// (Need to do this after adding to DOM to avoid IE6 clobbering it.)
checkbox.checked = true;
}
},
renderHeader: function(){
var grid = this,
hiderMenuNode = this.hiderMenuNode,
hiderToggleNode = this.hiderToggleNode,
id;
this.inherited(arguments);
if(!hiderMenuNode){ // first run
// Assume that if this plugin is used, then columns are hidable.
// Create the toggle node.
hiderToggleNode = this.hiderToggleNode =
put(this.headerScrollNode, "button.ui-icon.dgrid-hider-toggle[type=button]");
this._listeners.push(listen(hiderToggleNode, "click", function(e){
grid._toggleColumnHiderMenu(e);
}));
// Create the column list, with checkboxes.
hiderMenuNode = this.hiderMenuNode =
put("div#dgrid-hider-menu-" + this.id +
".dgrid-hider-menu[role=dialog][aria-label=" + this.i18nColumnHider.popupLabel + "]");
this._listeners.push(listen(hiderMenuNode, "keyup", function (e) {
var charOrCode = e.charCode || e.keyCode;
if(charOrCode === /*ESCAPE*/ 27){
grid._toggleColumnHiderMenu(e);
hiderToggleNode.focus();
}
}));
// Make sure our menu is initially hidden, then attach to the document.
hiderMenuNode.style.display = "none";
put(this.domNode, hiderMenuNode);
// Hook up delegated listener for modifications to checkboxes.
this._listeners.push(listen(hiderMenuNode,
".dgrid-hider-menu-check:" + (hasIE < 9 || hasIEQuirks ? "click" : "change"),
function(e){
grid._updateColumnHiddenState(
getColumnIdFromCheckbox(e.target, grid), !e.target.checked);
}
));
this._listeners.push(listen(hiderMenuNode, "mousedown", function(e){
// Stop click events from propagating here, so that we can simply
// track body clicks for hide without having to drill-up to check.
e.stopPropagation();
}));
// Hook up top-level mousedown listener if it hasn't been yet.
if(!bodyListener){
bodyListener = listen.pausable(document, "mousedown", function(e){
// If an event reaches this listener, the menu is open,
// but a click occurred outside, so close the dropdown.
activeGrid && activeGrid._toggleColumnHiderMenu(e);
});
bodyListener.pause(); // pause initially; will resume when menu opens
}
}else{ // subsequent run
// Remove active rules, and clear out the menu (to be repopulated).
for(id in this._columnHiderRules){
this._columnHiderRules[id].remove();
}
hiderMenuNode.innerHTML = "";
}
this._columnHiderCheckboxes = {};
this._columnHiderRules = {};
// Populate menu with checkboxes/labels based on current columns.
this._renderHiderMenuEntries();
},
destroy: function(){
this.inherited(arguments);
// Remove any remaining rules applied to hidden columns.
for(var id in this._columnHiderRules){
this._columnHiderRules[id].remove();
}
},
isColumnHidden: function(id){
// summary:
// Convenience method to determine current hidden state of a column
return !!this._columnHiderRules[id];
},
_toggleColumnHiderMenu: function(){
var hidden = this._hiderMenuOpened, // reflects hidden state after toggle
hiderMenuNode = this.hiderMenuNode,
domNode = this.domNode,
firstCheckbox;
// Show or hide the hider menu
hiderMenuNode.style.display = (hidden ? "none" : "");
// Adjust height of menu
if (hidden) {
// Clear the set size
hiderMenuNode.style.height = "";
} else {
// Adjust height of the menu if necessary
// Why 12? Based on menu default paddings and border, we need
// to adjust to be 12 pixels shorter. Given the infrequency of
// this style changing, we're assuming it will remain this
// static value of 12 for now, to avoid pulling in any sort of
// computed styles.
if (hiderMenuNode.offsetHeight > domNode.offsetHeight - 12) {
hiderMenuNode.style.height = (domNode.offsetHeight - 12) + "px";
}
// focus on the first checkbox
(firstCheckbox = this._columnHiderFirstCheckbox) && firstCheckbox.focus();
}
// Pause or resume the listener for clicks outside the menu
bodyListener[hidden ? "pause" : "resume"]();
// Update activeGrid appropriately
activeGrid = hidden ? null : this;
// Toggle the instance property
this._hiderMenuOpened = !hidden;
},
_hideColumn: function(id){
// summary:
// Hides the column indicated by the given id.
// Use miscUtil function directly, since we clean these up ourselves anyway
var selectorPrefix = "#" + miscUtil.escapeCssIdentifier(this.domNode.id) + " .dgrid-column-",
tableRule; // used in IE8 code path
if (this._columnHiderRules[id]) {
return;
}
this._columnHiderRules[id] =
miscUtil.addCssRule(selectorPrefix + id, "display: none;");
if(has("ie") === 8 && !has("quirks")){
tableRule = miscUtil.addCssRule(".dgrid-row-table", "display: inline-table;");
window.setTimeout(function(){
tableRule.remove();
}, 0);
}
},
_updateColumnHiddenState: function(id, hidden){
// summary:
// Performs internal work for toggleColumnHiddenState; see the public
// method for more information.
if(!hidden){
this._columnHiderRules[id] && this._columnHiderRules[id].remove();
delete this._columnHiderRules[id];
}else{
this._hideColumn(id);
}
// Update hidden state in actual column definition,
// in case columns are re-rendered.
this.columns[id].hidden = hidden;
// Emit event to notify of column state change.
listen.emit(this.domNode, "dgrid-columnstatechange", {
grid: this,
column: this.columns[id],
hidden: hidden,
bubbles: true
});
// Adjust the size of the header.
this.resize();
},
toggleColumnHiddenState: function(id, hidden){
// summary:
// Shows or hides the column with the given id.
// id: String
// ID of column to show/hide.
// hide: Boolean?
// If specified, explicitly sets the hidden state of the specified
// column. If unspecified, toggles the column from the current state.
if(typeof hidden === "undefined"){ hidden = !this._columnHiderRules[id]; }
this._updateColumnHiddenState(id, hidden);
// Since this can be called directly, re-sync the appropriate checkbox.
this._columnHiderCheckboxes[id].checked = !hidden;
}
});
});
|
/* eslint-disable */
var path = require('path');
var glob = require('glob');
var webpack = require('webpack');
var env = process.env.NODE_ENV;
function createConfig (filepath) {
var filename = path.basename(filepath, '.example.js');
var outputPath = path.dirname(filepath);
return {
entry: path.resolve(__dirname, filepath),
module: {
loaders: [
{ test: /\.js$/, loaders: ['babel-loader'], exclude: /node_modules/ }
]
},
output: {
filename: filename + '.js',
path: path.resolve(__dirname, outputPath)
},
plugins: [
{
apply: function apply(compiler) {
compiler.parser.plugin('expression global', function expressionGlobalPlugin() {
this.state.module.addVariable('global', "(function() { return this; }()) || Function('return this')()")
return false
})
}
},
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(env)
})
]
};
}
module.exports = glob.sync('examples/**/*.example.js').map(createConfig);
|
var session=require('../sessioncache').session;
function Token()
{
}
Token.prototype.auth=function(authentication,callBack)
{
if(authentication.indexOf("Token ")==0)
{
authentication=authentication.slice(6);
}
var data=session.getData(authentication);
var passport;
if(data==null)
{
passport={
status : false,
message : 'You are not login or your session has been expired'
}
}else
{
passport=data.__passport__;
}
passport.token=authentication; //set the token value to make sure
callBack(passport);
}
exports.getInstance=function()
{
return new Token();
} |
describe('Dependencies config', () => {
it('should load jQuery', () => {
expect(jQuery).toBeDefined();
});
it('should register Materialize jQuery plugins', () => {
expect($('div').sideNav).toBeDefined();
});
it('should register Materialize global object', () => {
expect(Materialize).toBeDefined();
});
it('should register Materialize css', () => {
var script = $('link').filter((i, e) => {
return e.href.indexOf('materialize.css') >= 0;
});
expect(script.length).toBe(1);
});
}); |
(function (){
'use strict';
function sanitize ($sanitize){
return function (input) {
if (input === null || input === undefined || input === ''){
input = ' ';
}
return $sanitize(input);
};
}
angular.module('sds-angular-controls').filter('sanitize', sanitize);
})();
|
/**
* @author: @AngularClass
*/
const webpack = require('webpack');
const helpers = require('./helpers');
/**
* Webpack Plugins
*
* problem with copy-webpack-plugin
*/
const AssetsPlugin = require('assets-webpack-plugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const TsConfigPathsPlugin = require('awesome-typescript-loader').TsConfigPathsPlugin;
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const HtmlElementsPlugin = require('./html-elements-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const InlineManifestWebpackPlugin = require('inline-manifest-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const ngcWebpack = require('ngc-webpack');
/**
* Webpack Constants
*/
const HMR = helpers.hasProcessFlag('hot');
const AOT = process.env.BUILD_AOT || helpers.hasNpmFlag('aot');
const METADATA = {
title: 'Angular2 Webpack Starter by @gdi2290 from @AngularClass',
baseUrl: '/',
isDevServer: helpers.isWebpackDevServer(),
HMR: HMR
};
/**
* Webpack configuration
*
* See: http://webpack.github.io/docs/configuration.html#cli
*/
module.exports = function (options) {
isProd = options.env === 'production';
return {
/**
* Cache generated modules and chunks to improve performance for multiple incremental builds.
* This is enabled by default in watch mode.
* You can pass false to disable it.
*
* See: http://webpack.github.io/docs/configuration.html#cache
*/
//cache: false,
/**
* The entry point for the bundle
* Our Angular.js app
*
* See: http://webpack.github.io/docs/configuration.html#entry
*/
entry: {
'polyfills': './src/polyfills.browser.ts',
'main': AOT ? './src/main.browser.aot.ts' :
'./src/main.browser.ts'
},
/**
* Options affecting the resolving of modules.
*
* See: http://webpack.github.io/docs/configuration.html#resolve
*/
resolve: {
/**
* An array of extensions that should be used to resolve modules.
*
* See: http://webpack.github.io/docs/configuration.html#resolve-extensions
*/
extensions: ['.ts', '.js', '.json'],
/**
* An array of directory names to be resolved to the current directory
*/
modules: [helpers.root('src'), helpers.root('node_modules')],
plugins: [
new TsConfigPathsPlugin({
tsconfig: '../tsconfig.json'
})
]
},
/**
* Options affecting the normal modules.
*
* See: http://webpack.github.io/docs/configuration.html#module
*/
module: {
rules: [
/**
* Typescript loader support for .ts
*
* Component Template/Style integration using `angular2-template-loader`
* Angular 2 lazy loading (async routes) via `ng-router-loader`
*
* `ng-router-loader` expects vanilla JavaScript code, not TypeScript code. This is why the
* order of the loader matter.
*
* See: https://github.com/s-panferov/awesome-typescript-loader
* See: https://github.com/TheLarkInn/angular2-template-loader
* See: https://github.com/shlomiassaf/ng-router-loader
*/
{
test: /\.ts$/,
use: [
{
loader: '@angularclass/hmr-loader',
options: {
pretty: !isProd,
prod: isProd
}
},
{
/**
* MAKE SURE TO CHAIN VANILLA JS CODE, I.E. TS COMPILATION OUTPUT.
*/
loader: 'ng-router-loader',
options: {
loader: 'async-import',
genDir: 'compiled',
aot: AOT
}
},
{
loader: 'awesome-typescript-loader',
options: {
configFileName: 'tsconfig.webpack.json',
useCache: !isProd
}
},
{
loader: 'angular2-template-loader'
}
],
exclude: [/\.(spec|e2e)\.ts$/]
},
/**
* Json loader support for *.json files.
*
* See: https://github.com/webpack/json-loader
*/
{
test: /\.json$/,
use: 'json-loader'
},
/**
* To string and css loader support for *.css files (from Angular components)
* Returns file content as string
*
*/
{
test: /\.css$/,
use: ['to-string-loader', 'css-loader'],
exclude: [helpers.root('src', 'styles')]
},
/**
* To string and sass loader support for *.scss files (from Angular components)
* Returns compiled css content as string
*
*/
{
test: /\.scss$/,
use: ['to-string-loader', 'css-loader', 'sass-loader'],
exclude: [helpers.root('src', 'styles')]
},
/**
* Raw loader support for *.html
* Returns file content as string
*
* See: https://github.com/webpack/raw-loader
*/
{
test: /\.html$/,
use: 'raw-loader',
exclude: [helpers.root('src/index.html')]
},
/**
* File loader for supporting images, for example, in CSS files.
*/
{
test: /\.(jpg|png|gif)$/,
use: 'file-loader'
},
/* File loader for supporting fonts, for example, in CSS files.
*/
{
test: /\.(eot|woff2?|svg|ttf)([\?]?.*)$/,
use: 'file-loader'
}
],
},
/**
* Add additional plugins to the compiler.
*
* See: http://webpack.github.io/docs/configuration.html#plugins
*/
plugins: [
new AssetsPlugin({
path: helpers.root('dist'),
filename: 'webpack-assets.json',
prettyPrint: true
}),
/**
* Plugin: ForkCheckerPlugin
* Description: Do type checking in a separate process, so webpack don't need to wait.
*
* See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
*/
new CheckerPlugin(),
/**
* Plugin: CommonsChunkPlugin
* Description: Shares common code between the pages.
* It identifies common modules and put them into a commons chunk.
*
* See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
* See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
*/
new CommonsChunkPlugin({
name: 'polyfills',
chunks: ['polyfills']
}),
/**
* This enables tree shaking of the vendor modules
*/
new CommonsChunkPlugin({
name: 'vendor',
chunks: ['main'],
minChunks: module => /node_modules/.test(module.resource)
}),
/**
* Specify the correct order the scripts will be injected in
*/
new CommonsChunkPlugin({
name: ['polyfills', 'vendor'].reverse()
}),
new CommonsChunkPlugin({
name: ['manifest'],
minChunks: Infinity,
}),
/**
* Plugin: ContextReplacementPlugin
* Description: Provides context to Angular's use of System.import
*
* See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
* See: https://github.com/angular/angular/issues/11580
*/
new ContextReplacementPlugin(
/**
* The (\\|\/) piece accounts for path separators in *nix and Windows
*/
/angular(\\|\/)core(\\|\/)@angular/,
helpers.root('src'), // location of your src
{
/**
* Your Angular Async Route paths relative to this root directory
*/
}
),
/**
* Plugin: CopyWebpackPlugin
* Description: Copy files and directories in webpack.
*
* Copies project static assets.
*
* See: https://www.npmjs.com/package/copy-webpack-plugin
*/
new CopyWebpackPlugin([
{ from: 'src/assets', to: 'assets' },
{ from: 'src/meta'}
],
isProd ? { ignore: [ 'mock-data/**/*' ] } : undefined
),
/**
* Plugin: HtmlWebpackPlugin
* Description: Simplifies creation of HTML files to serve your webpack bundles.
* This is especially useful for webpack bundles that include a hash in the filename
* which changes every compilation.
*
* See: https://github.com/ampedandwired/html-webpack-plugin
*/
new HtmlWebpackPlugin({
template: 'src/index.html',
title: METADATA.title,
chunksSortMode: 'dependency',
metadata: METADATA,
inject: 'head'
}),
/**
* Plugin: ScriptExtHtmlWebpackPlugin
* Description: Enhances html-webpack-plugin functionality
* with different deployment options for your scripts including:
*
* See: https://github.com/numical/script-ext-html-webpack-plugin
*/
new ScriptExtHtmlWebpackPlugin({
defaultAttribute: 'defer'
}),
/**
* Plugin: HtmlElementsPlugin
* Description: Generate html tags based on javascript maps.
*
* If a publicPath is set in the webpack output configuration, it will be automatically added to
* href attributes, you can disable that by adding a "=href": false property.
* You can also enable it to other attribute by settings "=attName": true.
*
* The configuration supplied is map between a location (key) and an element definition object (value)
* The location (key) is then exported to the template under then htmlElements property in webpack configuration.
*
* Example:
* Adding this plugin configuration
* new HtmlElementsPlugin({
* headTags: { ... }
* })
*
* Means we can use it in the template like this:
* <%= webpackConfig.htmlElements.headTags %>
*
* Dependencies: HtmlWebpackPlugin
*/
new HtmlElementsPlugin({
headTags: require('./head-config.common')
}),
/**
* Plugin LoaderOptionsPlugin (experimental)
*
* See: https://gist.github.com/sokra/27b24881210b56bbaff7
*/
new LoaderOptionsPlugin({}),
/**
* Fix Angular 2
*/
new NormalModuleReplacementPlugin(
/facade(\\|\/)async/,
helpers.root('node_modules/@angular/core/src/facade/async.js')
),
new NormalModuleReplacementPlugin(
/facade(\\|\/)collection/,
helpers.root('node_modules/@angular/core/src/facade/collection.js')
),
new NormalModuleReplacementPlugin(
/facade(\\|\/)errors/,
helpers.root('node_modules/@angular/core/src/facade/errors.js')
),
new NormalModuleReplacementPlugin(
/facade(\\|\/)lang/,
helpers.root('node_modules/@angular/core/src/facade/lang.js')
),
new NormalModuleReplacementPlugin(
/facade(\\|\/)math/,
helpers.root('node_modules/@angular/core/src/facade/math.js')
),
new ngcWebpack.NgcWebpackPlugin({
disabled: !AOT,
tsConfig: helpers.root('tsconfig.webpack.json'),
resourceOverride: helpers.root('config/resource-override.js')
}),
/**
* Plugin: InlineManifestWebpackPlugin
* Inline Webpack's manifest.js in index.html
*
* https://github.com/szrenwei/inline-manifest-webpack-plugin
*/
new InlineManifestWebpackPlugin(),
],
/**
* Include polyfills or mocks for various node stuff
* Description: Node configuration
*
* See: https://webpack.github.io/docs/configuration.html#node
*/
node: {
global: true,
crypto: 'empty',
process: true,
module: false,
clearImmediate: false,
setImmediate: false
}
};
}
|
/*eslint no-unused-vars: ["error", { "varsIgnorePattern": "gmlResponseInformationHitsWfs" }] */
goog.provide('ngeo.test.data.msGMLOutputInformationHitsWfs');
var gmlResponseInformationHitsWfs =
'<?xml version=\'1.0\' encoding="UTF-8" ?>' +
'<wfs:FeatureCollection' +
' xmlns:ms="http://mapserver.gis.umn.edu/mapserver"' +
' xmlns:gml="http://www.opengis.net/gml"' +
' xmlns:wfs="http://www.opengis.net/wfs"' +
' xmlns:ogc="http://www.opengis.net/ogc"' +
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' +
' xsi:schemaLocation="http://mapserver.gis.umn.edu/mapserver https://geomapfish-demo.camptocamp.net/1.6/mapserv?SERVICE=WFS&VERSION=1.1.0&REQUEST=DescribeFeatureType&TYPENAME=feature:information,feature:bus_stop&OUTPUTFORMAT=SFE_XMLSCHEMA http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd"' +
' numberOfFeatures="3">' +
'</wfs:FeatureCollection>';
|
import React from 'react'
import Icon from 'react-icon-base'
const MdRadioButtonChecked = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m20 33.4q5.5 0 9.4-4t4-9.4-4-9.4-9.4-4-9.4 4-4 9.4 4 9.4 9.4 4z m0-30q6.9 0 11.8 4.8t4.8 11.8-4.8 11.8-11.8 4.8-11.8-4.8-4.8-11.8 4.8-11.8 11.8-4.8z m0 8.2q3.4 0 5.9 2.5t2.5 5.9-2.5 5.9-5.9 2.5-5.9-2.5-2.5-5.9 2.5-5.9 5.9-2.5z"/></g>
</Icon>
)
export default MdRadioButtonChecked
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "m12.87 15.07-2.54-2.51.03-.03c1.74-1.94 2.98-4.17 3.71-6.53H17V4h-7V2H8v2H1v1.99h11.17C11.5 7.92 10.44 9.75 9 11.35 8.07 10.32 7.3 9.19 6.69 8h-2c.73 1.63 1.73 3.17 2.98 4.56l-5.09 5.02L4 19l5-5 3.11 3.11.76-2.04zM18.5 10h-2L12 22h2l1.12-3h4.75L21 22h2l-4.5-12zm-2.62 7 1.62-4.33L19.12 17h-3.24z"
}), 'TranslateOutlined'); |
'use strict';
var isObservableValue = require('observable-value/is-observable-value')
, Database = require('../../../');
module.exports = function (a) {
var db = new Database(), proto = db.Object.prototype, obj = new db.Object()
, event, observable;
obj.set('raz', 1);
observable = obj._raz;
a(observable.value, 1, "Observable");
a(isObservableValue(observable), true, "Observable value");
a(observable.lastModified, obj._getPropertyLastModified_(proto.$raz._sKey_),
"Initial last modified");
observable.on('change', function (e) {
event = e;
});
observable.value = 13;
a.deep(event, { type: 'change', newValue: 13, oldValue: 1,
dbjs: event.dbjs, target: observable }, "Event");
a(observable.lastModified, event.dbjs.stamp, "Evented last modified");
a(obj.raz, 13, "Value");
a(observable._lastModified.value, event.dbjs.stamp,
"Last modified observable");
obj.raz = 14;
a(observable._lastModified.value, obj.$raz._lastOwnEvent_.stamp,
"Last modified observable: Update");
obj.raz = null;
a(observable.toString(), '');
obj.set('foo', 2);
a(obj._foo.lastModified, obj._getPropertyLastModified_('foo'));
obj.foo = 2;
a(obj._foo.lastModified, obj._getPropertyLastModified_('foo'));
};
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = transformClass;
function _helperFunctionName() {
const data = _interopRequireDefault(require("@babel/helper-function-name"));
_helperFunctionName = function () {
return data;
};
return data;
}
function _helperReplaceSupers() {
const data = _interopRequireWildcard(require("@babel/helper-replace-supers"));
_helperReplaceSupers = function () {
return data;
};
return data;
}
function _helperOptimiseCallExpression() {
const data = _interopRequireDefault(require("@babel/helper-optimise-call-expression"));
_helperOptimiseCallExpression = function () {
return data;
};
return data;
}
function defineMap() {
const data = _interopRequireWildcard(require("@babel/helper-define-map"));
defineMap = function () {
return data;
};
return data;
}
function _core() {
const data = require("@babel/core");
_core = function () {
return data;
};
return data;
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function buildConstructor(classRef, constructorBody, node) {
const func = _core().types.functionDeclaration(_core().types.cloneNode(classRef), [], constructorBody);
_core().types.inherits(func, node);
return func;
}
const verifyConstructorVisitor = _core().traverse.visitors.merge([_helperReplaceSupers().environmentVisitor, {
Super(path, state) {
if (state.isDerived) return;
const {
node,
parentPath
} = path;
if (parentPath.isCallExpression({
callee: node
})) {
throw path.buildCodeFrameError("super() is only allowed in a derived constructor");
}
},
ThisExpression(path, state) {
if (!state.isDerived) return;
const {
node,
parentPath
} = path;
if (parentPath.isMemberExpression({
object: node
})) {
return;
}
const assertion = _core().types.callExpression(state.file.addHelper("assertThisInitialized"), [node]);
path.replaceWith(assertion);
path.skip();
}
}]);
function transformClass(path, file, builtinClasses, isLoose) {
const classState = {
parent: undefined,
scope: undefined,
node: undefined,
path: undefined,
file: undefined,
classId: undefined,
classRef: undefined,
superName: undefined,
superReturns: [],
isDerived: false,
extendsNative: false,
construct: undefined,
constructorBody: undefined,
userConstructor: undefined,
userConstructorPath: undefined,
hasConstructor: false,
instancePropBody: [],
instancePropRefs: {},
staticPropBody: [],
body: [],
bareSupers: new Set(),
superThises: [],
pushedConstructor: false,
pushedInherits: false,
protoAlias: null,
isLoose: false,
hasInstanceDescriptors: false,
hasStaticDescriptors: false,
instanceMutatorMap: {},
staticMutatorMap: {}
};
const setState = newState => {
Object.assign(classState, newState);
};
const findThisesVisitor = _core().traverse.visitors.merge([_helperReplaceSupers().environmentVisitor, {
ThisExpression(path) {
classState.superThises.push(path);
}
}]);
function pushToMap(node, enumerable, kind = "value", scope) {
let mutatorMap;
if (node.static) {
setState({
hasStaticDescriptors: true
});
mutatorMap = classState.staticMutatorMap;
} else {
setState({
hasInstanceDescriptors: true
});
mutatorMap = classState.instanceMutatorMap;
}
const map = defineMap().push(mutatorMap, node, kind, classState.file, scope);
if (enumerable) {
map.enumerable = _core().types.booleanLiteral(true);
}
return map;
}
function maybeCreateConstructor() {
let hasConstructor = false;
const paths = classState.path.get("body.body");
for (const path of paths) {
hasConstructor = path.equals("kind", "constructor");
if (hasConstructor) break;
}
if (hasConstructor) return;
let params, body;
if (classState.isDerived) {
const constructor = _core().template.expression.ast`
(function () {
super(...arguments);
})
`;
params = constructor.params;
body = constructor.body;
} else {
params = [];
body = _core().types.blockStatement([]);
}
classState.path.get("body").unshiftContainer("body", _core().types.classMethod("constructor", _core().types.identifier("constructor"), params, body));
}
function buildBody() {
maybeCreateConstructor();
pushBody();
verifyConstructor();
if (classState.userConstructor) {
const {
constructorBody,
userConstructor,
construct
} = classState;
constructorBody.body = constructorBody.body.concat(userConstructor.body.body);
_core().types.inherits(construct, userConstructor);
_core().types.inherits(constructorBody, userConstructor.body);
}
pushDescriptors();
}
function pushBody() {
const classBodyPaths = classState.path.get("body.body");
for (const path of classBodyPaths) {
const node = path.node;
if (path.isClassProperty()) {
throw path.buildCodeFrameError("Missing class properties transform.");
}
if (node.decorators) {
throw path.buildCodeFrameError("Method has decorators, put the decorator plugin before the classes one.");
}
if (_core().types.isClassMethod(node)) {
const isConstructor = node.kind === "constructor";
if (isConstructor) {
path.traverse(verifyConstructorVisitor, {
isDerived: classState.isDerived,
file: classState.file
});
}
const replaceSupers = new (_helperReplaceSupers().default)({
methodPath: path,
objectRef: classState.classRef,
superRef: classState.superName,
isLoose: classState.isLoose,
file: classState.file
});
replaceSupers.replace();
const state = {
returns: [],
bareSupers: new Set()
};
path.traverse(_core().traverse.visitors.merge([_helperReplaceSupers().environmentVisitor, {
ReturnStatement(path, state) {
if (!path.getFunctionParent().isArrowFunctionExpression()) {
state.returns.push(path);
}
},
Super(path, state) {
const {
node,
parentPath
} = path;
if (parentPath.isCallExpression({
callee: node
})) {
state.bareSupers.add(parentPath);
}
}
}]), state);
if (isConstructor) {
pushConstructor(state, node, path);
} else {
pushMethod(node, path);
}
}
}
}
function clearDescriptors() {
setState({
hasInstanceDescriptors: false,
hasStaticDescriptors: false,
instanceMutatorMap: {},
staticMutatorMap: {}
});
}
function pushDescriptors() {
pushInheritsToBody();
const {
body
} = classState;
let instanceProps;
let staticProps;
if (classState.hasInstanceDescriptors) {
instanceProps = defineMap().toClassObject(classState.instanceMutatorMap);
}
if (classState.hasStaticDescriptors) {
staticProps = defineMap().toClassObject(classState.staticMutatorMap);
}
if (instanceProps || staticProps) {
if (instanceProps) {
instanceProps = defineMap().toComputedObjectFromClass(instanceProps);
}
if (staticProps) {
staticProps = defineMap().toComputedObjectFromClass(staticProps);
}
let args = [_core().types.cloneNode(classState.classRef), _core().types.nullLiteral(), _core().types.nullLiteral()];
if (instanceProps) args[1] = instanceProps;
if (staticProps) args[2] = staticProps;
let lastNonNullIndex = 0;
for (let i = 0; i < args.length; i++) {
if (!_core().types.isNullLiteral(args[i])) lastNonNullIndex = i;
}
args = args.slice(0, lastNonNullIndex + 1);
body.push(_core().types.expressionStatement(_core().types.callExpression(classState.file.addHelper("createClass"), args)));
}
clearDescriptors();
}
function wrapSuperCall(bareSuper, superRef, thisRef, body) {
let bareSuperNode = bareSuper.node;
let call;
if (classState.isLoose) {
bareSuperNode.arguments.unshift(_core().types.thisExpression());
if (bareSuperNode.arguments.length === 2 && _core().types.isSpreadElement(bareSuperNode.arguments[1]) && _core().types.isIdentifier(bareSuperNode.arguments[1].argument, {
name: "arguments"
})) {
bareSuperNode.arguments[1] = bareSuperNode.arguments[1].argument;
bareSuperNode.callee = _core().types.memberExpression(_core().types.cloneNode(superRef), _core().types.identifier("apply"));
} else {
bareSuperNode.callee = _core().types.memberExpression(_core().types.cloneNode(superRef), _core().types.identifier("call"));
}
call = _core().types.logicalExpression("||", bareSuperNode, _core().types.thisExpression());
} else {
bareSuperNode = (0, _helperOptimiseCallExpression().default)(_core().types.callExpression(classState.file.addHelper("getPrototypeOf"), [_core().types.cloneNode(classState.classRef)]), _core().types.thisExpression(), bareSuperNode.arguments);
call = _core().types.callExpression(classState.file.addHelper("possibleConstructorReturn"), [_core().types.thisExpression(), bareSuperNode]);
}
if (bareSuper.parentPath.isExpressionStatement() && bareSuper.parentPath.container === body.node.body && body.node.body.length - 1 === bareSuper.parentPath.key) {
if (classState.superThises.length) {
call = _core().types.assignmentExpression("=", thisRef(), call);
}
bareSuper.parentPath.replaceWith(_core().types.returnStatement(call));
} else {
bareSuper.replaceWith(_core().types.assignmentExpression("=", thisRef(), call));
}
}
function verifyConstructor() {
if (!classState.isDerived) return;
const path = classState.userConstructorPath;
const body = path.get("body");
path.traverse(findThisesVisitor);
let guaranteedSuperBeforeFinish = !!classState.bareSupers.size;
let thisRef = function () {
const ref = path.scope.generateDeclaredUidIdentifier("this");
thisRef = () => _core().types.cloneNode(ref);
return ref;
};
for (const bareSuper of classState.bareSupers) {
wrapSuperCall(bareSuper, classState.superName, thisRef, body);
if (guaranteedSuperBeforeFinish) {
bareSuper.find(function (parentPath) {
if (parentPath === path) {
return true;
}
if (parentPath.isLoop() || parentPath.isConditional() || parentPath.isArrowFunctionExpression()) {
guaranteedSuperBeforeFinish = false;
return true;
}
});
}
}
for (const thisPath of classState.superThises) {
const {
node,
parentPath
} = thisPath;
if (parentPath.isMemberExpression({
object: node
})) {
thisPath.replaceWith(thisRef());
continue;
}
thisPath.replaceWith(_core().types.callExpression(classState.file.addHelper("assertThisInitialized"), [thisRef()]));
}
let wrapReturn;
if (classState.isLoose) {
wrapReturn = returnArg => {
const thisExpr = _core().types.callExpression(classState.file.addHelper("assertThisInitialized"), [thisRef()]);
return returnArg ? _core().types.logicalExpression("||", returnArg, thisExpr) : thisExpr;
};
} else {
wrapReturn = returnArg => _core().types.callExpression(classState.file.addHelper("possibleConstructorReturn"), [thisRef()].concat(returnArg || []));
}
const bodyPaths = body.get("body");
if (!bodyPaths.length || !bodyPaths.pop().isReturnStatement()) {
body.pushContainer("body", _core().types.returnStatement(guaranteedSuperBeforeFinish ? thisRef() : wrapReturn()));
}
for (const returnPath of classState.superReturns) {
returnPath.get("argument").replaceWith(wrapReturn(returnPath.node.argument));
}
}
function pushMethod(node, path) {
const scope = path ? path.scope : classState.scope;
if (node.kind === "method") {
if (processMethod(node, scope)) return;
}
pushToMap(node, false, null, scope);
}
function processMethod(node, scope) {
if (classState.isLoose && !node.decorators) {
let {
classRef
} = classState;
if (!node.static) {
insertProtoAliasOnce();
classRef = classState.protoAlias;
}
const methodName = _core().types.memberExpression(_core().types.cloneNode(classRef), node.key, node.computed || _core().types.isLiteral(node.key));
let func = _core().types.functionExpression(null, node.params, node.body, node.generator, node.async);
_core().types.inherits(func, node);
const key = _core().types.toComputedKey(node, node.key);
if (_core().types.isStringLiteral(key)) {
func = (0, _helperFunctionName().default)({
node: func,
id: key,
scope
});
}
const expr = _core().types.expressionStatement(_core().types.assignmentExpression("=", methodName, func));
_core().types.inheritsComments(expr, node);
classState.body.push(expr);
return true;
}
return false;
}
function insertProtoAliasOnce() {
if (classState.protoAlias === null) {
setState({
protoAlias: classState.scope.generateUidIdentifier("proto")
});
const classProto = _core().types.memberExpression(classState.classRef, _core().types.identifier("prototype"));
const protoDeclaration = _core().types.variableDeclaration("var", [_core().types.variableDeclarator(classState.protoAlias, classProto)]);
classState.body.push(protoDeclaration);
}
}
function pushConstructor(replaceSupers, method, path) {
if (path.scope.hasOwnBinding(classState.classRef.name)) {
path.scope.rename(classState.classRef.name);
}
setState({
userConstructorPath: path,
userConstructor: method,
hasConstructor: true,
bareSupers: replaceSupers.bareSupers,
superReturns: replaceSupers.returns
});
const {
construct
} = classState;
_core().types.inheritsComments(construct, method);
construct.params = method.params;
_core().types.inherits(construct.body, method.body);
construct.body.directives = method.body.directives;
pushConstructorToBody();
}
function pushConstructorToBody() {
if (classState.pushedConstructor) return;
classState.pushedConstructor = true;
if (classState.hasInstanceDescriptors || classState.hasStaticDescriptors) {
pushDescriptors();
}
classState.body.push(classState.construct);
pushInheritsToBody();
}
function pushInheritsToBody() {
if (!classState.isDerived || classState.pushedInherits) return;
setState({
pushedInherits: true
});
classState.body.unshift(_core().types.expressionStatement(_core().types.callExpression(classState.file.addHelper(classState.isLoose ? "inheritsLoose" : "inherits"), [_core().types.cloneNode(classState.classRef), _core().types.cloneNode(classState.superName)])));
}
function setupClosureParamsArgs() {
const {
superName
} = classState;
const closureParams = [];
const closureArgs = [];
if (classState.isDerived) {
const arg = classState.extendsNative ? _core().types.callExpression(classState.file.addHelper("wrapNativeSuper"), [_core().types.cloneNode(superName)]) : _core().types.cloneNode(superName);
const param = classState.scope.generateUidIdentifierBasedOnNode(superName);
closureParams.push(param);
closureArgs.push(arg);
setState({
superName: _core().types.cloneNode(param)
});
}
return {
closureParams,
closureArgs
};
}
function classTransformer(path, file, builtinClasses, isLoose) {
setState({
parent: path.parent,
scope: path.scope,
node: path.node,
path,
file,
isLoose
});
setState({
classId: classState.node.id,
classRef: classState.node.id ? _core().types.identifier(classState.node.id.name) : classState.scope.generateUidIdentifier("class"),
superName: classState.node.superClass,
isDerived: !!classState.node.superClass,
constructorBody: _core().types.blockStatement([])
});
setState({
extendsNative: classState.isDerived && builtinClasses.has(classState.superName.name) && !classState.scope.hasBinding(classState.superName.name, true)
});
const {
classRef,
node,
constructorBody
} = classState;
setState({
construct: buildConstructor(classRef, constructorBody, node)
});
let {
body
} = classState;
const {
closureParams,
closureArgs
} = setupClosureParamsArgs();
buildBody();
if (!classState.isLoose) {
constructorBody.body.unshift(_core().types.expressionStatement(_core().types.callExpression(classState.file.addHelper("classCallCheck"), [_core().types.thisExpression(), _core().types.cloneNode(classState.classRef)])));
}
body = body.concat(classState.staticPropBody.map(fn => fn(_core().types.cloneNode(classState.classRef))));
const isStrict = path.isInStrictMode();
let constructorOnly = classState.classId && body.length === 1;
if (constructorOnly && !isStrict) {
for (const param of classState.construct.params) {
if (!_core().types.isIdentifier(param)) {
constructorOnly = false;
break;
}
}
}
const directives = constructorOnly ? body[0].body.directives : [];
if (!isStrict) {
directives.push(_core().types.directive(_core().types.directiveLiteral("use strict")));
}
if (constructorOnly) {
return _core().types.toExpression(body[0]);
}
body.push(_core().types.returnStatement(_core().types.cloneNode(classState.classRef)));
const container = _core().types.arrowFunctionExpression(closureParams, _core().types.blockStatement(body, directives));
return _core().types.callExpression(container, closureArgs);
}
return classTransformer(path, file, builtinClasses, isLoose);
} |
#!/usr/bin/env node
var fs = require('fs');
var TypeResolver = require('../lib/typeresolver');
var generated = TypeResolver.printReadme();
var readmeFilename = __dirname+'/../README.md';
var readme = fs.readFileSync(readmeFilename, {encoding:'utf8'});
var marker_top = '<!--- BEGIN GENERATED GAMES -->';
var marker_bottom = '<!--- END GENERATED GAMES -->';
var start = readme.indexOf(marker_top);
start += marker_top.length;
var end = readme.indexOf(marker_bottom);
var updated = readme.substr(0,start)+"\n\n"+generated+"\n"+readme.substr(end);
fs.writeFileSync(readmeFilename, updated);
|
{
"translatorID": "a667ae9e-186f-46d2-b824-d70064614668",
"label": "Slate",
"creator": "Sebastian Karcher",
"target": "^https?://(.*)slate\\.com",
"minVersion": "2.1",
"maxVersion": "",
"priority": 100,
"inRepository": true,
"translatorType": 4,
"browserSupport": "gcsibv",
"lastUpdated": "2016-12-27 20:28:06"
}
/*********************** BEGIN FRAMEWORK ***********************/
/**
Copyright (c) 2010-2013, Erik Hetzner
This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Affero General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public
License along with this program. If not, see
<http://www.gnu.org/licenses/>.
*/
/**
* Flatten a nested array; e.g., [[1], [2,3]] -> [1,2,3]
*/
function flatten(a) {
var retval = new Array();
for (var i in a) {
var entry = a[i];
if (entry instanceof Array) {
retval = retval.concat(flatten(entry));
} else {
retval.push(entry);
}
}
return retval;
}
var FW = {
_scrapers : new Array()
};
FW._Base = function () {
this.callHook = function (hookName, item, doc, url) {
if (typeof this['hooks'] === 'object') {
var hook = this['hooks'][hookName];
if (typeof hook === 'function') {
hook(item, doc, url);
}
}
};
this.evaluateThing = function(val, doc, url) {
var valtype = typeof val;
if (valtype === 'object') {
if (val instanceof Array) {
/* map over each array val */
/* this.evaluate gets out of scope */
var parentEval = this.evaluateThing;
var retval = val.map ( function(i) { return parentEval (i, doc, url); } );
return flatten(retval);
} else {
return val.evaluate(doc, url);
}
} else if (valtype === 'function') {
return val(doc, url);
} else {
return val;
}
};
/*
* makeItems is the function that does the work of making an item.
* doc: the doc tree for the item
* url: the url for the item
* attachments ...
* eachItem: a function to be called for each item made, with the arguments (doc, url, ...)
* ret: the function to call when you are done, with no args
*/
this.makeItems = function (doc, url, attachments, eachItem, ret) {
ret();
}
};
FW.Scraper = function (init) {
FW._scrapers.push(new FW._Scraper(init));
};
FW._Scraper = function (init) {
for (x in init) {
this[x] = init[x];
}
this._singleFieldNames = [
"abstractNote",
"applicationNumber",
"archive",
"archiveLocation",
"artworkMedium",
"artworkSize",
"assignee",
"audioFileType",
"audioRecordingType",
"billNumber",
"blogTitle",
"bookTitle",
"callNumber",
"caseName",
"code",
"codeNumber",
"codePages",
"codeVolume",
"committee",
"company",
"conferenceName",
"country",
"court",
"date",
"dateDecided",
"dateEnacted",
"dictionaryTitle",
"distributor",
"docketNumber",
"documentNumber",
"DOI",
"edition",
"encyclopediaTitle",
"episodeNumber",
"extra",
"filingDate",
"firstPage",
"forumTitle",
"genre",
"history",
"institution",
"interviewMedium",
"ISBN",
"ISSN",
"issue",
"issueDate",
"issuingAuthority",
"journalAbbreviation",
"label",
"language",
"legalStatus",
"legislativeBody",
"letterType",
"libraryCatalog",
"manuscriptType",
"mapType",
"medium",
"meetingName",
"nameOfAct",
"network",
"number",
"numberOfVolumes",
"numPages",
"pages",
"patentNumber",
"place",
"postType",
"presentationType",
"priorityNumbers",
"proceedingsTitle",
"programTitle",
"programmingLanguage",
"publicLawNumber",
"publicationTitle",
"publisher",
"references",
"reportNumber",
"reportType",
"reporter",
"reporterVolume",
"rights",
"runningTime",
"scale",
"section",
"series",
"seriesNumber",
"seriesText",
"seriesTitle",
"session",
"shortTitle",
"studio",
"subject",
"system",
"thesisType",
"title",
"type",
"university",
"url",
"versionNumber",
"videoRecordingType",
"volume",
"websiteTitle",
"websiteType" ];
this._makeAttachments = function(doc, url, config, item) {
if (config instanceof Array) {
config.forEach(function (child) { this._makeAttachments(doc, url, child, item); }, this);
} else if (typeof config === 'object') {
/* plural or singual */
var urlsFilter = config["urls"] || config["url"];
var typesFilter = config["types"] || config["type"];
var titlesFilter = config["titles"] || config["title"];
var snapshotsFilter = config["snapshots"] || config["snapshot"];
var attachUrls = this.evaluateThing(urlsFilter, doc, url);
var attachTitles = this.evaluateThing(titlesFilter, doc, url);
var attachTypes = this.evaluateThing(typesFilter, doc, url);
var attachSnapshots = this.evaluateThing(snapshotsFilter, doc, url);
if (!(attachUrls instanceof Array)) {
attachUrls = [attachUrls];
}
for (var k in attachUrls) {
var attachUrl = attachUrls[k];
var attachType;
var attachTitle;
var attachSnapshot;
if (attachTypes instanceof Array) { attachType = attachTypes[k]; }
else { attachType = attachTypes; }
if (attachTitles instanceof Array) { attachTitle = attachTitles[k]; }
else { attachTitle = attachTitles; }
if (attachSnapshots instanceof Array) { attachSnapshot = attachSnapshots[k]; }
else { attachSnapshot = attachSnapshots; }
item["attachments"].push({ url : attachUrl,
title : attachTitle,
mimeType : attachType,
snapshot : attachSnapshot });
}
}
};
this.makeItems = function (doc, url, ignore, eachItem, ret) {
var item = new Zotero.Item(this.itemType);
item.url = url;
for (var i in this._singleFieldNames) {
var field = this._singleFieldNames[i];
if (this[field]) {
var fieldVal = this.evaluateThing(this[field], doc, url);
if (fieldVal instanceof Array) {
item[field] = fieldVal[0];
} else {
item[field] = fieldVal;
}
}
}
var multiFields = ["creators", "tags"];
for (var j in multiFields) {
var key = multiFields[j];
var val = this.evaluateThing(this[key], doc, url);
if (val) {
for (var k in val) {
item[key].push(val[k]);
}
}
}
this._makeAttachments(doc, url, this["attachments"], item);
eachItem(item, this, doc, url);
ret();
};
};
FW._Scraper.prototype = new FW._Base;
FW.MultiScraper = function (init) {
FW._scrapers.push(new FW._MultiScraper(init));
};
FW._MultiScraper = function (init) {
for (x in init) {
this[x] = init[x];
}
this._mkSelectItems = function(titles, urls) {
var items = new Object;
for (var i in titles) {
items[urls[i]] = titles[i];
}
return items;
};
this._selectItems = function(titles, urls, callback) {
var items = new Array();
Zotero.selectItems(this._mkSelectItems(titles, urls), function (chosen) {
for (var j in chosen) {
items.push(j);
}
callback(items);
});
};
this._mkAttachments = function(doc, url, urls) {
var attachmentsArray = this.evaluateThing(this['attachments'], doc, url);
var attachmentsDict = new Object();
if (attachmentsArray) {
for (var i in urls) {
attachmentsDict[urls[i]] = attachmentsArray[i];
}
}
return attachmentsDict;
};
/* This logic is very similar to that used by _makeAttachments in
* a normal scraper, but abstracting it out would not achieve much
* and would complicate it. */
this._makeChoices = function(config, doc, url, choiceTitles, choiceUrls) {
if (config instanceof Array) {
config.forEach(function (child) { this._makeTitlesUrls(child, doc, url, choiceTitles, choiceUrls); }, this);
} else if (typeof config === 'object') {
/* plural or singual */
var urlsFilter = config["urls"] || config["url"];
var titlesFilter = config["titles"] || config["title"];
var urls = this.evaluateThing(urlsFilter, doc, url);
var titles = this.evaluateThing(titlesFilter, doc, url);
var titlesIsArray = (titles instanceof Array);
if (!(urls instanceof Array)) {
urls = [urls];
}
for (var k in urls) {
var myUrl = urls[k];
var myTitle;
if (titlesIsArray) { myTitle = titles[k]; }
else { myTitle = titles; }
choiceUrls.push(myUrl);
choiceTitles.push(myTitle);
}
}
};
this.makeItems = function(doc, url, ignore, eachItem, ret) {
if (this.beforeFilter) {
var newurl = this.beforeFilter(doc, url);
if (newurl != url) {
this.makeItems(doc, newurl, ignore, eachItem, ret);
return;
}
}
var titles = [];
var urls = [];
this._makeChoices(this["choices"], doc, url, titles, urls);
var attachments = this._mkAttachments(doc, url, urls);
var parentItemTrans = this.itemTrans;
this._selectItems(titles, urls, function (itemsToUse) {
if(!itemsToUse) {
ret();
} else {
var cb = function (doc1) {
var url1 = doc1.documentURI;
var itemTrans = parentItemTrans;
if (itemTrans === undefined) {
itemTrans = FW.getScraper(doc1, url1);
}
if (itemTrans === undefined) {
/* nothing to do */
} else {
itemTrans.makeItems(doc1, url1, attachments[url1],
eachItem, function() {});
}
};
Zotero.Utilities.processDocuments(itemsToUse, cb, ret);
}
});
};
};
FW._MultiScraper.prototype = new FW._Base;
FW.WebDelegateTranslator = function (init) {
return new FW._WebDelegateTranslator(init);
};
FW._WebDelegateTranslator = function (init) {
for (x in init) {
this[x] = init[x];
}
this.makeItems = function(doc, url, attachments, eachItem, ret) {
// need for scoping
var parentThis = this;
var translator = Zotero.loadTranslator("web");
translator.setHandler("itemDone", function(obj, item) {
eachItem(item, parentThis, doc, url);
});
translator.setDocument(doc);
if (this.translatorId) {
translator.setTranslator(this.translatorId);
translator.translate();
} else {
translator.setHandler("translators", function(obj, translators) {
if (translators.length) {
translator.setTranslator(translators[0]);
translator.translate();
}
});
translator.getTranslators();
}
ret();
};
};
FW._WebDelegateTranslator.prototype = new FW._Base;
FW._StringMagic = function () {
this._filters = new Array();
this.addFilter = function(filter) {
this._filters.push(filter);
return this;
};
this.split = function(re) {
return this.addFilter(function(s) {
return s.split(re).filter(function(e) { return (e != ""); });
});
};
this.replace = function(s1, s2, flags) {
return this.addFilter(function(s) {
if (s.match(s1)) {
return s.replace(s1, s2, flags);
} else {
return s;
}
});
};
this.prepend = function(prefix) {
return this.replace(/^/, prefix);
};
this.append = function(postfix) {
return this.replace(/$/, postfix);
};
this.remove = function(toStrip, flags) {
return this.replace(toStrip, '', flags);
};
this.trim = function() {
return this.addFilter(function(s) { return Zotero.Utilities.trim(s); });
};
this.trimInternal = function() {
return this.addFilter(function(s) { return Zotero.Utilities.trimInternal(s); });
};
this.match = function(re, group) {
if (!group) group = 0;
return this.addFilter(function(s) {
var m = s.match(re);
if (m === undefined || m === null) { return undefined; }
else { return m[group]; }
});
};
this.cleanAuthor = function(type, useComma) {
return this.addFilter(function(s) { return Zotero.Utilities.cleanAuthor(s, type, useComma); });
};
this.key = function(field) {
return this.addFilter(function(n) { return n[field]; });
};
this.capitalizeTitle = function() {
return this.addFilter(function(s) { return Zotero.Utilities.capitalizeTitle(s); });
};
this.unescapeHTML = function() {
return this.addFilter(function(s) { return Zotero.Utilities.unescapeHTML(s); });
};
this.unescape = function() {
return this.addFilter(function(s) { return unescape(s); });
};
this._applyFilters = function(a, doc1) {
for (i in this._filters) {
a = flatten(a);
/* remove undefined or null array entries */
a = a.filter(function(x) { return ((x !== undefined) && (x !== null)); });
for (var j = 0 ; j < a.length ; j++) {
try {
if ((a[j] === undefined) || (a[j] === null)) { continue; }
else { a[j] = this._filters[i](a[j], doc1); }
} catch (x) {
a[j] = undefined;
Zotero.debug("Caught exception " + x + "on filter: " + this._filters[i]);
}
}
/* remove undefined or null array entries */
/* need this twice because they could have become undefined or null along the way */
a = a.filter(function(x) { return ((x !== undefined) && (x !== null)); });
}
return flatten(a);
};
};
FW.PageText = function () {
return new FW._PageText();
};
FW._PageText = function() {
this._filters = new Array();
this.evaluate = function (doc) {
var a = [doc.documentElement.innerHTML];
a = this._applyFilters(a, doc);
if (a.length == 0) { return false; }
else { return a; }
};
};
FW._PageText.prototype = new FW._StringMagic();
FW.Url = function () { return new FW._Url(); };
FW._Url = function () {
this._filters = new Array();
this.evaluate = function (doc, url) {
var a = [url];
a = this._applyFilters(a, doc);
if (a.length == 0) { return false; }
else { return a; }
};
};
FW._Url.prototype = new FW._StringMagic();
FW.Xpath = function (xpathExpr) { return new FW._Xpath(xpathExpr); };
FW._Xpath = function (_xpath) {
this._xpath = _xpath;
this._filters = new Array();
this.text = function() {
var filter = function(n) {
if (typeof n === 'object' && n.textContent) { return n.textContent; }
else { return n; }
};
this.addFilter(filter);
return this;
};
this.sub = function(xpath) {
var filter = function(n, doc) {
var result = doc.evaluate(xpath, n, null, XPathResult.ANY_TYPE, null);
if (result) {
return result.iterateNext();
} else {
return undefined;
}
};
this.addFilter(filter);
return this;
};
this.evaluate = function (doc) {
var res = doc.evaluate(this._xpath, doc, null, XPathResult.ANY_TYPE, null);
var resultType = res.resultType;
var a = new Array();
if (resultType == XPathResult.STRING_TYPE) {
a.push(res.stringValue);
} else if (resultType == XPathResult.BOOLEAN_TYPE) {
a.push(res.booleanValue);
} else if (resultType == XPathResult.NUMBER_TYPE) {
a.push(res.numberValue);
} else if (resultType == XPathResult.ORDERED_NODE_ITERATOR_TYPE ||
resultType == XPathResult.UNORDERED_NODE_ITERATOR_TYPE) {
var x;
while ((x = res.iterateNext())) { a.push(x); }
}
a = this._applyFilters(a, doc);
if (a.length == 0) { return false; }
else { return a; }
};
};
FW._Xpath.prototype = new FW._StringMagic();
FW.detectWeb = function (doc, url) {
for (var i in FW._scrapers) {
var scraper = FW._scrapers[i];
var itemType = scraper.evaluateThing(scraper['itemType'], doc, url);
var v = scraper.evaluateThing(scraper['detect'], doc, url);
if (v.length > 0 && v[0]) {
return itemType;
}
}
return undefined;
};
FW.getScraper = function (doc, url) {
var itemType = FW.detectWeb(doc, url);
return FW._scrapers.filter(function(s) {
return (s.evaluateThing(s['itemType'], doc, url) == itemType)
&& (s.evaluateThing(s['detect'], doc, url));
})[0];
};
FW.doWeb = function (doc, url) {
var scraper = FW.getScraper(doc, url);
scraper.makeItems(doc, url, [],
function(item, scraper, doc, url) {
scraper.callHook('scraperDone', item, doc, url);
if (!item['title']) {
item['title'] = "";
}
item.complete();
},
function() {
Zotero.done();
});
Zotero.wait();
};
/*********************** END FRAMEWORK ***********************/
/*
Springer Open Translator
Copyright (C) 2011 Sebastian Karcher
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
function detectWeb(doc, url) { return FW.detectWeb(doc, url); }
function doWeb(doc, url) { return FW.doWeb(doc, url); }
/** Articles */
FW.Scraper({
itemType : 'magazineArticle',
detect : FW.Xpath('//article/header/h1[@class="hed"]'),
title : FW.Xpath('//article//h1[@class="hed"]').text().trim(),
attachments : [{ url: FW.Url().remove(/\?(.*)/).replace(/(\.[1-99])?(\.single)?\.html/, ".single.html" ),
title: "Slate Snapshot",
type: "text/html" }],
creators : FW.Xpath('//div[@class="byline"]/a').text().remove(/By/).split(/\ and\ /).cleanAuthor("author"),
date : FW.Xpath('//div[@class="pub-date"]').text().remove(/\n/g).remove(/\d{1,2}:\d{2}.+/).trim(),
abstractNote : FW.Xpath('//h2[@class="dek"]').text().trim(),
language : "en-US",
ISSN : "1091-2339",
publicationTitle : "Slate"
});
/**Multiple */
FW.MultiScraper({
itemType : 'multiple',
detect : FW.Xpath('//body[contains(@class, "landing")]//article//h1[@class="hed"]'),
choices : {
titles : FW.Xpath('//article//a[@class="primary"]/following-sibling::div/span[@class="hed"]').text().trim(),
urls : FW.Xpath('//article//a[@class="primary"]').key("href")
}
});
/** BEGIN TEST CASES **/
var testCases = [
{
"type": "web",
"url": "http://www.slate.com/articles/news_and_politics/history_lesson/2011/10/new_deal_accomplishments_do_conservatives_who_attack_the_new_dea.html",
"items": [
{
"itemType": "magazineArticle",
"title": "What the New Deal Accomplished",
"creators": [
{
"firstName": "Michael",
"lastName": "Hiltzik",
"creatorType": "author"
}
],
"date": "Oct. 13 2011",
"ISSN": "1091-2339",
"abstractNote": "651,000 miles of highway. 8,000 parks. The Triborough Bridge. Do conservatives who attack the New Deal actually know what America gained from it?",
"language": "en-US",
"libraryCatalog": "Slate",
"publicationTitle": "Slate",
"url": "http://www.slate.com/articles/news_and_politics/history_lesson/2011/10/new_deal_accomplishments_do_conservatives_who_attack_the_new_dea.html",
"attachments": [
{
"title": "Slate Snapshot",
"mimeType": "text/html"
}
],
"tags": [],
"notes": [],
"seeAlso": []
}
]
},
{
"type": "web",
"url": "http://www.slate.com/articles/life/dear_prudence.html",
"items": "multiple"
}
]
/** END TEST CASES **/ |
(function() {
// Get some required handles
var video = document.getElementById('v');
var recStatus = document.getElementById('recStatus');
var startRecBtn = document.getElementById('startRecBtn');
var stopRecBtn = document.getElementById('stopRecBtn');
// Define a new speech recognition instance
var rec = null;
try {
rec = new webkitSpeechRecognition();
}
catch(e) {
document.querySelector('.msg').setAttribute('data-state', 'show');
startRecBtn.setAttribute('disabled', 'true');
stopRecBtn.setAttribute('disabled', 'true');
}
if (rec) {
rec.continuous = true;
rec.interimResults = false;
rec.lang = 'en';
// Define a threshold above which we are confident(!) that the recognition results are worth looking at
var confidenceThreshold = 0.5;
// Simple function that checks existence of s in str
var userSaid = function(str, s) {
return str.indexOf(s) > -1;
}
// Highlights the relevant command that was recognised in the command list for display purposes
var highlightCommand = function(cmd) {
var el = document.getElementById(cmd);
el.setAttribute('data-state', 'highlight');
setTimeout(function() {
el.setAttribute('data-state', '');
}, 3000);
}
// Process the results when they are returned from the recogniser
rec.onresult = function(e) {
// Check each result starting from the last one
for (var i = e.resultIndex; i < e.results.length; ++i) {
// If this is a final result
if (e.results[i].isFinal) {
// If the result is equal to or greater than the required threshold
if (parseFloat(e.results[i][0].confidence) >= parseFloat(confidenceThreshold)) {
var str = e.results[i][0].transcript;
console.log('Recognised: ' + str);
// If the user said 'video' then parse it further
if (userSaid(str, 'video')) {
// Replay the video
if (userSaid(str, 'replay')) {
video.currentTime = 0;
video.play();
highlightCommand('vidReplay');
}
// Play the video
else if (userSaid(str, 'play')) {
video.play();
highlightCommand('vidPlay');
}
// Stop the video
else if (userSaid(str, 'stop')) {
video.pause();
highlightCommand('vidStop');
}
// If the user said 'volume' then parse it even further
else if (userSaid(str, 'volume')) {
// Check the current volume setting of the video
var vol = Math.floor(video.volume * 10) / 10;
// Increase the volume
if (userSaid(str, 'increase')) {
if (vol >= 0.9) video.volume = 1;
else video.volume += 0.1;
highlightCommand('vidVolInc');
}
// Decrease the volume
else if (userSaid(str, 'decrease')) {
if (vol <= 0.1) video.volume = 0;
else video.volume -= 0.1;
highlightCommand('vidVolDec');
}
// Turn the volume off (mute)
else if (userSaid(str, 'of')) {
video.muted = true;
highlightCommand('vidVolOff');
}
// Turn the volume on (unmute)
else if (userSaid(str, 'on')) {
video.muted = false;
highlightCommand('vidVolOn');
}
}
}
}
}
}
};
// Start speech recognition
var startRec = function() {
rec.start();
recStatus.innerHTML = 'recognising';
}
// Stop speech recognition
var stopRec = function() {
rec.stop();
recStatus.innerHTML = 'not recognising';
}
// Setup listeners for the start and stop recognition buttons
startRecBtn.addEventListener('click', startRec, false);
stopRecBtn.addEventListener('click', stopRec, false);
}
})(); |
/**
The built-in "book" generator for Extrovert.js.
@module book.js
@license Copyright (c) 2015 | James M. Devlin
*/
define(['require', '../core', '../utilities/log', 'extrovert/providers/three/provider-three'], function( require, extro, log, provider ) {
'use strict';
var _opts = null;
var _eng = null;
var _side = null;
var _noun = null;
function mapTextures( cubeGeo, width, height ) {
for (var i = 0; i < cubeGeo.faces.length ; i++) {
var fvu = cubeGeo.faceVertexUvs[0][i];
if( Math.abs( cubeGeo.faces[ i ].normal.z ) > 0.9) {
for( var fv = 0; fv < 3; fv++ ) {
if( Math.abs( fvu[fv].y ) < 0.01 ) {
fvu[ fv ].y = 1 - ( width / height );
}
}
}
}
cubeGeo.uvsNeedUpdate = true;
}
var BookGenerator = function( ) {
var extrovert = require('../core');
var utils = require('../utilities/utils');
return {
options: {
name: 'book',
material: { color: 0xFFFFFF, friction: 0.2, restitution: 1.0 },
block: { depth: 'height' },
clickForce: 5000,
dims: [512, 814, 2], // Std paperback = 4.25 x 6.75 = 512x814
pagify: true,
title: null,
cover: null,
doubleSided: true,
camera: {
position: [0,0,400]
}
},
init: function( genOpts, eng ) {
_opts = genOpts;
_eng = eng;
extrovert.createPlacementPlane( [0,0,200] );
_side = provider.createMaterial( { color: genOpts.pageColor || genOpts.material.color, friction: genOpts.material.friction, restitution: genOpts.material.restitution });
},
generate: function( noun, elems ) {
extrovert.LOGGING && log.msg('book.generate( %o, %o )', noun, elems);
_noun = noun;
if( noun.cover ) {
var coverMat = provider.createMaterial({ tex: provider.loadTexture( noun.cover ), friction: 0.2, resitution: 1.0 });
var coverMesh = extrovert.createObject({ type: 'box', pos: [0,0,0], dims: _opts.dims, mat: coverMat, mass: 1000 });
}
function _createMat( t ) { return provider.createMaterial({ tex: t, friction: 0.2, restitution: 1.0 }); }
function _isEven( val, index ) { return (index % 2) === 0; }
function _isOdd( val, index ) { return !_isEven(val, index); }
for( var i = 0; i < elems.length; i++ ) {
var obj = (noun.adapt && noun.adapt( elems[ i ] )) || elems[ i ];
var rast = null;
if( noun.rasterizer ) {
rast = ( typeof noun.rasterizer === 'string' ) ?
_eng.rasterizers[ noun.rasterizer ] : noun.rasterizer;
} else {
rast = _eng.rasterizers.paint_plain_text_stream;
}
if( _opts.pagify ) {
var done = false,
info = { },
rastOpts = {
width: _opts.texWidth || 512, // Default to power-of-2 textures
height: _opts.texHeight || 1024,
bkColor: _opts.pageColor || (_opts.material && _opts.material.color) || 0xFFFFFF,
textColor: _opts.textColor || 0x232323
},
textures = rast.paint(obj, rastOpts, info );
var mats = textures.map( _createMat );
var front = mats.filter( _isEven );
var back = mats.filter( _isOdd );
for( var tt = 0; tt < front.length; tt++ ) {
var tilePos = [0, 0, -(tt * _opts.dims[2]) - _opts.dims[2] ];
var matArray = [ _side, _side, _side, _side, front[ tt ], tt < back.length ? back[ tt ] : _side ];
var meshMat = provider.createCubeMaterial( matArray );
var mesh = extrovert.createObject({ type: 'box', pos: tilePos, dims: _opts.dims, mat: meshMat, mass: 1000 });
mapTextures( mesh.geometry, rastOpts.width, rastOpts.height );
extrovert.LOGGING && log.msg('Generating page %o at position %f, %f, %f', mesh, tilePos[0], tilePos[1], tilePos[2]);
}
}
}
}
};
};
return BookGenerator;
});
|
/** @license MIT License (c) copyright B Cavalier & J Hann */
/**
* unfold
* @author: brian@hovercraftstudios.com
*/
(function(define) {
define(function(require) {
/**
* @deprecated Use when.unfold
*/
return require('./when').unfold;
});
})(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); } );
|
'use strict'
var wrap = require('../../shimmer').wrapMethod
module.exports = initialize
function initialize(agent, dns) {
var methods = [
'lookup',
'resolve',
'resolve4',
'resolve6',
'resolveCname',
'resolveMx',
'resolveNaptr',
'resolveNs',
'resolveTxt',
'resolveSrv',
'reverse',
]
wrap(dns, 'dns', methods, wrapDns)
function wrapDns(fn, method) {
return agent.tracer.wrapFunctionLast('dns.' + method, null, fn)
}
}
|
#!/usr/bin/env node
var http = require('http');
var fs = require('fs');
var outFile = require('path').resolve(__dirname, '../lib/simple-html-tokenizer/html5-named-char-refs.js');
console.log('downloading html5 entities.json');
http.get("http://www.w3.org/TR/html5/entities.json", function(res) {
console.log(res.statusCode);
res.setEncoding('utf8');
var body = '';
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function() {
var data = JSON.parse(body);
console.log(outFile);
fs.writeFileSync(outFile, buildEntitiesModule(data));
});
});
// lifted from jshint
var UNSAFE = /[\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/;
function codepointLiteral(codepoint) {
var n = codepoint.toString(16);
if (n.length < 4) {
n = new Array(4 - n.length + 1).join('0') + n;
}
return '\\u' + n;
}
function codepointsLiteral(codepoints) {
return '"' + codepoints.map(codepointLiteral).join('') + '"';
}
function buildEntitiesModule(data) {
var dest = 'export default {\n';
var seen = Object.create(null);
var entities = Object.keys(data);
var len = entities.length;
var entity, name, characters, literal;
for (var i = 0; i < len; i++) {
entity = entities[i];
if (entity[entity.length-1] === ';') {
name = entity.slice(1,-1);
} else {
name = entity.slice(1);
}
if (seen[name]) {
continue;
}
seen[name] = true;
if (i > 0) {
dest += ',';
}
characters = data[entity].characters;
if (UNSAFE.test(characters)) {
literal = codepointsLiteral(data[entity].codepoints);
} else {
literal = JSON.stringify(characters);
}
dest += name + ':' + literal;
}
dest += '\n};\n';
return dest;
}
|
var gulp = require('gulp'),
plumber = require('gulp-plumber'),
rename = require('gulp-rename');
var autoprefixer = require('gulp-autoprefixer');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin'),
cache = require('gulp-cache');
var minifycss = require('gulp-minify-css');
var less = require('gulp-less');
var browserSync = require('browser-sync');
//BrowserSync Reload function (redundant?)
gulp.task('browser-sync', gulp.series(function() {
browserSync({
server: {
baseDir: "./"
}
});
}));
// Pipe all Images
gulp.task('images', gulp.series(function(){
gulp.src('src/images/**/*')
.pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
.pipe(gulp.dest('dist/images/'));
}));
// Pipe all CSS
gulp.task('styles', gulp.series(function() {
gulp.src(['src/styles/**/*.less'])
.pipe(plumber({
errorHandler: function (error) {
console.log(error.message);
this.emit('end');
}}))
.pipe(less())
.pipe(autoprefixer('last 2 versions'))
.pipe(gulp.dest('dist/styles/'))
.pipe(rename({suffix: '.min'}))
.pipe(minifycss())
.pipe(gulp.dest('dist/styles/'))
.pipe(browserSync.reload({stream:true}))
}));
// Pipe all JS
gulp.task('scripts', gulp.series(function(){
return gulp.src('src/scripts/**/*.js')
.pipe(plumber({
errorHandler: function (error) {
console.log(error.message);
this.emit('end');
}}))
.pipe(concat('main.js'))
.pipe(gulp.dest('dist/scripts/'))
.pipe(rename({suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest('dist/scripts/'))
.pipe(browserSync.reload({stream:true}))
}));
// Main gulp task - triggers BrowserSync, and watches for changes in Less, JS, and HTML
gulp.task('default', gulp.series('browser-sync', function(){
gulp.watch("src/styles/**/*.less", ['styles']);
gulp.watch("src/scripts/**/*.js", ['scripts']);
gulp.watch('*.html', browserSync.reload); // Had to change this line from something else to make it reload
}));
|
describe('Demonstrating Excellence', function() {
integration(function() {
describe('Demonstrating Excellence\'s ability', function() {
beforeEach(function() {
this.setupTest({
phase: 'conflict',
player1: {
inPlay: ['moto-horde', 'moto-horde', 'moto-horde']
},
player2: {
provinces: ['demonstrating-excellence']
}
});
this.demonstratingExcellence = this.player2.findCardByName('demonstrating-excellence');
this.noMoreActions();
this.initiateConflict({
type: 'military',
attackers: ['moto-horde', 'moto-horde', 'moto-horde'],
defenders: []
});
});
it('should work properly', function() {
this.noMoreActions();
expect(this.player2).toHavePrompt('Triggered Abilities');
expect(this.player2).toBeAbleToSelect('demonstrating-excellence');
let fate = this.player2.fate;
this.demonstratingExcellence = this.player2.clickCard('demonstrating-excellence');
expect(this.player1).toHavePrompt('Break Demonstrating Excellence');
expect(this.player2.fate).toBe(fate + 1);
expect(this.demonstratingExcellence.isBroken).toBe(true);
});
});
});
});
|
var towns = [
"Sofia",
"Washington",
"London",
"Paris"
];
for (var town in towns) {
console.log(towns[town]);
} |
Package.describe({
name: 'rocketchat:slashcommands-join',
version: '0.0.1',
summary: 'Command handler for the /join command',
git: ''
});
Package.onUse(function(api) {
api.versionsFrom('1.0');
api.use([
'coffeescript',
'check',
'rocketchat:lib@0.0.1'
]);
api.addFiles('client.coffee', 'client');
api.addFiles('server.coffee', 'server');
// TAPi18n
api.use('templating', 'client');
var _ = Npm.require('underscore');
var fs = Npm.require('fs');
tapi18nFiles = _.compact(_.map(fs.readdirSync('packages/rocketchat-slashcommands-join/i18n'), function(filename) {
if (fs.statSync('packages/rocketchat-slashcommands-join/i18n/' + filename).size > 16) {
return 'i18n/' + filename;
}
}));
api.use('tap:i18n@1.6.1', ['client', 'server']);
api.imply('tap:i18n');
api.addFiles(tapi18nFiles, ['client', 'server']);
});
Package.onTest(function(api) {
});
|
(function() {
var app = angular.module('app');
app.factory('proxy', ['proxyFactory', function(proxyFactory) {
var proxy = proxyFactory('clientes/api/');
return proxy;
}]);
})();
|
var ReactAsync = require('react-async');
var debug = require('debug')('react-markup');
var util = require('util');
exports = module.exports = function () {
return function (options) {
var context = options.context || {};
var callback = options.callback || function (err) { console.log(err) };
var clientScripts = options.clientScripts || [];
var component = options.component || function () { console.log('no component passed!') };
// application data (this has the same effect as handlebars context, except for react components)
var renderedComponent = component(context);
// render the react markup to a string
ReactAsync.renderComponentToStringWithAsyncState(renderedComponent, function (err, markup, data) {
if (!markup) {
debug(util.inspect(err));
return callback('could not render markup - check server console');
}
// add doctype to markup (not possible in jsx - so it needs to be done dirty)
markup = '<!DOCTYPE html>' + markup;
callback(err, options.staticPage ? markup : ReactAsync.injectIntoMarkup(markup, data, clientScripts))
});
};
};
|
// This file has been autogenerated.
exports.setEnvironment = function() {
process.env['AZURE_BATCH_ACCOUNT'] = 'batchtestnodesdk';
process.env['AZURE_BATCH_ENDPOINT'] = 'https://batchtestnodesdk.japaneast.batch.azure.com';
process.env['AZURE_SUBSCRIPTION_ID'] = '00000000-0000-0000-0000-000000000000';
};
exports.scopes = [[function (nock) {
var result =
nock('http://batchtestnodesdk.japaneast.batch.azure.com:443')
.get('/jobs/HelloWorldJobNodeSDKTest/tasks/HelloWorldNodeSDKTestTask2/files/stdout.txt?api-version=2017-09-01.6.0')
.reply(200, "hello world\r\n", { 'transfer-encoding': 'chunked',
'content-type': 'application/octet-stream',
'last-modified': 'Mon, 02 Oct 2017 21:46:09 GMT',
server: 'Microsoft-HTTPAPI/2.0',
'request-id': '06b94731-8f6a-4c0a-9fdb-ab228ee99d6f',
'strict-transport-security': 'max-age=31536000; includeSubDomains',
'x-content-type-options': 'nosniff',
dataserviceversion: '3.0',
'ocp-creation-time': 'Mon, 02 Oct 2017 21:46:09 GMT',
'ocp-batch-file-isdirectory': 'False',
'ocp-batch-file-url': 'https%3A%2F%2Fbatchtestnodesdk.japaneast.batch.azure.com%2Fjobs%2FHelloWorldJobNodeSDKTest%2Ftasks%2FHelloWorldNodeSDKTestTask2%2Ffiles%2Fstdout.txt',
date: 'Mon, 02 Oct 2017 21:48:09 GMT',
connection: 'close' });
return result; },
function (nock) {
var result =
nock('https://batchtestnodesdk.japaneast.batch.azure.com:443')
.get('/jobs/HelloWorldJobNodeSDKTest/tasks/HelloWorldNodeSDKTestTask2/files/stdout.txt?api-version=2017-09-01.6.0')
.reply(200, "hello world\r\n", { 'transfer-encoding': 'chunked',
'content-type': 'application/octet-stream',
'last-modified': 'Mon, 02 Oct 2017 21:46:09 GMT',
server: 'Microsoft-HTTPAPI/2.0',
'request-id': '06b94731-8f6a-4c0a-9fdb-ab228ee99d6f',
'strict-transport-security': 'max-age=31536000; includeSubDomains',
'x-content-type-options': 'nosniff',
dataserviceversion: '3.0',
'ocp-creation-time': 'Mon, 02 Oct 2017 21:46:09 GMT',
'ocp-batch-file-isdirectory': 'False',
'ocp-batch-file-url': 'https%3A%2F%2Fbatchtestnodesdk.japaneast.batch.azure.com%2Fjobs%2FHelloWorldJobNodeSDKTest%2Ftasks%2FHelloWorldNodeSDKTestTask2%2Ffiles%2Fstdout.txt',
date: 'Mon, 02 Oct 2017 21:48:09 GMT',
connection: 'close' });
return result; }]]; |
/**
DataStream reads scalars, arrays and structs of data from an ArrayBuffer.
It's like a file-like DataView on steroids.
@param {ArrayBuffer} arrayBuffer ArrayBuffer to read from.
@param {?Number} byteOffset Offset from arrayBuffer beginning for the DataStream.
@param {?Boolean} endianness DataStream.BIG_ENDIAN or DataStream.LITTLE_ENDIAN (the default).
*/
DataStream = function(arrayBuffer, byteOffset, endianness) {
this._byteOffset = byteOffset || 0;
if (arrayBuffer instanceof ArrayBuffer) {
this.buffer = arrayBuffer;
} else if (typeof arrayBuffer == "object") {
this.dataView = arrayBuffer;
if (byteOffset) {
this._byteOffset += byteOffset;
}
} else {
this.buffer = new ArrayBuffer(arrayBuffer || 1);
}
this.position = 0;
this.endianness = endianness == null ? DataStream.LITTLE_ENDIAN : endianness;
};
DataStream.prototype = {};
/* Fix for Opera 12 not defining BYTES_PER_ELEMENT in typed array prototypes. */
if (Uint8Array.prototype.BYTES_PER_ELEMENT === undefined) {
Uint8Array.prototype.BYTES_PER_ELEMENT = Uint8Array.BYTES_PER_ELEMENT;
Int8Array.prototype.BYTES_PER_ELEMENT = Int8Array.BYTES_PER_ELEMENT;
Uint8ClampedArray.prototype.BYTES_PER_ELEMENT = Uint8ClampedArray.BYTES_PER_ELEMENT;
Uint16Array.prototype.BYTES_PER_ELEMENT = Uint16Array.BYTES_PER_ELEMENT;
Int16Array.prototype.BYTES_PER_ELEMENT = Int16Array.BYTES_PER_ELEMENT;
Uint32Array.prototype.BYTES_PER_ELEMENT = Uint32Array.BYTES_PER_ELEMENT;
Int32Array.prototype.BYTES_PER_ELEMENT = Int32Array.BYTES_PER_ELEMENT;
Float64Array.prototype.BYTES_PER_ELEMENT = Float64Array.BYTES_PER_ELEMENT;
}
/**
Saves the DataStream contents to the given filename.
Uses Chrome's anchor download property to initiate download.
@param {string} filename Filename to save as.
@return {null}
*/
DataStream.prototype.save = function(filename) {
var blob = new Blob(this.buffer);
var URL = (window.webkitURL || window.URL);
if (URL && URL.createObjectURL) {
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.setAttribute('href', url);
a.setAttribute('download', filename);
a.click();
URL.revokeObjectURL(url);
} else {
throw("DataStream.save: Can't create object URL.");
}
};
/**
Big-endian const to use as default endianness.
@type {boolean}
*/
DataStream.BIG_ENDIAN = false;
/**
Little-endian const to use as default endianness.
@type {boolean}
*/
DataStream.LITTLE_ENDIAN = true;
/**
Whether to extend DataStream buffer when trying to write beyond its size.
If set, the buffer is reallocated to twice its current size until the
requested write fits the buffer.
@type {boolean}
*/
DataStream.prototype._dynamicSize = true;
Object.defineProperty(DataStream.prototype, 'dynamicSize',
{ get: function() {
return this._dynamicSize;
},
set: function(v) {
if (!v) {
this._trimAlloc();
}
this._dynamicSize = v;
} });
/**
Virtual byte length of the DataStream backing buffer.
Updated to be max of original buffer size and last written size.
If dynamicSize is false is set to buffer size.
@type {number}
*/
DataStream.prototype._byteLength = 0;
/**
Returns the byte length of the DataStream object.
@type {number}
*/
Object.defineProperty(DataStream.prototype, 'byteLength',
{ get: function() {
return this._byteLength - this._byteOffset;
}});
/**
Set/get the backing ArrayBuffer of the DataStream object.
The setter updates the DataView to point to the new buffer.
@type {Object}
*/
Object.defineProperty(DataStream.prototype, 'buffer',
{ get: function() {
this._trimAlloc();
return this._buffer;
},
set: function(v) {
this._buffer = v;
this._dataView = new DataView(this._buffer, this._byteOffset);
this._byteLength = this._buffer.byteLength;
} });
/**
Set/get the byteOffset of the DataStream object.
The setter updates the DataView to point to the new byteOffset.
@type {number}
*/
Object.defineProperty(DataStream.prototype, 'byteOffset',
{ get: function() {
return this._byteOffset;
},
set: function(v) {
this._byteOffset = v;
this._dataView = new DataView(this._buffer, this._byteOffset);
this._byteLength = this._buffer.byteLength;
} });
/**
Set/get the backing DataView of the DataStream object.
The setter updates the buffer and byteOffset to point to the DataView values.
@type {Object}
*/
Object.defineProperty(DataStream.prototype, 'dataView',
{ get: function() {
return this._dataView;
},
set: function(v) {
this._byteOffset = v.byteOffset;
this._buffer = v.buffer;
this._dataView = new DataView(this._buffer, this._byteOffset);
this._byteLength = this._byteOffset + v.byteLength;
} });
/**
Internal function to resize the DataStream buffer when required.
@param {number} extra Number of bytes to add to the buffer allocation.
@return {null}
*/
DataStream.prototype._realloc = function(extra) {
if (!this._dynamicSize) {
return;
}
var req = this._byteOffset + this.position + extra;
var blen = this._buffer.byteLength;
if (req <= blen) {
if (req > this._byteLength) {
this._byteLength = req;
}
return;
}
if (blen < 1) {
blen = 1;
}
while (req > blen) {
blen *= 2;
}
var buf = new ArrayBuffer(blen);
var src = new Uint8Array(this._buffer);
var dst = new Uint8Array(buf, 0, src.length);
dst.set(src);
this.buffer = buf;
this._byteLength = req;
};
/**
Internal function to trim the DataStream buffer when required.
Used for stripping out the extra bytes from the backing buffer when
the virtual byteLength is smaller than the buffer byteLength (happens after
growing the buffer with writes and not filling the extra space completely).
@return {null}
*/
DataStream.prototype._trimAlloc = function() {
if (this._byteLength == this._buffer.byteLength) {
return;
}
var buf = new ArrayBuffer(this._byteLength);
var dst = new Uint8Array(buf);
var src = new Uint8Array(this._buffer, 0, dst.length);
dst.set(src);
this.buffer = buf;
};
/**
Sets the DataStream read/write position to given position.
Clamps between 0 and DataStream length.
@param {number} pos Position to seek to.
@return {null}
*/
DataStream.prototype.seek = function(pos) {
var npos = Math.max(0, Math.min(this.byteLength, pos));
this.position = (isNaN(npos) || !isFinite(npos)) ? 0 : npos;
};
/**
Returns true if the DataStream seek pointer is at the end of buffer and
there's no more data to read.
@return {boolean} True if the seek pointer is at the end of the buffer.
*/
DataStream.prototype.isEof = function() {
return (this.position >= this.byteLength);
};
/**
Maps an Int32Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
@param {number} length Number of elements to map.
@param {?boolean} e Endianness of the data to read.
@return {Object} Int32Array to the DataStream backing buffer.
*/
DataStream.prototype.mapInt32Array = function(length, e) {
this._realloc(length * 4);
var arr = new Int32Array(this._buffer, this.byteOffset+this.position, length);
DataStream.arrayToNative(arr, e == null ? this.endianness : e);
this.position += length * 4;
return arr;
};
/**
Maps an Int16Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
@param {number} length Number of elements to map.
@param {?boolean} e Endianness of the data to read.
@return {Object} Int16Array to the DataStream backing buffer.
*/
DataStream.prototype.mapInt16Array = function(length, e) {
this._realloc(length * 2);
var arr = new Int16Array(this._buffer, this.byteOffset+this.position, length);
DataStream.arrayToNative(arr, e == null ? this.endianness : e);
this.position += length * 2;
return arr;
};
/**
Maps an Int8Array into the DataStream buffer.
Nice for quickly reading in data.
@param {number} length Number of elements to map.
@param {?boolean} e Endianness of the data to read.
@return {Object} Int8Array to the DataStream backing buffer.
*/
DataStream.prototype.mapInt8Array = function(length) {
this._realloc(length * 1);
var arr = new Int8Array(this._buffer, this.byteOffset+this.position, length);
this.position += length * 1;
return arr;
};
/**
Maps a Uint32Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
@param {number} length Number of elements to map.
@param {?boolean} e Endianness of the data to read.
@return {Object} Uint32Array to the DataStream backing buffer.
*/
DataStream.prototype.mapUint32Array = function(length, e) {
this._realloc(length * 4);
var arr = new Uint32Array(this._buffer, this.byteOffset+this.position, length);
DataStream.arrayToNative(arr, e == null ? this.endianness : e);
this.position += length * 4;
return arr;
};
/**
Maps a Uint16Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
@param {number} length Number of elements to map.
@param {?boolean} e Endianness of the data to read.
@return {Object} Uint16Array to the DataStream backing buffer.
*/
DataStream.prototype.mapUint16Array = function(length, e) {
this._realloc(length * 2);
var arr = new Uint16Array(this._buffer, this.byteOffset+this.position, length);
DataStream.arrayToNative(arr, e == null ? this.endianness : e);
this.position += length * 2;
return arr;
};
/**
Maps a Uint8Array into the DataStream buffer.
Nice for quickly reading in data.
@param {number} length Number of elements to map.
@param {?boolean} e Endianness of the data to read.
@return {Object} Uint8Array to the DataStream backing buffer.
*/
DataStream.prototype.mapUint8Array = function(length) {
this._realloc(length * 1);
var arr = new Uint8Array(this._buffer, this.byteOffset+this.position, length);
this.position += length * 1;
return arr;
};
/**
Maps a Float64Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
@param {number} length Number of elements to map.
@param {?boolean} e Endianness of the data to read.
@return {Object} Float64Array to the DataStream backing buffer.
*/
DataStream.prototype.mapFloat64Array = function(length, e) {
this._realloc(length * 8);
var arr = new Float64Array(this._buffer, this.byteOffset+this.position, length);
DataStream.arrayToNative(arr, e == null ? this.endianness : e);
this.position += length * 8;
return arr;
};
/**
Maps a Float32Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
@param {number} length Number of elements to map.
@param {?boolean} e Endianness of the data to read.
@return {Object} Float32Array to the DataStream backing buffer.
*/
DataStream.prototype.mapFloat32Array = function(length, e) {
this._realloc(length * 4);
var arr = new Float32Array(this._buffer, this.byteOffset+this.position, length);
DataStream.arrayToNative(arr, e == null ? this.endianness : e);
this.position += length * 4;
return arr;
};
/**
Reads an Int32Array of desired length and endianness from the DataStream.
@param {number} length Number of elements to map.
@param {?boolean} e Endianness of the data to read.
@return {Object} The read Int32Array.
*/
DataStream.prototype.readInt32Array = function(length, e) {
length = length == null ? (this.byteLength-this.position / 4) : length;
var arr = new Int32Array(length);
DataStream.memcpy(arr.buffer, 0,
this.buffer, this.byteOffset+this.position,
length*arr.BYTES_PER_ELEMENT);
DataStream.arrayToNative(arr, e == null ? this.endianness : e);
this.position += arr.byteLength;
return arr;
};
/**
Reads an Int16Array of desired length and endianness from the DataStream.
@param {number} length Number of elements to map.
@param {?boolean} e Endianness of the data to read.
@return {Object} The read Int16Array.
*/
DataStream.prototype.readInt16Array = function(length, e) {
length = length == null ? (this.byteLength-this.position / 2) : length;
var arr = new Int16Array(length);
DataStream.memcpy(arr.buffer, 0,
this.buffer, this.byteOffset+this.position,
length*arr.BYTES_PER_ELEMENT);
DataStream.arrayToNative(arr, e == null ? this.endianness : e);
this.position += arr.byteLength;
return arr;
};
/**
Reads an Int8Array of desired length from the DataStream.
@param {number} length Number of elements to map.
@param {?boolean} e Endianness of the data to read.
@return {Object} The read Int8Array.
*/
DataStream.prototype.readInt8Array = function(length) {
length = length == null ? (this.byteLength-this.position) : length;
var arr = new Int8Array(length);
DataStream.memcpy(arr.buffer, 0,
this.buffer, this.byteOffset+this.position,
length*arr.BYTES_PER_ELEMENT);
this.position += arr.byteLength;
return arr;
};
/**
Reads a Uint32Array of desired length and endianness from the DataStream.
@param {number} length Number of elements to map.
@param {?boolean} e Endianness of the data to read.
@return {Object} The read Uint32Array.
*/
DataStream.prototype.readUint32Array = function(length, e) {
length = length == null ? (this.byteLength-this.position / 4) : length;
var arr = new Uint32Array(length);
DataStream.memcpy(arr.buffer, 0,
this.buffer, this.byteOffset+this.position,
length*arr.BYTES_PER_ELEMENT);
DataStream.arrayToNative(arr, e == null ? this.endianness : e);
this.position += arr.byteLength;
return arr;
};
/**
Reads a Uint16Array of desired length and endianness from the DataStream.
@param {number} length Number of elements to map.
@param {?boolean} e Endianness of the data to read.
@return {Object} The read Uint16Array.
*/
DataStream.prototype.readUint16Array = function(length, e) {
length = length == null ? (this.byteLength-this.position / 2) : length;
var arr = new Uint16Array(length);
DataStream.memcpy(arr.buffer, 0,
this.buffer, this.byteOffset+this.position,
length*arr.BYTES_PER_ELEMENT);
DataStream.arrayToNative(arr, e == null ? this.endianness : e);
this.position += arr.byteLength;
return arr;
};
/**
Reads a Uint8Array of desired length from the DataStream.
@param {number} length Number of elements to map.
@param {?boolean} e Endianness of the data to read.
@return {Object} The read Uint8Array.
*/
DataStream.prototype.readUint8Array = function(length) {
length = length == null ? (this.byteLength-this.position) : length;
var arr = new Uint8Array(length);
DataStream.memcpy(arr.buffer, 0,
this.buffer, this.byteOffset+this.position,
length*arr.BYTES_PER_ELEMENT);
this.position += arr.byteLength;
return arr;
};
/**
Reads a Float64Array of desired length and endianness from the DataStream.
@param {number} length Number of elements to map.
@param {?boolean} e Endianness of the data to read.
@return {Object} The read Float64Array.
*/
DataStream.prototype.readFloat64Array = function(length, e) {
length = length == null ? (this.byteLength-this.position / 8) : length;
var arr = new Float64Array(length);
DataStream.memcpy(arr.buffer, 0,
this.buffer, this.byteOffset+this.position,
length*arr.BYTES_PER_ELEMENT);
DataStream.arrayToNative(arr, e == null ? this.endianness : e);
this.position += arr.byteLength;
return arr;
};
/**
Reads a Float32Array of desired length and endianness from the DataStream.
@param {number} length Number of elements to map.
@param {?boolean} e Endianness of the data to read.
@return {Object} The read Float32Array.
*/
DataStream.prototype.readFloat32Array = function(length, e) {
length = length == null ? (this.byteLength-this.position / 4) : length;
var arr = new Float32Array(length);
DataStream.memcpy(arr.buffer, 0,
this.buffer, this.byteOffset+this.position,
length*arr.BYTES_PER_ELEMENT);
DataStream.arrayToNative(arr, e == null ? this.endianness : e);
this.position += arr.byteLength;
return arr;
};
/**
Writes an Int32Array of specified endianness to the DataStream.
@param {Object} arr The array to write.
@param {?boolean} e Endianness of the data to write.
*/
DataStream.prototype.writeInt32Array = function(arr, e) {
this._realloc(arr.length * 4);
if (arr instanceof Int32Array &&
this.byteOffset+this.position % arr.BYTES_PER_ELEMENT == 0) {
DataStream.memcpy(this._buffer, this.byteOffset+this.position,
arr.buffer, 0,
arr.byteLength);
this.mapInt32Array(arr.length, e);
} else {
for (var i=0; i<arr.length; i++) {
this.writeInt32(arr[i], e);
}
}
};
/**
Writes an Int16Array of specified endianness to the DataStream.
@param {Object} arr The array to write.
@param {?boolean} e Endianness of the data to write.
*/
DataStream.prototype.writeInt16Array = function(arr, e) {
this._realloc(arr.length * 2);
if (arr instanceof Int16Array &&
this.byteOffset+this.position % arr.BYTES_PER_ELEMENT == 0) {
DataStream.memcpy(this._buffer, this.byteOffset+this.position,
arr.buffer, 0,
arr.byteLength);
this.mapInt16Array(arr.length, e);
} else {
for (var i=0; i<arr.length; i++) {
this.writeInt16(arr[i], e);
}
}
};
/**
Writes an Int8Array to the DataStream.
@param {Object} arr The array to write.
*/
DataStream.prototype.writeInt8Array = function(arr) {
this._realloc(arr.length * 1);
if (arr instanceof Int8Array &&
this.byteOffset+this.position % arr.BYTES_PER_ELEMENT == 0) {
DataStream.memcpy(this._buffer, this.byteOffset+this.position,
arr.buffer, 0,
arr.byteLength);
this.mapInt8Array(arr.length);
} else {
for (var i=0; i<arr.length; i++) {
this.writeInt8(arr[i]);
}
}
};
/**
Writes a Uint32Array of specified endianness to the DataStream.
@param {Object} arr The array to write.
@param {?boolean} e Endianness of the data to write.
*/
DataStream.prototype.writeUint32Array = function(arr, e) {
this._realloc(arr.length * 4);
if (arr instanceof Uint32Array &&
this.byteOffset+this.position % arr.BYTES_PER_ELEMENT == 0) {
DataStream.memcpy(this._buffer, this.byteOffset+this.position,
arr.buffer, 0,
arr.byteLength);
this.mapUint32Array(arr.length, e);
} else {
for (var i=0; i<arr.length; i++) {
this.writeUint32(arr[i], e);
}
}
};
/**
Writes a Uint16Array of specified endianness to the DataStream.
@param {Object} arr The array to write.
@param {?boolean} e Endianness of the data to write.
*/
DataStream.prototype.writeUint16Array = function(arr, e) {
this._realloc(arr.length * 2);
if (arr instanceof Uint16Array &&
this.byteOffset+this.position % arr.BYTES_PER_ELEMENT == 0) {
DataStream.memcpy(this._buffer, this.byteOffset+this.position,
arr.buffer, 0,
arr.byteLength);
this.mapUint16Array(arr.length, e);
} else {
for (var i=0; i<arr.length; i++) {
this.writeUint16(arr[i], e);
}
}
};
/**
Writes a Uint8Array to the DataStream.
@param {Object} arr The array to write.
*/
DataStream.prototype.writeUint8Array = function(arr) {
this._realloc(arr.length * 1);
if (arr instanceof Uint8Array &&
this.byteOffset+this.position % arr.BYTES_PER_ELEMENT == 0) {
DataStream.memcpy(this._buffer, this.byteOffset+this.position,
arr.buffer, 0,
arr.byteLength);
this.mapUint8Array(arr.length);
} else {
for (var i=0; i<arr.length; i++) {
this.writeUint8(arr[i]);
}
}
};
/**
Writes a Float64Array of specified endianness to the DataStream.
@param {Object} arr The array to write.
@param {?boolean} e Endianness of the data to write.
*/
DataStream.prototype.writeFloat64Array = function(arr, e) {
this._realloc(arr.length * 8);
if (arr instanceof Float64Array &&
this.byteOffset+this.position % arr.BYTES_PER_ELEMENT == 0) {
DataStream.memcpy(this._buffer, this.byteOffset+this.position,
arr.buffer, 0,
arr.byteLength);
this.mapFloat64Array(arr.length, e);
} else {
for (var i=0; i<arr.length; i++) {
this.writeFloat64(arr[i], e);
}
}
};
/**
Writes a Float32Array of specified endianness to the DataStream.
@param {Object} arr The array to write.
@param {?boolean} e Endianness of the data to write.
*/
DataStream.prototype.writeFloat32Array = function(arr, e) {
this._realloc(arr.length * 4);
if (arr instanceof Float32Array &&
this.byteOffset+this.position % arr.BYTES_PER_ELEMENT == 0) {
DataStream.memcpy(this._buffer, this.byteOffset+this.position,
arr.buffer, 0,
arr.byteLength);
this.mapFloat32Array(arr.length, e);
} else {
for (var i=0; i<arr.length; i++) {
this.writeFloat32(arr[i], e);
}
}
};
/**
Reads a 32-bit int from the DataStream with the desired endianness.
@param {?boolean} e Endianness of the number.
@return {number} The read number.
*/
DataStream.prototype.readInt32 = function(e) {
var v = this._dataView.getInt32(this.position, e == null ? this.endianness : e);
this.position += 4;
return v;
};
/**
Reads a 32-bit int from the DataStream with the offset.
@param {number} offset The offset.
@return {number} The read number.
*/
DataStream.prototype.readInt = function (offset) {
this.seek(offset);
return this.readInt32();
};
/**
Reads a 16-bit int from the DataStream with the desired endianness.
@param {?boolean} e Endianness of the number.
@return {number} The read number.
*/
DataStream.prototype.readInt16 = function(e) {
var v = this._dataView.getInt16(this.position, e == null ? this.endianness : e);
this.position += 2;
return v;
};
/**
Reads a 16-bit int from the DataStream with the offset
@param {number} offset The offset.
@return {number} The read number.
*/
DataStream.prototype.readShort = function (offset) {
this.seek(offset);
return this.readInt16();
};
/**
Reads an 8-bit int from the DataStream.
@return {number} The read number.
*/
DataStream.prototype.readInt8 = function() {
var v = this._dataView.getInt8(this.position);
this.position += 1;
return v;
};
/**
Reads an 8-bit int from the DataStream with the offset.
@param {number} offset The offset.
@return {number} The read number.
*/
DataStream.prototype.readByte = function (offset) {
this.seek(offset);
return this.readInt8();
};
/**
Reads a 32-bit unsigned int from the DataStream with the desired endianness.
@param {?boolean} e Endianness of the number.
@return {number} The read number.
*/
DataStream.prototype.readUint32 = function(e) {
var v = this._dataView.getUint32(this.position, e == null ? this.endianness : e);
this.position += 4;
return v;
};
/**
Reads a 16-bit unsigned int from the DataStream with the desired endianness.
@param {?boolean} e Endianness of the number.
@return {number} The read number.
*/
DataStream.prototype.readUint16 = function(e) {
var v = this._dataView.getUint16(this.position, e == null ? this.endianness : e);
this.position += 2;
return v;
};
/**
Reads an 8-bit unsigned int from the DataStream.
@return {number} The read number.
*/
DataStream.prototype.readUint8 = function() {
var v = this._dataView.getUint8(this.position);
this.position += 1;
return v;
};
/**
Reads a 32-bit float from the DataStream with the desired endianness.
@param {?boolean} e Endianness of the number.
@return {number} The read number.
*/
DataStream.prototype.readFloat32 = function(e) {
var v = this._dataView.getFloat32(this.position, e == null ? this.endianness : e);
this.position += 4;
return v;
};
/**
Reads a 64-bit float from the DataStream with the desired endianness.
@param {?boolean} e Endianness of the number.
@return {number} The read number.
*/
DataStream.prototype.readFloat64 = function(e) {
var v = this._dataView.getFloat64(this.position, e == null ? this.endianness : e);
this.position += 8;
return v;
};
/**
Writes a 32-bit int to the DataStream with the desired endianness.
@param {number} v Number to write.
@param {?boolean} e Endianness of the number.
*/
DataStream.prototype.writeInt32 = function(v, e) {
this._realloc(4);
this._dataView.setInt32(this.position, v, e == null ? this.endianness : e);
this.position += 4;
};
/**
Writes a 16-bit int to the DataStream with the desired endianness.
@param {number} v Number to write.
@param {?boolean} e Endianness of the number.
*/
DataStream.prototype.writeInt16 = function(v, e) {
this._realloc(2);
this._dataView.setInt16(this.position, v, e == null ? this.endianness : e);
this.position += 2;
};
/**
Writes an 8-bit int to the DataStream.
@param {number} v Number to write.
*/
DataStream.prototype.writeInt8 = function(v) {
this._realloc(1);
this._dataView.setInt8(this.position, v);
this.position += 1;
};
/**
Writes a 32-bit unsigned int to the DataStream with the desired endianness.
@param {number} v Number to write.
@param {?boolean} e Endianness of the number.
*/
DataStream.prototype.writeUint32 = function(v, e) {
this._realloc(4);
this._dataView.setUint32(this.position, v, e == null ? this.endianness : e);
this.position += 4;
};
/**
Writes a 16-bit unsigned int to the DataStream with the desired endianness.
@param {number} v Number to write.
@param {?boolean} e Endianness of the number.
*/
DataStream.prototype.writeUint16 = function(v, e) {
this._realloc(2);
this._dataView.setUint16(this.position, v, e == null ? this.endianness : e);
this.position += 2;
};
/**
Writes an 8-bit unsigned int to the DataStream.
@param {number} v Number to write.
*/
DataStream.prototype.writeUint8 = function(v) {
this._realloc(1);
this._dataView.setUint8(this.position, v);
this.position += 1;
};
/**
Writes a 32-bit float to the DataStream with the desired endianness.
@param {number} v Number to write.
@param {?boolean} e Endianness of the number.
*/
DataStream.prototype.writeFloat32 = function(v, e) {
this._realloc(4);
this._dataView.setFloat32(this.position, v, e == null ? this.endianness : e);
this.position += 4;
};
/**
Writes a 64-bit float to the DataStream with the desired endianness.
@param {number} v Number to write.
@param {?boolean} e Endianness of the number.
*/
DataStream.prototype.writeFloat64 = function(v, e) {
this._realloc(8);
this._dataView.setFloat64(this.position, v, e == null ? this.endianness : e);
this.position += 8;
};
/**
Native endianness. Either DataStream.BIG_ENDIAN or DataStream.LITTLE_ENDIAN
depending on the platform endianness.
@type {boolean}
*/
DataStream.endianness = new Int8Array(new Int16Array([1]).buffer)[0] > 0;
/**
Copies byteLength bytes from the src buffer at srcOffset to the
dst buffer at dstOffset.
@param {Object} dst Destination ArrayBuffer to write to.
@param {number} dstOffset Offset to the destination ArrayBuffer.
@param {Object} src Source ArrayBuffer to read from.
@param {number} srcOffset Offset to the source ArrayBuffer.
@param {number} byteLength Number of bytes to copy.
*/
DataStream.memcpy = function(dst, dstOffset, src, srcOffset, byteLength) {
var dstU8 = new Uint8Array(dst, dstOffset, byteLength);
var srcU8 = new Uint8Array(src, srcOffset, byteLength);
dstU8.set(srcU8);
};
/**
Converts array to native endianness in-place.
@param {Object} array Typed array to convert.
@param {boolean} arrayIsLittleEndian True if the data in the array is
little-endian. Set false for big-endian.
@return {Object} The converted typed array.
*/
DataStream.arrayToNative = function(array, arrayIsLittleEndian) {
if (arrayIsLittleEndian == this.endianness) {
return array;
} else {
return this.flipArrayEndianness(array);
}
};
/**
Converts native endianness array to desired endianness in-place.
@param {Object} array Typed array to convert.
@param {boolean} littleEndian True if the converted array should be
little-endian. Set false for big-endian.
@return {Object} The converted typed array.
*/
DataStream.nativeToEndian = function(array, littleEndian) {
if (this.endianness == littleEndian) {
return array;
} else {
return this.flipArrayEndianness(array);
}
};
/**
Flips typed array endianness in-place.
@param {Object} array Typed array to flip.
@return {Object} The converted typed array.
*/
DataStream.flipArrayEndianness = function(array) {
var u8 = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
for (var i=0; i<array.byteLength; i+=array.BYTES_PER_ELEMENT) {
for (var j=i+array.BYTES_PER_ELEMENT-1, k=i; j>k; j--, k++) {
var tmp = u8[k];
u8[k] = u8[j];
u8[j] = tmp;
}
}
return array;
};
/**
Creates an array from an array of character codes.
Uses String.fromCharCode on the character codes and concats the results into a string.
@param {array} array Array of character codes.
@return {string} String created from the character codes.
**/
DataStream.createStringFromArray = function(array) {
var str = "";
for (var i=0; i<array.length; i++) {
str += String.fromCharCode(array[i]);
}
return str;
};
/**
Seek position where DataStream#readStruct ran into a problem.
Useful for debugging struct parsing.
@type {number}
*/
DataStream.prototype.failurePosition = 0;
/**
Reads a struct of data from the DataStream. The struct is defined as
a flat array of [name, type]-pairs. See the example below:
ds.readStruct([
'headerTag', 'uint32', // Uint32 in DataStream endianness.
'headerTag2', 'uint32be', // Big-endian Uint32.
'headerTag3', 'uint32le', // Little-endian Uint32.
'array', ['[]', 'uint32', 16], // Uint32Array of length 16.
'array2Length', 'uint32',
'array2', ['[]', 'uint32', 'array2Length'] // Uint32Array of length array2Length
]);
The possible values for the type are as follows:
// Number types
// Unsuffixed number types use DataStream endianness.
// To explicitly specify endianness, suffix the type with
// 'le' for little-endian or 'be' for big-endian,
// e.g. 'int32be' for big-endian int32.
'uint8' -- 8-bit unsigned int
'uint16' -- 16-bit unsigned int
'uint32' -- 32-bit unsigned int
'int8' -- 8-bit int
'int16' -- 16-bit int
'int32' -- 32-bit int
'float32' -- 32-bit float
'float64' -- 64-bit float
// String types
'cstring' -- ASCII string terminated by a zero byte.
'string:N' -- ASCII string of length N, where N is a literal integer.
'string:variableName' -- ASCII string of length $variableName,
where 'variableName' is a previously parsed number in the current struct.
'string,CHARSET:N' -- String of byteLength N encoded with given CHARSET.
'u16string:N' -- UCS-2 string of length N in DataStream endianness.
'u16stringle:N' -- UCS-2 string of length N in little-endian.
'u16stringbe:N' -- UCS-2 string of length N in big-endian.
// Complex types
[name, type, name_2, type_2, ..., name_N, type_N] -- Struct
function(dataStream, struct) {} -- Callback function to read and return data.
{get: function(dataStream, struct) {},
set: function(dataStream, struct) {}}
-- Getter/setter functions to read and return data, handy for using the same
struct definition for reading and writing structs.
['[]', type, length] -- Array of given type and length. The length can be either
a number, a string that references a previously-read
field, or a callback function(struct, dataStream, type){}.
If length is '*', reads in as many elements as it can.
@param {Object} structDefinition Struct definition object.
@return {Object} The read struct. Null if failed to read struct.
*/
DataStream.prototype.readStruct = function(structDefinition) {
var struct = {}, t, v, n;
var p = this.position;
for (var i=0; i<structDefinition.length; i+=2) {
t = structDefinition[i+1];
v = this.readType(t, struct);
if (v == null) {
if (this.failurePosition == 0) {
this.failurePosition = this.position;
}
this.position = p;
return null;
}
struct[structDefinition[i]] = v;
}
return struct;
};
/**
Read UCS-2 string of desired length and endianness from the DataStream.
@param {number} length The length of the string to read.
@param {boolean} endianness The endianness of the string data in the DataStream.
@return {string} The read string.
*/
DataStream.prototype.readUCS2String = function(length, endianness) {
return DataStream.createStringFromArray(this.readUint16Array(length, endianness));
};
/**
Read UCS-2 string of desired length and offset from the DataStream.
@param {number} offset The offset.
@param {number} length The length of the string to read.
@return {string} The read string.
*/
DataStream.prototype.readStringAt = function (offset, length) {
this.seek(offset);
return this.readUCS2String(length);
};
/**
Write a UCS-2 string of desired endianness to the DataStream. The
lengthOverride argument lets you define the number of characters to write.
If the string is shorter than lengthOverride, the extra space is padded with
zeroes.
@param {string} str The string to write.
@param {?boolean} endianness The endianness to use for the written string data.
@param {?number} lengthOverride The number of characters to write.
*/
DataStream.prototype.writeUCS2String = function(str, endianness, lengthOverride) {
if (lengthOverride == null) {
lengthOverride = str.length;
}
for (var i = 0; i < str.length && i < lengthOverride; i++) {
this.writeUint16(str.charCodeAt(i), endianness);
}
for (; i<lengthOverride; i++) {
this.writeUint16(0);
}
};
/**
Read a string of desired length and encoding from the DataStream.
@param {number} length The length of the string to read in bytes.
@param {?string} encoding The encoding of the string data in the DataStream.
Defaults to ASCII.
@return {string} The read string.
*/
DataStream.prototype.readString = function(length, encoding) {
if (encoding == null || encoding == "ASCII") {
return DataStream.createStringFromArray(this.mapUint8Array(length == null ? this.byteLength-this.position : length));
} else {
return (new TextDecoder(encoding)).decode(this.mapUint8Array(length));
}
};
/**
Writes a string of desired length and encoding to the DataStream.
@param {string} s The string to write.
@param {?string} encoding The encoding for the written string data.
Defaults to ASCII.
@param {?number} length The number of characters to write.
*/
DataStream.prototype.writeString = function(s, encoding, length) {
if (encoding == null || encoding == "ASCII") {
if (length != null) {
var i = 0;
var len = Math.min(s.length, length);
for (i=0; i<len; i++) {
this.writeUint8(s.charCodeAt(i));
}
for (; i<length; i++) {
this.writeUint8(0);
}
} else {
for (var i=0; i<s.length; i++) {
this.writeUint8(s.charCodeAt(i));
}
}
} else {
this.writeUint8Array((new TextEncoder(encoding)).encode(s.substring(0, length)));
}
};
/**
Read null-terminated string of desired length from the DataStream. Truncates
the returned string so that the null byte is not a part of it.
@param {?number} length The length of the string to read.
@return {string} The read string.
*/
DataStream.prototype.readCString = function(length) {
var blen = this.byteLength-this.position;
var u8 = new Uint8Array(this._buffer, this._byteOffset + this.position);
var len = blen;
if (length != null) {
len = Math.min(length, blen);
}
for (var i = 0; i < len && u8[i] != 0; i++); // find first zero byte
var s = DataStream.createStringFromArray(this.mapUint8Array(i));
if (length != null) {
this.position += len-i;
} else if (i != blen) {
this.position += 1; // trailing zero if not at end of buffer
}
return s;
};
/**
Writes a null-terminated string to DataStream and zero-pads it to length
bytes. If length is not given, writes the string followed by a zero.
If string is longer than length, the written part of the string does not have
a trailing zero.
@param {string} s The string to write.
@param {?number} length The number of characters to write.
*/
DataStream.prototype.writeCString = function(s, length) {
if (length != null) {
var i = 0;
var len = Math.min(s.length, length);
for (i=0; i<len; i++) {
this.writeUint8(s.charCodeAt(i));
}
for (; i<length; i++) {
this.writeUint8(0);
}
} else {
for (var i=0; i<s.length; i++) {
this.writeUint8(s.charCodeAt(i));
}
this.writeUint8(0);
}
};
/**
Reads an object of type t from the DataStream, passing struct as the thus-far
read struct to possible callbacks that refer to it. Used by readStruct for
reading in the values, so the type is one of the readStruct types.
@param {Object} t Type of the object to read.
@param {?Object} struct Struct to refer to when resolving length references
and for calling callbacks.
@return {?Object} Returns the object on successful read, null on unsuccessful.
*/
DataStream.prototype.readType = function(t, struct) {
if (typeof t == "function") {
return t(this, struct);
} else if (typeof t == "object" && !(t instanceof Array)) {
return t.get(this, struct);
} else if (t instanceof Array && t.length != 3) {
return this.readStruct(t, struct);
}
var v = null;
var lengthOverride = null;
var charset = "ASCII";
var pos = this.position;
var len;
if (typeof t == 'string' && /:/.test(t)) {
var tp = t.split(":");
t = tp[0];
len = tp[1];
// allow length to be previously parsed variable
// e.g. 'string:fieldLength', if `fieldLength` has
// been parsed previously.
if (struct[len] != null) {
lengthOverride = parseInt(struct[len]);
} else {
// assume literal integer e.g., 'string:4'
lengthOverride = parseInt(tp[1]);
}
}
if (typeof t == 'string' && /,/.test(t)) {
var tp = t.split(",");
t = tp[0];
charset = parseInt(tp[1]);
}
switch(t) {
case 'uint8':
v = this.readUint8(); break;
case 'int8':
v = this.readInt8(); break;
case 'uint16':
v = this.readUint16(this.endianness); break;
case 'int16':
v = this.readInt16(this.endianness); break;
case 'uint32':
v = this.readUint32(this.endianness); break;
case 'int32':
v = this.readInt32(this.endianness); break;
case 'float32':
v = this.readFloat32(this.endianness); break;
case 'float64':
v = this.readFloat64(this.endianness); break;
case 'uint16be':
v = this.readUint16(DataStream.BIG_ENDIAN); break;
case 'int16be':
v = this.readInt16(DataStream.BIG_ENDIAN); break;
case 'uint32be':
v = this.readUint32(DataStream.BIG_ENDIAN); break;
case 'int32be':
v = this.readInt32(DataStream.BIG_ENDIAN); break;
case 'float32be':
v = this.readFloat32(DataStream.BIG_ENDIAN); break;
case 'float64be':
v = this.readFloat64(DataStream.BIG_ENDIAN); break;
case 'uint16le':
v = this.readUint16(DataStream.LITTLE_ENDIAN); break;
case 'int16le':
v = this.readInt16(DataStream.LITTLE_ENDIAN); break;
case 'uint32le':
v = this.readUint32(DataStream.LITTLE_ENDIAN); break;
case 'int32le':
v = this.readInt32(DataStream.LITTLE_ENDIAN); break;
case 'float32le':
v = this.readFloat32(DataStream.LITTLE_ENDIAN); break;
case 'float64le':
v = this.readFloat64(DataStream.LITTLE_ENDIAN); break;
case 'cstring':
v = this.readCString(lengthOverride); break;
case 'string':
v = this.readString(lengthOverride, charset); break;
case 'u16string':
v = this.readUCS2String(lengthOverride, this.endianness); break;
case 'u16stringle':
v = this.readUCS2String(lengthOverride, DataStream.LITTLE_ENDIAN); break;
case 'u16stringbe':
v = this.readUCS2String(lengthOverride, DataStream.BIG_ENDIAN); break;
default:
if (t.length == 3) {
var ta = t[1];
var len = t[2];
var length = 0;
if (typeof len == 'function') {
length = len(struct, this, t);
} else if (typeof len == 'string' && struct[len] != null) {
length = parseInt(struct[len]);
} else {
length = parseInt(len);
}
if (typeof ta == "string") {
var tap = ta.replace(/(le|be)$/, '');
var endianness = null;
if (/le$/.test(ta)) {
endianness = DataStream.LITTLE_ENDIAN;
} else if (/be$/.test(ta)) {
endianness = DataStream.BIG_ENDIAN;
}
if (len == '*') {
length = null;
}
switch(tap) {
case 'uint8':
v = this.readUint8Array(length); break;
case 'uint16':
v = this.readUint16Array(length, endianness); break;
case 'uint32':
v = this.readUint32Array(length, endianness); break;
case 'int8':
v = this.readInt8Array(length); break;
case 'int16':
v = this.readInt16Array(length, endianness); break;
case 'int32':
v = this.readInt32Array(length, endianness); break;
case 'float32':
v = this.readFloat32Array(length, endianness); break;
case 'float64':
v = this.readFloat64Array(length, endianness); break;
case 'cstring':
case 'utf16string':
case 'string':
if (length == null) {
v = [];
while (!this.isEof()) {
var u = this.readType(ta, struct);
if (u == null) break;
v.push(u);
}
} else {
v = new Array(length);
for (var i=0; i<length; i++) {
v[i] = this.readType(ta, struct);
}
}
break;
}
} else {
if (len == '*') {
v = [];
this.buffer;
while (true) {
var p = this.position;
try {
var o = this.readType(ta, struct);
if (o == null) {
this.position = p;
break;
}
v.push(o);
} catch(e) {
this.position = p;
break;
}
}
} else {
v = new Array(length);
for (var i=0; i<length; i++) {
var u = this.readType(ta, struct);
if (u == null) return null;
v[i] = u;
}
}
}
break;
}
}
if (lengthOverride != null) {
this.position = pos + lengthOverride;
}
return v;
};
/**
Writes a struct to the DataStream. Takes a structDefinition that gives the
types and a struct object that gives the values. Refer to readStruct for the
structure of structDefinition.
@param {Object} structDefinition Type definition of the struct.
@param {Object} struct The struct data object.
*/
DataStream.prototype.writeStruct = function(structDefinition, struct) {
for (var i = 0; i < structDefinition.length; i+=2) {
var t = structDefinition[i+1];
this.writeType(t, struct[structDefinition[i]], struct);
}
};
/**
Writes object v of type t to the DataStream.
@param {Object} t Type of data to write.
@param {Object} v Value of data to write.
@param {Object} struct Struct to pass to write callback functions.
*/
DataStream.prototype.writeType = function(t, v, struct) {
if (typeof t == "function") {
return t(this, v);
} else if (typeof t == "object" && !(t instanceof Array)) {
return t.set(this, v, struct);
}
var lengthOverride = null;
var charset = "ASCII";
var pos = this.position;
if (typeof(t) == 'string' && /:/.test(t)) {
var tp = t.split(":");
t = tp[0];
lengthOverride = parseInt(tp[1]);
}
if (typeof t == 'string' && /,/.test(t)) {
var tp = t.split(",");
t = tp[0];
charset = parseInt(tp[1]);
}
switch(t) {
case 'uint8':
this.writeUint8(v);
break;
case 'int8':
this.writeInt8(v);
break;
case 'uint16':
this.writeUint16(v, this.endianness);
break;
case 'int16':
this.writeInt16(v, this.endianness);
break;
case 'uint32':
this.writeUint32(v, this.endianness);
break;
case 'int32':
this.writeInt32(v, this.endianness);
break;
case 'float32':
this.writeFloat32(v, this.endianness);
break;
case 'float64':
this.writeFloat64(v, this.endianness);
break;
case 'uint16be':
this.writeUint16(v, DataStream.BIG_ENDIAN);
break;
case 'int16be':
this.writeInt16(v, DataStream.BIG_ENDIAN);
break;
case 'uint32be':
this.writeUint32(v, DataStream.BIG_ENDIAN);
break;
case 'int32be':
this.writeInt32(v, DataStream.BIG_ENDIAN);
break;
case 'float32be':
this.writeFloat32(v, DataStream.BIG_ENDIAN);
break;
case 'float64be':
this.writeFloat64(v, DataStream.BIG_ENDIAN);
break;
case 'uint16le':
this.writeUint16(v, DataStream.LITTLE_ENDIAN);
break;
case 'int16le':
this.writeInt16(v, DataStream.LITTLE_ENDIAN);
break;
case 'uint32le':
this.writeUint32(v, DataStream.LITTLE_ENDIAN);
break;
case 'int32le':
this.writeInt32(v, DataStream.LITTLE_ENDIAN);
break;
case 'float32le':
this.writeFloat32(v, DataStream.LITTLE_ENDIAN);
break;
case 'float64le':
this.writeFloat64(v, DataStream.LITTLE_ENDIAN);
break;
case 'cstring':
this.writeCString(v, lengthOverride);
break;
case 'string':
this.writeString(v, charset, lengthOverride);
break;
case 'u16string':
this.writeUCS2String(v, this.endianness, lengthOverride);
break;
case 'u16stringle':
this.writeUCS2String(v, DataStream.LITTLE_ENDIAN, lengthOverride);
break;
case 'u16stringbe':
this.writeUCS2String(v, DataStream.BIG_ENDIAN, lengthOverride);
break;
default:
if (t.length == 3) {
var ta = t[1];
for (var i=0; i<v.length; i++) {
this.writeType(ta, v[i]);
}
break;
} else {
this.writeStruct(t, v);
break;
}
}
if (lengthOverride != null) {
this.position = pos;
this._realloc(lengthOverride);
this.position = pos + lengthOverride;
}
};
// Export DataStream for amd environments
if (typeof define === 'function' && define.amd) {
define('DataStream', [], function() {
return DataStream;
});
}
// Export DataStream for CommonJS
if (typeof module === 'object' && module && module.exports) {
module.exports = DataStream;
}
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.evaluate = evaluate;
var t = require("@webassemblyjs/ast");
var _require = require("./kernel/exec"),
executeStackFrame = _require.executeStackFrame;
var _require2 = require("./kernel/stackframe"),
createStackFrame = _require2.createStackFrame;
var modulevalue = require("./runtime/values/module");
function evaluate(allocator, code) {
// Create an empty module instance for the context
var moduleInstance = modulevalue.createInstance(allocator, t.module(undefined, []));
var stackFrame = createStackFrame(code, [], moduleInstance, allocator);
var res = executeStackFrame(stackFrame);
return res;
} |
$(document).ready(function () {
/*$(".button").click(function () {
setTimeout(function () {
alert('clicked');
window.location = "user.html";
}, 500);
});*/
// counter function starts
$('.count').each(function () {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
// counter function ends
$("option").click(function () {
setTimeout(function () {
if ('' !== $('#firstname').val() && '' !== $('#email').val() && '' !== $('#password').val()) {
$('.info, .success, .warning, .error').css('display', 'none');
$('.messages').css('display', 'none');
$('.warning').css('display', 'none');
} else {
$('.info, .success, .warning, .error').css('display', 'none');
$('.messages').css('display', 'block');
$('.warning').css('display', 'block');
document.getElementById('MSG_WARNING').innerHTML = "<b>Please Enter details for all Username, Email and Password</b>";
}
//window.location.href = "register/";
}, 500);
});
$("#file").change(function () {
alert('alert');
$("#filename").value = $("#file").value;
});
$(".prf_select").hide();
$(".ask_input_i").focus(function () {
setTimeout(function () {
$(".prf_select").show();
}, 1500);
});
$(".prf_select_give").hide();
$(".ask_input_give").focus(function () {
setTimeout(function () {
$(".prf_select_give").show();
}, 1500);
});
$(".khub_search").click(function () {
setTimeout(function () {
window.location = "khub.html";
}, 500);
});
// Knowldge Hub page tabs s
$(function () {
$('ul.tabs li:first').addClass('active');
$('.block article').hide();
$('.block article:first').show();
$('ul.tabs li').on('click', function () {
$('ul.tabs li').removeClass('active');
$(this).addClass('active');
$('.block article').hide();
var activeTab = $(this).find('a').attr('href');
$(activeTab).show();
return false;
});
});
// Knowldge Hub page tabs s
$("#profile_ask").hide();
$("#prf_input_ask").click(function () {
$("#profile_ask").slideToggle();
});
$("#profile_give").hide();
$("#prf_input_give").click(function () {
$("#profile_give").slideToggle();
});
$(".up_option").hide();
$(".a_up").click(function () {
$(".up_option").slideToggle();
});
$(".referel_img").hover(function(){
//$(this).hide();
});
/* Fade Effect S */
if($(window).width() < 769){
$('.nav_fade ul').hide();
$('a.nav_btn').show();
}
else if($(window).width() > 768){
$('.nav_fade ul').show();
$('a.nav_btn').hide();
}
$('.nav_btn').click(function(){
$('.nav_fade ul').fadeToggle(500);
});
$(window).resize(function(){
if($(window).width() < 769){
$('.nav_fade ul').hide();
$('a.nav_btn').show();
}
else if($(window).width() > 768){
$('.nav_fade ul').show();
$('a.nav_btn').hide();
}
});
/* Fade Effect E */
});
|
'use strict';
// const db = require('./index');
module.exports = function(sequelize, DataTypes) {
var users = sequelize.define('users', {
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
points: DataTypes.INTEGER,
image: DataTypes.STRING,
passportId: DataTypes.FLOAT,
currentLat: DataTypes.INTEGER,
currentLng: DataTypes.INTEGER
}, {
classMethods: {
associate: function(models) {
// db.Users.hasMany(db.models.Friends)
// Users.hasMany(Friends, {foreignKey: 'users_id'})
// Users.hasMany(models.Friends)
// Users.hasMany(models.Friends, {as: 'friender', foreignKey: 'frienderId'})
// Users.hasMany(models.Friends, {as: 'befriender', foreignKey: 'befrienderId'})
// associations can be defined here
//Users.hasMany(Friends)
//User.hasOne(project) in sequelize user is source and project is the target
}
}
});
return users;
}; |
version https://git-lfs.github.com/spec/v1
oid sha256:852ab0d705c6de3eba05683fff7ec17876d8732fe5d0a5702b43a8180ec79cfe
size 2943
|
;(function($){
/**
* jqGrid German Translation
* Version 1.0.0 (developed for jQuery Grid 3.3.1)
* Olaf Klöppel opensource@blue-hit.de
* http://blue-hit.de/
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
**/
$.jgrid = {};
$.jgrid.defaults = {
recordtext: "Zeile(n)",
loadtext: "Lädt...",
pgtext : "/"
};
$.jgrid.search = {
caption: "Suche...",
Find: "Finden",
Reset: "Zurücksetzen",
odata : ['gleich', 'ungleich', 'kleiner', 'kleiner oder gleich','größer','größer oder gleich', 'beginnt mit','endet mit','beinhaltet' ]
};
$.jgrid.edit = {
addCaption: "Datensatz hinzufügen",
editCaption: "Datensatz bearbeiten",
bSubmit: "Speichern",
bCancel: "Abbrechen",
bClose: "Schließen",
processData: "Verarbeitung läuft...",
msg: {
required:"Feld ist erforderlich",
number: "Bitte geben Sie eine Zahl ein",
minValue:"Wert muss größer oder gleich sein, als ",
maxValue:"Wert muss kleiner oder gleich sein, als ",
email: "ist keine valide E-Mail Adresse",
integer: "Bitte geben Sie eine Ganzzahl ein",
date: "Please, enter valid date value"
}
};
$.jgrid.del = {
caption: "Löschen",
msg: "Ausgewählte Datensätze löschen?",
bSubmit: "Löschen",
bCancel: "Abbrechen",
processData: "Verarbeitung läuft..."
};
$.jgrid.nav = {
edittext: " ",
edittitle: "Ausgewählten Zeile editieren",
addtext:" ",
addtitle: "Neuen Zeile einfügen",
deltext: " ",
deltitle: "Ausgewählte Zeile löschen",
searchtext: " ",
searchtitle: "Datensatz finden",
refreshtext: "",
refreshtitle: "Tabelle neu laden",
alertcap: "Warnung",
alerttext: "Bitte Zeile auswählen"
};
// setcolumns module
$.jgrid.col ={
caption: "Spalten anzeigen/verbergen",
bSubmit: "Speichern",
bCancel: "Abbrechen"
};
$.jgrid.errors = {
errcap : "Fehler",
nourl : "Keine URL angegeben",
norecords: "Keine Datensätze zum verarbeiten"
};
})(jQuery);
|
'use strict';
exports.BattleMovedex = {
acupressure: {
inherit: true,
desc: "Raises a random stat by 2 stages as long as the stat is not already at stage 6. The user can choose to use this move on itself or an ally. Fails if no stat stage can be raised or if the user or ally has a substitute.",
flags: {snatch: 1},
onHit: function (target) {
if (target.volatiles['substitute']) {
return false;
}
let stats = [];
for (let stat in target.boosts) {
if (target.boosts[stat] < 6) {
stats.push(stat);
}
}
if (stats.length) {
let randomStat = stats[this.random(stats.length)];
let boost = {};
boost[randomStat] = 2;
this.boost(boost);
} else {
return false;
}
},
},
aromatherapy: {
inherit: true,
onHit: function (target, source) {
this.add('-cureteam', source, '[from] move: Aromatherapy');
source.side.pokemon.forEach(pokemon => pokemon.clearStatus());
},
},
assist: {
inherit: true,
desc: "A random move among those known by the user's party members is selected for use. Does not select Assist, Chatter, Copycat, Counter, Covet, Destiny Bond, Detect, Endure, Feint, Focus Punch, Follow Me, Helping Hand, Me First, Metronome, Mimic, Mirror Coat, Mirror Move, Protect, Sketch, Sleep Talk, Snatch, Struggle, Switcheroo, Thief or Trick.",
onHit: function (target) {
let moves = [];
for (let j = 0; j < target.side.pokemon.length; j++) {
let pokemon = target.side.pokemon[j];
if (pokemon === target) continue;
for (let i = 0; i < pokemon.moves.length; i++) {
let move = pokemon.moves[i];
let noAssist = {
assist:1, chatter:1, copycat:1, counter:1, covet:1, destinybond:1, detect:1, endure:1, feint:1, focuspunch:1, followme:1, helpinghand:1, mefirst:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, protect:1, sketch:1, sleeptalk:1, snatch:1, struggle:1, switcheroo:1, thief:1, trick:1,
};
if (move && !noAssist[move]) {
moves.push(move);
}
}
}
let randomMove = '';
if (moves.length) randomMove = moves[this.random(moves.length)];
if (!randomMove) {
return false;
}
this.useMove(randomMove, target);
},
},
aquaring: {
inherit: true,
flags: {},
},
beatup: {
inherit: true,
basePower: 10,
basePowerCallback: function (pokemon, target) {
pokemon.addVolatile('beatup');
if (!pokemon.side.pokemon[pokemon.volatiles.beatup.index]) return null;
return 10;
},
desc: "Deals typeless damage. Hits one time for the user and one time for each unfainted Pokemon without a major status condition in the user's party. For each hit, the damage formula uses the participating Pokemon's base Attack as the Attack stat, the target's base Defense as the Defense stat, and ignores stat stages and other effects that modify Attack or Defense; each hit is considered to come from the user.",
onModifyMove: function (move, pokemon) {
move.type = '???';
move.category = 'Physical';
},
effect: {
duration: 1,
onStart: function (pokemon) {
let index = 0;
let team = pokemon.side.pokemon;
while (!team[index] || team[index].fainted || team[index].status) {
index++;
if (index >= team.length) break;
}
this.effectData.index = index;
},
onRestart: function (pokemon) {
let index = this.effectData.index;
let team = pokemon.side.pokemon;
do {
index++;
if (index >= team.length) break;
} while (!team[index] || team[index].fainted || team[index].status);
this.effectData.index = index;
},
onModifyAtkPriority: -101,
onModifyAtk: function (atk, pokemon) {
this.add('-activate', pokemon, 'move: Beat Up', '[of] ' + pokemon.side.pokemon[this.effectData.index].name);
this.event.modifier = 1;
return pokemon.side.pokemon[this.effectData.index].template.baseStats.atk;
},
onFoeModifyDefPriority: -101,
onFoeModifyDef: function (def, pokemon) {
this.event.modifier = 1;
return pokemon.template.baseStats.def;
},
},
},
bide: {
inherit: true,
effect: {
duration: 3,
onLockMove: 'bide',
onStart: function (pokemon) {
this.effectData.totalDamage = 0;
this.add('-start', pokemon, 'move: Bide');
},
onDamagePriority: -101,
onDamage: function (damage, target, source, move) {
if (!move || move.effectType !== 'Move' || !source) return;
this.effectData.totalDamage += damage;
this.effectData.lastDamageSource = source;
},
onAfterSetStatus: function (status, pokemon) {
if (status.id === 'slp' || status.id === 'frz') {
pokemon.removeVolatile('bide');
}
},
onBeforeMove: function (pokemon, target, move) {
if (this.effectData.duration === 1) {
this.add('-end', pokemon, 'move: Bide');
if (!this.effectData.totalDamage) {
this.add('-fail', pokemon);
return false;
}
target = this.effectData.lastDamageSource;
if (!target) {
this.add('-fail', pokemon);
return false;
}
if (!target.isActive) target = this.resolveTarget(pokemon, this.getMove('pound'));
if (!this.isAdjacent(pokemon, target)) {
this.add('-miss', pokemon, target);
return false;
}
let moveData = {
id: 'bide',
name: "Bide",
accuracy: true,
damage: this.effectData.totalDamage * 2,
category: "Physical",
priority: 1,
flags: {contact: 1, protect: 1},
ignoreImmunity: true,
effectType: 'Move',
type: 'Normal',
};
this.tryMoveHit(target, pokemon, moveData);
return false;
}
this.add('-activate', pokemon, 'move: Bide');
},
onMoveAborted: function (pokemon) {
pokemon.removeVolatile('bide');
},
onEnd: function (pokemon) {
this.add('-end', pokemon, 'move: Bide', '[silent]');
},
},
},
bind: {
inherit: true,
accuracy: 75,
},
bonerush: {
inherit: true,
accuracy: 80,
},
bravebird: {
inherit: true,
recoil: [1, 3],
},
brickbreak: {
inherit: true,
desc: "Whether or not this attack misses or the target is immune, the effects of Reflect and Light Screen end for the target's side of the field before damage is calculated.",
shortDesc: "Destroys screens, even if the target is immune.",
onTryHit: function (pokemon) {
pokemon.side.removeSideCondition('reflect');
pokemon.side.removeSideCondition('lightscreen');
},
},
bulletseed: {
inherit: true,
basePower: 10,
},
chatter: {
inherit: true,
desc: "Has an X% chance to confuse the target, where X is 0 unless the user is a Chatot that hasn't Transformed. If the user is a Chatot, X is 1, 11, or 31 depending on the volume of Chatot's recorded cry, if any; 1 for no recording or low volume, 11 for medium volume, and 31 for high volume.",
shortDesc: "For Chatot, 31% chance to confuse the target.",
secondary: {
chance: 31,
volatileStatus: 'confusion',
},
},
clamp: {
inherit: true,
accuracy: 75,
pp: 10,
},
conversion: {
inherit: true,
flags: {},
},
copycat: {
inherit: true,
onHit: function (pokemon) {
let noCopycat = {assist:1, chatter:1, copycat:1, counter:1, covet:1, destinybond:1, detect:1, endure:1, feint:1, focuspunch:1, followme:1, helpinghand:1, mefirst:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, protect:1, sketch:1, sleeptalk:1, snatch:1, struggle:1, switcheroo:1, thief:1, trick:1};
if (!this.lastMove || noCopycat[this.lastMove]) {
return false;
}
this.useMove(this.lastMove, pokemon);
},
},
cottonspore: {
inherit: true,
accuracy: 85,
},
covet: {
inherit: true,
basePower: 40,
},
crabhammer: {
inherit: true,
accuracy: 85,
},
crushgrip: {
inherit: true,
basePowerCallback: function (pokemon, target) {
return Math.floor(target.hp * 120 / target.maxhp) + 1;
},
},
curse: {
inherit: true,
desc: "If the user is not a Ghost type, lowers the user's Speed by 1 stage and raises the user's Attack and Defense by 1 stage. If the user is a Ghost type, the user loses 1/2 of its maximum HP, rounded down and even if it would cause fainting, in exchange for the target losing 1/4 of its maximum HP, rounded down, at the end of each turn while it is active. If the target uses Baton Pass, the replacement will continue to be affected. Fails if there is no target or if the target is already affected or has a substitute.",
flags: {},
onModifyMove: function (move, source, target) {
if (!source.hasType('Ghost')) {
delete move.volatileStatus;
delete move.onHit;
move.self = {boosts: {atk:1, def:1, spe:-1}};
move.target = move.nonGhostTarget;
} else if (target.volatiles['substitute']) {
delete move.volatileStatus;
delete move.onHit;
}
},
type: "???",
},
defog: {
inherit: true,
flags: {protect: 1, mirror: 1, authentic: 1},
},
detect: {
inherit: true,
priority: 3,
effect: {
duration: 1,
onStart: function (target) {
this.add('-singleturn', target, 'Protect');
},
onTryHitPriority: 3,
onTryHit: function (target, source, move) {
if (!move.flags['protect']) return;
this.add('-activate', target, 'Protect');
let lockedmove = source.getVolatile('lockedmove');
if (lockedmove) {
// Outrage counter is NOT reset
if (source.volatiles['lockedmove'].trueDuration >= 2) {
source.volatiles['lockedmove'].duration = 2;
}
}
return null;
},
},
},
disable: {
inherit: true,
accuracy: 80,
desc: "For 4 to 7 turns, the target's last move used becomes disabled. Fails if one of the target's moves is already disabled, if the target has not made a move, or if the target no longer knows the move.",
flags: {protect: 1, mirror: 1, authentic: 1},
volatileStatus: 'disable',
effect: {
durationCallback: function () {
return this.random(4, 8);
},
noCopy: true,
onStart: function (pokemon) {
if (!this.willMove(pokemon)) {
this.effectData.duration++;
}
if (!pokemon.lastMove) {
return false;
}
let moves = pokemon.moveset;
for (let i = 0; i < moves.length; i++) {
if (moves[i].id === pokemon.lastMove) {
if (!moves[i].pp) {
return false;
} else {
this.add('-start', pokemon, 'Disable', moves[i].move);
this.effectData.move = pokemon.lastMove;
return;
}
}
}
return false;
},
onEnd: function (pokemon) {
this.add('-end', pokemon, 'move: Disable');
},
onBeforeMovePriority: 7,
onBeforeMove: function (attacker, defender, move) {
if (move.id === this.effectData.move) {
this.add('cant', attacker, 'Disable', move);
return false;
}
},
onDisableMove: function (pokemon) {
let moves = pokemon.moveset;
for (let i = 0; i < moves.length; i++) {
if (moves[i].id === this.effectData.move) {
pokemon.disableMove(moves[i].id);
}
}
},
},
},
doomdesire: {
inherit: true,
accuracy: 85,
basePower: 120,
desc: "Deals typeless damage that cannot be a critical hit two turns after this move is used. Damage is calculated against the target on use, and at the end of the final turn that damage is dealt to the Pokemon at the position the original target had at the time. Fails if this move or Future Sight is already in effect for the target's position.",
onTry: function (source, target) {
target.side.addSideCondition('futuremove');
if (target.side.sideConditions['futuremove'].positions[target.position]) {
return false;
}
let damage = this.getDamage(source, target, {
name: "Doom Desire",
basePower: 120,
category: "Special",
flags: {},
willCrit: false,
type: '???',
}, true);
target.side.sideConditions['futuremove'].positions[target.position] = {
duration: 3,
move: 'doomdesire',
source: source,
moveData: {
id: 'doomdesire',
name: "Doom Desire",
accuracy: 85,
basePower: 0,
damage: damage,
category: "Special",
flags: {},
effectType: 'Move',
isFutureMove: true,
type: '???',
},
};
this.add('-start', source, 'Doom Desire');
return null;
},
},
doubleedge: {
inherit: true,
recoil: [1, 3],
},
drainpunch: {
inherit: true,
basePower: 60,
pp: 5,
},
dreameater: {
inherit: true,
desc: "The target is unaffected by this move unless it is asleep and does not have a substitute. The user recovers 1/2 the HP lost by the target, rounded down, but not less than 1 HP. If Big Root is held by the user, the HP recovered is 1.3x normal, rounded down.",
onTryHit: function (target) {
if (target.status !== 'slp' || target.volatiles['substitute']) {
this.add('-immune', target, '[msg]');
return null;
}
},
},
embargo: {
inherit: true,
flags: {protect: 1, mirror: 1},
onTryHit: function (pokemon) {
if (pokemon.ability === 'multitype' || pokemon.item === 'griseousorb') {
return false;
}
},
},
encore: {
inherit: true,
desc: "For 4 to 8 turns, the target is forced to repeat its last move used. If the affected move runs out of PP, the effect ends. Fails if the target is already under this effect, if it has not made a move, if the move has 0 PP, or if the move is Encore, Mimic, Mirror Move, Sketch, Struggle, or Transform.",
shortDesc: "The target repeats its last move for 4-8 turns.",
flags: {protect: 1, mirror: 1, authentic: 1},
volatileStatus: 'encore',
effect: {
durationCallback: function () {
return this.random(4, 9);
},
onStart: function (target) {
let noEncore = {encore:1, mimic:1, mirrormove:1, sketch:1, struggle:1, transform:1};
let moveIndex = target.moves.indexOf(target.lastMove);
if (!target.lastMove || noEncore[target.lastMove] || (target.moveset[moveIndex] && target.moveset[moveIndex].pp <= 0)) {
// it failed
this.add('-fail', target);
delete target.volatiles['encore'];
return;
}
this.effectData.move = target.lastMove;
this.add('-start', target, 'Encore');
if (!this.willMove(target)) {
this.effectData.duration++;
}
},
onOverrideDecision: function (pokemon) {
return this.effectData.move;
},
onResidualOrder: 13,
onResidual: function (target) {
if (target.moves.indexOf(target.lastMove) >= 0 && target.moveset[target.moves.indexOf(target.lastMove)].pp <= 0) {
// early termination if you run out of PP
delete target.volatiles.encore;
this.add('-end', target, 'Encore');
}
},
onEnd: function (target) {
this.add('-end', target, 'Encore');
},
onDisableMove: function (pokemon) {
if (!this.effectData.move || !pokemon.hasMove(this.effectData.move)) {
return;
}
for (let i = 0; i < pokemon.moveset.length; i++) {
if (pokemon.moveset[i].id !== this.effectData.move) {
pokemon.disableMove(pokemon.moveset[i].id);
}
}
},
},
},
endeavor: {
inherit: true,
onTry: function (pokemon, target) {
if (pokemon.hp >= target.hp) {
this.add('-fail', pokemon);
return null;
}
},
},
explosion: {
inherit: true,
basePower: 500,
},
extremespeed: {
inherit: true,
shortDesc: "Usually goes first.",
priority: 1,
},
fakeout: {
inherit: true,
priority: 1,
},
feint: {
inherit: true,
basePower: 50,
desc: "Fails unless the target is using Detect or Protect. If this move is successful, it breaks through the target's Detect or Protect for this turn, allowing other Pokemon to attack the target normally.",
shortDesc: "Breaks protection. Fails if target is not protecting.",
onTry: function (source, target) {
if (!target.volatiles['protect']) {
this.add('-fail', source);
return null;
}
},
},
firespin: {
inherit: true,
accuracy: 70,
basePower: 15,
},
flail: {
inherit: true,
basePowerCallback: function (pokemon, target) {
let ratio = pokemon.hp * 64 / pokemon.maxhp;
if (ratio < 2) {
return 200;
}
if (ratio < 6) {
return 150;
}
if (ratio < 13) {
return 100;
}
if (ratio < 22) {
return 80;
}
if (ratio < 43) {
return 40;
}
return 20;
},
},
flareblitz: {
inherit: true,
recoil: [1, 3],
},
focuspunch: {
inherit: true,
beforeMoveCallback: function () { },
onTry: function (pokemon) {
if (pokemon.volatiles['focuspunch'] && pokemon.volatiles['focuspunch'].lostFocus) {
this.attrLastMove('[still]');
this.add('cant', pokemon, 'Focus Punch', 'Focus Punch');
return false;
}
},
},
foresight: {
inherit: true,
flags: {protect: 1, mirror: 1, authentic: 1},
},
furycutter: {
inherit: true,
basePower: 10,
},
futuresight: {
inherit: true,
accuracy: 90,
basePower: 80,
desc: "Deals typeless damage that cannot be a critical hit two turns after this move is used. Damage is calculated against the target on use, and at the end of the final turn that damage is dealt to the Pokemon at the position the original target had at the time. Fails if this move or Doom Desire is already in effect for the target's position.",
pp: 15,
onTry: function (source, target) {
target.side.addSideCondition('futuremove');
if (target.side.sideConditions['futuremove'].positions[target.position]) {
return false;
}
let damage = this.getDamage(source, target, {
name: "Future Sight",
basePower: 80,
category: "Special",
flags: {},
willCrit: false,
type: '???',
}, true);
target.side.sideConditions['futuremove'].positions[target.position] = {
duration: 3,
move: 'futuresight',
source: source,
moveData: {
id: 'futuresight',
name: "Future Sight",
accuracy: 90,
basePower: 0,
damage: damage,
category: "Special",
flags: {},
effectType: 'Move',
isFutureMove: true,
type: '???',
},
};
this.add('-start', source, 'Future Sight');
return null;
},
},
gigadrain: {
inherit: true,
basePower: 60,
},
glare: {
inherit: true,
accuracy: 75,
},
growth: {
inherit: true,
desc: "Raises the user's Special Attack by 1 stage.",
shortDesc: "Raises the user's Sp. Atk by 1.",
onModifyMove: function () { },
boosts: {
spa: 1,
},
},
healbell: {
inherit: true,
onHit: function (target, source) {
this.add('-activate', source, 'move: Heal Bell');
source.side.pokemon.forEach(pokemon => {
if (!pokemon.hasAbility('soundproof')) pokemon.cureStatus(true);
});
},
},
healblock: {
inherit: true,
desc: "For 5 turns, the target is prevented from restoring any HP as long as it remains active. During the effect, healing moves are unusable, move effects that grant healing will not heal, but Abilities and items will continue to heal the user. If an affected Pokemon uses Baton Pass, the replacement will remain under the effect. Pain Split is unaffected.",
flags: {protect: 1, mirror: 1},
effect: {
duration: 5,
durationCallback: function (target, source, effect) {
if (source && source.hasAbility('persistent')) {
return 7;
}
return 5;
},
onStart: function (pokemon) {
this.add('-start', pokemon, 'move: Heal Block');
},
onDisableMove: function (pokemon) {
for (let i = 0; i < pokemon.moveset.length; i++) {
if (this.getMove(pokemon.moveset[i].id).flags['heal']) {
pokemon.disableMove(pokemon.moveset[i].id);
}
}
},
onBeforeMovePriority: 6,
onBeforeMove: function (pokemon, target, move) {
if (move.flags['heal']) {
this.add('cant', pokemon, 'move: Heal Block', move);
return false;
}
},
onResidualOrder: 17,
onEnd: function (pokemon) {
this.add('-end', pokemon, 'move: Heal Block');
},
onTryHeal: function (damage, pokemon, source, effect) {
if (effect && (effect.id === 'drain' || effect.id === 'leechseed' || effect.id === 'wish')) {
return false;
}
},
},
},
healingwish: {
inherit: true,
flags: {heal: 1},
onAfterMove: function (pokemon) {
pokemon.switchFlag = true;
},
effect: {
duration: 1,
onStart: function (side) {
this.debug('Healing Wish started on ' + side.name);
},
onSwitchInPriority: -1,
onSwitchIn: function (target) {
if (target.position !== this.effectData.sourcePosition) {
return;
}
if (target.hp > 0) {
target.heal(target.maxhp);
target.setStatus('');
this.add('-heal', target, target.getHealth, '[from] move: Healing Wish');
target.side.removeSideCondition('healingwish');
} else {
target.switchFlag = true;
}
},
},
},
highjumpkick: {
inherit: true,
basePower: 100,
desc: "If this attack is not successful, the user loses HP equal to half the target's maximum HP, rounded down, if the target is immune, or half of the damage the target would have taken, rounded down, but no less than 1 HP and no more than half of the target's maximum HP, as crash damage. Pokemon with the Ability Magic Guard are unaffected by crash damage.",
shortDesc: "If miss, user takes 1/2 damage it would've dealt.",
pp: 20,
onMoveFail: function (target, source, move) {
move.causedCrashDamage = true;
let damage = this.getDamage(source, target, move, true);
if (!damage) damage = target.maxhp;
this.damage(this.clampIntRange(damage / 2, 1, Math.floor(target.maxhp / 2)), source, source, 'highjumpkick');
},
},
iciclespear: {
inherit: true,
basePower: 10,
},
imprison: {
inherit: true,
desc: "The user prevents all of its foes from using any moves that the user also knows as long as the user remains active. Fails if no opponents know any of the user's moves.",
flags: {authentic: 1},
onTryHit: function (pokemon) {
let targets = pokemon.side.foe.active;
for (let i = 0; i < targets.length; i++) {
if (!targets[i] || targets[i].fainted) continue;
for (let j = 0; j < pokemon.moves.length; j++) {
if (targets[i].moves.indexOf(pokemon.moves[j]) >= 0) return;
}
}
return false;
},
},
jumpkick: {
inherit: true,
basePower: 85,
desc: "If this attack is not successful, the user loses HP equal to half the target's maximum HP, rounded down, if the target is immune, or half of the damage the target would have taken, rounded down, but no less than 1 HP and no more than half of the target's maximum HP, as crash damage. Pokemon with the Ability Magic Guard are unaffected by crash damage.",
shortDesc: "If miss, user takes 1/2 damage it would've dealt.",
pp: 25,
onMoveFail: function (target, source, move) {
move.causedCrashDamage = true;
let damage = this.getDamage(source, target, move, true);
if (!damage) damage = target.maxhp;
this.damage(this.clampIntRange(damage / 2, 1, Math.floor(target.maxhp / 2)), source, source, 'jumpkick');
},
},
lastresort: {
inherit: true,
basePower: 130,
},
lightscreen: {
inherit: true,
effect: {
duration: 5,
durationCallback: function (target, source, effect) {
if (source && source.hasItem('lightclay')) {
return 8;
}
return 5;
},
onAnyModifyDamagePhase1: function (damage, source, target, move) {
if (target !== source && target.side === this.effectData.target && this.getCategory(move) === 'Special') {
if (!move.crit && !move.infiltrates) {
this.debug('Light Screen weaken');
if (target.side.active.length > 1) return this.chainModify([0xAAC, 0x1000]);
return this.chainModify(0.5);
}
}
},
onStart: function (side) {
this.add('-sidestart', side, 'Light Screen');
},
onResidualOrder: 21,
onEnd: function (side) {
this.add('-sideend', side, 'Light Screen');
},
},
},
luckychant: {
inherit: true,
flags: {},
},
lunardance: {
inherit: true,
flags: {heal: 1},
onAfterMove: function (pokemon) {
pokemon.switchFlag = true;
},
effect: {
duration: 1,
onStart: function (side) {
this.debug('Lunar Dance started on ' + side.name);
},
onSwitchInPriority: -1,
onSwitchIn: function (target) {
if (target.position !== this.effectData.sourcePosition) {
return;
}
if (target.hp > 0) {
target.heal(target.maxhp);
target.setStatus('');
for (let m in target.moveset) {
target.moveset[m].pp = target.moveset[m].maxpp;
}
this.add('-heal', target, target.getHealth, '[from] move: Lunar Dance');
target.side.removeSideCondition('lunardance');
} else {
target.switchFlag = true;
}
},
},
},
magiccoat: {
inherit: true,
desc: "The user is unaffected by certain non-damaging moves directed at it and will instead use such moves against the original user. Once a move is reflected, this effect ends. Moves reflected in this way are unable to be reflected again by another Pokemon under this effect. If the user has the Ability Soundproof, this move's effect happens before a sound-based move can be nullified. The Abilities Lightning Rod and Storm Drain redirect their respective moves before this move takes effect.",
effect: {
duration: 1,
onTryHitPriority: 2,
onTryHit: function (target, source, move) {
if (target === source || move.hasBounced || !move.flags['reflectable']) {
return;
}
target.removeVolatile('magiccoat');
let newMove = this.getMoveCopy(move.id);
newMove.hasBounced = true;
this.useMove(newMove, target, source);
return null;
},
},
},
magmastorm: {
inherit: true,
accuracy: 70,
},
magnetrise: {
inherit: true,
flags: {gravity: 1},
volatileStatus: 'magnetrise',
effect: {
duration: 5,
onStart: function (target) {
if (target.volatiles['ingrain'] || target.ability === 'levitate') return false;
this.add('-start', target, 'Magnet Rise');
},
onImmunity: function (type) {
if (type === 'Ground') return false;
},
onResidualOrder: 6,
onResidualSubOrder: 9,
onEnd: function (target) {
this.add('-end', target, 'Magnet Rise');
},
},
},
mefirst: {
inherit: true,
effect: {
duration: 1,
onModifyDamagePhase2: function (damage) {
return damage * 1.5;
},
},
},
metronome: {
inherit: true,
onHit: function (target) {
let moves = [];
for (let i in exports.BattleMovedex) {
let move = exports.BattleMovedex[i];
if (i !== move.id) continue;
if (move.isNonstandard) continue;
let noMetronome = {
assist:1, chatter:1, copycat:1, counter:1, covet:1, destinybond:1, detect:1, endure:1, feint:1, focuspunch:1, followme:1, helpinghand:1, mefirst:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, protect:1, sketch:1, sleeptalk:1, snatch:1, struggle:1, switcheroo:1, thief:1, trick:1,
};
if (!noMetronome[move.id] && move.num < 468) {
moves.push(move.id);
}
}
let randomMove = '';
if (moves.length) randomMove = moves[this.random(moves.length)];
if (!randomMove) return false;
this.useMove(randomMove, target);
},
},
mimic: {
inherit: true,
onHit: function (target, source) {
let disallowedMoves = {chatter:1, metronome:1, mimic:1, sketch:1, struggle:1, transform:1};
if (source.transformed || !target.lastMove || disallowedMoves[target.lastMove] || source.moves.indexOf(target.lastMove) !== -1 || target.volatiles['substitute']) return false;
let moveslot = source.moves.indexOf('mimic');
if (moveslot < 0) return false;
let move = Dex.getMove(target.lastMove);
source.moveset[moveslot] = {
move: move.name,
id: move.id,
pp: 5,
maxpp: move.pp * 8 / 5,
disabled: false,
used: false,
virtual: true,
};
source.moves[moveslot] = toId(move.name);
this.add('-activate', source, 'move: Mimic', move.name);
},
},
minimize: {
inherit: true,
desc: "Raises the user's evasiveness by 1 stage. Whether or not the user's evasiveness was changed, Stomp will have its power doubled if used against the user while it is active.",
shortDesc: "Raises the user's evasiveness by 1.",
boosts: {
evasion: 1,
},
},
miracleeye: {
inherit: true,
flags: {protect: 1, mirror: 1, authentic: 1},
},
mirrormove: {
inherit: true,
onTryHit: function () { },
onHit: function (pokemon) {
let noMirror = {acupressure:1, aromatherapy:1, assist:1, chatter:1, copycat:1, counter:1, curse:1, doomdesire:1, feint:1, focuspunch:1, futuresight:1, gravity:1, hail:1, haze:1, healbell:1, helpinghand:1, lightscreen:1, luckychant:1, magiccoat:1, mefirst:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, mist:1, mudsport:1, naturepower:1, perishsong:1, psychup:1, raindance:1, reflect:1, roleplay:1, safeguard:1, sandstorm:1, sketch:1, sleeptalk:1, snatch:1, spikes:1, spitup:1, stealthrock:1, struggle:1, sunnyday:1, tailwind:1, toxicspikes:1, transform:1, watersport:1};
if (!pokemon.lastAttackedBy || !pokemon.lastAttackedBy.pokemon.lastMove || noMirror[pokemon.lastAttackedBy.move] || !pokemon.lastAttackedBy.pokemon.hasMove(pokemon.lastAttackedBy.move)) {
return false;
}
this.useMove(pokemon.lastAttackedBy.move, pokemon);
},
target: "self",
},
moonlight: {
inherit: true,
onHit: function (pokemon) {
if (this.isWeather(['sunnyday', 'desolateland'])) {
this.heal(pokemon.maxhp * 2 / 3);
} else if (this.isWeather(['raindance', 'primordialsea', 'sandstorm', 'hail'])) {
this.heal(pokemon.maxhp / 4);
} else {
this.heal(pokemon.maxhp / 2);
}
},
},
morningsun: {
inherit: true,
onHit: function (pokemon) {
if (this.isWeather(['sunnyday', 'desolateland'])) {
this.heal(pokemon.maxhp * 2 / 3);
} else if (this.isWeather(['raindance', 'primordialsea', 'sandstorm', 'hail'])) {
this.heal(pokemon.maxhp / 4);
} else {
this.heal(pokemon.maxhp / 2);
}
},
},
odorsleuth: {
inherit: true,
flags: {protect: 1, mirror: 1, authentic: 1},
},
outrage: {
inherit: true,
pp: 15,
onAfterMove: function () {},
},
payback: {
inherit: true,
basePowerCallback: function (pokemon, target) {
if (this.willMove(target)) {
return 50;
}
return 100;
},
desc: "Power doubles if the target moves before the user; power is also doubled if the target switches out.",
},
petaldance: {
inherit: true,
basePower: 90,
pp: 20,
onAfterMove: function () {},
},
poisongas: {
inherit: true,
accuracy: 55,
target: "normal",
},
powertrick: {
inherit: true,
flags: {},
},
protect: {
inherit: true,
priority: 3,
effect: {
duration: 1,
onStart: function (target) {
this.add('-singleturn', target, 'Protect');
},
onTryHitPriority: 3,
onTryHit: function (target, source, move) {
if (!move.flags['protect']) return;
this.add('-activate', target, 'Protect');
let lockedmove = source.getVolatile('lockedmove');
if (lockedmove) {
// Outrage counter is NOT reset
if (source.volatiles['lockedmove'].trueDuration >= 2) {
source.volatiles['lockedmove'].duration = 2;
}
}
return null;
},
},
},
psychup: {
inherit: true,
flags: {snatch:1, authentic: 1},
},
recycle: {
inherit: true,
flags: {},
},
reflect: {
inherit: true,
effect: {
duration: 5,
durationCallback: function (target, source, effect) {
if (source && source.hasItem('lightclay')) {
return 8;
}
return 5;
},
onAnyModifyDamagePhase1: function (damage, source, target, move) {
if (target !== source && target.side === this.effectData.target && this.getCategory(move) === 'Physical') {
if (!move.crit && !move.infiltrates) {
this.debug('Reflect weaken');
if (target.side.active.length > 1) return this.chainModify([0xAAC, 0x1000]);
return this.chainModify(0.5);
}
}
},
onStart: function (side) {
this.add('-sidestart', side, 'Reflect');
},
onResidualOrder: 21,
onEnd: function (side) {
this.add('-sideend', side, 'Reflect');
},
},
},
reversal: {
inherit: true,
basePowerCallback: function (pokemon, target) {
let ratio = pokemon.hp * 64 / pokemon.maxhp;
if (ratio < 2) {
return 200;
}
if (ratio < 6) {
return 150;
}
if (ratio < 13) {
return 100;
}
if (ratio < 22) {
return 80;
}
if (ratio < 43) {
return 40;
}
return 20;
},
},
roar: {
inherit: true,
flags: {protect: 1, mirror: 1, sound: 1, authentic: 1},
},
rockblast: {
inherit: true,
accuracy: 80,
},
sandtomb: {
inherit: true,
accuracy: 70,
basePower: 15,
},
scaryface: {
inherit: true,
accuracy: 90,
},
selfdestruct: {
inherit: true,
basePower: 400,
},
sketch: {
inherit: true,
onHit: function (target, source) {
let disallowedMoves = {chatter:1, sketch:1, struggle:1};
if (source.transformed || !target.lastMove || disallowedMoves[target.lastMove] || source.moves.indexOf(target.lastMove) >= 0 || target.volatiles['substitute']) return false;
let moveslot = source.moves.indexOf('sketch');
if (moveslot < 0) return false;
let move = Dex.getMove(target.lastMove);
let sketchedMove = {
move: move.name,
id: move.id,
pp: move.pp,
maxpp: move.pp,
disabled: false,
used: false,
};
source.moveset[moveslot] = sketchedMove;
source.baseMoveset[moveslot] = sketchedMove;
source.moves[moveslot] = toId(move.name);
this.add('-activate', source, 'move: Mimic', move.name);
},
},
skillswap: {
inherit: true,
onHit: function (target, source) {
let targetAbility = target.ability;
let sourceAbility = source.ability;
if (targetAbility === sourceAbility) {
return false;
}
this.add('-activate', source, 'move: Skill Swap');
source.setAbility(targetAbility);
target.setAbility(sourceAbility);
},
},
sleeptalk: {
inherit: true,
beforeMoveCallback: function (pokemon) {
if (pokemon.volatiles['choicelock'] || pokemon.volatiles['encore']) {
this.addMove('move', pokemon, 'Sleep Talk');
this.add('-fail', pokemon);
return true;
}
},
},
spikes: {
inherit: true,
flags: {},
},
spite: {
inherit: true,
flags: {protect: 1, mirror: 1, authentic: 1},
},
stealthrock: {
inherit: true,
flags: {},
},
struggle: {
inherit: true,
onModifyMove: function (move) {
move.type = '???';
},
},
suckerpunch: {
inherit: true,
desc: "Fails if the target did not select a physical or special attack for use this turn, or if the target moves before the user.",
onTry: function (source, target) {
let decision = this.willMove(target);
if (!decision || decision.choice !== 'move' || decision.move.category === 'Status' || target.volatiles.mustrecharge) {
this.add('-fail', source);
return null;
}
},
},
synthesis: {
inherit: true,
onHit: function (pokemon) {
if (this.isWeather(['sunnyday', 'desolateland'])) {
this.heal(pokemon.maxhp * 2 / 3);
} else if (this.isWeather(['raindance', 'primordialsea', 'sandstorm', 'hail'])) {
this.heal(pokemon.maxhp / 4);
} else {
this.heal(pokemon.maxhp / 2);
}
},
},
tackle: {
inherit: true,
accuracy: 95,
basePower: 35,
},
tailglow: {
inherit: true,
desc: "Raises the user's Special Attack by 2 stages.",
shortDesc: "Raises the user's Sp. Atk by 2.",
boosts: {
spa: 2,
},
},
tailwind: {
inherit: true,
desc: "For 3 turns, the user and its party members have their Speed doubled. Fails if this move is already in effect for the user's side.",
shortDesc: "For 3 turns, allies' Speed is doubled.",
effect: {
duration: 3,
durationCallback: function (target, source, effect) {
if (source && source.ability === 'persistent') {
return 5;
}
return 3;
},
onStart: function (side) {
this.add('-sidestart', side, 'move: Tailwind');
},
onModifySpe: function (spe) {
return spe * 2;
},
onResidualOrder: 21,
onResidualSubOrder: 4,
onEnd: function (side) {
this.add('-sideend', side, 'move: Tailwind');
},
},
},
taunt: {
inherit: true,
desc: "For 3 to 5 turns, prevents the target from using non-damaging moves.",
shortDesc: "For 3-5 turns, the target can't use status moves.",
flags: {protect: 1, mirror: 1, authentic: 1},
effect: {
durationCallback: function () {
return this.random(3, 6);
},
onStart: function (target) {
this.add('-start', target, 'move: Taunt');
},
onResidualOrder: 12,
onEnd: function (target) {
this.add('-end', target, 'move: Taunt');
},
onDisableMove: function (pokemon) {
let moves = pokemon.moveset;
for (let i = 0; i < moves.length; i++) {
if (this.getMove(moves[i].move).category === 'Status') {
pokemon.disableMove(moves[i].id);
}
}
},
onBeforeMovePriority: 5,
onBeforeMove: function (attacker, defender, move) {
if (move.category === 'Status') {
this.add('cant', attacker, 'move: Taunt', move);
return false;
}
},
},
},
thrash: {
inherit: true,
basePower: 90,
pp: 20,
onAfterMove: function () {},
},
torment: {
inherit: true,
flags: {protect: 1, mirror: 1, authentic: 1},
},
toxic: {
inherit: true,
accuracy: 85,
},
toxicspikes: {
inherit: true,
desc: "Sets up a hazard on the foe's side of the field, poisoning each foe that switches in, unless it is a Flying-type Pokemon or has the Ability Levitate. Can be used up to two times before failing. Foes become poisoned with one layer and badly poisoned with two layers. Can be removed from the foe's side if any foe uses Rapid Spin, is hit by Defog, or a grounded Poison-type Pokemon switches in. Safeguard prevents the foe's party from being poisoned on switch-in, as well as switching in with a substitute.",
flags: {},
effect: {
// this is a side condition
onStart: function (side) {
this.add('-sidestart', side, 'move: Toxic Spikes');
this.effectData.layers = 1;
},
onRestart: function (side) {
if (this.effectData.layers >= 2) return false;
this.add('-sidestart', side, 'move: Toxic Spikes');
this.effectData.layers++;
},
onSwitchIn: function (pokemon) {
if (!pokemon.runImmunity('Ground')) return;
if (!pokemon.runImmunity('Poison')) return;
if (pokemon.hasType('Poison')) {
this.add('-sideend', pokemon.side, 'move: Toxic Spikes', '[of] ' + pokemon);
pokemon.side.removeSideCondition('toxicspikes');
}
if (pokemon.volatiles['substitute']) {
return;
} else if (this.effectData.layers >= 2) {
pokemon.trySetStatus('tox', pokemon.side.foe.active[0]);
} else {
pokemon.trySetStatus('psn', pokemon.side.foe.active[0]);
}
},
},
},
transform: {
inherit: true,
desc: "The user transforms into the target. The target's current stats, stat stages, types, moves, Ability, weight, IVs, species, and sprite are copied. The user's level and HP remain the same and each copied move receives only 5 PP. This move fails if the target has transformed.",
flags: {authentic: 1},
},
uproar: {
inherit: true,
basePower: 50,
},
volttackle: {
inherit: true,
recoil: [1, 3],
},
whirlpool: {
inherit: true,
accuracy: 70,
basePower: 15,
},
whirlwind: {
inherit: true,
flags: {protect: 1, mirror: 1, authentic: 1},
},
wish: {
inherit: true,
desc: "At the end of the next turn, the Pokemon at the user's position has 1/2 of its maximum HP restored to it, rounded down. Fails if this move is already in effect for the user's position.",
shortDesc: "Next turn, heals 50% of the recipient's max HP.",
flags: {heal: 1},
sideCondition: 'Wish',
effect: {
duration: 2,
onResidualOrder: 0,
onEnd: function (side) {
let target = side.active[this.effectData.sourcePosition];
if (!target.fainted) {
let source = this.effectData.source;
let damage = this.heal(target.maxhp / 2, target, target);
if (damage) this.add('-heal', target, target.getHealth, '[from] move: Wish', '[wisher] ' + source.name);
}
},
},
},
woodhammer: {
inherit: true,
recoil: [1, 3],
},
worryseed: {
inherit: true,
onTryHit: function (pokemon) {
let bannedAbilities = {multitype:1, truant:1};
if (bannedAbilities[pokemon.ability]) {
return false;
}
},
},
wrap: {
inherit: true,
accuracy: 85,
},
wringout: {
inherit: true,
basePowerCallback: function (pokemon, target) {
return Math.floor(target.hp * 120 / target.maxhp) + 1;
},
},
};
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Article Schema
*/
var ArticleSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill Article name',
trim: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Article', ArticleSchema); |
/*------------------------ AJAX: PERIODICAL UPDATER ------------------------*/
fuse.ajax.TimedUpdater = (function() {
function Klass() { }
function TimedUpdater(container, url, options) {
var onDone,
callbackName = 'on' + Request.Events[4],
instance = __instance || new Klass,
options = _extend(clone(TimedUpdater.options), options);
__instance = null;
// this._super() equivalent
fuse.ajax.Base.call(instance, url, options);
options = instance.options;
// dynamically set readyState eventName to allow for easy customization
onDone = options[callbackName];
instance.container = container;
instance.frequency = options.frequency;
instance.maxDecay = options.maxDecay;
options[callbackName] = function(request, json) {
if (!request.aborted) {
instance.updateDone(request);
onDone && onDone(request, json);
}
};
instance.onStop = options.onStop;
instance.onTimerEvent = function() { instance.start(); };
instance.start();
return instance;
}
var __instance, __apply = TimedUpdater.apply, __call = TimedUpdater.call,
Request = fuse.ajax.Request,
TimedUpdater = Class(fuse.ajax.Base, { 'constructor': TimedUpdater });
TimedUpdater.call = function(thisArg) {
__instance = thisArg;
return __call.apply(this, arguments);
};
TimedUpdater.apply = function(thisArg, argArray) {
__instance = thisArg;
return __apply.call(this, thisArg, argArray);
};
Klass.prototype = TimedUpdater.plugin;
return TimedUpdater;
})();
(function(plugin) {
plugin.updateDone = function updateDone(request) {
var options = this.options, decay = options.decay,
responseText = request.responseText;
if (decay) {
this.decay = Math.min(responseText == String(this.lastText) ?
(this.decay * decay) : 1, this.maxDecay);
this.lastText = responseText;
}
this.timer = global.setTimeout(this.onTimerEvent,
this.decay * this.frequency * this.timerMultiplier);
};
plugin.start = function start() {
this.updater = new fuse.ajax.Updater(this.container, this.url, this.options);
};
plugin.stop = function stop() {
global.clearTimeout(this.timer);
this.lastText = null;
this.updater.abort();
this.onStop && this.onStop.apply(this, arguments);
};
// prevent JScript bug with named function expressions
var updateDone = nil, start = nil, stop = nil;
})(fuse.ajax.TimedUpdater.plugin);
fuse.ajax.TimedUpdater.options = {
'decay': 1,
'frequency': 2,
'maxDecay': Infinity
};
|
const fitCurve = require('../src/fit-curve');
const _ = require('lodash');
const expect = require('chai').expect;
const verifyMatch = (expectedResult, actualResult) => {
expect(actualResult).to.have.length(expectedResult.length);
expectedResult.forEach(function (expectedBezierCurve, i) {
var actualBezierCurve = actualResult[i];
_.zip(actualBezierCurve, expectedBezierCurve).forEach(function (pairs) {
expect(pairs[0][0]).to.closeTo(pairs[1][0], 1.0e-6);
expect(pairs[0][1]).to.closeTo(pairs[1][1], 1.0e-6);
});
});
};
describe("Fitten curve", () => {
it("should match example #1", () => {
const expectedResult = [
[[0, 0], [20.27317402, 20.27317402], [-1.24665147, 0], [20, 0]]
];
const actualResult = fitCurve([[0, 0], [10, 10], [10, 0], [20, 0]], 50);
verifyMatch(expectedResult, actualResult);
});
it("should match example #2", () => {
const expectedResult = [
[[0, 0], [20.27317402, 20.27317402], [-1.24665147, 0], [20, 0]]
];
const actualResult = fitCurve([[0, 0], [10, 10], [10, 0], [20, 0], [20, 0]], 50);
verifyMatch(expectedResult, actualResult);
});
it("should match example #3", () => {
const expectedResult = [
[ [ 244, 92 ],
[ 284.2727272958473, 105.42424243194908 ],
[ 287.98676736182495, 85 ],
[ 297, 85 ]
]
];
const actualResult = fitCurve([
[244,92],[247,93],[251,95],[254,96],[258,97],[261,97],[265,97],[267,97],
[270,97],[273,97],[281,97],[284,95],[286,94],[289,92],[291,90],[292,88],
[294,86],[295,85],[296,85],[297,85]], 10);
verifyMatch(expectedResult, actualResult);
});
it("should match example #3", () => {
const expectedResult = [
[[0, 0], [3.333333333333333, 3.333333333333333], [5.285954792089683, 10], [10, 10]],
[[ 10, 10], [13.333333333333334, 10 ], [7.6429773960448415, 2.3570226039551585 ], [10, 0]],
[[10, 0], [12.3570226, -2.3570226], [16.66666667, 0], [20, 0]]
];
const actualResult = fitCurve([[0, 0], [10, 10], [10, 0], [20, 0]], 1);
verifyMatch(expectedResult, actualResult);
});
it("shouldn't fail on perfect match", () => {
const expectedResult = [
[[0, 0], [6.66666666, 2.66666666], [13.33333333, 5.33333333], [20, 8]]
];
const actualResult = fitCurve([[0, 0], [10, 4], [20, 8]], 0);
verifyMatch(expectedResult, actualResult);
});
describe("when no arguments provided", () => {
it("should throw a TypeError exception", () => {
expect(() => fitCurve()).to.throw(TypeError, "First argument should be an array");
})
});
describe("when one of the points doesn't conform expected format", () => {
it("should throw an exception", () => {
expect(() => fitCurve([[1, 1], [1]])).to.throw(Error,
"Each point should be an array of numbers. Each point should have the same amount of numbers.");
});
});
describe("when only one unique point provided", () => {
it("should not throw an exception and return empty array", () => {
const result = fitCurve([[1, 1], [1, 1]]);
expect(result).to.eql([]);
})
});
});
|
// Native Javascript for Bootstrap 3
// by dnp_theme
(function(factory){
// CommonJS/RequireJS and "native" compatibility
if(typeof module !== "undefined" && typeof exports == "object") {
// A commonJS/RequireJS environment
if(typeof window != "undefined") {
// Window and document exist, so return the factory's return value.
module.exports = factory();
} else {
// Let the user give the factory a Window and Document.
module.exports = factory;
}
} else {
// Assume a traditional browser.
window.Affix = factory();
}
})(function(){
//AFFIX DEFINITION
var Affix = function(element,options) {
options = options || {};
this.element = typeof element === 'object' ? element : document.querySelector(element);
this.options = {};
this.options.target = options.target ? ((typeof(options.target) === 'object') ? options.target : document.querySelector(options.target)) : null; // target is an object
this.options.offsetTop = options.offsetTop && options.offsetTop ? ( options.offsetTop === 'function' ? options.offsetTop() : parseInt(options.offsetTop,0) ) : 0; // offset option is an integer number or function to determine that number
this.options.offsetBottom = options.offsetBottom && options.offsetBottom ? ( options.offsetBottom === 'function' ? options.offsetBottom() : parseInt(options.offsetBottom,0) ) : null;
if (this.element && (this.options.target || this.options.offsetTop || this.options.offsetBottom ) ) { this.init(); }
}
//AFFIX METHODS
Affix.prototype = {
init: function () {
this.affixed = false;
this.affixedBottom = false;
this.getPinOffsetTop = 0;
this.getPinOffsetBottom = null;
//actions
this.checkPosition();
this.updateAffix();
this.scrollEvent();
this.resizeEvent()
},
processOffsetTop: function () {
if ( this.options.target !== null ) {
return this.targetRect().top + this.scrollOffset();
} else if ( this.options.offsetTop !== null ) {
return this.options.offsetTop
}
},
processOffsetBottom: function () {
if ( this.options.offsetBottom !== null ) {
var maxScroll = this.getMaxScroll();
return maxScroll - this.elementHeight() - this.options.offsetBottom
}
},
offsetTop: function () {
return this.processOffsetTop()
},
offsetBottom: function () {
return this.processOffsetBottom()
},
checkPosition: function () {
this.getPinOffsetTop = this.offsetTop
this.getPinOffsetBottom = this.offsetBottom
},
scrollOffset: function () {
return window.pageYOffset || document.documentElement.scrollTop
},
pinTop: function () {
if ( !/affix/.test(this.element.className) ) {
this.element.className += ' affix';
this.affixed = true
}
},
unPinTop: function () {
if ( /affix/.test(this.element.className) ) {
this.element.className = this.element.className.replace(' affix','');
this.affixed = false
}
},
pinBottom: function () {
if ( !/'affix-bottom'/.test(this.element.className) ) {
this.element.className += ' affix-bottom';
this.affixedBottom = true
}
},
unPinBottom: function () {
if ( /'affix-bottom'/.test(this.element.className) ) {
this.element.className = this.element.className.replace(' affix-bottom','');
this.affixedBottom = false
}
},
updatePin: function () {
if (this.affixed === false && (parseInt(this.offsetTop(),0) - parseInt(this.scrollOffset(),0) < 0)) {
this.pinTop();
} else if (this.affixed === true && (parseInt(this.scrollOffset(),0) <= parseInt(this.getPinOffsetTop(),0) )) {
this.unPinTop()
}
if (this.affixedBottom === false && (parseInt(this.offsetBottom(),0) - parseInt(this.scrollOffset(),0) < 0)) {
this.pinBottom();
} else if (this.affixedBottom === true && (parseInt(this.scrollOffset(),0) <= parseInt(this.getPinOffsetBottom(),0) )) {
this.unPinBottom()
}
},
updateAffix : function () { // Unpin and check position again
this.unPinTop();
this.unPinBottom();
this.checkPosition()
this.updatePin() // If any case update values again
},
elementHeight : function(){
return this.element.offsetHeight
},
targetRect : function(){
return this.options.target.getBoundingClientRect()
},
getMaxScroll : function(){
return Math.max( document.body.scrollHeight, document.body.offsetHeight,
document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight )
},
scrollEvent : function(){
var self = this;
window.addEventListener('scroll', function() {
self.updatePin()
}, false);
},
resizeEvent : function(){
var self = this,
isIE = (new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null) ? parseFloat( RegExp.$1 ) : false,
dl = (isIE && isIE < 10) ? 500 : 50;
window.addEventListener('resize', function () {
setTimeout(function(){
self.updateAffix()
},dl);
}, false);
}
};
// AFFIX DATA API
// =================
var Affixes = document.querySelectorAll('[data-spy="affix"]'), i = 0, afl = Affixes.length;
for (i;i<afl;i++) {
var item = Affixes[i], options = {};
options.offsetTop = item.getAttribute('data-offset-top');
options.offsetBottom = item.getAttribute('data-offset-bottom');
options.target = item.getAttribute('data-target');
if ( item && (options.offsetTop !== null || options.offsetBottom !== null || options.target !== null) ) { //don't do anything unless we have something valid to pin
new Affix(item, options);
}
}
return Affix;
});
(function(factory){
// CommonJS/RequireJS and "native" compatibility
if(typeof module !== "undefined" && typeof exports == "object") {
// A commonJS/RequireJS environment
if(typeof window != "undefined") {
// Window and document exist, so return the factory's return value.
module.exports = factory();
} else {
// Let the user give the factory a Window and Document.
module.exports = factory;
}
} else {
// Assume a traditional browser.
window.Alert = factory();
}
})(function(root){
// ALERT DEFINITION
// ===================
var Alert = function( element ) {
this.btn = typeof element === 'object' ? element : document.querySelector(element);
this.alert = null;
this.duration = 150; // default alert transition duration
this.init();
}
// ALERT METHODS
// ================
Alert.prototype = {
init : function() {
this.actions();
document.addEventListener('click', this.close, false); //delegate to all alerts, including those inserted later into the DOM
},
actions : function() {
var self = this;
this.close = function(e) {
var target = e.target;
self.btn = target.getAttribute('data-dismiss') === 'alert' && target.className === 'close' ? target : target.parentNode;
self.alert = self.btn.parentNode;
if ( self.alert !== null && self.btn.getAttribute('data-dismiss') === 'alert' && /in/.test(self.alert.className) ) {
self.alert.className = self.alert.className.replace(' in','');
setTimeout(function() {
self.alert && self.alert.parentNode.removeChild(self.alert);
}, self.duration);
}
}
}
}
// ALERT DATA API
// =================
var Alerts = document.querySelectorAll('[data-dismiss="alert"]'), i = 0, all = Alerts.length;
for (i;i<all;i++) {
new Alert(Alerts[i]);
}
return Alert;
});
(function(factory){
// CommonJS/RequireJS and "native" compatibility
if(typeof module !== "undefined" && typeof exports == "object") {
// A commonJS/RequireJS environment
if(typeof window != "undefined") {
// Window and document exist, so return the factory's return value.
module.exports = factory();
} else {
// Let the user give the factory a Window and Document.
module.exports = factory;
}
} else {
// Assume a traditional browser.
window.Button = factory();
}
})(function(){
// BUTTON DEFINITION
// ===================
var Button = function( element, option ) {
this.btn = typeof element === 'object' ? element : document.querySelector(element);
this.option = typeof option === 'string' ? option : null;
this.init();
};
// BUTTON METHODS
// ================
Button.prototype = {
init : function() {
var self = this;
this.actions();
if ( /btn/.test(this.btn.className) ) {
if ( this.option && this.option !== 'reset' ) {
this.state = this.btn.getAttribute('data-'+this.option+'-text') || null;
!this.btn.getAttribute('data-original-text') && this.btn.setAttribute('data-original-text',self.btn.innerHTML.replace(/^\s+|\s+$/g, ''));
this.setState();
} else if ( this.option === 'reset' ) {
this.reset();
}
}
if ( /btn-group/.test(this.btn.className) ) {
this.btn.addEventListener('click', this.toggle, false);
}
},
actions : function() {
var self = this,
changeEvent = (('CustomEvent' in window) && window.dispatchEvent)
? new CustomEvent('bs.button.change') : null; // The custom event that will be triggered on demand
// assign event to a trigger function
function triggerChange(t) { if (changeEvent) { t.dispatchEvent(changeEvent); } }
this.setState = function() {
if ( this.option === 'loading' ) {
this.addClass(this.btn,'disabled');
this.btn.setAttribute('disabled','disabled');
}
this.btn.innerHTML = this.state;
},
this.reset = function() {
if ( /disabled/.test(self.btn.className) || self.btn.getAttribute('disabled') === 'disabled' ) {
this.removeClass(this.btn,'disabled');
self.btn.removeAttribute('disabled');
}
self.btn.innerHTML = self.btn.getAttribute('data-original-text');
},
this.toggle = function(e) {
var parent = e.target.parentNode,
label = e.target.tagName === 'LABEL' ? e.target : parent.tagName === 'LABEL' ? parent : null; // the .btn label
if ( !label ) return; //react if a label or its immediate child is clicked
var target = this, //e.currentTarget || e.srcElement; // the button group, the target of the handler function
labels = target.querySelectorAll('.btn'), ll = labels.length, i = 0, // all the button group buttons
input = label.getElementsByTagName('INPUT')[0];
if ( !input ) return; //return if no input found
//manage the dom manipulation
if ( input.type === 'checkbox' ) { //checkboxes
if ( !input.checked ) {
self.addClass(label,'active');
input.getAttribute('checked');
input.setAttribute('checked','checked');
input.checked = true;
} else {
self.removeClass(label,'active');
input.getAttribute('checked');
input.removeAttribute('checked');
input.checked = false;
}
triggerChange(input); //trigger the change for the input
triggerChange(self.btn); //trigger the change for the btn-group
}
if ( input.type === 'radio' ) { // radio buttons
if ( !input.checked ) { // don't trigger if already active
self.addClass(label,'active');
input.setAttribute('checked','checked');
input.checked = true;
triggerChange(self.btn);
triggerChange(input); //trigger the change
for (i;i<ll;i++) {
var l = labels[i];
if ( l !== label && /active/.test(l.className) ) {
var inp = l.getElementsByTagName('INPUT')[0];
self.removeClass(l,'active');
inp.removeAttribute('checked');
inp.checked = false;
triggerChange(inp); // trigger the change
}
}
}
}
},
this.addClass = function(el,c) { // where modern browsers fail, use classList
if (el.classList) { el.classList.add(c); } else { el.className += ' '+c; el.offsetWidth; }
},
this.removeClass = function(el,c) {
if (el.classList) { el.classList.remove(c); } else { el.className = el.className.replace(c,'').replace(/^\s+|\s+$/g,''); el.offsetWidth; }
}
}
}
// BUTTON DATA API
// =================
var Buttons = document.querySelectorAll('[data-toggle=button]'), i = 0, btl = Buttons.length;
for (i;i<btl;i++) {
new Button(Buttons[i]);
}
var ButtonGroups = document.querySelectorAll('[data-toggle=buttons]'), j = 0, bgl = ButtonGroups.length;
for (j;j<bgl;j++) {
new Button(ButtonGroups[j]);
}
return Button;
});
(function(factory){
// CommonJS/RequireJS and "native" compatibility
if(typeof module !== "undefined" && typeof exports == "object") {
// A commonJS/RequireJS environment
if(typeof window != "undefined") {
// Window and document exist, so return the factory's return value.
module.exports = factory();
} else {
// Let the user give the factory a Window and Document.
module.exports = factory;
}
} else {
// Assume a traditional browser.
window.Carousel = factory();
}
})(function(){
// CAROUSEL DEFINITION
// ===================
var Carousel = function( element, options ) {
options = options || {};
this.carousel = (typeof element === 'object') ? element : document.querySelector( element );
this.options = {}; //replace extend
this.options.keyboard = options.keyboard === 'true' ? true : false;
this.options.pause = options.pause ? options.pause : 'hover'; // false / hover
// bootstrap carousel default transition duration / option
this.duration = 600;
this.isIE = (new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null) ? parseFloat( RegExp.$1 ) : false;
this.options.duration = (this.isIE && this.isIE < 10) ? 0 : (options.duration || this.duration);
var items = this.carousel.querySelectorAll('.item'), il=items.length; //this is an object
this.controls = this.carousel.querySelectorAll('.carousel-control');
this.prev = this.controls[0];
this.next = this.controls[1];
this.slides = []; for (var i = 0; i < il; i++) { this.slides.push(items[i]); } // this is an array
this.indicator = this.carousel.querySelector( ".carousel-indicators" ); // object
this.indicators = this.carousel.querySelectorAll( ".carousel-indicators li" ); // object
this.total = this.slides.length;
this.timer = null;
this.direction = null;
this.index = 0;
if (options.interval === 'false' ) {
this.options.interval = false;
} else {
this.options.interval = parseInt(options.interval) || 5000;
}
this.init();
};
// CAROUSEL METHODS
// ================
Carousel.prototype = {
init: function() {
if ( this.options.interval !== false ){
this.cycle();
}
if ( this.options && this.options.pause === 'hover' && this.options.interval !== false ) {
this.pause();
}
this.actions();
this._addEventListeners();
},
cycle: function(e) {
var self = this;
self.direction = 'left';
self.timer = setInterval(function() {
self.index++;
if( self.index == self.slides.length ) {
self.index = 0;
}
self._slideTo( self.index, e );
}, self.options.interval);
},
pause: function() {
var self = this;
var pauseHandler = function () {
if ( self.options.interval !==false && !/paused/.test(self.carousel.className) ) {
self.carousel.className += ' paused';
clearInterval( self.timer );
self.timer = null;
}
};
var resumeHandler = function() {
if ( self.options.interval !==false && /paused/.test(self.carousel.className) ) {
self.cycle();
self.carousel.className = self.carousel.className.replace(' paused','');
}
};
self.carousel.addEventListener( "mouseenter", pauseHandler, false);
self.carousel.addEventListener( "mouseleave", resumeHandler, false);
self.carousel.addEventListener( "touchstart", pauseHandler, false);
self.carousel.addEventListener( "touchend", resumeHandler, false);
},
_slideTo: function( next, e ) {
var self = this;
var active = self._getActiveIndex(); // the current active
//determine type
var direction = self.direction;
var dr = direction === 'left' ? 'next' : 'prev';
var slid = null, slide=null;
//register events
if (('CustomEvent' in window) && window.dispatchEvent) {
slid = new CustomEvent("slid.bs.carousel");
slide = new CustomEvent("slide.bs.carousel");
}
if (slid) { self.carousel.dispatchEvent(slid); } //here we go with the slid
self._removeEventListeners();
clearInterval(self.timer);
self.timer = null;
self._curentPage( self.indicators[next] );
if ( /slide/.test(this.carousel.className) && !(this.isIE && this.isIE < 10) ) {
self.slides[next].className += (' '+dr);
self.slides[next].offsetWidth;
self.slides[next].className += (' '+direction);
self.slides[active].className += (' '+direction);
setTimeout(function() { //we're gonna fake waiting for the animation to finish, cleaner and better
self._addEventListeners();
self.slides[next].className += ' active';
self.slides[active].className = self.slides[active].className.replace(' active','');
self.slides[next].className = self.slides[next].className.replace(' '+dr,'');
self.slides[next].className = self.slides[next].className.replace(' '+direction,'');
self.slides[active].className = self.slides[active].className.replace(' '+direction,'');
if ( self.options.interval !== false && !/paused/.test(self.carousel.className) ){
clearInterval(self.timer); self.cycle();
}
if (slide) { self.carousel.dispatchEvent(slide); } //here we go with the slide
}, self.options.duration + 100 );
} else {
self.slides[next].className += ' active';
self.slides[next].offsetWidth;
self.slides[active].className = self.slides[active].className.replace(' active','');
setTimeout(function() {
self._addEventListeners();
if ( self.options.interval !== false && !/paused/.test(self.carousel.className) ){
clearInterval(self.timer); self.cycle();
}
if (slide) { self.carousel.dispatchEvent(slide); } //here we go with the slide
}, self.options.duration + 100 );
}
},
_addEventListeners : function () {
var self = this;
self.next && self.next.addEventListener( "click", self.controlsHandler, false);
self.prev && self.prev.addEventListener( "click", self.controlsHandler, false);
self.indicator && self.indicator.addEventListener( "click", self.indicatorHandler, false);
if (self.options.keyboard === true) {
window.addEventListener('keydown', self.keyHandler, false);
}
},
_removeEventListeners : function () { // prevent mouse bubbles while animating
var self = this;
self.next && self.next.removeEventListener( "click", self.controlsHandler, false);
self.prev && self.prev.removeEventListener( "click", self.controlsHandler, false);
self.indicator && self.indicator.removeEventListener( "click", self.indicatorHandler, false);
if (self.options.keyboard === true) {
window.removeEventListener('keydown', self.keyHandler, false);
}
},
_getActiveIndex : function () {
return this.slides.indexOf(this.carousel.querySelector('.item.active'))
},
_curentPage: function( p ) {
for( var i = 0; i < this.indicators.length; ++i ) {
var a = this.indicators[i];
a.className = "";
}
if (p) p.className = "active";
},
actions: function() {
var self = this;
self.indicatorHandler = function(e) {
e.preventDefault();
var target = e.target;
var active = self._getActiveIndex(); // the current active
if ( target && !/active/.test(target.className) && target.getAttribute('data-slide-to') ) {
var n = parseInt( target.getAttribute('data-slide-to'), 10 );
self.index = n;
if( self.index == 0 ) {
self.index = 0;
} else if ( self.index == self.total - 1 ) {
self.index = self.total - 1;
}
//determine direction first
if ( (active < self.index ) || (active === self.total - 1 && self.index === 0 ) ) {
self.direction = 'left'; // next
} else if ( (active > self.index) || (active === 0 && self.index === self.total -1 ) ) {
self.direction = 'right'; // prev
}
} else { return false; }
self._slideTo( self.index, e ); //Do the slide
},
self.controlsHandler = function (e) {
var target = e.currentTarget || e.srcElement;
e.preventDefault();
if ( target === self.next ) {
self.index++;
self.direction = 'left'; //set direction first
if( self.index == self.total - 1 ) {
self.index = self.total - 1;
} else if ( self.index == self.total ){
self.index = 0
}
} else if ( target === self.prev ) {
self.index--;
self.direction = 'right'; //set direction first
if( self.index == 0 ) {
self.index = 0;
} else if ( self.index < 0 ){
self.index = self.total - 1
}
}
self._slideTo( self.index, e ); //Do the slide
}
self.keyHandler = function (e) {
switch (e.which) {
case 39:
e.preventDefault();
self.index++;
self.direction = 'left';
if( self.index == self.total - 1 ) { self.index = self.total - 1; } else
if ( self.index == self.total ){ self.index = 0 }
break;
case 37:
e.preventDefault();
self.index--;
self.direction = 'right';
if( self.index == 0 ) { self.index = 0; } else
if ( self.index < 0 ){ self.index = self.total - 1 }
break;
default: return;
}
self._slideTo( self.index, e ); //Do the slide
}
}
}
// CAROUSEL DATA API
// =================
var Carousels = document.querySelectorAll('[data-ride="carousel"]'), i = 0, crl = Carousels.length;
for (i;i<crl;i++) {
var c = Carousels[i], options = {};
options.interval = c.getAttribute('data-interval') && c.getAttribute('data-interval');
options.pause = c.getAttribute('data-pause') && c.getAttribute('data-pause') || 'hover';
options.keyboard = c.getAttribute('data-keyboard') && c.getAttribute('data-keyboard') || false;
options.duration = c.getAttribute('data-duration') && c.getAttribute('data-duration') || false;
new Carousel(c, options)
}
return Carousel;
});
// Native Javascript for Bootstrap 3 | Collapse
// by dnp_theme
(function(factory){
// CommonJS/RequireJS and "native" compatibility
if(typeof module !== "undefined" && typeof exports == "object") {
// A commonJS/RequireJS environment
if(typeof window != "undefined") {
// Window and document exist, so return the factory's return value.
module.exports = factory();
} else {
// Let the user give the factory a Window and Document.
module.exports = factory;
}
} else {
// Assume a traditional browser.
window.Collapse = factory();
}
})(function(){
// COLLAPSE DEFINITION
// ===================
var Collapse = function( element, options ) {
options = options || {};
this.isIE = (new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null) ? parseFloat( RegExp.$1 ) : false;
this.btn = typeof element === 'object' ? element : document.querySelector(element);
this.accordion = null;
this.collapse = null;
this.duration = 300; // default collapse transition duration
this.options = {};
this.options.duration = (this.isIE && this.isIE < 10) ? 0 : (options.duration || this.duration);
this.init();
};
// COLLAPSE METHODS
// ================
Collapse.prototype = {
init : function() {
this.actions();
this.addEvent();
},
actions : function() {
var self = this;
var getOuterHeight = function (el) {
var s = el && el.currentStyle || window.getComputedStyle(el), // the getComputedStyle polyfill would do this for us, but we want to make sure it does
btp = s.borderTopWidth || 0,
mtp = /px/.test(s.marginTop) ? Math.round(s.marginTop.replace('px','')) : 0,
mbp = /px/.test(s.marginBottom) ? Math.round(s.marginBottom.replace('px','')) : 0,
mte = /em/.test(s.marginTop) ? Math.round(s.marginTop.replace('em','') * parseInt(s.fontSize)) : 0,
mbe = /em/.test(s.marginBottom) ? Math.round(s.marginBottom.replace('em','') * parseInt(s.fontSize)) : 0;
return el.clientHeight + parseInt( btp ) + parseInt( mtp ) + parseInt( mbp ) + parseInt( mte ) + parseInt( mbe ); //we need an accurate margin value
};
this.toggle = function(e) {
self.btn = self.getTarget(e).btn;
self.collapse = self.getTarget(e).collapse;
if (!/in/.test(self.collapse.className)) {
self.open(e);
} else {
self.close(e);
}
},
this.close = function(e) {
e.preventDefault();
self.btn = self.getTarget(e).btn;
self.collapse = self.getTarget(e).collapse;
self._close(self.collapse);
self.removeClass(self.btn,'collapsed');
},
this.open = function(e) {
e.preventDefault();
self.btn = self.getTarget(e).btn;
self.collapse = self.getTarget(e).collapse;
self.accordion = self.btn.getAttribute('data-parent') && self.getClosest(self.btn, self.btn.getAttribute('data-parent'));
self._open(self.collapse);
self.addClass(self.btn,'collapsed');
if ( self.accordion !== null ) {
var active = self.accordion.querySelectorAll('.collapse.in'), al = active.length, i = 0;
for (i;i<al;i++) {
if ( active[i] !== self.collapse) self._close(active[i]);
}
}
},
this._open = function(c) {
self.removeEvent();
self.addClass(c,'in');
c.setAttribute('area-expanded','true');
self.addClass(c,'collapsing');
setTimeout(function() {
var h = self.getMaxHeight(c);
c.style.height = h + 'px';
c.style.overflowY = 'hidden';
}, 0);
setTimeout(function() {
c.style.height = '';
c.style.overflowY = '';
self.removeClass(c,'collapsing');
self.addEvent();
}, self.options.duration);
},
this._close = function(c) {
self.removeEvent();
c.setAttribute('area-expanded','false');
c.style.height = self.getMaxHeight(c) + 'px';
setTimeout(function() {
c.style.height = '0px';
c.style.overflowY = 'hidden';
self.addClass(c,'collapsing');
}, 0);
setTimeout(function() {
self.removeClass(c,'collapsing');
self.removeClass(c,'in');
c.style.overflowY = '';
c.style.height = '';
self.addEvent();
}, self.options.duration);
},
this.getMaxHeight = function(l) { // get collapse trueHeight and border
var h = 0;
for (var k = 0, ll = l.children.length; k < ll; k++) {
h += getOuterHeight(l.children[k]);
}
return h;
},
this.removeEvent = function() {
this.btn.removeEventListener('click', this.toggle, false);
},
this.addEvent = function() {
this.btn.addEventListener('click', this.toggle, false);
},
this.getTarget = function(e) {
var t = e.currentTarget || e.srcElement,
h = t.href && t.getAttribute('href').replace('#',''),
d = t.getAttribute('data-target') && ( t.getAttribute('data-target') ),
id = h || ( d && /#/.test(d)) && d.replace('#',''),
cl = (d && d.charAt(0) === '.') && d, //the navbar collapse trigger targets a class
c = id && document.getElementById(id) || cl && document.querySelector(cl);
return {
btn : t,
collapse : c
};
},
this.getClosest = function (el, s) { //el is the element and s the selector of the closest item to find
// source http://gomakethings.com/climbing-up-and-down-the-dom-tree-with-vanilla-javascript/
var f = s.charAt(0);
for ( ; el && el !== document; el = el.parentNode ) {// Get closest match
if ( f === '.' ) {// If selector is a class
if ( document.querySelector(s) !== undefined ) { return el; }
}
if ( f === '#' ) { // If selector is an ID
if ( el.id === s.substr(1) ) { return el; }
}
}
return false;
};
this.addClass = function(el,c) {
if (el.classList) { el.classList.add(c); } else { el.className += ' '+c; }
};
this.removeClass = function(el,c) {
if (el.classList) { el.classList.remove(c); } else { el.className = el.className.replace(c,'').replace(/^\s+|\s+$/g,''); }
};
}
};
// COLLAPSE DATA API
// =================
var Collapses = document.querySelectorAll('[data-toggle="collapse"]'), i = 0, cll = Collapses.length;
for (i;i<cll;i++) {
var item = Collapses[i], options = {};
options.duration = item.getAttribute('data-duration');
new Collapse(item,options);
}
return Collapse;
});
(function(factory){
// CommonJS/RequireJS and "native" compatibility
if(typeof module !== "undefined" && typeof exports == "object") {
// A commonJS/RequireJS environment
if(typeof window != "undefined") {
// Window and document exist, so return the factory's return value.
module.exports = factory();
} else {
// Let the user give the factory a Window and Document.
module.exports = factory;
}
} else {
// Assume a traditional browser.
window.Dropdown = factory();
}
})(function(root){
// DROPDOWN DEFINITION
// ===================
var Dropdown = function( element) {
this.menu = typeof element === 'object' ? element : document.querySelector(element);
this.init();
}
// DROPDOWN METHODS
// ================
Dropdown.prototype = {
init : function() {
this.actions();
this.menu.setAttribute('tabindex', '0'); // Fix onblur on Chrome | Safari
document.addEventListener('click', this.handle, false);
},
actions : function() {
var self = this;
this.handle = function(e) { // fix some Safari bug with <button>
var target = e.target || e.currentTarget;
if ( target === self.menu || target === self.menu.querySelector('span') ) { self.toggle(e); } else { self.close(200); }
/\#$/g.test(target.href) && e.preventDefault();
}
this.toggle = function(e) {
if (/open/.test(this.menu.parentNode.className)) {
this.close(0);
document.removeEventListener('keydown', this.key, false);
} else {
this.menu.parentNode.className += ' open';
this.menu.setAttribute('aria-expanded',true);
document.addEventListener('keydown', this.key, false);
}
}
this.key = function(e) {
if (e.which == 27) {self.close(0);}
}
this.close = function(t) {
setTimeout(function() { // links inside dropdown-menu don't fire without a short delay
self.menu.parentNode.className = self.menu.parentNode.className.replace(' open','');
self.menu.setAttribute('aria-expanded',false);
}, t);
}
}
}
// DROPDOWN DATA API
// =================
var Dropdowns = document.querySelectorAll('[data-toggle=dropdown]'), i = 0, ddl = Dropdowns.length;
for (i;i<ddl;i++) {
new Dropdown(Dropdowns[i]);
}
return Dropdown;
});
(function(factory){
// CommonJS/RequireJS and "native" compatibility
if(typeof module !== "undefined" && typeof exports == "object") {
// A commonJS/RequireJS environment
if(typeof window != "undefined") {
// Window and document exist, so return the factory's return value.
module.exports = factory();
} else {
// Let the user give the factory a Window and Document.
module.exports = factory;
}
} else {
// Assume a traditional browser.
window.Modal = factory();
}
})(function(){
//MODAL DEFINITION
var Modal = function(element, options) { // element is the trigger button / options.target is the modal
options = options || {};
this.isIE = (new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null) ? parseFloat( RegExp.$1 ) : false;
this.opened = false;
this.modal = typeof element === 'object' ? element : document.querySelector(element);
this.options = {};
this.options.backdrop = options.backdrop === 'false' ? false : true;
this.options.keyboard = options.keyboard === 'false' ? false : true;
this.options.content = options.content;
this.duration = options.duration || 300; // the default modal fade duration option
this.options.duration = (this.isIE && this.isIE < 10) ? 0 : this.duration;
this.scrollbarWidth = 0;
this.dialog = this.modal.querySelector('.modal-dialog');
this.timer = 0;
this.init();
};
var getWindowWidth = function() {
var htmlRect = document.documentElement.getBoundingClientRect(),
fullWindowWidth = window.innerWidth || (htmlRect.right - Math.abs(htmlRect.left));
return fullWindowWidth;
};
Modal.prototype = {
init : function() {
this.actions();
this.trigger();
if ( this.options.content && this.options.content !== undefined ) {
this.content( this.options.content );
}
},
actions : function() {
var self = this;
this.open = function() {
this._open();
},
this.close = function() {
this._close();
},
this._open = function() {
if ( this.options.backdrop ) {
this.createOverlay();
} else { this.overlay = null }
if ( this.overlay ) {
setTimeout( function() {
self.addClass(self.overlay,'in');
}, 0);
}
clearTimeout(self.modal.getAttribute('data-timer'));
this.timer = setTimeout( function() {
self.modal.style.display = 'block';
self.opened = true;
self.checkScrollbar();
self.adjustDialog();
self.setScrollbar();
self.resize();
self.dismiss();
self.keydown();
self.addClass(document.body,'modal-open');
self.addClass(self.modal,'in');
self.modal.setAttribute('aria-hidden', false);
}, self.options.duration/2);
this.modal.setAttribute('data-timer',self.timer);
},
this._close = function() {
if ( this.overlay ) {
this.removeClass(this.overlay,'in');
}
this.removeClass(this.modal,'in');
this.modal.setAttribute('aria-hidden', true);
clearTimeout(self.modal.getAttribute('data-timer'));
this.timer = setTimeout( function() {
self.opened = false;
self.removeClass(document.body,'modal-open');
self.resize();
self.resetAdjustments();
self.resetScrollbar();
self.dismiss();
self.keydown();
self.modal.style.display = '';
}, self.options.duration/2);
this.modal.setAttribute('data-timer',self.timer);
setTimeout( function() {
if (!document.querySelector('.modal.in')) { self.removeOverlay(); }
}, self.options.duration);
},
this.content = function( content ) {
return this.modal.querySelector('.modal-content').innerHTML = content;
},
this.createOverlay = function() {
var backdrop = document.createElement('div'), overlay = document.querySelector('.modal-backdrop');
backdrop.setAttribute('class','modal-backdrop fade');
if ( overlay ) {
this.overlay = overlay;
} else {
this.overlay = backdrop;
document.body.appendChild(backdrop);
}
},
this.removeOverlay = function() {
var overlay = document.querySelector('.modal-backdrop');
if ( overlay !== null && overlay !== undefined ) {
document.body.removeChild(overlay)
}
},
this.keydown = function() {
function keyHandler(e) {
if (self.options.keyboard && e.which == 27) {
self.close();
}
}
if (this.opened) {
document.addEventListener('keydown', keyHandler, false);
} else {
document.removeEventListener('keydown', keyHandler, false);
}
},
this.trigger = function() {
var triggers = document.querySelectorAll('[data-toggle="modal"]'), tgl = triggers.length, i = 0;
for ( i;i<tgl;i++ ) {
triggers[i].addEventListener('click', function(e) {
var b = e.target,
s = b.getAttribute('data-target') && b.getAttribute('data-target').replace('#','')
|| b.getAttribute('href') && b.getAttribute('href').replace('#','');
if ( document.getElementById( s ) === self.modal ) {
self.open()
}
})
}
},
this._resize = function() {
var overlay = this.overlay||document.querySelector('.modal-backdrop'),
dim = { w: document.documentElement.clientWidth + 'px', h: document.documentElement.clientHeight + 'px' };
// setTimeout(function() {
if ( overlay !== null && /in/.test(overlay.className) ) {
overlay.style.height = dim.h; overlay.style.width = dim.w;
}
// }, self.options.duration/2)
},
this.oneResize = function() {
function oneResize() {
self._resize();
self.handleUpdate();
window.removeEventListener('resize', oneResize, false);
}
window.addEventListener('resize', oneResize, false);
},
this.resize = function() {
function resizeHandler() {
// setTimeout(function() {
self._resize();
self.handleUpdate();
console.log('offresize')
// }, 100)
}
if (this.opened) {
window.addEventListener('resize', this.oneResize, false);
} else {
window.removeEventListener('resize', this.oneResize, false);
}
},
this.dismiss = function() {
function dismissHandler(e) {
if ( e.target.parentNode.getAttribute('data-dismiss') === 'modal' || e.target.getAttribute('data-dismiss') === 'modal' || e.target === self.modal ) {
e.preventDefault(); self.close()
}
}
if (this.opened) {
this.modal.addEventListener('click', dismissHandler, false);
} else {
this.modal.removeEventListener('click', dismissHandler, false);
}
},
// these following methods are used to handle overflowing modals
this.handleUpdate = function () {
this.adjustDialog();
},
this.adjustDialog = function () {
this.modal.style.paddingLeft = !this.bodyIsOverflowing && this.modalIsOverflowing ? this.scrollbarWidth + 'px' : '';
this.modal.style.paddingRight = this.bodyIsOverflowing && !this.modalIsOverflowing ? this.scrollbarWidth + 'px' : '';
},
this.resetAdjustments = function () {
this.modal.style.paddingLeft = '';
this.modal.style.paddingRight = '';
},
this.checkScrollbar = function () {
this.bodyIsOverflowing = document.body.clientWidth < getWindowWidth();
this.modalIsOverflowing = this.modal.scrollHeight > document.documentElement.clientHeight;
this.scrollbarWidth = this.measureScrollbar();
},
this.setScrollbar = function () {
var bodyStyle = window.getComputedStyle(document.body), bodyPad = parseInt((bodyStyle.paddingRight), 10);
if (this.bodyIsOverflowing) { document.body.style.paddingRight = (bodyPad + this.scrollbarWidth) + 'px'; }
},
this.resetScrollbar = function () {
document.body.style.paddingRight = '';
},
this.measureScrollbar = function () { // thx walsh
var scrollDiv = document.createElement('div');
scrollDiv.className = 'modal-scrollbar-measure';
document.body.appendChild(scrollDiv);
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
return scrollbarWidth;
},
this.addClass = function(el,c) {
if (el.classList) { el.classList.add(c); } else { el.className += ' '+c; }
},
this.removeClass = function(el,c) {
if (el.classList) { el.classList.remove(c); } else { el.className = el.className.replace(c,'').replace(/^\s+|\s+$/g,''); }
}
}
};
// DATA API
var Modals = document.querySelectorAll('.modal'), mdl = Modals.length, i = 0;
for ( i;i<mdl;i++ ) {
var modal = Modals[i], options = {};
options.keyboard = modal.getAttribute('data-keyboard');
options.backdrop = modal.getAttribute('data-backdrop');
options.duration = modal.getAttribute('data-duration');
new Modal(modal,options)
}
return Modal;
});
(function(factory){
// CommonJS/RequireJS and "native" compatibility
if(typeof module !== "undefined" && typeof exports == "object") {
// A commonJS/RequireJS environment
if(typeof window != "undefined") {
// Window and document exist, so return the factory's return value.
module.exports = factory();
} else {
// Let the user give the factory a Window and Document.
module.exports = factory;
}
} else {
// Assume a traditional browser.
window.Popover = factory();
}
})(function(){
// POPOVER DEFINITION
// ===================
var Popover = function( element,options ) {
options = options || {};
this.isIE = (new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null) ? parseFloat( RegExp.$1 ) : false;
this.link = typeof element === 'object' ? element : document.querySelector(element);
this.title = this.link.getAttribute('data-title') || null;
this.content = this.link.getAttribute('data-content') || null;
this.popover = null;
this.options = {};
this.options.template = options.template ? options.template : null;
this.options.trigger = options.trigger ? options.trigger : 'hover';
this.options.animation = options.animation && options.animation !== 'true' ? options.animation : 'true';
this.options.placement = options.placement ? options.placement : 'top';
this.options.delay = parseInt(options.delay) || 100;
this.options.dismiss = options.dismiss && options.dismiss === 'true' ? true : false;
this.duration = 150;
this.options.duration = (this.isIE && this.isIE < 10) ? 0 : (options.duration || this.duration);
this.options.container = document.body;
if ( this.content || this.options.template ) this.init();
this.timer = 0 // the link own event timer
this.rect = null;
}
// POPOVER METHODS
// ================
Popover.prototype = {
init : function() {
this.actions();
var events = ('onmouseleave' in this.link) ? [ 'mouseenter', 'mouseleave'] : [ 'mouseover', 'mouseout' ];
if (this.options.trigger === 'hover') {
this.link.addEventListener(events[0], this.open, false);
if (!this.options.dismiss) { this.link.addEventListener(events[1], this.close, false); }
} else if (this.options.trigger === 'click') {
this.link.addEventListener('click', this.toggle, false);
if (!this.options.dismiss) { this.link.addEventListener('blur', this.close, false); }
} else if (this.options.trigger === 'focus') {
this.link.addEventListener('focus', this.toggle, false);
if (!this.options.dismiss) { this.link.addEventListener('blur', this.close, false); }
}
if (this.options.dismiss) { document.addEventListener('click', this.dismiss, false); }
if (!(this.isIE && this.isIE < 9) ) { // dismiss on window resize
window.addEventListener('resize', this.close, false );
}
},
actions : function() {
var self = this;
this.toggle = function(e) {
if (self.popover === null) {
self.open()
} else {
self.close()
}
},
this.open = function(e) {
clearTimeout(self.link.getAttribute('data-timer'));
self.timer = setTimeout( function() {
if (self.popover === null) {
self.createPopover();
self.stylePopover();
self.updatePopover()
}
}, self.options.duration );
self.link.setAttribute('data-timer',self.timer);
},
this.dismiss = function(e) {
if (self.popover && e.target === self.popover.querySelector('.close')) {
self.close();
}
},
this.close = function(e) {
clearTimeout(self.link.getAttribute('data-timer'));
self.timer = setTimeout( function() {
if (self.popover && self.popover !== null && /in/.test(self.popover.className)) {
self.popover.className = self.popover.className.replace(' in','');
setTimeout(function() {
self.removePopover(); // for performance/testing reasons we can keep the popovers if we want
}, self.options.duration);
}
}, self.options.delay + self.options.duration);
self.link.setAttribute('data-timer',self.timer);
},
//remove the popover
this.removePopover = function() {
this.popover && this.options.container.removeChild(this.popover);
this.popover = null;
this.timer = null
},
this.createPopover = function() {
this.popover = document.createElement('div');
if ( this.content !== null && this.options.template === null ) { //create the popover from data attributes
this.popover.setAttribute('role','tooltip');
var popoverArrow = document.createElement('div');
popoverArrow.setAttribute('class','arrow');
if (this.title !== null) {
var popoverTitle = document.createElement('h3');
popoverTitle.setAttribute('class','popover-title');
if (this.options.dismiss) {
popoverTitle.innerHTML = this.title + '<button type="button" class="close">×</button>';
} else {
popoverTitle.innerHTML = this.title;
}
this.popover.appendChild(popoverTitle);
}
var popoverContent = document.createElement('div');
popoverContent.setAttribute('class','popover-content');
this.popover.appendChild(popoverArrow);
this.popover.appendChild(popoverContent);
//set popover content
if (this.options.dismiss && this.title === null) {
popoverContent.innerHTML = this.content + '<button type="button" class="close">×</button>';
} else {
popoverContent.innerHTML = this.content;
}
} else { // or create the popover from template
var template = document.createElement('div');
template.innerHTML = this.options.template;
this.popover.innerHTML = template.firstChild.innerHTML;
}
//append to the container
this.options.container.appendChild(this.popover);
this.popover.style.display = 'block';
},
this.stylePopover = function(pos) {
this.rect = this.getRect();
var placement = pos || this.options.placement;
var animation = this.options.animation === 'true' ? 'fade' : '';
this.popover.setAttribute('class','popover '+placement+' '+animation);
var linkDim = { w: this.link.offsetWidth, h: this.link.offsetHeight }; //link real dimensions
// all popover dimensions
var pd = this.popoverDimensions(this.popover);
var toolDim = { w : pd.w, h: pd.h }; //popover real dimensions
//window vertical and horizontal scroll
var scrollYOffset = this.getScroll().y;
var scrollXOffset = this.getScroll().x;
//apply styling
if ( /top/.test(placement) ) { //TOP
this.popover.style.top = this.rect.top + scrollYOffset - toolDim.h + 'px';
this.popover.style.left = this.rect.left + scrollXOffset - toolDim.w/2 + linkDim.w/2 + 'px'
} else if ( /bottom/.test(placement) ) { //BOTTOM
this.popover.style.top = this.rect.top + scrollYOffset + linkDim.h + 'px';
this.popover.style.left = this.rect.left + scrollXOffset - toolDim.w/2 + linkDim.w/2 + 'px';
} else if ( /left/.test(placement) ) { //LEFT
this.popover.style.top = this.rect.top + scrollYOffset - toolDim.h/2 + linkDim.h/2 + 'px';
this.popover.style.left = this.rect.left + scrollXOffset - toolDim.w + 'px';
} else if ( /right/.test(placement) ) { //RIGHT
this.popover.style.top = this.rect.top + scrollYOffset - toolDim.h/2 + linkDim.h/2 + 'px';
this.popover.style.left = this.rect.left + scrollXOffset + linkDim.w + 'px';
}
},
this.updatePopover = function() {
var placement = null;
if ( !self.isElementInViewport(self.popover) ) {
placement = self.updatePlacement();
} else {
placement = self.options.placement;
}
self.stylePopover(placement);
self.popover.className += ' in';
},
this.updatePlacement = function() {
var pos = this.options.placement;
if ( /top/.test(pos) ) { //TOP
return 'bottom';
} else if ( /bottom/.test(pos) ) { //BOTTOM
return 'top';
} else if ( /left/.test(pos) ) { //LEFT
return 'right';
} else if ( /right/.test(pos) ) { //RIGHT
return 'left';
}
},
this.getRect = function() {
return this.link.getBoundingClientRect()
},
this.getScroll = function() {
return {
y : window.pageYOffset || document.documentElement.scrollTop,
x : window.pageXOffset || document.documentElement.scrollLeft
}
},
this.popoverDimensions = function(p) {//check popover width and height
return {
w : p.offsetWidth,
h : p.offsetHeight
}
},
this.isElementInViewport = function(t) { // check if this.popover is in viewport
var r = t.getBoundingClientRect();
return (
r.top >= 0 &&
r.left >= 0 &&
r.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
r.right <= (window.innerWidth || document.documentElement.clientWidth)
)
}
}
}
// POPOVER DATA API
// =================
var Popovers = document.querySelectorAll('[data-toggle=popover]'), i = 0, ppl = Popovers.length;
for (i;i<ppl;i++){
var item = Popovers[i], options = {};
options.trigger = item.getAttribute('data-trigger'); // click / hover / focus
options.animation = item.getAttribute('data-animation'); // true / false
options.duration = item.getAttribute('data-duration');
options.placement = item.getAttribute('data-placement');
options.dismiss = item.getAttribute('data-dismiss');
options.delay = item.getAttribute('data-delay');
new Popover(item,options);
}
return Popover;
});
(function(factory){
// CommonJS/RequireJS and "native" compatibility
if(typeof module !== "undefined" && typeof exports == "object") {
// A commonJS/RequireJS environment
if(typeof window != "undefined") {
// Window and document exist, so return the factory's return value.
module.exports = factory();
} else {
// Let the user give the factory a Window and Document.
module.exports = factory;
}
} else {
// Assume a traditional browser.
window.ScrollSpy = factory();
}
})(function(){
//SCROLLSPY DEFINITION
var ScrollSpy = function(element,item,options) {
options = options || {};
//this is the container element we spy it's elements on
this.element = typeof element === 'object' ? element : document.querySelector(element);
this.options = {};
this.isIE = (new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null) ? parseFloat( RegExp.$1 ) : false;
// this is the UL menu component our scrollSpy object will target, configure and required by the container element
this.options.target = options.target ? (typeof options.target === 'object' ? options.target : document.querySelector(options.target)) : null;
//we need to determine the index of each menu item
this.items = this.options.target && this.options.target.getElementsByTagName('A');
this.item = item;
// the parent LI element
this.parent = this.item.parentNode;
// the upper level LI ^ UL ^ LI, this is required for dropdown menus
this.parentParent = this.parent.parentNode.parentNode;
this.tg = this.item.href && document.getElementById(this.item.getAttribute('href').replace('#',''));
this.active = false;
this.topEdge = 0;
this.bottomEdge = 0;
//determine which is the real scrollTarget
if ( this.element.offsetHeight < this.element.scrollHeight ) { // or this.scrollHeight()
this.scrollTarget = this.element;
} else {
this.scrollTarget = window;
}
if ( this.options.target ) {
this.init();
}
};
//SCROLLSPY METHODS
ScrollSpy.prototype = {
init: function () {
if ( this.item.getAttribute('href') && this.item.getAttribute('href').indexOf('#') > -1 ) {
//actions
this.checkEdges();
this.refresh()
this.scrollEvent();
if (!(this.isIE && this.isIE < 9)) { this.resizeEvent(); }
}
},
topLimit: function () { // the target offset
if ( this.scrollTarget === window ) {
return this.tg.getBoundingClientRect().top + this.scrollOffset() - 5
} else {
return this.tg.offsetTop;
}
},
bottomLimit: function () {
return this.topLimit() + this.tg.clientHeight
},
checkEdges: function () {
this.topEdge = this.topLimit();
this.bottomEdge = this.bottomLimit()
},
scrollOffset: function () {
if ( this.scrollTarget === window ) {
return window.pageYOffset || document.documentElement.scrollTop
} else {
return this.element.scrollTop
}
},
activate: function () {
if ( this.parent && this.parent.tagName === 'LI' && !/active/.test(this.parent.className) ) {
this.addClass(this.parent,'active');
if ( this.parentParent && this.parentParent.tagName === 'LI' // activate the dropdown as well
&& /dropdown/.test(this.parentParent.className)
&& !/active/.test(this.parentParent.className) ) { this.addClass(this.parentParent,'active'); }
this.active = true
}
},
deactivate: function () {
if ( this.parent && this.parent.tagName === 'LI' && /active/.test(this.parent.className) ) {
this.removeClass(this.parent,'active');
if ( this.parentParent && this.parentParent.tagName === 'LI' // deactivate the dropdown as well
&& /dropdown/.test(this.parentParent.className)
&& /active/.test(this.parentParent.className) ) { this.removeClass(this.parentParent,'active'); }
this.active = false
}
},
toggle: function () {
if ( this.active === false
&& ( this.bottomEdge > this.scrollOffset() && this.scrollOffset() >= this.topEdge )) { //regular use, scroll just entered the element's topLimit or bottomLimit
this.activate();
} else if (this.active === true && (this.bottomEdge <= this.scrollOffset() && this.scrollOffset() < this.topEdge )) {
this.deactivate()
}
},
refresh : function () { // check edges again
this.deactivate();
this.checkEdges();
this.toggle() // If any case update values again
},
scrollEvent : function(){
var self = this;
this.scrollTarget.addEventListener('scroll', onSpyScroll, false);
function onSpyScroll() {
self.refresh();
}
},
resizeEvent : function(){
var self = this;
window.addEventListener('resize', onSpyResize, false);
function onSpyResize() {
self.refresh()
}
},
scrollHeight : function() {
if ( this.scrollTarget === window ) {
return Math.max( document.body.scrollHeight, document.body.offsetHeight,
document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight );
} else {
return this.element.scrollHeight
}
},
addClass : function(el,c) {
if (el.classList) { el.classList.add(c); } else { el.className += ' '+c; }
},
removeClass : function(el,c) {
if (el.classList) { el.classList.remove(c); } else { el.className = el.className.replace(c,'').replace(/^\s+|\s+$/g,''); }
}
};
//SCROLLSPY API
//=============
var scrollSpyes = document.querySelectorAll('[data-spy="scroll"]'), i = 0, ssl = scrollSpyes.length; // mostly is the document.body or a large container with many elements having id="not-null-id"
for (i;i<ssl;i++) {
var spy = scrollSpyes[i], options = {};
options.target = spy.getAttribute('data-target') || null; // this must be a .nav component with id="not-null"
if ( options.target !== null ) {
var menu = options.target === 'object' ? options.target : document.querySelector(options.target),
items = menu.querySelectorAll('a'), j = 0, il = items.length;
for (j;j<il;j++) {
var item = items[j];
if ( item.href && item.getAttribute('href') !== '#' )
new ScrollSpy(spy, item, options);
}
}
}
return ScrollSpy;
});
(function(factory){
// CommonJS/RequireJS and "native" compatibility
if(typeof module !== "undefined" && typeof exports == "object") {
// A commonJS/RequireJS environment
if(typeof window != "undefined") {
// Window and document exist, so return the factory's return value.
module.exports = factory();
} else {
// Let the user give the factory a Window and Document.
module.exports = factory;
}
} else {
// Assume a traditional browser.
window.Tab = factory();
}
})(function(){
// TAB DEFINITION
// ===================
var Tab = function( element,options ) {
options = options || {};
this.isIE = (new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null) ? parseFloat( RegExp.$1 ) : false;
this.tab = typeof element === 'object' ? element : document.querySelector(element);
this.tabs = this.tab.parentNode.parentNode;
this.dropdown = this.tabs.querySelector('.dropdown');
if ( /dropdown-menu/.test(this.tabs.className) ) {
this.dropdown = this.tabs.parentNode;
this.tabs = this.tabs.parentNode.parentNode;
}
this.options = options;
// default tab transition duration
this.duration = 150;
this.options.duration = (this.isIE && this.isIE < 10) ? 0 : (options.duration || this.duration);
this.init();
}
// TAB METHODS
// ================
Tab.prototype = {
init : function() {
this.actions();
this.tab.addEventListener('click', this.action, false);
},
actions : function() {
var self = this;
this.action = function(e) {
e = e || window.e; e.preventDefault();
var next = e.target; //the tab we clicked is now the next tab
var nextContent = document.getElementById(next.getAttribute('href').replace('#','')); //this is the actual object, the next tab content to activate
var isDropDown = new RegExp('(?:^|\\s)'+ 'dropdown-menu' +'(?!\\S)');
// get current active tab and content
var activeTab = self.getActiveTab();
var activeContent = self.getActiveContent();
if ( !/active/.test(next.parentNode.className) ) {
// toggle "active" class name
self.removeClass(activeTab,'active');
self.addClass(next.parentNode,'active');
// handle dropdown menu "active" class name
if ( self.dropdown ) {
if ( !(isDropDown.test(self.tab.parentNode.parentNode.className)) ) {
if (/active/.test(self.dropdown.className)) self.removeClass(self.dropdown,'active');
} else {
if (!/active/.test(self.dropdown.className)) self.addClass(self.dropdown,'active');
}
}
//1. hide current active content first
self.removeClass(activeContent,'in');
setTimeout(function() { // console.log(self)
//2. toggle current active content from view
self.removeClass(activeContent,'active');
self.addClass(nextContent,'active');
}, self.options.duration);
setTimeout(function() {
//3. show next active content
self.addClass(nextContent,'in');
}, self.options.duration*2);
}
},
this.addClass = function(el,c) {
if (el.classList) { el.classList.add(c); } else { el.className += ' '+c; }
},
this.removeClass = function(el,c) {
if (el.classList) { el.classList.remove(c); } else { el.className = el.className.replace(c,'').replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,''); }
},
this.getActiveTab = function() {
var activeTabs = this.tabs.querySelectorAll('.active');
if ( activeTabs.length === 1 && !/dropdown/.test(activeTabs[0].className) ) {
return activeTabs[0]
} else if ( activeTabs.length > 1 ) {
return activeTabs[activeTabs.length-1]
}
},
this.getActiveContent = function() {
var a = this.getActiveTab().getElementsByTagName('A')[0].getAttribute('href').replace('#','');
return a && document.getElementById(a)
}
}
}
// TAB DATA API
// =================
var Tabs = document.querySelectorAll("[data-toggle='tab'], [data-toggle='pill']"), tbl = Tabs.length, i=0;
for ( i;i<tbl;i++ ) {
var tab = Tabs[i], options = {};
options.duration = tab.getAttribute('data-duration') && tab.getAttribute('data-duration') || false;
new Tab(tab,options);
}
return Tab;
});
(function(factory){
// CommonJS/RequireJS and "native" compatibility
if(typeof module !== "undefined" && typeof exports == "object") {
// A commonJS/RequireJS environment
if(typeof window != "undefined") {
// Window and document exist, so return the factory's return value.
module.exports = factory();
} else {
// Let the user give the factory a Window and Document.
module.exports = factory;
}
} else {
// Assume a traditional browser.
window.Tooltip = factory();
}
})(function(root){
// TOOLTIP DEFINITION
// ===================
var Tooltip = function( element,options ) {
options = options || {};
this.link = typeof element === 'object' ? element : document.querySelector(element);
this.title = this.link.getAttribute('title') || this.link.getAttribute('data-original-title');
this.tooltip = null;
this.options = {};
this.options.animation = options.animation && options.animation !== 'fade' ? options.animation : 'fade';
this.options.placement = options.placement ? options.placement : 'top';
this.options.delay = parseInt(options.delay) || 100;
this.isIE = (new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null) ? parseFloat( RegExp.$1 ) : false;
this.duration = 150;
this.options.duration = this.isIE && this.isIE < 10 ? 0 : (options.duration || this.duration);
this.options.container = options.container || document.body;
if ( this.title ) this.init();
this.timer = 0 // the link own event timer
}
// TOOLTIP METHODS
// ================
Tooltip.prototype = {
init : function() {
this.actions();
this.rect = null;
var events = ('onmouseleave' in this.link) ? [ 'mouseenter', 'mouseleave'] : [ 'mouseover', 'mouseout' ];
this.link.addEventListener(events[0], this.open, false);
this.link.addEventListener(events[1], this.close, false);
//remove title from link
this.link.setAttribute('data-original-title',this.title);
this.link.removeAttribute('title');
},
actions : function() {
var self = this;
this.open = function(e) {
clearTimeout(self.link.getAttribute('data-timer'));
self.timer = setTimeout( function() {
if (self.tooltip === null) {
self.createToolTip();
self.styleTooltip();
self.updateTooltip()
}
}, self.options.duration );
self.link.setAttribute('data-timer',self.timer);
},
this.close = function(e) {
clearTimeout(self.link.getAttribute('data-timer'));
self.timer = setTimeout( function() {
if (self.tooltip && self.tooltip !== null) {
self.tooltip.className = self.tooltip.className.replace(' in','');
setTimeout(function() {
self.removeToolTip(); // for performance/testing reasons we can keep the tooltips if we want
}, self.options.duration);
}
}, self.options.delay + self.options.duration);
self.link.setAttribute('data-timer',self.timer);
},
//remove the tooltip
this.removeToolTip = function() {
this.tooltip && this.options.container.removeChild(this.tooltip);
this.tooltip = null;
},
//create the tooltip structure
this.createToolTip = function() {
this.tooltip = document.createElement('div');
this.tooltip.setAttribute('role','tooltip');
var tooltipArrow = document.createElement('div');
tooltipArrow.setAttribute('class','tooltip-arrow');
var tooltipInner = document.createElement('div');
tooltipInner.setAttribute('class','tooltip-inner');
this.tooltip.appendChild(tooltipArrow);
this.tooltip.appendChild(tooltipInner);
//set tooltip content
tooltipInner.innerHTML = this.title;
//append to the container
this.options.container.appendChild(this.tooltip);
},
this.styleTooltip = function(pos) {
this.rect = this.getRect();
var placement = pos || this.options.placement;
this.tooltip.setAttribute('class','tooltip '+placement+' '+this.options.animation);
var linkDim = { w: this.link.offsetWidth, h: this.link.offsetHeight }; //link real dimensions
// all tooltip dimensions
var td = this.tooltipDimensions(this.tooltip);
var toolDim = { w : td.w, h: td.h }; //tooltip real dimensions
//window vertical and horizontal scroll
var scrollYOffset = this.getScroll().y;
var scrollXOffset = this.getScroll().x;
//apply styling
if ( /top/.test(placement) ) { //TOP
this.tooltip.style.top = this.rect.top + scrollYOffset - toolDim.h + 'px';
this.tooltip.style.left = this.rect.left + scrollXOffset - toolDim.w/2 + linkDim.w/2 + 'px'
} else if ( /bottom/.test(placement) ) { //BOTTOM
this.tooltip.style.top = this.rect.top + scrollYOffset + linkDim.h + 'px';
this.tooltip.style.left = this.rect.left + scrollXOffset - toolDim.w/2 + linkDim.w/2 + 'px';
} else if ( /left/.test(placement) ) { //LEFT
this.tooltip.style.top = this.rect.top + scrollYOffset - toolDim.h/2 + linkDim.h/2 + 'px';
this.tooltip.style.left = this.rect.left + scrollXOffset - toolDim.w + 'px';
} else if ( /right/.test(placement) ) { //RIGHT
this.tooltip.style.top = this.rect.top + scrollYOffset - toolDim.h/2 + linkDim.h/2 + 'px';
this.tooltip.style.left = this.rect.left + scrollXOffset + linkDim.w + 'px';
}
},
this.updateTooltip = function() {
var placement = null;
if ( !this.isElementInViewport(this.tooltip) ) {
placement = this.updatePlacement();
} else {
placement = this.options.placement;
}
this.styleTooltip(placement);
this.tooltip.className += ' in';
},
this.updatePlacement = function() {
var pos = this.options.placement;
if ( /top/.test(pos) ) { //TOP
return 'bottom';
} else if ( /bottom/.test(pos) ) { //BOTTOM
return 'top';
} else if ( /left/.test(pos) ) { //LEFT
return 'right';
} else if ( /right/.test(pos) ) { //RIGHT
return 'left';
}
},
this.getRect = function() {
return this.link.getBoundingClientRect()
},
this.getScroll = function() {
return {
y : window.pageYOffset || document.documentElement.scrollTop,
x : window.pageXOffset || document.documentElement.scrollLeft
}
},
this.tooltipDimensions = function(t) {//check tooltip width and height
return {
w : t.offsetWidth,
h : t.offsetHeight
}
},
this.isElementInViewport = function(t) { // check if this.tooltip is in viewport
var r = t.getBoundingClientRect();
return (
r.top >= 0 &&
r.left >= 0 &&
r.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
r.right <= (window.innerWidth || document.documentElement.clientWidth)
)
}
}
}
// TOOLTIP DATA API
// =================
var Tooltips = document.querySelectorAll('[data-toggle=tooltip]'), i = 0, tpl = Tooltips.length;
for (i;i<tpl;i++){
var item = Tooltips[i], options = {};
options.animation = item.getAttribute('data-animation');
options.placement = item.getAttribute('data-placement');
options.duration = item.getAttribute('data-duration');
options.delay = item.getAttribute('data-delay');
new Tooltip(item,options);
}
return Tooltip;
});
|
module.exports = {
getOptions: function (target) {
return target.virtuals;
},
decorate: function(model, virtuals) {
var loading = {}, loadingModel = false;
model.on("watching", function (propertyPath) {
var property = propertyPath[0];
if (model.get(property) != null) return;
var self = this;
if (virtuals[property]) {
if (loading[property]) return;
loading[property] = true;
virtuals[property].call(model, function (err, value) {
loading[property] = false;
if (err) return;
model.set(property, value);
});
} else {
var selfVirtual = virtuals["*"];
if (!selfVirtual || loadingModel) return;
loadingModel = true;
selfVirtual.call(model, property, function () {
});
}
});
}
} |
// When the DOM is ready
$(function () {
// Grab our template
var template = $('#bookmark-template').html();
// Load our bookmarks
window.loadBookmarks(function (err, bookmarks) {
// If there was an error, throw it
if (err) { throw err; }
// Iterate over the bookmarks
var bookmarkHtmlArr = bookmarks.map(function (bookmark) {
var html = templatez(template, bookmark);
return html;
}),
bookmarkHtml = bookmarkHtmlArr.join('');
// Append the content to our table
var bookmarkList = document.getElementById('bookmark-list');
bookmarkList.innerHTML = bookmarkHtml;
// Performify the list
var options = {
valueNames: ['title', 'uri'],
plugins: [
['matchSearch']
]
},
list = new List('bookmark-list-container', options);
// Set up search function
var $search = $('#search'),
defaultColumns = {title:1,uri:1},
columns = defaultColumns;
function searchList() {
var val = $search.val();
list.matchSearch(val, columns);
}
// When our search field is typed into, search
// TODO: Change to onchange
$search.on('keyup', searchList);
// When the search form is submitted, search
var $searchForm = $('#search-form');
$searchForm.on('submit', function (e) {
// Prevent the submission
e.preventDefault();
// Search the list
searchList();
});
// When one of the search links is clicked
// TODO: This should fire a method of a Search class
var $searchBtn = $searchForm.find('.search-btn');
$searchForm.on('click', 'a', function () {
// Grab the text
var $a = $(this),
search = $a.data('search'),
text = $a.data('text');
// Update the button text
$searchBtn.text(text);
// If the search is *, use the default columns
if (search === '*') {
columns = defaultColumns;
} else {
// Otherwise, search the specific column
columns = {};
columns[search] = 1;
}
// Search meow
searchList();
});
});
}); |
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon([/*#__PURE__*/_jsx("circle", {
cx: "20",
cy: "12",
r: "2"
}, "0"), /*#__PURE__*/_jsx("circle", {
cx: "4",
cy: "12",
r: "2"
}, "1"), /*#__PURE__*/_jsx("circle", {
cx: "12",
cy: "20",
r: "2"
}, "2"), /*#__PURE__*/_jsx("path", {
d: "m13.943 8.6191 4.4044-4.392 1.4122 1.4162-4.4043 4.392zM8.32 9.68l.31.32 1.42-1.41-4.02-4.04h-.01l-.31-.32-1.42 1.41 4.02 4.05zm7.09 4.26L14 15.35l3.99 4.01.35.35 1.42-1.41-3.99-4.01zm-6.82.01-4.03 4.01-.32.33 1.41 1.41 4.03-4.02.33-.32z"
}, "3"), /*#__PURE__*/_jsx("circle", {
cx: "12",
cy: "4",
r: "2"
}, "4")], 'StreamOutlined'); |
//////////////////////////////////////
// //
// Calendar functionality //
// //
//////////////////////////////////////
$(document).ready(function() {
var gCalURL = 'https://www.google.com/calendar/feeds/nk1n38oqstjhj5cm87f28ljpog%40group.calendar.google.com/public/basic';
// initialize the draggable events
$('#external-events div.external-event').each(function() {
var eventObject = {};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject);
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
// initialize the calendar
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek'
},
allDaySlot : false,
events: {
url: gCalURL,
backgroundColor : "#bbb",
textColor : "#666"
},
editable: true,
droppable: true,
drop: function(date, allDay) {
BNB.calendar.dropEventHandler(date, allDay, this);
}
});
// Set right click event handler for context menu
document.getElementsByTagName("body")[0].onmousedown = (function(){
return function(){
var rightClick,
e = window.event;
// Make sure it's a right click
if (e.which) rightClick = (e.which == 3);
else if (e.button) rightClick = (e.button == 2);
// User right clicked -- open menu
if(rightClick) {
BNB.calendar.rightClickMenu(e);
return false;
}
}
})();
});
var BNB = BNB || {};
BNB.calendar = (function(){
var disableRightClickMenu = false;
// Sync external event Objects with the current calendar
// Arg: URL string
function getEvents(url){
var a = {"containerEvent":{"container":true,"title":"ProtocolA","length":0,"description":"",
"steps":{"step1":{"eventId":10,"instanceId":0,"verb":"The First Step","active":true,"length":30000,
"container":false,"stepNumber":1,"notes":""},"step2":{"eventId":10,"instanceId":0,"verb":"The Second Step",
"active":false,"length":10000,"container":false,"stepNumber":2,"notes":"Step 2 requires extra precision."},
"step3":{"eventId":10,"instanceId":0,"verb":"The Third Step","active":true,"length":10000,"container":false,
"stepNumber":3,"notes":""},"step4":{"eventId":10,"instanceId":0,"verb":"The Fourth Step","active":true,
"length":7000,"container":false,"stepNumber":4,"notes":"This is the final step, make sure to clean up."}}}};
syncEvents(a)
}
// Get JSON objects from another file (done in getEvents()) and
// add the data to the list of draggable events
// Arg: JSON object
function syncEvents(eventList){
var dragContainer = document.getElementById('external-events');
// Iterate over each item in eventList
for (var key in eventList) {
// don't touch the inherited properties
if (!eventList.hasOwnProperty(key)) continue;
// Create the draggable event node
var eventNode = document.createElement('div');
eventNode.className = 'custom-event';
// Populate DOM data-* with JSON properties
eventNode.innerHTML = eventList[key].title;
//eventNode.style.backgroundColor = eventList[key].backgroundColor;
eventNode.setAttribute("data-allDay", eventList[key].allDay);
eventNode.setAttribute("data-active", eventList[key].active);
eventNode.setAttribute("data-length", eventList[key].length);
eventNode.setAttribute("data-container", eventList[key].container);
// If the event object is a container, add all the attributes of the child elements to the DOM
if(eventList[key].container == true){
var i = 1;
while(eventList[key].steps["step" + i]){
eventNode.setAttribute("data-step"+i+"-verb", eventList[key].steps["step" + i].verb);
eventNode.setAttribute("data-step"+i+"-event-id", eventList[key].steps["step" + i].eventId);
eventNode.setAttribute("data-step"+i+"-step-number", eventList[key].steps["step" + i].stepNumber);
eventNode.setAttribute("data-step"+i+"-allDay", eventList[key].steps["step" + i].allDay);
eventNode.setAttribute("data-step"+i+"-active", eventList[key].steps["step" + i].active);
eventNode.setAttribute("data-step"+i+"-length", eventList[key].steps["step" + i].length);
eventNode.setAttribute("data-step"+i+"-container", eventList[key].steps["step" + i].container);
eventNode.setAttribute("data-step"+i+"-notes", eventList[key].steps["step" + i].notes);
i++;
}
}
// Add draggable event element to the page
dragContainer.appendChild(eventNode);
}
// Make them draggable
$('#external-events div.custom-event').each(function() {
var eventObject = {
title: $.trim($(this).text()),
backgroundColor : this.style.backgroundColor,
allDay : this.getAttribute("data-allDay"),
length : this.getAttribute("data-length")
};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject);
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
var syncButton = document.getElementById('sync-events');
syncButton.parentNode.removeChild(syncButton);
}
// Add an event to the calendar when it's dropped in place
// Arg: Date object, bool, reference to this
function dropEventHandler(date, allDay, that){
var weekDays = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
// Create a unique ID for the steps of the protocol to share
var instanceId;
// Create a background color based on unique ID
// But make sure it's a LIGHT color that can show white text! (ie 5-c hex)
do{
instanceId = "xxxxxx".replace(/[x]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
while(parseInt(instanceId[0], 16) < 5 || parseInt(instanceId[0], 16) > 12 ||
parseInt(instanceId[2], 16) < 5 || parseInt(instanceId[2], 16) > 12 ||
parseInt(instanceId[4], 16) < 5 || parseInt(instanceId[4], 16) > 12 )
var instanceBgColor = instanceId[0].toString() +
instanceId[2].toString() +
instanceId[4].toString();
// Render a single step
if(that.getAttribute("data-container") == "false"){
// retrieve the dropped element's stored Event Object
var originalEventObject = $(that).data('eventObject');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
copiedEventObject.end = (new Date(date.getTime() + that.getAttribute("data-length") * 1000));
copiedEventObject.allDay = that.getAttribute("data-allDay") === "true" ? true : false;
// Add step to database
modifyProtocolStep.enqueue(eventStep);
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
// Read each sub-step of the DOM element to render multiple steps into a protocol
} else {
// retrieve the dropped element's stored Event Object
var originalEventObject = $(that).data('eventObject');
var timeTracker = date;
var i = 1;
// Get each item in the container and add them to the calendar
while(that.getAttribute("data-step"+i+"-allDay")){
// Create an object to add to the calendar
var eventStep = {};
eventStep.eventId = that.getAttribute("data-step"+i+"-event-id");
eventStep.instanceId = instanceId;
eventStep.verb = that.getAttribute("data-step"+i+"-verb");
eventStep.allDay = false;
eventStep.locked = true;
eventStep.active = that.getAttribute("data-step"+i+"-active");
eventStep.length = that.getAttribute("data-step"+i+"-length");
eventStep.stepNumber = that.getAttribute("data-step"+i+"-step-number");
eventStep.backgroundColor = "#" + instanceBgColor;
eventStep.textColor = "#fff";
eventStep.start = (new Date(timeTracker.getTime()));
eventStep.end = (new Date(timeTracker.getTime() + eventStep.length * 1000));
eventStep.notes = that.getAttribute("data-step"+i+"-notes").length > 0 ?
that.getAttribute("data-step"+i+"-notes") : 'There are no notes for this event.';
// Use this to decide the next step's .start
timeTracker = eventStep.end;
// Send data to database
modifyProtocolStep.enqueue(eventStep, "add");
// Add event to calendar
$('#calendar').fullCalendar('renderEvent', eventStep, true);
i++;
}
// Send all the queued data
modifyProtocolStep.send();
}
}
// The supplied renderer sucks
// Do Date math and rerender each dragged object
function renderUpdatedEvents(evObj, dayDelta, minDelta){
evObj._start = evObj.start = new Date(evObj.start.getTime() + minDelta * 60000 + dayDelta * 86400000);
evObj._end = evObj.end = new Date(evObj.end.getTime() + minDelta * 60000 + dayDelta * 86400000);
// Update modified event
$('#calendar').fullCalendar( 'updateEvent', event );
}
// Display an error at the top of the page
function displayTopError(e){
// Create nodes if the error isn't already shown
if(!document.getElementsByClassName("top-error")[0]){
var error = document.createElement("div");
error.className = "top-error";
error.innerHTML = e;
document.getElementsByTagName("body")[0].appendChild(error);
} else {
// If the error is already shown, simply change the text inside
var error = document.getElementsByClassName("top-error")[0];
error.innerHTML = e;
}
// Create an "X" element to close the error message
var closeError = document.createElement("div");
closeError.className = "close";
closeError.innerHTML = "X";
closeError.onclick = removeTopError;
error.appendChild(closeError);
// Show error
$(error).fadeIn(100, "linear");
// Auto hide error after time limit
setTimeout(function(){
// Make sure the element hasn't been closed already
if(document.getElementsByClassName("top-error")[0]){
removeTopError(true);
}
},10000);
}
// Remove the error at the top of the page. No easing for user-closed error, only auto-close
function removeTopError(easing){
easing = easing || false;
// remove element without fading effects
if(!easing){
document.getElementsByClassName("top-error")[0].parentNode.removeChild(document.getElementsByClassName("top-error")[0]);
} else {
// fade out and remove element
$(document.getElementsByClassName("top-error")[0]).fadeOut(200, function(){
document.getElementsByClassName("top-error")[0].parentNode.removeChild(document.getElementsByClassName("top-error")[0]);
});
}
}
// Functions for editing and saving notes for selected steps
var Notes = (function(){
var currentStepNode;
// This functions assumes that an element without notes
// has a data-notes value of "There are no notes for this event."
function editNotes(ele){
var formContainer = document.createElement("div"),
formContent = '',
header = '<h3>Edit Notes</h3>',
inputArea = '<textarea placeholder="Jot down some notes" autofocus></textarea>',
submitButton = '<input type="button" value="Update" onclick="BNB.calendar.Notes.submitEditNotes(this)">',
closeButton = '<span class="close" onclick="BNB.calendar.Notes.removeEditNotes(this.parentNode);">X</span>';
// If a dialog is already open, close it
if(document.getElementsByClassName("edit-notes-form")[0]){
removeEditNotes(document.getElementsByClassName("edit-notes-form")[0]);
}
// Track the clicked element
currentStepNode = ele.parentNode;
// Add notes to the textarea if notes exist
if(currentStepNode.getAttribute("data-notes") != "There are no notes for this event."){
inputArea = '<textarea autofocus>' +
currentStepNode.getAttribute("data-notes") +
'</textarea>';
}
// Assemble Notes dialog box
formContent = header + inputArea + submitButton + closeButton;
// Add a new "Edit Notes" dialog box to the page
formContainer.className = "edit-notes-form";
formContainer.innerHTML = formContent;
addEditNotes(ele, formContainer);
}
// Recieve edited notes and save them
function submitEditNotes(ele){
var popup = document.getElementsByClassName("edit-notes-form")[0],
updatedNotes = ele.parentNode.getElementsByTagName("textarea")[0].value;
if(!updatedNotes) updatedNotes = "There are no notes for this event."
// Update notes
currentStepNode.setAttribute("data-notes", updatedNotes);
// Save notes to database
modifyProtocolStep.enqueue( makeJsonFromNode(currentStepNode), "edit" );
// Remove popup
removeEditNotes(popup);
}
// Add element's edit notes popup
function addEditNotes(ele, formContainer){
document.getElementsByTagName("body")[0].appendChild(formContainer);
// Reposition the notes popup alongside the current node
var stepPos = currentStepNode.getBoundingClientRect();
formContainer.style.top = stepPos.top - 8 + "px";
// Switch popup to left side if it's editing a step on friday or saturday
if($(currentStepNode).hasClass("fri") || $(currentStepNode).hasClass("sat")){
formContainer.style.left = stepPos.left + 10 + "px";
if($(currentStepNode).hasClass("fri")) formContainer.className += " fri";
if($(currentStepNode).hasClass("sat")) formContainer.className += " sat";
} else{
formContainer.style.left = stepPos.left + 390 + "px";
}
// Show notes form
$(formContainer).fadeIn(100);
// Set editing attribute
currentStepNode.setAttribute("data-editing", "true");
}
// Remove element's edit notes popup
function removeEditNotes(ele){
// Hide notes form
$(ele).fadeOut(100, function(){
ele.parentNode.removeChild(ele);
});
// Unset editing attribute
currentStepNode.setAttribute("data-editing", "false");
// Clear reference
currentStepNode = null;
}
return{
editNotes : editNotes,
submitEditNotes : submitEditNotes,
addEditNotes : addEditNotes,
removeEditNotes : removeEditNotes
}
})();
var protocolLock = (function(){
function toggleLock(ele){
var instanceId = ele.parentNode.getAttribute("data-instance-id");
// Change both the DOM and the actual event data to toggle and track locked status
if(ele.className == "locked"){
// Edit DOM - instant data value/not persistant
$("[data-instance-id="+instanceId+"]").each(function(){
if(this.getElementsByClassName("locked")[0])
this.getElementsByClassName("locked")[0].className = "unlocked";
this.setAttribute("data-locked", 'false');
});
// Directly lock/unlock event data - persistant data value/not instant
var evList = $('#calendar').fullCalendar( 'clientEvents' );
for(ev in evList){
if(evList[ev].instanceId === instanceId)
evList[ev].locked = false;
}
} else {
// Edit DOM - instant data value/not persistant
$("[data-instance-id="+ele.parentNode.getAttribute("data-instance-id")+"]").each(function(){
if(this.getElementsByClassName("unlocked")[0])
this.getElementsByClassName("unlocked")[0].className = "locked";
this.setAttribute("data-locked",'true');
});
// Directly lock/unlock event data - persistant data value/not instant
var evList = $('#calendar').fullCalendar( 'clientEvents' );
for(ev in evList){
if(evList[ev].instanceId === instanceId)
evList[ev].locked = true;
}
}
}
// Show lock icons on protocol step hover
function show(ele){
var instanceId = ele.parentNode.getAttribute("data-instance-id");
$("[data-instance-id="+instanceId+"]").each(function(){
if(this.getElementsByClassName("locked")[0])
this.getElementsByClassName("locked")[0].style.display = "block";
if(this.getElementsByClassName("unlocked")[0])
this.getElementsByClassName("unlocked")[0].style.display = "block";
});
}
// Hide lock icons when not hovering on protocol step
function hide(ele){
var instanceId = ele.parentNode.getAttribute("data-instance-id");
$("[data-instance-id="+instanceId+"]").each(function(){
if(this == ele) return
if(this.getElementsByClassName("locked")[0])
this.getElementsByClassName("locked")[0].style.display = "";
if(this.getElementsByClassName("unlocked")[0])
this.getElementsByClassName("unlocked")[0].style.display = "";
});
}
return {
toggleLock : toggleLock,
show : show,
hide : hide
}
})();
// Showing right click menu
function rightClickMenu(e){
// For testing purposes!
if(disableRightClickMenu) return;
var clickedElement = window.event.srcElement,
targetElement, // The element to get information from
menuToShow,
body = document.getElementsByTagName("body")[0],
menu = document.createElement("div"),
copy = document.createElement("p"),
paste = document.createElement("p"),
undo = document.createElement("p"),
del = document.createElement("p"),
cancel = document.createElement("p");
// Clear the right click menu if it's already showing
if(document.getElementById("right-click-menu")){
var oldMenu = document.getElementById("right-click-menu");
oldMenu.parentNode.removeChild(oldMenu);
oldMenu = null;
}
//----------------------------------------------------------------//
// Supress normal right clicks if a day/step is right-clicked on //
//----------------------------------------------------------------//
// A STEP was clicked on
if (clickedElement.className == "fc-event-inner" || clickedElement.className == "edit-notes"){
targetElement = clickedElement.parentNode;
menuToShow = "copy";
}
else if(clickedElement.className == "fc-event-time" || clickedElement.className == "fc-event-title"){
targetElement = clickedElement.parentNode.parentNode;
menuToShow = "copy";
}
// A DAY was clicked on
else if( $(clickedElement).hasClass("fc-day")){
targetElement = clickedElement;
menuToShow = "paste";
}
else if( $(clickedElement).hasClass("fc-day-content") ){
targetElement = clickedElement.parentNode.parentNode;
menuToShow = "paste";
}
else if( $(clickedElement.parentNode).hasClass("fc-day-content") &&
clickedElement.parentNode.parentNode.parentNode.className.indexOf("fc-col") == -1){
targetElement = clickedElement.parentNode.parentNode.parentNode;
menuToShow = "paste";
}
else if( $(clickedElement.parentNode).hasClass("fc-day")){
targetElement = clickedElement.parentNode;
menuToShow = "paste";
}
// An HOUR was clicked on
else if( clickedElement.className.indexOf("week-day") !== -1){
targetElement = clickedElement;
menuToShow = "paste";
}
// Nothing of interest was clicked on
else {
// Show normal right click
document.oncontextmenu = function(){return true;}
return;
}
// Hide right click menu
document.oncontextmenu = function(){return false;}
// Place menu at the mouse cursor's position
menu.style.top = e.y + "px";
menu.style.left = e.x + "px";
menu.id = "right-click-menu";
paste.innerHTML = "Paste Protocol";
copy.innerHTML = "Copy Protocol";
del.innerHTML = "Delete Protocol"
undo.innerHTML = "Undo";
cancel.innerHTML = "Cancel";
// Copy structure of protocol
copy.onclick = function(){
protocolStructure.copy(targetElement);
body.removeChild(menu);
body.onclick="";
};
// Delete structure of protocol
del.onclick = function(){
protocolStructure.del(targetElement.getAttribute("data-instance-id"));
body.removeChild(menu);
body.onclick="";
};
// Paste structure of protocol
paste.onclick = function(){
protocolStructure.paste(targetElement, null);
body.removeChild(menu);
body.onclick="";
};
// Paste structure of protocol
undo.onclick = function(){
protocolStructure.undo(targetElement);
body.removeChild(menu);
body.onclick="";
};
// Clear right click menu -- this also handles clicking "Cancel"
body.onclick = function(){
body.removeChild(menu);
body.onclick="";
};
if(menuToShow == "copy") menu.appendChild(copy);
if(menuToShow == "copy") menu.appendChild(del);
if(menuToShow == "paste") menu.appendChild(paste);
if(menuToShow == "paste") menu.appendChild(undo);
menu.appendChild(cancel);
body.appendChild(menu)
}
// Copy, Paste, Undo functionality for right click menu
var protocolStructure = (function (){
var copiedStructure = [],
lastDatePastedInto; // Used for Undo
function copy(ele){
var instanceId = ele.getAttribute("data-instance-id");
var selector = "[data-instance-id="+ instanceId +"]";
// Only select the current view's steps
if(ele.className.indexOf("fc-event-vert") !== -1) selector = ".fc-event-vert" + selector;
if(ele.className.indexOf("fc-event-hori") !== -1) selector = ".fc-event-hori" + selector;
// Get each step in the protocol and add it to copiedStructure
$(selector).each(function(){
var copiedProtocolStep = {
verb: this.getElementsByClassName("fc-event-title")[0].innerHTML,
backgroundColor: this.getAttribute("data-bg-color"),
allDay: false,
start: this.getAttribute("data-event-start"),
active: this.getAttribute("data-active"),
end: this.getAttribute("data-event-end"),
container: false,
eventId: this.getAttribute("data-event-id"),
stepNumber: this.getAttribute("data-step-number"),
notes: this.getAttribute("data-notes")
};
// Add copied step to the copied protocol structure
copiedStructure[copiedProtocolStep.stepNumber] = copiedProtocolStep;
});
}
// Paste structure of a protocol to another date
function paste(clickedEle, dateReference){
var clickedDate = new Date(clickedEle.getAttribute("data-date"));
var originalStartDates = [];
// Used for Undo functionality -- without this line the Undo will increment
// the Paste's date position by a day each call
if(dateReference) clickedDate = new Date(dateReference.setDate(dateReference.getDate() - 1));
// Record each element's start date since they're overwrittern
// in the next parts
for(var i = 1; i < copiedStructure.length; i++){
originalStartDates[i] = new Date(copiedStructure[i].start).getTime();
}
// The date returned from clicking on an empty element
// returns an unfavorable time, set it to the start
// of the first step
// Month view
if(clickedEle.className.indexOf("fc-day") !== -1){
clickedDate.setDate(clickedDate.getDate() + 1);
clickedDate.setHours(new Date(copiedStructure[1].start).getHours());
clickedDate.setMinutes(new Date(copiedStructure[1].start).getMinutes());
}
// Week view
else if(clickedEle.className.indexOf("week-day") !== -1){
clickedDate.setDate(clickedDate.getDate());
}
// Remember the date in case the user uses Undo
lastDatePastedInto = new Date(clickedDate);
// Create an instance Id for the new protocol
var instanceId;
// Create a background color based on unique ID
// But make sure it's a LIGHT color that can show white text! (ie 5-c hex)
do{
instanceId = "xxxxxx".replace(/[x]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
while(parseInt(instanceId[0], 16) < 5 || parseInt(instanceId[0], 16) > 12 ||
parseInt(instanceId[2], 16) < 5 || parseInt(instanceId[2], 16) > 12 ||
parseInt(instanceId[4], 16) < 5 || parseInt(instanceId[4], 16) > 12 )
var instanceBgColor = instanceId[0].toString() +
instanceId[2].toString() +
instanceId[4].toString();
// Set each step's start and end dates
for(i = 1; i < copiedStructure.length; i++){
if(i == 1){ // First step
copiedStructure[i].start = clickedDate;
copiedStructure[i].end =
new Date(
clickedDate.getTime() +
new Date(copiedStructure[i].end).getTime() -
originalStartDates[i]
);
} else { // Not the first step
copiedStructure[i].start =
new Date(
new Date(copiedStructure[i].start).getTime() - // Time Between
originalStartDates[i-1] + // this ele and last
copiedStructure[i-1].start.getTime()
);
copiedStructure[i].end =
new Date(
copiedStructure[i].start.getTime() +
new Date(copiedStructure[i].end).getTime() -
originalStartDates[i]
);
}
// Set values common to the protocol
copiedStructure[i].instanceId = instanceId;
copiedStructure[i].textColor = "#fff";
copiedStructure[i].backgroundColor = "#" + instanceBgColor;
// Add elements to the calendar
$('#calendar').fullCalendar('renderEvent', copiedStructure[i], true);
}
}
// Undo protocol paste/delete that was last used
function undo(ele){
var instanceId = copiedStructure[1].instanceId;
if($("[data-instance-id="+ instanceId +"]").length > 0){
protocolStructure.del(instanceId);
} else {
paste(ele, lastDatePastedInto);
}
}
// Remove protocol that was last added
function del(id){
$("[data-instance-id="+ id +"]").each(function(){
$('#calendar').fullCalendar("removeEvents", this.getAttribute("data-fc-id"));
});
}
return {
copy : copy,
paste : paste,
del : del,
undo : undo
}
})();
// Add / Edit / Remove protocol steps by using Ajax calls
// Args: JSON Event object, Action string: add edit remove
// ## Look into cookies to store locally in case user closes window
// ## Check once a second if queue has items?
var modifyProtocolStep = (function(){
var queue = [],
hasCallFinished = true;
function enqueue(stepData){
queue.push(stepData);
}
function send(){
// Nothing to do
if(!hasCallFinished || queue.length < 1) return;
// when done, call send() again
}
return {
enqueue : enqueue,
send : send
}
})();
// Return Json created from scraping DOM node's data
function makeJsonFromNode(node){
return {
verb : node.getElementsByClassName("fc-event-title")[0].innerHTML,
eventId : node.getAttribute("data-event-id"),
instanceId : node.getAttribute("data-instance-id"),
stepNumber : node.getAttribute("data-step-number"),
start : node.getAttribute("data-event-start"),
end : node.getAttribute("data-event-end"),
notes : node.getAttribute("data-notes"),
active : node.getAttribute("data-active"),
bgColor : node.getAttribute("data-bg-color"),
locked : node.getAttribute("data-locked") || true,
container : false,
allDay : false,
length : (new Date(node.getAttribute("data-event-end")).getTime() -
new Date(node.getAttribute("data-event-start")).getTime())/1000
};
}
// Return the HTML needed to display an event(action) on the calendar
// Args: eventObject, objects + functions from fullCalendar's scope
function makeHtmlFromJson(event, classes, seg, skinCss, htmlEscape, formatDates, opt){
var weekDays = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
var isLocked = (event.locked == "true" || event.locked == true) ? "locked" : "unlocked";
var html =
// Classes
" class='" + classes.join(' ') + " " +
weekDays[new Date(event._start).getDay()] + "'" +
// Data attributes
" data-step-number='" + event.stepNumber + "'" +
" data-event-id='" + event.eventId + "'" +
" data-event-start='" + event._start + "'" +
" data-event-end='" + event._end + "'" +
" data-active='" + event.active + "'" +
" data-notes='" + event.notes + "'" +
" data-bg-color='" + event.backgroundColor + "'" +
" data-instance-id='" + event.instanceId + "'" +
" data-fc-id='" + event._id + "'" +
" data-locked='" + event.locked + "'" +
// Css positioning
" style='position:absolute;z-index:8;top:" + seg.top +
"px;left:" + seg.left + "px;border-color:"+ event.backgroundColor + ";" + skinCss + "'" +
">" +
// Lock + Notes Icon
"<span class='"+ isLocked +"' onclick='BNB.calendar.protocolLock.toggleLock(this);' "+
"onmouseover='BNB.calendar.protocolLock.show(this)' " +
"onmouseout='BNB.calendar.protocolLock.hide(this)'></span>" +
"<span class='edit-notes' onclick='BNB.calendar.Notes.editNotes(this)'></span>"+
// Title + Date
"<div class='fc-event-inner'>" +
"<div class='fc-event-time'>" +
htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) +
"</div>" +
"<div class='fc-event-title'>" +
htmlEscape(event.verb || event.title) +
"</div>";
// Add padding to start + end for passive events
if(event.active == "false" && classes.join(' ').indexOf('vert') != -1){
html +=
"<div class='passive-padding-start' style='background-color:" +
event.backgroundColor + "'></div>" +
"<div class='passive-padding-end' style='background-color:" +
event.backgroundColor + "'></div>";
}
html +=
"</div>" + // .fc-event-inner
"<div class='fc-event-bg'></div>";
return html;
}
return {
makeJsonFromNode : makeJsonFromNode,
displayTopError : displayTopError,
removeTopError : removeTopError,
getEvents : getEvents,
dropEventHandler : dropEventHandler,
protocolLock : protocolLock,
Notes : Notes,
rightClickMenu : rightClickMenu,
renderUpdatedEvents : renderUpdatedEvents,
makeHtmlFromJson : makeHtmlFromJson
}
})();
|
var App, templateLoader, storage;
App = {};
App.Controllers = {};
App.Models = {};
//inicio de nuestro cargador dinamico de plantillas
templateLoader = new TemplateLoader(Handlebars, { withCache : false });
storage = new Storage({ method : "session" });
Handlebars.render = function(string, data){
return Handlebars.compile(string)(data);
};
(function(){
var cookies = document.cookie.split(";"),
cookieKeys = {},
fooKey = $("#foo").val();
cookies.forEach(function(token){
var cookie = token.split("=");
cookieKeys[cookie[0]] = cookie[1];
});
$.ajaxSetup({
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", fooKey);
}
});
})();
|
// Styles
import '../../stylus/components/_messages.styl'
// Mixins
import Colorable from '../../mixins/colorable'
import Themeable from '../../mixins/themeable'
/* @vue/component */
export default {
name: 'v-messages',
mixins: [Colorable, Themeable],
props: {
value: {
type: Array,
default: () => ([])
}
},
methods: {
genChildren () {
return this.$createElement('transition-group', {
staticClass: 'v-messages__wrapper',
attrs: {
name: 'message-transition',
tag: 'div'
}
}, this.value.map(m => this.genMessage(m)))
},
genMessage (key) {
return this.$createElement('div', {
staticClass: 'v-messages__message',
key,
domProps: {
innerHTML: key
}
})
}
},
render (h) {
return h('div', this.setTextColor(this.color, {
staticClass: 'v-messages',
class: this.themeClasses
}), [this.genChildren()])
}
}
|
(function ($) {
/**
* Form behavior for Panopoly Admin
*/
Drupal.behaviors.panopolyAdmin = {
attach: function (context, settings) {
var width = $('#node-edit #edit-title').width() - $('#node-edit .form-item-path-alias label').width() - 3;
$('#node-edit .form-item-path-alias input').css('width', width);
if ($('#node-edit .form-item-body-und-0-value label').html() == 'Body <span class="form-required" title="This field is required.">*</span>') {
$('#node-edit .form-item-body-und-0-value label').hide();
}
if ($('#node-edit .form-item-field-featured-image-und-0-alt label')) {
$('#node-edit .form-item-field-featured-image-und-0-alt label').html('Alt Text');
}
}
}
})(jQuery);
|
(function($) {
var getTime = function() { return new Date().getTime(); };
var SafeForm = function(element, options) {
this.initialize(element, options);
}
SafeForm.prototype = {
constructor: SafeForm,
initialize: function(element, options) {
this.$element = $(element);
this.options = $.extend({}, $.fn.safeform.defaults, options);
this.disabled = false;
this.submittedAt = getTime();
this.$element.submit($.proxy(this.prevenDoubleSubmit, this));
},
disable: function() {
this.disabled = true;
},
complete: function() {
this.disabled = false;
},
submit: function() {
this.$element.submit();
},
isAutoRefreshed: function() {
var o = this.options,
now = getTime();
return o.timeout && now - this.submittedAt > o.timeout;
},
prevenDoubleSubmit: function(event) {
var o = this.options;
if (this.disabled && !this.isAutoRefreshed()) return false;
this.disable();
this.submittedAt = getTime();
if ($.isFunction(o.submit)) {
return o.submit.call(this.$element, event);
}
}
};
$.fn.safeform = function(option) {
return this.each(function () {
var $this = $(this),
data = $this.data('safeform'),
options = typeof option == 'object' && option;
if (!data) $this.data('safeform', (data = new SafeForm(this, options)));
if (typeof option == 'string') data[option]();
});
};
$.fn.safeform.Constructor = SafeForm;
$.fn.safeform.defaults = {
timeout: null,
submit: null
};
})(window.jQuery); |
/**
* Created by marco on 10/01/2015.
*/
module.exports = function (grunt) {
grunt.registerMultiTask('stripdefine', 'Strip define call from dist file', function () {
this.filesSrc.forEach(function (filepath) {
// Remove `define('js-init' ...)` and `define('js-build' ...)`
var mod = grunt.file.read(filepath).replace(/define\("js-(init|build)", function\(\)\{\}\);/g, '');
grunt.file.write(filepath, mod);
});
});
}; |
"use strict";
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 __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var sidebar_routes_config_1 = require('../.././sidebar/sidebar-routes.config');
var sidebar_metadata_1 = require('../.././sidebar/sidebar.metadata');
var common_1 = require('@angular/common');
var NavbarComponent = (function () {
function NavbarComponent(location) {
this.location = location;
}
NavbarComponent.prototype.ngOnInit = function () {
this.listTitles = sidebar_routes_config_1.ROUTES.filter(function (listTitle) { return listTitle.menuType !== sidebar_metadata_1.MenuType.BRAND; });
};
NavbarComponent.prototype.getTitle = function () {
var titlee = this.location.prepareExternalUrl(this.location.path());
if (titlee.charAt(0) === '#') {
titlee = titlee.slice(2);
}
for (var item = 0; item < this.listTitles.length; item++) {
if (this.listTitles[item].path === titlee) {
return this.listTitles[item].title;
}
}
return 'Dashboard';
};
NavbarComponent = __decorate([
core_1.Component({
moduleId: module.id,
selector: 'navbar-cmp',
templateUrl: 'navbar.component.html'
}),
__metadata('design:paramtypes', [common_1.Location])
], NavbarComponent);
return NavbarComponent;
}());
exports.NavbarComponent = NavbarComponent;
//# sourceMappingURL=navbar.component.js.map |
define({
"feedbackStyleLabel": "Στιλ σχολίων για αποστάσεις και κατευθύνσεις",
"showTabLabel": "Εμφάνιση καρτέλας",
"feedbackShapeLabel": "Σχήμα σχολίων",
"lineColorLabel": "Χρώμα γραμμής",
"lineWidthLabel": "Πλάτος γραμμής",
"feedbackLabel": "Ετικέτα σχολίων",
"textColorLabel": "Χρώμα κειμένου",
"textSizeLabel": "Μέγεθος κειμένου",
"tabErrorMessage": "Πρέπει να παραμετροποιήσετε το widget έτσι ώστε να εμφανίζεται τουλάχιστον μία καρτέλα.",
"lineLabel": "Γραμμή",
"circleLabel": "Κύκλος",
"ellipseLabel": "Έλλειψη",
"ringsLabel": "Δακτύλιοι",
"transparency": "Διαφάνεια"
}); |
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.0-rc.5-master-2ddeb91
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.divider
* @description Divider module!
*/
angular.module('material.components.divider', [
'material.core'
])
.directive('mdDivider', MdDividerDirective);
/**
* @ngdoc directive
* @name mdDivider
* @module material.components.divider
* @restrict E
*
* @description
* Dividers group and separate content within lists and page layouts using strong visual and spatial distinctions. This divider is a thin rule, lightweight enough to not distract the user from content.
*
* @param {boolean=} md-inset Add this attribute to activate the inset divider style.
* @usage
* <hljs lang="html">
* <md-divider></md-divider>
*
* <md-divider md-inset></md-divider>
* </hljs>
*
*/
function MdDividerDirective($mdTheming) {
return {
restrict: 'E',
link: $mdTheming
};
}
MdDividerDirective.$inject = ["$mdTheming"];
})(window, window.angular); |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var TiSocialPinterestCircular = function TiSocialPinterestCircular(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'm20 35c-8.3 0-15-6.7-15-15s6.7-15 15-15 15 6.7 15 15-6.7 15-15 15z m0-26.7c-6.4 0-11.7 5.3-11.7 11.7s5.3 11.7 11.7 11.7 11.7-5.3 11.7-11.7-5.3-11.7-11.7-11.7z m0.6 5c-4.2 0-6.2 3-6.2 5.4 0 1.5 0.5 2.9 1.7 3.3 0.2 0.1 0.4 0.1 0.5-0.2 0-0.1 0.1-0.5 0.2-0.7 0-0.2 0-0.3-0.2-0.4-0.3-0.5-0.5-1-0.5-1.7 0-2.2 1.6-4.2 4.2-4.2 2.3 0 3.6 1.4 3.6 3.3 0 2.5-1.1 4.6-2.7 4.6-0.9 0-1.6-0.7-1.4-1.6 0.3-1.1 0.8-2.3 0.8-3.1 0-0.7-0.4-1.3-1.2-1.3-0.9 0-1.7 0.9-1.7 2.2 0 0.8 0.3 1.4 0.3 1.4l-1.1 4.7c-0.3 1.4 0 3.1 0 3.3 0 0.1 0.1 0.1 0.2 0.1 0.1-0.2 1.2-1.5 1.5-2.9 0.2-0.4 0.7-2.4 0.7-2.4 0.3 0.6 1.1 1.1 2.1 1.1 2.8 0 4.6-2.5 4.6-5.9 0-2.6-2.1-5-5.4-5z' })
)
);
};
exports.default = TiSocialPinterestCircular;
module.exports = exports['default']; |
/*!
* Module dependencies.
*/
var Collection = require('./collection').Collection,
Cursor = require('./cursor').Cursor,
DbCommand = require('./commands/db_command').DbCommand;
/**
* Allows the user to access the admin functionality of MongoDB
*
* @class Represents the Admin methods of MongoDB.
* @param {Object} db Current db instance we wish to perform Admin operations on.
* @return {Function} Constructor for Admin type.
*/
function Admin(db) {
this.db = db;
};
/**
* Retrieve the server information for the current
* instance of the db client
*
* @param {Function} callback Callback function of format `function(err, result) {}`.
* @return {null} Returns no result
* @api public
*/
Admin.prototype.buildInfo = function(callback) {
this.serverInfo(callback);
}
/**
* Retrieve the server information for the current
* instance of the db client
*
* @param {Function} callback Callback function of format `function(err, result) {}`.
* @return {null} Returns no result
* @api private
*/
Admin.prototype.serverInfo = function(callback) {
var self = this;
var command = {buildinfo:1};
this.command(command, function(err, doc) {
if(err != null) return callback(err, null);
return callback(null, doc.documents[0]);
});
}
/**
* Retrieve the current profiling Level for MongoDB
*
* @param {Function} callback Callback function of format `function(err, result) {}`.
* @return {null} Returns no result
* @api public
*/
Admin.prototype.profilingLevel = function(callback) {
var self = this;
var command = {profile:-1};
this.command(command, function(err, doc) {
doc = doc.documents[0];
if(err == null && (doc.ok == 1 || typeof doc.was === 'number')) {
var was = doc.was;
if(was == 0) {
callback(null, "off");
} else if(was == 1) {
callback(null, "slow_only");
} else if(was == 2) {
callback(null, "all");
} else {
callback(new Error("Error: illegal profiling level value " + was), null);
}
} else {
err != null ? callback(err, null) : callback(new Error("Error with profile command"), null);
}
});
};
/**
* Ping the MongoDB server and retrieve results
*
* @param {Object} [options] Optional parameters to the command.
* @param {Function} callback Callback function of format `function(err, result) {}`.
* @return {null} Returns no result
* @api public
*/
Admin.prototype.ping = function(options, callback) {
// Unpack calls
var args = Array.prototype.slice.call(arguments, 0);
callback = args.pop();
options = args.length ? args.shift() : {};
// Set self
var self = this;
var databaseName = this.db.databaseName;
this.db.databaseName = 'admin';
this.db.executeDbCommand({ping:1}, options, function(err, result) {
self.db.databaseName = databaseName;
return callback(err, result);
})
}
/**
* Authenticate against MongoDB
*
* @param {String} username The user name for the authentication.
* @param {String} password The password for the authentication.
* @param {Function} callback Callback function of format `function(err, result) {}`.
* @return {null} Returns no result
* @api public
*/
Admin.prototype.authenticate = function(username, password, callback) {
var self = this;
var databaseName = this.db.databaseName;
this.db.databaseName = 'admin';
this.db.authenticate(username, password, function(err, result) {
self.db.databaseName = databaseName;
return callback(err, result);
})
}
/**
* Logout current authenticated user
*
* @param {Object} [options] Optional parameters to the command.
* @param {Function} callback Callback function of format `function(err, result) {}`.
* @return {null} Returns no result
* @api public
*/
Admin.prototype.logout = function(callback) {
var self = this;
var databaseName = this.db.databaseName;
this.db.databaseName = 'admin';
this.db.logout(function(err, result) {
return callback(err, result);
})
self.db.databaseName = databaseName;
}
/**
* Add a user to the MongoDB server, if the user exists it will
* overwrite the current password
*
* Options
* - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
*
* @param {String} username The user name for the authentication.
* @param {String} password The password for the authentication.
* @param {Object} [options] additional options during update.
* @param {Function} callback Callback function of format `function(err, result) {}`.
* @return {null} Returns no result
* @api public
*/
Admin.prototype.addUser = function(username, password, options, callback) {
var self = this;
var args = Array.prototype.slice.call(arguments, 2);
callback = args.pop();
options = args.length ? args.shift() : {};
var self = this;
var databaseName = this.db.databaseName;
this.db.databaseName = 'admin';
this.db.addUser(username, password, options, function(err, result) {
self.db.databaseName = databaseName;
return callback(err, result);
})
}
/**
* Remove a user from the MongoDB server
*
* Options
* - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB.
*
* @param {String} username The user name for the authentication.
* @param {Object} [options] additional options during update.
* @param {Function} callback Callback function of format `function(err, result) {}`.
* @return {null} Returns no result
* @api public
*/
Admin.prototype.removeUser = function(username, options, callback) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
callback = args.pop();
options = args.length ? args.shift() : {};
var self = this;
var databaseName = this.db.databaseName;
this.db.databaseName = 'admin';
this.db.removeUser(username, options, function(err, result) {
self.db.databaseName = databaseName;
return callback(err, result);
})
}
/**
* Set the current profiling level of MongoDB
*
* @param {String} level The new profiling level (off, slow_only, all)
* @param {Function} callback Callback function of format `function(err, result) {}`.
* @return {null} Returns no result
* @api public
*/
Admin.prototype.setProfilingLevel = function(level, callback) {
var self = this;
var command = {};
var profile = 0;
if(level == "off") {
profile = 0;
} else if(level == "slow_only") {
profile = 1;
} else if(level == "all") {
profile = 2;
} else {
return callback(new Error("Error: illegal profiling level value " + level));
}
// Set up the profile number
command['profile'] = profile;
// Execute the command to set the profiling level
this.command(command, function(err, doc) {
doc = doc.documents[0];
if(err == null && (doc.ok == 1 || typeof doc.was === 'number')) {
return callback(null, level);
} else {
return err != null ? callback(err, null) : callback(new Error("Error with profile command"), null);
}
});
};
/**
* Retrive the current profiling information for MongoDB
*
* @param {Function} callback Callback function of format `function(err, result) {}`.
* @return {null} Returns no result
* @api public
*/
Admin.prototype.profilingInfo = function(callback) {
var self = this;
var databaseName = this.db.databaseName;
this.db.databaseName = 'admin';
try {
new Cursor(this.db, new Collection(this.db, DbCommand.SYSTEM_PROFILE_COLLECTION), {}).toArray(function(err, items) {
return callback(err, items);
});
} catch (err) {
return callback(err, null);
}
self.db.databaseName = databaseName;
};
/**
* Execute a db command against the Admin database
*
* @param {Object} command A command object `{ping:1}`.
* @param {Object} [options] Optional parameters to the command.
* @param {Function} callback Callback function of format `function(err, result) {}`.
* @return {null} Returns no result
* @api public
*/
Admin.prototype.command = function(command, options, callback) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
callback = args.pop();
options = args.length ? args.shift() : {};
// Execute a command
this.db.executeDbAdminCommand(command, options, function(err, result) {
// Ensure change before event loop executes
return callback != null ? callback(err, result) : null;
});
}
/**
* Validate an existing collection
*
* @param {String} collectionName The name of the collection to validate.
* @param {Object} [options] Optional parameters to the command.
* @param {Function} callback Callback function of format `function(err, result) {}`.
* @return {null} Returns no result
* @api public
*/
Admin.prototype.validateCollection = function(collectionName, options, callback) {
var args = Array.prototype.slice.call(arguments, 1);
callback = args.pop();
options = args.length ? args.shift() : {};
var self = this;
var command = {validate: collectionName};
var keys = Object.keys(options);
// Decorate command with extra options
for(var i = 0; i < keys.length; i++) {
if(options.hasOwnProperty(keys[i])) {
command[keys[i]] = options[keys[i]];
}
}
this.db.executeDbCommand(command, function(err, doc) {
if(err != null) return callback(err, null);
doc = doc.documents[0];
if(doc.ok == 0) {
return callback(new Error("Error with validate command"), null);
} else if(doc.result != null && doc.result.constructor != String) {
return callback(new Error("Error with validation data"), null);
} else if(doc.result != null && doc.result.match(/exception|corrupt/) != null) {
return callback(new Error("Error: invalid collection " + collectionName), null);
} else if(doc.valid != null && !doc.valid) {
return callback(new Error("Error: invalid collection " + collectionName), null);
} else {
return callback(null, doc);
}
});
};
/**
* List the available databases
*
* @param {Function} callback Callback function of format `function(err, result) {}`.
* @return {null} Returns no result
* @api public
*/
Admin.prototype.listDatabases = function(callback) {
// Execute the listAllDatabases command
this.db.executeDbAdminCommand({listDatabases:1}, {}, function(err, result) {
if(err != null) {
callback(err, null);
} else {
callback(null, result.documents[0]);
}
});
}
/**
* @ignore
*/
exports.Admin = Admin;
|
import React from 'react'
import Icon from 'react-icon-base'
const GoMail = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m2.5 7.5v25h35v-25h-35z m30 2.5l-12.5 10.3-12.5-10.3h25z m-27.5 2.5l9.8 7.5-9.8 7.5v-15z m2.5 17.5l9.9-8.1 2.6 2 2.6-2 9.9 8.1h-25z m27.5-2.5l-9.9-7.5 9.9-7.5v15z"/></g>
</Icon>
)
export default GoMail
|
var gulp = require('gulp'),
concat = require('gulp-concat'),
rename = require("gulp-rename"),
uglify = require('gulp-uglify');
gulp.task('scripts', function() {
return gulp
.src([
'./src/dropdown/index.js',
'./src/dropdown/dropdown/*.js',
'./src/dropdown/dropdown-item/*.js',
'./src/modal/index.js',
'./src/modal/directive.js',
'./src/popup/index.js',
'./src/popup/directive.js',
'./src/checkbox/index.js',
'./src/checkbox/directive.js',
'./src/radio/index.js',
'./src/radio/directive.js',
'./src/progress/index.js',
'./src/progress/directive.js',
'./src/tabs/index.js',
'./src/tabs/tab/*.js',
'./src/tabs/tabset/*.js',
'./src/index.js'
])
.pipe(concat('semanticular.js'))
.pipe(gulp.dest('./dist/'))
.pipe(uglify())
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest('./dist/'));
});
gulp.task('default', ['scripts']);
|
;
(function() {
window.require(["ace/snippets/cobol"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})(); |
'use strict';
var _ = require('underscore');
module.exports = (function() {
var self = {};
self.vobject = require('./vobject');
/**
* Split ICS text by CRLF and merge folded lines
*
* CRLF (Carriage Return Line Feed) is defined as the sequence `\r\n`
* Folded lines are defined as a CLRF followed by whitespace character
*
* @param {String} ics text to be split into lines
* @return {Array} lines parsed from the ics
*/
self.splitICS = function(ics) {
var unfoldedLines = [];
_.each(ics.split(/[\r\n]{1,2}/), function(line) {
if (line.length > 0) {
if (/[ \t]/.test(line[0])) {
// Line Began with a Space or Tab, Fold with Previous Line
unfoldedLines[unfoldedLines.length - 1] = unfoldedLines[unfoldedLines.length - 1] + line.slice(1);
}
else {
// Save Line
unfoldedLines.push(line);
}
}
});
return unfoldedLines;
};
/**
* Parse component string into vobject component
* @param {String} componentStr to be parsed
* @return {Object} vobject representation of the parsed string
*/
self.parseComponent = function(componentStr) {
var componentName = componentStr.split(':')[1];
switch (componentName) {
case 'VCALENDAR':
var calendarComponent = self.vobject.calendar();
return calendarComponent;
case 'VEVENT':
var eventComponent = self.vobject.event();
return eventComponent;
case 'VTODO':
var todoComponent = self.vobject.todo();
return todoComponent;
case 'VALARM':
var alarmComponent = self.vobject.alarm();
return alarmComponent;
case 'VCARD':
var cardComponent = self.vobject.card();
return cardComponent;
default:
var component = self.vobject.component(componentName);
return component;
}
};
/**
* Parse property string into vobject property
* @param {String} propertyStr to be parsed
* @return {Object} vobject representation of the parsed string
*/
self.parseProperty = function(propertyStr) {
var propertyName = propertyStr.split(':')[0].split(';')[0].toUpperCase();
switch (propertyName) {
case 'ATTENDEE':
var attendeeProperty = self.vobject.attendee();
attendeeProperty.parseICS(propertyStr);
return attendeeProperty;
case 'ORGANIZER':
var organizerProperty = self.vobject.organizer();
organizerProperty.parseICS(propertyStr);
return organizerProperty;
default:
var property = self.vobject.property();
property.parseICS(propertyStr);
return property;
}
};
/**
* Parses ICS text into vobject components and properties
* @param {String} ics text to be parsed
* @return {Object} base vobject component parsed from ics
*/
self.parseICS = function(ics) {
var lines = self.splitICS(ics);
var component = null;
_.each(lines, function(line) {
var key = line.split(':')[0];
if (key === 'BEGIN') {
// BEGIN Component
if (component === null) {
// Base Component
var baseComponent = self.parseComponent(line);
baseComponent._parent = baseComponent;
component = baseComponent;
}
else {
// Attach Sub-Component
var subComponent = self.parseComponent(line);
subComponent._parent = component;
component.pushComponent(subComponent);
component = subComponent;
}
}
else if (key === 'END') {
// END Component
var parent = component._parent;
// Delete Parent Reference to maintain non-circular structure
delete component._parent;
component = parent;
}
else {
// Property
var property = self.parseProperty(line);
component.pushProperty(property);
}
});
return component;
};
return self;
}());
|
'use strict';
console.log(require.config);
require.config({
// 非AMD模块的js使用shim配置导出
shim: {
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
}
},
// 根据路径定义别名 alias
paths: {
jquery: 'vendor/jquery',
underscore: 'vendor/underscore',
backbone: 'vendor/backbone'
}
});
require(['test'], function(TEST) {
console.log(TEST.a);
}); |
import express from 'express';
import config from 'config';
import mongo from 'mongodb';
import Grid from 'gridfs-stream';
import httpError from '../helper/httpError';
import ZipStream from 'zip-stream';
const router = express.Router();
let database = undefined;
let gfs = undefined;
// connect to MongoDB
mongo.MongoClient.connect(config.database.connection, (err, db) => {
if (err) {
throw err;
}
database = db;
gfs = new Grid(database, mongo);
});
/* GET home page. */
router.get('/', (req, res) => {
res.render('index', {
title: 'nodefilestore'
});
});
function handleMultipleFiles(files, res) {
const archive = new ZipStream();
archive.on('error', (error) =>{
throw error;
});
// prepare header
res.setHeader('Content-disposition', 'attachment; filename=bundle.zip');
res.setHeader('Content-type', 'application/zip');
archive.pipe(res);
const zipFile = (fileIndex) => {
if (fileIndex >= files.length) {
archive.finalize();
return;
}
const currentFile = files[fileIndex];
const readStream = gfs.createReadStream({ _id: currentFile._id });
archive.entry(readStream, {
name: currentFile.filename
}, (err) => {
if (err) {
throw err;
}
// add next entry
const newFileIndex = fileIndex + 1;
zipFile(newFileIndex);
});
};
zipFile(0);
}
router.get('/download/:token', (req, res, next) => {
const now = new Date();
database
.collection('uploads')
.find({
'token': req.params.token,
'expirationDate': { '$gte': now }
})
.limit(1)
.next((err, upload) => {
if (err) {
return next(httpError.createError(500, err));
}
if (!upload) { // download token not found or expired
const fileNotFoundError = httpError.createError(404);
fileNotFoundError.isFromDownloadRoute = true;
return next(fileNotFoundError);
}
const fileIds = upload.files;
gfs
.files
.find({ '_id': { $in: fileIds }})
.toArray((error, files) => {
if (error) {
return next(httpError.createError(500, error));
}
if (!files || files.length === 0) { // file(s) not found
const fileNotFoundError = httpError.createError(404);
fileNotFoundError.isFromDownloadRoute = true;
return next(fileNotFoundError);
}
if (files.length === 1) { // single file
const file = files[0];
// stream download
res.setHeader('Content-disposition', 'attachment; filename=' + file.filename);
res.setHeader('Content-type', file.contentType);
res.setHeader('Content-length', file.length);
const readStream = gfs.createReadStream({ _id: file._id });
readStream.pipe(res);
}
else { // multiple files
handleMultipleFiles(files, res);
}
});
});
});
export default router;
|
function _foo(x) {
console.log(x);
debugger;
}
// ---
// Found console.log (2:2)
// Found debugger statement (3:2)
|
import Ember from 'ember';
import {module, test} from 'qunit';
import PostControllerMixin from 'rescue-mission/mixins/post-controller';
module('PostControllerMixin');
// Replace this with your real tests.
test('it works', function(assert) {
var PostControllerObject = Ember.Object.extend(PostControllerMixin);
var subject = PostControllerObject.create();
assert.ok(subject);
});
|
import test from 'ava'
import fse from 'fs-extra'
import Promise from 'bluebird'
const fs = Promise.promisifyAll(fse)
const tmpdir = require('os').tmpdir()
import { gatsby } from '../support'
test('calling gatsby new succesfully creates new site from default starter', async t => {
const sitePath = `${tmpdir}/gatsby-default-starter`
await fs.remove(sitePath)
const noArgs = await gatsby(['new', sitePath])
const file = await fs.statAsync(`${sitePath}/html.js`)
t.is(noArgs.code, 0)
t.truthy(file)
})
|
#!/usr/bin/env node
var fs = require('fs');
var pathlib = require('path');
var ejs = require('ejs');
var markextend = require('markextend');
var codemirror = require('codemirror-highlight');
markextend.setOptions({
// 代码高亮
highlight: function(code, lang) {
if(lang && !codemirror.modes[lang]) {
if(lang === 'coffee') lang = 'coffeescript';
if(lang === 'json') lang = 'javascript';
if(lang === 'html') lang = 'xml';
if(lang === 'rgl') lang = 'xml';
if(lang === 'console') return code;
try {
codemirror.loadMode(lang);
} catch(e) {
console.error(e);
}
}
if(codemirror.modes[lang])
return codemirror.highlight(code, {mode: lang});
else
return code;
}
});
// var sitemap = require('./sitemap.json');
var premark = require('./premark.js');
var jsdoc = require('./jsdoc.js');
var cssdoc = require('./cssdoc.js');
/**
* @function build 通过`path`生成单个文档
* @param {string} path 路径,如`unit/button`、`component/modal`
* @return {void}
*/
function build(path, sitemap, template) {
var level = path.split('/');
if(path === 'index' || level[1] === 'index')
return;
// if(path === 'index')
// level = ['start', 'index'];
// 组织模板数据
var data = {
sitemap: sitemap,
mainnavs: [],
sidenavs: [],
relativePath: '../',
isIndex: false,
mainnav: level[0],
sidenav: level[1],
article: '',
script: '',
api: '',
current: null
}
// if(path === 'index') {
// data.relativePath = '';
// data.isIndex = true;
// data.mainnav = null;
// data.sidenav = null;
// }
// 组织主导航数据
sitemap.children.forEach(function(level1) {
level1.path = (level1.lowerName + '/' + level1.children[0].lowerName + '.html').toLowerCase();
// level1.path = level1.path || (level1.lowerName + '/index.html').toLowerCase();
data.mainnavs.push(level1);
});
// 组织侧边栏数据
for(var i = 0; i < sitemap.children.length; i++)
if(sitemap.children[i].lowerName === level[0]) {
data.sidenavs = sitemap.children[i].children;
data.sidenavs.forEach(function(item) {
if(item.lowerName === level[1])
data.current = item;
item.path = item.path || (data.relativePath + level[0] + '/' + item.lowerName + '.html').toLowerCase();
item.blank = /^http/.test(item.path);
});
break;
}
// 如果是JS组件,使用jsdoc解析../src目录下的js代码生成API
if(level[0].slice(0, 2) === 'js') {
var jsFile = __dirname + '/../src/js/' + level[0].slice(2, 20).toLowerCase() + '/' + level[1] + '.js';
// @TODO
if(level[1] === 'validation')
jsFile = __dirname + '/../src/js/util/validation.js';
else if(level[1] === 'draggable' || level[1] === 'droppable')
jsFile = __dirname + '/../node_modules/regular-ui-dragdrop/src/' + level[1] + '.js';
if(fs.existsSync(jsFile))
data.api = jsdoc.render(jsFile, template.jsApi);
}
var tpl = template.head + '<div class="g-bd"><div class="g-bdc">' + template.sidebar + template.main + '</div></div>' + template.foot;
var htmlPath = __dirname + '/view/' + path + '.html';
var ejsPath = __dirname + '/view/' + path + '.ejs';
var mdPath = __dirname + '/view/' + path + '.md';
if(fs.existsSync(htmlPath))
tpl = template.head + fs.readFileSync(htmlPath) + template.foot;
else if(fs.existsSync(ejsPath))
tpl = template.head + fs.readFileSync(ejsPath) + template.foot;
else if(fs.existsSync(mdPath)) {
// 根据./view目录下的markdown文件生成文档
var markdown = fs.readFileSync(mdPath) + '';
if(level[0].slice(0, 2) === 'js' || level[0] === 'demo') {
// 根据markdown文件中的示例代码直接生成js脚本
data.script = premark.buildScript(markdown);
} else {
// 根据markdown文件中的示例代码直接生成html
markdown = premark.placeHTML(markdown);
}
data.article = markextend(markdown);
}
// 渲染HTML文件
var html = ejs.render(tpl, data);
var filepath = __dirname + '/../doc/' + path.toLowerCase() + '.html';
var filedir = pathlib.dirname(filepath);
if(!fs.existsSync(filedir))
fs.mkdirSync(filedir);
fs.writeFileSync(filepath, html, {encoding: 'utf8', mode: 0644});
// console.log('[SUCCESS] build: ' + path);
}
module.exports = build; |
/**
* Module definition and dependencies
*/
angular.module('ngGo.Board.Layer.HoverLayer.Service', [
'ngGo',
'ngGo.Board.Layer.Service',
'ngGo.Board.Object.Markup.Service',
'ngGo.Board.Object.StoneFaded.Service'
])
/**
* Factory definition
*/
.factory('HoverLayer', function(BoardLayer, Markup, StoneFaded) {
/**
* Constructor
*/
function HoverLayer(board, context) {
//Container for items to restore
this.restore = [];
//Call parent constructor
BoardLayer.call(this, board, context);
}
/**
* Prototype extension
*/
angular.extend(HoverLayer.prototype, BoardLayer.prototype);
/**
* Add hover item
*/
HoverLayer.prototype.add = function(x, y, hover) {
//Validate coordinates
if (!this.grid.isOnGrid(x, y)) {
return;
}
//Remove any previous item at this position
this.remove(x, y);
//Create hover object
hover.object = {
x: x,
y: y
};
//Stones
if (hover.type === 'stones') {
hover.objectClass = StoneFaded;
hover.object.color = hover.value;
}
//Markup
else if (hover.type === 'markup') {
hover.objectClass = Markup;
if (typeof hover.value === 'object') {
hover.object = angular.extend(hover.object, hover.value);
}
else {
hover.object.type = hover.value;
}
}
//Unknown
else {
console.warn('Unknown hover type', hover.type);
return;
}
//Check if we need to hide something on layers underneath
if (this.board.has(hover.type, x, y)) {
this.restore.push({
x: x,
y: y,
layer: hover.type,
value: this.board.get(hover.type, x, y)
});
this.board.remove(hover.type, x, y);
}
//Add to stack
this.grid.set(x, y, hover);
//Draw item
if (hover.objectClass && hover.objectClass.draw) {
hover.objectClass.draw.call(this, hover.object);
}
};
/**
* Remove the hover object
*/
HoverLayer.prototype.remove = function(x, y) {
//Validate coordinates
if (!this.grid.has(x, y)) {
return;
}
//Get object and clear it
var hover = this.grid.get(x, y);
if (hover.objectClass && hover.objectClass.clear) {
hover.objectClass.clear.call(this, hover.object);
}
//Other objects to restore?
for (var i = 0; i < this.restore.length; i++) {
if (this.restore[i].x === x && this.restore[i].y === y) {
this.board.add(
this.restore[i].layer, this.restore[i].x, this.restore[i].y, this.restore[i].value
);
this.restore.splice(i, 1);
}
}
};
/**
* Remove all hover objects
*/
HoverLayer.prototype.removeAll = function() {
//Anything to do?
if (this.grid.isEmpty()) {
return;
}
//Get all item as objects
var i;
var hover = this.grid.all('layer');
//Clear them
for (i = 0; i < hover.length; i++) {
if (hover[i].objectClass && hover[i].objectClass.clear) {
hover[i].objectClass.clear.call(this, hover[i].object);
}
}
//Clear layer and empty grid
this.clear();
this.grid.empty();
//Restore objects on other layers
for (i = 0; i < this.restore.length; i++) {
this.board.add(
this.restore[i].layer, this.restore[i].x, this.restore[i].y, this.restore[i].value
);
}
//Clear restore array
this.restore = [];
};
/**
* Draw layer
*/
HoverLayer.prototype.draw = function() {
//Can only draw when we have dimensions and context
if (!this.context || this.board.drawWidth === 0 || this.board.drawheight === 0) {
return;
}
//Loop objects and clear them
var hover = this.grid.all('hover');
for (var i = 0; i < hover.length; i++) {
if (hover.objectClass && hover.objectClass.draw) {
hover.objectClass.draw.call(this, hover.object);
}
}
};
//Return
return HoverLayer;
});
|
/* Guilded Already 1.0.0
* Copyright (c) 2009 C. Jason Harrelson (midas)
* Guilded Flash Growler is licensed under the terms of the MIT License */
g.alreadyGridInit=function(options){if(g.beforeAlreadyGridInit)g.beforeAlreadyGridInit(options);var grid=$j('#'+options.id);grid.alreadyGrid(options);if(g.afterAlreadyGridInit)g.afterAlreadyGridInit(options);}; |
NEWSBLUR.Views.StoryTitlesHeader = Backbone.View.extend({
el: ".NB-story-titles-header",
options: {
'layout': 'split'
},
events: {
"click .NB-feedbar-options" : "open_options_popover",
"click .NB-feedbar-mark-feed-read" : "mark_folder_as_read",
"click .NB-feedbar-mark-feed-read-expand" : "expand_mark_read",
"click .NB-feedbar-mark-feed-read-time" : "mark_folder_as_read_days",
"click .NB-story-title-indicator" : "show_hidden_story_titles"
},
initialize: function() {
this.$story_titles_feedbar = $(".NB-story-titles-header");
this.$feed_view_feedbar = $(".NB-feed-story-view-header");
// if (this.options.layout == 'split' || this.options.layout == 'list') {
this.$story_titles_feedbar.show();
this.$feed_view_feedbar.hide();
// } else if (this.options.layout == 'full') {
// this.$story_titles_feedbar.hide();
// this.$feed_view_feedbar.show();
// this.setElement(this.$feed_view_feedbar);
// }
},
render: function(options) {
var $view;
this.options = _.extend({}, this.options, options);
this.showing_fake_folder = NEWSBLUR.reader.flags['river_view'] &&
NEWSBLUR.reader.active_folder &&
(NEWSBLUR.reader.active_folder.get('fake') || !NEWSBLUR.reader.active_folder.get('folder_title'));
if (NEWSBLUR.reader.flags['starred_view']) {
$view = $(_.template('\
<div class="NB-folder NB-no-hover">\
<div class="NB-search-container"></div>\
<div class="NB-feedbar-options-container">\
<span class="NB-feedbar-options">\
<div class="NB-icon"></div>\
<%= NEWSBLUR.assets.view_setting("starred", "order") %>\
</span>\
</div>\
<div class="NB-starred-icon"></div>\
<div class="NB-feedlist-manage-icon"></div>\
<span class="folder_title_text"><%= folder_title %></span>\
</div>\
', {
folder_title: NEWSBLUR.reader.active_fake_folder_title()
}));
this.search_view = new NEWSBLUR.Views.FeedSearchView({
feedbar_view: this
}).render();
this.search_view.blur_search();
$(".NB-search-container", $view).html(this.search_view.$el);
} else if (NEWSBLUR.reader.active_feed == "read") {
$view = $(_.template('\
<div class="NB-folder NB-no-hover">\
<div class="NB-feedbar-options-container">\
<span class="NB-feedbar-options">\
<div class="NB-icon"></div>\
<%= NEWSBLUR.assets.view_setting("read", "order") %>\
</span>\
</div>\
<div class="NB-read-icon"></div>\
<div class="NB-feedlist-manage-icon"></div>\
<div class="folder_title_text"><%= folder_title %></div>\
</div>\
', {
folder_title: NEWSBLUR.reader.active_fake_folder_title()
}));
} else if (this.showing_fake_folder) {
$view = $(_.template('\
<div class="NB-folder NB-no-hover NB-folder-<%= all_stories ? "river" : "fake" %>">\
<div class="NB-feedbar-mark-feed-read-container">\
<div class="NB-feedbar-mark-feed-read"><div class="NB-icon"></div></div>\
<div class="NB-feedbar-mark-feed-read-time" data-days="1">1d</div>\
<div class="NB-feedbar-mark-feed-read-time" data-days="3">3d</div>\
<div class="NB-feedbar-mark-feed-read-time" data-days="7">7d</div>\
<div class="NB-feedbar-mark-feed-read-time" data-days="14">14d</div>\
<div class="NB-feedbar-mark-feed-read-expand"></div>\
</div>\
<div class="NB-search-container"></div>\
<% if (show_options) { %>\
<div class="NB-feedbar-options-container">\
<span class="NB-feedbar-options">\
<div class="NB-icon"></div>\
<%= NEWSBLUR.assets.view_setting(folder_id, "read_filter") %>\
·\
<%= NEWSBLUR.assets.view_setting(folder_id, "order") %>\
<% if (infrequent_stories) { %>\
·\
< <%= infrequent_freq %> stories/month\
<% } %>\
</span>\
</div>\
<% } %>\
<div class="NB-story-title-indicator">\
<div class="NB-story-title-indicator-count"></div>\
<span class="NB-story-title-indicator-text">show hidden stories</span>\
</div>\
<div class="NB-folder-icon"></div>\
<div class="NB-feedlist-manage-icon"></div>\
<span class="folder_title_text"><%= folder_title %></span>\
</div>\
', {
folder_title: NEWSBLUR.reader.active_fake_folder_title(),
folder_id: NEWSBLUR.reader.active_feed,
all_stories: NEWSBLUR.reader.active_feed == "river:" || NEWSBLUR.reader.active_feed == "river:infrequent",
infrequent_stories: NEWSBLUR.reader.active_feed == "river:infrequent",
infrequent_freq: NEWSBLUR.assets.preference('infrequent_stories_per_month'),
show_options: !NEWSBLUR.reader.active_folder.get('fake') ||
NEWSBLUR.reader.active_folder.get('show_options')
}));
this.search_view = new NEWSBLUR.Views.FeedSearchView({
feedbar_view: this
}).render();
this.search_view.blur_search();
$(".NB-search-container", $view).html(this.search_view.$el);
} else if (NEWSBLUR.reader.flags['river_view'] &&
NEWSBLUR.reader.active_folder &&
NEWSBLUR.reader.active_folder.get('folder_title')) {
this.view = new NEWSBLUR.Views.Folder({
model: NEWSBLUR.reader.active_folder,
collection: NEWSBLUR.reader.active_folder.folder_view.collection,
feedbar: true,
only_title: true
}).render();
$view = this.view.$el;
this.search_view = this.view.search_view;
} else {
this.view = new NEWSBLUR.Views.FeedTitleView({
model: NEWSBLUR.assets.get_feed(this.options.feed_id),
type: 'story'
}).render();
$view = this.view.$el;
this.search_view = this.view.search_view;
}
this.$el.html($view);
if (NEWSBLUR.reader.flags.searching) {
this.focus_search();
}
return this;
},
remove: function() {
if (this.view) {
this.view.remove();
delete this.view;
}
// Backbone.View.prototype.remove.call(this);
},
search_has_focus: function() {
return this.search_view && this.search_view.has_focus();
},
focus_search: function() {
if (!this.search_view) return;
this.search_view.focus_search();
},
// ===========
// = Actions =
// ===========
show_feed_hidden_story_title_indicator: function(is_feed_load) {
if (!is_feed_load) return;
if (!NEWSBLUR.reader.active_feed) return;
if (NEWSBLUR.reader.flags.search) return;
if (NEWSBLUR.reader.flags['feed_list_showing_starred']) return;
NEWSBLUR.reader.flags['unread_threshold_temporarily'] = null;
var unread_view_name = NEWSBLUR.reader.get_unread_view_name();
var $indicator = this.$('.NB-story-title-indicator');
var unread_hidden_stories;
if (NEWSBLUR.reader.flags['river_view']) {
unread_hidden_stories = NEWSBLUR.reader.active_folder &&
NEWSBLUR.reader.active_folder.folders &&
NEWSBLUR.reader.active_folder.folders.unread_counts &&
NEWSBLUR.reader.active_folder.folders.unread_counts().ng;
} else {
unread_hidden_stories = NEWSBLUR.assets.active_feed.unread_counts().ng;
}
var hidden_stories = unread_hidden_stories || !!NEWSBLUR.assets.stories.hidden().length;
if (!hidden_stories) {
$indicator.hide();
return;
}
if (is_feed_load) {
$indicator.css({'display': 'block', 'opacity': 0});
_.delay(function() {
$indicator.animate({'opacity': 1}, {'duration': 1000, 'easing': 'easeOutCubic'});
}, 500);
}
$indicator.removeClass('unread_threshold_positive')
.removeClass('unread_threshold_neutral')
.removeClass('unread_threshold_negative')
.addClass('unread_threshold_'+unread_view_name);
},
show_hidden_story_titles: function() {
var $indicator = this.$('.NB-story-title-indicator');
var temp_unread_view_name = NEWSBLUR.reader.get_unread_view_name();
var unread_view_name = NEWSBLUR.reader.get_unread_view_name(null, true);
var hidden_stories_at_threshold = NEWSBLUR.assets.stories.any(function(story) {
var score = story.score();
if (temp_unread_view_name == 'positive') return score == 0;
else if (temp_unread_view_name == 'neutral') return score < 0;
});
var hidden_stories_below_threshold = temp_unread_view_name == 'positive' &&
NEWSBLUR.assets.stories.any(function(story) {
return story.score() < 0;
});
// NEWSBLUR.log(['show_hidden_story_titles', hidden_stories_at_threshold, hidden_stories_below_threshold, unread_view_name, temp_unread_view_name, NEWSBLUR.reader.flags['unread_threshold_temporarily']]);
// First click, open neutral. Second click, open negative.
if (temp_unread_view_name == 'positive' &&
hidden_stories_at_threshold &&
hidden_stories_below_threshold) {
NEWSBLUR.reader.flags['unread_threshold_temporarily'] = 'neutral';
NEWSBLUR.reader.show_story_titles_above_intelligence_level({
'unread_view_name': 'neutral',
'animate': true,
'follow': true
});
$indicator.removeClass('unread_threshold_positive')
.removeClass('unread_threshold_negative');
$indicator.addClass('unread_threshold_neutral');
$(".NB-story-title-indicator-text", $indicator).text("show hidden stories");
} else if (NEWSBLUR.reader.flags['unread_threshold_temporarily'] != 'negative') {
NEWSBLUR.reader.flags['unread_threshold_temporarily'] = 'negative';
NEWSBLUR.reader.show_story_titles_above_intelligence_level({
'unread_view_name': 'negative',
'animate': true,
'follow': true
});
$indicator.removeClass('unread_threshold_positive')
.removeClass('unread_threshold_neutral');
$indicator.addClass('unread_threshold_negative');
// $indicator.animate({'opacity': 0}, {'duration': 500}).css('display', 'none');
$(".NB-story-title-indicator-text", $indicator).text("hide hidden stories");
} else {
NEWSBLUR.reader.flags['unread_threshold_temporarily'] = null;
NEWSBLUR.reader.show_story_titles_above_intelligence_level({
'unread_view_name': unread_view_name,
'animate': true,
'follow': true
});
$indicator.removeClass('unread_threshold_positive')
.removeClass('unread_threshold_neutral')
.removeClass('unread_threshold_negative');
$indicator.addClass('unread_threshold_'+unread_view_name);
$(".NB-story-title-indicator-text", $indicator).text("show hidden stories");
}
},
open_options_popover: function(e) {
if (!(this.showing_fake_folder ||
NEWSBLUR.reader.active_feed == "read" ||
NEWSBLUR.reader.flags['starred_view'])) return;
NEWSBLUR.FeedOptionsPopover.create({
anchor: this.$(".NB-feedbar-options"),
feed_id: NEWSBLUR.reader.active_feed
});
},
mark_folder_as_read: function(e, days_back) {
if (!this.showing_fake_folder) return;
if (NEWSBLUR.assets.preference('mark_read_river_confirm')) {
NEWSBLUR.reader.open_mark_read_modal({days: days_back || 0});
} else {
NEWSBLUR.reader.mark_folder_as_read();
}
this.$('.NB-feedbar-mark-feed-read-container').fadeOut(400);
},
mark_folder_as_read_days: function(e) {
if (!this.showing_fake_folder) return;
var days = parseInt($(e.target).data('days'), 10);
this.mark_folder_as_read(e, days);
},
expand_mark_read: function() {
if (!this.showing_fake_folder) return;
NEWSBLUR.Views.FeedTitleView.prototype.expand_mark_read.call(this);
}
}); |
angular.module('app', ['ui.multiselect'])
.controller('appCtrl', ['$scope', function($scope){
$scope.cars = [
{id:1, name: 'Audi'},
{id:2, name: 'BMW'},
{id:3, name: 'Honda'}
];
$scope.selectedCar = [];
$scope.fruits = [
{id: 1, name: 'Apple'},
{id: 2, name: 'Orange'},
{id: 3, name: 'Banana'}
];
$scope.selectedFruit = null;
}]);
|
// warning: This file is auto generated by `npm run build:tests`
// Do not edit by hand!
process.env.TZ = 'UTC'
var expect = require('chai').expect
var ini_set = require('../../../../src/php/info/ini_set') // eslint-disable-line no-unused-vars,camelcase
var ini_get = require('../../../../src/php/info/ini_get') // eslint-disable-line no-unused-vars,camelcase
var ctype_punct = require('../../../../src/php/ctype/ctype_punct.js') // eslint-disable-line no-unused-vars,camelcase
describe('src/php/ctype/ctype_punct.js (tested in test/languages/php/ctype/test-ctype_punct.js)', function () {
it('should pass example 1', function (done) {
var expected = true
var result = ctype_punct('!?')
expect(result).to.deep.equal(expected)
done()
})
})
|
"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: "M18 19H6c-.55 0-1-.45-1-1V6c0-.55.45-1 1-1h5c.55 0 1-.45 1-1s-.45-1-1-1H5c-1.11 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-6c0-.55-.45-1-1-1s-1 .45-1 1v5c0 .55-.45 1-1 1zM14 4c0 .55.45 1 1 1h2.59l-9.13 9.13c-.39.39-.39 1.02 0 1.41.39.39 1.02.39 1.41 0L19 6.41V9c0 .55.45 1 1 1s1-.45 1-1V3h-6c-.55 0-1 .45-1 1z"
}), 'LaunchRounded');
exports.default = _default; |
define(function(require) {
'use strict';
var ViewComponent;
var $ = require('jquery');
var _ = require('underscore');
var BaseComponent = require('oroui/js/app/components/base/component');
var tools = require('oroui/js/tools');
/**
* Creates a view passed through 'view' option and binds it with _sourceElement
* Passes all events triggered on component to the created view.
*/
ViewComponent = BaseComponent.extend({
/**
* @constructor
* @param {Object} options
*/
initialize: function(options) {
var subPromises = _.values(options._subPromises);
var viewOptions = _.extend(
_.omit(options, '_sourceElement', '_subPromises', 'view'),
{el: options._sourceElement}
);
var initializeView = _.bind(this._initializeView, this, viewOptions);
// mark element
options._sourceElement.attr('data-bound-view', options.view);
this._deferredInit();
if (subPromises.length) {
// ensure that all nested components are already initialized
$.when.apply($, subPromises).then(function() {
tools.loadModules(options.view, initializeView);
});
} else {
tools.loadModules(options.view, initializeView);
}
},
/**
*
* @param {Object} options
* @param {Function} View
* @protected
*/
_initializeView: function(options, View) {
if (this.disposed) {
this._resolveDeferredInit();
return;
}
this.view = new View(options);
// pass all component events to view
this.on('all', function() {
// add 'component:' prefix to event name
arguments[0] = 'component:' + arguments[0];
this.view.trigger.apply(this.view, arguments);
}, this);
if (this.view.deferredRender) {
this.view.deferredRender
.done(_.bind(this._resolveDeferredInit, this))
.fail(function() {
throw new Error('View rendering failed');
});
} else {
this._resolveDeferredInit();
}
}
});
return ViewComponent;
});
|
'use strict';
var Node = require(__dirname);
var ParameterNode = module.exports = Node.define({
type: 'PARAMETER',
constructor: function(val) {
Node.call(this);
this._val = val;
this.isExplicit = false;
},
value: function() {
return this._val;
}
});
// wrap a value as a parameter node if value is not already a node
module.exports.getNodeOrParameterNode = function(value) {
if (value && value.toNode) {
// use toNode
return value.toNode();
} else {
// wrap as parameter node
return new ParameterNode(value);
}
};
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var articles = require('./routes/articles');
require('./db');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/articles', articles);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
|
Meteor.startup(function () {
// fixtures
if (Items.find().count() === 0) {
_.each([
"Hat",
"Shoes",
"Coat",
"Gloves",
"Socks",
"Sweater",
"T-shirt"
], function (name) {
Items.insert({name: name});
});
}
PeopleWithContacts.remove({});
// Used for updatepush example
PeopleWithContacts.insert({
firstName: 'Albert',
lastName: 'Einstein',
age: new Date().getFullYear() - 1879
});
// Used for updateArrayItem example
PeopleWithContacts.insert({
firstName: 'Winston',
lastName: 'Churchill',
age: new Date().getFullYear() - 1874,
contacts: [
{name: 'Randolph Churchill', phone: '+1 555-555-5555'},
{name: 'Jennie Jerome', phone: '+1 555-555-5555'},
{name: 'Clementine Hozier', phone: '+1 555-555-5555'}
]
});
});
|
// ICM 2015
// DOM Manipulation
// https://github.com/ITPNYU/ICM-2015
var divs = [];
var slider;
var checkbox;
var dropdown;
var input;
function setup() {
noCanvas();
// Make a button from a div
var divButton = createButton('make a div');
divButton.mousePressed(makeDiv);
// Make a slider
slider = createSlider(1, 48, 12);
// Make a checkbox
checkbox = createCheckbox('red');
// Make a dropdown menu
dropdown = createSelect();
dropdown.option('date');
dropdown.option('random number');
// Make a text input
input = createInput('your name');
// Make a button
var clearButton = createButton('clear');
clearButton.mousePressed(clearDivs);
}
// Call remove() on all new divs added
function clearDivs() {
for (var i = 0; i < divs.length; i++) {
divs[i].remove();
}
divs = [];
}
// Make a new div
function makeDiv() {
var div;
// Check the dropdown
if (dropdown.selected() === 'date') {
div = createDiv(input.value() + ', this div was made at ' + Date());
} else {
div = createDiv(input.value() + ', here\'s the length of the array: ' + int(divs.length+1));
}
// User the slider for font size
div.style('font-size', slider.value() + 'pt');
// Check the checkbox
if (checkbox.checked()) {
div.style('background-color', '#D00');
}
divs.push(div);
}
|
var App = (function () {
'use strict';
App.mapsVector = function( ){
var color1 = App.color.primary;
var color2 = App.color.dark;
var color3 = App.color.danger;
var color4 = App.color.warning;
var color5 = App.color.info;
var color6 = App.color.dark;
var color7 = App.color.warning;
var color8 = App.color.danger;
//Maps
$('#usa-map').vectorMap({
map: 'us_merc_en',
backgroundColor: 'transparent',
regionStyle: {
initial: {
fill: color1,
},
hover: {
"fill-opacity": 0.8
}
}
});
$('#france-map').vectorMap({
map: 'fr_merc_en',
backgroundColor: 'transparent',
regionStyle: {
initial: {
fill: color2,
},
hover: {
"fill-opacity": 0.8
}
}
});
$('#uk-map').vectorMap({
map: 'uk_mill_en',
backgroundColor: 'transparent',
regionStyle: {
initial: {
fill: color3,
},
hover: {
"fill-opacity": 0.8
}
}
});
$('#chicago-map').vectorMap({
map: 'us-il-chicago_mill_en',
backgroundColor: 'transparent',
regionStyle: {
initial: {
fill: color4,
},
hover: {
"fill-opacity": 0.8
}
}
});
$('#australia-map').vectorMap({
map: 'au_mill_en',
backgroundColor: 'transparent',
regionStyle: {
initial: {
fill: color5,
},
hover: {
"fill-opacity": 0.8
}
}
});
$('#india-map').vectorMap({
map: 'in_mill_en',
backgroundColor: 'transparent',
regionStyle: {
initial: {
fill: color6,
},
hover: {
"fill-opacity": 0.8
}
}
});
$('#vector-map').vectorMap({
map: 'map',
backgroundColor: 'transparent',
regionStyle: {
initial: {
fill: color7,
"fill-opacity": 0.8,
stroke: 'none',
"stroke-width": 0,
"stroke-opacity": 1
},
hover: {
"fill-opacity": 0.8
}
},
markerStyle:{
initial:{
r: 10
}
},
markers: [
{coords: [100, 100], name: 'Marker 1', style: {fill: '#acb1b6',stroke:'#cfd5db',"stroke-width": 3}},
{coords: [200, 200], name: 'Marker 2', style: {fill: '#acb1b6',stroke:'#cfd5db',"stroke-width": 3}},
]
});
$('#canada-map').vectorMap({
map: 'ca_lcc_en',
backgroundColor: 'transparent',
regionStyle: {
initial: {
fill: color8,
},
hover: {
"fill-opacity": 0.8
}
}
});
};
return App;
})(App || {});
|
/*
* Copyright 2019 - Universidad Politécnica de Madrid.
*
* This file is part of Keyrock
*
*/
// Load database configuration before
require('../../config/config_database');
// const keyrock = require('../../bin/www');
const config_service = require('../../../lib/configService.js');
config_service.set_config(require('../../config-test.js'));
const config = config_service.get_config();
const should = require('should');
const request = require('request');
const utils = require('../../utils');
const authenticate = utils.readExampleFile('./test/templates/api/000-authenticate.json');
const provider_login = authenticate.good_admin_login;
const user_login = authenticate.good_login;
const role_user_assignments = utils.readExampleFile('./test/templates/api/011-role_user_assignments.json');
let token;
let unauhtorized_token;
let application_id;
const users = [];
const roles = [];
describe('API - 11 - Role user assignment: ', function () {
// CREATE TOKEN WITH PROVIDER CREDENTIALS
// eslint-disable-next-line no-undef
before(function (done) {
const good_login = {
url: config.host + '/v1/auth/tokens',
method: 'POST',
json: provider_login,
headers: {
'Content-Type': 'application/json'
}
};
return request(good_login, function (error, response) {
token = response.headers['x-subject-token'];
done();
});
});
// CREATE NOT AUTHORIZED TOKEN IN APPLICATION
// eslint-disable-next-line no-undef
before(function (done) {
const good_login = {
url: config.host + '/v1/auth/tokens',
method: 'POST',
json: user_login,
headers: {
'Content-Type': 'application/json'
}
};
return request(good_login, function (error, response) {
unauhtorized_token = response.headers['x-subject-token'];
done();
});
});
// CREATE APPLICATION
// eslint-disable-next-line no-undef
before(function (done) {
const create_application = {
url: config.host + '/v1/applications',
method: 'POST',
body: JSON.stringify(role_user_assignments.before.applications[0]),
headers: {
'Content-Type': 'application/json',
'X-Auth-token': token
}
};
request(create_application, function (error, response, body) {
const json = JSON.parse(body);
application_id = json.application.id;
done();
});
});
// CREATE USERS
// eslint-disable-next-line no-undef
before(function (done) {
const users_template = role_user_assignments.before.users;
for (let i = 0; i < users_template.length; i++) {
const create_user = {
url: config.host + '/v1/users',
method: 'POST',
body: JSON.stringify(users_template[i]),
headers: {
'Content-Type': 'application/json',
'X-Auth-token': token
}
};
request(create_user, function (error, response, body) {
const json = JSON.parse(body);
users.push(json.user.id);
if (i === users_template.length - 1) {
done();
}
});
}
});
// CREATE ROLES
// eslint-disable-next-line no-undef
before(function (done) {
const roles_template = role_user_assignments.before.roles;
for (let i = 0; i < roles_template.length; i++) {
const create_role = {
url: config.host + '/v1/applications/' + application_id + '/roles',
method: 'POST',
body: JSON.stringify(roles_template[i]),
headers: {
'Content-Type': 'application/json',
'X-Auth-token': token
}
};
request(create_role, function (error, response, body) {
const json = JSON.parse(body);
roles.push(json.role.id);
if (i === roles_template.length - 1) {
done();
}
});
}
});
describe('1) When assigning a role to a user with provider token', function () {
it('should return a 201 OK', function (done) {
const assign_role = {
url: config.host + '/v1/applications/' + application_id + '/users/' + users[0] + '/roles/' + roles[0],
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Auth-token': token
}
};
request(assign_role, function (error, response, body) {
should.not.exist(error);
const json = JSON.parse(body);
should(json).have.property('role_user_assignments');
response.statusCode.should.equal(201);
done();
});
});
});
describe('2) When assigning a role to a user with an unauhtorized token', function () {
it('should return a 403 Forbidden', function (done) {
const assign_role = {
url: config.host + '/v1/applications/' + application_id + '/users/' + users[0] + '/roles/' + roles[0],
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Auth-token': unauhtorized_token
}
};
request(assign_role, function (error, response) {
should.not.exist(error);
response.statusCode.should.equal(403);
done();
});
});
});
describe('3) When list users authorized in an application', function () {
// eslint-disable-next-line snakecase/snakecase
beforeEach(function (done) {
const max_index = users.length > roles.length ? users.length : roles.length;
for (let i = 0; i < max_index; i++) {
const assign_role = {
url: config.host + '/v1/applications/' + application_id + '/users/' + users[i] + '/roles/' + roles[i],
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Auth-token': token
}
};
request(assign_role, function () {
if (i === max_index - 1) {
done();
}
});
}
});
it('should return a 200 OK', function (done) {
const assign_permission = {
url: config.host + '/v1/applications/' + application_id + '/users',
method: 'GET',
headers: {
'X-Auth-token': token
}
};
request(assign_permission, function (error, response, body) {
should.not.exist(error);
const json = JSON.parse(body);
should(json).have.property('role_user_assignments');
response.statusCode.should.equal(200);
done();
});
});
});
describe('4) When list roles of a user authorized in the application', function () {
// eslint-disable-next-line snakecase/snakecase
beforeEach(function (done) {
const max_index = roles.length;
for (let i = 0; i < max_index; i++) {
const assign_role = {
url: config.host + '/v1/applications/' + application_id + '/users/' + users[0] + '/roles/' + roles[i],
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Auth-token': token
}
};
request(assign_role, function () {
if (i === max_index - 1) {
done();
}
});
}
});
it('should return a 200 OK', function (done) {
const assign_permission = {
url: config.host + '/v1/applications/' + application_id + '/users/' + users[0] + '/roles',
method: 'GET',
headers: {
'X-Auth-token': token
}
};
request(assign_permission, function (error, response, body) {
should.not.exist(error);
const json = JSON.parse(body);
should(json).have.property('role_user_assignments');
response.statusCode.should.equal(200);
done();
});
});
});
describe('4) When removing a role from a user authorized in the application', function () {
let user_id;
let role_id;
// eslint-disable-next-line snakecase/snakecase
beforeEach(function (done) {
user_id = users[1];
role_id = roles[2];
const assign_role = {
url: config.host + '/v1/applications/' + application_id + '/users/' + user_id + '/roles/' + role_id,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Auth-token': token
}
};
request(assign_role, function () {
done();
});
});
it('should return a 204 OK', function (done) {
const assign_permission = {
url: config.host + '/v1/applications/' + application_id + '/users/' + user_id + '/roles/' + role_id,
method: 'DELETE',
headers: {
'X-Auth-token': token
}
};
request(assign_permission, function (error, response) {
should.not.exist(error);
response.statusCode.should.equal(204);
done();
});
});
});
});
|
logger.log("Setting bodyParser JSON");
module.exports = bodyParser.json();
|
/*
Highcharts JS v9.3.2 (2021-11-29)
Variable Pie module for Highcharts
(c) 2010-2021 Grzegorz Blachliski
License: www.highcharts.com/license
*/
'use strict';(function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/variable-pie",["highcharts"],function(e){a(e);a.Highcharts=e;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function e(a,b,e,m){a.hasOwnProperty(b)||(a[b]=m.apply(null,e))}a=a?a._modules:{};e(a,"Series/VariablePie/VariablePieSeries.js",[a["Core/Series/SeriesRegistry.js"],a["Core/Utilities.js"]],function(a,
b){var e=this&&this.__extends||function(){var a=function(b,c){a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(c,a){c.__proto__=a}||function(c,a){for(var h in a)a.hasOwnProperty(h)&&(c[h]=a[h])};return a(b,c)};return function(b,c){function r(){this.constructor=b}a(b,c);b.prototype=null===c?Object.create(c):(r.prototype=c.prototype,new r)}}(),m=a.seriesTypes.pie,w=b.arrayMax,x=b.arrayMin,z=b.clamp,A=b.extend,B=b.fireEvent,C=b.merge,n=b.pick;b=function(a){function b(){var c=null!==
a&&a.apply(this,arguments)||this;c.data=void 0;c.options=void 0;c.points=void 0;c.radii=void 0;return c}e(b,a);b.prototype.calculateExtremes=function(){var c=this.chart,a=this.options;var b=this.zData;var e=Math.min(c.plotWidth,c.plotHeight)-2*(a.slicedOffset||0),t={};c=this.center||this.getCenter();["minPointSize","maxPointSize"].forEach(function(c){var b=a[c],h=/%$/.test(b);b=parseInt(b,10);t[c]=h?e*b/100:2*b});this.minPxSize=c[3]+t.minPointSize;this.maxPxSize=z(c[2],c[3]+t.minPointSize,t.maxPointSize);
b.length&&(c=n(a.zMin,x(b.filter(this.zValEval))),b=n(a.zMax,w(b.filter(this.zValEval))),this.getRadii(c,b,this.minPxSize,this.maxPxSize))};b.prototype.getRadii=function(c,a,b,e){var h=0,l=this.zData,r=l.length,k=[],m="radius"!==this.options.sizeBy,n=a-c;for(h;h<r;h++){var g=this.zValEval(l[h])?l[h]:c;g<=c?g=b/2:g>=a?g=e/2:(g=0<n?(g-c)/n:.5,m&&(g=Math.sqrt(g)),g=Math.ceil(b+g*(e-b))/2);k.push(g)}this.radii=k};b.prototype.redraw=function(){this.center=null;a.prototype.redraw.apply(this,arguments)};
b.prototype.translate=function(c){this.generatePoints();var b=0,a=this.options,e=a.slicedOffset,m=e+(a.borderWidth||0),l=a.startAngle||0,u=Math.PI/180*(l-90),k=Math.PI/180*(n(a.endAngle,l+360)-90);l=k-u;var y=this.points,w=a.dataLabels.distance;a=a.ignoreHiddenPoint;var g=y.length;this.startAngleRad=u;this.endAngleRad=k;this.calculateExtremes();c||(this.center=c=this.getCenter());for(k=0;k<g;k++){var f=y[k];var p=this.radii[k];f.labelDistance=n(f.options.dataLabels&&f.options.dataLabels.distance,
w);this.maxLabelDistance=Math.max(this.maxLabelDistance||0,f.labelDistance);var d=u+b*l;if(!a||f.visible)b+=f.percentage/100;var q=u+b*l;f.shapeType="arc";f.shapeArgs={x:c[0],y:c[1],r:p,innerR:c[3]/2,start:Math.round(1E3*d)/1E3,end:Math.round(1E3*q)/1E3};d=(q+d)/2;d>1.5*Math.PI?d-=2*Math.PI:d<-Math.PI/2&&(d+=2*Math.PI);f.slicedTranslation={translateX:Math.round(Math.cos(d)*e),translateY:Math.round(Math.sin(d)*e)};var v=Math.cos(d)*c[2]/2;var x=Math.sin(d)*c[2]/2;q=Math.cos(d)*p;p*=Math.sin(d);f.tooltipPos=
[c[0]+.7*v,c[1]+.7*x];f.half=d<-Math.PI/2||d>Math.PI/2?1:0;f.angle=d;v=Math.min(m,f.labelDistance/5);f.labelPosition={natural:{x:c[0]+q+Math.cos(d)*f.labelDistance,y:c[1]+p+Math.sin(d)*f.labelDistance},"final":{},alignment:f.half?"right":"left",connectorPosition:{breakAt:{x:c[0]+q+Math.cos(d)*v,y:c[1]+p+Math.sin(d)*v},touchingSliceAt:{x:c[0]+q,y:c[1]+p}}}}B(this,"afterTranslate")};b.prototype.zValEval=function(a){return"number"!==typeof a||isNaN(a)?null:!0};b.defaultOptions=C(m.defaultOptions,{minPointSize:"10%",
maxPointSize:"100%",zMin:void 0,zMax:void 0,sizeBy:"area",tooltip:{pointFormat:'<span style="color:{point.color}">\u25cf</span> {series.name}<br/>Value: {point.y}<br/>Size: {point.z}<br/>'}});return b}(m);A(b.prototype,{pointArrayMap:["y","z"],parallelArrays:["x","y","z"]});a.registerSeriesType("variablepie",b);"";"";return b});e(a,"masters/modules/variable-pie.src.js",[],function(){})});
//# sourceMappingURL=variable-pie.js.map |
import { StackNavigator } from 'react-navigation'
import LaunchScreen from '../Containers/LaunchScreen'
import styles from './Styles/NavigationStyles'
// Manifest of possible screens
const PrimaryNav = StackNavigator({
LaunchScreen: { screen: LaunchScreen }
}, {
// Default config for all screens
headerMode: 'none',
initialRouteName: 'LaunchScreen',
navigationOptions: {
headerStyle: styles.header
}
})
export default PrimaryNav
|
define(['backbone', 'model/main-model', 'view/input-view',
'view/result-view', 'view/analysis-root-view'], function(Backbone, Main, InputView, ResultView, AnalysisRootView) {
app = window.app = {};
var model = app.model = new Main();
app.inputView = new InputView({ model: model });
app.resultView = new ResultView({ model: model });
app.analysisRootView = new AnalysisRootView({ model: model });
});
|
"use strict"
const _ = require("lodash")
const keywordSets = {}
keywordSets.nonLengthUnits = new Set([
// Relative length units
"%",
// Time length units
"s",
"ms",
// Angle
"deg",
"grad",
"turn",
"rad",
// Frequency
"Hz",
"kHz",
// Resolution
"dpi",
"dpcm",
"dppx",
])
keywordSets.lengthUnits = new Set([
// Relative length units
"em",
"ex",
"ch",
"rem",
// Viewport-percentage lengths
"vh",
"vw",
"vmin",
"vmax",
"vm",
// Absolute length units
"px",
"mm",
"cm",
"in",
"pt",
"pc",
"q",
])
keywordSets.units = uniteSets(keywordSets.nonLengthUnits, keywordSets.lengthUnits)
keywordSets.colorFunctionNames = new Set([
"rgb",
"rgba",
"hsl",
"hsla",
"hwb",
"gray",
])
keywordSets.camelCaseFunctionNames = new Set([
"translateX",
"translateY",
"translateZ",
"scaleX",
"scaleY",
"scaleZ",
"rotateX",
"rotateY",
"rotateZ",
"skewX",
"skewY",
])
keywordSets.basicKeywords = new Set([
"initial",
"inherit",
"unset",
])
keywordSets.fontFamilyKeywords = uniteSets(keywordSets.basicKeywords, [
"serif",
"sans-serif",
"cursive",
"fantasy",
"monospace",
])
keywordSets.fontWeightRelativeKeywords = new Set([
"bolder",
"lighter",
])
keywordSets.fontWeightAbsoluteKeywords = new Set(["bold"])
keywordSets.fontWeightNumericKeywords = new Set([
"100",
"200",
"300",
"400",
"500",
"600",
"700",
"800",
"900",
])
keywordSets.fontWeightKeywords = uniteSets(
keywordSets.basicKeywords,
keywordSets.fontWeightRelativeKeywords,
keywordSets.fontWeightAbsoluteKeywords,
keywordSets.fontWeightNumericKeywords
)
keywordSets.animationNameKeywords = uniteSets(keywordSets.basicKeywords,
["none"]
)
keywordSets.animationTimingFunctionKeywords = uniteSets(keywordSets.basicKeywords, [
"linear",
"ease",
"ease-in",
"ease-in-out",
"ease-out",
"step-start",
"step-end",
"steps",
"cubic-bezier",
])
keywordSets.animationIterationCountKeywords = new Set(["infinite"])
keywordSets.animationDirectionKeywords = uniteSets(keywordSets.basicKeywords, [
"normal",
"reverse",
"alternate",
"alternate-reverse",
])
keywordSets.animationFillModeKeywords = new Set([
"none",
"forwards",
"backwards",
"both",
])
keywordSets.animationPlayStateKeywords = uniteSets(keywordSets.basicKeywords, [
"running",
"paused",
])
// cf. https://developer.mozilla.org/en-US/docs/Web/CSS/animation
keywordSets.animationShorthandKeywords = uniteSets(
keywordSets.basicKeywords,
keywordSets.animationNameKeywords,
keywordSets.animationTimingFunctionKeywords,
keywordSets.animationIterationCountKeywords,
keywordSets.animationDirectionKeywords,
keywordSets.animationFillModeKeywords,
keywordSets.animationPlayStateKeywords
)
// These are the ones that can have single-colon notation
keywordSets.levelOneAndTwoPseudoElements = new Set([
"before",
"after",
"first-line",
"first-letter",
])
// These are the ones that require double-colon notation
keywordSets.levelThreePseudoElements = new Set([
"before",
"after",
"first-line",
"first-letter",
"selection",
"spelling-error",
"grammar-error",
"backdrop",
"marker",
"placeholder",
"shadow",
"slotted",
"content",
])
keywordSets.pseudoElements = uniteSets(
keywordSets.levelOneAndTwoPseudoElements,
keywordSets.levelThreePseudoElements
)
keywordSets.aNPlusBNotationPseudoClasses = new Set([
"nth-child",
"nth-column",
"nth-last-child",
"nth-last-column",
"nth-last-of-type",
"nth-of-type",
])
keywordSets.linguisticPseudoClasses = new Set([
"dir",
"lang",
])
keywordSets.otherPseudoClasses = new Set([
"active",
"any-link",
"blank",
"checked",
"contains",
"current",
"default",
"disabled",
"drop",
"empty",
"enabled",
"first-child",
"first-of-type",
"focus",
"focus-within",
"fullscreen",
"future",
"has",
"host",
"host-context",
"hover",
"indeterminate",
"in-range",
"invalid",
"last-child",
"last-of-type",
"link",
"matches",
"not",
"only-child",
"only-of-type",
"optional",
"out-of-range",
"past",
"placeholder-shown",
"read-only",
"read-write",
"required",
"root",
"scope",
"target",
"user-error",
"user-invalid",
"val",
"valid",
"visited",
])
keywordSets.pseudoClasses = uniteSets(
keywordSets.aNPlusBNotationPseudoClasses,
keywordSets.linguisticPseudoClasses,
keywordSets.otherPseudoClasses
)
keywordSets.shorthandTimeProperties = new Set([
"transition",
"animation",
])
keywordSets.longhandTimeProperties = new Set([
"transition-duration",
"transition-delay",
"animation-duration",
"animation-delay",
])
keywordSets.timeProperties = uniteSets(
keywordSets.shorthandTimeProperties,
keywordSets.longhandTimeProperties
)
keywordSets.camelCaseKeywords = new Set([
"optimizeSpeed",
"optimizeQuality",
"optimizeLegibility",
"geometricPrecision",
"currentColor",
"crispEdges",
"visiblePainted",
"visibleFill",
"visibleStroke",
"sRGB",
"linearRGB",
])
// https://developer.mozilla.org/docs/Web/CSS/counter-increment
keywordSets.counterIncrementKeywords = uniteSets(keywordSets.basicKeywords, ["none"])
keywordSets.gridRowKeywords = uniteSets(keywordSets.basicKeywords, [
"auto",
"span",
])
keywordSets.gridColumnKeywords = uniteSets(keywordSets.basicKeywords, [
"auto",
"span",
])
keywordSets.gridAreaKeywords = uniteSets(keywordSets.basicKeywords, [
"auto",
"span",
])
// https://developer.mozilla.org/ru/docs/Web/CSS/list-style-type
keywordSets.listStyleTypeKeywords = uniteSets(keywordSets.basicKeywords, [
"none",
"disc",
"circle",
"square",
"decimal",
"cjk-decimal",
"decimal-leading-zero",
"lower-roman",
"upper-roman",
"lower-greek",
"lower-alpha",
"lower-latin",
"upper-alpha",
"upper-latin",
"arabic-indic",
"armenian",
"bengali",
"cambodian",
"cjk-earthly-branch",
"cjk-ideographic",
"devanagari",
"ethiopic-numeric",
"georgian",
"gujarati",
"gurmukhi",
"hebrew",
"hiragana",
"hiragana-iroha",
"japanese-formal",
"japanese-informal",
"kannada",
"katakana",
"katakana-iroha",
"khmer",
"korean-hangul-formal",
"korean-hanja-formal",
"korean-hanja-informal",
"lao",
"lower-armenian",
"malayalam",
"mongolian",
"myanmar",
"oriya",
"persian",
"simp-chinese-formal",
"simp-chinese-informal",
"tamil",
"telugu",
"thai",
"tibetan",
"trad-chinese-formal",
"trad-chinese-informal",
"upper-armenian",
"disclosure-open",
"disclosure-closed",
// Non-standard extensions (without prefixe)
"ethiopic-halehame",
"ethiopic-halehame-am",
"ethiopic-halehame-ti-er",
"ethiopic-halehame-ti-et",
"hangul",
"hangul-consonant",
"urdu",
])
keywordSets.listStylePositionKeywords = uniteSets(keywordSets.basicKeywords, [
"inside",
"outside",
])
keywordSets.listStyleImageKeywords = uniteSets(keywordSets.basicKeywords, ["none"])
keywordSets.listStyleShorthandKeywords = uniteSets(
keywordSets.basicKeywords,
keywordSets.listStyleTypeKeywords,
keywordSets.listStylePositionKeywords,
keywordSets.listStyleImageKeywords
)
keywordSets.fontStyleKeywords = uniteSets(keywordSets.basicKeywords, [
"normal",
"italic",
"oblique",
])
keywordSets.fontVariantKeywords = uniteSets(keywordSets.basicKeywords, [
"normal",
"none",
"historical-forms",
"none",
"common-ligatures",
"no-common-ligatures",
"discretionary-ligatures",
"no-discretionary-ligatures",
"historical-ligatures",
"no-historical-ligatures",
"contextual",
"no-contextual",
"small-caps",
"small-caps",
"all-small-caps",
"petite-caps",
"all-petite-caps",
"unicase",
"titling-caps",
"lining-nums",
"oldstyle-nums",
"proportional-nums",
"tabular-nums",
"diagonal-fractions",
"stacked-fractions",
"ordinal",
"slashed-zero",
"jis78",
"jis83",
"jis90",
"jis04",
"simplified",
"traditional",
"full-width",
"proportional-width",
"ruby",
])
keywordSets.fontStretchKeywords = uniteSets(keywordSets.basicKeywords, [
"semi-condensed",
"condensed",
"extra-condensed",
"ultra-condensed",
"semi-expanded",
"expanded",
"extra-expanded",
"ultra-expanded",
])
keywordSets.fontSizeKeywords = uniteSets(keywordSets.basicKeywords, [
"xx-small",
"x-small",
"small",
"medium",
"large",
"x-large",
"xx-large",
"larger",
"smaller",
])
keywordSets.lineHeightKeywords = uniteSets(keywordSets.basicKeywords, ["normal"])
keywordSets.fontShorthandKeywords = uniteSets(
keywordSets.basicKeywords,
keywordSets.fontStyleKeywords,
keywordSets.fontVariantKeywords,
keywordSets.fontWeightKeywords,
keywordSets.fontStretchKeywords,
keywordSets.fontSizeKeywords,
keywordSets.lineHeightKeywords, keywordSets.fontFamilyKeywords
)
keywordSets.keyframeSelectorKeywords = new Set([
"from",
"to",
])
// https://developer.mozilla.org/en/docs/Web/CSS/At-rule
keywordSets.atRules = new Set([
"apply",
"annotation",
"character-variant",
"charset",
"counter-style",
"custom-media",
"custom-selector",
"document",
"font-face",
"font-feature-values",
"import",
"keyframes",
"media",
"namespace",
"nest",
"ornaments",
"page",
"styleset",
"stylistic",
"supports",
"swash",
"viewport",
])
// https://drafts.csswg.org/mediaqueries/#descdef-media-update
keywordSets.deprecatedMediaFeatureNames = new Set([
"device-aspect-ratio",
"device-height",
"device-width",
"max-device-aspect-ratio",
"max-device-height",
"max-device-width",
"min-device-aspect-ratio",
"min-device-height",
"min-device-width",
])
// https://drafts.csswg.org/mediaqueries/#descdef-media-update
keywordSets.mediaFeatureNames = uniteSets(keywordSets.deprecatedMediaFeatureNames, [
"any-hover",
"any-pointer",
"aspect-ratio",
"color",
"color-gamut",
"color-index",
"grid",
"height",
"hover",
"max-aspect-ratio",
"max-color",
"max-color-index",
"max-height",
"max-monochrome",
"max-resolution",
"max-width",
"min-aspect-ratio",
"min-color",
"min-color-index",
"min-height",
"min-monochrome",
"min-resolution",
"min-width",
"monochrome",
"orientation",
"overflow-block",
"overflow-inline",
"pointer",
"resolution",
"scan",
"scripting",
"update",
"width",
])
// https://www.w3.org/TR/CSS22/ui.html#system-colors
keywordSets.systemColors = new Set([
"activeborder",
"activecaption",
"appworkspace",
"background",
"buttonface",
"buttonhighlight",
"buttonshadow",
"buttontext",
"captiontext",
"graytext",
"highlight",
"highlighttext",
"inactiveborder",
"inactivecaption",
"inactivecaptiontext",
"infobackground",
"infotext",
"menu",
"menutext",
"scrollbar",
"threeddarkshadow",
"threedface",
"threedhighlight",
"threedlightshadow",
"threedshadow",
"window",
"windowframe",
"windowtext",
])
function uniteSets() {
const sets = Array.from(arguments)
return new Set(sets.reduce((result, set) => {
return result.concat(_.toArray(set))
}, []))
}
module.exports = keywordSets
|
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
const _excluded = ["children", "className", "error", "icon", "optional", "StepIconComponent", "StepIconProps", "componentsProps"];
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled';
import styled from '../styles/styled';
import useThemeProps from '../styles/useThemeProps';
import StepIcon from '../StepIcon';
import StepperContext from '../Stepper/StepperContext';
import StepContext from '../Step/StepContext';
import stepLabelClasses, { getStepLabelUtilityClass } from './stepLabelClasses';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
const useUtilityClasses = styleProps => {
const {
classes,
orientation,
active,
completed,
error,
disabled,
alternativeLabel
} = styleProps;
const slots = {
root: ['root', orientation, error && 'error', disabled && 'disabled', alternativeLabel && 'alternativeLabel'],
label: ['label', active && 'active', completed && 'completed', error && 'error', disabled && 'disabled', alternativeLabel && 'alternativeLabel'],
iconContainer: ['iconContainer', alternativeLabel && 'alternativeLabel'],
labelContainer: ['labelContainer']
};
return composeClasses(slots, getStepLabelUtilityClass, classes);
};
const StepLabelRoot = styled('span', {
name: 'MuiStepLabel',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
styleProps
} = props;
return [styles.root, styles[styleProps.orientation]];
}
})(({
styleProps
}) => _extends({
/* Styles applied to the root element. */
display: 'flex',
alignItems: 'center',
[`&.${stepLabelClasses.alternativeLabel}`]: {
flexDirection: 'column'
},
[`&.${stepLabelClasses.disabled}`]: {
cursor: 'default'
}
}, styleProps.orientation === 'vertical' && {
textAlign: 'left',
padding: '8px 0'
}));
const StepLabelLabel = styled('span', {
name: 'MuiStepLabel',
slot: 'Label',
overridesResolver: (props, styles) => styles.label
})(({
theme
}) => _extends({}, theme.typography.body2, {
display: 'block',
/* Styles applied to the Typography component that wraps `children`. */
transition: theme.transitions.create('color', {
duration: theme.transitions.duration.shortest
}),
[`&.${stepLabelClasses.active}`]: {
color: theme.palette.text.primary,
fontWeight: 500
},
[`&.${stepLabelClasses.completed}`]: {
color: theme.palette.text.primary,
fontWeight: 500
},
[`&.${stepLabelClasses.alternativeLabel}`]: {
textAlign: 'center',
marginTop: 16
},
[`&.${stepLabelClasses.error}`]: {
color: theme.palette.error.main
}
}));
const StepLabelIconContainer = styled('span', {
name: 'MuiStepLabel',
slot: 'IconContainer',
overridesResolver: (props, styles) => styles.iconContainer
})(() => ({
/* Styles applied to the `icon` container element. */
flexShrink: 0,
// Fix IE11 issue
display: 'flex',
paddingRight: 8,
[`&.${stepLabelClasses.alternativeLabel}`]: {
paddingRight: 0
}
}));
const StepLabelLabelContainer = styled('span', {
name: 'MuiStepLabel',
slot: 'LabelContainer',
overridesResolver: (props, styles) => styles.labelContainer
})(({
theme
}) => ({
/* Styles applied to the container element which wraps `Typography` and `optional`. */
width: '100%',
color: theme.palette.text.secondary
}));
const StepLabel = /*#__PURE__*/React.forwardRef(function StepLabel(inProps, ref) {
const props = useThemeProps({
props: inProps,
name: 'MuiStepLabel'
});
const {
children,
className,
error = false,
icon: iconProp,
optional,
StepIconComponent: StepIconComponentProp,
StepIconProps,
componentsProps = {}
} = props,
other = _objectWithoutPropertiesLoose(props, _excluded);
const {
alternativeLabel,
orientation
} = React.useContext(StepperContext);
const {
active,
disabled,
completed,
icon: iconContext
} = React.useContext(StepContext);
const icon = iconProp || iconContext;
let StepIconComponent = StepIconComponentProp;
if (icon && !StepIconComponent) {
StepIconComponent = StepIcon;
}
const styleProps = _extends({}, props, {
active,
alternativeLabel,
completed,
disabled,
error,
orientation
});
const classes = useUtilityClasses(styleProps);
return /*#__PURE__*/_jsxs(StepLabelRoot, _extends({
className: clsx(classes.root, className),
ref: ref,
styleProps: styleProps
}, other, {
children: [icon || StepIconComponent ? /*#__PURE__*/_jsx(StepLabelIconContainer, {
className: classes.iconContainer,
styleProps: styleProps,
children: /*#__PURE__*/_jsx(StepIconComponent, _extends({
completed: completed,
active: active,
error: error,
icon: icon
}, StepIconProps))
}) : null, /*#__PURE__*/_jsxs(StepLabelLabelContainer, {
className: classes.labelContainer,
styleProps: styleProps,
children: [children ? /*#__PURE__*/_jsx(StepLabelLabel, _extends({
className: classes.label,
styleProps: styleProps
}, componentsProps.label, {
children: children
})) : null, optional]
})]
}));
});
process.env.NODE_ENV !== "production" ? StepLabel.propTypes
/* remove-proptypes */
= {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* In most cases will simply be a string containing a title for the label.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The props used for each slot inside.
* @default {}
*/
componentsProps: PropTypes.object,
/**
* If `true`, the step is marked as failed.
* @default false
*/
error: PropTypes.bool,
/**
* Override the default label of the step icon.
*/
icon: PropTypes.node,
/**
* The optional node to display.
*/
optional: PropTypes.node,
/**
* The component to render in place of the [`StepIcon`](/api/step-icon/).
*/
StepIconComponent: PropTypes.elementType,
/**
* Props applied to the [`StepIcon`](/api/step-icon/) element.
*/
StepIconProps: PropTypes.object,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.object
} : void 0;
StepLabel.muiName = 'StepLabel';
export default StepLabel; |
module.exports={"title":"Player.me","hex":"C0379A","source":"https://player.me/p/about-us","svg":"<svg role=\"img\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><title>Player.me icon</title><path d=\"M11.981 0a8.957 8.957 0 0 0-8.956 8.957v.363C3.283 15.828 10.082 24 10.082 24V13.205c-1.638-.747-2.756-2.369-2.756-4.253a4.66 4.66 0 1 1 6.152 4.416l-.033.01v4.427c4.296-.713 7.531-4.401 7.531-8.845A8.959 8.959 0 0 0 12.017.001h-.038.002z\"/></svg>","path":"M11.981 0a8.957 8.957 0 0 0-8.956 8.957v.363C3.283 15.828 10.082 24 10.082 24V13.205c-1.638-.747-2.756-2.369-2.756-4.253a4.66 4.66 0 1 1 6.152 4.416l-.033.01v4.427c4.296-.713 7.531-4.401 7.531-8.845A8.959 8.959 0 0 0 12.017.001h-.038.002z"}; |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.BodyCell = void 0;
var _react = _interopRequireWildcard(require("react"));
var _classnames = _interopRequireDefault(require("classnames"));
var _ObjectUtils = _interopRequireDefault(require("../utils/ObjectUtils"));
var _DomHandler = _interopRequireDefault(require("../utils/DomHandler"));
var _RowRadioButton = require("./RowRadioButton");
var _RowCheckbox = require("./RowCheckbox");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { return function () { var Super = _getPrototypeOf(Derived), result; if (_isNativeReflectConstruct()) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var BodyCell = /*#__PURE__*/function (_Component) {
_inherits(BodyCell, _Component);
var _super = _createSuper(BodyCell);
function BodyCell(props) {
var _this;
_classCallCheck(this, BodyCell);
_this = _super.call(this, props);
_this.state = {
editing: _this.props.editing
};
_this.onExpanderClick = _this.onExpanderClick.bind(_assertThisInitialized(_this));
_this.onClick = _this.onClick.bind(_assertThisInitialized(_this));
_this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this));
_this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this));
_this.onEditorFocus = _this.onEditorFocus.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(BodyCell, [{
key: "onExpanderClick",
value: function onExpanderClick(event) {
if (this.props.onRowToggle) {
this.props.onRowToggle({
originalEvent: event,
data: this.props.rowData
});
}
event.preventDefault();
}
}, {
key: "onKeyDown",
value: function onKeyDown(event) {
if (this.props.editMode !== 'row') {
if (event.which === 13 || event.which === 9) {
// tab || enter
this.switchCellToViewMode(true);
}
if (event.which === 27) // escape
{
this.switchCellToViewMode(false);
}
}
}
}, {
key: "onClick",
value: function onClick() {
if (this.props.editMode !== 'row') {
this.editingCellClick = true;
if (this.props.editor && !this.state.editing) {
this.setState({
editing: true
});
if (this.props.editorValidatorEvent === 'click') {
this.bindDocumentEditListener();
}
}
}
}
}, {
key: "onBlur",
value: function onBlur() {
if (this.props.editMode !== 'row' && this.state.editing && this.props.editorValidatorEvent === 'blur') {
this.switchCellToViewMode(true);
}
}
}, {
key: "onEditorFocus",
value: function onEditorFocus(event) {
this.onClick(event);
}
}, {
key: "bindDocumentEditListener",
value: function bindDocumentEditListener() {
var _this2 = this;
if (!this.documentEditListener) {
this.documentEditListener = function (event) {
if (!_this2.editingCellClick) {
_this2.switchCellToViewMode(true);
}
_this2.editingCellClick = false;
};
this.editingCellClick = false;
document.addEventListener('click', this.documentEditListener);
}
}
}, {
key: "closeCell",
value: function closeCell() {
var _this3 = this;
/* When using the 'tab' key, the focus event of the next cell is not called in IE. */
setTimeout(function () {
_this3.setState({
editing: false
});
}, 1);
this.unbindDocumentEditListener();
}
}, {
key: "switchCellToViewMode",
value: function switchCellToViewMode(submit) {
if (this.props.editorValidator && submit) {
var valid = this.props.editorValidator(this.props);
if (valid) {
if (this.props.onEditorSubmit) {
this.props.onEditorSubmit(this.props);
}
this.closeCell();
} // as per previous version if not valid and another editor is open, keep invalid data editor open.
} else {
if (submit && this.props.onEditorSubmit) {
this.props.onEditorSubmit(this.props);
} else if (this.props.onEditorCancel) {
this.props.onEditorCancel(this.props);
}
this.closeCell();
}
}
}, {
key: "unbindDocumentEditListener",
value: function unbindDocumentEditListener() {
if (this.documentEditListener) {
document.removeEventListener('click', this.documentEditListener);
this.documentEditListener = null;
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate() {
var _this4 = this;
if (this.props.editMode !== 'row' && this.container && this.props.editor) {
clearTimeout(this.tabindexTimeout);
if (this.state.editing) {
var focusable = _DomHandler.default.findSingle(this.container, 'input');
if (focusable && document.activeElement !== focusable && !focusable.hasAttribute('data-isCellEditing')) {
focusable.setAttribute('data-isCellEditing', true);
focusable.focus();
}
this.keyHelper.tabIndex = -1;
} else {
this.tabindexTimeout = setTimeout(function () {
if (_this4.keyHelper) {
_this4.keyHelper.setAttribute('tabindex', 0);
}
}, 50);
}
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.unbindDocumentEditListener();
}
}, {
key: "render",
value: function render() {
var _this5 = this;
var content, header, editorKeyHelper;
var cellClassName = (0, _classnames.default)(this.props.bodyClassName || this.props.className, {
'p-selection-column': this.props.selectionMode,
'p-editable-column': this.props.editor,
'p-cell-editing': this.state.editing && this.props.editor
});
if (this.props.expander) {
var iconClassName = (0, _classnames.default)('p-row-toggler-icon pi pi-fw p-clickable', {
'pi-chevron-down': this.props.expanded,
'pi-chevron-right': !this.props.expanded
});
content = /*#__PURE__*/_react.default.createElement("button", {
type: "button",
onClick: this.onExpanderClick,
className: "p-row-toggler p-link"
}, /*#__PURE__*/_react.default.createElement("span", {
className: iconClassName
}));
} else if (this.props.selectionMode) {
var showSelection = true;
if (this.props.showSelectionElement) {
showSelection = this.props.showSelectionElement(this.props.rowData);
}
if (showSelection) {
if (this.props.selectionMode === 'single') content = /*#__PURE__*/_react.default.createElement(_RowRadioButton.RowRadioButton, {
onClick: this.props.onRadioClick,
rowData: this.props.rowData,
selected: this.props.selected
});else content = /*#__PURE__*/_react.default.createElement(_RowCheckbox.RowCheckbox, {
onClick: this.props.onCheckboxClick,
rowData: this.props.rowData,
selected: this.props.selected
});
}
} else if (this.props.rowReorder) {
var showReorder = true;
if (this.props.showRowReorderElement) {
showReorder = this.props.showRowReorderElement(this.props.rowData);
}
if (showReorder) {
var reorderIcon = (0, _classnames.default)('p-table-reorderablerow-handle', this.props.rowReorderIcon);
content = /*#__PURE__*/_react.default.createElement("i", {
className: reorderIcon
});
}
} else if (this.props.rowEditor) {
if (this.state.editing) {
content = /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("button", {
type: "button",
onClick: this.props.onRowEditSave,
className: "p-row-editor-save p-link"
}, /*#__PURE__*/_react.default.createElement("span", {
className: "p-row-editor-save-icon pi pi-fw pi-check p-clickable"
})), /*#__PURE__*/_react.default.createElement("button", {
type: "button",
onClick: this.props.onRowEditCancel,
className: "p-row-editor-cancel p-link"
}, /*#__PURE__*/_react.default.createElement("span", {
className: "p-row-editor-cancel-icon pi pi-fw pi-times p-clickable"
})));
} else {
content = /*#__PURE__*/_react.default.createElement("button", {
type: "button",
onClick: this.props.onRowEditInit,
className: "p-row-editor-init p-link"
}, /*#__PURE__*/_react.default.createElement("span", {
className: "p-row-editor-init-icon pi pi-fw pi-pencil p-clickable"
}));
}
} else {
if (this.state.editing && this.props.editor) {
content = this.props.editor(this.props);
} else {
if (this.props.body) content = this.props.body(this.props.rowData, this.props);else content = _ObjectUtils.default.resolveFieldData(this.props.rowData, this.props.field);
}
}
if (this.props.responsive) {
header = /*#__PURE__*/_react.default.createElement("span", {
className: "p-column-title"
}, this.props.header);
}
if (this.props.editMode !== 'row') {
/* eslint-disable */
editorKeyHelper = this.props.editor && /*#__PURE__*/_react.default.createElement("a", {
tabIndex: "0",
ref: function ref(el) {
_this5.keyHelper = el;
},
className: "p-cell-editor-key-helper p-hidden-accessible",
onFocus: this.onEditorFocus
}, /*#__PURE__*/_react.default.createElement("span", null));
/* eslint-enable */
}
return /*#__PURE__*/_react.default.createElement("td", {
ref: function ref(el) {
_this5.container = el;
},
className: cellClassName,
style: this.props.bodyStyle || this.props.style,
onClick: this.onClick,
onKeyDown: this.onKeyDown,
rowSpan: this.props.rowSpan,
onBlur: this.onBlur
}, header, editorKeyHelper, content);
}
}], [{
key: "getDerivedStateFromProps",
value: function getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.editMode === 'row' && nextProps.editing !== prevState.editing) {
return {
editing: nextProps.editing
};
}
return null;
}
}]);
return BodyCell;
}(_react.Component);
exports.BodyCell = BodyCell; |
module.exports = {
output: {
filename: 'bundle.js'
},
// Turn on sourcemaps
devtool: 'source-map',
resolve: {
extensions: ['', '.webpack.js', '.web.js', '.ts', '.js']
},
// Add minification
plugins: [
//new webpack.optimize.UglifyJsPlugin()
],
module: {
preLoaders: [
{
test: /\.js$/,
loader: "source-map-loader"
}
],
loaders: [
{ test: /\.ts$/, loader: 'ts' }
]
}
}
|
'use strict';
const common = require('../common.js');
const bench = common.createBenchmark(main, {
method: ['for', 'for-of', 'for-in', 'forEach'],
count: [5, 10, 20, 100],
millions: [5]
});
function useFor(n, items, count) {
var i, j;
bench.start();
for (i = 0; i < n; i++) {
for (j = 0; j < count; j++) {
/* eslint-disable no-unused-vars */
var item = items[j];
/* esline-enable no-unused-vars */
}
}
bench.end(n / 1e6);
}
function useForOf(n, items) {
var i, item;
bench.start();
for (i = 0; i < n; i++) {
for (item of items) {}
}
bench.end(n / 1e6);
}
function useForIn(n, items) {
var i, j, item;
bench.start();
for (i = 0; i < n; i++) {
for (j in items) {
/* eslint-disable no-unused-vars */
item = items[j];
/* esline-enable no-unused-vars */
}
}
bench.end(n / 1e6);
}
function useForEach(n, items) {
var i;
bench.start();
for (i = 0; i < n; i++) {
items.forEach((item) => {});
}
bench.end(n / 1e6);
}
function main(conf) {
const n = +conf.millions * 1e6;
const count = +conf.count;
const items = new Array(count);
var i;
var fn;
for (i = 0; i < count; i++)
items[i] = i;
switch (conf.method) {
case 'for':
fn = useFor;
break;
case 'for-of':
fn = useForOf;
break;
case 'for-in':
fn = useForIn;
break;
case 'forEach':
fn = useForEach;
break;
default:
throw new Error('Unexpected method');
}
fn(n, items, count);
}
|
/**
* A very simple node web server that will respond to requests
* with the Tropo WebAPI JSON version of "Hello, World!"
*/
var http = require('http');
var tropowebapi = require('tropo-webapi');
var server = http.createServer(function (request, response) {
// Create a new instance of the TropoWebAPI object.
var tropo = new tropowebapi.TropoWebAPI();
tropo.say("Hello, World!");
// Render out the JSON for Tropo to consume.
response.writeHead(200, {'Content-Type': 'application/json'});
response.end(tropowebapi.TropoJSON(tropo));
}).listen(8000); // Listen on port 8000 for requests. |
import { canDefineNonEnumerableProperties } from 'ember-metal/platform';
/**
Returns all of the keys defined on an object or hash. This is useful
when inspecting objects for debugging. On browsers that support it, this
uses the native `Object.keys` implementation.
@method keys
@for Ember
@param {Object} obj
@return {Array} Array containing keys of obj
*/
var keys = Object.keys;
if (!keys || !canDefineNonEnumerableProperties) {
// modified from
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
keys = (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
return function keys(obj) {
if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
throw new TypeError('Object.keys called on non-object');
}
var result = [], prop, i;
for (prop in obj) {
if (prop !== '_super' &&
prop.lastIndexOf('__',0) !== 0 &&
hasOwnProperty.call(obj, prop)) {
result.push(prop);
}
}
if (hasDontEnumBug) {
for (i = 0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) {
result.push(dontEnums[i]);
}
}
}
return result;
};
}());
}
export default keys;
|
/*
* routing-proxy.js: A routing proxy consuming a RoutingTable and multiple HttpProxy instances
*
* (C) 2011 Nodejitsu Inc.
* MIT LICENCE
*
*/
var events = require('events'),
util = require('util'),
HttpProxy = require('./http-proxy').HttpProxy,
ProxyTable = require('./proxy-table').ProxyTable;
//
// ### function RoutingProxy (options)
// #### @options {Object} Options for this instance
// Constructor function for the RoutingProxy object, a higher level
// reverse proxy Object which can proxy to multiple hosts and also interface
// easily with a RoutingTable instance.
//
var RoutingProxy = exports.RoutingProxy = function (options) {
events.EventEmitter.call(this);
var self = this;
options = options || {};
if (options.router) {
this.proxyTable = new ProxyTable(options);
this.proxyTable.on('routes', function (routes) {
self.emit('routes', routes);
});
}
//
// Create a set of `HttpProxy` objects to be used later on calls
// to `.proxyRequest()` and `.proxyWebSocketRequest()`.
//
this.proxies = {};
//
// Setup default target options (such as `https`).
//
this.target = {};
this.target.https = options.target && options.target.https;
//
// Setup other default options to be used for instances of
// `HttpProxy` created by this `RoutingProxy` instance.
//
this.source = options.source || { host: 'localhost', port: 8000 };
this.https = this.source.https || options.https;
this.enable = options.enable;
this.forward = options.forward;
this.changeOrigin = options.changeOrigin || false;
//
// Listen for 'newListener' events so that we can bind 'proxyError'
// listeners to each HttpProxy's 'proxyError' event.
//
this.on('newListener', function (evt) {
if (evt === 'proxyError' || evt === 'webSocketProxyError') {
Object.keys(self.proxies).forEach(function (key) {
self.proxies[key].on(evt, this.emit.bind(this, evt));
});
}
});
};
//
// Inherit from `events.EventEmitter`.
//
util.inherits(RoutingProxy, events.EventEmitter);
//
// ### function add (options)
// #### @options {Object} Options for the `HttpProxy` to add.
// Adds a new instance of `HttpProxy` to this `RoutingProxy` instance
// for the specified `options.host` and `options.port`.
//
RoutingProxy.prototype.add = function (options) {
var self = this,
key = this._getKey(options);
//
// TODO: Consume properties in `options` related to the `ProxyTable`.
//
options.target = options.target || {};
options.target.host = options.target.host || options.host;
options.target.port = options.target.port || options.port;
options.target.https = this.target && this.target.https ||
options.target && options.target.https;
//
// Setup options to pass-thru to the new `HttpProxy` instance
// for the specified `options.host` and `options.port` pair.
//
['https', 'enable', 'forward', 'changeOrigin'].forEach(function (key) {
if (options[key] !== false && self[key]) {
options[key] = self[key];
}
});
this.proxies[key] = new HttpProxy(options);
if (this.listeners('proxyError').length > 0) {
this.proxies[key].on('proxyError', this.emit.bind(this, 'proxyError'));
}
if (this.listeners('webSocketProxyError').length > 0) {
this.proxies[key].on('webSocketProxyError', this.emit.bind(this, 'webSocketProxyError'));
}
this.proxies[key].on('start', this.emit.bind(this, 'start'));
this.proxies[key].on('forward', this.emit.bind(this, 'forward'));
this.proxies[key].on('end', this.emit.bind(this, 'end'));
};
//
// ### function remove (options)
// #### @options {Object} Options mapping to the `HttpProxy` to remove.
// Removes an instance of `HttpProxy` from this `RoutingProxy` instance
// for the specified `options.host` and `options.port` (if they exist).
//
RoutingProxy.prototype.remove = function (options) {
var key = this._getKey(options),
proxy = this.proxies[key];
delete this.proxies[key];
return proxy;
};
//
// ### function close()
// Cleans up any state left behind (sockets, timeouts, etc)
// associated with this instance.
//
RoutingProxy.prototype.close = function () {
var self = this;
if (this.proxyTable) {
//
// Close the `RoutingTable` associated with
// this instance (if any).
//
this.proxyTable.close();
}
//
// Close all sockets for all `HttpProxy` object(s)
// associated with this instance.
//
Object.keys(this.proxies).forEach(function (key) {
self.proxies[key].close();
});
};
//
// ### function proxyRequest (req, res, [port, host, paused])
// #### @req {ServerRequest} Incoming HTTP Request to proxy.
// #### @res {ServerResponse} Outgoing HTTP Request to write proxied data to.
// #### @options {Object} Options for the outgoing proxy request.
//
// options.port {number} Port to use on the proxy target host.
// options.host {string} Host of the proxy target.
// options.buffer {Object} Result from `httpProxy.buffer(req)`
// options.https {Object|boolean} Settings for https.
//
RoutingProxy.prototype.proxyRequest = function (req, res, options) {
options = options || {};
var location;
//
// Check the proxy table for this instance to see if we need
// to get the proxy location for the request supplied. We will
// always ignore the proxyTable if an explicit `port` and `host`
// arguments are supplied to `proxyRequest`.
//
if (this.proxyTable && !options.host) {
location = this.proxyTable.getProxyLocation(req);
//
// If no location is returned from the ProxyTable instance
// then respond with `404` since we do not have a valid proxy target.
//
if (!location) {
try {
res.writeHead(404);
res.end();
}
catch (er) {
console.error("res.writeHead/res.end error: %s", er.message);
}
return;
}
//
// When using the ProxyTable in conjunction with an HttpProxy instance
// only the following arguments are valid:
//
// * `proxy.proxyRequest(req, res, { host: 'localhost' })`: This will be skipped
// * `proxy.proxyRequest(req, res, { buffer: buffer })`: Buffer will get updated appropriately
// * `proxy.proxyRequest(req, res)`: Options will be assigned appropriately.
//
options.port = location.port;
options.host = location.host;
}
var key = this._getKey(options),
proxy;
if ((this.target && this.target.https)
|| (location && location.protocol === 'https')) {
options.target = options.target || {};
options.target.https = true;
}
if (!this.proxies[key]) {
this.add(options);
}
proxy = this.proxies[key];
proxy.proxyRequest(req, res, options.buffer);
};
//
// ### function proxyWebSocketRequest (req, socket, head, options)
// #### @req {ServerRequest} Websocket request to proxy.
// #### @socket {net.Socket} Socket for the underlying HTTP request
// #### @head {string} Headers for the Websocket request.
// #### @options {Object} Options to use when proxying this request.
//
// options.port {number} Port to use on the proxy target host.
// options.host {string} Host of the proxy target.
// options.buffer {Object} Result from `httpProxy.buffer(req)`
// options.https {Object|boolean} Settings for https.
//
RoutingProxy.prototype.proxyWebSocketRequest = function (req, socket, head, options) {
options = options || {};
var location,
proxy,
key;
if (this.proxyTable && !options.host) {
location = this.proxyTable.getProxyLocation(req);
if (!location) {
return socket.destroy();
}
options.port = location.port;
options.host = location.host;
}
key = this._getKey(options);
if (!this.proxies[key]) {
this.add(options);
}
proxy = this.proxies[key];
proxy.proxyWebSocketRequest(req, socket, head, options.buffer);
};
//
// ### @private function _getKey (options)
// #### @options {Object} Options to extract the key from
// Ensures that the appropriate options are present in the `options`
// provided and responds with a string key representing the `host`, `port`
// combination contained within.
//
RoutingProxy.prototype._getKey = function (options) {
if (!options || ((!options.host || !options.port)
&& (!options.target || !options.target.host || !options.target.port))) {
throw new Error('options.host and options.port or options.target are required.');
}
return [
options.host || options.target.host,
options.port || options.target.port
].join(':');
};
|
$(document).ready(function () {
// Set the default CSS theme and icon library globally
JSONEditor.defaults.theme = 'bootstrap3';
JSONEditor.defaults.iconlib = 'fontawesome4';
var partials = window.partials;
var editor = null;
JSONEditor.defaults.editors.templateSelect = JSONEditor.defaults.editors.select.extend({
preBuild: function () {
this.enum_options = partials;
this.enum_display = partials;
this.enum_values = partials;
},
setValue: function (value, initial) {
this._super(value, initial);
},
onInputChange: function () {
this._super();
var that = this;
$.get("/schema/" + this.value, function (data) {
var value = editor.getValue();
data.properties["template"] = { "type": "string", "format": "template" };
that.parent.schema = data;
var topEditor = that;
while (topEditor.parent) {
topEditor = topEditor.parent;
}
var schema = topEditor.schema;
editor.destroy();
editor = new JSONEditor(document.getElementById('editor_holder'), {
schema: schema
});
editor.setValue(value);
//that.init();
//that.parent.build();
});
}
});
JSONEditor.defaults.resolvers.unshift(function (schema) {
if (schema.type === "string" && schema.format === "template") {
return "templateSelect";
}
});
var schemaUrl = window.schemaUrl;
var dataUrl = window.dataUrl;
$.get(schemaUrl, function (data) {
editor = new JSONEditor(document.getElementById('editor_holder'), {
schema: data
});
$.get(dataUrl, function (model) {
editor.setValue(model);
});
});
// Hook up the submit button to log to the console
$('#' + window.saveactionid).click(function () {
// Get the value from the editor
console.log(editor.getValue());
if (editor.validate()) {
$.ajax({
type: 'PUT',
url: dataUrl,
data: JSON.stringify(editor.getValue()),
headers: { "Content-Type": "application/json" },
});
}
});
}); |
import { module, test } from "qunit";
import spawnInjector from "inject-loader!services/streaming/spawn";
import ExecObj from "services/streaming/exec-obj";
module( "services/streaming/spawn" );
test( "Merge parameters and options", assert => {
assert.expect( 3 );
let callback;
let execObj;
const spawn = spawnInjector({
"./logger": {
logDebug() {}
},
"utils/node/child_process/spawn": function() {
return callback( ...arguments );
}
})[ "default" ];
callback = ( command, params, options ) => {
assert.strictEqual( command, "foo", "Uses the correct command" );
assert.deepEqual( params, [ "baz", "foo", "bar" ], "Appends the params" );
assert.propEqual(
options,
{ detached: true, env: { foo: "bar", qux: "quux" } },
"Merges the env options property"
);
};
execObj = new ExecObj(
"foo",
[ "baz" ],
{ qux: "quux" }
);
spawn( execObj, [ "foo", "bar" ], { detached: true, env: { foo: "bar" } } );
});
|
module.exports = function (classes){
'use strict';
var debug = require('debug')('jsonrpc');
var EventEmitter = classes.ES5Class.$define('EventEmitter', {}, {
/**
* Output a piece of debug information.
*/
trace : function (direction, message){
var msg = ' ' + direction + ' ' + message;
debug(msg);
return msg;
},
/**
* Check if current request has an integer id
* @param {Object} request
* @return {Boolean}
*/
hasId : function (request){
return request && typeof request['id'] !== 'undefined' && /^\-?\d+$/.test(request['id']);
}
}).$inherit(require('eventemitter3').EventEmitter, []);
return EventEmitter;
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.