code
stringlengths 2
1.05M
|
---|
$(function () {
function tally(selector) {
$(selector).each(function () {
var total = 0,
column = $(this).siblings(selector).andSelf().index(this);
$(this).parents().prevUntil(':has(' + selector + ')').each(function () {
total += parseFloat($('td.sum:eq(' + column + ')', this).html()) || 0;
})
$(this).html(total);
});
}
tally('td.subtotal');
});
|
// Download the Node helper library from twilio.com/docs/node/install
// These consts are your accountSid and authToken from https://www.twilio.com/console
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);
client.sip
.ipAccessControlLists('AL32a3c49700934481addd5ce1659f04d2')
.ipAddresses.each(ipAddress => {
console.log(ipAddress.friendlyName);
});
|
module.exports = {
plugins: [
require('postcss-custom-media'),
require('postcss-media-minmax'),
require('autoprefixer')
]
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;
var uuidGen = Cc["@mozilla.org/uuid-generator;1"]
.getService(Ci.nsIUUIDGenerator);
var loader = Cc["@mozilla.org/moz/jssubscript-loader;1"]
.getService(Ci.mozIJSSubScriptLoader);
loader.loadSubScript("chrome://marionette/content/simpletest.js");
loader.loadSubScript("chrome://marionette/content/common.js");
loader.loadSubScript("chrome://marionette/content/actions.js");
Cu.import("chrome://marionette/content/capture.js");
Cu.import("chrome://marionette/content/elements.js");
Cu.import("chrome://marionette/content/error.js");
Cu.import("resource://gre/modules/FileUtils.jsm");
Cu.import("resource://gre/modules/NetUtil.jsm");
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
var utils = {};
utils.window = content;
// Load Event/ChromeUtils for use with JS scripts:
loader.loadSubScript("chrome://marionette/content/EventUtils.js", utils);
loader.loadSubScript("chrome://marionette/content/ChromeUtils.js", utils);
loader.loadSubScript("chrome://marionette/content/atoms.js", utils);
loader.loadSubScript("chrome://marionette/content/sendkeys.js", utils);
var marionetteLogObj = new MarionetteLogObj();
var isB2G = false;
var marionetteTestName;
var winUtil = content.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowUtils);
var listenerId = null; // unique ID of this listener
var curContainer = { frame: content, shadowRoot: null };
var isRemoteBrowser = () => curContainer.frame.contentWindow !== null;
var previousContainer = null;
var elementManager = new ElementManager([]);
var accessibility = new Accessibility();
var actions = new ActionChain(utils, checkForInterrupted);
var importedScripts = null;
// Contains the last file input element that was the target of
// sendKeysToElement.
var fileInputElement;
// A dict of sandboxes used this session
var sandboxes = {};
// The name of the current sandbox
var sandboxName = 'default';
// the unload handler
var onunload;
// Flag to indicate whether an async script is currently running or not.
var asyncTestRunning = false;
var asyncTestCommandId;
var asyncTestTimeoutId;
var inactivityTimeoutId = null;
var heartbeatCallback = function () {}; // Called by the simpletest methods.
var originalOnError;
//timer for doc changes
var checkTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
//timer for readystate
var readyStateTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
// timer for navigation commands.
var navTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
var onDOMContentLoaded;
// Send move events about this often
var EVENT_INTERVAL = 30; // milliseconds
// last touch for each fingerId
var multiLast = {};
Cu.import("resource://gre/modules/Log.jsm");
var logger = Log.repository.getLogger("Marionette");
logger.info("loaded listener.js");
var modalHandler = function() {
// This gets called on the system app only since it receives the mozbrowserprompt event
sendSyncMessage("Marionette:switchedToFrame", { frameValue: null, storePrevious: true });
let isLocal = sendSyncMessage("MarionetteFrame:handleModal", {})[0].value;
if (isLocal) {
previousContainer = curContainer;
}
curContainer = { frame: content, shadowRoot: null };
};
/**
* Called when listener is first started up.
* The listener sends its unique window ID and its current URI to the actor.
* If the actor returns an ID, we start the listeners. Otherwise, nothing happens.
*/
function registerSelf() {
let msg = {value: winUtil.outerWindowID};
// register will have the ID and a boolean describing if this is the main process or not
let register = sendSyncMessage("Marionette:register", msg);
if (register[0]) {
let {id, remotenessChange} = register[0][0];
let {B2G, raisesAccessibilityExceptions} = register[0][2];
isB2G = B2G;
accessibility.strict = raisesAccessibilityExceptions;
listenerId = id;
if (typeof id != "undefined") {
// check if we're the main process
if (register[0][1] == true) {
addMessageListener("MarionetteMainListener:emitTouchEvent", emitTouchEventForIFrame);
}
importedScripts = FileUtils.getDir('TmpD', [], false);
importedScripts.append('marionetteContentScripts');
startListeners();
let rv = {};
if (remotenessChange) {
rv.listenerId = id;
}
sendAsyncMessage("Marionette:listenersAttached", rv);
}
}
}
function emitTouchEventForIFrame(message) {
message = message.json;
let identifier = actions.nextTouchId;
let domWindowUtils = curContainer.frame.
QueryInterface(Components.interfaces.nsIInterfaceRequestor).
getInterface(Components.interfaces.nsIDOMWindowUtils);
var ratio = domWindowUtils.screenPixelsPerCSSPixel;
var typeForUtils;
switch (message.type) {
case 'touchstart':
typeForUtils = domWindowUtils.TOUCH_CONTACT;
break;
case 'touchend':
typeForUtils = domWindowUtils.TOUCH_REMOVE;
break;
case 'touchcancel':
typeForUtils = domWindowUtils.TOUCH_CANCEL;
break;
case 'touchmove':
typeForUtils = domWindowUtils.TOUCH_CONTACT;
break;
}
domWindowUtils.sendNativeTouchPoint(identifier, typeForUtils,
Math.round(message.screenX * ratio), Math.round(message.screenY * ratio),
message.force, 90);
}
// Eventually we will not have a closure for every single command, but
// use a generic dispatch for all listener commands.
//
// Perhaps one could even conceive having a separate instance of
// CommandProcessor for the listener, because the code is mostly the same.
function dispatch(fn) {
return function(msg) {
let id = msg.json.command_id;
let req = Task.spawn(function*() {
if (typeof msg.json == "undefined" || msg.json instanceof Array) {
return yield fn.apply(null, msg.json);
} else {
return yield fn(msg.json);
}
});
let okOrValueResponse = rv => {
if (typeof rv == "undefined") {
sendOk(id);
} else {
sendResponse({value: rv}, id);
}
};
req.then(okOrValueResponse, err => sendError(err, id))
.catch(error.report);
};
}
/**
* Add a message listener that's tied to our listenerId.
*/
function addMessageListenerId(messageName, handler) {
addMessageListener(messageName + listenerId, handler);
}
/**
* Remove a message listener that's tied to our listenerId.
*/
function removeMessageListenerId(messageName, handler) {
removeMessageListener(messageName + listenerId, handler);
}
var getTitleFn = dispatch(getTitle);
var getPageSourceFn = dispatch(getPageSource);
var getActiveElementFn = dispatch(getActiveElement);
var clickElementFn = dispatch(clickElement);
var goBackFn = dispatch(goBack);
var getElementAttributeFn = dispatch(getElementAttribute);
var getElementTextFn = dispatch(getElementText);
var getElementTagNameFn = dispatch(getElementTagName);
var getElementRectFn = dispatch(getElementRect);
var isElementEnabledFn = dispatch(isElementEnabled);
var getCurrentUrlFn = dispatch(getCurrentUrl);
var findElementContentFn = dispatch(findElementContent);
var findElementsContentFn = dispatch(findElementsContent);
var isElementSelectedFn = dispatch(isElementSelected);
var clearElementFn = dispatch(clearElement);
var isElementDisplayedFn = dispatch(isElementDisplayed);
var getElementValueOfCssPropertyFn = dispatch(getElementValueOfCssProperty);
var switchToShadowRootFn = dispatch(switchToShadowRoot);
var getCookiesFn = dispatch(getCookies);
var singleTapFn = dispatch(singleTap);
var takeScreenshotFn = dispatch(takeScreenshot);
/**
* Start all message listeners
*/
function startListeners() {
addMessageListenerId("Marionette:receiveFiles", receiveFiles);
addMessageListenerId("Marionette:newSession", newSession);
addMessageListenerId("Marionette:executeScript", executeScript);
addMessageListenerId("Marionette:executeAsyncScript", executeAsyncScript);
addMessageListenerId("Marionette:executeJSScript", executeJSScript);
addMessageListenerId("Marionette:singleTap", singleTapFn);
addMessageListenerId("Marionette:actionChain", actionChain);
addMessageListenerId("Marionette:multiAction", multiAction);
addMessageListenerId("Marionette:get", get);
addMessageListenerId("Marionette:pollForReadyState", pollForReadyState);
addMessageListenerId("Marionette:cancelRequest", cancelRequest);
addMessageListenerId("Marionette:getCurrentUrl", getCurrentUrlFn);
addMessageListenerId("Marionette:getTitle", getTitleFn);
addMessageListenerId("Marionette:getPageSource", getPageSourceFn);
addMessageListenerId("Marionette:goBack", goBackFn);
addMessageListenerId("Marionette:goForward", goForward);
addMessageListenerId("Marionette:refresh", refresh);
addMessageListenerId("Marionette:findElementContent", findElementContentFn);
addMessageListenerId("Marionette:findElementsContent", findElementsContentFn);
addMessageListenerId("Marionette:getActiveElement", getActiveElementFn);
addMessageListenerId("Marionette:clickElement", clickElementFn);
addMessageListenerId("Marionette:getElementAttribute", getElementAttributeFn);
addMessageListenerId("Marionette:getElementText", getElementTextFn);
addMessageListenerId("Marionette:getElementTagName", getElementTagNameFn);
addMessageListenerId("Marionette:isElementDisplayed", isElementDisplayedFn);
addMessageListenerId("Marionette:getElementValueOfCssProperty", getElementValueOfCssPropertyFn);
addMessageListenerId("Marionette:getElementRect", getElementRectFn);
addMessageListenerId("Marionette:isElementEnabled", isElementEnabledFn);
addMessageListenerId("Marionette:isElementSelected", isElementSelectedFn);
addMessageListenerId("Marionette:sendKeysToElement", sendKeysToElement);
addMessageListenerId("Marionette:clearElement", clearElementFn);
addMessageListenerId("Marionette:switchToFrame", switchToFrame);
addMessageListenerId("Marionette:switchToParentFrame", switchToParentFrame);
addMessageListenerId("Marionette:switchToShadowRoot", switchToShadowRootFn);
addMessageListenerId("Marionette:deleteSession", deleteSession);
addMessageListenerId("Marionette:sleepSession", sleepSession);
addMessageListenerId("Marionette:emulatorCmdResult", emulatorCmdResult);
addMessageListenerId("Marionette:importScript", importScript);
addMessageListenerId("Marionette:getAppCacheStatus", getAppCacheStatus);
addMessageListenerId("Marionette:setTestName", setTestName);
addMessageListenerId("Marionette:takeScreenshot", takeScreenshotFn);
addMessageListenerId("Marionette:addCookie", addCookie);
addMessageListenerId("Marionette:getCookies", getCookiesFn);
addMessageListenerId("Marionette:deleteAllCookies", deleteAllCookies);
addMessageListenerId("Marionette:deleteCookie", deleteCookie);
}
/**
* Used during newSession and restart, called to set up the modal dialog listener in b2g
*/
function waitForReady() {
if (content.document.readyState == 'complete') {
readyStateTimer.cancel();
content.addEventListener("mozbrowsershowmodalprompt", modalHandler, false);
content.addEventListener("unload", waitForReady, false);
}
else {
readyStateTimer.initWithCallback(waitForReady, 100, Ci.nsITimer.TYPE_ONE_SHOT);
}
}
/**
* Called when we start a new session. It registers the
* current environment, and resets all values
*/
function newSession(msg) {
isB2G = msg.json.B2G;
accessibility.strict = msg.json.raisesAccessibilityExceptions;
resetValues();
if (isB2G) {
readyStateTimer.initWithCallback(waitForReady, 100, Ci.nsITimer.TYPE_ONE_SHOT);
// We have to set correct mouse event source to MOZ_SOURCE_TOUCH
// to offer a way for event listeners to differentiate
// events being the result of a physical mouse action.
// This is especially important for the touch event shim,
// in order to prevent creating touch event for these fake mouse events.
actions.inputSource = Ci.nsIDOMMouseEvent.MOZ_SOURCE_TOUCH;
}
}
/**
* Puts the current session to sleep, so all listeners are removed except
* for the 'restart' listener. This is used to keep the content listener
* alive for reuse in B2G instead of reloading it each time.
*/
function sleepSession(msg) {
deleteSession();
addMessageListener("Marionette:restart", restart);
}
/**
* Restarts all our listeners after this listener was put to sleep
*/
function restart(msg) {
removeMessageListener("Marionette:restart", restart);
if (isB2G) {
readyStateTimer.initWithCallback(waitForReady, 100, Ci.nsITimer.TYPE_ONE_SHOT);
}
registerSelf();
}
/**
* Removes all listeners
*/
function deleteSession(msg) {
removeMessageListenerId("Marionette:receiveFiles", receiveFiles);
removeMessageListenerId("Marionette:newSession", newSession);
removeMessageListenerId("Marionette:executeScript", executeScript);
removeMessageListenerId("Marionette:executeAsyncScript", executeAsyncScript);
removeMessageListenerId("Marionette:executeJSScript", executeJSScript);
removeMessageListenerId("Marionette:singleTap", singleTapFn);
removeMessageListenerId("Marionette:actionChain", actionChain);
removeMessageListenerId("Marionette:multiAction", multiAction);
removeMessageListenerId("Marionette:get", get);
removeMessageListenerId("Marionette:pollForReadyState", pollForReadyState);
removeMessageListenerId("Marionette:cancelRequest", cancelRequest);
removeMessageListenerId("Marionette:getTitle", getTitleFn);
removeMessageListenerId("Marionette:getPageSource", getPageSourceFn);
removeMessageListenerId("Marionette:getCurrentUrl", getCurrentUrlFn);
removeMessageListenerId("Marionette:goBack", goBackFn);
removeMessageListenerId("Marionette:goForward", goForward);
removeMessageListenerId("Marionette:refresh", refresh);
removeMessageListenerId("Marionette:findElementContent", findElementContentFn);
removeMessageListenerId("Marionette:findElementsContent", findElementsContentFn);
removeMessageListenerId("Marionette:getActiveElement", getActiveElementFn);
removeMessageListenerId("Marionette:clickElement", clickElementFn);
removeMessageListenerId("Marionette:getElementAttribute", getElementAttributeFn);
removeMessageListenerId("Marionette:getElementText", getElementTextFn);
removeMessageListenerId("Marionette:getElementTagName", getElementTagNameFn);
removeMessageListenerId("Marionette:isElementDisplayed", isElementDisplayedFn);
removeMessageListenerId("Marionette:getElementValueOfCssProperty", getElementValueOfCssPropertyFn);
removeMessageListenerId("Marionette:getElementRect", getElementRectFn);
removeMessageListenerId("Marionette:isElementEnabled", isElementEnabledFn);
removeMessageListenerId("Marionette:isElementSelected", isElementSelectedFn);
removeMessageListenerId("Marionette:sendKeysToElement", sendKeysToElement);
removeMessageListenerId("Marionette:clearElement", clearElementFn);
removeMessageListenerId("Marionette:switchToFrame", switchToFrame);
removeMessageListenerId("Marionette:switchToParentFrame", switchToParentFrame);
removeMessageListenerId("Marionette:switchToShadowRoot", switchToShadowRootFn);
removeMessageListenerId("Marionette:deleteSession", deleteSession);
removeMessageListenerId("Marionette:sleepSession", sleepSession);
removeMessageListenerId("Marionette:emulatorCmdResult", emulatorCmdResult);
removeMessageListenerId("Marionette:importScript", importScript);
removeMessageListenerId("Marionette:getAppCacheStatus", getAppCacheStatus);
removeMessageListenerId("Marionette:setTestName", setTestName);
removeMessageListenerId("Marionette:takeScreenshot", takeScreenshotFn);
removeMessageListenerId("Marionette:addCookie", addCookie);
removeMessageListenerId("Marionette:getCookies", getCookiesFn);
removeMessageListenerId("Marionette:deleteAllCookies", deleteAllCookies);
removeMessageListenerId("Marionette:deleteCookie", deleteCookie);
if (isB2G) {
content.removeEventListener("mozbrowsershowmodalprompt", modalHandler, false);
}
elementManager.reset();
// reset container frame to the top-most frame
curContainer = { frame: content, shadowRoot: null };
curContainer.frame.focus();
actions.touchIds = {};
}
/*
* Helper methods
*/
/**
* Generic method to send a message to the server
*/
function sendToServer(name, data, objs, id) {
if (!data) {
data = {}
}
if (id) {
data.command_id = id;
}
sendAsyncMessage(name, data, objs);
}
/**
* Send response back to server
*/
function sendResponse(value, command_id) {
sendToServer("Marionette:done", value, null, command_id);
}
/**
* Send ack back to server
*/
function sendOk(command_id) {
sendToServer("Marionette:ok", null, null, command_id);
}
/**
* Send log message to server
*/
function sendLog(msg) {
sendToServer("Marionette:log", {message: msg});
}
/**
* Send error message to server
*/
function sendError(err, cmdId) {
sendToServer("Marionette:error", null, {error: err}, cmdId);
}
/**
* Clear test values after completion of test
*/
function resetValues() {
sandboxes = {};
curContainer = { frame: content, shadowRoot: null };
actions.mouseEventsOnly = false;
}
/**
* Dump a logline to stdout. Prepends logline with a timestamp.
*/
function dumpLog(logline) {
dump(Date.now() + " Marionette: " + logline);
}
/**
* Check if our context was interrupted
*/
function wasInterrupted() {
if (previousContainer) {
let element = content.document.elementFromPoint((content.innerWidth/2), (content.innerHeight/2));
if (element.id.indexOf("modal-dialog") == -1) {
return true;
}
else {
return false;
}
}
return sendSyncMessage("MarionetteFrame:getInterruptedState", {})[0].value;
}
function checkForInterrupted() {
if (wasInterrupted()) {
if (previousContainer) {
// if previousContainer is set, then we're in a single process environment
curContainer = actions.container = previousContainer;
previousContainer = null;
}
else {
//else we're in OOP environment, so we'll switch to the original OOP frame
sendSyncMessage("Marionette:switchToModalOrigin");
}
sendSyncMessage("Marionette:switchedToFrame", { restorePrevious: true });
}
}
/*
* Marionette Methods
*/
/**
* Returns a content sandbox that can be used by the execute_foo functions.
*/
function createExecuteContentSandbox(win, timeout) {
let mn = new Marionette(
win,
"content",
marionetteLogObj,
timeout,
heartbeatCallback,
marionetteTestName);
let principal = win;
if (sandboxName == "system") {
principal = Cc["@mozilla.org/systemprincipal;1"].createInstance(Ci.nsIPrincipal);
}
let sandbox = new Cu.Sandbox(principal, {sandboxPrototype: win});
sandbox.global = sandbox;
sandbox.window = win;
sandbox.document = sandbox.window.document;
sandbox.navigator = sandbox.window.navigator;
sandbox.testUtils = utils;
sandbox.asyncTestCommandId = asyncTestCommandId;
sandbox.marionette = mn;
mn.exports.forEach(fn => {
if (typeof mn[fn] == "function") {
sandbox[fn] = mn[fn].bind(mn);
} else {
sandbox[fn] = mn[fn];
}
});
sandbox.runEmulatorCmd = (cmd, cb) => this.runEmulatorCmd(cmd, cb);
sandbox.runEmulatorShell = (args, cb) => this.runEmulatorShell(args, cb);
sandbox.asyncComplete = (obj, id) => {
if (id == asyncTestCommandId) {
curContainer.frame.removeEventListener("unload", onunload, false);
curContainer.frame.clearTimeout(asyncTestTimeoutId);
if (inactivityTimeoutId != null) {
curContainer.frame.clearTimeout(inactivityTimeoutId);
}
sendSyncMessage("Marionette:shareData",
{log: elementManager.wrapValue(marionetteLogObj.getLogs())});
marionetteLogObj.clearLogs();
if (error.isError(obj)) {
sendError(obj, id);
} else {
if (Object.keys(_emu_cbs).length) {
_emu_cbs = {};
sendError(new WebDriverError("Emulator callback still pending when finish() called"), id);
} else {
sendResponse({value: elementManager.wrapValue(obj)}, id);
}
}
asyncTestRunning = false;
asyncTestTimeoutId = undefined;
asyncTestCommandId = undefined;
inactivityTimeoutId = null;
}
};
sandbox.finish = function() {
if (asyncTestRunning) {
sandbox.asyncComplete(mn.generate_results(), sandbox.asyncTestCommandId);
} else {
return mn.generate_results();
}
};
sandbox.marionetteScriptFinished = val =>
sandbox.asyncComplete(val, sandbox.asyncTestCommandId);
sandboxes[sandboxName] = sandbox;
}
/**
* Execute the given script either as a function body (executeScript)
* or directly (for mochitest like JS Marionette tests).
*/
function executeScript(msg, directInject) {
// Set up inactivity timeout.
if (msg.json.inactivityTimeout) {
let setTimer = function() {
inactivityTimeoutId = curContainer.frame.setTimeout(function() {
sendError(new ScriptTimeoutError("timed out due to inactivity"), asyncTestCommandId);
}, msg.json.inactivityTimeout);
};
setTimer();
heartbeatCallback = function() {
curContainer.frame.clearTimeout(inactivityTimeoutId);
setTimer();
};
}
asyncTestCommandId = msg.json.command_id;
let script = msg.json.script;
let filename = msg.json.filename;
sandboxName = msg.json.sandboxName;
if (msg.json.newSandbox ||
!(sandboxName in sandboxes) ||
(sandboxes[sandboxName].window != curContainer.frame)) {
createExecuteContentSandbox(curContainer.frame, msg.json.timeout);
if (!sandboxes[sandboxName]) {
sendError(new WebDriverError("Could not create sandbox!"), asyncTestCommandId);
return;
}
} else {
sandboxes[sandboxName].asyncTestCommandId = asyncTestCommandId;
}
let sandbox = sandboxes[sandboxName];
try {
if (directInject) {
if (importedScripts.exists()) {
let stream = Components.classes["@mozilla.org/network/file-input-stream;1"].
createInstance(Components.interfaces.nsIFileInputStream);
stream.init(importedScripts, -1, 0, 0);
let data = NetUtil.readInputStreamToString(stream, stream.available());
stream.close();
script = data + script;
}
let res = Cu.evalInSandbox(script, sandbox, "1.8", filename ? filename : "dummy file" ,0);
sendSyncMessage("Marionette:shareData",
{log: elementManager.wrapValue(marionetteLogObj.getLogs())});
marionetteLogObj.clearLogs();
if (res == undefined || res.passed == undefined) {
sendError(new JavaScriptError("Marionette.finish() not called"), asyncTestCommandId);
}
else {
sendResponse({value: elementManager.wrapValue(res)}, asyncTestCommandId);
}
}
else {
try {
sandbox.__marionetteParams = Cu.cloneInto(elementManager.convertWrappedArguments(
msg.json.args, curContainer), sandbox, { wrapReflectors: true });
} catch (e) {
sendError(e, asyncTestCommandId);
return;
}
script = "var __marionetteFunc = function(){" + script + "};" +
"__marionetteFunc.apply(null, __marionetteParams);";
if (importedScripts.exists()) {
let stream = Components.classes["@mozilla.org/network/file-input-stream;1"].
createInstance(Components.interfaces.nsIFileInputStream);
stream.init(importedScripts, -1, 0, 0);
let data = NetUtil.readInputStreamToString(stream, stream.available());
stream.close();
script = data + script;
}
let res = Cu.evalInSandbox(script, sandbox, "1.8", filename ? filename : "dummy file", 0);
sendSyncMessage("Marionette:shareData",
{log: elementManager.wrapValue(marionetteLogObj.getLogs())});
marionetteLogObj.clearLogs();
sendResponse({value: elementManager.wrapValue(res)}, asyncTestCommandId);
}
} catch (e) {
let err = new JavaScriptError(
e,
"execute_script",
msg.json.filename,
msg.json.line,
script);
sendError(err, asyncTestCommandId);
}
}
/**
* Sets the test name, used in logging messages.
*/
function setTestName(msg) {
marionetteTestName = msg.json.value;
sendOk(msg.json.command_id);
}
/**
* Execute async script
*/
function executeAsyncScript(msg) {
executeWithCallback(msg);
}
/**
* Receive file objects from chrome in order to complete a
* sendKeysToElement action on a file input element.
*/
function receiveFiles(msg) {
if ('error' in msg.json) {
let err = new InvalidArgumentError(msg.json.error);
sendError(err, msg.json.command_id);
return;
}
if (!fileInputElement) {
let err = new InvalidElementStateError("receiveFiles called with no valid fileInputElement");
sendError(err, msg.json.command_id);
return;
}
let fs = Array.prototype.slice.call(fileInputElement.files);
fs.push(msg.json.file);
fileInputElement.mozSetFileArray(fs);
fileInputElement = null;
sendOk(msg.json.command_id);
}
/**
* Execute pure JS test. Handles both async and sync cases.
*/
function executeJSScript(msg) {
if (msg.json.async) {
executeWithCallback(msg, msg.json.async);
}
else {
executeScript(msg, true);
}
}
/**
* This function is used by executeAsync and executeJSScript to execute a script
* in a sandbox.
*
* For executeJSScript, it will return a message only when the finish() method is called.
* For executeAsync, it will return a response when marionetteScriptFinished/arguments[arguments.length-1]
* method is called, or if it times out.
*/
function executeWithCallback(msg, useFinish) {
// Set up inactivity timeout.
if (msg.json.inactivityTimeout) {
let setTimer = function() {
inactivityTimeoutId = curContainer.frame.setTimeout(function() {
sandbox.asyncComplete(new ScriptTimeoutError("timed out due to inactivity"), asyncTestCommandId);
}, msg.json.inactivityTimeout);
};
setTimer();
heartbeatCallback = function() {
curContainer.frame.clearTimeout(inactivityTimeoutId);
setTimer();
};
}
let script = msg.json.script;
let filename = msg.json.filename;
asyncTestCommandId = msg.json.command_id;
sandboxName = msg.json.sandboxName;
onunload = function() {
sendError(new JavaScriptError("unload was called"), asyncTestCommandId);
};
curContainer.frame.addEventListener("unload", onunload, false);
if (msg.json.newSandbox ||
!(sandboxName in sandboxes) ||
(sandboxes[sandboxName].window != curContainer.frame)) {
createExecuteContentSandbox(curContainer.frame, msg.json.timeout);
if (!sandboxes[sandboxName]) {
sendError(new JavaScriptError("Could not create sandbox!"), asyncTestCommandId);
return;
}
}
else {
sandboxes[sandboxName].asyncTestCommandId = asyncTestCommandId;
}
let sandbox = sandboxes[sandboxName];
sandbox.tag = script;
asyncTestTimeoutId = curContainer.frame.setTimeout(function() {
sandbox.asyncComplete(new ScriptTimeoutError("timed out"), asyncTestCommandId);
}, msg.json.timeout);
originalOnError = curContainer.frame.onerror;
curContainer.frame.onerror = function errHandler(msg, url, line) {
sandbox.asyncComplete(new JavaScriptError(msg + "@" + url + ", line " + line), asyncTestCommandId);
curContainer.frame.onerror = originalOnError;
};
let scriptSrc;
if (useFinish) {
if (msg.json.timeout == null || msg.json.timeout == 0) {
sendError(new TimeoutError("Please set a timeout"), asyncTestCommandId);
}
scriptSrc = script;
}
else {
try {
sandbox.__marionetteParams = Cu.cloneInto(elementManager.convertWrappedArguments(
msg.json.args, curContainer), sandbox, { wrapReflectors: true });
} catch (e) {
sendError(e, asyncTestCommandId);
return;
}
scriptSrc = "__marionetteParams.push(marionetteScriptFinished);" +
"var __marionetteFunc = function() { " + script + "};" +
"__marionetteFunc.apply(null, __marionetteParams); ";
}
try {
asyncTestRunning = true;
if (importedScripts.exists()) {
let stream = Cc["@mozilla.org/network/file-input-stream;1"].
createInstance(Ci.nsIFileInputStream);
stream.init(importedScripts, -1, 0, 0);
let data = NetUtil.readInputStreamToString(stream, stream.available());
stream.close();
scriptSrc = data + scriptSrc;
}
Cu.evalInSandbox(scriptSrc, sandbox, "1.8", filename ? filename : "dummy file", 0);
} catch (e) {
let err = new JavaScriptError(
e,
"execute_async_script",
msg.json.filename,
msg.json.line,
scriptSrc);
sandbox.asyncComplete(err, asyncTestCommandId);
}
}
/**
* This function creates a touch event given a touch type and a touch
*/
function emitTouchEvent(type, touch) {
if (!wasInterrupted()) {
let loggingInfo = "emitting Touch event of type " + type + " to element with id: " + touch.target.id + " and tag name: " + touch.target.tagName + " at coordinates (" + touch.clientX + ", " + touch.clientY + ") relative to the viewport";
dumpLog(loggingInfo);
var docShell = curContainer.frame.document.defaultView.
QueryInterface(Components.interfaces.nsIInterfaceRequestor).
getInterface(Components.interfaces.nsIWebNavigation).
QueryInterface(Components.interfaces.nsIDocShell);
if (docShell.asyncPanZoomEnabled && actions.scrolling) {
// if we're in APZ and we're scrolling, we must use injectTouchEvent to dispatch our touchmove events
let index = sendSyncMessage("MarionetteFrame:getCurrentFrameId");
// only call emitTouchEventForIFrame if we're inside an iframe.
if (index != null) {
sendSyncMessage("Marionette:emitTouchEvent",
{ index: index, type: type, id: touch.identifier,
clientX: touch.clientX, clientY: touch.clientY,
screenX: touch.screenX, screenY: touch.screenY,
radiusX: touch.radiusX, radiusY: touch.radiusY,
rotation: touch.rotationAngle, force: touch.force });
return;
}
}
// we get here if we're not in asyncPacZoomEnabled land, or if we're the main process
/*
Disabled per bug 888303
marionetteLogObj.log(loggingInfo, "TRACE");
sendSyncMessage("Marionette:shareData",
{log: elementManager.wrapValue(marionetteLogObj.getLogs())});
marionetteLogObj.clearLogs();
*/
let domWindowUtils = curContainer.frame.QueryInterface(Components.interfaces.nsIInterfaceRequestor).getInterface(Components.interfaces.nsIDOMWindowUtils);
domWindowUtils.sendTouchEvent(type, [touch.identifier], [touch.clientX], [touch.clientY], [touch.radiusX], [touch.radiusY], [touch.rotationAngle], [touch.force], 1, 0);
}
}
/**
* This function generates a pair of coordinates relative to the viewport given a
* target element and coordinates relative to that element's top-left corner.
* @param 'x', and 'y' are the relative to the target.
* If they are not specified, then the center of the target is used.
*/
function coordinates(target, x, y) {
let box = target.getBoundingClientRect();
if (x == null) {
x = box.width / 2;
}
if (y == null) {
y = box.height / 2;
}
let coords = {};
coords.x = box.left + x;
coords.y = box.top + y;
return coords;
}
/**
* This function returns true if the given coordinates are in the viewport.
* @param 'x', and 'y' are the coordinates relative to the target.
* If they are not specified, then the center of the target is used.
*/
function elementInViewport(el, x, y) {
let c = coordinates(el, x, y);
let curFrame = curContainer.frame;
let viewPort = {top: curFrame.pageYOffset,
left: curFrame.pageXOffset,
bottom: (curFrame.pageYOffset + curFrame.innerHeight),
right:(curFrame.pageXOffset + curFrame.innerWidth)};
return (viewPort.left <= c.x + curFrame.pageXOffset &&
c.x + curFrame.pageXOffset <= viewPort.right &&
viewPort.top <= c.y + curFrame.pageYOffset &&
c.y + curFrame.pageYOffset <= viewPort.bottom);
}
/**
* This function throws the visibility of the element error if the element is
* not displayed or the given coordinates are not within the viewport.
* @param 'x', and 'y' are the coordinates relative to the target.
* If they are not specified, then the center of the target is used.
*/
function checkVisible(el, x, y) {
// Bug 1094246 - Webdriver's isShown doesn't work with content xul
if (utils.getElementAttribute(el, "namespaceURI").indexOf("there.is.only.xul") == -1) {
//check if the element is visible
let visible = utils.isElementDisplayed(el);
if (!visible) {
return false;
}
}
if (el.tagName.toLowerCase() === 'body') {
return true;
}
if (!elementInViewport(el, x, y)) {
//check if scroll function exist. If so, call it.
if (el.scrollIntoView) {
el.scrollIntoView(false);
if (!elementInViewport(el)) {
return false;
}
}
else {
return false;
}
}
return true;
}
/**
* Function that perform a single tap
*/
function singleTap(id, corx, cory) {
let el = elementManager.getKnownElement(id, curContainer);
// after this block, the element will be scrolled into view
let visible = checkVisible(el, corx, cory);
if (!visible) {
throw new ElementNotVisibleError("Element is not currently visible and may not be manipulated");
}
return accessibility.getAccessibleObject(el, true).then(acc => {
checkVisibleAccessibility(acc, el, visible);
checkActionableAccessibility(acc, el);
if (!curContainer.frame.document.createTouch) {
actions.mouseEventsOnly = true;
}
let c = coordinates(el, corx, cory);
if (!actions.mouseEventsOnly) {
let touchId = actions.nextTouchId++;
let touch = createATouch(el, c.x, c.y, touchId);
emitTouchEvent('touchstart', touch);
emitTouchEvent('touchend', touch);
}
actions.mouseTap(el.ownerDocument, c.x, c.y);
});
}
/**
* Check if the element's unavailable accessibility state matches the enabled
* state
* @param nsIAccessible object
* @param WebElement corresponding to nsIAccessible object
* @param Boolean enabled element's enabled state
*/
function checkEnabledAccessibility(accesible, element, enabled) {
if (!accesible) {
return;
}
let disabledAccessibility = accessibility.matchState(
accesible, 'STATE_UNAVAILABLE');
let explorable = curContainer.frame.document.defaultView.getComputedStyle(
element, null).getPropertyValue('pointer-events') !== 'none';
let message;
if (!explorable && !disabledAccessibility) {
message = 'Element is enabled but is not explorable via the ' +
'accessibility API';
} else if (enabled && disabledAccessibility) {
message = 'Element is enabled but disabled via the accessibility API';
} else if (!enabled && !disabledAccessibility) {
message = 'Element is disabled but enabled via the accessibility API';
}
accessibility.handleErrorMessage(message, element);
}
/**
* Check if the element's visible state corresponds to its accessibility API
* visibility
* @param nsIAccessible object
* @param WebElement corresponding to nsIAccessible object
* @param Boolean visible element's visibility state
*/
function checkVisibleAccessibility(accesible, element, visible) {
if (!accesible) {
return;
}
let hiddenAccessibility = accessibility.isHidden(accesible);
let message;
if (visible && hiddenAccessibility) {
message = 'Element is not currently visible via the accessibility API ' +
'and may not be manipulated by it';
} else if (!visible && !hiddenAccessibility) {
message = 'Element is currently only visible via the accessibility API ' +
'and can be manipulated by it';
}
accessibility.handleErrorMessage(message, element);
}
/**
* Check if it is possible to activate an element with the accessibility API
* @param nsIAccessible object
* @param WebElement corresponding to nsIAccessible object
*/
function checkActionableAccessibility(accesible, element) {
if (!accesible) {
return;
}
let message;
if (!accessibility.hasActionCount(accesible)) {
message = 'Element does not support any accessible actions';
} else if (!accessibility.isActionableRole(accesible)) {
message = 'Element does not have a correct accessibility role ' +
'and may not be manipulated via the accessibility API';
} else if (!accessibility.hasValidName(accesible)) {
message = 'Element is missing an accesible name';
} else if (!accessibility.matchState(accesible, 'STATE_FOCUSABLE')) {
message = 'Element is not focusable via the accessibility API';
}
accessibility.handleErrorMessage(message, element);
}
/**
* Check if element's selected state corresponds to its accessibility API
* selected state.
* @param nsIAccessible object
* @param WebElement corresponding to nsIAccessible object
* @param Boolean selected element's selected state
*/
function checkSelectedAccessibility(accessible, element, selected) {
if (!accessible) {
return;
}
if (!accessibility.matchState(accessible, 'STATE_SELECTABLE')) {
// Element is not selectable via the accessibility API
return;
}
let selectedAccessibility = accessibility.matchState(
accessible, 'STATE_SELECTED');
let message;
if (selected && !selectedAccessibility) {
message = 'Element is selected but not selected via the accessibility API';
} else if (!selected && selectedAccessibility) {
message = 'Element is not selected but selected via the accessibility API';
}
accessibility.handleErrorMessage(message, element);
}
/**
* Function to create a touch based on the element
* corx and cory are relative to the viewport, id is the touchId
*/
function createATouch(el, corx, cory, touchId) {
let doc = el.ownerDocument;
let win = doc.defaultView;
let [clientX, clientY, pageX, pageY, screenX, screenY] =
actions.getCoordinateInfo(el, corx, cory);
let atouch = doc.createTouch(win, el, touchId, pageX, pageY, screenX, screenY, clientX, clientY);
return atouch;
}
/**
* Function to start action chain on one finger
*/
function actionChain(msg) {
let command_id = msg.json.command_id;
let args = msg.json.chain;
let touchId = msg.json.nextId;
let callbacks = {};
callbacks.onSuccess = value => sendResponse(value, command_id);
callbacks.onError = err => sendError(err, command_id);
let touchProvider = {};
touchProvider.createATouch = createATouch;
touchProvider.emitTouchEvent = emitTouchEvent;
try {
actions.dispatchActions(
args,
touchId,
curContainer,
elementManager,
callbacks,
touchProvider);
} catch (e) {
sendError(e, command_id);
}
}
/**
* Function to emit touch events which allow multi touch on the screen
* @param type represents the type of event, touch represents the current touch,touches are all pending touches
*/
function emitMultiEvents(type, touch, touches) {
let target = touch.target;
let doc = target.ownerDocument;
let win = doc.defaultView;
// touches that are in the same document
let documentTouches = doc.createTouchList(touches.filter(function(t) {
return ((t.target.ownerDocument === doc) && (type != 'touchcancel'));
}));
// touches on the same target
let targetTouches = doc.createTouchList(touches.filter(function(t) {
return ((t.target === target) && ((type != 'touchcancel') || (type != 'touchend')));
}));
// Create changed touches
let changedTouches = doc.createTouchList(touch);
// Create the event object
let event = doc.createEvent('TouchEvent');
event.initTouchEvent(type,
true,
true,
win,
0,
false, false, false, false,
documentTouches,
targetTouches,
changedTouches);
target.dispatchEvent(event);
}
/**
* Function to dispatch one set of actions
* @param touches represents all pending touches, batchIndex represents the batch we are dispatching right now
*/
function setDispatch(batches, touches, command_id, batchIndex) {
if (typeof batchIndex === "undefined") {
batchIndex = 0;
}
// check if all the sets have been fired
if (batchIndex >= batches.length) {
multiLast = {};
sendOk(command_id);
return;
}
// a set of actions need to be done
let batch = batches[batchIndex];
// each action for some finger
let pack;
// the touch id for the finger (pack)
let touchId;
// command for the finger
let command;
// touch that will be created for the finger
let el;
let corx;
let cory;
let touch;
let lastTouch;
let touchIndex;
let waitTime = 0;
let maxTime = 0;
let c;
batchIndex++;
// loop through the batch
for (let i = 0; i < batch.length; i++) {
pack = batch[i];
touchId = pack[0];
command = pack[1];
switch (command) {
case 'press':
el = elementManager.getKnownElement(pack[2], curContainer);
c = coordinates(el, pack[3], pack[4]);
touch = createATouch(el, c.x, c.y, touchId);
multiLast[touchId] = touch;
touches.push(touch);
emitMultiEvents('touchstart', touch, touches);
break;
case 'release':
touch = multiLast[touchId];
// the index of the previous touch for the finger may change in the touches array
touchIndex = touches.indexOf(touch);
touches.splice(touchIndex, 1);
emitMultiEvents('touchend', touch, touches);
break;
case 'move':
el = elementManager.getKnownElement(pack[2], curContainer);
c = coordinates(el);
touch = createATouch(multiLast[touchId].target, c.x, c.y, touchId);
touchIndex = touches.indexOf(lastTouch);
touches[touchIndex] = touch;
multiLast[touchId] = touch;
emitMultiEvents('touchmove', touch, touches);
break;
case 'moveByOffset':
el = multiLast[touchId].target;
lastTouch = multiLast[touchId];
touchIndex = touches.indexOf(lastTouch);
let doc = el.ownerDocument;
let win = doc.defaultView;
// since x and y are relative to the last touch, therefore, it's relative to the position of the last touch
let clientX = lastTouch.clientX + pack[2],
clientY = lastTouch.clientY + pack[3];
let pageX = clientX + win.pageXOffset,
pageY = clientY + win.pageYOffset;
let screenX = clientX + win.mozInnerScreenX,
screenY = clientY + win.mozInnerScreenY;
touch = doc.createTouch(win, el, touchId, pageX, pageY, screenX, screenY, clientX, clientY);
touches[touchIndex] = touch;
multiLast[touchId] = touch;
emitMultiEvents('touchmove', touch, touches);
break;
case 'wait':
if (pack[2] != undefined ) {
waitTime = pack[2]*1000;
if (waitTime > maxTime) {
maxTime = waitTime;
}
}
break;
}//end of switch block
}//end of for loop
if (maxTime != 0) {
checkTimer.initWithCallback(function(){setDispatch(batches, touches, command_id, batchIndex);}, maxTime, Ci.nsITimer.TYPE_ONE_SHOT);
}
else {
setDispatch(batches, touches, command_id, batchIndex);
}
}
/**
* Function to start multi-action
*/
function multiAction(msg) {
let command_id = msg.json.command_id;
let args = msg.json.value;
// maxlen is the longest action chain for one finger
let maxlen = msg.json.maxlen;
try {
// unwrap the original nested array
let commandArray = elementManager.convertWrappedArguments(args, curContainer);
let concurrentEvent = [];
let temp;
for (let i = 0; i < maxlen; i++) {
let row = [];
for (let j = 0; j < commandArray.length; j++) {
if (commandArray[j][i] != undefined) {
// add finger id to the front of each action, i.e. [finger_id, action, element]
temp = commandArray[j][i];
temp.unshift(j);
row.push(temp);
}
}
concurrentEvent.push(row);
}
// now concurrent event is made of sets where each set contain a list of actions that need to be fired.
// note: each action belongs to a different finger
// pendingTouches keeps track of current touches that's on the screen
let pendingTouches = [];
setDispatch(concurrentEvent, pendingTouches, command_id);
} catch (e) {
sendError(e, command_id);
}
}
/*
* This implements the latter part of a get request (for the case we need to resume one
* when a remoteness update happens in the middle of a navigate request). This is most of
* of the work of a navigate request, but doesn't assume DOMContentLoaded is yet to fire.
*/
function pollForReadyState(msg, start, callback) {
let {pageTimeout, url, command_id} = msg.json;
start = start ? start : new Date().getTime();
if (!callback) {
callback = () => {};
}
let end = null;
function checkLoad() {
navTimer.cancel();
end = new Date().getTime();
let aboutErrorRegex = /about:.+(error)\?/;
let elapse = end - start;
let doc = curContainer.frame.document;
if (pageTimeout == null || elapse <= pageTimeout) {
if (doc.readyState == "complete") {
callback();
sendOk(command_id);
} else if (doc.readyState == "interactive" &&
aboutErrorRegex.exec(doc.baseURI) &&
!doc.baseURI.startsWith(url)) {
// We have reached an error url without requesting it.
callback();
sendError(new UnknownError("Error loading page"), command_id);
} else if (doc.readyState == "interactive" &&
doc.baseURI.startsWith("about:")) {
callback();
sendOk(command_id);
} else {
navTimer.initWithCallback(checkLoad, 100, Ci.nsITimer.TYPE_ONE_SHOT);
}
} else {
callback();
sendError(new TimeoutError("Error loading page, timed out (checkLoad)"), command_id);
}
}
checkLoad();
}
/**
* Navigate to the given URL. The operation will be performed on the
* current browsing context, which means it handles the case where we
* navigate within an iframe. All other navigation is handled by the
* driver (in chrome space).
*/
function get(msg) {
let start = new Date().getTime();
// Prevent DOMContentLoaded events from frames from invoking this
// code, unless the event is coming from the frame associated with
// the current window (i.e. someone has used switch_to_frame).
onDOMContentLoaded = function onDOMContentLoaded(event) {
if (!event.originalTarget.defaultView.frameElement ||
event.originalTarget.defaultView.frameElement == curContainer.frame.frameElement) {
pollForReadyState(msg, start, () => {
removeEventListener("DOMContentLoaded", onDOMContentLoaded, false);
onDOMContentLoaded = null;
});
}
};
function timerFunc() {
removeEventListener("DOMContentLoaded", onDOMContentLoaded, false);
sendError(new TimeoutError("Error loading page, timed out (onDOMContentLoaded)"), msg.json.command_id);
}
if (msg.json.pageTimeout != null) {
navTimer.initWithCallback(timerFunc, msg.json.pageTimeout, Ci.nsITimer.TYPE_ONE_SHOT);
}
addEventListener("DOMContentLoaded", onDOMContentLoaded, false);
if (isB2G) {
curContainer.frame.location = msg.json.url;
} else {
// We need to move to the top frame before navigating
sendSyncMessage("Marionette:switchedToFrame", { frameValue: null });
curContainer.frame = content;
curContainer.frame.location = msg.json.url;
}
}
/**
* Cancel the polling and remove the event listener associated with a current
* navigation request in case we're interupted by an onbeforeunload handler
* and navigation doesn't complete.
*/
function cancelRequest() {
navTimer.cancel();
if (onDOMContentLoaded) {
removeEventListener("DOMContentLoaded", onDOMContentLoaded, false);
}
}
/**
* Get URL of the top-level browsing context.
*/
function getCurrentUrl(isB2G) {
if (isB2G) {
return curContainer.frame.location.href;
} else {
return content.location.href;
}
}
/**
* Get the title of the current browsing context.
*/
function getTitle() {
return curContainer.frame.top.document.title;
}
/**
* Get source of the current browsing context's DOM.
*/
function getPageSource() {
let XMLSerializer = curContainer.frame.XMLSerializer;
let source = new XMLSerializer().serializeToString(curContainer.frame.document);
return source;
}
/**
* Cause the browser to traverse one step backward in the joint history
* of the current top-level browsing context.
*/
function goBack() {
curContainer.frame.history.back();
}
/**
* Go forward in history
*/
function goForward(msg) {
curContainer.frame.history.forward();
sendOk(msg.json.command_id);
}
/**
* Refresh the page
*/
function refresh(msg) {
let command_id = msg.json.command_id;
curContainer.frame.location.reload(true);
let listen = function() {
removeEventListener("DOMContentLoaded", arguments.callee, false);
sendOk(command_id);
};
addEventListener("DOMContentLoaded", listen, false);
}
/**
* Find an element in the current browsing context's document using the
* given search strategy.
*/
function findElementContent(opts) {
return new Promise((resolve, reject) => {
elementManager.find(
curContainer,
opts,
opts.searchTimeout,
false /* all */,
resolve,
reject);
});
}
/**
* Find elements in the current browsing context's document using the
* given search strategy.
*/
function findElementsContent(opts) {
return new Promise((resolve, reject) => {
elementManager.find(
curContainer,
opts,
opts.searchTimeout,
true /* all */,
resolve,
reject);
});
}
/**
* Find and return the active element on the page.
*
* @return {WebElement}
* Reference to web element.
*/
function getActiveElement() {
let el = curContainer.frame.document.activeElement;
return elementManager.addToKnownElements(el);
}
/**
* Send click event to element.
*
* @param {WebElement} id
* Reference to the web element to click.
*/
function clickElement(id) {
let el = elementManager.getKnownElement(id, curContainer);
let visible = checkVisible(el);
if (!visible) {
throw new ElementNotVisibleError("Element is not visible");
}
return accessibility.getAccessibleObject(el, true).then(acc => {
checkVisibleAccessibility(acc, el, visible);
if (utils.isElementEnabled(el)) {
checkEnabledAccessibility(acc, el, true);
checkActionableAccessibility(acc, el);
utils.synthesizeMouseAtCenter(el, {}, el.ownerDocument.defaultView);
} else {
throw new InvalidElementStateError("Element is not Enabled");
}
});
}
/**
* Get a given attribute of an element.
*
* @param {WebElement} id
* Reference to the web element to get the attribute of.
* @param {string} name
* Name of the attribute.
*
* @return {string}
* The value of the attribute.
*/
function getElementAttribute(id, name) {
let el = elementManager.getKnownElement(id, curContainer);
return utils.getElementAttribute(el, name);
}
/**
* Get the text of this element. This includes text from child elements.
*
* @param {WebElement} id
* Reference to web element.
*
* @return {string}
* Text of element.
*/
function getElementText(id) {
let el = elementManager.getKnownElement(id, curContainer);
return utils.getElementText(el);
}
/**
* Get the tag name of an element.
*
* @param {WebElement} id
* Reference to web element.
*
* @return {string}
* Tag name of element.
*/
function getElementTagName(id) {
let el = elementManager.getKnownElement(id, curContainer);
return el.tagName.toLowerCase();
}
/**
* Determine the element displayedness of the given web element.
*
* Also performs additional accessibility checks if enabled by session
* capability.
*/
function isElementDisplayed(id) {
let el = elementManager.getKnownElement(id, curContainer);
let displayed = utils.isElementDisplayed(el);
return accessibility.getAccessibleObject(el).then(acc => {
checkVisibleAccessibility(acc, el, displayed);
return displayed;
});
}
/**
* Retrieves the computed value of the given CSS property of the given
* web element.
*
* @param {String} id
* Web element reference.
* @param {String} prop
* The CSS property to get.
*
* @return {String}
* Effective value of the requested CSS property.
*/
function getElementValueOfCssProperty(id, prop) {
let el = elementManager.getKnownElement(id, curContainer);
let st = curContainer.frame.document.defaultView.getComputedStyle(el, null);
return st.getPropertyValue(prop);
}
/**
* Get the position and dimensions of the element.
*
* @param {WebElement} id
* Reference to web element.
*
* @return {Object.<string, number>}
* The x, y, width, and height properties of the element.
*/
function getElementRect(id) {
let el = elementManager.getKnownElement(id, curContainer);
let clientRect = el.getBoundingClientRect();
return {
x: clientRect.x + curContainer.frame.pageXOffset,
y: clientRect.y + curContainer.frame.pageYOffset,
width: clientRect.width,
height: clientRect.height
};
}
/**
* Check if element is enabled.
*
* @param {WebElement} id
* Reference to web element.
*
* @return {boolean}
* True if enabled, false otherwise.
*/
function isElementEnabled(id) {
let el = elementManager.getKnownElement(id, curContainer);
let enabled = utils.isElementEnabled(el);
return accessibility.getAccessibleObject(el).then(acc => {
checkEnabledAccessibility(acc, el, enabled);
return enabled;
});
}
/**
* Determines if the referenced element is selected or not.
*
* This operation only makes sense on input elements of the Checkbox-
* and Radio Button states, or option elements.
*/
function isElementSelected(id) {
let el = elementManager.getKnownElement(id, curContainer);
let selected = utils.isElementSelected(el);
return accessibility.getAccessibleObject(el).then(acc => {
checkSelectedAccessibility(acc, el, selected);
return selected;
});
}
/**
* Send keys to element
*/
function sendKeysToElement(msg) {
let command_id = msg.json.command_id;
let val = msg.json.value;
let el;
return Promise.resolve(elementManager.getKnownElement(msg.json.id, curContainer))
.then(knownEl => {
el = knownEl;
// Element should be actionable from the accessibility standpoint to be able
// to send keys to it.
return accessibility.getAccessibleObject(el, true)
}).then(acc => {
checkActionableAccessibility(acc, el);
if (el.type == "file") {
let p = val.join("");
fileInputElement = el;
// In e10s, we can only construct File objects in the parent process,
// so pass the filename to driver.js, which in turn passes them back
// to this frame script in receiveFiles.
sendSyncMessage("Marionette:getFiles",
{value: p, command_id: command_id});
} else {
utils.sendKeysToElement(curContainer.frame, el, val, sendOk, sendError, command_id);
}
}).catch(e => sendError(e, command_id));
}
/**
* Clear the text of an element.
*/
function clearElement(id) {
try {
let el = elementManager.getKnownElement(id, curContainer);
if (el.type == "file") {
el.value = null;
} else {
utils.clearElement(el);
}
} catch (e) {
// Bug 964738: Newer atoms contain status codes which makes wrapping
// this in an error prototype that has a status property unnecessary
if (e.name == "InvalidElementStateError") {
throw new InvalidElementStateError(e.message);
} else {
throw e;
}
}
}
/**
* Switch the current context to the specified host's Shadow DOM.
* @param {WebElement} id
* Reference to web element.
*/
function switchToShadowRoot(id) {
if (!id) {
// If no host element is passed, attempt to find a parent shadow root or, if
// none found, unset the current shadow root
if (curContainer.shadowRoot) {
let parent = curContainer.shadowRoot.host;
while (parent && !(parent instanceof curContainer.frame.ShadowRoot)) {
parent = parent.parentNode;
}
curContainer.shadowRoot = parent;
}
return;
}
let foundShadowRoot;
let hostEl = elementManager.getKnownElement(id, curContainer);
foundShadowRoot = hostEl.shadowRoot;
if (!foundShadowRoot) {
throw new NoSuchElementError('Unable to locate shadow root: ' + id);
}
curContainer.shadowRoot = foundShadowRoot;
}
/**
* Switch to the parent frame of the current Frame. If the frame is the top most
* is the current frame then no action will happen.
*/
function switchToParentFrame(msg) {
let command_id = msg.json.command_id;
curContainer.frame = curContainer.frame.parent;
let parentElement = elementManager.addToKnownElements(curContainer.frame);
sendSyncMessage("Marionette:switchedToFrame", { frameValue: parentElement });
sendOk(msg.json.command_id);
}
/**
* Switch to frame given either the server-assigned element id,
* its index in window.frames, or the iframe's name or id.
*/
function switchToFrame(msg) {
let command_id = msg.json.command_id;
function checkLoad() {
let errorRegex = /about:.+(error)|(blocked)\?/;
if (curContainer.frame.document.readyState == "complete") {
sendOk(command_id);
return;
} else if (curContainer.frame.document.readyState == "interactive" &&
errorRegex.exec(curContainer.frame.document.baseURI)) {
sendError(new UnknownError("Error loading page"), command_id);
return;
}
checkTimer.initWithCallback(checkLoad, 100, Ci.nsITimer.TYPE_ONE_SHOT);
}
let foundFrame = null;
let frames = [];
let parWindow = null;
// Check of the curContainer.frame reference is dead
try {
frames = curContainer.frame.frames;
//Until Bug 761935 lands, we won't have multiple nested OOP iframes. We will only have one.
//parWindow will refer to the iframe above the nested OOP frame.
parWindow = curContainer.frame.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowUtils).outerWindowID;
} catch (e) {
// We probably have a dead compartment so accessing it is going to make Firefox
// very upset. Let's now try redirect everything to the top frame even if the
// user has given us a frame since search doesnt look up.
msg.json.id = null;
msg.json.element = null;
}
if ((msg.json.id === null || msg.json.id === undefined) && (msg.json.element == null)) {
// returning to root frame
sendSyncMessage("Marionette:switchedToFrame", { frameValue: null });
curContainer.frame = content;
if(msg.json.focus == true) {
curContainer.frame.focus();
}
checkTimer.initWithCallback(checkLoad, 100, Ci.nsITimer.TYPE_ONE_SHOT);
return;
}
if (msg.json.element != undefined) {
if (elementManager.seenItems[msg.json.element] != undefined) {
let wantedFrame;
try {
wantedFrame = elementManager.getKnownElement(msg.json.element, curContainer); //Frame Element
} catch (e) {
sendError(e, command_id);
}
if (frames.length > 0) {
for (let i = 0; i < frames.length; i++) {
// use XPCNativeWrapper to compare elements; see bug 834266
if (XPCNativeWrapper(frames[i].frameElement) == XPCNativeWrapper(wantedFrame)) {
curContainer.frame = frames[i].frameElement;
foundFrame = i;
}
}
}
if (foundFrame === null) {
// Either the frame has been removed or we have a OOP frame
// so lets just get all the iframes and do a quick loop before
// throwing in the towel
let iframes = curContainer.frame.document.getElementsByTagName("iframe");
for (var i = 0; i < iframes.length; i++) {
if (XPCNativeWrapper(iframes[i]) == XPCNativeWrapper(wantedFrame)) {
curContainer.frame = iframes[i];
foundFrame = i;
}
}
}
}
}
if (foundFrame === null) {
if (typeof(msg.json.id) === 'number') {
try {
foundFrame = frames[msg.json.id].frameElement;
if (foundFrame !== null) {
curContainer.frame = foundFrame;
foundFrame = elementManager.addToKnownElements(curContainer.frame);
}
else {
// If foundFrame is null at this point then we have the top level browsing
// context so should treat it accordingly.
sendSyncMessage("Marionette:switchedToFrame", { frameValue: null});
curContainer.frame = content;
if(msg.json.focus == true) {
curContainer.frame.focus();
}
checkTimer.initWithCallback(checkLoad, 100, Ci.nsITimer.TYPE_ONE_SHOT);
return;
}
} catch (e) {
// Since window.frames does not return OOP frames it will throw
// and we land up here. Let's not give up and check if there are
// iframes and switch to the indexed frame there
let iframes = curContainer.frame.document.getElementsByTagName("iframe");
if (msg.json.id >= 0 && msg.json.id < iframes.length) {
curContainer.frame = iframes[msg.json.id];
foundFrame = msg.json.id;
}
}
}
}
if (foundFrame === null) {
sendError(new NoSuchFrameError("Unable to locate frame: " + (msg.json.id || msg.json.element)), command_id);
return true;
}
// send a synchronous message to let the server update the currently active
// frame element (for getActiveFrame)
let frameValue = elementManager.wrapValue(curContainer.frame.wrappedJSObject)['ELEMENT'];
sendSyncMessage("Marionette:switchedToFrame", { frameValue: frameValue });
let rv = null;
if (curContainer.frame.contentWindow === null) {
// The frame we want to switch to is a remote/OOP frame;
// notify our parent to handle the switch
curContainer.frame = content;
rv = {win: parWindow, frame: foundFrame};
} else {
curContainer.frame = curContainer.frame.contentWindow;
if (msg.json.focus)
curContainer.frame.focus();
checkTimer.initWithCallback(checkLoad, 100, Ci.nsITimer.TYPE_ONE_SHOT);
}
sendResponse({value: rv}, command_id);
}
/**
* Add a cookie to the document
*/
function addCookie(msg) {
let cookie = msg.json.cookie;
if (!cookie.expiry) {
var date = new Date();
var thePresent = new Date(Date.now());
date.setYear(thePresent.getFullYear() + 20);
cookie.expiry = date.getTime() / 1000; // Stored in seconds.
}
if (!cookie.domain) {
var location = curContainer.frame.document.location;
cookie.domain = location.hostname;
} else {
var currLocation = curContainer.frame.location;
var currDomain = currLocation.host;
if (currDomain.indexOf(cookie.domain) == -1) {
sendError(new InvalidCookieDomainError("You may only set cookies for the current domain"), msg.json.command_id);
}
}
// The cookie's domain may include a port. Which is bad. Remove it
// We'll catch ip6 addresses by mistake. Since no-one uses those
// this will be okay for now. See Bug 814416
if (cookie.domain.match(/:\d+$/)) {
cookie.domain = cookie.domain.replace(/:\d+$/, '');
}
var document = curContainer.frame.document;
if (!document || !document.contentType.match(/html/i)) {
sendError(new UnableToSetCookieError("You may only set cookies on html documents"), msg.json.command_id);
}
let added = sendSyncMessage("Marionette:addCookie", {value: cookie});
if (added[0] !== true) {
sendError(new UnableToSetCookieError(), msg.json.command_id);
return;
}
sendOk(msg.json.command_id);
}
/**
* Get all cookies for the current domain.
*/
function getCookies() {
let rv = [];
let cookies = getVisibleCookies(curContainer.frame.location);
for (let cookie of cookies) {
let expires = cookie.expires;
// session cookie, don't return an expiry
if (expires == 0) {
expires = null;
// date before epoch time, cap to epoch
} else if (expires == 1) {
expires = 0;
}
rv.push({
'name': cookie.name,
'value': cookie.value,
'path': cookie.path,
'domain': cookie.host,
'secure': cookie.isSecure,
'httpOnly': cookie.httpOnly,
'expiry': expires
});
}
return rv;
}
/**
* Delete a cookie by name
*/
function deleteCookie(msg) {
let toDelete = msg.json.name;
let cookies = getVisibleCookies(curContainer.frame.location);
for (let cookie of cookies) {
if (cookie.name == toDelete) {
let deleted = sendSyncMessage("Marionette:deleteCookie", {value: cookie});
if (deleted[0] !== true) {
sendError(new UnknownError("Could not delete cookie: " + msg.json.name), msg.json.command_id);
return;
}
}
}
sendOk(msg.json.command_id);
}
/**
* Delete all the visibile cookies on a page
*/
function deleteAllCookies(msg) {
let cookies = getVisibleCookies(curContainer.frame.location);
for (let cookie of cookies) {
let deleted = sendSyncMessage("Marionette:deleteCookie", {value: cookie});
if (!deleted[0]) {
sendError(new UnknownError("Could not delete cookie: " + JSON.stringify(cookie)), msg.json.command_id);
return;
}
}
sendOk(msg.json.command_id);
}
/**
* Get all the visible cookies from a location
*/
function getVisibleCookies(location) {
let currentPath = location.pathname || '/';
let result = sendSyncMessage("Marionette:getVisibleCookies",
{value: [currentPath, location.hostname]});
return result[0];
}
function getAppCacheStatus(msg) {
sendResponse({ value: curContainer.frame.applicationCache.status },
msg.json.command_id);
}
// emulator callbacks
var _emu_cb_id = 0;
var _emu_cbs = {};
function runEmulatorCmd(cmd, callback) {
if (callback) {
_emu_cbs[_emu_cb_id] = callback;
}
sendAsyncMessage("Marionette:runEmulatorCmd", {emulator_cmd: cmd, id: _emu_cb_id});
_emu_cb_id += 1;
}
function runEmulatorShell(args, callback) {
if (callback) {
_emu_cbs[_emu_cb_id] = callback;
}
sendAsyncMessage("Marionette:runEmulatorShell", {emulator_shell: args, id: _emu_cb_id});
_emu_cb_id += 1;
}
function emulatorCmdResult(msg) {
let message = msg.json;
if (!sandboxes[sandboxName]) {
return;
}
let cb = _emu_cbs[message.id];
delete _emu_cbs[message.id];
if (!cb) {
return;
}
try {
cb(message.result);
} catch (e) {
sendError(e, -1);
return;
}
}
function importScript(msg) {
let command_id = msg.json.command_id;
let file;
if (importedScripts.exists()) {
file = FileUtils.openFileOutputStream(importedScripts,
FileUtils.MODE_APPEND | FileUtils.MODE_WRONLY);
}
else {
//Note: The permission bits here don't actually get set (bug 804563)
importedScripts.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE,
parseInt("0666", 8));
file = FileUtils.openFileOutputStream(importedScripts,
FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE);
importedScripts.permissions = parseInt("0666", 8); //actually set permissions
}
file.write(msg.json.script, msg.json.script.length);
file.close();
sendOk(command_id);
}
/**
* Perform a screen capture in content context.
*
* @param {UUID=} id
* Optional web element reference of an element to take a screenshot
* of.
* @param {boolean=} full
* True to take a screenshot of the entire document element. Is not
* considered if {@code id} is not defined. Defaults to true.
* @param {Array.<UUID>=} highlights
* Draw a border around the elements found by their web element
* references.
*
* @return {string}
* Base64 encoded string of an image/png type.
*/
function takeScreenshot(id, full=true, highlights=[]) {
let canvas;
let highlightEls = [];
for (let h of highlights) {
let el = elementManager.getKnownElement(h, curContainer);
highlightEls.push(el);
}
// viewport
if (!id && !full) {
canvas = capture.viewport(curContainer.frame.document, highlightEls);
// element or full document element
} else {
let node;
if (id) {
node = elementManager.getKnownElement(id, curContainer);
} else {
node = curContainer.frame.document.documentElement;
}
canvas = capture.element(node, highlightEls);
}
return capture.toBase64(canvas);
}
// Call register self when we get loaded
registerSelf();
|
var blockControl = (function(){
var blockArr=[],
lineSpacing = 20;
return {
createBlock : function( lines ) {
var txtArr = [],
lineArr = lines,
yLoc = this.randomY(),
i=0,l=lines.length;
for ( i;i<l;i++ ) {
var txt = new TextLine( lineArr[i], yLoc + (lineSpacing*(i+1)) );
txtArr.push( txt );
}
txtArr.reverse();
blockArr.push( txtArr );
console.log( txtArr );
},
getBlock : function() {
if( blockArr.length > 0 ) {
return blockArr[0];
} else {
return 'completed';
}
},
randomY : function() {
return Math.floor( (Math.random() * 500) + lineSpacing );
},
//user just cleared first line in block, remove block from array
lineEmpty : function() {
try {
console.log('lineEmpty call : blockArr length is : ' + blockArr.length);
var firstBlock = blockArr[0];
console.log('first block is ');
console.log(firstBlock);
if( firstBlock.length > 0 ) {
firstBlock.splice(firstBlock.length-1,1);
console.log('removed first element in blockArr');
console.log('new total lines are : ' + blockArr[0].length);
if( firstBlock.length == 0 ) {
blockArr.shift();
console.log('block completed... remaining blocks :');
console.log( blockArr );
//done with block
}
}
} catch(e) {
console.log('error : ' + e.message);
}
}
}
})();
|
const getIdentifier = require('../lib/replacer/getIdentifier'),
v8 = require('v8-natives')
const bits = [0],
symbols = [
'a',
'b',
'c'
],
symbolsLastIndex = symbols.length - 1
for (let i = 0; i <= 7; i++) {
getIdentifier(bits, symbols, symbolsLastIndex)
}
getIdentifier(bits, symbols, symbolsLastIndex)
v8.optimizeFunctionOnNextCall(getIdentifier)
getIdentifier(bits, symbols, symbolsLastIndex)
v8.helpers.printStatus(getIdentifier)
|
var ElementType = require("domelementtype");
var re_whitespace = /\s+/g;
var NodePrototype = require("./lib/node");
var ElementPrototype = require("./lib/element");
function DomHandler(callback, options, elementCB){
if(typeof callback === "object"){
elementCB = options;
options = callback;
callback = null;
} else if(typeof options === "function"){
elementCB = options;
options = defaultOpts;
}
this._callback = callback;
this._options = options || defaultOpts;
this._elementCB = elementCB;
this.dom = [];
this._done = false;
this._tagStack = [];
this._parser = this._parser || null;
}
//default options
var defaultOpts = {
normalizeWhitespace: false, //Replace all whitespace with single spaces
withStartIndices: false, //Add startIndex properties to nodes
};
DomHandler.prototype.onparserinit = function(parser){
this._parser = parser;
};
//Resets the handler back to starting state
DomHandler.prototype.onreset = function(){
DomHandler.call(this, this._callback, this._options, this._elementCB);
};
//Signals the handler that parsing is done
DomHandler.prototype.onend = function(){
if(this._done) return;
this._done = true;
this._parser = null;
this._handleCallback(null);
};
DomHandler.prototype._handleCallback =
DomHandler.prototype.onerror = function(error){
if(typeof this._callback === "function"){
this._callback(error, this.dom);
} else {
if(error) throw error;
}
};
DomHandler.prototype.onclosetag = function(){
//if(this._tagStack.pop().name !== name) this._handleCallback(Error("Tagname didn't match!"));
var elem = this._tagStack.pop();
if(this._elementCB) this._elementCB(elem);
};
DomHandler.prototype._addDomElement = function(element){
var parent = this._tagStack[this._tagStack.length - 1];
var siblings = parent ? parent.children : this.dom;
var previousSibling = siblings[siblings.length - 1];
element.next = null;
if(this._options.withStartIndices){
element.startIndex = this._parser.startIndex;
}
if (this._options.withDomLvl1) {
element.__proto__ = element.type === "tag" ? ElementPrototype : NodePrototype;
}
if(previousSibling){
element.prev = previousSibling;
previousSibling.next = element;
} else {
element.prev = null;
}
siblings.push(element);
element.parent = parent || null;
};
DomHandler.prototype.onopentag = function(name, attribs){
var element = {
type: name === "script" ? ElementType.Script : name === "style" ? ElementType.Style : ElementType.Tag,
name: name,
attribs: attribs,
children: []
};
this._addDomElement(element);
this._tagStack.push(element);
};
DomHandler.prototype.ontext = function(data){
//the ignoreWhitespace is officially dropped, but for now,
//it's an alias for normalizeWhitespace
var normalize = this._options.normalizeWhitespace || this._options.ignoreWhitespace;
var lastTag;
if(!this._tagStack.length && this.dom.length && (lastTag = this.dom[this.dom.length-1]).type === ElementType.Text){
if(normalize){
lastTag.data = (lastTag.data + data).replace(re_whitespace, " ");
} else {
lastTag.data += data;
}
} else {
if(
this._tagStack.length &&
(lastTag = this._tagStack[this._tagStack.length - 1]) &&
(lastTag = lastTag.children[lastTag.children.length - 1]) &&
lastTag.type === ElementType.Text
){
if(normalize){
lastTag.data = (lastTag.data + data).replace(re_whitespace, " ");
} else {
lastTag.data += data;
}
} else {
if(normalize){
data = data.replace(re_whitespace, " ");
}
this._addDomElement({
data: data,
type: ElementType.Text
});
}
}
};
DomHandler.prototype.oncomment = function(data){
var lastTag = this._tagStack[this._tagStack.length - 1];
if(lastTag && lastTag.type === ElementType.Comment){
lastTag.data += data;
return;
}
var element = {
data: data,
type: ElementType.Comment
};
this._addDomElement(element);
this._tagStack.push(element);
};
DomHandler.prototype.oncdatastart = function(){
var element = {
children: [{
data: "",
type: ElementType.Text
}],
type: ElementType.CDATA
};
this._addDomElement(element);
this._tagStack.push(element);
};
DomHandler.prototype.oncommentend = DomHandler.prototype.oncdataend = function(){
this._tagStack.pop();
};
DomHandler.prototype.onprocessinginstruction = function(name, data){
this._addDomElement({
name: name,
data: data,
type: ElementType.Directive
});
};
module.exports = DomHandler;
|
/*!
* Timemap.js Copyright 2008 Nick Rabinowitz.
* Licensed under the MIT License (see LICENSE.txt)
*/
/**
* @overview
*
* <p>Timemap.js is intended to sync a SIMILE Timeline with a web-based map.
* Thanks to Jorn Clausen (http://www.oe-files.de) for initial concept and code.
* Timemap.js is licensed under the MIT License (see <a href="../LICENSE.txt">LICENSE.txt</a>).</p>
* <p><strong>Depends on:</strong>
* <a href="http://jquery.com">jQuery</a>,
* <a href="https://github.com/nrabinowitz/mxn"> a customized version of Mapstraction 2.x<a>,
* a map provider of your choice, <a href="code.google.com/p/simile-widgets">SIMILE Timeline v1.2 - 2.3.1.</a>
* </p>
* <p><strong>Tested browsers:</strong> Firefox 3.x, Google Chrome, IE7, IE8</p>
* <p><strong>Tested map providers:</strong>
* <a href="http://code.google.com/apis/maps/documentation/javascript/v2/reference.html">Google v2</a>,
* <a href="http://code.google.com/apis/maps/documentation/javascript/reference.html">Google v3</a>,
* <a href="http://openlayers.org">OpenLayers</a>,
* <a href="http://msdn.microsoft.com/en-us/library/bb429565.aspx">Bing Maps</a>
* </p>
* <ul>
* <li><a href="http://code.google.com/p/timemap/">Project Homepage</a></li>
* <li><a href="http://groups.google.com/group/timemap-development">Discussion Group</a></li>
* <li><a href="../examples/index.html">Working Examples</a></li>
* </ul>
*
* @name timemap.js
* @author Nick Rabinowitz (www.nickrabinowitz.com)
* @version 2.0.1
*/
// for jslint
(function(){
// borrowing some space-saving devices from jquery
var
// Will speed up references to window, and allows munging its name.
window = this,
// Will speed up references to undefined, and allows munging its name.
undefined,
// aliases for Timeline objects
Timeline = window.Timeline, DateTime = Timeline.DateTime,
// alias libraries
$ = window.jQuery,
mxn = window.mxn,
// alias Mapstraction classes
Mapstraction = mxn.Mapstraction,
LatLonPoint = mxn.LatLonPoint,
BoundingBox = mxn.BoundingBox,
Marker = mxn.Marker,
Polyline = mxn.Polyline,
// events
E_ITEMS_LOADED = 'itemsloaded',
// Google icon path
GIP = "http://www.google.com/intl/en_us/mapfiles/ms/icons/",
// aliases for class names, allowing munging
TimeMap, TimeMapFilterChain, TimeMapDataset, TimeMapTheme, TimeMapItem;
/*----------------------------------------------------------------------------
* TimeMap Class
*---------------------------------------------------------------------------*/
/**
* @class
* The TimeMap object holds references to timeline, map, and datasets.
*
* @constructor
* This will create the visible map, but not the timeline, which must be initialized separately.
*
* @param {DOM Element} tElement The timeline element.
* @param {DOM Element} mElement The map element.
* @param {Object} [options] A container for optional arguments
* @param {TimeMapTheme|String} [options.theme=red] Color theme for the timemap
* @param {Boolean} [options.syncBands=true] Whether to synchronize all bands in timeline
* @param {LatLonPoint} [options.mapCenter=0,0] Point for map center
* @param {Number} [options.mapZoom=0] Initial map zoom level
* @param {String} [options.mapType=physical] The maptype for the map (see {@link TimeMap.mapTypes} for options)
* @param {Function|String} [options.mapFilter={@link TimeMap.filters.hidePastFuture}]
* How to hide/show map items depending on timeline state;
* options: keys in {@link TimeMap.filters} or function. Set to
* null or false for no filter.
* @param {Boolean} [options.showMapTypeCtrl=true] Whether to display the map type control
* @param {Boolean} [options.showMapCtrl=true] Whether to show map navigation control
* @param {Boolean} [options.centerOnItems=true] Whether to center and zoom the map based on loaded item
* @param {String} [options.eventIconPath] Path for directory holding event icons; if set at the TimeMap
* level, will override dataset and item defaults
* @param {Boolean} [options.checkResize=true] Whether to update the timemap display when the window is
* resized. Necessary for fluid layouts, but might be better set to
* false for absolutely-sized timemaps to avoid extra processing
* @param {Boolean} [options.multipleInfoWindows=false] Whether to allow multiple simultaneous info windows for
* map providers that allow this (Google v3, OpenLayers)
* @param {mixed} [options[...]] Any of the options for {@link TimeMapDataset},
* {@link TimeMapItem}, or {@link TimeMapTheme} may be set here,
* to cascade to the entire TimeMap, though they can be overridden
* at lower levels
* </pre>
*/
TimeMap = function(tElement, mElement, options) {
var tm = this,
// set defaults for options
defaults = {
mapCenter: new LatLonPoint(0,0),
mapZoom: 0,
mapType: 'physical',
showMapTypeCtrl: true,
showMapCtrl: true,
syncBands: true,
mapFilter: 'hidePastFuture',
centerOnItems: true,
theme: 'red',
dateParser: 'hybrid',
checkResize: true,
multipleInfoWindows:false
},
mapCenter;
// save DOM elements
/**
* Map element
* @name TimeMap#mElement
* @type DOM Element
*/
tm.mElement = mElement;
/**
* Timeline element
* @name TimeMap#tElement
* @type DOM Element
*/
tm.tElement = tElement;
/**
* Map of datasets
* @name TimeMap#datasets
* @type Object
*/
tm.datasets = {};
/**
* Filter chains for this timemap
* @name TimeMap#chains
* @type Object
*/
tm.chains = {};
/**
* Container for optional settings passed in the "options" parameter
* @name TimeMap#opts
* @type Object
*/
tm.opts = options = $.extend(defaults, options);
// allow map center to be specified as a point object
mapCenter = options.mapCenter;
if (mapCenter.constructor != LatLonPoint && mapCenter.lat) {
options.mapCenter = new LatLonPoint(mapCenter.lat, mapCenter.lon);
}
// allow map types to be specified by key
options.mapType = util.lookup(options.mapType, TimeMap.mapTypes);
// allow map filters to be specified by key
options.mapFilter = util.lookup(options.mapFilter, TimeMap.filters);
// allow theme options to be specified in options
options.theme = TimeMapTheme.create(options.theme, options);
// initialize map
tm.initMap();
};
// STATIC FIELDS
/**
* Current library version.
* @constant
* @type String
*/
TimeMap.version = "2.0.1";
/**
* @name TimeMap.util
* @namespace
* Namespace for TimeMap utility functions.
*/
var util = TimeMap.util = {};
// STATIC METHODS
/**
* Intializes a TimeMap.
*
* <p>The idea here is to throw all of the standard intialization settings into
* a large object and then pass it to the TimeMap.init() function. The full
* data format is outlined below, but if you leave elements out the script
* will use default settings instead.</p>
*
* <p>See the examples and the
* <a href="http://code.google.com/p/timemap/wiki/UsingTimeMapInit">UsingTimeMapInit wiki page</a>
* for usage.</p>
*
* @param {Object} config Full set of configuration options.
* @param {String} [config.mapId] DOM id of the element to contain the map.
* Either this or mapSelector is required.
* @param {String} [config.timelineId] DOM id of the element to contain the timeline.
* Either this or timelineSelector is required.
* @param {String} [config.mapSelector] jQuery selector for the element to contain the map.
* Either this or mapId is required.
* @param {String} [config.timelineSelector] jQuery selector for the element to contain the timeline.
* Either this or timelineId is required.
* @param {Object} [config.options] Options for the TimeMap object (see the {@link TimeMap} constructor)
* @param {Object[]} config.datasets Array of datasets to load
* @param {Object} config.datasets[x] Configuration options for a particular dataset
* @param {String|Class} config.datasets[x].type Loader type for this dataset (generally a sub-class
* of {@link TimeMap.loaders.base})
* @param {Object} config.datasets[x].options Options for the loader. See the {@link TimeMap.loaders.base}
* constructor and the constructors for the various loaders for
* more details.
* @param {String} [config.datasets[x].id] Optional id for the dataset in the {@link TimeMap#datasets}
* object, for future reference; otherwise "ds"+x is used
* @param {String} [config.datasets[x][...]] Other options for the {@link TimeMapDataset} object
* @param {String|Array} [config.bandIntervals=wk] Intervals for the two default timeline bands. Can either be an
* array of interval constants or a key in {@link TimeMap.intervals}
* @param {Object[]} [config.bandInfo] Array of configuration objects for Timeline bands, to be passed to
* Timeline.createBandInfo (see the <a href="http://code.google.com/p/simile-widgets/wiki/Timeline_GettingStarted">Timeline Getting Started tutorial</a>).
* This will override config.bandIntervals, if provided.
* @param {Timeline.Band[]} [config.bands] Array of instantiated Timeline Band objects. This will override
* config.bandIntervals and config.bandInfo, if provided.
* @param {Function} [config.dataLoadedFunction] Function to be run as soon as all datasets are loaded, but
* before they've been displayed on the map and timeline
* (this will override dataDisplayedFunction and scrollTo)
* @param {Function} [config.dataDisplayedFunction] Function to be run as soon as all datasets are loaded and
* displayed on the map and timeline
* @param {String|Date} [config.scrollTo=earliest] Date to scroll to once data is loaded - see
* {@link TimeMap.parseDate} for options
* @return {TimeMap} The initialized TimeMap object
*/
TimeMap.init = function(config) {
var err = "TimeMap.init: Either %Id or %Selector is required",
// set defaults
defaults = {
options: {},
datasets: [],
bands: false,
bandInfo: false,
bandIntervals: "wk",
scrollTo: "earliest"
},
state = TimeMap.state,
intervals, tm,
datasets = [], x, dsOptions, topOptions, dsId,
bands = [], eventSource;
// get DOM element selectors
config.mapSelector = config.mapSelector || '#' + config.mapId;
config.timelineSelector = config.timelineSelector || '#' + config.timelineId;
// get state from url hash if state functions are available
if (state) {
state.setConfigFromUrl(config);
}
// merge options and defaults
config = $.extend(defaults, config);
if (!config.bandInfo && !config.bands) {
// allow intervals to be specified by key
intervals = util.lookup(config.bandIntervals, TimeMap.intervals);
// make default band info
config.bandInfo = [
{
width: "80%",
intervalUnit: intervals[0],
intervalPixels: 70
},
{
width: "20%",
intervalUnit: intervals[1],
intervalPixels: 100,
showEventText: false,
overview: true,
trackHeight: 0.4,
trackGap: 0.2
}
];
}
// create the TimeMap object
tm = new TimeMap(
$(config.timelineSelector).get(0),
$(config.mapSelector).get(0),
config.options
);
// create the dataset objects
config.datasets.forEach(function(ds, x) {
// put top-level data into options
dsOptions = $.extend({
title: ds.title,
theme: ds.theme,
dateParser: ds.dateParser
}, ds.options);
dsId = ds.id || "ds" + x;
datasets[x] = tm.createDataset(dsId, dsOptions);
if (x > 0) {
// set all to the same eventSource
datasets[x].eventSource = datasets[0].eventSource;
}
});
// add a pointer to the eventSource in the TimeMap
tm.eventSource = datasets[0].eventSource;
// set up timeline bands
// ensure there's at least an empty eventSource
eventSource = (datasets[0] && datasets[0].eventSource) || new Timeline.DefaultEventSource();
// check for pre-initialized bands (manually created with Timeline.createBandInfo())
if (config.bands) {
config.bands.forEach(function(band) {
// substitute dataset event source
// assume that these have been set up like "normal" Timeline bands:
// with an empty event source if events are desired, and null otherwise
if (band.eventSource !== null) {
band.eventSource = eventSource;
}
});
bands = config.bands;
}
// otherwise, make bands from band info
else {
config.bandInfo.forEach(function(bandInfo, x) {
// if eventSource is explicitly set to null or false, ignore
if (!(('eventSource' in bandInfo) && !bandInfo.eventSource)) {
bandInfo.eventSource = eventSource;
}
else {
bandInfo.eventSource = null;
}
bands[x] = Timeline.createBandInfo(bandInfo);
if (x > 0 && util.TimelineVersion() == "1.2") {
// set all to the same layout
bands[x].eventPainter.setLayout(bands[0].eventPainter.getLayout());
}
});
}
// initialize timeline
tm.initTimeline(bands);
// initialize load manager
var loadManager = TimeMap.loadManager,
callback = function() {
loadManager.increment();
};
loadManager.init(tm, config.datasets.length, config);
// load data!
config.datasets.forEach(function(data, x) {
var dataset = datasets[x],
options = data.data || data.options || {},
type = data.type || options.type,
// get loader class
loaderClass = (typeof type == 'string') ? TimeMap.loaders[type] : type,
// load with appropriate loader
loader = new loaderClass(options);
loader.load(dataset, callback);
});
// return timemap object for later manipulation
return tm;
};
// METHODS
TimeMap.prototype = {
/**
*
* Initialize the map.
*/
initMap: function() {
var tm = this,
options = tm.opts,
map, i;
/**
* The Mapstraction object
* @name TimeMap#map
* @type Mapstraction
*/
tm.map = map = new Mapstraction(tm.mElement, options.mapProvider);
// display the map centered on a latitude and longitude
map.setCenterAndZoom(options.mapCenter, options.mapZoom);
// set default controls and map type
map.addControls({
pan: options.showMapCtrl,
zoom: options.showMapCtrl ? 'large' : false,
map_type: options.showMapTypeCtrl
});
map.setMapType(options.mapType);
// allow multiple windows if desired
if (options.multipleInfoWindows) {
map.setOption('enableMultipleBubbles', true);
}
/**
* Return the native map object (specific to the map provider)
* @name TimeMap#getNativeMap
* @function
* @return {Object} The native map object (e.g. GMap2)
*/
tm.getNativeMap = function() { return map.getMap(); };
},
/**
* Initialize the timeline - this must happen separately to allow full control of
* timeline properties.
*
* @param {BandInfo Array} bands Array of band information objects for timeline
*/
initTimeline: function(bands) {
var tm = this, timeline,
opts = tm.opts,
// filter: hide when item is hidden
itemVisible = function(item) {
return item.visible;
},
// filter: hide when dataset is hidden
datasetVisible = function(item) {
return item.dataset.visible;
},
// handler to open item window
eventClickHandler = function(x, y, evt) {
evt.item.openInfoWindow();
},
resizeTimerID, x, painter;
// synchronize & highlight timeline bands
for (x=1; x < bands.length; x++) {
if (opts.syncBands) {
bands[x].syncWith = 0;
}
bands[x].highlight = true;
}
/**
* The associated timeline object
* @name TimeMap#timeline
* @type Timeline
*/
tm.timeline = timeline = Timeline.create(tm.tElement, bands);
// hijack timeline popup window to open info window
for (x=0; x < timeline.getBandCount(); x++) {
painter = timeline.getBand(x).getEventPainter().constructor;
painter.prototype._showBubble = eventClickHandler;
}
// filter chain for map placemarks
tm.addFilterChain("map",
// on
function(item) {
item.showPlacemark();
},
// off
function(item) {
item.hidePlacemark();
},
// pre/post
null, null,
// initial chain
[itemVisible, datasetVisible]
);
// filter: hide map items depending on timeline state
if (opts.mapFilter) {
tm.addFilter("map", opts.mapFilter);
// update map on timeline scroll
timeline.getBand(0).addOnScrollListener(function() {
tm.filter("map");
});
}
// filter chain for timeline events
tm.addFilterChain("timeline",
// on
function(item) {
item.showEvent();
},
// off
function(item) {
item.hideEvent();
},
// pre
null,
// post
function() {
// XXX: needed if we go to Timeline filtering?
tm.eventSource._events._index();
timeline.layout();
},
// initial chain
[itemVisible, datasetVisible]
);
// filter: hide timeline items depending on map state
if (opts.timelineFilter) {
tm.addFilter("map", opts.timelineFilter);
}
// add callback for window resize, if necessary
if (opts.checkResize) {
window.onresize = function() {
if (!resizeTimerID) {
resizeTimerID = window.setTimeout(function() {
resizeTimerID = null;
timeline.layout();
}, 500);
}
};
}
},
/**
* Parse a date in the context of the timeline. Uses the standard parser
* ({@link TimeMap.dateParsers.hybrid}) but accepts "now", "earliest",
* "latest", "first", and "last" (referring to loaded events)
*
* @param {String|Date} s String (or date) to parse
* @return {Date} Parsed date
*/
parseDate: function(s) {
var d = new Date(),
eventSource = this.eventSource,
parser = TimeMap.dateParsers.hybrid,
// make sure there are events to scroll to
hasEvents = eventSource.getCount() > 0 ? true : false;
switch (s) {
case "now":
break;
case "earliest":
case "first":
if (hasEvents) {
d = eventSource.getEarliestDate();
}
break;
case "latest":
case "last":
if (hasEvents) {
d = eventSource.getLatestDate();
}
break;
default:
// assume it's a date, try to parse
d = parser(s);
}
return d;
},
/**
* Scroll the timeline to a given date. If lazyLayout is specified, this function
* will also call timeline.layout(), but only if it won't be called by the
* onScroll listener. This involves a certain amount of reverse engineering,
* and may not be future-proof.
*
* @param {String|Date} d Date to scroll to (either a date object, a
* date string, or one of the strings accepted
* by TimeMap#parseDate)
* @param {Boolean} [lazyLayout] Whether to call timeline.layout() if not
* required by the scroll.
* @param {Boolean} [animated] Whether to do an animated scroll, rather than a jump.
*/
scrollToDate: function(d, lazyLayout, animated) {
var timeline = this.timeline,
topband = timeline.getBand(0),
x, time, layouts = [],
band, minTime, maxTime;
d = this.parseDate(d);
if (d) {
time = d.getTime();
// check which bands will need layout after scroll
for (x=0; x < timeline.getBandCount(); x++) {
band = timeline.getBand(x);
minTime = band.getMinDate().getTime();
maxTime = band.getMaxDate().getTime();
layouts[x] = (lazyLayout && time > minTime && time < maxTime);
}
// do scroll
if (animated) {
// create animation
var provider = util.TimelineVersion() == '1.2' ? Timeline : SimileAjax,
a = provider.Graphics.createAnimation(function(abs, diff) {
topband.setCenterVisibleDate(new Date(abs));
}, topband.getCenterVisibleDate().getTime(), time, 1000);
a.run();
}
else {
topband.setCenterVisibleDate(d);
}
// layout as necessary
for (x=0; x < layouts.length; x++) {
if (layouts[x]) {
timeline.getBand(x).layout();
}
}
}
// layout if requested even if no date is found
else if (lazyLayout) {
timeline.layout();
}
},
/**
* Create an empty dataset object and add it to the timemap
*
* @param {String} id The id of the dataset
* @param {Object} options A container for optional arguments for dataset constructor -
* see the options passed to {@link TimeMapDataset}
* @return {TimeMapDataset} The new dataset object
*/
createDataset: function(id, options) {
var tm = this,
dataset = new TimeMapDataset(tm, options);
// save id reference
dataset.id = id;
tm.datasets[id] = dataset;
// add event listener
if (tm.opts.centerOnItems) {
var map = tm.map;
$(dataset).bind(E_ITEMS_LOADED, function() {
// determine the center and zoom level from the bounds
map.autoCenterAndZoom();
});
}
return dataset;
},
/**
* Run a function on each dataset in the timemap. This is the preferred
* iteration method, as it allows for future iterator options.
*
* @param {Function} f The function to run, taking one dataset as an argument
*/
each: function(f) {
var tm = this,
id;
for (id in tm.datasets) {
if (tm.datasets.hasOwnProperty(id)) {
f(tm.datasets[id]);
}
}
},
/**
* Run a function on each item in each dataset in the timemap.
* @param {Function} f The function to run, taking one item as an argument
*/
eachItem: function(f) {
this.each(function(ds) {
ds.each(function(item) {
f(item);
});
});
},
/**
* Get all items from all datasets.
* @return {TimeMapItem[]} Array of all items
*/
getItems: function() {
var items = [];
this.each(function(ds) {
items = items.concat(ds.items);
});
return items;
},
/**
* Save the currently selected item
* @param {TimeMapItem|String} item Item to select, or undefined
* to clear selection
*/
setSelected: function(item) {
this.opts.selected = item;
},
/**
* Get the currently selected item
* @return {TimeMapItem} Selected item
*/
getSelected: function() {
return this.opts.selected;
},
// Helper functions for dealing with filters
/**
* Update items, hiding or showing according to filters
* @param {String} chainId Filter chain to update on
*/
filter: function(chainId) {
var fc = this.chains[chainId];
if (fc) {
fc.run();
}
},
/**
* Add a new filter chain
*
* @param {String} chainId Id of the filter chain
* @param {Function} fon Function to run on an item if filter is true
* @param {Function} foff Function to run on an item if filter is false
* @param {Function} [pre] Function to run before the filter runs
* @param {Function} [post] Function to run after the filter runs
* @param {Function[]} [chain] Optional initial filter chain
*/
addFilterChain: function(chainId, fon, foff, pre, post, chain) {
this.chains[chainId] = new TimeMapFilterChain(this, fon, foff, pre, post, chain);
},
/**
* Remove a filter chain
*
* @param {String} chainId Id of the filter chain
*/
removeFilterChain: function(chainId) {
delete this.chains[chainId];
},
/**
* Add a function to a filter chain
*
* @param {String} chainId Id of the filter chain
* @param {Function} f Function to add
*/
addFilter: function(chainId, f) {
var fc = this.chains[chainId];
if (fc) {
fc.add(f);
}
},
/**
* Remove a function from a filter chain
*
* @param {String} chainId Id of the filter chain
* @param {Function} [f] The function to remove
*/
removeFilter: function(chainId, f) {
var fc = this.chains[chainId];
if (fc) {
fc.remove(f);
}
}
};
/*----------------------------------------------------------------------------
* Load manager
*---------------------------------------------------------------------------*/
/**
* @class Static singleton for managing multiple asynchronous loads
*/
TimeMap.loadManager = new function() {
var mgr = this;
/**
* Initialize (or reset) the load manager
* @name TimeMap.loadManager#init
* @function
*
* @param {TimeMap} tm TimeMap instance
* @param {Number} target Number of datasets we're loading
* @param {Object} [options] Container for optional settings
* @param {Function} [options.dataLoadedFunction]
* Custom function replacing default completion function;
* should take one parameter, the TimeMap object
* @param {String|Date} [options.scrollTo]
* Where to scroll the timeline when load is complete
* Options: "earliest", "latest", "now", date string, Date
* @param {Function} [options.dataDisplayedFunction]
* Custom function to fire once data is loaded and displayed;
* should take one parameter, the TimeMap object
*/
mgr.init = function(tm, target, config) {
mgr.count = 0;
mgr.tm = tm;
mgr.target = target;
mgr.opts = config || {};
};
/**
* Increment the count of loaded datasets
* @name TimeMap.loadManager#increment
* @function
*/
mgr.increment = function() {
mgr.count++;
if (mgr.count >= mgr.target) {
mgr.complete();
}
};
/**
* Function to fire when all loads are complete.
* Default behavior is to scroll to a given date (if provided) and
* layout the timeline.
* @name TimeMap.loadManager#complete
* @function
*/
mgr.complete = function() {
var tm = mgr.tm,
opts = mgr.opts,
// custom function including timeline scrolling and layout
func = opts.dataLoadedFunction;
if (func) {
func(tm);
}
else {
tm.scrollToDate(opts.scrollTo, true);
// check for state support
if (tm.initState) {
tm.initState();
}
// custom function to be called when data is loaded
func = opts.dataDisplayedFunction;
if (func) {
func(tm);
}
}
};
}();
/*----------------------------------------------------------------------------
* Loader namespace and base classes
*---------------------------------------------------------------------------*/
/**
* @namespace
* Namespace for different data loader functions.
* New loaders can add their factories or constructors to this object; loader
* functions are passed an object with parameters in TimeMap.init().
*
* @example
TimeMap.init({
datasets: [
{
// name of class in TimeMap.loaders
type: "json_string",
options: {
url: "mydata.json"
},
// etc...
}
],
// etc...
});
*/
TimeMap.loaders = {
/**
* @namespace
* Namespace for storing callback functions
* @private
*/
cb: {},
/**
* Cancel a specific load request. In practice, this is really only
* applicable to remote asynchronous loads. Note that this doesn't cancel
* the download of data, just the callback that loads it.
* @param {String} callbackName Name of the callback function to cancel
*/
cancel: function(callbackName) {
var namespace = TimeMap.loaders.cb;
// replace with self-cancellation function
namespace[callbackName] = function() {
delete namespace[callbackName];
};
},
/**
* Cancel all current load requests.
*/
cancelAll: function() {
var loaderNS = TimeMap.loaders,
namespace = loaderNS.cb,
callbackName;
for (callbackName in namespace) {
if (namespace.hasOwnProperty(callbackName)) {
loaderNS.cancel(callbackName);
}
}
},
/**
* Static counter for naming callback functions
* @private
* @type int
*/
counter: 0,
/**
* @class
* Abstract loader class. All loaders should inherit from this class.
*
* @constructor
* @param {Object} options All options for the loader
* @param {Function} [options.parserFunction=Do nothing]
* Parser function to turn a string into a JavaScript array
* @param {Function} [options.preloadFunction=Do nothing]
* Function to call on data before loading
* @param {Function} [options.transformFunction=Do nothing]
* Function to call on individual items before loading
* @param {String|Date} [options.scrollTo=earliest] Date to scroll the timeline to in the default callback
* (see {@link TimeMap#parseDate} for accepted syntax)
*/
base: function(options) {
var dummy = function(data) { return data; },
loader = this;
/**
* Parser function to turn a string into a JavaScript array
* @name TimeMap.loaders.base#parse
* @function
* @parameter {String} s String to parse
* @return {Object[]} Array of item data
*/
loader.parse = options.parserFunction || dummy;
/**
* Function to call on data object before loading
* @name TimeMap.loaders.base#preload
* @function
* @parameter {Object} data Data to preload
* @return {Object[]} Array of item data
*/
loader.preload = options.preloadFunction || dummy;
/**
* Function to call on a single item data object before loading
* @name TimeMap.loaders.base#transform
* @function
* @parameter {Object} data Data to transform
* @return {Object} Transformed data for one item
*/
loader.transform = options.transformFunction || dummy;
/**
* Date to scroll the timeline to on load
* @name TimeMap.loaders.base#scrollTo
* @default "earliest"
* @type String|Date
*/
loader.scrollTo = options.scrollTo || "earliest";
/**
* Get the name of a callback function that can be cancelled. This callback applies the parser,
* preload, and transform functions, loads the data, then calls the user callback
* @name TimeMap.loaders.base#getCallbackName
* @function
*
* @param {TimeMapDataset} dataset Dataset to load data into
* @param {Function} callback User-supplied callback function. If no function
* is supplied, the default callback will be used
* @return {String} The name of the callback function in TimeMap.loaders.cb
*/
loader.getCallbackName = function(dataset, callback) {
var callbacks = TimeMap.loaders.cb,
// Define a unique function name
callbackName = "_" + TimeMap.loaders.counter++;
// Define default callback
callback = callback || function() {
dataset.timemap.scrollToDate(loader.scrollTo, true);
};
// create callback
callbacks[callbackName] = function(result) {
// parse
var items = loader.parse(result);
// preload
items = loader.preload(items);
// load
dataset.loadItems(items, loader.transform);
// callback
callback();
// delete the callback function
delete callbacks[callbackName];
};
return callbackName;
};
/**
* Get a callback function that can be cancelled. This is a convenience function
* to be used if the callback name itself is not needed.
* @name TimeMap.loaders.base#getCallback
* @function
* @see TimeMap.loaders.base#getCallbackName
*
* @param {TimeMapDataset} dataset Dataset to load data into
* @param {Function} callback User-supplied callback function
* @return {Function} The configured callback function
*/
loader.getCallback = function(dataset, callback) {
// get loader callback name
var callbackName = loader.getCallbackName(dataset, callback);
// return the function
return TimeMap.loaders.cb[callbackName];
};
/**
* Cancel the callback function for this loader.
* @name TimeMap.loaders.base#cancel
* @function
*/
loader.cancel = function() {
TimeMap.loaders.cancel(loader.callbackName);
};
},
/**
* @class
* Basic loader class, for pre-loaded data.
* Other types of loaders should take the same parameter.
*
* @augments TimeMap.loaders.base
* @example
TimeMap.init({
datasets: [
{
type: "basic",
options: {
data: [
// object literals for each item
{
title: "My Item",
start: "2009-10-06",
point: {
lat: 37.824,
lon: -122.256
}
},
// etc...
]
}
}
],
// etc...
});
* @see <a href="../../examples/basic.html">Basic Example</a>
*
* @constructor
* @param {Object} options All options for the loader
* @param {Array} options.data Array of items to load
* @param {mixed} [options[...]] Other options (see {@link TimeMap.loaders.base})
*/
basic: function(options) {
var loader = new TimeMap.loaders.base(options);
/**
* Array of item data to load.
* @name TimeMap.loaders.basic#data
* @default []
* @type Object[]
*/
loader.data = options.items ||
// allow "value" for backwards compatibility
options.value || [];
/**
* Load javascript literal data.
* New loaders should implement a load function with the same signature.
* @name TimeMap.loaders.basic#load
* @function
*
* @param {TimeMapDataset} dataset Dataset to load data into
* @param {Function} callback Function to call once data is loaded
*/
loader.load = function(dataset, callback) {
// get callback function and call immediately on data
(this.getCallback(dataset, callback))(this.data);
};
return loader;
},
/**
* @class
* Generic class for loading remote data with a custom parser function
*
* @augments TimeMap.loaders.base
*
* @constructor
* @param {Object} options All options for the loader
* @param {String} options.url URL of file to load (NB: must be local address)
* @param {mixed} [options[...]] Other options. In addition to options for
* {@link TimeMap.loaders.base}), any option for
* <a href="http://api.jquery.com/jQuery.ajax/">jQuery.ajax</a>
* may be set here
*/
remote: function(options) {
var loader = new TimeMap.loaders.base(options);
/**
* Object to hold optional settings. Any setting for
* <a href="http://api.jquery.com/jQuery.ajax/">jQuery.ajax</a> should be set on this
* object before load() is called.
* @name TimeMap.loaders.remote#opts
* @type String
*/
loader.opts = $.extend({}, options, {
type: 'GET',
dataType: 'text'
});
/**
* Load function for remote files.
* @name TimeMap.loaders.remote#load
* @function
*
* @param {TimeMapDataset} dataset Dataset to load data into
* @param {Function} callback Function to call once data is loaded
*/
loader.load = function(dataset, callback) {
// get loader callback name (allows cancellation)
loader.callbackName = loader.getCallbackName(dataset, callback);
// set the callback function
loader.opts.success = TimeMap.loaders.cb[loader.callbackName];
// download remote data
$.ajax(loader.opts);
};
return loader;
}
};
/*----------------------------------------------------------------------------
* TimeMapFilterChain Class
*---------------------------------------------------------------------------*/
/**
* @class
* TimeMapFilterChain holds a set of filters to apply to the map or timeline.
*
* @constructor
* @param {TimeMap} timemap Reference to the timemap object
* @param {Function} fon Function to run on an item if filter is true
* @param {Function} foff Function to run on an item if filter is false
* @param {Function} [pre] Function to run before the filter runs
* @param {Function} [post] Function to run after the filter runs
* @param {Function[]} [chain] Optional initial filter chain
*/
TimeMapFilterChain = function(timemap, fon, foff, pre, post, chain) {
var fc = this,
dummy = $.noop;
/**
* Reference to parent TimeMap
* @name TimeMapFilterChain#timemap
* @type TimeMap
*/
fc.timemap = timemap;
/**
* Chain of filter functions, each taking an item and returning a boolean
* @name TimeMapFilterChain#chain
* @type Function[]
*/
fc.chain = chain || [];
/**
* Function to run on an item if filter is true
* @name TimeMapFilterChain#on
* @function
*/
fc.on = fon || dummy;
/**
* Function to run on an item if filter is false
* @name TimeMapFilterChain#off
* @function
*/
fc.off = foff || dummy;
/**
* Function to run before the filter runs
* @name TimeMapFilterChain#pre
* @function
*/
fc.pre = pre || dummy;
/**
* Function to run after the filter runs
* @name TimeMapFilterChain#post
* @function
*/
fc.post = post || dummy;
};
// METHODS
TimeMapFilterChain.prototype = {
/**
* Add a filter to the filter chain.
* @param {Function} f Function to add
*/
add: function(f) {
return this.chain.push(f);
},
/**
* Remove a filter from the filter chain
* @param {Function} [f] Function to remove; if not supplied, the last filter
* added is removed
*/
remove: function(f) {
var chain = this.chain,
i = f ? chain.indexOf(f) : chain.length - 1;
// remove specific filter or last if none specified
return chain.splice(i, 1);
},
/**
* Run filters on all items
*/
run: function() {
var fc = this,
chain = fc.chain;
// early exit
if (!chain.length) {
return;
}
// pre-filter function
fc.pre();
// run items through filter
fc.timemap.eachItem(function(item) {
var done,
i = chain.length;
L: while (!done) {
while (i--) {
if (!chain[i](item)) {
// false condition
fc.off(item);
break L;
}
}
// true condition
fc.on(item);
done = true;
}
});
// post-filter function
fc.post();
}
};
/**
* @namespace
* Namespace for different filter functions. Adding new filters to this
* namespace allows them to be specified by string name.
* @example
TimeMap.init({
options: {
mapFilter: "hideFuture"
},
// etc...
});
*/
TimeMap.filters = {
/**
* Static filter function: Hide items not in the visible area of the timeline.
*
* @param {TimeMapItem} item Item to test for filter
* @return {Boolean} Whether to show the item
*/
hidePastFuture: function(item) {
return item.onVisibleTimeline();
},
/**
* Static filter function: Hide items later than the visible area of the timeline.
*
* @param {TimeMapItem} item Item to test for filter
* @return {Boolean} Whether to show the item
*/
hideFuture: function(item) {
var maxVisibleDate = item.timeline.getBand(0).getMaxVisibleDate().getTime(),
itemStart = item.getStartTime();
if (itemStart !== undefined) {
// hide items in the future
return itemStart < maxVisibleDate;
}
return true;
},
/**
* Static filter function: Hide items not present at the exact
* center date of the timeline (will only work for duration events).
*
* @param {TimeMapItem} item Item to test for filter
* @return {Boolean} Whether to show the item
*/
showMomentOnly: function(item) {
var topband = item.timeline.getBand(0),
momentDate = topband.getCenterVisibleDate().getTime(),
itemStart = item.getStartTime(),
itemEnd = item.getEndTime();
if (itemStart !== undefined) {
// hide items in the future
return itemStart < momentDate &&
// hide items in the past
(itemEnd > momentDate || itemStart > momentDate);
}
return true;
}
};
/*----------------------------------------------------------------------------
* TimeMapDataset Class
*---------------------------------------------------------------------------*/
/**
* @class
* The TimeMapDataset object holds an array of items and dataset-level
* options and settings, including visual themes.
*
* @constructor
* @param {TimeMap} timemap Reference to the timemap object
* @param {Object} [options] Object holding optional arguments
* @param {String} [options.id] Key for this dataset in the datasets map
* @param {String} [options.title] Title of the dataset (for the legend)
* @param {String|TimeMapTheme} [options.theme] Theme settings.
* @param {String|Function} [options.dateParser] Function to replace default date parser.
* @param {Boolean} [options.noEventLoad=false] Whether to skip loading events on the timeline
* @param {Boolean} [options.noPlacemarkLoad=false] Whether to skip loading placemarks on the map
* @param {String} [options.infoTemplate] HTML for the info window content, with variable expressions
* (as "{{varname}}" by default) to be replaced by option data
* @param {String} [options.templatePattern] Regex pattern defining variable syntax in the infoTemplate
* @param {mixed} [options[...]] Any of the options for {@link TimeMapItem} or
* {@link TimeMapTheme} may be set here, to cascade to
* the dataset's objects, though they can be
* overridden at the TimeMapItem level
*/
TimeMapDataset = function(timemap, options) {
var ds = this;
/**
* Reference to parent TimeMap
* @name TimeMapDataset#timemap
* @type TimeMap
*/
ds.timemap = timemap;
/**
* EventSource for timeline events
* @name TimeMapDataset#eventSource
* @type Timeline.EventSource
*/
ds.eventSource = new Timeline.DefaultEventSource();
/**
* Array of child TimeMapItems
* @name TimeMapDataset#items
* @type Array
*/
ds.items = [];
/**
* Whether the dataset is visible
* @name TimeMapDataset#visible
* @type Boolean
*/
ds.visible = true;
/**
* Container for optional settings passed in the "options" parameter
* @name TimeMapDataset#opts
* @type Object
*/
ds.opts = options = $.extend({}, timemap.opts, options);
// allow date parser to be specified by key
options.dateParser = util.lookup(options.dateParser, TimeMap.dateParsers);
// allow theme options to be specified in options
options.theme = TimeMapTheme.create(options.theme, options);
};
TimeMapDataset.prototype = {
/**
* Return an array of this dataset's items
* @param {Number} [index] Index of single item to return
* @return {TimeMapItem[]} Single item, or array of all items if no index was supplied
*/
getItems: function(index) {
var items = this.items;
return index === undefined ? items :
index in items ? items[index] : null;
},
/**
* Return the title of the dataset
* @return {String} Dataset title
*/
getTitle: function() {
return this.opts.title;
},
/**
* Run a function on each item in the dataset. This is the preferred
* iteration method, as it allows for future iterator options.
*
* @param {Function} f The function to run
*/
each: function(f) {
this.items.forEach(f);
},
/**
* Add an array of items to the map and timeline.
*
* @param {Object[]} data Array of data to be loaded
* @param {Function} [transform] Function to transform data before loading
* @see TimeMapDataset#loadItem
*/
loadItems: function(data, transform) {
if (data) {
var ds = this;
data.forEach(function(item) {
ds.loadItem(item, transform);
});
$(ds).trigger(E_ITEMS_LOADED);
}
},
clearItems: function() {
var ds = this;
ds.items = new Array();
$(ds).trigger(E_ITEMS_LOADED);
},
/**
* Add one item to map and timeline.
* Each item has both a timeline event and a map placemark.
*
* @param {Object} data Data to be loaded - see the {@link TimeMapItem} constructor for details
* @param {Function} [transform] If data is not in the above format, transformation function to make it so
* @return {TimeMapItem} The created item (for convenience, as it's already been added)
* @see TimeMapItem
*/
loadItem: function(data, transform) {
// apply transformation, if any
if (transform) {
data = transform(data);
}
// transform functions can return a false value to skip a datum in the set
if (data) {
// create new item, cascading options
var ds = this, item;
data.options = $.extend({}, ds.opts, {title:null}, data.options);
item = new TimeMapItem(data, ds);
// add the item to the dataset
ds.items.push(item);
// return the item object
return item;
}
}
};
/*----------------------------------------------------------------------------
* TimeMapTheme Class
*---------------------------------------------------------------------------*/
/**
* @class
* Predefined visual themes for datasets, defining colors and images for
* map markers and timeline events. Note that theme is only used at creation
* time - updating the theme of an existing object won't do anything.
*
* @constructor
* @param {Object} [options] A container for optional arguments
* @param {String} [options.icon=http://www.google.com/intl/en_us/mapfiles/ms/icons/red-dot.png]
* Icon image for marker placemarks
* @param {Number[]} [options.iconSize=[32,32]] Array of two integers indicating marker icon size as
* [width, height] in pixels
* @param {String} [options.iconShadow=http://www.google.com/intl/en_us/mapfiles/ms/icons/msmarker.shadow.png]
* Icon image for marker placemarks
* @param {Number[]} [options.iconShadowSize=[59,32]] Array of two integers indicating marker icon shadow
* size as [width, height] in pixels
* @param {Number[]} [options.iconAnchor=[16,33]] Array of two integers indicating marker icon anchor
* point as [xoffset, yoffset] in pixels
* @param {String} [options.color=#FE766A] Default color in hex for events, polylines, polygons.
* @param {String} [options.lineColor=color] Color for polylines/polygons.
* @param {Number} [options.lineOpacity=1] Opacity for polylines/polygons.
* @param {Number} [options.lineWeight=2] Line weight in pixels for polylines/polygons.
* @param {String} [options.fillColor=color] Color for polygon fill.
* @param {String} [options.fillOpacity=0.25] Opacity for polygon fill.
* @param {String} [options.eventColor=color] Background color for duration events.
* @param {String} [options.eventTextColor=null] Text color for events (null=Timeline default).
* @param {String} [options.eventIconPath=timemap/images/] Path to instant event icon directory.
* @param {String} [options.eventIconImage=red-circle.gif] Filename of instant event icon image.
* @param {URL} [options.eventIcon=eventIconPath+eventIconImage] URL for instant event icons.
* @param {Boolean} [options.classicTape=false] Whether to use the "classic" style timeline event tape
* (needs additional css to work - see examples/artists.html).
*/
TimeMapTheme = function(options) {
// work out various defaults - the default theme is Google's reddish color
var defaults = {
/** Default color in hex
* @name TimeMapTheme#color
* @type String */
color: "#FE766A",
/** Opacity for polylines/polygons
* @name TimeMapTheme#lineOpacity
* @type Number */
lineOpacity: 1,
/** Line weight in pixels for polylines/polygons
* @name TimeMapTheme#lineWeight
* @type Number */
lineWeight: 2,
/** Opacity for polygon fill
* @name TimeMapTheme#fillOpacity
* @type Number */
fillOpacity: 0.4,
/** Text color for duration events
* @name TimeMapTheme#eventTextColor
* @type String */
eventTextColor: null,
/** Path to instant event icon directory
* @name TimeMapTheme#eventIconPath
* @type String */
eventIconPath: "timemap/images/",
/** Filename of instant event icon image
* @name TimeMapTheme#eventIconImage
* @type String */
eventIconImage: "red-circle.png",
/** Whether to use the "classic" style timeline event tape
* @name TimeMapTheme#classicTape
* @type Boolean */
classicTape: false,
/** Icon image for marker placemarks
* @name TimeMapTheme#icon
* @type String */
icon: GIP + "red-dot.png",
/** Icon size for marker placemarks
* @name TimeMapTheme#iconSize
* @type Number[] */
iconSize: [32, 32],
/** Icon shadow image for marker placemarks
* @name TimeMapTheme#iconShadow
* @type String */
iconShadow: GIP + "msmarker.shadow.png",
/** Icon shadow size for marker placemarks
* @name TimeMapTheme#iconShadowSize
* @type Number[] */
iconShadowSize: [59, 32],
/** Icon anchor for marker placemarks
* @name TimeMapTheme#iconAnchor
* @type Number[] */
iconAnchor: [16, 33]
};
// merge defaults with options
var settings = $.extend(defaults, options);
// cascade some settings as defaults
defaults = {
/** Line color for polylines/polygons
* @name TimeMapTheme#lineColor
* @type String */
lineColor: settings.color,
/** Fill color for polygons
* @name TimeMapTheme#fillColor
* @type String */
fillColor: settings.color,
/** Background color for duration events
* @name TimeMapTheme#eventColor
* @type String */
eventColor: settings.color,
/** Full URL for instant event icons
* @name TimeMapTheme#eventIcon
* @type String */
eventIcon: settings.eventIcon || settings.eventIconPath + settings.eventIconImage
};
// return configured options as theme
return $.extend(defaults, settings);
};
/**
* Create a theme, based on an optional new or pre-set theme
*
* @param {TimeMapTheme|String} [theme] Existing theme to clone, or string key in {@link TimeMap.themes}
* @param {Object} [options] Optional settings to overwrite - see {@link TimeMapTheme}
* @return {TimeMapTheme} Configured theme
*/
TimeMapTheme.create = function(theme, options) {
// test for string matches and missing themes
theme = util.lookup(theme, TimeMap.themes);
if (!theme) {
return new TimeMapTheme(options);
}
if (options) {
// see if we need to clone - guessing fewer keys in options
var clone = false, key;
for (key in options) {
if (theme.hasOwnProperty(key)) {
clone = {};
break;
}
}
// clone if necessary
if (clone) {
for (key in theme) {
if (theme.hasOwnProperty(key)) {
clone[key] = options[key] || theme[key];
}
}
// fix event icon path, allowing full image path in options
clone.eventIcon = options.eventIcon ||
clone.eventIconPath + clone.eventIconImage;
return clone;
}
}
return theme;
};
/*----------------------------------------------------------------------------
* TimeMapItem Class
*---------------------------------------------------------------------------*/
/**
* @class
* The TimeMapItem object holds references to one or more map placemarks and
* an associated timeline event.
*
* @constructor
* @param {String} data Object containing all item data
* @param {String} [data.title=Untitled] Title of the item (visible on timeline)
* @param {String|Date} [data.start] Start time of the event on the timeline
* @param {String|Date} [data.end] End time of the event on the timeline (duration events only)
* @param {Object} [data.point] Data for a single-point placemark:
* @param {Float} [data.point.lat] Latitude of map marker
* @param {Float} [data.point.lon] Longitude of map marker
* @param {Object[]} [data.polyline] Data for a polyline placemark, as an array in "point" format
* @param {Object[]} [data.polygon] Data for a polygon placemark, as an array "point" format
* @param {Object} [data.overlay] Data for a ground overlay:
* @param {String} [data.overlay.image] URL of image to overlay
* @param {Float} [data.overlay.north] Northern latitude of the overlay
* @param {Float} [data.overlay.south] Southern latitude of the overlay
* @param {Float} [data.overlay.east] Eastern longitude of the overlay
* @param {Float} [data.overlay.west] Western longitude of the overlay
* @param {Object[]} [data.placemarks] Array of placemarks, e.g. [{point:{...}}, {polyline:[...]}]
* @param {Object} [data.options] A container for optional arguments
* @param {String} [data.options.description] Plain-text description of the item
* @param {LatLonPoint} [data.options.infoPoint] Point indicating the center of this item
* @param {String} [data.options.infoHtml] Full HTML for the info window
* @param {String} [data.options.infoUrl] URL from which to retrieve full HTML for the info window
* @param {String} [data.options.infoTemplate] HTML for the info window content, with variable expressions
* (as "{{varname}}" by default) to be replaced by option data
* @param {String} [data.options.templatePattern=/{{([^}]+)}}/g]
* Regex pattern defining variable syntax in the infoTemplate
* @param {Function} [data.options.openInfoWindow={@link TimeMapItem.openInfoWindowBasic}]
* Function redefining how info window opens
* @param {Function} [data.options.closeInfoWindow={@link TimeMapItem.closeInfoWindowBasic}]
* Function redefining how info window closes
* @param {String|TimeMapTheme} [data.options.theme] Theme applying to this item, overriding dataset theme
* @param {mixed} [data.options[...]] Any of the options for {@link TimeMapTheme} may be set here
* @param {TimeMapDataset} dataset Reference to the parent dataset object
*/
TimeMapItem = function(data, dataset) {
var item = this,
// set defaults for options
options = $.extend({
type: 'none',
description: '',
infoPoint: null,
infoHtml: '',
infoUrl: '',
openInfoWindow: data.options.infoUrl ?
TimeMapItem.openInfoWindowAjax :
TimeMapItem.openInfoWindowBasic,
infoTemplate: '<div class="infotitle">{{title}}</div>' +
'<div class="infodescription">{{description}}</div>',
templatePattern: /\{\{([^}]+)\}\}/g,
closeInfoWindow: TimeMapItem.closeInfoWindowBasic
}, data.options),
tm = dataset.timemap,
// allow theme options to be specified in options
theme = options.theme = TimeMapTheme.create(options.theme, options),
parser = options.dateParser,
eventClass = Timeline.DefaultEventSource.Event,
// settings for timeline event
start = data.start,
end = data.end,
geometry = data.geometry,
eventIcon = theme.eventIcon,
textColor = theme.eventTextColor,
title = options.title = data.title || 'Untitled',
event = null,
instant,
// empty containers
placemarks = [],
pdataArr = [],
pdata = null,
type = "",
point = null,
i;
// set core fields
/**
* This item's parent dataset
* @name TimeMapItem#dataset
* @type TimeMapDataset
*/
item.dataset = dataset;
/**
* The timemap's map object
* @name TimeMapItem#map
* @type Mapstraction
*/
item.map = tm.map;
/**
* The timemap's timeline object
* @name TimeMapItem#timeline
* @type Timeline
*/
item.timeline = tm.timeline;
/**
* Container for optional settings passed in through the "options" parameter
* @name TimeMapItem#opts
* @type Object
*/
item.opts = options;
// Create timeline event
start = start ? parser(start) : null;
end = end ? parser(end) : null;
instant = !end;
if (start !== null) {
if (util.TimelineVersion() == "1.2") {
// attributes by parameter
event = new eventClass(start, end, null, null,
instant, title, null, null, null, eventIcon, theme.eventColor,
theme.eventTextColor);
} else {
if (!textColor) {
// tweak to show old-style events
textColor = (theme.classicTape && !instant) ? '#FFFFFF' : '#000000';
}
// attributes in object
event = new eventClass({
start: start,
end: end,
instant: instant,
text: title,
icon: eventIcon,
color: theme.eventColor,
textColor: textColor
});
}
// create cross-reference and add to timeline
event.item = item;
// allow for custom event loading
if (!options.noEventLoad) {
// add event to timeline
dataset.eventSource.add(event);
}
}
/**
* This item's timeline event
* @name TimeMapItem#event
* @type Timeline.Event
*/
item.event = event;
// internal function: create map placemark
// takes a data object (could be full data, could be just placemark)
// returns an object with {placemark, type, point}
function createPlacemark(pdata) {
var placemarks = [],
type = "",
points = [],
pBounds;
// point placemark
if (pdata.geometry_points) {
pdata.geometry_points.forEach(function(gpx) {
var lat = gpx.lat,
lon = gpx.lon;
if (lat === undefined || lon === undefined) {
// give up
return placemark;
}
var point = new LatLonPoint(
parseFloat(lat),
parseFloat(lon)
);
points.push(point);
// create marker
var placemark = new Marker(point);
placemark.setLabel(pdata.title);
placemark.addData(theme);
placemarks.push(placemark);
type = "marker";
});
} else if (pdata.point) {
var lat = pdata.point.lat,
lon = pdata.point.lon;
if (lat === undefined || lon === undefined) {
// give up
return placemark;
}
point = new LatLonPoint(
parseFloat(lat),
parseFloat(lon)
);
points.push(point);
// create marker
placemark = new Marker(point);
placemark.setLabel(pdata.title);
placemark.addData(theme);
placemarks.push(placemark);
type = "marker";
}
if (pdata.geometry_polygons) {
pdata.geometry_polygons.forEach(function(polygon) {
var polypoints = [],
line = polygon;
pBounds = new BoundingBox();
if (line && line.length) {
for (x=0; x<line.length; x++) {
var point = new LatLonPoint(
parseFloat(line[x].lat),
parseFloat(line[x].lon)
);
polypoints.push(point);
// add point to visible map bounds
pBounds.extend(point);
}
var placemark = new Polyline(polypoints);
placemark.addData({
color: theme.lineColor,
width: theme.lineWeight,
opacity: theme.lineOpacity,
closed: true,
fillColor: theme.fillColor,
fillOpacity: theme.fillOpacity
});
placemarks.push(placemark);
// set type and point
type = "polygon";
point = pBounds.getCenter();
placemark = new Marker(point);
placemarks.push(placemark);
points.push(polypoints);
}
});
}
// polyline and polygon placemarks
else if (pdata.polyline || pdata.polygon) {
var polypoints = [],
isPolygon = "polygon" in pdata,
line = pdata.polyline || pdata.polygon,
x;
pBounds = new BoundingBox();
if (line && line.length) {
for (x=0; x<line.length; x++) {
point = new LatLonPoint(
parseFloat(line[x].lat),
parseFloat(line[x].lon)
);
points.push(point);
// add point to visible map bounds
pBounds.extend(point);
}
// make polyline or polygon
placemark = new Polyline(points);
placemark.addData({
color: theme.lineColor,
width: theme.lineWeight,
opacity: theme.lineOpacity,
closed: isPolygon,
fillColor: theme.fillColor,
fillOpacity: theme.fillOpacity
});
placemarks.push(placemark);
// set type and point
type = isPolygon ? "polygon" : "polyline";
point = isPolygon ?
pBounds.getCenter() :
points[Math.floor(points.length/2)];
points.push(point);
}
}
// ground overlay placemark
else if ("overlay" in pdata) {
var sw = new LatLonPoint(
parseFloat(pdata.overlay.south),
parseFloat(pdata.overlay.west)
),
ne = new LatLonPoint(
parseFloat(pdata.overlay.north),
parseFloat(pdata.overlay.east)
);
pBounds = new BoundingBox(sw.lat, sw.lon, ne.lat, ne.lon);
// mapstraction can only add it - there's no placemark type :(
// XXX: look into extending Mapstraction here
tm.map.addImageOverlay("img" + (new Date()).getTime(), pdata.overlay.image, theme.lineOpacity,
sw.lon, sw.lat, ne.lon, ne.lat);
type = "overlay";
point = pBounds.getCenter();
points.push(point);
}
return {
"placemarks": placemarks,
"type": type,
"points": points
};
}
// Create array of placemark data
if ("placemarks" in data) {
pdataArr = data.placemarks;
} else {
// we have one or more single placemarks
["point", "polyline", "polygon", "overlay", "geometry_points", "geometry_polygons"].forEach(function(type) {
if (type in data) {
// push placemarks into array
pdata = {};
pdata[type] = data[type];
pdataArr.push(pdata);
}
});
}
// Create placemark objects
pdataArr.forEach(function(pdata) {
// put in title if necessary
pdata.title = pdata.title || title;
// create the placemark
var p = createPlacemark(pdata);
// check that the placemark was valid
if (p) {
// take the first point and type as a default
point = point || p.point;
type = type || p.type;
if (p.placemarks) {
p.placemarks.forEach(function(pm) {
placemarks.push(pm);
});
}
}
});
// set type, overriding for arrays
options.type = placemarks.length > 1 ? "array" : type;
// set infoPoint, checking for custom option
options.infoPoint = options.infoPoint ?
// check for custom infoPoint and convert to point
new LatLonPoint(
parseFloat(options.infoPoint.lat),
parseFloat(options.infoPoint.lon)
) :
point;
// create cross-reference(s) and add placemark(s) if any exist
placemarks.forEach(function(placemark) {
placemark.item = item;
// add listener to make placemark open when event is clicked
placemark.click.addHandler(function() {
item.openInfoWindow();
});
// allow for custom placemark loading
if (!options.noPlacemarkLoad) {
if (util.getPlacemarkType(placemark) == 'marker') {
// add placemark to map
tm.map.addMarker(placemark);
} else {
// add polyline to map
tm.map.addPolyline(placemark);
}
// hide placemarks until the next refresh
placemark.hide();
}
});
/**
* This item's placemark(s)
* @name TimeMapItem#placemark
* @type Marker|Polyline|Array
*/
item.placemark = placemarks.length == 1 ? placemarks[0] :
placemarks.length ? placemarks :
null;
// getter functions
/**
* Return this item's native placemark object (specific to map provider;
* undefined if this item has more than one placemark)
* @name TimeMapItem#getNativePlacemark
* @function
* @return {Object} The native placemark object (e.g. GMarker)
*/
item.getNativePlacemark = function() {
var placemark = item.placemark;
return placemark && (placemark.proprietary_marker || placemark.proprietary_polyline);
};
/**
* Return the placemark type for this item
* @name TimeMapItem#getType
* @function
*
* @return {String} Placemark type
*/
item.getType = function() { return options.type; };
/**
* Return the title for this item
* @name TimeMapItem#getTitle
* @function
*
* @return {String} Item title
*/
item.getTitle = function() { return options.title; };
/**
* Return the item's "info point" (the anchor for the map info window)
* @name TimeMapItem#getInfoPoint
* @function
*
* @return {GLatLng} Info point
*/
item.getInfoPoint = function() {
// default to map center if placemark not set
return options.infoPoint || item.map.getCenter();
};
/**
* Return the start date of the item's event, if any
* @name TimeMapItem#getStart
* @function
*
* @return {Date} Item start date or undefined
*/
item.getStart = function() {
return item.event ? item.event.getStart() : null;
};
/**
* Return the end date of the item's event, if any
* @name TimeMapItem#getEnd
* @function
*
* @return {Date} Item end dateor undefined
*/
item.getEnd = function() {
return item.event ? item.event.getEnd() : null;
};
/**
* Return the timestamp of the start date of the item's event, if any
* @name TimeMapItem#getStartTime
* @function
*
* @return {Number} Item start date timestamp or undefined
*/
item.getStartTime = function() {
var start = item.getStart();
if (start) {
return start.getTime();
}
};
/**
* Return the timestamp of the end date of the item's event, if any
* @name TimeMapItem#getEndTime
* @function
*
* @return {Number} Item end date timestamp or undefined
*/
item.getEndTime = function() {
var end = item.getEnd();
if (end) {
return end.getTime();
}
};
/**
* Whether the item is currently selected
* (i.e., the item's info window is open)
* @name TimeMapItem#isSelected
* @function
* @return Boolean
*/
item.isSelected = function() {
return tm.getSelected() === item;
};
/**
* Whether the item is visible
* @name TimeMapItem#visible
* @type Boolean
*/
item.visible = true;
/**
* Whether the item's placemark is visible
* @name TimeMapItem#placemarkVisible
* @type Boolean
*/
item.placemarkVisible = false;
/**
* Whether the item's event is visible
* @name TimeMapItem#eventVisible
* @type Boolean
*/
item.eventVisible = true;
/**
* Open the info window for this item.
* By default this is the map infoWindow, but you can set custom functions
* for whatever behavior you want when the event or placemark is clicked
* @name TimeMapItem#openInfoWindow
* @function
*/
item.openInfoWindow = function() {
options.openInfoWindow.call(item);
tm.setSelected(item);
};
/**
* Close the info window for this item.
* By default this is the map infoWindow, but you can set custom functions
* for whatever behavior you want.
* @name TimeMapItem#closeInfoWindow
* @function
*/
item.closeInfoWindow = function() {
options.closeInfoWindow.call(item);
tm.setSelected(undefined);
};
};
TimeMapItem.prototype = {
/**
* Show the map placemark(s)
*/
showPlacemark: function() {
// XXX: Special case for overlay image (support for some providers)?
var item = this,
f = function(placemark) {
if (placemark.api) {
placemark.show();
}
};
if (item.placemark && !item.placemarkVisible) {
if (item.getType() == "array") {
item.placemark.forEach(f);
} else {
f(item.placemark);
}
item.placemarkVisible = true;
}
},
/**
* Hide the map placemark(s)
*/
hidePlacemark: function() {
// XXX: Special case for overlay image (support for some providers)?
var item = this,
f = function(placemark) {
if (placemark.api) {
placemark.hide();
}
};
if (item.placemark && item.placemarkVisible) {
if (item.getType() == "array") {
item.placemark.forEach(f);
} else {
f(item.placemark);
}
item.placemarkVisible = false;
}
item.closeInfoWindow();
},
/**
* Show the timeline event.
* NB: Will likely require calling timeline.layout()
*/
showEvent: function() {
var item = this,
event = item.event;
if (event && !item.eventVisible) {
// XXX: Use timeline filtering API
item.timeline.getBand(0)
.getEventSource()._events._events.add(event);
item.eventVisible = true;
}
},
/**
* Hide the timeline event.
* NB: Will likely require calling timeline.layout(),
* AND calling eventSource._events._index() (ugh)
*/
hideEvent: function() {
var item = this,
event = item.event;
if (event && item.eventVisible){
// XXX: Use timeline filtering API
item.timeline.getBand(0)
.getEventSource()._events._events.remove(event);
item.eventVisible = false;
}
},
/**
* Scroll the timeline to the start of this item's event
* @param {Boolean} [animated] Whether to do an animated scroll, rather than a jump.
*/
scrollToStart: function(animated) {
var item = this;
if (item.event) {
item.dataset.timemap.scrollToDate(item.getStart(), false, animated);
}
},
/**
* Get the HTML for the info window, filling in the template if necessary
* @return {String} Info window HTML
*/
getInfoHtml: function() {
var opts = this.opts,
html = opts.infoHtml,
patt = opts.templatePattern,
match;
// create content for info window if none is provided
if (!html) {
// fill in template
html = opts.infoTemplate;
match = patt.exec(html);
while (match) {
html = html.replace(match[0], opts[match[1]]||'');
match = patt.exec(html);
}
// cache for future use
opts.infoHtml = html;
}
return html;
},
/**
* Determine if this item's event is in the current visible area
* of the top band of the timeline. Note that this only considers the
* dates, not whether the event is otherwise hidden.
* @return {Boolean} Whether the item's event is visible
*/
onVisibleTimeline: function() {
var item = this,
topband = item.timeline.getBand(0),
maxVisibleDate = topband.getMaxVisibleDate().getTime(),
minVisibleDate = topband.getMinVisibleDate().getTime(),
itemStart = item.getStartTime(),
itemEnd = item.getEndTime();
return itemStart !== undefined ?
// item is in the future
itemStart < maxVisibleDate &&
// item is in the past
(itemEnd > minVisibleDate || itemStart > minVisibleDate) :
// item has no start date
true;
}
};
/**
* Standard open info window function, using static text in map window
*/
TimeMapItem.openInfoWindowBasic = function() {
var item = this,
html = item.getInfoHtml(),
ds = item.dataset,
placemarks = item.placemark;
// scroll timeline if necessary
if (!item.onVisibleTimeline()) {
ds.timemap.scrollToDate(item.getStart());
}
// open window
if (item.getType() == "marker" && placemarks.api) {
placemarks.setInfoBubble(html);
placemarks.openBubble();
// deselect when window is closed
item.closeHandler = placemarks.closeInfoBubble.addHandler(function() {
// deselect
ds.timemap.setSelected(undefined);
// kill self
placemarks.closeInfoBubble.removeHandler(item.closeHandler);
});
} else if (item.placemark){
if (item.placemark.length > 1) {
item.map.openBubble(item.placemark[1].location, html);
} else {
item.map.openBubble(item.getInfoPoint(), html);
}
item.map.tmBubbleItem = item;
}
};
/**
* Open info window function using ajax-loaded text in map window
*/
TimeMapItem.openInfoWindowAjax = function() {
var item = this;
if (!item.opts.infoHtml && item.opts.infoUrl) { // load content via AJAX
$.get(item.opts.infoUrl, function(result) {
item.opts.infoHtml = result;
item.openInfoWindow();
});
return;
}
// fall back on basic function if content is loaded or URL is missing
item.openInfoWindow = function() {
TimeMapItem.openInfoWindowBasic.call(item);
item.dataset.timemap.setSelected(item);
};
item.openInfoWindow();
};
/**
* Standard close window function, using the map window
*/
TimeMapItem.closeInfoWindowBasic = function() {
var item = this;
if (item.getType() == "marker") {
item.placemark.closeBubble();
} else {
if (item == item.map.tmBubbleItem) {
item.map.closeBubble();
item.map.tmBubbleItem = null;
}
}
};
/*----------------------------------------------------------------------------
* Utility functions
*---------------------------------------------------------------------------*/
/**
* Get XML tag value as a string
*
* @param {jQuery} n jQuery object with context
* @param {String} tag Name of tag to look for
* @param {String} [ns] XML namespace to look in
* @return {String} Tag value as string
*/
TimeMap.util.getTagValue = function(n, tag, ns) {
return util.getNodeList(n, tag, ns).first().text();
};
/**
* Empty container for mapping XML namespaces to URLs
* @example
TimeMap.util.nsMap['georss'] = 'http://www.georss.org/georss';
// find georss:point
TimeMap.util.getNodeList(node, 'point', 'georss')
*/
TimeMap.util.nsMap = {};
/**
* Cross-browser implementation of getElementsByTagNameNS.
* Note: Expects any applicable namespaces to be mapped in
* {@link TimeMap.util.nsMap}.
*
* @param {jQuery|XML Node} n jQuery object with context, or XML node
* @param {String} tag Name of tag to look for
* @param {String} [ns] XML namespace to look in
* @return {jQuery} jQuery object with the list of nodes found
*/
TimeMap.util.getNodeList = function(n, tag, ns) {
var nsMap = TimeMap.util.nsMap;
// get context node
n = n.jquery ? n[0] : n;
// no context
return !n ? $() :
// no namespace
!ns ? $(tag, n) :
// native function exists
(n.getElementsByTagNameNS && nsMap[ns]) ? $(n.getElementsByTagNameNS(nsMap[ns], tag)) :
// no function, try the colon tag name
$(n.getElementsByTagName(ns + ':' + tag));
};
/**
* Make TimeMap.init()-style points from a GLatLng, LatLonPoint, array, or string
*
* @param {Object} coords GLatLng, LatLonPoint, array, or string to convert
* @param {Boolean} [reversed] Whether the points are KML-style lon/lat, rather than lat/lon
* @return {Object} TimeMap.init()-style point object
*/
TimeMap.util.makePoint = function(coords, reversed) {
var latlon = null;
// GLatLng or LatLonPoint
if (coords.lat && coords.lng) {
latlon = [coords.lat(), coords.lng()];
}
// array of coordinates
if ($.type(coords)=='array') {
latlon = coords;
}
// string
if (!latlon) {
// trim extra whitespace
coords = $.trim(coords);
if (coords.indexOf(',') > -1) {
// split on commas
latlon = coords.split(",");
} else {
// split on whitespace
latlon = coords.split(/[\r\n\f ]+/);
}
}
// deal with extra coordinates (i.e. KML altitude)
if (latlon.length > 2) {
latlon = latlon.slice(0, 2);
}
// deal with backwards (i.e. KML-style) coordinates
if (reversed) {
latlon.reverse();
}
return {
"lat": $.trim(latlon[0]),
"lon": $.trim(latlon[1])
};
};
/**
* Make TimeMap.init()-style polyline/polygons from a whitespace-delimited
* string of coordinates (such as those in GeoRSS and KML).
*
* @param {Object} coords String to convert
* @param {Boolean} [reversed] Whether the points are KML-style lon/lat, rather than lat/lon
* @return {Object} Formated coordinate array
*/
TimeMap.util.makePoly = function(coords, reversed) {
var poly = [],
latlon, x,
coordArr = $.trim(coords).split(/[\r\n\f ]+/);
// loop through coordinates
for (x=0; x<coordArr.length; x++) {
latlon = (coordArr[x].indexOf(',') > 0) ?
// comma-separated coordinates (KML-style lon/lat)
coordArr[x].split(",") :
// space-separated coordinates - increment to step by 2s
[coordArr[x], coordArr[++x]];
// deal with extra coordinates (i.e. KML altitude)
if (latlon.length > 2) {
latlon = latlon.slice(0, 2);
}
// deal with backwards (i.e. KML-style) coordinates
if (reversed) {
latlon.reverse();
}
poly.push({
"lat": latlon[0],
"lon": latlon[1]
});
}
return poly;
};
/**
* Format a date as an ISO 8601 string
*
* @param {Date} d Date to format
* @param {Number} [precision] Precision indicator:<pre>
* 3 (default): Show full date and time
* 2: Show full date and time, omitting seconds
* 1: Show date only
*</pre>
* @return {String} Formatted string
*/
TimeMap.util.formatDate = function(d, precision) {
// default to high precision
precision = precision || 3;
var str = "";
if (d) {
var yyyy = d.getUTCFullYear(),
mo = d.getUTCMonth(),
dd = d.getUTCDate();
// deal with early dates
if (yyyy < 1000) {
return (yyyy < 1 ? (yyyy * -1 + "BC") : yyyy + "");
}
// check for date.js support
if (d.toISOString && precision == 3) {
return d.toISOString();
}
// otherwise, build ISO 8601 string
var pad = function(num) {
return ((num < 10) ? "0" : "") + num;
};
str += yyyy + '-' + pad(mo + 1 ) + '-' + pad(dd);
// show time if top interval less than a week
if (precision > 1) {
var hh = d.getUTCHours(),
mm = d.getUTCMinutes(),
ss = d.getUTCSeconds();
str += 'T' + pad(hh) + ':' + pad(mm);
// show seconds if the interval is less than a day
if (precision > 2) {
str += pad(ss);
}
str += 'Z';
}
}
return str;
};
/**
* Determine the SIMILE Timeline version.
*
* @return {String} At the moment, only "1.2", "2.2.0", or what Timeline provides
*/
TimeMap.util.TimelineVersion = function() {
// Timeline.version support added in 2.3.0
return Timeline.version ||
// otherwise check manually
(Timeline.DurationEventPainter ? "1.2" : "2.2.0");
};
/**
* Identify the placemark type of a Mapstraction placemark
*
* @param {Object} pm Placemark to identify
* @return {String} Type of placemark, or false if none found
*/
TimeMap.util.getPlacemarkType = function(pm) {
return pm.constructor == Marker ? 'marker' :
pm.constructor == Polyline ?
(pm.closed ? 'polygon' : 'polyline') :
false;
};
/**
* Attempt look up a key in an object, returning either the value,
* undefined if the key is a string but not found, or the key if not a string
*
* @param {String|Object} key Key to look up
* @param {Object} map Object in which to look
* @return {Object} Value, undefined, or key
*/
TimeMap.util.lookup = function(key, map) {
return typeof key == 'string' ? map[key] : key;
};
// add indexOf support for older browsers (simple version, no "from" support)
if (!([].indexOf)) {
Array.prototype.indexOf = function(el) {
var a = this,
i = a.length;
while (--i >= 0) {
if (a[i] === el) {
break;
}
}
return i;
};
}
// add forEach support for older browsers (simple version, no "this" support)
if (!([].forEach)) {
Array.prototype.forEach = function(f) {
var a = this,
i;
for (i=0; i < a.length; i++) {
if (i in a) {
f(a[i], i, a);
}
}
};
}
/*----------------------------------------------------------------------------
* Lookup maps
* (need to be at end because some call util functions on initialization)
*---------------------------------------------------------------------------*/
/**
* @namespace
* Lookup map of common timeline intervals.
* Add custom intervals here if you want to refer to them by key rather
* than as a function name.
* @example
TimeMap.init({
bandIntervals: "hr",
// etc...
});
*
*/
TimeMap.intervals = {
/** second / minute */
sec: [DateTime.SECOND, DateTime.MINUTE],
/** minute / hour */
min: [DateTime.MINUTE, DateTime.HOUR],
/** hour / day */
hr: [DateTime.HOUR, DateTime.DAY],
/** day / week */
day: [DateTime.DAY, DateTime.WEEK],
/** week / month */
wk: [DateTime.WEEK, DateTime.MONTH],
/** month / year */
mon: [DateTime.MONTH, DateTime.YEAR],
/** year / decade */
yr: [DateTime.YEAR, DateTime.DECADE],
/** decade / century */
dec: [DateTime.DECADE, DateTime.CENTURY]
};
/**
* @namespace
* Lookup map of map types.
* @example
TimeMap.init({
options: {
mapType: "satellite"
},
// etc...
});
*/
TimeMap.mapTypes = {
/** Normal map */
normal: Mapstraction.ROAD,
/** Satellite map */
satellite: Mapstraction.SATELLITE,
/** Hybrid map */
hybrid: Mapstraction.HYBRID,
/** Physical (terrain) map */
physical: Mapstraction.PHYSICAL
};
/**
* @namespace
* Lookup map of supported date parser functions.
* Add custom date parsers here if you want to refer to them by key rather
* than as a function name.
* @example
TimeMap.init({
datasets: [
{
options: {
dateParser: "gregorian"
},
// etc...
}
],
// etc...
});
*/
TimeMap.dateParsers = {
/**
* Better Timeline Gregorian parser... shouldn't be necessary :(.
* Gregorian dates are years with "BC" or "AD"
*
* @param {String} s String to parse into a Date object
* @return {Date} Parsed date or null
*/
gregorian: function(s) {
if (!s || typeof s != "string") {
return null;
}
// look for BC
var bc = Boolean(s.match(/b\.?c\.?/i)),
// parse - parseInt will stop at non-number characters
year = parseInt(s, 10),
d;
// look for success
if (!isNaN(year)) {
// deal with BC
if (bc) {
year = 1 - year;
}
// make Date and return
d = new Date(0);
d.setUTCFullYear(year);
return d;
}
else {
return null;
}
},
/**
* Parse date strings with a series of date parser functions, until one works.
* In order:
* <ol>
* <li>Date.parse() (so Date.js should work here, if it works with Timeline...)</li>
* <li>Gregorian parser</li>
* <li>The Timeline ISO 8601 parser</li>
* </ol>
*
* @param {String} s String to parse into a Date object
* @return {Date} Parsed date or null
*/
hybrid: function(s) {
// in case we don't know if this is a string or a date
if (s instanceof Date) {
return s;
}
var parsers = TimeMap.dateParsers,
// try native date parse and timestamp
d = new Date(typeof s == "number" ? s : Date.parse(parsers.fixChromeBug(s)));
if (isNaN(d)) {
if (typeof s == "string") {
// look for Gregorian dates
if (s.match(/^-?\d{1,6} ?(a\.?d\.?|b\.?c\.?e?\.?|c\.?e\.?)?$/i)) {
d = parsers.gregorian(s);
}
// try ISO 8601 parse
else {
try {
d = parsers.iso8601(s);
} catch(e) {
d = null;
}
}
// look for timestamps
if (!d && s.match(/^\d{7,}$/)) {
d = new Date(parseInt(s, 10));
}
} else {
return null;
}
}
// d should be a date or null
return d;
},
/**
* ISO8601 parser: parse ISO8601 datetime strings
* @function
*/
iso8601: DateTime.parseIso8601DateTime,
/**
* Clunky fix for Chrome bug: http://code.google.com/p/chromium/issues/detail?id=46703
* @private
*/
fixChromeBug: function(s) {
return Date.parse("-200") == Date.parse("200") ?
(typeof s == "string" && s.substr(0,1) == "-" ? null : s) :
s;
}
};
/**
* @namespace
* Pre-set event/placemark themes in a variety of colors.
* Add custom themes here if you want to refer to them by key rather
* than as a function name.
* @example
TimeMap.init({
options: {
theme: "orange"
},
datasets: [
{
options: {
theme: "yellow"
},
// etc...
}
],
// etc...
});
*/
TimeMap.themes = {
/**
* Red theme: <span style="background:#FE766A">#FE766A</span>
* This is the default.
*
* @type TimeMapTheme
*/
red: new TimeMapTheme(),
/**
* Blue theme: <span style="background:#5A7ACF">#5A7ACF</span>
*
* @type TimeMapTheme
*/
blue: new TimeMapTheme({
icon: GIP + "blue-dot.png",
color: "#5A7ACF",
eventIconImage: "blue-circle.png"
}),
/**
* Green theme: <span style="background:#19CF54">#19CF54</span>
*
* @type TimeMapTheme
*/
green: new TimeMapTheme({
icon: GIP + "green-dot.png",
color: "#19CF54",
eventIconImage: "green-circle.png"
}),
/**
* Light blue theme: <span style="background:#5ACFCF">#5ACFCF</span>
*
* @type TimeMapTheme
*/
ltblue: new TimeMapTheme({
icon: GIP + "ltblue-dot.png",
color: "#5ACFCF",
eventIconImage: "ltblue-circle.png"
}),
/**
* Purple theme: <span style="background:#8E67FD">#8E67FD</span>
*
* @type TimeMapTheme
*/
purple: new TimeMapTheme({
icon: GIP + "purple-dot.png",
color: "#8E67FD",
eventIconImage: "purple-circle.png"
}),
/**
* Orange theme: <span style="background:#FF9900">#FF9900</span>
*
* @type TimeMapTheme
*/
orange: new TimeMapTheme({
icon: GIP + "orange-dot.png",
color: "#FF9900",
eventIconImage: "orange-circle.png"
}),
/**
* Yellow theme: <span style="background:#FF9900">#ECE64A</span>
*
* @type TimeMapTheme
*/
yellow: new TimeMapTheme({
icon: GIP + "yellow-dot.png",
color: "#ECE64A",
eventIconImage: "yellow-circle.png"
}),
/**
* Pink theme: <span style="background:#E14E9D">#E14E9D</span>
*
* @type TimeMapTheme
*/
pink: new TimeMapTheme({
icon: GIP + "pink-dot.png",
color: "#E14E9D",
eventIconImage: "pink-circle.png"
})
};
// save to window
window.TimeMap = TimeMap;
window.TimeMapFilterChain = TimeMapFilterChain;
window.TimeMapDataset = TimeMapDataset;
window.TimeMapTheme = TimeMapTheme;
window.TimeMapItem = TimeMapItem;
})();
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M11 9h2V6h3V4h-3V1h-2v3H8v2h3v3zm-4 9c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zm10 0c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2zm-8.9-5h7.45c.75 0 1.41-.41 1.75-1.03l3.86-7.01L19.42 4l-3.87 7H8.53L4.27 2H1v2h2l3.6 7.59L3.62 17H19v-2H7l1.1-2z" />
, 'AddShoppingCartSharp');
|
<script type="text/javascript">
var check = null;
function printDuration() {
if (check == null) {
var cnt = 0;
check = setInterval(function () {
cnt += 1;
document.getElementById("para").innerHTML = cnt;
$('#start').load('curl.php?randval='+ Math.random());
}, 1000);
}
}
function stop() {
clearInterval(check);
check = null;
document.getElementById("para").innerHTML = '0';
}
</script>
<script>$(document).click(function()
{
//curl.php is called every 10 seconds to update MySQL database
var refreshId = setInterval(function()
{
$('#start').load('curl.php?randval='+ Math.random());
}, 1000);
//stop the clock when this button is clicked
$("#stop").click(function()
{
clearInterval(refreshId);
});
});
</script>
|
var _ = require('lodash'),
sinon = require('sinon'),
Collection = require('postman-collection').Collection,
Runner = require('../../../index.js').Runner;
describe('Control Flow', function () {
this.timeout(10 * 1000);
var timeout = 1000,
runner,
spec,
callbacks;
beforeEach(function () {
runner = new Runner();
callbacks = {};
spec = {
collection: {
item: [{
request: {
url: 'http://postman-echo.com/get',
method: 'GET'
}
}]
}
};
// add a spy for each callback
_.forEach(_.keys(Runner.Run.triggers), function (eventName) {
callbacks[eventName] = sinon.spy();
});
});
it('must allow a run to be aborted', function (done) {
callbacks.done = sinon.spy(function () {
expect(callbacks).be.ok();
expect(callbacks.done.calledOnce).be.ok();
expect(callbacks.done.getCall(0).args[0]).to.be(null);
expect(callbacks.start.calledOnce).be.ok();
expect(callbacks.abort.calledOnce).be.ok();
return done();
});
// eslint-disable-next-line handle-callback-err
runner.run(new Collection(spec.collection), {}, function (err, run) {
run.start(callbacks);
run.abort();
});
});
it('must allow a run to be paused and then resumed', function (done) {
callbacks.done = sinon.spy(function () {
expect(callbacks).be.ok();
expect(callbacks.done.calledOnce).be.ok();
expect(callbacks.done.getCall(0).args[0]).to.be(null);
expect(callbacks.start.calledOnce).be.ok();
expect(callbacks.pause.calledOnce).be.ok();
expect(callbacks.resume.calledOnce).be.ok();
return done();
});
// eslint-disable-next-line handle-callback-err
runner.run(new Collection(spec.collection), {}, function (err, run) {
run.start(callbacks);
run.pause(() => {
setTimeout(run.resume.bind(run), timeout);
});
});
});
it('must allow a run to be paused and then aborted', function (done) {
callbacks.done = sinon.spy(function () {
expect(callbacks).be.ok();
expect(callbacks.done.calledOnce).be.ok();
expect(callbacks.done.getCall(0).args[0]).to.be(null);
expect(callbacks.start.calledOnce).be.ok();
expect(callbacks.pause.calledOnce).be.ok();
expect(callbacks.abort.calledOnce).be.ok();
return done();
});
// eslint-disable-next-line handle-callback-err
runner.run(new Collection(spec.collection), {}, function (err, run) {
run.start(callbacks);
run.pause(() => {
setTimeout(run.abort.bind(run), timeout);
});
});
});
});
|
module.exports = function sendOK (data, options) {
// Get access to `req`, `res`, & `sails`
var req = this.req;
var res = this.res;
var sails = req._sails;
sails.log.silly('res.ok() :: Sending 201 ("CREATED") response');
// Set status code
res.status(201);
// If appropriate, serve data as JSON(P)
if (req.wantsJSON) {
return res.jsonx(data);
}
// If second argument is a string, we take that to mean it refers to a view.
// If it was omitted, use an empty object (`{}`)
options = (typeof options === 'string') ? { view: options } : options || {};
// If a view was provided in options, serve it.
// Otherwise try to guess an appropriate view, or if that doesn't
// work, just send JSON.
if (options.view) {
return res.view(options.view, { data: data });
}
// If no second argument provided, try to serve the implied view,
// but fall back to sending JSON(P) if no view can be inferred.
else return res.guessView({ data: data }, function couldNotGuessView () {
return res.jsonx(data);
});
};
|
export default class Icosahedron extends THREE.Object3D {
constructor() {
super()
const geometry = new THREE.IcosahedronBufferGeometry( 50, 2 )
const material = new THREE.MeshStandardMaterial({
color: 0xAAAAAA,
emissive: 0xAAAAAA,
roughness: 0.7,
metalness: 1,
wireframe: true,
wireframeLinewidth: 1
})
const mesh = new THREE.Mesh( geometry, material )
this.add( mesh )
}
}
|
function Pointers () {
// Neeed mouse to perform click
var mouse = require('./mouse.js');
var utils = require('../utils.js');
// Consts
// Buttons : http://msdn.microsoft.com/en-us/library/ie/ff974878(v=vs.85).aspx
this.LEFT_BUTTON = 1;
this.RIGHT_BUTTON = 2;
this.MIDDLE_BUTTON = 4;
this.BACK_BUTTON = 8;
this.FORWARD_BUTTON = 16;
this.PEN_ERASER_BUTTON = 32;
this.BUTTONS_MASK = this.LEFT_BUTTON | this.RIGHT_BUTTON
| this.MIDDLE_BUTTON | this.BACK_BUTTON | this.FORWARD_BUTTON
| this.PEN_ERASER_BUTTON;
// Pointer types :
this.MOUSE = 'mouse';
this.PEN = 'pen';
this.TOUCH = 'touch';
this.UNKNOWN = '';
// Private vars
var _prefixed = !!window.navigator.msPointerEnabled;
/**
* Indicates if pointer events are available
*
* @return Boolean
*/
this.isConnected = function () {
return _prefixed || window.navigator.pointerEnabled;
};
/**
* Perform a pen pointing on the given DOM element.
*
* @param DOMElement element A DOMElement to point with the pen
* @param Object options Event options
* @return Boolean
*/
this.pen = function (element, options) {
options = options||{};
options.pointerType = this.PEN;
options.buttons = this.LEFT_BUTTON;
return this.point(element, options);
};
/**
* Perform a touch on the given DOM element.
*
* @param DOMElement element A DOMElement to touch
* @param Object options Event options
* @return Boolean
*/
this.touch = function (element, options) {
options = options||{};
options.pointerType = this.TOUCH;
options.buttons = this.LEFT_BUTTON;
return this.point(element, options);
};
/**
* Perform a click on the given DOM element.
*
* @param DOMElement element A DOMElement to point
* @param Object options Event options
* @return Boolean
*/
this.click = function (element, options) {
options = options||{};
options.pointerType = this.MOUSE;
options.buttons = this.LEFT_BUTTON;
return this.point(element, options);
};
/**
* Perform a real full pointer "click" on the given DOM element.
*
* @param DOMElement element A DOMElement to point
* @param Object options Point options
* @return Boolean
*/
this.point = function (element, options) {
options = options||{};
options.type = 'pointerdown';
dispatched = this.dispatch(element, options);
options.type = 'pointerup';
dispatched = this.dispatch(element, options)&&dispatched;
// IE10 trigger the click event even if the pointer event is cancelled
// also, the click is a MouseEvent
if(_prefixed) {
options.type = 'click';
return mouse.dispatch(element, options);
// IE11+ fixed the issue and unprefixed pointer events.
// The click is a PointerEvent
} else if(dispatched) {
options.type = 'click';
return this.dispatch(element, options);
}
return false;
};
/**
* Dispatches a pointer event to the given DOM element.
*
* @param DOMElement element A DOMElement on wich to dispatch the event
* @param Object options Event options
* @return Boolean
*/
this.dispatch = function(element,options) {
var button, pointerType, event, coords;
options = options || {};
if(options.buttons !== options.buttons&this.BUTTONS_MASK) {
throw Error('Bad value for the "buttons" property.');
}
options.buttons = options.buttons || this.LEFT_BUTTON;
if(options.button) {
throw Error('Please use the "buttons" property.');
}
if(options.buttons&this.LEFT_BUTTON) {
button = 0;
} else if(options.buttons&this.MIDDLE_BUTTON) {
button = 1;
} else if(options.buttons&this.RIGHT_BUTTON) {
button = 2;
} else if(options.buttons&this.BACK_BUTTON) {
button = 3;
} else if(options.buttons&this.FORWARD_BUTTON) {
button = 4;
} else if(options.buttons&this.PEN_ERASER_BUTTON) {
button = 5;
} else {
button = -1;
}
options.pointerType = options.pointerType || this.UNKNOWN;
// IE10 fix for pointer types
// http://msdn.microsoft.com/en-us/library/ie/hh772359(v=vs.85).aspx
if(_prefixed) {
if(options.pointerType == this.MOUSE) {
pointerType = 4;
} else if(options.pointerType == this.TOUCH) {
pointerType = 2;
} else if(options.pointerType == this.PEN) {
pointerType = 3;
} else {
pointerType = 0;
}
} else {
pointerType = options.pointerType;
}
event = document.createEvent((_prefixed ? 'MS' : '') + 'PointerEvent');
coords = utils.getPossiblePointerCoords(element);
if(null===coords) {
throw Error('Unable to find a point in the viewport at wich the given'
+' element can receive a pointer event.');
}
utils.setEventCoords(event, element);
event.initPointerEvent(
_prefixed ? 'MSPointer' + options.type[7].toUpperCase()
+ options.type.substring(8) : options.type,
'false' === options.canBubble ? false : true,
'false' === options.cancelable ? false : true,
options.view||window, options.detail||1,
// Screen coordinates (relative to the whole user screen)
// FIXME: find a way to get the right screen coordinates
coords.x + window.screenLeft, coords.y + window.screenTop,
// Client coordinates (relative to the viewport)
coords.x, coords.y,
!!options.ctrlKey, !!options.altKey,
!!options.shiftKey, !!options.metaKey,
button, options.relatedTarget||element,
options.offsetX||0, options.offsetY||0,
options.width||1, options.height||1,
options.pressure||255, options.rotation||0,
options.tiltX||0, options.tiltY||0,
options.pointerId||1, pointerType,
options.hwTimestamp||Date.now(), options.isPrimary||true);
utils.setEventProperty(event, 'buttons', options.buttons);
utils.setEventProperty(event, 'pointerType', pointerType);
return element.dispatchEvent(event);
};
}
module.exports = new Pointers();
|
/*
* jsPlumb
*
* Title:jsPlumb 1.4.1
*
* Provides a way to visually connect elements on an HTML page, using either SVG, Canvas
* elements, or VML.
*
* This file contains the base functionality for DOM type adapters.
*
* Copyright (c) 2010 - 2013 Simon Porritt (http://jsplumb.org)
*
* http://jsplumb.org
* http://github.com/sporritt/jsplumb
* http://code.google.com/p/jsplumb
*
* Dual licensed under the MIT and GPL2 licenses.
*/
;(function() {
var canvasAvailable = !!document.createElement('canvas').getContext,
svgAvailable = !!window.SVGAngle || document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"),
// http://stackoverflow.com/questions/654112/how-do-you-detect-support-for-vml-or-svg-in-a-browser
vmlAvailable = function() {
if (vmlAvailable.vml == undefined) {
var a = document.body.appendChild(document.createElement('div'));
a.innerHTML = '<v:shape id="vml_flag1" adj="1" />';
var b = a.firstChild;
b.style.behavior = "url(#default#VML)";
vmlAvailable.vml = b ? typeof b.adj == "object": true;
a.parentNode.removeChild(a);
}
return vmlAvailable.vml;
};
/**
Manages dragging for some instance of jsPlumb.
*/
var DragManager = function(_currentInstance) {
var _draggables = {}, _dlist = [], _delements = {}, _elementsWithEndpoints = {},
// elementids mapped to the draggable to which they belong.
_draggablesForElements = {};
/**
register some element as draggable. right now the drag init stuff is done elsewhere, and it is
possible that will continue to be the case.
*/
this.register = function(el) {
var jpcl = jsPlumb.CurrentLibrary;
el = jpcl.getElementObject(el);
var id = _currentInstance.getId(el),
domEl = jpcl.getDOMElement(el),
parentOffset = jpcl.getOffset(el);
if (!_draggables[id]) {
_draggables[id] = el;
_dlist.push(el);
_delements[id] = {};
}
// look for child elements that have endpoints and register them against this draggable.
var _oneLevel = function(p, startOffset) {
if (p) {
for (var i = 0; i < p.childNodes.length; i++) {
if (p.childNodes[i].nodeType != 3 && p.childNodes[i].nodeType != 8) {
var cEl = jpcl.getElementObject(p.childNodes[i]),
cid = _currentInstance.getId(cEl, null, true);
if (cid && _elementsWithEndpoints[cid] && _elementsWithEndpoints[cid] > 0) {
var cOff = jpcl.getOffset(cEl);
_delements[id][cid] = {
id:cid,
offset:{
left:cOff.left - parentOffset.left,
top:cOff.top - parentOffset.top
}
};
_draggablesForElements[cid] = id;
}
_oneLevel(p.childNodes[i]);
}
}
}
};
_oneLevel(domEl);
};
// refresh the offsets for child elements of this element.
this.updateOffsets = function(elId) {
var jpcl = jsPlumb.CurrentLibrary,
el = jpcl.getElementObject(elId),
id = _currentInstance.getId(el),
children = _delements[id],
parentOffset = jpcl.getOffset(el);
if (children) {
for (var i in children) {
var cel = jpcl.getElementObject(i),
cOff = jpcl.getOffset(cel);
_delements[id][i] = {
id:i,
offset:{
left:cOff.left - parentOffset.left,
top:cOff.top - parentOffset.top
}
};
_draggablesForElements[i] = id;
}
}
};
/**
notification that an endpoint was added to the given el. we go up from that el's parent
node, looking for a parent that has been registered as a draggable. if we find one, we add this
el to that parent's list of elements to update on drag (if it is not there already)
*/
this.endpointAdded = function(el) {
var jpcl = jsPlumb.CurrentLibrary, b = document.body, id = _currentInstance.getId(el), c = jpcl.getDOMElement(el),
p = c.parentNode, done = p == b;
_elementsWithEndpoints[id] = _elementsWithEndpoints[id] ? _elementsWithEndpoints[id] + 1 : 1;
while (p != null && p != b) {
var pid = _currentInstance.getId(p, null, true);
if (pid && _draggables[pid]) {
var idx = -1, pEl = jpcl.getElementObject(p), pLoc = jpcl.getOffset(pEl);
if (_delements[pid][id] == null) {
var cLoc = jsPlumb.CurrentLibrary.getOffset(el);
_delements[pid][id] = {
id:id,
offset:{
left:cLoc.left - pLoc.left,
top:cLoc.top - pLoc.top
}
};
_draggablesForElements[id] = pid;
}
break;
}
p = p.parentNode;
}
};
this.endpointDeleted = function(endpoint) {
if (_elementsWithEndpoints[endpoint.elementId]) {
_elementsWithEndpoints[endpoint.elementId]--;
if (_elementsWithEndpoints[endpoint.elementId] <= 0) {
for (var i in _delements) {
if (_delements[i]) {
delete _delements[i][endpoint.elementId];
delete _draggablesForElements[endpoint.elementId];
}
}
}
}
};
this.changeId = function(oldId, newId) {
_delements[newId] = _delements[oldId];
_delements[oldId] = {};
_draggablesForElements[newId] = _draggablesForElements[oldId];
_draggablesForElements[oldId] = null;
};
this.getElementsForDraggable = function(id) {
return _delements[id];
};
this.elementRemoved = function(elementId) {
var elId = _draggablesForElements[elementId];
if (elId) {
delete _delements[elId][elementId];
delete _draggablesForElements[elementId];
}
};
this.reset = function() {
_draggables = {};
_dlist = [];
_delements = {};
_elementsWithEndpoints = {};
};
};
// for those browsers that dont have it. they still don't have it! but at least they won't crash.
if (!window.console)
window.console = { time:function(){}, timeEnd:function(){}, group:function(){}, groupEnd:function(){}, log:function(){} };
window.jsPlumbAdapter = {
headless:false,
appendToRoot : function(node) {
document.body.appendChild(node);
},
getRenderModes : function() {
return [ "canvas", "svg", "vml" ]
},
isRenderModeAvailable : function(m) {
return {
"canvas":canvasAvailable,
"svg":svgAvailable,
"vml":vmlAvailable()
}[m];
},
getDragManager : function(_jsPlumb) {
return new DragManager(_jsPlumb);
},
setRenderMode : function(mode) {
var renderMode;
if (mode) {
mode = mode.toLowerCase();
var canvasAvailable = this.isRenderModeAvailable("canvas"),
svgAvailable = this.isRenderModeAvailable("svg"),
vmlAvailable = this.isRenderModeAvailable("vml");
// now test we actually have the capability to do this.
if (mode === "svg") {
if (svgAvailable) renderMode = "svg"
else if (canvasAvailable) renderMode = "canvas"
else if (vmlAvailable) renderMode = "vml"
}
else if (mode === "canvas" && canvasAvailable) renderMode = "canvas";
else if (vmlAvailable) renderMode = "vml";
}
return renderMode;
}
};
})();
|
/**
* @author Maximilian Greschke <maximilian@veyo-care.com>
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var TypeError = (function (_Error) {
_inherits(TypeError, _Error);
function TypeError(raw) {
_classCallCheck(this, TypeError);
_get(Object.getPrototypeOf(TypeError.prototype), 'constructor', this).call(this, raw);
}
return TypeError;
})(Error);
exports.TypeError = TypeError;
|
import TestContainer from 'mocha-test-container-support';
import { act } from '@testing-library/preact';
import {
bootstrapPropertiesPanel,
changeInput,
inject
} from 'test/TestHelper';
import {
query as domQuery
} from 'min-dom';
import {
getBusinessObject
} from 'bpmn-js/lib/util/ModelUtil';
import {
getExtensionElementsList
} from 'src/utils/ExtensionElementsUtil';
import CoreModule from 'bpmn-js/lib/core';
import SelectionModule from 'diagram-js/lib/features/selection';
import ModelingModule from 'bpmn-js/lib/features/modeling';
import BpmnPropertiesPanel from 'src/render';
import BpmnPropertiesProvider from 'src/provider/bpmn';
import CamundaPlatformPropertiesProvider from 'src/provider/camunda-platform';
import camundaModdleExtensions from 'camunda-bpmn-moddle/resources/camunda.json';
import diagramXML from './FormField.bpmn';
describe('provider/camunda-platform - FormFieldProperty', function() {
const testModules = [
BpmnPropertiesPanel,
BpmnPropertiesProvider,
CamundaPlatformPropertiesProvider,
CoreModule,
ModelingModule,
SelectionModule
];
const moddleExtensions = {
camunda: camundaModdleExtensions
};
let container;
beforeEach(function() {
container = TestContainer.get(this);
});
beforeEach(bootstrapPropertiesPanel(diagramXML, {
modules: testModules,
moddleExtensions,
debounceInput: false
}));
describe('#ID', function() {
it('should display', inject(async function(elementRegistry, selection) {
// given
const task = elementRegistry.get('UserTask_1');
await act(() => {
selection.select(task);
});
const idInput = domQuery('#bio-properties-panel-UserTask_1-formField-0-formFieldProperties-property-1-id', container);
const properties = getFormFieldProperties(task, 0);
// then
expect(idInput).to.exist;
expect(idInput.value).to.equal(properties.get('values')[0].id);
}));
it('should update', inject(async function(elementRegistry, selection) {
// given
const task = elementRegistry.get('UserTask_1');
await act(() => {
selection.select(task);
});
const idInput = domQuery('#bio-properties-panel-UserTask_1-formField-0-formFieldProperties-property-1-id', container);
const properties = getFormFieldProperties(task, 0);
// when
changeInput(idInput, 'newVal');
// then
expect(properties.get('values')[0].id).to.equal('newVal');
}));
it('should update on external change', inject(
async function(elementRegistry, selection, commandStack) {
// given
const task = elementRegistry.get('UserTask_1');
const properties = getFormFieldProperties(task, 0);
const originalValue = properties.get('values')[0].id;
await act(() => {
selection.select(task);
});
const idInput = domQuery('#bio-properties-panel-UserTask_1-formField-0-formFieldProperties-property-1-id', container);
changeInput(idInput, 'newVal');
// when
await act(() => {
commandStack.undo();
});
// then
expect(idInput.value).to.eql(originalValue);
}));
});
describe('#Value', function() {
it('should display', inject(async function(elementRegistry, selection) {
// given
const task = elementRegistry.get('UserTask_1');
await act(() => {
selection.select(task);
});
const valueInput = domQuery('#bio-properties-panel-UserTask_1-formField-0-formFieldProperties-property-1-value', container);
const properties = getFormFieldProperties(task, 0);
// then
expect(valueInput).to.exist;
expect(valueInput.value).to.equal(properties.get('values')[0].value);
}));
it('should update', inject(async function(elementRegistry, selection) {
// given
const task = elementRegistry.get('UserTask_1');
await act(() => {
selection.select(task);
});
const valueInput = domQuery('#bio-properties-panel-UserTask_1-formField-0-formFieldProperties-property-1-value', container);
const properties = getFormFieldProperties(task, 0);
// when
changeInput(valueInput, 'newVal');
// then
expect(properties.get('values')[0].value).to.equal('newVal');
}));
it('should update on external change', inject(
async function(elementRegistry, selection, commandStack) {
// given
const task = elementRegistry.get('UserTask_1');
const properties = getFormFieldProperties(task, 0);
const originalValue = properties.get('values')[0].value;
await act(() => {
selection.select(task);
});
const valueInput = domQuery('#bio-properties-panel-UserTask_1-formField-0-formFieldProperties-property-1-value', container);
changeInput(valueInput, 'newVal');
// when
await act(() => {
commandStack.undo();
});
// then
expect(valueInput.value).to.eql(originalValue);
}));
});
});
// helper //////
function getFormData(element) {
const bo = getBusinessObject(element);
return getExtensionElementsList(bo, 'camunda:FormData')[0];
}
function getFormFieldsList(element) {
const businessObject = getBusinessObject(element);
const formData = getFormData(businessObject);
return formData && formData.fields;
}
function getFormField(element, idx) {
return getFormFieldsList(element)[idx];
}
function getFormFieldProperties(element, formFieldIdx) {
return getFormField(element, formFieldIdx).get('properties');
}
|
var profile = (function () {
return {
resourceTags : {
copyOnly : function (filename, mid) {
return copyOnly(filename, mid);
},
amd : function (filename, mid) {
return !copyOnly(filename, mid) && /\.js$/.test(filename);
}
}
};
})();
|
module.exports = {
initialize: global.Packages.Ephemeral.initialize
};
|
// Generated on 2016-08-26 using generator-angular 0.15.1
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Automatically load required Grunt tasks
require('jit-grunt')(grunt, {
useminPrepare: 'grunt-usemin',
ngtemplates: 'grunt-angular-templates',
cdnify: 'grunt-google-cdn'
});
// Configurable paths for the application
var appConfig = {
app: require('./bower.json').appPath || 'app',
dist: 'dist'
};
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
yeoman: appConfig,
// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
js: {
files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
tasks: ['newer:jshint:all', 'newer:jscs:all'],
options: {
livereload: '<%= connect.options.livereload %>'
}
},
jsTest: {
files: ['test/spec/{,*/}*.js'],
tasks: ['newer:jshint:test', 'newer:jscs:test', 'karma']
},
styles: {
files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
tasks: ['newer:copy:styles', 'postcss']
},
gruntfile: {
files: ['Gruntfile.js']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'<%= yeoman.app %>/{,*/}*.html',
'.tmp/styles/{,*/}*.css',
'<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
]
}
},
// The actual grunt server settings
connect: {
options: {
port: 9000,
// Change this to '0.0.0.0' to access the server from outside.
hostname: 'localhost',
livereload: 35729
},
livereload: {
options: {
open: true,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect().use(
'/app/styles',
connect.static('./app/styles')
),
connect.static(appConfig.app)
];
}
}
},
test: {
options: {
port: 9001,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect.static('test'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app)
];
}
}
},
dist: {
options: {
open: true,
base: '<%= yeoman.dist %>'
}
}
},
// Make sure there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: {
src: [
'Gruntfile.js',
'<%= yeoman.app %>/scripts/{,*/}*.js'
]
},
test: {
options: {
jshintrc: 'test/.jshintrc'
},
src: ['test/spec/{,*/}*.js']
}
},
// Make sure code styles are up to par
jscs: {
options: {
config: '.jscsrc',
verbose: true
},
all: {
src: [
'Gruntfile.js',
'<%= yeoman.app %>/scripts/{,*/}*.js'
]
},
test: {
src: ['test/spec/{,*/}*.js']
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/{,*/}*',
'!<%= yeoman.dist %>/.git{,*/}*'
]
}]
},
server: '.tmp'
},
// Add vendor prefixed styles
postcss: {
options: {
processors: [
require('autoprefixer-core')({browsers: ['last 1 version']})
]
},
server: {
options: {
map: true
},
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
// Automatically inject Bower components into the app
wiredep: {
app: {
src: ['<%= yeoman.app %>/index.html'],
ignorePath: /\.\.\//
},
test: {
devDependencies: true,
src: '<%= karma.unit.configFile %>',
ignorePath: /\.\.\//,
fileTypes:{
js: {
block: /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi,
detect: {
js: /'(.*\.js)'/gi
},
replace: {
js: '\'{{filePath}}\','
}
}
}
}
},
// Renames files for browser caching purposes
filerev: {
dist: {
src: [
'<%= yeoman.dist %>/scripts/{,*/}*.js',
'<%= yeoman.dist %>/styles/{,*/}*.css',
'<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
'<%= yeoman.dist %>/styles/fonts/*'
]
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
html: '<%= yeoman.app %>/index.html',
options: {
dest: '<%= yeoman.dist %>',
flow: {
html: {
steps: {
js: ['concat', 'uglifyjs'],
css: ['cssmin']
},
post: {}
}
}
}
},
// Performs rewrites based on filerev and the useminPrepare configuration
usemin: {
html: ['<%= yeoman.dist %>/{,*/}*.html'],
css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
js: ['<%= yeoman.dist %>/scripts/{,*/}*.js'],
options: {
assetsDirs: [
'<%= yeoman.dist %>',
'<%= yeoman.dist %>/images',
'<%= yeoman.dist %>/styles'
],
patterns: {
js: [[/(images\/[^''""]*\.(png|jpg|jpeg|gif|webp|svg))/g, 'Replacing references to images']]
}
}
},
// The following *-min tasks will produce minified files in the dist folder
// By default, your `index.html`'s <!-- Usemin block --> will take care of
// minification. These next options are pre-configured if you do not wish
// to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= yeoman.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= yeoman.dist %>/scripts/scripts.js': [
// '<%= yeoman.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.{png,jpg,jpeg,gif}',
dest: '<%= yeoman.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.svg',
dest: '<%= yeoman.dist %>/images'
}]
}
},
htmlmin: {
dist: {
options: {
collapseWhitespace: true,
conservativeCollapse: true,
collapseBooleanAttributes: true,
removeCommentsFromCDATA: true
},
files: [{
expand: true,
cwd: '<%= yeoman.dist %>',
src: ['*.html'],
dest: '<%= yeoman.dist %>'
}]
}
},
ngtemplates: {
dist: {
options: {
module: 'yoTodoApp',
htmlmin: '<%= htmlmin.dist.options %>',
usemin: 'scripts/scripts.js'
},
cwd: '<%= yeoman.app %>',
src: 'views/{,*/}*.html',
dest: '.tmp/templateCache.js'
}
},
// ng-annotate tries to make the code safe for minification automatically
// by using the Angular long form for dependency injection.
ngAnnotate: {
dist: {
files: [{
expand: true,
cwd: '.tmp/concat/scripts',
src: '*.js',
dest: '.tmp/concat/scripts'
}]
}
},
// Replace Google CDN references
cdnify: {
dist: {
html: ['<%= yeoman.dist %>/*.html']
}
},
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'*.{ico,png,txt}',
'*.html',
'images/{,*/}*.{webp}',
'styles/fonts/{,*/}*.*'
]
}, {
expand: true,
cwd: '.tmp/images',
dest: '<%= yeoman.dist %>/images',
src: ['generated/*']
}, {
expand: true,
cwd: 'bower_components/bootstrap/dist',
src: 'fonts/*',
dest: '<%= yeoman.dist %>'
}]
},
styles: {
expand: true,
cwd: '<%= yeoman.app %>/styles',
dest: '.tmp/styles/',
src: '{,*/}*.css'
}
},
// Run some tasks in parallel to speed up the build process
concurrent: {
server: [
'copy:styles'
],
test: [
'copy:styles'
],
dist: [
'copy:styles',
'imagemin',
'svgmin'
]
},
// Test settings
karma: {
unit: {
configFile: 'test/karma.conf.js',
singleRun: true
}
}
});
grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'wiredep',
'concurrent:server',
'postcss:server',
'connect:livereload',
'watch'
]);
});
grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run(['serve:' + target]);
});
grunt.registerTask('test', [
'clean:server',
'wiredep',
'concurrent:test',
'postcss',
'connect:test',
'karma'
]);
grunt.registerTask('build', [
'clean:dist',
'wiredep',
'useminPrepare',
'concurrent:dist',
'postcss',
'ngtemplates',
'concat',
'ngAnnotate',
'copy:dist',
'cdnify',
'cssmin',
'uglify',
'filerev',
'usemin',
'htmlmin'
]);
grunt.registerTask('default', [
'newer:jshint',
'newer:jscs',
'test',
'build'
]);
};
|
/*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
//node.js deps
//npm deps
const mqtt = require('mqtt');
//app deps
const exceptions = require('./lib/exceptions'),
isUndefined = require('../common/lib/is-undefined'),
tlsReader = require('../common/lib/tls-reader');
//begin module
const reconnectPeriod = 3 * 1000;
//
// This method is the exposed module; it validates the mqtt options,
// creates a secure mqtt connection via TLS, and returns the mqtt
// connection instance.
//
module.exports = function(options) {
//
// Validate options, set default reconnect period if not specified.
//
if (isUndefined(options) ||
Object.keys(options).length === 0) {
throw new Error(exceptions.INVALID_CONNECT_OPTIONS);
}
if (isUndefined(options.reconnectPeriod)) {
options.reconnectPeriod = reconnectPeriod;
}
// set port, do not override existing definitions if available
if (isUndefined(options.port))
{
options.port = 8883;
}
options.protocol = 'mqtts';
if (isUndefined(options.host))
{
if (!(isUndefined(options.region)))
{
options.host = 'data.iot.'+options.region+'.amazonaws.com';
}
else
{
throw new Error(exceptions.INVALID_CONNECT_OPTIONS);
}
}
//read and map certificates
tlsReader(options);
if ((!isUndefined(options)) && (options.debug===true))
{
console.log(options);
console.log('attempting new mqtt connection...');
}
//connect and return the client instance to map all mqttjs apis
const device = mqtt.connect(options);
//handle some exceptions
device
.on('error', function(error) {
//certificate issue
if (error.code === 'EPROTO') {
throw new Error(error);
}
});
return device;
};
|
/** @jsx jsx */
import { jsx } from "@emotion/core";
import { useRef, useEffect } from "react";
import { useSpring, animated, config } from "react-spring";
/*
Explanation for Triangle's seemingly convoluted animation:
- The biggest problem with Triangle is that if the animation goes from 0deg to 180deg then the opposite, it goes backwards instead of completing a full rotation.
- The above behaviour is undesirable so for eons I wanted to find a more elegant method than keeping an internal angle and incrementing it with 180degs indefinitely
- With React Spring the solution also seemed far away. Until I found the reset option which allows the animation to start over making it easily toggleable
- The remaining problem was that when the "from" property is passed the component animates on mount
- This was solved by dismissing animations and then imperatively mutating a reference after mount that would stop dismissal of animations on subsequent toggles
Take two:
- This worked great until more complex components got involved as reset meant that the animation will actually reset every single re-render
- Again that behaviour was undesirable so another reference that preserves the previous state was needed to dismiss resets when the state was unchanged
*/
const Triangle = ({ on }) => {
const dismissAnimation = useRef(true);
const previousState = useRef(on);
const props = useSpring({
from: { angle: on ? 180 : 0 },
to: { angle: on ? 360 : 180 },
reset: previousState.current !== on,
immediate: dismissAnimation.current,
config: config.gentle
});
useEffect(() => {
dismissAnimation.current = false;
}, []);
useEffect(() => {
previousState.current = on;
}, [on]);
return (
<animated.div
css={{
width: 0,
height: 0,
borderLeft: "75px solid transparent",
borderRight: "75px solid transparent",
borderBottom: `129.88px solid ${on ? "#129793" : "#505050"}`
}}
style={{
transform: props.angle.interpolate(angle => `rotate(${angle}deg`)
}}
/>
);
};
export default Triangle;
|
require('babel-register');
require('babel-polyfill');
require('./src/build-html.js');
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
var util = require('util');
var msRest = require('ms-rest');
var msRestAzure = require('ms-rest-azure');
var ServiceClient = msRest.ServiceClient;
var WebResource = msRest.WebResource;
var models = require('../models');
/**
* @class
* SubscriptionInCredentials
* __NOTE__: An instance of this class is automatically created for an
* instance of the AutoRestAzureSpecialParametersTestClient.
* Initializes a new instance of the SubscriptionInCredentials class.
* @constructor
*
* @param {AutoRestAzureSpecialParametersTestClient} client Reference to the service client.
*/
function SubscriptionInCredentials(client) {
this.client = client;
}
/**
* POST method with subscriptionId modeled in credentials. Set the credential
* subscriptionId to '1234-5678-9012-3456' to succeed
*
* @param {object} [options]
*
* @param {object} [options.customHeaders] headers that will be added to
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SubscriptionInCredentials.prototype.postMethodGlobalValid = function (options, callback) {
var client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Validate
try {
if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var requestUrl = this.client.baseUri +
'//azurespecials/subscriptionId/method/string/none/path/global/1234-5678-9012-3456/{subscriptionId}';
requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
var queryParameters = [];
if (queryParameters.length > 0) {
requestUrl += '?' + queryParameters.join('&');
}
// trim all duplicate forward slashes in the url
var regex = /([^:]\/)\/+/gi;
requestUrl = requestUrl.replace(regex, '$1');
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'POST';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
httpRequest.headers['Content-Length'] = 0;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 200) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = httpRequest;
error.response = response;
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
error.body = new client._models['ErrorModel']();
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
error.body.deserialize(parsedErrorResponse);
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody - "%s" for the default response.', defaultError, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* POST method with subscriptionId modeled in credentials. Set the credential
* subscriptionId to null, and client-side validation should prevent you from
* making this call
*
* @param {object} [options]
*
* @param {object} [options.customHeaders] headers that will be added to
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SubscriptionInCredentials.prototype.postMethodGlobalNull = function (options, callback) {
var client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Validate
try {
if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var requestUrl = this.client.baseUri +
'//azurespecials/subscriptionId/method/string/none/path/global/null/{subscriptionId}';
requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
var queryParameters = [];
if (queryParameters.length > 0) {
requestUrl += '?' + queryParameters.join('&');
}
// trim all duplicate forward slashes in the url
var regex = /([^:]\/)\/+/gi;
requestUrl = requestUrl.replace(regex, '$1');
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'POST';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
httpRequest.headers['Content-Length'] = 0;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 200) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = httpRequest;
error.response = response;
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
error.body = new client._models['ErrorModel']();
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
error.body.deserialize(parsedErrorResponse);
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody - "%s" for the default response.', defaultError, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* POST method with subscriptionId modeled in credentials. Set the credential
* subscriptionId to '1234-5678-9012-3456' to succeed
*
* @param {object} [options]
*
* @param {object} [options.customHeaders] headers that will be added to
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SubscriptionInCredentials.prototype.postMethodGlobalNotProvidedValid = function (options, callback) {
var client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Validate
try {
if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
}
if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var requestUrl = this.client.baseUri +
'//azurespecials/subscriptionId/method/string/none/path/globalNotProvided/1234-5678-9012-3456/{subscriptionId}';
requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
var queryParameters = [];
queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
if (queryParameters.length > 0) {
requestUrl += '?' + queryParameters.join('&');
}
// trim all duplicate forward slashes in the url
var regex = /([^:]\/)\/+/gi;
requestUrl = requestUrl.replace(regex, '$1');
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'POST';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
httpRequest.headers['Content-Length'] = 0;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 200) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = httpRequest;
error.response = response;
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
error.body = new client._models['ErrorModel']();
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
error.body.deserialize(parsedErrorResponse);
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody - "%s" for the default response.', defaultError, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* POST method with subscriptionId modeled in credentials. Set the credential
* subscriptionId to '1234-5678-9012-3456' to succeed
*
* @param {object} [options]
*
* @param {object} [options.customHeaders] headers that will be added to
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SubscriptionInCredentials.prototype.postPathGlobalValid = function (options, callback) {
var client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Validate
try {
if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var requestUrl = this.client.baseUri +
'//azurespecials/subscriptionId/path/string/none/path/global/1234-5678-9012-3456/{subscriptionId}';
requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
var queryParameters = [];
if (queryParameters.length > 0) {
requestUrl += '?' + queryParameters.join('&');
}
// trim all duplicate forward slashes in the url
var regex = /([^:]\/)\/+/gi;
requestUrl = requestUrl.replace(regex, '$1');
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'POST';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
httpRequest.headers['Content-Length'] = 0;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 200) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = httpRequest;
error.response = response;
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
error.body = new client._models['ErrorModel']();
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
error.body.deserialize(parsedErrorResponse);
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody - "%s" for the default response.', defaultError, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
/**
* POST method with subscriptionId modeled in credentials. Set the credential
* subscriptionId to '1234-5678-9012-3456' to succeed
*
* @param {object} [options]
*
* @param {object} [options.customHeaders] headers that will be added to
* request
*
* @param {function} callback
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
SubscriptionInCredentials.prototype.postSwaggerGlobalValid = function (options, callback) {
var client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Validate
try {
if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
var requestUrl = this.client.baseUri +
'//azurespecials/subscriptionId/swagger/string/none/path/global/1234-5678-9012-3456/{subscriptionId}';
requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
var queryParameters = [];
if (queryParameters.length > 0) {
requestUrl += '?' + queryParameters.join('&');
}
// trim all duplicate forward slashes in the url
var regex = /([^:]\/)\/+/gi;
requestUrl = requestUrl.replace(regex, '$1');
// Create HTTP transport objects
var httpRequest = new WebResource();
httpRequest.method = 'POST';
httpRequest.headers = {};
httpRequest.url = requestUrl;
// Set Headers
httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if(options) {
for(var headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
httpRequest.body = null;
httpRequest.headers['Content-Length'] = 0;
// Send Request
return client.pipeline(httpRequest, function (err, response, responseBody) {
if (err) {
return callback(err);
}
var statusCode = response.statusCode;
if (statusCode !== 200) {
var error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = httpRequest;
error.response = response;
if (responseBody === '') responseBody = null;
var parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
error.body = new client._models['ErrorModel']();
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
error.body.deserialize(parsedErrorResponse);
}
} catch (defaultError) {
error.message = util.format('Error "%s" occurred in deserializing the responseBody - "%s" for the default response.', defaultError, responseBody);
return callback(error);
}
return callback(error);
}
// Create Result
var result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
};
module.exports = SubscriptionInCredentials;
|
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Traditional Chinese strings.
* @author gasolin@gmail.com (Fred Lin)
*/
'use strict';
goog.provides('Blockly.messages.zh_tw');
/**
* Due to the frequency of long strings, the 80-column wrap rule need not apply
* to message files.
*/
// Context menus.
Blockly.MSG_DUPLICATE_BLOCK = '複製';
Blockly.MSG_REMOVE_COMMENT = '移除註解';
Blockly.MSG_ADD_COMMENT = '加入註解';
Blockly.MSG_EXTERNAL_INPUTS = '多行輸入';
Blockly.MSG_INLINE_INPUTS = '單行輸入';
Blockly.MSG_DELETE_BLOCK = '刪除積木';
Blockly.MSG_DELETE_X_BLOCKS = '刪除 %1 塊積木';
Blockly.MSG_COLLAPSE_BLOCK = '收合積木';
Blockly.MSG_EXPAND_BLOCK = '展開積木';
Blockly.MSG_DISABLE_BLOCK = '停用積木';
Blockly.MSG_ENABLE_BLOCK = '啟用積木';
Blockly.MSG_HELP = '說明';
Blockly.MSG_COLLAPSE_ALL = 'Collapse Blocks';
Blockly.MSG_EXPAND_ALL = 'Expand Blocks';
Blockly.MSG_ARRANGE_H = 'Arrange Blocks Horizontally';
Blockly.MSG_ARRANGE_V = 'Arrange Blocks Vertically';
Blockly.MSG_ARRANGE_S = 'Arrange Blocks Diagonally';
Blockly.MSG_SORT_W = 'Sort Blocks by Width';
Blockly.MSG_SORT_H = 'Sort Blocks by Height';
Blockly.MSG_SORT_C = 'Sort Blocks by Category';
// Variable renaming.
Blockly.MSG_CHANGE_VALUE_TITLE = '修改值:';
Blockly.MSG_NEW_VARIABLE = '新變量...';
Blockly.MSG_NEW_VARIABLE_TITLE = '新變量名稱:';
Blockly.MSG_RENAME_VARIABLE = '重新命名變量...';
Blockly.MSG_RENAME_VARIABLE_TITLE = '將所有 "%1" 變量重新命名為:';
// Toolbox.
Blockly.MSG_VARIABLE_CATEGORY = '變量';
Blockly.MSG_PROCEDURE_CATEGORY = '流程';
// Colour Blocks.
Blockly.LANG_CATEGORY_COLOUR = 'Colour';
Blockly.LANG_COLOUR_PICKER_HELPURL = 'http://en.wikipedia.org/wiki/Color';
Blockly.LANG_COLOUR_PICKER_TOOLTIP = 'Choose a colour form the palette.';
Blockly.LANG_COLOUR_RGB_HELPURL = 'http://en.wikipedia.org/wiki/RGB_color_model';
Blockly.LANG_COLOUR_RGB_TITLE = 'colour with';
Blockly.LANG_COLOUR_RGB_RED = 'red';
Blockly.LANG_COLOUR_RGB_GREEN = 'green';
Blockly.LANG_COLOUR_RGB_BLUE = 'blue';
Blockly.LANG_COLOUR_RGB_TOOLTIP = 'Create a colour with the specified amount of red, green,\n' +
'and blue. All values must be between 0.0 and 1.0.';
Blockly.LANG_COLOUR_BLEND_HELPURL = 'http://meyerweb.com/eric/tools/color-blend/';
Blockly.LANG_COLOUR_BLEND_TITLE = 'blend';
Blockly.LANG_COLOUR_BLEND_COLOUR1 = 'colour 1';
Blockly.LANG_COLOUR_BLEND_COLOUR2 = 'colour 2';
Blockly.LANG_COLOUR_BLEND_RATIO = 'ratio';
Blockly.LANG_COLOUR_BLEND_TOOLTIP = 'Blends two colours together with a given ratio (0.0 - 1.0).';
// Control Blocks.
Blockly.LANG_CATEGORY_CONTROLS = '控制';
Blockly.LANG_CONTROLS_IF_HELPURL = 'http://code.google.com/p/blockly/wiki/If_Then';
Blockly.LANG_CONTROLS_IF_TOOLTIP_1 = 'If a value is true, then do some statements.';
Blockly.LANG_CONTROLS_IF_TOOLTIP_2 = 'If a value is true, then do the first block of statements.\n' +
'Otherwise, do the second block of statements.';
Blockly.LANG_CONTROLS_IF_TOOLTIP_3 = 'If the first value is true, then do the first block of statements.\n' +
'Otherwise, if the second value is true, do the second block of statements.';
Blockly.LANG_CONTROLS_IF_TOOLTIP_4 = 'If the first value is true, then do the first block of statements.\n' +
'Otherwise, if the second value is true, do the second block of statements.\n' +
'If none of the values are true, do the last block of statements.';
Blockly.LANG_CONTROLS_IF_MSG_IF = '如果';
Blockly.LANG_CONTROLS_IF_MSG_ELSEIF = '否則如果';
Blockly.LANG_CONTROLS_IF_MSG_ELSE = '否則';
Blockly.LANG_CONTROLS_IF_MSG_THEN = '就';
Blockly.LANG_CONTROLS_IF_IF_TITLE_IF = '如果';
Blockly.LANG_CONTROLS_IF_IF_TOOLTIP = 'Add, remove, or reorder sections\n' +
'to reconfigure this if block.';
Blockly.LANG_CONTROLS_IF_ELSEIF_TITLE_ELSEIF = '否則如果';
Blockly.LANG_CONTROLS_IF_ELSEIF_TOOLTIP = 'Add a condition to the if block.';
Blockly.LANG_CONTROLS_IF_ELSE_TITLE_ELSE = '否則';
Blockly.LANG_CONTROLS_IF_ELSE_TOOLTIP = 'Add a final, catch-all condition to the if block.';
Blockly.LANG_CONTROLS_REPEAT_HELPURL = 'http://en.wikipedia.org/wiki/For_loop';
Blockly.LANG_CONTROLS_REPEAT_TITLE_REPEAT = '重複';
Blockly.LANG_CONTROLS_REPEAT_TITLE_TIMES = '次數';
Blockly.LANG_CONTROLS_REPEAT_INPUT_DO = '執行';
Blockly.LANG_CONTROLS_REPEAT_TOOLTIP = 'Do some statements several times.';
Blockly.LANG_CONTROLS_WHILEUNTIL_HELPURL = 'http://code.google.com/p/blockly/wiki/Repeat';
Blockly.LANG_CONTROLS_WHILEUNTIL_TITLE_REPEAT = '重複';
Blockly.LANG_CONTROLS_WHILEUNTIL_INPUT_DO = '執行';
Blockly.LANG_CONTROLS_WHILEUNTIL_OPERATOR_WHILE = '當';
Blockly.LANG_CONTROLS_WHILEUNTIL_OPERATOR_UNTIL = '直到';
Blockly.LANG_CONTROLS_WHILEUNTIL_TOOLTIP_WHILE = 'While a value is true, then do some statements.';
Blockly.LANG_CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL = 'While a value is false, then do some statements.';
Blockly.LANG_CONTROLS_FOR_HELPURL = 'http://en.wikipedia.org/wiki/For_loop';
Blockly.LANG_CONTROLS_FOR_INPUT_WITH = '使用';
Blockly.LANG_CONTROLS_FOR_INPUT_VAR = '變量';
Blockly.LANG_CONTROLS_FOR_INPUT_FROM = '從範圍';
Blockly.LANG_CONTROLS_FOR_INPUT_TO = '到';
Blockly.LANG_CONTROLS_FOR_INPUT_DO = '執行';
Blockly.LANG_CONTROLS_FOR_TOOLTIP = 'Count from a start number to an end number.\n' +
'For each count, set the current count number to\n' +
'variable "%1", and then do some statements.';
Blockly.LANG_CONTROLS_FOREACH_HELPURL = 'http://en.wikipedia.org/wiki/For_loop';
Blockly.LANG_CONTROLS_FOREACH_INPUT_ITEM = '取出每個';
Blockly.LANG_CONTROLS_FOREACH_INPUT_VAR = '變量';
Blockly.LANG_CONTROLS_FOREACH_INPUT_INLIST = '自列表';
Blockly.LANG_CONTROLS_FOREACH_INPUT_DO = '執行';
Blockly.LANG_CONTROLS_FOREACH_TOOLTIP = 'For each item in a list, set the item to\n' +
'variable "%1", and then do some statements.';
Blockly.LANG_CONTROLS_FLOW_STATEMENTS_HELPURL = 'http://en.wikipedia.org/wiki/Control_flow';
Blockly.LANG_CONTROLS_FLOW_STATEMENTS_INPUT_OFLOOP = '迴圈';
Blockly.LANG_CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK = '停止';
Blockly.LANG_CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE = '繼續下一個';
Blockly.LANG_CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK = 'Break out of the containing loop.';
Blockly.LANG_CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE = 'Skip the rest of this loop, and\n' +
'continue with the next iteration.';
Blockly.LANG_CONTROLS_FLOW_STATEMENTS_WARNING = 'Warning:\n' +
'This block may only\n' +
'be used within a loop.';
// Logic Blocks.
Blockly.LANG_CATEGORY_LOGIC = '邏輯';
Blockly.LANG_LOGIC_COMPARE_HELPURL = 'http://en.wikipedia.org/wiki/Inequality_(mathematics)';
Blockly.LANG_LOGIC_COMPARE_TOOLTIP_EQ = 'Return true if both inputs equal each other.';
Blockly.LANG_LOGIC_COMPARE_TOOLTIP_NEQ = 'Return true if both inputs are not equal to each other.';
Blockly.LANG_LOGIC_COMPARE_TOOLTIP_LT = 'Return true if the first input is smaller\n' +
'than the second input.';
Blockly.LANG_LOGIC_COMPARE_TOOLTIP_LTE = 'Return true if the first input is smaller\n' +
'than or equal to the second input.';
Blockly.LANG_LOGIC_COMPARE_TOOLTIP_GT = 'Return true if the first input is greater\n' +
'than the second input.';
Blockly.LANG_LOGIC_COMPARE_TOOLTIP_GTE = 'Return true if the first input is greater\n' +
'than or equal to the second input.';
Blockly.LANG_LOGIC_OPERATION_HELPURL = 'http://code.google.com/p/blockly/wiki/And_Or';
Blockly.LANG_LOGIC_OPERATION_AND = '且';
Blockly.LANG_LOGIC_OPERATION_OR = '或';
Blockly.LANG_LOGIC_OPERATION_TOOLTIP_AND = 'Return true if both inputs are true.';
Blockly.LANG_LOGIC_OPERATION_TOOLTIP_OR = 'Return true if either inputs are true.';
Blockly.LANG_LOGIC_NEGATE_HELPURL = 'http://code.google.com/p/blockly/wiki/Not';
Blockly.LANG_LOGIC_NEGATE_INPUT_NOT = '非';
Blockly.LANG_LOGIC_NEGATE_TOOLTIP = 'Returns true if the input is false.\n' +
'Returns false if the input is true.';
Blockly.LANG_LOGIC_BOOLEAN_HELPURL = 'http://code.google.com/p/blockly/wiki/True_False';
Blockly.LANG_LOGIC_BOOLEAN_TRUE = '是';
Blockly.LANG_LOGIC_BOOLEAN_FALSE = '否';
Blockly.LANG_LOGIC_BOOLEAN_TOOLTIP = 'Returns either true or false.';
Blockly.LANG_LOGIC_NULL_HELPURL = 'http://en.wikipedia.org/wiki/Nullable_type';
Blockly.LANG_LOGIC_NULL = '空';
Blockly.LANG_LOGIC_NULL_TOOLTIP = 'Returns null.';
Blockly.LANG_LOGIC_TERNARY_HELPURL = 'http://en.wikipedia.org/wiki/%3F:';
Blockly.LANG_LOGIC_TERNARY_CONDITION = 'test';
Blockly.LANG_LOGIC_TERNARY_IF_TRUE = 'if true';
Blockly.LANG_LOGIC_TERNARY_IF_FALSE = 'if false';
Blockly.LANG_LOGIC_TERNARY_TOOLTIP = 'Check the condition in "test". If the condition is true\n' +
'returns the "if true" value, otherwise returns the "if false" value.';
// Math Blocks.
Blockly.LANG_CATEGORY_MATH = '算數';
Blockly.LANG_MATH_NUMBER_HELPURL = 'http://en.wikipedia.org/wiki/Number';
Blockly.LANG_MATH_NUMBER_TOOLTIP = 'A number.';
Blockly.LANG_MATH_ARITHMETIC_HELPURL = 'http://en.wikipedia.org/wiki/Arithmetic';
Blockly.LANG_MATH_ARITHMETIC_TOOLTIP_ADD = 'Return the sum of the two numbers.';
Blockly.LANG_MATH_ARITHMETIC_TOOLTIP_MINUS = 'Return the difference of the two numbers.';
Blockly.LANG_MATH_ARITHMETIC_TOOLTIP_MULTIPLY = 'Return the product of the two numbers.';
Blockly.LANG_MATH_ARITHMETIC_TOOLTIP_DIVIDE = 'Return the quotient of the two numbers.';
Blockly.LANG_MATH_ARITHMETIC_TOOLTIP_POWER = 'Return the first number raised to\n' +
'the power of the second number.';
Blockly.LANG_MATH_SINGLE_HELPURL = 'http://en.wikipedia.org/wiki/Square_root';
Blockly.LANG_MATH_SINGLE_OP_ROOT = '開根號';
Blockly.LANG_MATH_SINGLE_OP_ABSOLUTE = '絕對值';
Blockly.LANG_MATH_SINGLE_TOOLTIP_ROOT = 'Return the square root of a number.';
Blockly.LANG_MATH_SINGLE_TOOLTIP_ABS = 'Return the absolute value of a number.';
Blockly.LANG_MATH_SINGLE_TOOLTIP_NEG = 'Return the negation of a number.';
Blockly.LANG_MATH_SINGLE_TOOLTIP_LN = 'Return the natural logarithm of a number.';
Blockly.LANG_MATH_SINGLE_TOOLTIP_LOG10 = 'Return the base 10 logarithm of a number.';
Blockly.LANG_MATH_SINGLE_TOOLTIP_EXP = 'Return e to the power of a number.';
Blockly.LANG_MATH_SINGLE_TOOLTIP_POW10 = 'Return 10 to the power of a number.';
Blockly.LANG_MATH_TRIG_HELPURL = 'http://en.wikipedia.org/wiki/Trigonometric_functions';
Blockly.LANG_MATH_TRIG_TOOLTIP_SIN = 'Return the sine of a degree.';
Blockly.LANG_MATH_TRIG_TOOLTIP_COS = 'Return the cosine of a degree.';
Blockly.LANG_MATH_TRIG_TOOLTIP_TAN = 'Return the tangent of a degree.';
Blockly.LANG_MATH_TRIG_TOOLTIP_ASIN = 'Return the arcsine of a number.';
Blockly.LANG_MATH_TRIG_TOOLTIP_ACOS = 'Return the arccosine of a number.';
Blockly.LANG_MATH_TRIG_TOOLTIP_ATAN = 'Return the arctangent of a number.';
Blockly.LANG_MATH_CONSTANT_HELPURL = 'http://en.wikipedia.org/wiki/Mathematical_constant';
Blockly.LANG_MATH_CONSTANT_TOOLTIP = 'Return one of the common constants: \u03c0 (3.141\u2026), e (2.718\u2026), \u03c6 (1.618\u2026),\n' +
'sqrt(2) (1.414\u2026), sqrt(\u00bd) (0.707\u2026), or \u221e (infinity).';
Blockly.LANG_MATH_IS_EVEN = 'is even';
Blockly.LANG_MATH_IS_ODD = 'is odd';
Blockly.LANG_MATH_IS_PRIME = 'is prime';
Blockly.LANG_MATH_IS_WHOLE = 'is whole';
Blockly.LANG_MATH_IS_POSITIVE = 'is positive';
Blockly.LANG_MATH_IS_NEGATIVE = 'is negative';
Blockly.LANG_MATH_IS_DIVISIBLE_BY = 'is divisible by';
Blockly.LANG_MATH_IS_TOOLTIP = 'Check if a number is an even, odd, prime, whole, positive, negative,\n' +
'or if it is divisible by certain number. Returns true or false.';
Blockly.LANG_MATH_CHANGE_HELPURL = 'http://en.wikipedia.org/wiki/Negation';
Blockly.LANG_MATH_CHANGE_TITLE_CHANGE = '修改';
Blockly.LANG_MATH_CHANGE_TITLE_ITEM = '變量';
Blockly.LANG_MATH_CHANGE_INPUT_BY = '自';
Blockly.LANG_MATH_CHANGE_TOOLTIP = 'Add a number to variable "%1".';
Blockly.LANG_MATH_ROUND_HELPURL = 'http://en.wikipedia.org/wiki/Rounding';
Blockly.LANG_MATH_ROUND_TOOLTIP = 'Round a number up or down.';
Blockly.LANG_MATH_ROUND_OPERATOR_ROUND = '四捨五入';
Blockly.LANG_MATH_ROUND_OPERATOR_ROUNDUP = '無條件進位';
Blockly.LANG_MATH_ROUND_OPERATOR_ROUNDDOWN = '無條件捨去';
Blockly.LANG_MATH_ONLIST_HELPURL = '';
Blockly.LANG_MATH_ONLIST_INPUT_OFLIST = '自列表';
Blockly.LANG_MATH_ONLIST_OPERATOR_SUM = '總和';
Blockly.LANG_MATH_ONLIST_OPERATOR_MIN = '最小值';
Blockly.LANG_MATH_ONLIST_OPERATOR_MAX = '最大值';
Blockly.LANG_MATH_ONLIST_OPERATOR_AVERAGE = '平均值';
Blockly.LANG_MATH_ONLIST_OPERATOR_MEDIAN = '中位數';
Blockly.LANG_MATH_ONLIST_OPERATOR_MODE = '比較眾數';
Blockly.LANG_MATH_ONLIST_OPERATOR_STD_DEV = '標準差';
Blockly.LANG_MATH_ONLIST_OPERATOR_RANDOM = '隨機抽取';
Blockly.LANG_MATH_ONLIST_TOOLTIP_SUM = 'Return the sum of all the numbers in the list.';
Blockly.LANG_MATH_ONLIST_TOOLTIP_MIN = 'Return the smallest number in the list.';
Blockly.LANG_MATH_ONLIST_TOOLTIP_MAX = 'Return the largest number in the list.';
Blockly.LANG_MATH_ONLIST_TOOLTIP_AVERAGE = 'Return the arithmetic mean of the list.';
Blockly.LANG_MATH_ONLIST_TOOLTIP_MEDIAN = 'Return the median number in the list.';
Blockly.LANG_MATH_ONLIST_TOOLTIP_MODE = 'Return a list of the most common item(s) in the list.';
Blockly.LANG_MATH_ONLIST_TOOLTIP_STD_DEV = 'Return the standard deviation of the list.';
Blockly.LANG_MATH_ONLIST_TOOLTIP_RANDOM = 'Return a random element from the list.';
Blockly.LANG_MATH_MODULO_HELPURL = 'http://en.wikipedia.org/wiki/Modulo_operation';
Blockly.LANG_MATH_MODULO_INPUT_DIVIDEND = '取餘數自';
Blockly.LANG_MATH_MODULO_TOOLTIP = 'Return the remainder of dividing both numbers.';
Blockly.LANG_MATH_CONSTRAIN_HELPURL = 'http://en.wikipedia.org/wiki/Clamping_%28graphics%29';
Blockly.LANG_MATH_CONSTRAIN_INPUT_CONSTRAIN = '限制數字';
Blockly.LANG_MATH_CONSTRAIN_INPUT_LOW = '介於 (低)';
Blockly.LANG_MATH_CONSTRAIN_INPUT_HIGH = '到 (高)';
Blockly.LANG_MATH_CONSTRAIN_TOOLTIP = 'Constrain a number to be between the specified limits (inclusive).';
Blockly.LANG_MATH_RANDOM_INT_HELPURL = 'http://en.wikipedia.org/wiki/Random_number_generation';
Blockly.LANG_MATH_RANDOM_INT_INPUT_FROM = '取隨機整數介於 (低)';
Blockly.LANG_MATH_RANDOM_INT_INPUT_TO = '到 (高)';
Blockly.LANG_MATH_RANDOM_INT_TOOLTIP = 'Return a random integer between the two\n' +
'specified limits, inclusive.';
Blockly.LANG_MATH_RANDOM_FLOAT_HELPURL = 'http://en.wikipedia.org/wiki/Random_number_generation';
Blockly.LANG_MATH_RANDOM_FLOAT_TITLE_RANDOM = '取隨機分數';
Blockly.LANG_MATH_RANDOM_FLOAT_TOOLTIP = 'Return a random fraction between\n' +
'0.0 (inclusive) and 1.0 (exclusive).';
// Text Blocks.
Blockly.LANG_CATEGORY_TEXT = '字串';
Blockly.LANG_TEXT_TEXT_HELPURL = 'http://en.wikipedia.org/wiki/String_(computer_science)';
Blockly.LANG_TEXT_TEXT_TOOLTIP = 'A letter, word, or line of text.';
Blockly.LANG_TEXT_JOIN_HELPURL = '';
Blockly.LANG_TEXT_JOIN_TITLE_CREATEWITH = '建立字串使用';
Blockly.LANG_TEXT_JOIN_TOOLTIP = 'Create a piece of text by joining\n' +
'together any number of items.';
Blockly.LANG_TEXT_CREATE_JOIN_TITLE_JOIN = '加入';
Blockly.LANG_TEXT_CREATE_JOIN_TOOLTIP = 'Add, remove, or reorder sections to reconfigure this text block.';
Blockly.LANG_TEXT_CREATE_JOIN_ITEM_TITLE_ITEM = '字串';
Blockly.LANG_TEXT_CREATE_JOIN_ITEM_TOOLTIP = 'Add an item to the text.';
Blockly.LANG_TEXT_APPEND_HELPURL = 'http://www.liv.ac.uk/HPC/HTMLF90Course/HTMLF90CourseNotesnode91.html';
Blockly.LANG_TEXT_APPEND_TO = '在';
Blockly.LANG_TEXT_APPEND_APPENDTEXT = '後加入文字';
Blockly.LANG_TEXT_APPEND_VARIABLE = '變量';
Blockly.LANG_TEXT_APPEND_TOOLTIP = 'Append some text to variable "%1".';
Blockly.LANG_TEXT_LENGTH_HELPURL = 'http://www.liv.ac.uk/HPC/HTMLF90Course/HTMLF90CourseNotesnode91.html';
Blockly.LANG_TEXT_LENGTH_INPUT_LENGTH = '長度';
Blockly.LANG_TEXT_LENGTH_TOOLTIP = 'Returns number of letters (including spaces)\n' +
'in the provided text.';
Blockly.LANG_TEXT_ISEMPTY_HELPURL = 'http://www.liv.ac.uk/HPC/HTMLF90Course/HTMLF90CourseNotesnode91.html';
Blockly.LANG_TEXT_ISEMPTY_INPUT_ISEMPTY = '為空';
Blockly.LANG_TEXT_ISEMPTY_TOOLTIP = 'Returns true if the provided text is empty.';
Blockly.LANG_TEXT_ENDSTRING_HELPURL = 'http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Farsubex.htm';
Blockly.LANG_TEXT_ENDSTRING_INPUT = '在字串中的字元';
Blockly.LANG_TEXT_ENDSTRING_TOOLTIP = 'Returns specified number of letters at the beginning or end of the text.';
Blockly.LANG_TEXT_ENDSTRING_OPERATOR_FIRST = '第一個';
Blockly.LANG_TEXT_ENDSTRING_OPERATOR_LAST = '最後一個';
Blockly.LANG_TEXT_INDEXOF_HELPURL = 'http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Farsubex.htm';
Blockly.LANG_TEXT_INDEXOF_TITLE_FIND = '尋找';
Blockly.LANG_TEXT_INDEXOF_INPUT_OCCURRENCE = '出現的字串';
Blockly.LANG_TEXT_INDEXOF_INPUT_INTEXT = '在字串';
Blockly.LANG_TEXT_INDEXOF_TOOLTIP = 'Returns the index of the first/last occurrence\n' +
'of first text in the second text.\n' +
'Returns 0 if text is not found.';
Blockly.LANG_TEXT_INDEXOF_OPERATOR_FIRST = '第一個';
Blockly.LANG_TEXT_INDEXOF_OPERATOR_LAST = '最後一個';
Blockly.LANG_TEXT_CHARAT_HELPURL = 'http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Farsubex.htm';
Blockly.LANG_TEXT_CHARAT_GET = 'get';
Blockly.LANG_TEXT_CHARAT_FROM_START = 'letter #';
Blockly.LANG_TEXT_CHARAT_FROM_END = 'letter # from end';
Blockly.LANG_TEXT_CHARAT_FIRST = 'first letter';
Blockly.LANG_TEXT_CHARAT_LAST = 'last letter';
Blockly.LANG_TEXT_CHARAT_RANDOM = 'random letter';
Blockly.LANG_TEXT_CHARAT_INPUT_AT = 'letter at';
Blockly.LANG_TEXT_CHARAT_INPUT_INTEXT = '的字元在字串';
Blockly.LANG_TEXT_CHARAT_TOOLTIP = 'Returns the letter at the specified position.';
Blockly.LANG_TEXT_CHANGECASE_HELPURL = 'http://www.liv.ac.uk/HPC/HTMLF90Course/HTMLF90CourseNotesnode91.html';
Blockly.LANG_TEXT_CHANGECASE_TITLE_TO = '改成';
Blockly.LANG_TEXT_CHANGECASE_TOOLTIP = 'Return a copy of the text in a different case.';
Blockly.LANG_TEXT_CHANGECASE_OPERATOR_UPPERCASE = '轉大寫';
Blockly.LANG_TEXT_CHANGECASE_OPERATOR_LOWERCASE = '轉小寫';
Blockly.LANG_TEXT_CHANGECASE_OPERATOR_TITLECASE = '頭字母大寫';
Blockly.LANG_TEXT_TRIM_HELPURL = 'http://www.liv.ac.uk/HPC/HTMLF90Course/HTMLF90CourseNotesnode91.html';
Blockly.LANG_TEXT_TRIM_TITLE_SPACE = '從';
Blockly.LANG_TEXT_TRIM_TITLE_SIDES = '消除空格';
Blockly.LANG_TEXT_TRIM_TOOLTIP = 'Return a copy of the text with spaces\n' +
'removed from one or both ends.';
Blockly.LANG_TEXT_TRIM_TITLE_SIDES = '消除空格';
Blockly.LANG_TEXT_TRIM_TITLE_SIDE = '消除空格';
Blockly.LANG_TEXT_TRIM_OPERATOR_BOTH = '兩側';
Blockly.LANG_TEXT_TRIM_OPERATOR_LEFT = '左側';
Blockly.LANG_TEXT_TRIM_OPERATOR_RIGHT = '右側';
Blockly.LANG_TEXT_PRINT_HELPURL = 'http://www.liv.ac.uk/HPC/HTMLF90Course/HTMLF90CourseNotesnode91.html';
Blockly.LANG_TEXT_PRINT_TITLE_PRINT = '印出';
Blockly.LANG_TEXT_PRINT_TOOLTIP = 'Print the specified text, number or other value.';
Blockly.LANG_TEXT_PROMPT_HELPURL = 'http://www.liv.ac.uk/HPC/HTMLF90Course/HTMLF90CourseNotesnode92.html';
Blockly.LANG_TEXT_PROMPT_TITLE_PROMPT_FOR = '輸入';
Blockly.LANG_TEXT_PROMPT_TITILE_WITH_MESSAGE = '並顯示提示訊息';
Blockly.LANG_TEXT_PROMPT_TOOLTIP = 'Prompt for user input with the specified text.';
Blockly.LANG_TEXT_PROMPT_TYPE_TEXT = '文字';
Blockly.LANG_TEXT_PROMPT_TYPE_NUMBER = '數字';
// Lists Blocks.
Blockly.LANG_CATEGORY_LISTS = '列表';
Blockly.LANG_LISTS_CREATE_EMPTY_HELPURL = 'http://en.wikipedia.org/wiki/Linked_list#Empty_lists';
Blockly.LANG_LISTS_CREATE_EMPTY_TITLE = '建立空列表';
Blockly.LANG_LISTS_CREATE_EMPTY_TOOLTIP = 'Returns a list, of length 0, containing no data records';
Blockly.LANG_LISTS_CREATE_WITH_INPUT_WITH = '使用這些值建立列表';
Blockly.LANG_LISTS_CREATE_WITH_TOOLTIP = 'Create a list with any number of items.';
Blockly.LANG_LISTS_CREATE_WITH_CONTAINER_TITLE_ADD = '加入';
Blockly.LANG_LISTS_CREATE_WITH_CONTAINER_TOOLTIP = 'Add, remove, or reorder sections to reconfigure this list block.';
Blockly.LANG_LISTS_CREATE_WITH_ITEM_TITLE = '項目';
Blockly.LANG_LISTS_CREATE_WITH_ITEM_TOOLTIP = 'Add an item to the list.';
Blockly.LANG_LISTS_REPEAT_HELPURL = 'http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Farsubex.htm';
Blockly.LANG_LISTS_REPEAT_INPUT_WITH = '建立列表使用項目';
Blockly.LANG_LISTS_REPEAT_INPUT_REPEATED = '重複';
Blockly.LANG_LISTS_REPEAT_INPUT_TIMES = '次數';
Blockly.LANG_LISTS_REPEAT_TOOLTIP = 'Creates a list consisting of the given value\n' +
'repeated the specified number of times.';
Blockly.LANG_LISTS_LENGTH_HELPURL = 'http://www.liv.ac.uk/HPC/HTMLF90Course/HTMLF90CourseNotesnode91.html';
Blockly.LANG_LISTS_LENGTH_INPUT_LENGTH = '長度';
Blockly.LANG_LISTS_LENGTH_TOOLTIP = 'Returns the length of a list.';
Blockly.LANG_LISTS_IS_EMPTY_HELPURL = 'http://www.liv.ac.uk/HPC/HTMLF90Course/HTMLF90CourseNotesnode91.html';
Blockly.LANG_LISTS_INPUT_IS_EMPTY = '值為空';
Blockly.LANG_LISTS_TOOLTIP = 'Returns true if the list is empty.';
Blockly.LANG_LISTS_INDEX_OF_HELPURL = 'http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Farsubex.htm';
Blockly.LANG_LISTS_INDEX_OF_TITLE_FIND = '找出';
Blockly.LANG_LISTS_INDEX_OF_INPUT_OCCURRENCE = '項目出現';
Blockly.LANG_LISTS_INDEX_OF_INPUT_IN_LIST = '在列表';
Blockly.LANG_LISTS_INDEX_OF_TOOLTIP = 'Returns the index of the first/last occurrence\n' +
'of the item in the list.\n' +
'Returns 0 if text is not found.';
Blockly.LANG_LISTS_INDEX_OF_FIRST = '第一個';
Blockly.LANG_LISTS_INDEX_OF_LAST = '最後一個';
Blockly.LANG_LISTS_GET_INDEX_HELPURL = 'http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Farsubex.htm';
Blockly.LANG_LISTS_GET_INDEX_GET = 'get';
Blockly.LANG_LISTS_GET_INDEX_GET_REMOVE = 'get and remove';
Blockly.LANG_LISTS_GET_INDEX_REMOVE = 'remove';
Blockly.LANG_LISTS_GET_INDEX_FROM_START = '#';
Blockly.LANG_LISTS_GET_INDEX_FROM_END = '# from end';
Blockly.LANG_LISTS_GET_INDEX_FIRST = 'first';
Blockly.LANG_LISTS_GET_INDEX_LAST = 'last';
Blockly.LANG_LISTS_GET_INDEX_RANDOM = 'random';
Blockly.LANG_LISTS_GET_INDEX_INPUT_IN_LIST = 'in list';
Blockly.LANG_LISTS_GET_INDEX_TOOLTIP_GET_FROM_START = 'Returns the item at the specified position in a list.\n' +
'#1 is the first item.';
Blockly.LANG_LISTS_GET_INDEX_TOOLTIP_GET_FROM_END = 'Returns the item at the specified position in a list.\n' +
'#1 is the last item.';
Blockly.LANG_LISTS_GET_INDEX_TOOLTIP_GET_FIRST = 'Returns the first item in a list.';
Blockly.LANG_LISTS_GET_INDEX_TOOLTIP_GET_LAST = 'Returns the last item in a list.';
Blockly.LANG_LISTS_GET_INDEX_TOOLTIP_GET_RANDOM = 'Returns a random item in a list.';
Blockly.LANG_LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_START = 'Removes and returns the item at the specified position\n' +
' in a list. #1 is the first item.';
Blockly.LANG_LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_END = 'Removes and returns the item at the specified position\n' +
' in a list. #1 is the last item.';
Blockly.LANG_LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST = 'Removes and returns the first item in a list.';
Blockly.LANG_LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST = 'Removes and returns the last item in a list.';
Blockly.LANG_LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM = 'Removes and returns a random item in a list.';
Blockly.LANG_LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_START = 'Removes the item at the specified position\n' +
' in a list. #1 is the first item.';
Blockly.LANG_LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_END = 'Removes the item at the specified position\n' +
' in a list. #1 is the last item.';
Blockly.LANG_LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST = 'Removes the first item in a list.';
Blockly.LANG_LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST = 'Removes the last item in a list.';
Blockly.LANG_LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM = 'Removes a random item in a list.';
Blockly.LANG_LISTS_SET_INDEX_HELPURL = 'http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Farsubex.htm';
Blockly.LANG_LISTS_SET_INDEX_INPUT_AT = '設定項目設定項目';
Blockly.LANG_LISTS_SET_INDEX_INPUT_IN_LIST = '從列表';
Blockly.LANG_LISTS_SET_INDEX_INPUT_TO = '為';
Blockly.LANG_LISTS_SET_INDEX_TOOLTIP = 'Sets the value at the specified position in a list.';
// Variables Blocks.
Blockly.LANG_VARIABLES_GET_HELPURL = 'http://en.wikipedia.org/wiki/Variable_(computer_science)';
Blockly.LANG_VARIABLES_GET_TITLE = '取值';
Blockly.LANG_VARIABLES_GET_ITEM = '變量';
Blockly.LANG_VARIABLES_GET_TOOLTIP = 'Returns the value of this variable.';
Blockly.LANG_VARIABLES_SET_HELPURL = 'http://en.wikipedia.org/wiki/Variable_(computer_science)';
Blockly.LANG_VARIABLES_SET_TITLE = '賦值';
Blockly.LANG_VARIABLES_SET_ITEM = '變量';
Blockly.LANG_VARIABLES_SET_TOOLTIP = 'Sets this variable to be equal to the input.';
// Procedures Blocks.
Blockly.LANG_PROCEDURES_DEFNORETURN_HELPURL = 'http://en.wikipedia.org/wiki/Procedure_%28computer_science%29';
Blockly.LANG_PROCEDURES_DEFNORETURN_PROCEDURE = '流程';
Blockly.LANG_PROCEDURES_DEFNORETURN_DO = '執行';
Blockly.LANG_PROCEDURES_DEFNORETURN_TOOLTIP = 'A procedure with no return value.';
Blockly.LANG_PROCEDURES_DEFRETURN_HELPURL = 'http://en.wikipedia.org/wiki/Procedure_%28computer_science%29';
Blockly.LANG_PROCEDURES_DEFRETURN_PROCEDURE = Blockly.LANG_PROCEDURES_DEFNORETURN_PROCEDURE;
Blockly.LANG_PROCEDURES_DEFRETURN_DO = Blockly.LANG_PROCEDURES_DEFNORETURN_DO;
Blockly.LANG_PROCEDURES_DEFRETURN_RETURN = '回傳';
Blockly.LANG_PROCEDURES_DEFRETURN_TOOLTIP = 'A procedure with a return value.';
Blockly.LANG_PROCEDURES_DEF_DUPLICATE_WARNING = 'Warning:\n' +
'This procedure has\n' +
'duplicate parameters.';
Blockly.LANG_PROCEDURES_CALLNORETURN_HELPURL = 'http://en.wikipedia.org/wiki/Procedure_%28computer_science%29';
Blockly.LANG_PROCEDURES_CALLNORETURN_CALL = '呼叫';
Blockly.LANG_PROCEDURES_CALLNORETURN_PROCEDURE = '流程';
Blockly.LANG_PROCEDURES_CALLNORETURN_TOOLTIP = 'Call a procedure with no return value.';
Blockly.LANG_PROCEDURES_CALLRETURN_HELPURL = 'http://en.wikipedia.org/wiki/Procedure_%28computer_science%29';
Blockly.LANG_PROCEDURES_CALLRETURN_CALL = Blockly.LANG_PROCEDURES_CALLNORETURN_CALL;
Blockly.LANG_PROCEDURES_CALLRETURN_PROCEDURE = Blockly.LANG_PROCEDURES_CALLNORETURN_PROCEDURE;
Blockly.LANG_PROCEDURES_CALLRETURN_TOOLTIP = 'Call a procedure with a return value.';
Blockly.LANG_PROCEDURES_MUTATORCONTAINER_TITLE = '參數';
Blockly.LANG_PROCEDURES_MUTATORARG_TITLE = '變量:';
Blockly.LANG_PROCEDURES_HIGHLIGHT_DEF = 'Highlight Procedure';
Blockly.LANG_PROCEDURES_IFRETURN_TOOLTIP = 'If a value is true, then return a value.';
Blockly.LANG_PROCEDURES_IFRETURN_WARNING = 'Warning:\n' +
'This block may only be\n' +
'used within a procedure.';
|
const path = require("path");
const util = require("util");
const fs = require("fs");
const rimraf = require("rimraf");
const vm = require("vm");
const webpack = require("../");
const readdir = util.promisify(fs.readdir);
const writeFile = util.promisify(fs.writeFile);
const utimes = util.promisify(fs.utimes);
const mkdir = util.promisify(fs.mkdir);
describe("Persistent Caching", () => {
const tempPath = path.resolve(__dirname, "js", "persistent-caching");
const outputPath = path.resolve(tempPath, "output");
const cachePath = path.resolve(tempPath, "cache");
const srcPath = path.resolve(tempPath, "src");
const config = {
mode: "none",
context: tempPath,
cache: {
type: "filesystem",
buildDependencies: {
// avoid rechecking build dependencies
// for performance
// this is already covered by another test case
defaultWebpack: []
},
cacheLocation: cachePath
},
target: "node",
output: {
library: { type: "commonjs-module", export: "default" },
path: outputPath
}
};
beforeEach(done => {
rimraf(tempPath, done);
});
const updateSrc = async data => {
const ts = new Date(Date.now() - 10000);
await mkdir(srcPath, { recursive: true });
for (const key of Object.keys(data)) {
const p = path.resolve(srcPath, key);
await writeFile(p, data[key]);
await utimes(p, ts, ts);
}
};
const compile = async (configAdditions = {}) => {
return new Promise((resolve, reject) => {
webpack({ ...config, ...configAdditions }, (err, stats) => {
if (err) return reject(err);
if (stats.hasErrors())
return reject(stats.toString({ preset: "errors-only" }));
resolve(stats);
});
});
};
const execute = () => {
const cache = {};
const require = name => {
if (cache[name]) return cache[name].exports;
if (!name.endsWith(".js")) name += ".js";
const p = path.resolve(outputPath, name);
const source = fs.readFileSync(p, "utf-8");
const context = {};
const fn = vm.runInThisContext(
`(function(require, module, exports) { ${source} })`,
context,
{
filename: p
}
);
const m = { exports: {} };
cache[name] = m;
fn(require, m, m.exports);
return m.exports;
};
return require("./main");
};
it("should merge multiple small files", async () => {
const files = Array.from({ length: 30 }).map((_, i) => `file${i}.js`);
const data = {
"index.js": `
${files.map((f, i) => `import f${i} from "./${f}";`).join("\n")}
export default ${files.map((_, i) => `f${i}`).join(" + ")};
`
};
for (const file of files) {
data[file] = `export default 1;`;
}
await updateSrc(data);
await compile();
expect(execute()).toBe(30);
for (let i = 0; i < 30; i++) {
updateSrc({
[files[i]]: `export default 2;`
});
await compile();
expect(execute()).toBe(31 + i);
}
const cacheFiles = await readdir(cachePath);
expect(cacheFiles.length).toBeLessThan(20);
expect(cacheFiles.length).toBeGreaterThan(10);
}, 60000);
it("should optimize unused content", async () => {
const data = {
"a.js": 'import "react-dom";',
"b.js": 'import "acorn";',
"c.js": 'import "core-js";',
"d.js": 'import "date-fns";',
"e.js": 'import "lodash";'
};
const createEntry = items => {
const entry = {};
for (const item of items.split("")) entry[item] = `./src/${item}.js`;
return entry;
};
await updateSrc(data);
await compile({ entry: createEntry("abcde") });
await compile({ entry: createEntry("abc") });
await compile({ entry: createEntry("cde") });
await compile({ entry: createEntry("acd") });
await compile({ entry: createEntry("bce") });
await compile({ entry: createEntry("abcde") });
const cacheFiles = await readdir(cachePath);
expect(cacheFiles.length).toBeGreaterThan(4);
}, 60000);
it("should allow persistent caching of container related objects", async () => {
const data = {
"index.js":
"export default import('container/src/exposed').then(m => m.default);",
"exposed.js": "import lib from 'lib'; export default 21 + lib;",
"lib.js": "export default 20",
"lib2.js": "export default 21"
};
await updateSrc(data);
const configAdditions = {
plugins: [
new webpack.container.ModuleFederationPlugin({
name: "container",
library: { type: "commonjs-module" },
exposes: ["./src/exposed"],
remotes: {
container: ["./no-container", "./container"]
},
shared: {
lib: {
import: "./src/lib",
shareKey: "lib",
version: "1.2.0",
requiredVersion: "^1.0.0"
},
"./src/lib2": {
shareKey: "lib",
version: "1.2.3"
}
}
})
]
};
await compile(configAdditions);
await expect(execute()).resolves.toBe(42);
await updateSrc({
"exposed.js": "module.exports = { ok: true };"
});
await compile(configAdditions);
await expect(execute()).resolves.toEqual({ ok: true });
}, 60000);
});
|
'use strict';
angular.module('cpZenPlatform')
.filter('inputPrefix', function () {
return function (input, prevValue, prefixValue) {
if (input.indexOf(prefixValue) === 0) {// We don't reapply the prefix
return input;
} else {
if (prevValue && prevValue.indexOf(prefixValue) === 0) { // Avoid modiication of the prefix
return prevValue;
} else { // default behavior, append
return prefixValue + input;
}
}
};
});
|
/**
*
*/
(function (window, angular) {
'use strict';
//TO_DEV *0* : $('#first').val() -> test via $element('#id')
//TO_READ : javascript `atomic` single-thread :
//handles flow via queue (ARRAY)
//TO_MEM (tested):
//CLASS (ES6) static prop< -> same as for FUNCTION
function getUTC(pDt) {
const ret = new Date(pDt);
//? x - y > 0 ?
ret.setMinutes(ret.getMinutes() - ret.getTimezoneOffset());
return ret;
}
function getDaysDiff(pStart, pEnd) {
const ms = 24 * 60 * 60 * 1000;
return (getUTC(pEnd) - getUTC(pStart)) / ms;
}
Object.defineProperty(window, 'XpectXdateDocsNotifications', {
value: function () { }
});
//issue : promise's then has no `this`
//TO_DEV *1* : angular.bind `this`
//workaround : a global-dom-access object
//window.XpectXdateDocsNotifications = function () { };
//retrieve a watchable dom element
//window.XpectXdateDocsNotifications.getFor = function (prmX) {
// try {
// return document.getElementById(prmX + 'Docs');
// } catch (e) { return undefined; }
//};
//this module (within iife) default notifier is a dom element
window.XpectXdateDocsNotifications.getElement = function () {
try {
return document.getElementById('rsqMenuXpectXdateDocs');
} catch (e) { return undefined; }
};
const ReskewBaseIdentifiers = Object.seal({
Xdate: 'xdate',
Xpect: 'xpect',
Xtend: 'xtend',
Xpoint: 'xpoint'
});
function XdateKindDescriptor(prmN) {
const _getQS = function (prmN) {//the relevant POST QueryString
switch (prmN) {
case 'actual': return '&history=HD';
case 'expired': return '&history=HO';
case 'any': return '&history=HE';
default: return '';
}
};
Object.defineProperties(this, {
'name': { value: prmN },
'qs': { value: _getQS(prmN) }
});
}
const XdateKind = Object.seal({
/** principal id-string for `Xdate` */
BASE_ID: ReskewBaseIdentifiers.Xdate,
/** Non-expired only */
Actual: new XdateKindDescriptor('actual'),
/** Expired (historical) only */
Expired: new XdateKindDescriptor('expired'),
/** Any existing db record / document */
Any: new XdateKindDescriptor('any'),
getIsValid: function (prmK) {
if (!prmK) return false;
switch (prmK) {
case XdateKind.Actual:
case XdateKind.Expired:
case XdateKind.Any:
return true;
default: return false;
}
}
});
/** Xdate Documents Service */
function XdateDocuments(prmHttp, prmStoreSvc) {
Object.defineProperties(XdateDocuments, {
'notifier': { value: null, writable: true },
'baseQS': { value: '/db?crud=r&document=xdate' },
'setQeury': { value:
function (prmSvc, prmK, prmAzz, prmEx) {//Svc = StoreSvc
XdateDocuments.query = {
model: XdateKind.BASE_ID,
actuality: prmK ? prmK.qs : undefined,
exchange: prmEx,
asset: prmAzz
};//STATIC property <-> NO THIS @ `post.then`
XdateDocuments.query.string =
XdateDocuments.baseQS
+ (prmK ?
prmK.qs : prmSvc.get(prmSvc.keys.actuality))
+ '&exchange=' +
(prmEx ?
prmEx : prmSvc.get(prmSvc.keys.exchange))
+ '&asset=' +
(prmAzz ?
prmAzz : prmSvc.get(prmSvc.keys.asset));
}
}
});
Object.defineProperties(this, {
'http': { value: prmHttp },
'store': { value: prmStoreSvc },
'postRequest': { value:
function (prmNotif, prmK, prmAzz, prmEx) {
if (XdateDocuments.notifier) return {};
XdateDocuments.notifier = prmNotif;
XdateDocuments.setQeury(
this.store, prmK, prmAzz, prmEx);
this.http
.post(XdateDocuments.query.string)
.then(function (prmRes) {//*******************
//T_READ *1* : why NO `this` @ promise.then ->
//emit = me + up , broadcast = me + down
XdateDocuments.notifier.rsqData = {
query: angular.copy(XdateDocuments.query),
docs: prmRes.data
};//attach prop to dom-elem (as for any js obj)
XdateDocuments.notifier = null;
})
.catch(function (prmE) {
XdateDocuments.notifier.rsqData = {
query: angular.copy(XdateDocuments.query),
error: prmE
};
XdateDocuments.notifier = null;
});
}
}
});
}//XdateDocuments service
function XpectKindDescriptor(prmN) {
const _getQS = function (prmN) {//the relevant POST QueryString
switch (prmN) {
case ReskewBaseIdentifiers.Xpect:
return '&document=xpect&xtend=D';
case ReskewBaseIdentifiers.Xtend:
return '&document=xpect&xtend=O';
case 'any': return '&document=xpect&xtend=E';
default: return '';
}
};
Object.defineProperties(this, {//construct the returned `new`
'name': { value: prmN },
'title': { value: prmN.replace('x', 'X') },
'qs': { value: _getQS(prmN) }
});
}
//TO_MEM *0*
/** This is not a type (`instanceof` requires `function`!) */
const XpectKind = Object.seal({
/** principal id-string for `Xpect` */
BASE_ID: ReskewBaseIdentifiers.Xpect,
/** `Xpect` instances only */
Xpect: new XpectKindDescriptor(ReskewBaseIdentifiers.Xpect),
/** `Xpect`s with extended-features only */
Xtend: new XpectKindDescriptor(ReskewBaseIdentifiers.Xtend),
/** `Xpect` or `Xtent` instances */
Any: new XpectKindDescriptor('any'),
getIsValid: function (prmK) {
if (!prmK) return false;
switch (prmK) {
case XpectKind.Xpect:
case XpectKind.Xtend:
return true;
default: return false;
}
}
});
/** Xpect Documents Service */
function XpectDocuments(prmHttp, prmStoreSvc) {
Object.defineProperties(XpectDocuments, {
'notifier': { value: null, writable: true },
'baseQS': { value: '/db?crud=r' },
'setQeury': { value:
function (prmSvc, prmK, prmAzz, prmEx) {//Svc = StoreSvc
XpectDocuments.query = {
model: XpectKind.BASE_ID,
kind: prmK,
exchange: prmEx,
asset: prmAzz
};//STATIC property <-> NO THIS @ `post.then`
XpectDocuments.query.string =
XpectDocuments.baseQS
+ '&login=' + prmSvc.get(prmSvc.keys.login)
+ (prmK ?
prmK.qs : XpectKind.Any.qs)
+ '&exchange=' +
(prmEx ?
prmEx : prmSvc.get(prmSvc.keys.exchange))
+ '&asset=' +
(prmAzz ?
prmAzz : prmSvc.get(prmSvc.keys.asset));
}
}
});
Object.defineProperties(this, {
'http': { value: prmHttp },
'store': { value: prmStoreSvc },
/** Post http query */
'postRequest': { value:
function (prmNotif, prmKind, prmAzz, prmEx) {
if (XpectDocuments.notifier) return {};
XpectDocuments.notifier = prmNotif;
XpectDocuments.setQeury(
this.store, prmKind, prmAzz, prmEx);
this.http
.post(XpectDocuments.query.string)
.then(function (prmRes) {
XpectDocuments.notifier.rsqData = {
query: angular.copy(XpectDocuments.query),
docs: prmRes.data
};
XpectDocuments.notifier = null;
})
.catch(function (prmE) {
XpectDocuments.notifier.rsqData = {
query: angular.copy(XpectDocuments.query),
error: prmE
};
XpectDocuments.notifier = null;
});
}
}
});
}//XpectDocuments service
const XpointKind = Object.seal({
/** principal id-string for `Xpoint` */
BASE_ID: ReskewBaseIdentifiers.Xpoint
});
/** Xpoint Documents Service */
function XpointDocuments(prmHttp, prmStoreSvc) {
Object.defineProperties(XpointDocuments, {
'notifier': { value: null, writable: true },
'baseQS': { value: '/db?crud=r&document=xpoint' },
'setQeury': { value:
function (prmSvc, prmEx, prmAzz, prmAct) {
XpointDocuments.query = {
model: XpointKind.BASE_ID,
actuality: prmAct,
exchange: prmEx,
asset: prmAzz
};//STATIC property <-> NO THIS @ `post.then`
XpointDocuments.query.string =
XpointDocuments.baseQS
+ '&login=' + prmSvc.get(prmSvc.keys.login)
+ (prmAct ?
prmAct : prmSvc.get(prmSvc.keys.actuality))
+ '&exchange=' +
(prmEx ?
prmEx : prmSvc.get(prmSvc.keys.exchange))
+ '&asset=' +
(prmAzz ?
prmAzz : prmSvc.get(prmSvc.keys.asset));
}
}
});//angular svc <-> 1 instance : static prop definded ONCE!
//
Object.defineProperties(this, {
'http': { value: prmHttp },
'store': { value: prmStoreSvc },
/** Post http query */
'postRequest': { value:
function (prmNotif, prmAct, prmAzz, prmEx) {
//TO_DO *2* : postpone once svc is busy --------
if (XpointDocuments.notifier) return {};// --------
XpointDocuments.notifier = prmNotif;
XpointDocuments.setQeury(
this.store, prmEx, prmAzz, prmAct);
this.http
.post(XpointDocuments.query.string)
.then(function (prmRes) {
XpointDocuments.notifier.rsqData = {
query: angular.copy(XpointDocuments.query),
docs: prmRes.data
};
XpointDocuments.notifier = null;
})
.catch(function (prmE) {
XpointDocuments.notifier.rsqData = {
query: angular.copy(XpointDocuments.query),
error: prmE
};
XpointDocuments.notifier = null;
});
}
}
});
}//XpointDocuments Service
angular.module('reskewMenuXpectXdate', [])
.constant('ReskewBaseIdentifiers', ReskewBaseIdentifiers)
.constant('XdateKind', XdateKind)
.constant('XpectKind', XpectKind)
.constant('XpointKind', XpointKind)
.constant('SelectedClass', 'ul_basic_checked')
.service('xdateDocsService',
['$http', 'domStorageService', XdateDocuments])
.service('xpectDocsService',
['$http', 'domStorageService', XpectDocuments])
.service('xpointDocsService',
['$http', 'domStorageService', XpointDocuments])
.controller('menuXpectXdateController',
['$scope', '$http', '$compile',
'domStorageService', 'xdateDocsService',
'xpectDocsService', 'xpointDocsService',
'ReskewBaseIdentifiers',
function ($scope, $http, $compile,
storeSvc, xdtSvc, xpctSvc, xpntSvc, ID/*short name*/) {
//
// --- 1st ---
this.$onInit = function () {
const _sel = {};
Object.defineProperty(_sel, ID.Xdate, {
value: null,
writable: true
});
Object.defineProperty(_sel, 'kind', {//ReskewBaseIdentifiers
value: null,
writable: true
});
Object.defineProperty(_sel, 'name', {
value: null,
writable: true
});
Object.defineProperty(_sel, 'clear', {
value: null,
writable: true
});
Object.defineProperties($scope, {
'unwatchDataEvents': { value: null, writable: true },
'dataEventsNotifier': {
value: XpectXdateDocsNotifications.getElement()
},
'dataEventsCount': { value: 0, writable: true },
'onData': { value:
function () {
return $scope.dataEventsNotifier.rsqData;
}
},
'model': { value: {}, writable: true },
'selected': { value: Object.seal(_sel) },
'unwatchSelected': { value:
$scope.$watch(
'selected.kind + "|" +\
selected.name + "|" +\
selected.' + ID.Xdate,
function (prmC, prmP) {
if (prmC != prmP) {
if ($scope.selected.kind
&&
$scope.selected[ID.Xdate]) {
if ($scope.specificView)
$scope.specificView.remove();
//
$scope.specificView = $compile(
'<rsq-xpect \
name="selected.name" \
xdate="selected.xdate" \
model="model.xpect[selected.kind][selected.name]" '
+ ($scope.selected.kind == ID.Xpect
? 'points="model.xpoint[selected.xdate][selected.name]">'
: 'xpoint-model="model.xpoint">')
+ '</rsq-xpect>'
)($scope);//.$new(true)
$scope.element.find('div')
.append($scope.specificView);
//console.log(
// 'Menu State : ' + prmC);
}
}
})
},
'onMenuXdate': { value:
/** invoked from child scope via '&' binding.
an invocation <-> actual state change */
function (prmS) {
//console.log('Menu.Xdate : selected ' + prmS);
$scope.selected[ID.Xdate] = prmS;
}
},
'onMenuXpect': { value:
/** invoked from child scope via '&' binding.
an invocation <-> actual state change (guaranteed) */
function (prmK, prmS) {
//console.log('Menu.' + prmK +
// ' : selected ' + prmS);
//A. set unselected as null
const _u = (prmK == ID.Xpect)
? ID.Xtend
: ID.Xpect;
$scope.selected.kind = prmK;
//B. set the selection
$scope.selected.name = prmS;
//C. notify relevant watcher to clear itself
$scope.selected.clear = _u;
}
},
//when `selected` state is valid -> compile view elem
'specificView': { value: null, writable: true },
'onDataWatchRequired': { value:
function () {
//TO_DO *1* : ? should remove existing elemz ?
//? `selected` reset ?
$scope.unwatchDataEvents =
$scope.$watch('onData()',
function (prmC, prmP) {//C[urrent], P[revious]
if (!prmC) return;
//console.log('$digest : onData');
if (!prmC.error) {
//TO_DO *2* : empty data? len = 0?
$scope.model[prmC.query.model] =
prmC.docs;
if (++$scope.dataEventsCount == 3) {
$scope.unwatchDataEvents();
$scope.dataEventsCount = 0;
$scope.element.find('div')
.append(
$compile(
'<rsq-menu-xdate \
model="model.xdate" \
notify="onMenuXdate(prmS)">\
</rsq-menu-xdate><hr>\
<rsq-menu-xpect \
kind="xpect" \
model-ex="model.xpect.xpect" \
model="model.xpect.xpect_namesArr" \
notify="onMenuXpect(prmK, prmS)" \
clear="selected.clear">\
</rsq-menu-xpect><hr>\
<rsq-menu-xpect \
kind="xtend" \
model-ex="model.xpect.xtend" \
model="model.xpect.xtend_namesArr" \
notify="onMenuXpect(prmK, prmS)" \
clear="selected.clear">\
</rsq-menu-xpect>'
)($scope));
}
} else {//post returned error
}
}
);
}
}
});
};//==== init ====
//
$scope.$on('LoginSuccessful', function (prmEvnt, prmDscr) {
$scope.onDataWatchRequired();
xdtSvc.postRequest($scope.dataEventsNotifier);
xpctSvc.postRequest($scope.dataEventsNotifier);
xpntSvc.postRequest($scope.dataEventsNotifier);
});
}
])
.directive('rsqMenuXpectXdate', function () {
//NAMES list container of both `Xpect` and `Xtend`.
//the user clicks on the desireable object
return {
restrict: 'E',
scope: {
},
// --- 2nd ---
link: function ($scope, elem) {//no attrz
Object.defineProperties($scope, {
'element': { value: elem }
});
},
controller: 'menuXpectXdateController',
template:
'<div>\
<input type="hidden" id="rsqMenuXpectXdateDocs"/>\
</div>'
};
});
})(window, window.angular);
|
import * as challengeActions from '../actions/challenge_actions';
import _ from 'lodash';
//TODO: write tests
export default function(state, action) {
if (!state){
state = {
isRetrievingChallenges: false, //TODO: Make this better, we should have one for every player
challenges: []
};
}
switch (action.type) {
case challengeActions.OPEN_CHALLENGE_DIALOG:
return Object.assign({}, state, {isDialogOpen : true});
case challengeActions.CLOSE_CHALLENGE_DIALOG:
return Object.assign({}, state, {isDialogOpen : false});
case challengeActions.REQUEST_CHALLENGE_PLAYER:
return Object.assign({}, state, {isRetrievingChallenges : true});
case challengeActions.RECEIVE_CHALLENGE_PLAYER:
return Object.assign({}, state, receiveChallengePlayer(state, action));
case challengeActions.REQUEST_CHALLENGES:
return Object.assign({}, state, requestChallenges(action));
case challengeActions.RECEIVE_CHALLENGES:
return Object.assign({}, state, receiveChallenges(action));
case challengeActions.REQUEST_CHALLENGE_ACCEPT :
return Object.assign({}, state, {}); //TODO: Do something?
case challengeActions.RECEIVE_CHALLENGE_ACCEPT :
return Object.assign({}, state, updateChallengeStatus(state, action.challengeId, 'ACCEPT')); //TODO: Make this actually update the status of the challenge in memory?
case challengeActions.REQUEST_CHALLENGE_DECLINE :
return Object.assign({}, state, {}); //TODO: Do something?
case challengeActions.RECEIVE_CHALLENGE_DECLINE :
return Object.assign({}, state, updateChallengeStatus(state, action.challengeId, 'DECLINE')); //TODO: Make this actually update the status of the challenge in memory?
case challengeActions.REQUEST_CHALLENGE_COMPLETE:
return Object.assign({}, state, {}); //TODO: Do something?
case challengeActions.RECEIVE_CHALLENGE_COMPLETE:
return Object.assign({}, state, updateChallengeStatus(state, action.challengeId, 'COMPLETE')); //TODO: Make this actually update the status of the challenge in memory?
}
return state;
}
function receiveChallengePlayer(state, action){
if (!action.challenge)
return {isRetrievingChallenges: false};
var newChallenges;
if (Array.isArray(state.challenges)){
newChallenges = state.challenges;
}
else {
newChallenges = [];
}
newChallenges = _.unionWith(newChallenges, [action.challenge], (x,y) => x.Id === y.Id);
return {
challenges: newChallenges,
isRetrievingChallenges: false
}
}
function requestChallenges(action){
return {
isRetrievingChallenges : true
}
}
function receiveChallenges(action){
return {
isRetrievingChallenges: false,
challenges: action.challenges ? action.challenges : []
}
}
//This is bad and inefficient...probably
function updateChallengeStatus(state, challengeId, status){
if (!challengeId || !status){
return {}; //Don't change anything
}
var challengeToUpdate = state.challenges.find((x) => x.Id === challengeId);
if (!challengeToUpdate){
return;
}
challengeToUpdate = Object.assign({}, challengeToUpdate, {}); //TODO: This is WRONG! We need to know WHO'S state we are updating!!!!
return{
challenges : _.unionWith(state.challenges, [challengeToUpdate], (x,y) => x.Id === y.Id)
};
}
|
// Copyright (c) 2013-2014 Turbulenz Limited
;
var CascadedShadowOccluder = (function () {
function CascadedShadowOccluder(drawParameters, rendererInfo) {
this.drawParameters = drawParameters;
this.rendererInfo = rendererInfo;
}
CascadedShadowOccluder.prototype.clear = function () {
this.drawParameters = null;
this.rendererInfo = null;
};
return CascadedShadowOccluder;
})();
;
var CascadedShadowSplit = (function () {
function CascadedShadowSplit(md, x, y) {
this.viewportX = x;
this.viewportY = y;
/* tslint:disable:no-duplicate-variable */
var camera = Camera.create(md);
camera.parallel = true;
camera.aspectRatio = 1;
camera.viewOffsetX = 0;
camera.viewOffsetY = 0;
this.camera = camera;
/* tslint:enable:no-duplicate-variable */
this.origin = md.v3BuildZero();
this.at = md.v3BuildZero();
this.viewWindowX = 0;
this.viewWindowY = 0;
this.minLightDistance = 0;
this.maxLightDistance = 0;
this.minLightDistanceX = 0;
this.maxLightDistanceX = 0;
this.minLightDistanceY = 0;
this.maxLightDistanceY = 0;
this.lightViewWindowX = 0;
this.lightViewWindowY = 0;
this.lightDepth = 0;
this.shadowDepthScale = 0;
this.shadowDepthOffset = 0;
this.staticNodesChangeCounter = -1;
this.numOverlappingRenderables = -1;
this.numStaticOverlappingRenderables = -1;
this.needsRedraw = false;
this.needsBlur = false;
this.overlappingRenderables = [];
this.overlappingExtents = [];
this.numOccluders = 0;
this.occluders = [];
this.occludersToDraw = [];
this.viewShadowProjection = md.m34BuildIdentity();
this.shadowOffset = md.v2BuildZero();
this.frustumPoints = [];
return this;
}
CascadedShadowSplit.prototype.setAsDummy = function () {
var m = this.viewShadowProjection;
m[0] = 0.0;
m[1] = 0.0;
m[2] = 0.0;
m[3] = 1.0;
m[4] = 0.0;
m[5] = 0.0;
m[6] = 0.0;
m[7] = 1.0;
m[8] = 0.0;
m[9] = 0.0;
m[10] = 0.0;
m[11] = 1.0;
var v = this.shadowOffset;
v[0] = 0.0;
v[1] = 0.0;
};
return CascadedShadowSplit;
})();
;
var CascadedShadowMapping = (function () {
function CascadedShadowMapping(gd, md, shaderManager, size, blurDisabled) {
shaderManager.load("shaders/cascadedshadows.cgfx");
this.gd = gd;
this.md = md;
this.clearColor = md.v4Build(1, 1, 1, 0);
this.tempMatrix44 = md.m44BuildIdentity();
this.tempMatrix43 = md.m43BuildIdentity();
this.tempMatrix33 = md.m33BuildIdentity();
this.tempV3Direction = md.v3BuildZero();
this.tempV3Right = md.v3BuildZero();
this.tempV3Up = md.v3BuildZero();
this.tempV3At = md.v3BuildZero();
this.tempV3Origin = md.v3BuildZero();
this.tempV3AxisX = md.v3BuildZero();
this.tempV3AxisY = md.v3BuildZero();
this.tempV3AxisZ = md.v3BuildZero();
this.tempV3Cross1 = md.v3BuildZero();
this.tempV3Cross2 = md.v3BuildZero();
this.tempV3Cross3 = md.v3BuildZero();
this.tempV3Int = md.v3BuildZero();
this.techniqueParameters = gd.createTechniqueParameters({
shadowSize: 0.0,
invShadowSize: 0.0,
shadowMapTexture: null,
viewShadowProjection0: null,
shadowOffset0: null,
viewShadowProjection1: null,
shadowOffset1: null,
viewShadowProjection2: null,
shadowOffset2: null,
viewShadowProjection3: null,
shadowOffset3: null
});
this.quadPrimitive = gd.PRIMITIVE_TRIANGLE_STRIP;
this.quadSemantics = gd.createSemantics(['POSITION', 'TEXCOORD0']);
this.quadVertexBuffer = gd.createVertexBuffer({
numVertices: 4,
attributes: ['FLOAT2', 'FLOAT2'],
dynamic: false,
data: [
-1.0, 1.0, 0.0, 1.0,
1.0, 1.0, 1.0, 1.0,
-1.0, -1.0, 0.0, 0.0,
1.0, -1.0, 1.0, 0.0
]
});
this.uvScaleOffset = md.v4BuildZero();
this.pixelOffsetH = [0, 0];
this.pixelOffsetV = [0, 0];
this.bufferWidth = 0;
this.bufferHeight = 0;
this.globalTechniqueParameters = gd.createTechniqueParameters();
this.globalTechniqueParametersArray = [this.globalTechniqueParameters];
this.shader = null;
/* tslint:disable:no-bitwise */
var splitSize = (size >>> 1);
/* tslint:enable:no-bitwise */
this.splits = [
new CascadedShadowSplit(md, 0, 0),
new CascadedShadowSplit(md, splitSize, 0),
new CascadedShadowSplit(md, 0, splitSize),
new CascadedShadowSplit(md, splitSize, splitSize)];
this.dummySplit = new CascadedShadowSplit(md, 0, 0);
this.dummySplit.setAsDummy();
this.numSplitsToRedraw = 0;
var precision = gd.maxSupported("FRAGMENT_SHADER_PRECISION");
if (blurDisabled || (precision && precision < 16)) {
this.blurEnabled = false;
} else {
this.blurEnabled = true;
}
this.updateBuffers(size);
var camera = Camera.create(md);
camera.parallel = true;
camera.aspectRatio = 1;
camera.viewOffsetX = 0;
camera.viewOffsetY = 0;
this.sideCamera = camera;
this.sideCameraNearPlane = md.v4BuildZero();
this.numMainFrustumSidePlanes = 0;
this.numMainFrustumPlanes = 0;
this.mainFrustumNearPlaneIndex = -1;
this.mainFrustumPlanes = [
new Float32Array(4),
new Float32Array(4),
new Float32Array(4),
new Float32Array(4),
new Float32Array(4),
new Float32Array(4),
new Float32Array(4)
];
this.numSplitFrustumPlanes = 0;
this.splitFrustumPlanes = [];
this.intersectingPlanes = [];
this.farFrustumPoints = [];
this.tempFrustumPoints = [];
this.clampedFrustumPoints = [];
this.visibleNodes = [];
this.numOccludees = 0;
this.occludeesExtents = [];
this.occludersExtents = [];
/* tslint:disable:no-string-literal */
this.update = function _cascadedShadowsUpdateFn() {
var node = this.node;
while (!node.local && node.parent) {
node = node.parent;
}
this.shadowTechniqueParameters['world'] = node.world;
};
this.skinnedUpdate = function _cascadedShadowsSkinnedUpdateFn() {
var shadowTechniqueParameters = this.shadowTechniqueParameters;
shadowTechniqueParameters['world'] = this.node.world;
var skinController = this.skinController;
if (skinController) {
shadowTechniqueParameters['skinBones'] = skinController.output;
skinController.update();
}
};
/* tslint:enable:no-string-literal */
return this;
}
// Methods
CascadedShadowMapping.prototype.updateShader = function (sm) {
var shader = sm.get("shaders/cascadedshadows.cgfx");
if (shader !== this.shadowMappingShader) {
this.shader = shader;
this.rigidTechnique = shader.getTechnique("rigid");
this.skinnedTechnique = shader.getTechnique("skinned");
this.blurTechnique = shader.getTechnique("blur");
}
};
CascadedShadowMapping.prototype.destroyBuffers = function () {
if (this.renderTarget) {
this.renderTarget.destroy();
this.renderTarget = null;
}
if (this.texture) {
this.texture.destroy();
this.texture = null;
}
if (this.blurRenderTarget) {
this.blurRenderTarget.destroy();
this.blurRenderTarget = null;
}
if (this.blurTexture) {
this.blurTexture.destroy();
this.blurTexture = null;
}
if (this.depthBuffer) {
this.depthBuffer.destroy();
this.depthBuffer = null;
}
};
CascadedShadowMapping.prototype.updateBuffers = function (size) {
if (this.size === size) {
return true;
}
if (!size) {
size = this.size;
}
/* tslint:disable:no-bitwise */
var splitSize = (size >>> 1);
/* tslint:enable:no-bitwise */
var gd = this.gd;
this.destroyBuffers();
this.depthBuffer = gd.createRenderBuffer({
width: size,
height: size,
format: "D24S8"
});
if (this.blurEnabled) {
this.blurTexture = gd.createTexture({
width: splitSize,
height: splitSize,
format: "R8G8B8A8",
mipmaps: false,
renderable: true
});
}
if (this.depthBuffer && (!this.blurEnabled || this.blurTexture)) {
if (this.blurEnabled) {
this.blurRenderTarget = gd.createRenderTarget({
colorTexture0: this.blurTexture
});
}
if (!this.blurEnabled || this.blurRenderTarget) {
this.texture = gd.createTexture({
width: size,
height: size,
format: "R8G8B8A8",
mipmaps: false,
renderable: true
});
if (this.texture) {
this.renderTarget = gd.createRenderTarget({
colorTexture0: this.texture,
depthBuffer: this.depthBuffer
});
if (this.renderTarget) {
var techniqueParameters = this.techniqueParameters;
/* tslint:disable:no-string-literal */
techniqueParameters['shadowSize'] = size;
techniqueParameters['invShadowSize'] = (1.0 / size);
techniqueParameters['shadowMapTexture'] = this.texture;
/* tslint:enable:no-string-literal */
this.size = size;
return true;
}
}
}
}
this.size = 0;
this.destroyBuffers();
return false;
};
CascadedShadowMapping.prototype._addPoint = function (p, points, numPoints) {
// Only add point if not already present, there are few points so complexity is not an issue
var n;
for (n = 0; n < numPoints; n += 1) {
var op = points[n];
if (p[0] === op[0] && p[1] === op[1] && p[2] === op[2]) {
return numPoints;
}
}
points[numPoints] = this.md.v3Copy(p, points[numPoints]);
return (numPoints + 1);
};
CascadedShadowMapping.prototype._intersect = function (s, e, plane, points, numPoints) {
var sd = ((s[0] * plane[0]) + (s[1] * plane[1]) + (s[2] * plane[2]) - plane[3]);
if (sd >= 0) {
numPoints = this._addPoint(s, points, numPoints);
}
var ed = ((e[0] * plane[0]) + (e[1] * plane[1]) + (e[2] * plane[2]) - plane[3]);
if (ed >= 0) {
numPoints = this._addPoint(e, points, numPoints);
}
if ((sd * ed) < 0) {
var d0 = (e[0] - s[0]);
var d1 = (e[1] - s[1]);
var d2 = (e[2] - s[2]);
var dp = -sd / ((d0 * plane[0]) + (d1 * plane[1]) + (d2 * plane[2]));
d0 *= dp;
d1 *= dp;
d2 *= dp;
points[numPoints] = this.md.v3Build((s[0] + d0), (s[1] + d1), (s[2] + d2), points[numPoints]);
numPoints += 1;
}
return numPoints;
};
CascadedShadowMapping.prototype._intersectEnd = function (x, y, z, e, plane, points, numPoints) {
var sd = ((x * plane[0]) + (y * plane[1]) + (z * plane[2]) - plane[3]);
var ed = ((e[0] * plane[0]) + (e[1] * plane[1]) + (e[2] * plane[2]) - plane[3]);
if ((sd * ed) < 0) {
var d0 = (e[0] - x);
var d1 = (e[1] - y);
var d2 = (e[2] - z);
var dp = -sd / ((d0 * plane[0]) + (d1 * plane[1]) + (d2 * plane[2]));
d0 *= dp;
d1 *= dp;
d2 *= dp;
points[numPoints] = this.md.v3Build((x + d0), (y + d1), (z + d2), points[numPoints]);
} else {
points[numPoints] = this.md.v3Build(e[0], e[1], e[2], points[numPoints]);
}
};
CascadedShadowMapping.prototype._clampFrustumPoints = function (frustumPoints, floorPlane) {
var clampedFrustumPoints = this.clampedFrustumPoints;
var numPoints = 0;
numPoints = this._intersect(frustumPoints[0], frustumPoints[4], floorPlane, clampedFrustumPoints, numPoints);
numPoints = this._intersect(frustumPoints[1], frustumPoints[5], floorPlane, clampedFrustumPoints, numPoints);
numPoints = this._intersect(frustumPoints[2], frustumPoints[6], floorPlane, clampedFrustumPoints, numPoints);
numPoints = this._intersect(frustumPoints[3], frustumPoints[7], floorPlane, clampedFrustumPoints, numPoints);
numPoints = this._intersect(frustumPoints[4], frustumPoints[5], floorPlane, clampedFrustumPoints, numPoints);
numPoints = this._intersect(frustumPoints[5], frustumPoints[6], floorPlane, clampedFrustumPoints, numPoints);
numPoints = this._intersect(frustumPoints[6], frustumPoints[7], floorPlane, clampedFrustumPoints, numPoints);
numPoints = this._intersect(frustumPoints[7], frustumPoints[4], floorPlane, clampedFrustumPoints, numPoints);
return numPoints;
};
CascadedShadowMapping.prototype._clampSideFrustumPoints = function (frustumPoints, floorPlane) {
var clampedFrustumPoints = this.clampedFrustumPoints;
var numPoints = 0;
numPoints = this._intersect(frustumPoints[0], frustumPoints[4], floorPlane, clampedFrustumPoints, numPoints);
numPoints = this._intersect(frustumPoints[1], frustumPoints[5], floorPlane, clampedFrustumPoints, numPoints);
numPoints = this._intersect(frustumPoints[2], frustumPoints[6], floorPlane, clampedFrustumPoints, numPoints);
numPoints = this._intersect(frustumPoints[3], frustumPoints[7], floorPlane, clampedFrustumPoints, numPoints);
numPoints = this._intersect(frustumPoints[0], frustumPoints[1], floorPlane, clampedFrustumPoints, numPoints);
numPoints = this._intersect(frustumPoints[1], frustumPoints[2], floorPlane, clampedFrustumPoints, numPoints);
numPoints = this._intersect(frustumPoints[2], frustumPoints[3], floorPlane, clampedFrustumPoints, numPoints);
numPoints = this._intersect(frustumPoints[3], frustumPoints[0], floorPlane, clampedFrustumPoints, numPoints);
numPoints = this._intersect(frustumPoints[4], frustumPoints[5], floorPlane, clampedFrustumPoints, numPoints);
numPoints = this._intersect(frustumPoints[5], frustumPoints[6], floorPlane, clampedFrustumPoints, numPoints);
numPoints = this._intersect(frustumPoints[6], frustumPoints[7], floorPlane, clampedFrustumPoints, numPoints);
numPoints = this._intersect(frustumPoints[7], frustumPoints[4], floorPlane, clampedFrustumPoints, numPoints);
return numPoints;
};
CascadedShadowMapping.prototype.updateShadowMap = function (lightDirection, camera, scene, maxDistance, floorPlane) {
var md = this.md;
this._extractMainFrustumPlanes(camera, lightDirection, maxDistance, floorPlane);
var cameraMatrix = camera.matrix;
var cameraRight = md.m43Right(cameraMatrix, this.tempV3Right);
var cameraUp = md.m43Up(cameraMatrix, this.tempV3Up);
var cameraAt = md.m43At(cameraMatrix, this.tempV3At);
var direction = md.v3Normalize(lightDirection, this.tempV3Direction);
camera.getFrustumFarPoints(camera.farPlane, this.farFrustumPoints);
camera.getFrustumPoints(maxDistance, camera.nearPlane, this.tempFrustumPoints);
var numClampedFrustumPoints = this._clampFrustumPoints(this.tempFrustumPoints, floorPlane);
var sideCamera = this._updateSideCamera(cameraRight, cameraUp, cameraAt, direction, this.clampedFrustumPoints, numClampedFrustumPoints);
var sideCameraMaxDistance = sideCamera.farPlane;
var up;
if (Math.abs(md.v3Dot(direction, cameraAt)) < Math.abs(md.v3Dot(direction, cameraUp))) {
up = cameraAt;
} else {
up = cameraUp;
}
md.v3Normalize(up, up);
var zaxis = md.v3Neg(direction, this.tempV3AxisZ);
var xaxis = md.v3Cross(up, zaxis, this.tempV3AxisX);
md.v3Normalize(xaxis, xaxis);
var yaxis = md.v3Cross(zaxis, xaxis, this.tempV3AxisY);
var splitDistances = CascadedShadowMapping.splitDistances;
var splits = this.splits;
var numSplits = splits.length;
var splitStart = -sideCamera.nearPlane;
var previousSplitPoints = [];
var n, split, splitEnd;
for (n = 0; n < numSplits; n += 1) {
split = splits[n];
splitEnd = sideCameraMaxDistance * splitDistances[n];
numClampedFrustumPoints = this._getSideCameraFrustumPoints(splitEnd, splitStart, direction, camera, maxDistance, floorPlane);
this._updateSplit(split, xaxis, yaxis, zaxis, cameraMatrix, this.clampedFrustumPoints, numClampedFrustumPoints, previousSplitPoints, scene, maxDistance);
splitStart = splitEnd;
if (0 === split.occludersToDraw.length && (n + 1) < numSplits) {
splitEnd = (splitEnd + (sideCameraMaxDistance * splitDistances[n + 1])) / 2.0;
numClampedFrustumPoints = this._getSideCameraFrustumPoints(splitEnd, splitStart, direction, camera, maxDistance, floorPlane);
this._updateSplit(split, xaxis, yaxis, zaxis, cameraMatrix, this.clampedFrustumPoints, numClampedFrustumPoints, previousSplitPoints, scene, maxDistance);
splitStart = splitEnd;
}
}
var techniqueParameters = this.techniqueParameters;
n = -1;
do {
n += 1;
if (n >= numSplits) {
split = this.dummySplit;
break;
}
split = splits[n];
} while(0 === split.occludersToDraw.length);
/* tslint:disable:no-string-literal */
techniqueParameters['viewShadowProjection0'] = split.viewShadowProjection;
techniqueParameters['shadowOffset0'] = split.shadowOffset;
do {
n += 1;
if (n >= numSplits) {
split = this.dummySplit;
break;
}
split = splits[n];
} while(0 === split.occludersToDraw.length);
/* tslint:disable:no-string-literal */
techniqueParameters['viewShadowProjection1'] = split.viewShadowProjection;
techniqueParameters['shadowOffset1'] = split.shadowOffset;
do {
n += 1;
if (n >= numSplits) {
split = this.dummySplit;
break;
}
split = splits[n];
} while(0 === split.occludersToDraw.length);
/* tslint:disable:no-string-literal */
techniqueParameters['viewShadowProjection2'] = split.viewShadowProjection;
techniqueParameters['shadowOffset2'] = split.shadowOffset;
do {
n += 1;
if (n >= numSplits) {
split = this.dummySplit;
break;
}
split = splits[n];
} while(0 === split.occludersToDraw.length);
/* tslint:disable:no-string-literal */
techniqueParameters['viewShadowProjection3'] = split.viewShadowProjection;
techniqueParameters['shadowOffset3'] = split.shadowOffset;
/* tslint:enable:no-string-literal */
};
CascadedShadowMapping.prototype._planeNormalize = function (a, b, c, d, dst) {
var res = dst;
if (!res) {
res = new Float32Array(4);
}
var lsq = ((a * a) + (b * b) + (c * c));
if (lsq > 0.0) {
var lr = 1.0 / Math.sqrt(lsq);
res[0] = (a * lr);
res[1] = (b * lr);
res[2] = (c * lr);
res[3] = (d * lr);
} else {
res[0] = 0;
res[1] = 0;
res[2] = 0;
res[3] = 0;
}
return res;
};
CascadedShadowMapping.prototype._extractMainFrustumPlanes = function (camera, lightDirection, maxDistance, floorPlane) {
// This is crap...
var oldFarPlane = camera.farPlane;
camera.farPlane = maxDistance;
camera.updateProjectionMatrix();
camera.updateViewProjectionMatrix();
var planeNormalize = this._planeNormalize;
var m = camera.viewProjectionMatrix;
var m0 = m[0];
var m1 = m[1];
var m2 = m[2];
var m3 = m[3];
var m4 = m[4];
var m5 = m[5];
var m6 = m[6];
var m7 = m[7];
var m8 = m[8];
var m9 = m[9];
var m10 = m[10];
var m11 = m[11];
var m12 = m[12];
var m13 = m[13];
var m14 = m[14];
var m15 = m[15];
var planes = this.mainFrustumPlanes;
var numPlanes = 0;
var p;
var d0 = lightDirection[0];
var d1 = lightDirection[1];
var d2 = lightDirection[2];
// Negate 'd' here to avoid doing it on the isVisible functions
p = planeNormalize((m3 + m0), (m7 + m4), (m11 + m8), -(m15 + m12), planes[numPlanes]); // left
if ((d0 * p[0]) + (d1 * p[1]) + (d2 * p[2]) <= 0) {
planes[numPlanes] = p;
numPlanes += 1;
}
p = planeNormalize((m3 - m0), (m7 - m4), (m11 - m8), -(m15 - m12), planes[numPlanes]); // right
if ((d0 * p[0]) + (d1 * p[1]) + (d2 * p[2]) <= 0) {
planes[numPlanes] = p;
numPlanes += 1;
}
p = planeNormalize((m3 - m1), (m7 - m5), (m11 - m9), -(m15 - m13), planes[numPlanes]); // top
if ((d0 * p[0]) + (d1 * p[1]) + (d2 * p[2]) <= 0) {
planes[numPlanes] = p;
numPlanes += 1;
}
p = planeNormalize((m3 + m1), (m7 + m5), (m11 + m9), -(m15 + m13), planes[numPlanes]); // bottom
if ((d0 * p[0]) + (d1 * p[1]) + (d2 * p[2]) <= 0) {
planes[numPlanes] = p;
numPlanes += 1;
}
this.numMainFrustumSidePlanes = numPlanes;
p = planeNormalize((m3 + m2), (m7 + m6), (m11 + m10), -(m15 + m14), planes[numPlanes]); // near
if ((d0 * p[0]) + (d1 * p[1]) + (d2 * p[2]) <= 0) {
this.mainFrustumNearPlaneIndex = numPlanes;
planes[numPlanes] = p;
numPlanes += 1;
} else {
this.mainFrustumNearPlaneIndex = -1;
}
p = planeNormalize((m3 - m2), (m7 - m6), (m11 - m10), -(m15 - m14), planes[numPlanes]); // far
if ((d0 * p[0]) + (d1 * p[1]) + (d2 * p[2]) <= 0) {
planes[numPlanes] = p;
numPlanes += 1;
}
p = planeNormalize(floorPlane[0], floorPlane[1], floorPlane[2], floorPlane[3], planes[numPlanes]); // floor
if ((d0 * p[0]) + (d1 * p[1]) + (d2 * p[2]) <= 0) {
planes[numPlanes] = p;
numPlanes += 1;
}
this.numMainFrustumPlanes = numPlanes;
camera.farPlane = oldFarPlane;
camera.updateProjectionMatrix();
camera.updateViewProjectionMatrix();
};
CascadedShadowMapping.prototype._extractSplitFrustumPlanes = function (camera) {
var planeNormalize = this._planeNormalize;
var m = camera.viewProjectionMatrix;
var m0 = m[0];
var m1 = m[1];
//var m2 = m[2];
var m3 = m[3];
var m4 = m[4];
var m5 = m[5];
//var m6 = m[6];
var m7 = m[7];
var m8 = m[8];
var m9 = m[9];
//var m10 = m[10];
var m11 = m[11];
var m12 = m[12];
var m13 = m[13];
//var m14 = m[14];
var m15 = m[15];
var planes = this.splitFrustumPlanes;
// Negate 'd' here to avoid doing it on the isVisible functions
planes[0] = planeNormalize((m3 + m0), (m7 + m4), (m11 + m8), -(m15 + m12), planes[0]); // left
planes[1] = planeNormalize((m3 - m0), (m7 - m4), (m11 - m8), -(m15 - m12), planes[1]); // right
planes[2] = planeNormalize((m3 - m1), (m7 - m5), (m11 - m9), -(m15 - m13), planes[2]); // top
planes[3] = planeNormalize((m3 + m1), (m7 + m5), (m11 + m9), -(m15 + m13), planes[3]); // bottom
var numMainFrustumPlanes = this.numMainFrustumPlanes;
var mainFrustumPlanes = this.mainFrustumPlanes;
var n;
for (n = 0; n < numMainFrustumPlanes; n += 1) {
planes[4 + n] = mainFrustumPlanes[n];
}
this.numSplitFrustumPlanes = 4 + numMainFrustumPlanes;
planes.length = this.numSplitFrustumPlanes;
return planes;
};
CascadedShadowMapping.prototype._isInsidePlanesAABB = function (extents, planes, numPlanes, overlappingExtents, numOverlappingRenderables) {
var abs = Math.abs;
var n0 = extents[0];
var n1 = extents[1];
var n2 = extents[2];
var p0 = extents[3];
var p1 = extents[4];
var p2 = extents[5];
var n = 0;
do {
var plane = planes[n];
var d0 = plane[0];
var d1 = plane[1];
var d2 = plane[2];
var maxDistance = (d0 * (d0 < 0 ? n0 : p0) + d1 * (d1 < 0 ? n1 : p1) + d2 * (d2 < 0 ? n2 : p2) - plane[3]);
if (maxDistance < 0.001) {
return false;
} else {
// Clamp extents to the part that is inside the plane
if (maxDistance < abs(d0) * (p0 - n0)) {
if (d0 < 0) {
p0 = n0 - (maxDistance / d0);
} else {
n0 = p0 - (maxDistance / d0);
}
}
if (maxDistance < abs(d1) * (p1 - n1)) {
if (d1 < 0) {
p1 = n1 - (maxDistance / d1);
} else {
n1 = p1 - (maxDistance / d1);
}
}
if (maxDistance < abs(d2) * (p2 - n2)) {
if (d2 < 0) {
p2 = n2 - (maxDistance / d2);
} else {
n2 = p2 - (maxDistance / d2);
}
}
}
n += 1;
} while(n < numPlanes);
var res = overlappingExtents[numOverlappingRenderables];
if (!res) {
res = new Float32Array(6);
overlappingExtents[numOverlappingRenderables] = res;
}
res[0] = n0;
res[1] = n1;
res[2] = n2;
res[3] = p0;
res[4] = p1;
res[5] = p2;
return true;
};
CascadedShadowMapping.prototype._filterFullyInsidePlanes = function (extents, planes, intersectingPlanes) {
var n0 = extents[0];
var n1 = extents[1];
var n2 = extents[2];
var p0 = extents[3];
var p1 = extents[4];
var p2 = extents[5];
var numPlanes = planes.length;
var numIntersectingPlanes = 0;
var n = 0;
do {
var plane = planes[n];
var d0 = plane[0];
var d1 = plane[1];
var d2 = plane[2];
if ((d0 * (d0 > 0 ? n0 : p0) + d1 * (d1 > 0 ? n1 : p1) + d2 * (d2 > 0 ? n2 : p2)) < plane[3]) {
intersectingPlanes[numIntersectingPlanes] = plane;
numIntersectingPlanes += 1;
}
n += 1;
} while(n < numPlanes);
return numIntersectingPlanes;
};
CascadedShadowMapping.prototype._v3Cross = function (a, b, dst) {
var a0 = a[0];
var a1 = a[1];
var a2 = a[2];
var b0 = b[0];
var b1 = b[1];
var b2 = b[2];
dst[0] = ((a1 * b2) - (a2 * b1));
dst[1] = ((a2 * b0) - (a0 * b2));
dst[2] = ((a0 * b1) - (a1 * b0));
return dst;
};
CascadedShadowMapping.prototype._findPlanesIntersection = function (plane1, plane2, plane3, dst) {
var md = this.md;
var det = md.m33Determinant(md.m33Build(plane1, plane2, plane3, this.tempMatrix33));
if (det === 0.0) {
return null;
}
var invDet = 1.0 / det;
var _v3Cross = this._v3Cross;
var c23 = _v3Cross(plane2, plane3, this.tempV3Cross1);
var c31 = _v3Cross(plane3, plane1, this.tempV3Cross2);
var c12 = _v3Cross(plane1, plane2, this.tempV3Cross3);
return md.v3Add3(md.v3ScalarMul(c23, (plane1[3] * invDet), c23), md.v3ScalarMul(c31, (plane2[3] * invDet), c31), md.v3ScalarMul(c12, (plane3[3] * invDet), c12), dst);
};
CascadedShadowMapping.prototype._findMaxWindowZ = function (zaxis, planes, currentMaxDistance) {
var maxWindowZ = currentMaxDistance;
var a0 = -zaxis[0];
var a1 = -zaxis[1];
var a2 = -zaxis[2];
// First 4 planes are assumed to be the split ones
// Calculate intersections between then and the main camera ones
var numMainFrustumSidePlanes = this.numMainFrustumSidePlanes;
var mainFrustumNearPlaneIndex = this.mainFrustumNearPlaneIndex;
var tempP = this.tempV3Int;
var p, n, plane, dz;
for (n = 0; n < numMainFrustumSidePlanes; n += 1) {
p = this._findPlanesIntersection(planes[0], planes[2], planes[4 + n], tempP);
if (p) {
if (mainFrustumNearPlaneIndex !== -1) {
plane = planes[4 + mainFrustumNearPlaneIndex];
if (((plane[0] * p[0]) + (plane[1] * p[1]) + (plane[2] * p[2])) < plane[3]) {
continue;
}
}
dz = ((a0 * p[0]) + (a1 * p[1]) + (a2 * p[2]));
if (maxWindowZ < dz) {
maxWindowZ = dz;
}
}
}
for (n = 0; n < numMainFrustumSidePlanes; n += 1) {
p = this._findPlanesIntersection(planes[0], planes[3], planes[4 + n], tempP);
if (p) {
if (mainFrustumNearPlaneIndex !== -1) {
plane = planes[4 + mainFrustumNearPlaneIndex];
if (((plane[0] * p[0]) + (plane[1] * p[1]) + (plane[2] * p[2])) < plane[3]) {
continue;
}
}
dz = ((a0 * p[0]) + (a1 * p[1]) + (a2 * p[2]));
if (maxWindowZ < dz) {
maxWindowZ = dz;
}
}
}
for (n = 0; n < numMainFrustumSidePlanes; n += 1) {
p = this._findPlanesIntersection(planes[1], planes[2], planes[4 + n], tempP);
if (p) {
if (mainFrustumNearPlaneIndex !== -1) {
plane = planes[4 + mainFrustumNearPlaneIndex];
if (((plane[0] * p[0]) + (plane[1] * p[1]) + (plane[2] * p[2])) < plane[3]) {
continue;
}
}
dz = ((a0 * p[0]) + (a1 * p[1]) + (a2 * p[2]));
if (maxWindowZ < dz) {
maxWindowZ = dz;
}
}
}
for (n = 0; n < numMainFrustumSidePlanes; n += 1) {
p = this._findPlanesIntersection(planes[1], planes[3], planes[4 + n], tempP);
if (p) {
if (mainFrustumNearPlaneIndex !== -1) {
plane = planes[4 + mainFrustumNearPlaneIndex];
if (((plane[0] * p[0]) + (plane[1] * p[1]) + (plane[2] * p[2])) < plane[3]) {
continue;
}
}
dz = ((a0 * p[0]) + (a1 * p[1]) + (a2 * p[2]));
if (maxWindowZ < dz) {
maxWindowZ = dz;
}
}
}
return maxWindowZ;
};
CascadedShadowMapping.prototype._updateSideCamera = function (cameraRight, cameraUp, cameraAt, lightDirection, frustumPoints, numFrustumPoints) {
var md = this.md;
var yaxis;
if (Math.abs(md.v3Dot(lightDirection, cameraAt)) < Math.max(Math.abs(md.v3Dot(lightDirection, cameraRight)), Math.abs(md.v3Dot(lightDirection, cameraUp)))) {
yaxis = md.v3Neg(lightDirection, this.tempV3AxisY);
} else {
yaxis = cameraUp;
}
var xaxis = md.v3Cross(yaxis, cameraAt, this.tempV3AxisX);
md.v3Normalize(xaxis, xaxis);
//var yaxis = md.v3Cross(cameraAt, xaxis);
//var zaxis = md.v3Cross(yaxis, xaxis);
var zaxis = md.v3Cross(xaxis, yaxis, this.tempV3AxisZ);
var r0 = -xaxis[0];
var r1 = -xaxis[1];
var r2 = -xaxis[2];
var u0 = -yaxis[0];
var u1 = -yaxis[1];
var u2 = -yaxis[2];
var a0 = -zaxis[0];
var a1 = -zaxis[1];
var a2 = -zaxis[2];
var minWindowX = Number.MAX_VALUE;
var maxWindowX = -Number.MAX_VALUE;
var minWindowY = Number.MAX_VALUE;
var maxWindowY = -Number.MAX_VALUE;
var minWindowZ = Number.MAX_VALUE;
var maxWindowZ = -Number.MAX_VALUE;
var n, p, dx, dy, dz;
for (n = 0; n < numFrustumPoints; n += 1) {
p = frustumPoints[n];
dx = ((r0 * p[0]) + (r1 * p[1]) + (r2 * p[2]));
dy = ((u0 * p[0]) + (u1 * p[1]) + (u2 * p[2]));
dz = ((a0 * p[0]) + (a1 * p[1]) + (a2 * p[2]));
if (minWindowX > dx) {
minWindowX = dx;
}
if (maxWindowX < dx) {
maxWindowX = dx;
}
if (minWindowY > dy) {
minWindowY = dy;
}
if (maxWindowY < dy) {
maxWindowY = dy;
}
if (minWindowZ > dz) {
minWindowZ = dz;
}
if (maxWindowZ < dz) {
maxWindowZ = dz;
}
}
// Calculate origin
var origin = this.tempV3Origin;
var ox = (minWindowX + maxWindowX) / 2.0;
var oy = (minWindowY + maxWindowY) / 2.0;
var oz = minWindowZ;
origin[0] = ox * r0 + oy * u0 + oz * a0;
origin[1] = ox * r1 + oy * u1 + oz * a1;
origin[2] = ox * r2 + oy * u2 + oz * a2;
var lightViewWindowX = (maxWindowX - minWindowX) / 2.0;
var lightViewWindowY = (maxWindowY - minWindowY) / 2.0;
var lightDepth = (maxWindowZ - minWindowZ);
// Prepare camera to get light frustum planes
var camera = this.sideCamera;
camera.matrix = md.m43Build(xaxis, yaxis, zaxis, origin, camera.matrix);
camera.updateViewMatrix();
var distanceScale = (1.0 / (256 * 256 * 256));
camera.nearPlane = (lightDepth * distanceScale);
camera.farPlane = (lightDepth + distanceScale);
camera.recipViewWindowX = 1.0 / lightViewWindowX;
camera.recipViewWindowY = 1.0 / lightViewWindowY;
camera.updateProjectionMatrix();
camera.updateViewProjectionMatrix();
var m = this.sideCamera.viewProjectionMatrix;
var nearPlane = this.sideCameraNearPlane;
this._planeNormalize((m[3] + m[2]), (m[7] + m[6]), (m[11] + m[10]), -(m[15] + m[14]), nearPlane);
return camera;
};
CascadedShadowMapping.prototype._getSideCameraFrustumPoints = function (endDistance, startDistance, lightDirection, mainCamera, maxDistance, floorPlane) {
var farFrustumPoints = this.farFrustumPoints;
var frustumPoints = this.tempFrustumPoints;
var nearPlane = this.sideCameraNearPlane;
var nearDistance = nearPlane[3];
var mainCameraMatrix = mainCamera.matrix;
var ax = -mainCameraMatrix[6];
var ay = -mainCameraMatrix[7];
var az = -mainCameraMatrix[8];
if (Math.abs((ax * lightDirection[0]) + (ay * lightDirection[1]) + (az * lightDirection[2])) > Math.SQRT1_2) {
// Worst case scenario, camera facing the light, change maps to overlapping regions
var sideCameraMaxDistance = this.sideCamera.farPlane;
mainCamera.getFrustumPoints(maxDistance * (endDistance / sideCameraMaxDistance), Math.max(mainCamera.nearPlane, maxDistance * (startDistance / sideCameraMaxDistance)), frustumPoints);
} else {
var x = mainCameraMatrix[9];
var y = mainCameraMatrix[10];
var z = mainCameraMatrix[11];
nearPlane[3] = nearDistance + startDistance;
this._intersectEnd(x, y, z, farFrustumPoints[0], nearPlane, frustumPoints, 0);
this._intersectEnd(x, y, z, farFrustumPoints[1], nearPlane, frustumPoints, 1);
this._intersectEnd(x, y, z, farFrustumPoints[2], nearPlane, frustumPoints, 2);
this._intersectEnd(x, y, z, farFrustumPoints[3], nearPlane, frustumPoints, 3);
nearPlane[3] = nearDistance + endDistance;
this._intersectEnd(x, y, z, farFrustumPoints[0], nearPlane, frustumPoints, 4);
this._intersectEnd(x, y, z, farFrustumPoints[1], nearPlane, frustumPoints, 5);
this._intersectEnd(x, y, z, farFrustumPoints[2], nearPlane, frustumPoints, 6);
this._intersectEnd(x, y, z, farFrustumPoints[3], nearPlane, frustumPoints, 7);
nearPlane[3] = nearDistance;
}
return this._clampSideFrustumPoints(frustumPoints, floorPlane);
};
CascadedShadowMapping.prototype._updateSplit = function (split, xaxis, yaxis, zaxis, mainCameraMatrix, frustumPoints, numFrustumPoints, previousSplitPoints, scene, maxDistance) {
var md = this.md;
// Calculate split window limits
var r0 = -xaxis[0];
var r1 = -xaxis[1];
var r2 = -xaxis[2];
var u0 = -yaxis[0];
var u1 = -yaxis[1];
var u2 = -yaxis[2];
var a0 = -zaxis[0];
var a1 = -zaxis[1];
var a2 = -zaxis[2];
var minWindowX = Number.MAX_VALUE;
var maxWindowX = -Number.MAX_VALUE;
var minWindowY = Number.MAX_VALUE;
var maxWindowY = -Number.MAX_VALUE;
var minWindowZ = Number.MAX_VALUE;
var maxWindowZ = -Number.MAX_VALUE;
var n, p, dx, dy, dz;
for (n = 0; n < numFrustumPoints; n += 1) {
p = frustumPoints[n];
dx = ((r0 * p[0]) + (r1 * p[1]) + (r2 * p[2]));
dy = ((u0 * p[0]) + (u1 * p[1]) + (u2 * p[2]));
dz = ((a0 * p[0]) + (a1 * p[1]) + (a2 * p[2]));
if (minWindowX > dx) {
minWindowX = Math.floor(dx);
}
if (maxWindowX < dx) {
maxWindowX = Math.ceil(dx);
}
if (minWindowY > dy) {
minWindowY = Math.floor(dy);
}
if (maxWindowY < dy) {
maxWindowY = Math.ceil(dy);
}
if (minWindowZ > dz) {
minWindowZ = Math.floor(dz);
}
if (maxWindowZ < dz) {
maxWindowZ = Math.ceil(dz);
}
}
var sceneExtents = scene.extents;
var minSceneWindowZ = ((a0 * (a0 > 0 ? sceneExtents[0] : sceneExtents[3])) + (a1 * (a1 > 0 ? sceneExtents[1] : sceneExtents[4])) + (a2 * (a2 > 0 ? sceneExtents[2] : sceneExtents[5])));
if (minWindowZ > minSceneWindowZ) {
minWindowZ = Math.floor(minSceneWindowZ);
}
if (0 === this.numMainFrustumSidePlanes) {
// Camera almost parallel to the split (worst case)
maxWindowZ = Math.ceil(maxWindowZ + maxDistance);
}
// Calculate origin of split
var origin = this.tempV3Origin;
var ox = (minWindowX + maxWindowX) / 2.0;
var oy = (minWindowY + maxWindowY) / 2.0;
var oz = minWindowZ;
origin[0] = ox * r0 + oy * u0 + oz * a0;
origin[1] = ox * r1 + oy * u1 + oz * a1;
origin[2] = ox * r2 + oy * u2 + oz * a2;
if (a0 < 0) {
origin[0] = Math.ceil(origin[0]);
} else if (a0 > 0) {
origin[0] = Math.floor(origin[0]);
} else {
origin[0] = Math.round(origin[0]);
}
if (a1 < 0) {
origin[1] = Math.ceil(origin[1]);
} else if (a1 > 0) {
origin[1] = Math.floor(origin[1]);
} else {
origin[1] = Math.round(origin[1]);
}
if (a2 < 0) {
origin[2] = Math.ceil(origin[2]);
} else if (a2 > 0) {
origin[2] = Math.floor(origin[2]);
} else {
origin[2] = Math.round(origin[2]);
}
var lightViewWindowX = (maxWindowX - minWindowX) / 2.0;
var lightViewWindowY = (maxWindowY - minWindowY) / 2.0;
var lightDepth = (maxWindowZ - minWindowZ);
// Prepare camera to get split frustum planes
var camera = split.camera;
camera.matrix = md.m43Build(xaxis, yaxis, zaxis, origin, camera.matrix);
camera.updateViewMatrix();
var viewMatrix = camera.viewMatrix;
split.lightViewWindowX = lightViewWindowX;
split.lightViewWindowY = lightViewWindowY;
split.lightDepth = lightDepth;
var distanceScale = (1.0 / (256 * 256 * 256));
camera.nearPlane = (lightDepth * distanceScale);
camera.farPlane = (lightDepth + distanceScale);
camera.recipViewWindowX = 1.0 / lightViewWindowX;
camera.recipViewWindowY = 1.0 / lightViewWindowY;
camera.updateProjectionMatrix();
camera.updateViewProjectionMatrix();
var frustumPlanes = this._extractSplitFrustumPlanes(camera);
if (0 < this.numMainFrustumSidePlanes) {
maxWindowZ = this._findMaxWindowZ(zaxis, frustumPlanes, maxWindowZ);
split.lightDepth = lightDepth = (maxWindowZ - minWindowZ);
camera.farPlane = (lightDepth + distanceScale);
}
var frustumUpdated = this._updateRenderables(split, zaxis, origin, frustumPlanes, scene);
// Now prepare draw array
var overlappingRenderables = split.overlappingRenderables;
var overlappingExtents = split.overlappingExtents;
var occluders = split.occluders;
var numOverlappingRenderables = split.numOverlappingRenderables;
var numStaticOverlappingRenderables = split.numStaticOverlappingRenderables;
if (frustumUpdated || numStaticOverlappingRenderables !== numOverlappingRenderables) {
if (!split.needsRedraw) {
split.needsRedraw = true;
this.numSplitsToRedraw += 1;
}
var occludeesExtents = this.occludeesExtents;
var occludersExtents = this.occludersExtents;
var numOccluders = this._filterOccluders(overlappingRenderables, overlappingExtents, numOverlappingRenderables, occluders, occludeesExtents, occludersExtents, (scene.frameIndex - 1));
numOccluders = this._updateOccludersLimits(split, viewMatrix, occluders, occludersExtents, numOccluders);
split.numOccluders = numOccluders;
if (0 < numOccluders) {
this._updateOccludeesLimits(split, viewMatrix, occludeesExtents);
split.needsBlur = true;
}
} else {
split.needsRedraw = false;
}
// Prepare rendering data
var shadowMapSize = this.size;
// Need padding to avoid culling near objects
var minLightDistance = (split.minLightDistance - distanceScale);
// Need padding to avoid encoding singularity at far plane
var maxLightDistance = (split.maxLightDistance + distanceScale);
var minLightDistanceX = split.minLightDistanceX;
var maxLightDistanceX = split.maxLightDistanceX;
var minLightDistanceY = split.minLightDistanceY;
var maxLightDistanceY = split.maxLightDistanceY;
var numPreviousSplitPoints = previousSplitPoints.length;
if (numPreviousSplitPoints && split.numOccluders) {
// Calculate previous split window compared to current one
var roffset = viewMatrix[9];
var uoffset = viewMatrix[10];
var previousMinWindowX = Number.MAX_VALUE;
var previousMaxWindowX = -Number.MAX_VALUE;
var previousMinWindowY = Number.MAX_VALUE;
var previousMaxWindowY = -Number.MAX_VALUE;
for (n = 0; n < numPreviousSplitPoints; n += 1) {
p = previousSplitPoints[n];
dx = ((r0 * p[0]) + (r1 * p[1]) + (r2 * p[2]) - roffset);
dy = ((u0 * p[0]) + (u1 * p[1]) + (u2 * p[2]) - uoffset);
if (previousMinWindowX > dx) {
previousMinWindowX = dx;
}
if (previousMaxWindowX < dx) {
previousMaxWindowX = dx;
}
if (previousMinWindowY > dy) {
previousMinWindowY = dy;
}
if (previousMaxWindowY < dy) {
previousMaxWindowY = dy;
}
}
if (maxLightDistanceX >= previousMaxWindowX) {
if (minLightDistanceX >= previousMinWindowX) {
if (previousMinWindowY <= minLightDistanceY && maxLightDistanceY <= previousMaxWindowY) {
minLightDistanceX = Math.max(minLightDistanceX, previousMaxWindowX);
}
}
} else {
if (previousMinWindowY <= minLightDistanceY && maxLightDistanceY <= previousMaxWindowY) {
maxLightDistanceX = Math.min(maxLightDistanceX, previousMinWindowX);
}
}
if (maxLightDistanceY >= previousMaxWindowY) {
if (minLightDistanceY >= previousMinWindowY) {
if (previousMinWindowX <= minLightDistanceX && maxLightDistanceX <= previousMaxWindowX) {
minLightDistanceY = Math.max(minLightDistanceY, previousMaxWindowY);
}
}
} else {
if (previousMinWindowX <= minLightDistanceX && maxLightDistanceX <= previousMaxWindowX) {
maxLightDistanceY = Math.min(maxLightDistanceY, previousMinWindowY);
}
}
}
if (minLightDistanceX < -lightViewWindowX) {
minLightDistanceX = -lightViewWindowX;
}
if (maxLightDistanceX > lightViewWindowX) {
maxLightDistanceX = lightViewWindowX;
}
if (minLightDistanceY < -lightViewWindowY) {
minLightDistanceY = -lightViewWindowY;
}
if (maxLightDistanceY > lightViewWindowY) {
maxLightDistanceY = lightViewWindowY;
}
var minimalViewWindowX, minimalViewWindowY;
if (maxLightDistanceX !== -minLightDistanceX || maxLightDistanceY !== -minLightDistanceY) {
// we can adjust the origin
var dX = (minLightDistanceX + maxLightDistanceX) / 2.0;
var dY = (minLightDistanceY + maxLightDistanceY) / 2.0;
origin[0] -= ((xaxis[0] * dX) + (yaxis[0] * dY));
origin[1] -= ((xaxis[1] * dX) + (yaxis[1] * dY));
origin[2] -= ((xaxis[2] * dX) + (yaxis[2] * dY));
camera.matrix = md.m43Build(xaxis, yaxis, zaxis, origin, camera.matrix);
camera.updateViewMatrix();
minimalViewWindowX = (maxLightDistanceX - minLightDistanceX) / 2.0;
minimalViewWindowY = (maxLightDistanceY - minLightDistanceY) / 2.0;
} else {
minimalViewWindowX = Math.max(Math.abs(maxLightDistanceX), Math.abs(minLightDistanceX));
minimalViewWindowY = Math.max(Math.abs(maxLightDistanceY), Math.abs(minLightDistanceY));
}
var borderPadding = ((this.blurEnabled ? 2.0 : 1.0) / shadowMapSize);
minimalViewWindowX += borderPadding * minimalViewWindowX;
if (lightViewWindowX > minimalViewWindowX) {
lightViewWindowX = minimalViewWindowX;
}
minimalViewWindowY += borderPadding * minimalViewWindowY;
if (lightViewWindowY > minimalViewWindowY) {
lightViewWindowY = minimalViewWindowY;
}
if (lightViewWindowX === 0 || lightViewWindowY === 0) {
lightViewWindowX = 0.001;
lightViewWindowY = 0.001;
}
camera.recipViewWindowX = 1.0 / lightViewWindowX;
camera.recipViewWindowY = 1.0 / lightViewWindowY;
if (minLightDistance > camera.nearPlane) {
camera.nearPlane = minLightDistance;
}
if (camera.farPlane > maxLightDistance) {
camera.farPlane = maxLightDistance;
}
camera.updateProjectionMatrix();
camera.updateViewProjectionMatrix();
camera.updateFrustumPlanes();
var occludersToDraw = split.occludersToDraw;
if (minLightDistanceX >= maxLightDistanceX || minLightDistanceY >= maxLightDistanceY) {
if (occludersToDraw.length !== 0) {
split.needsRedraw = true;
}
occludersToDraw.length = 0;
} else if (split.needsRedraw) {
var numOccludersToDraw = this._filterRedundantOccuders(occluders, occludersExtents, occludersToDraw, camera.frustumPlanes, (scene.frameIndex - 1), split.numOccluders);
occludersToDraw.length = numOccludersToDraw;
if (1 < numOccludersToDraw) {
occludersToDraw.sort(this._sortNegative);
}
}
var shadowProjection = camera.viewProjectionMatrix;
var shadowDepthScale = split.shadowDepthScale;
var shadowDepthOffset = (shadowDepthScale ? split.shadowDepthOffset : 1.0);
var viewToShadowProjection = md.m43MulM44(mainCameraMatrix, shadowProjection, this.tempMatrix44);
var viewShadowProjection = split.viewShadowProjection;
viewShadowProjection[0] = viewToShadowProjection[0];
viewShadowProjection[1] = viewToShadowProjection[4];
viewShadowProjection[2] = viewToShadowProjection[8];
viewShadowProjection[3] = viewToShadowProjection[12];
viewShadowProjection[4] = viewToShadowProjection[1];
viewShadowProjection[5] = viewToShadowProjection[5];
viewShadowProjection[6] = viewToShadowProjection[9];
viewShadowProjection[7] = viewToShadowProjection[13];
viewShadowProjection[8] = viewToShadowProjection[2] * shadowDepthScale;
viewShadowProjection[9] = viewToShadowProjection[6] * shadowDepthScale;
viewShadowProjection[10] = viewToShadowProjection[10] * shadowDepthScale;
viewShadowProjection[11] = (viewToShadowProjection[14] * shadowDepthScale) + shadowDepthOffset;
var invSize = (1.0 / this.size);
var shadowOffset = split.shadowOffset;
shadowOffset[0] = (split.viewportX * invSize) + 0.25;
shadowOffset[1] = (split.viewportY * invSize) + 0.25;
if (occludersToDraw.length) {
frustumPoints = camera.getFrustumFarPoints(camera.farPlane, split.frustumPoints);
for (n = 0; n < 4; n += 1) {
previousSplitPoints.push(frustumPoints[n]);
}
}
};
CascadedShadowMapping.prototype._updateRenderables = function (split, zaxis, origin, frustumPlanes, scene) {
var _filterFullyInsidePlanes = this._filterFullyInsidePlanes;
var _isInsidePlanesAABB = this._isInsidePlanesAABB;
var visibleNodes = this.visibleNodes;
var intersectingPlanes = this.intersectingPlanes;
var numIntersectingPlanes;
var previousOrigin = split.origin;
var previousAt = split.at;
var overlappingRenderables = split.overlappingRenderables;
var overlappingExtents = split.overlappingExtents;
var staticNodesChangeCounter = scene.staticNodesChangeCounter;
var numOverlappingRenderables, numVisibleNodes;
var node, renderables, numRenderables, renderable;
var i, n, extents, extentsCopy;
var frustumUpdated = false;
if (previousAt[0] !== zaxis[0] || previousAt[1] !== zaxis[1] || previousAt[2] !== zaxis[2] || previousOrigin[0] !== origin[0] || previousOrigin[1] !== origin[1] || previousOrigin[2] !== origin[2] || split.viewWindowX !== split.lightViewWindowX || split.viewWindowY !== split.lightViewWindowY || split.staticNodesChangeCounter !== staticNodesChangeCounter) {
previousAt[0] = zaxis[0];
previousAt[1] = zaxis[1];
previousAt[2] = zaxis[2];
previousOrigin[0] = origin[0];
previousOrigin[1] = origin[1];
previousOrigin[2] = origin[2];
split.viewWindowX = split.lightViewWindowX;
split.viewWindowY = split.lightViewWindowY;
split.staticNodesChangeCounter = staticNodesChangeCounter;
frustumUpdated = true;
numOverlappingRenderables = 0;
numVisibleNodes = scene.staticSpatialMap.getVisibleNodes(frustumPlanes, visibleNodes, 0);
for (n = 0; n < numVisibleNodes; n += 1) {
node = visibleNodes[n];
renderables = node.renderables;
if (renderables) {
numIntersectingPlanes = _filterFullyInsidePlanes(node.getWorldExtents(), frustumPlanes, intersectingPlanes);
numRenderables = renderables.length;
if (0 < numIntersectingPlanes) {
for (i = 0; i < numRenderables; i += 1) {
renderable = renderables[i];
extents = renderable.getWorldExtents();
if (_isInsidePlanesAABB(extents, intersectingPlanes, numIntersectingPlanes, overlappingExtents, numOverlappingRenderables)) {
overlappingRenderables[numOverlappingRenderables] = renderable;
numOverlappingRenderables += 1;
}
}
} else {
for (i = 0; i < numRenderables; i += 1) {
renderable = renderables[i];
extents = renderable.getWorldExtents();
extentsCopy = overlappingExtents[numOverlappingRenderables];
if (!extentsCopy) {
extentsCopy = new Float32Array(6);
overlappingExtents[numOverlappingRenderables] = extentsCopy;
}
extentsCopy[0] = extents[0];
extentsCopy[1] = extents[1];
extentsCopy[2] = extents[2];
extentsCopy[3] = extents[3];
extentsCopy[4] = extents[4];
extentsCopy[5] = extents[5];
overlappingRenderables[numOverlappingRenderables] = renderable;
numOverlappingRenderables += 1;
}
}
}
}
split.numStaticOverlappingRenderables = numOverlappingRenderables;
} else {
numOverlappingRenderables = split.numStaticOverlappingRenderables;
}
// Query the dynamic renderables
numVisibleNodes = scene.dynamicSpatialMap.getVisibleNodes(frustumPlanes, visibleNodes, 0);
for (n = 0; n < numVisibleNodes; n += 1) {
node = visibleNodes[n];
renderables = node.renderables;
if (renderables) {
numIntersectingPlanes = _filterFullyInsidePlanes(node.getWorldExtents(), frustumPlanes, intersectingPlanes);
numRenderables = renderables.length;
if (0 < numIntersectingPlanes) {
for (i = 0; i < numRenderables; i += 1) {
renderable = renderables[i];
extents = renderable.getWorldExtents();
if (_isInsidePlanesAABB(extents, intersectingPlanes, numIntersectingPlanes, overlappingExtents, numOverlappingRenderables)) {
overlappingRenderables[numOverlappingRenderables] = renderable;
numOverlappingRenderables += 1;
}
}
} else {
for (i = 0; i < numRenderables; i += 1) {
renderable = renderables[i];
extents = renderable.getWorldExtents();
extentsCopy = overlappingExtents[numOverlappingRenderables];
if (!extentsCopy) {
extentsCopy = new Float32Array(6);
overlappingExtents[numOverlappingRenderables] = extentsCopy;
}
extentsCopy[0] = extents[0];
extentsCopy[1] = extents[1];
extentsCopy[2] = extents[2];
extentsCopy[3] = extents[3];
extentsCopy[4] = extents[4];
extentsCopy[5] = extents[5];
overlappingRenderables[numOverlappingRenderables] = renderable;
numOverlappingRenderables += 1;
}
}
}
}
split.numOverlappingRenderables = numOverlappingRenderables;
return frustumUpdated;
};
CascadedShadowMapping.prototype._sortNegative = function (a, b) {
return (a.sortKey - b.sortKey);
};
CascadedShadowMapping.prototype._filterOccluders = function (overlappingRenderables, overlappingExtents, numOverlappingRenderables, occluders, occludeesExtents, occludersExtents, frameIndex) {
var numOccludees = 0;
var numOccluders = 0;
var n, renderable, extents, rendererInfo, shadowMappingUpdate;
var drawParametersArray, numDrawParameters, drawParametersIndex;
for (n = 0; n < numOverlappingRenderables; n += 1) {
renderable = overlappingRenderables[n];
if (!renderable.disabled && !renderable.node.disabled) {
if (renderable.shadowMappingDrawParameters) {
rendererInfo = renderable.rendererInfo;
if (!rendererInfo) {
rendererInfo = renderingCommonCreateRendererInfoFn(renderable);
rendererInfo.shadowMappingFullyVisible = -1;
}
shadowMappingUpdate = rendererInfo.shadowMappingUpdate;
if (shadowMappingUpdate) {
shadowMappingUpdate.call(renderable);
extents = overlappingExtents[n];
drawParametersArray = renderable.shadowMappingDrawParameters;
numDrawParameters = drawParametersArray.length;
for (drawParametersIndex = 0; drawParametersIndex < numDrawParameters; drawParametersIndex += 1) {
var drawParameters = drawParametersArray[drawParametersIndex];
var occluder = occluders[numOccluders];
if (!occluder) {
occluder = new CascadedShadowOccluder(drawParameters, rendererInfo);
occluders[numOccluders] = occluder;
} else {
occluder.drawParameters = drawParameters;
occluder.rendererInfo = rendererInfo;
}
occludersExtents[numOccluders] = extents;
numOccluders += 1;
}
}
}
if (frameIndex === renderable.frameVisible) {
occludeesExtents[numOccludees] = overlappingExtents[n];
numOccludees += 1;
}
}
}
this.numOccludees = numOccludees;
return numOccluders;
};
CascadedShadowMapping.prototype._updateOccludeesLimits = function (split, viewMatrix, occludeesExtents) {
var numOccludees = this.numOccludees;
var r0 = -viewMatrix[0];
var r1 = -viewMatrix[3];
var r2 = -viewMatrix[6];
var roffset = viewMatrix[9];
var u0 = -viewMatrix[1];
var u1 = -viewMatrix[4];
var u2 = -viewMatrix[7];
var uoffset = viewMatrix[10];
var d0 = -viewMatrix[2];
var d1 = -viewMatrix[5];
var d2 = -viewMatrix[8];
var offset = viewMatrix[11];
var maxWindowX = split.lightViewWindowX;
var minWindowX = -maxWindowX;
var maxWindowY = split.lightViewWindowY;
var minWindowY = -maxWindowY;
var maxWindowZ = split.lightDepth;
var minLightDistance = split.maxLightDistance;
var maxLightDistance = split.minLightDistance;
var n, extents, n0, n1, n2, p0, p1, p2, lightDistance;
for (n = 0; n < numOccludees;) {
extents = occludeesExtents[n];
n0 = extents[0];
n1 = extents[1];
n2 = extents[2];
p0 = extents[3];
p1 = extents[4];
p2 = extents[5];
lightDistance = ((r0 * (r0 > 0 ? n0 : p0)) + (r1 * (r1 > 0 ? n1 : p1)) + (r2 * (r2 > 0 ? n2 : p2)) - roffset);
if (lightDistance < maxWindowX) {
lightDistance = ((r0 * (r0 > 0 ? p0 : n0)) + (r1 * (r1 > 0 ? p1 : n1)) + (r2 * (r2 > 0 ? p2 : n2)) - roffset);
if (lightDistance > minWindowX) {
lightDistance = ((u0 * (u0 > 0 ? n0 : p0)) + (u1 * (u1 > 0 ? n1 : p1)) + (u2 * (u2 > 0 ? n2 : p2)) - uoffset);
if (lightDistance < maxWindowY) {
lightDistance = ((u0 * (u0 > 0 ? p0 : n0)) + (u1 * (u1 > 0 ? p1 : n1)) + (u2 * (u2 > 0 ? p2 : n2)) - uoffset);
if (lightDistance > minWindowY) {
lightDistance = ((d0 * (d0 > 0 ? n0 : p0)) + (d1 * (d1 > 0 ? n1 : p1)) + (d2 * (d2 > 0 ? n2 : p2)) - offset);
if (lightDistance < maxWindowZ) {
if (lightDistance < minLightDistance) {
minLightDistance = lightDistance;
}
lightDistance = ((d0 * (d0 > 0 ? p0 : n0)) + (d1 * (d1 > 0 ? p1 : n1)) + (d2 * (d2 > 0 ? p2 : n2)) - offset);
if (maxLightDistance < lightDistance) {
maxLightDistance = lightDistance;
}
n += 1;
continue;
}
}
}
}
}
numOccludees -= 1;
if (n < numOccludees) {
occludeesExtents[n] = occludeesExtents[numOccludees];
} else {
break;
}
}
if (minLightDistance < split.minLightDistance) {
minLightDistance = split.minLightDistance;
}
if (maxLightDistance > split.maxLightDistance) {
maxLightDistance = split.maxLightDistance;
}
debug.assert(-0.01 <= minLightDistance);
minLightDistance = Math.max(0, minLightDistance);
var distanceRange = (maxLightDistance - minLightDistance);
if (0.001 < distanceRange) {
split.shadowDepthScale = 0.5;
split.shadowDepthOffset = 0.5;
} else {
split.shadowDepthScale = 0;
split.shadowDepthOffset = 0;
}
};
CascadedShadowMapping.prototype._updateOccludersLimits = function (split, viewMatrix, occluders, occludersExtents, numOccluders) {
var r0 = -viewMatrix[0];
var r1 = -viewMatrix[3];
var r2 = -viewMatrix[6];
var roffset = viewMatrix[9];
var u0 = -viewMatrix[1];
var u1 = -viewMatrix[4];
var u2 = -viewMatrix[7];
var uoffset = viewMatrix[10];
var d0 = -viewMatrix[2];
var d1 = -viewMatrix[5];
var d2 = -viewMatrix[8];
var offset = viewMatrix[11];
var maxWindowX = split.lightViewWindowX;
var minWindowX = -maxWindowX;
var maxWindowY = split.lightViewWindowY;
var minWindowY = -maxWindowY;
var maxWindowZ = split.lightDepth;
var minLightDistance = Number.MAX_VALUE;
var maxLightDistance = -minLightDistance;
var minLightDistanceX = minLightDistance;
var maxLightDistanceX = -minLightDistance;
var minLightDistanceY = minLightDistance;
var maxLightDistanceY = -minLightDistance;
var n, extents, n0, n1, n2, p0, p1, p2;
var minX, maxX, minY, maxY, minZ, maxZ;
for (n = 0; n < numOccluders;) {
extents = occludersExtents[n];
n0 = extents[0];
n1 = extents[1];
n2 = extents[2];
p0 = extents[3];
p1 = extents[4];
p2 = extents[5];
minX = ((r0 * (r0 > 0 ? n0 : p0)) + (r1 * (r1 > 0 ? n1 : p1)) + (r2 * (r2 > 0 ? n2 : p2)) - roffset);
if (minX < maxWindowX) {
maxX = ((r0 * (r0 > 0 ? p0 : n0)) + (r1 * (r1 > 0 ? p1 : n1)) + (r2 * (r2 > 0 ? p2 : n2)) - roffset);
if (maxX > minWindowX) {
minY = ((u0 * (u0 > 0 ? n0 : p0)) + (u1 * (u1 > 0 ? n1 : p1)) + (u2 * (u2 > 0 ? n2 : p2)) - uoffset);
if (minY < maxWindowY) {
maxY = ((u0 * (u0 > 0 ? p0 : n0)) + (u1 * (u1 > 0 ? p1 : n1)) + (u2 * (u2 > 0 ? p2 : n2)) - uoffset);
if (maxY > minWindowY) {
minZ = ((d0 * (d0 > 0 ? n0 : p0)) + (d1 * (d1 > 0 ? n1 : p1)) + (d2 * (d2 > 0 ? n2 : p2)) - offset);
if (minZ < maxWindowZ) {
maxZ = ((d0 * (d0 > 0 ? p0 : n0)) + (d1 * (d1 > 0 ? p1 : n1)) + (d2 * (d2 > 0 ? p2 : n2)) - offset);
if (minZ < minLightDistance) {
minLightDistance = minZ;
}
if (maxLightDistance < maxZ) {
maxLightDistance = maxZ;
}
if (minX < minLightDistanceX) {
minLightDistanceX = minX;
}
if (maxLightDistanceX < maxX) {
maxLightDistanceX = maxX;
}
if (minY < minLightDistanceY) {
minLightDistanceY = minY;
}
if (maxLightDistanceY < maxY) {
maxLightDistanceY = maxY;
}
n += 1;
continue;
}
}
}
}
}
// if we reach this code is because the occluder is out of bounds
numOccluders -= 1;
if (n < numOccluders) {
occludersExtents[n] = occludersExtents[numOccluders];
var discardedOccluder = occluders[n];
occluders[n] = occluders[numOccluders];
occluders[numOccluders] = discardedOccluder;
discardedOccluder.clear();
} else {
break;
}
}
if (numOccluders === 0) {
return 0;
}
if (maxLightDistance > split.lightDepth) {
maxLightDistance = split.lightDepth;
}
split.minLightDistance = minLightDistance;
split.maxLightDistance = maxLightDistance;
split.minLightDistanceX = minLightDistanceX;
split.maxLightDistanceX = maxLightDistanceX;
split.minLightDistanceY = minLightDistanceY;
split.maxLightDistanceY = maxLightDistanceY;
return numOccluders;
};
// Filter out occluders fully included on previous splits
CascadedShadowMapping.prototype._filterRedundantOccuders = function (occluders, occludersExtents, occludersToDraw, frustumPlanes, frameIndex, numOccluders) {
var numPlanes = frustumPlanes.length;
var numToDraw = 0;
for (var n = 0; n < numOccluders; n += 1) {
var occluder = occluders[n];
var rendererInfo = occluder.rendererInfo;
if (rendererInfo.shadowMappingFullyVisible !== frameIndex) {
var extents = occludersExtents[n];
var n0 = extents[0];
var n1 = extents[1];
var n2 = extents[2];
var p0 = extents[3];
var p1 = extents[4];
var p2 = extents[5];
var i = 0;
do {
var plane = frustumPlanes[i];
var d0 = plane[0];
var d1 = plane[1];
var d2 = plane[2];
var distance = (d0 * (d0 > 0 ? n0 : p0) + d1 * (d1 > 0 ? n1 : p1) + d2 * (d2 > 0 ? n2 : p2) - plane[3]);
if (distance < -0.01) {
break;
}
i += 1;
} while(i < numPlanes);
if (i >= numPlanes) {
rendererInfo.shadowMappingFullyVisible = frameIndex;
}
occludersToDraw[numToDraw] = occluder.drawParameters;
numToDraw += 1;
}
}
return numToDraw;
};
CascadedShadowMapping.prototype.drawShadowMap = function () {
if (this.numSplitsToRedraw === 0) {
return;
}
var globalTechniqueParametersArray = this.globalTechniqueParametersArray;
var gtp = this.globalTechniqueParameters;
var renderTarget = this.renderTarget;
var clearColor = this.clearColor;
var gd = this.gd;
var md = this.md;
/* tslint:disable:no-bitwise */
var splitSize = (this.size >>> 1);
/* tslint:enable:no-bitwise */
var splits = this.splits;
var numSplits = splits.length;
if (!gd.beginRenderTarget(renderTarget)) {
return;
}
if (this.numSplitsToRedraw === numSplits) {
gd.clear(clearColor, 1.0, 0);
}
var n, split, splitCamera, occludersToDraw;
for (n = 0; n < numSplits; n += 1) {
split = splits[n];
if (split.needsRedraw) {
split.needsRedraw = false;
gd.setViewport(split.viewportX, split.viewportY, splitSize, splitSize);
gd.setScissor(split.viewportX, split.viewportY, splitSize, splitSize);
if (this.numSplitsToRedraw !== numSplits) {
gd.clear(clearColor, 1.0, 0);
}
splitCamera = split.camera;
occludersToDraw = split.occludersToDraw;
if (occludersToDraw.length) {
/* tslint:disable:no-string-literal */
gtp['viewProjectionTranspose'] = md.m44Transpose(splitCamera.viewProjectionMatrix, gtp['viewProjectionTranspose']);
/* tslint:enable:no-string-literal */
gd.drawArray(occludersToDraw, globalTechniqueParametersArray, 0);
}
}
}
gd.endRenderTarget();
this.numSplitsToRedraw = 0;
};
CascadedShadowMapping.prototype.blurShadowMap = function () {
if (!this.blurEnabled) {
return;
}
var gd = this.gd;
gd.setStream(this.quadVertexBuffer, this.quadSemantics);
var shadowMappingBlurTechnique = this.blurTechnique;
gd.setTechnique(shadowMappingBlurTechnique);
var quadPrimitive = this.quadPrimitive;
var uvScaleOffset = this.uvScaleOffset;
var pixelOffsetH = this.pixelOffsetH;
var pixelOffsetV = this.pixelOffsetV;
/* tslint:disable:no-bitwise */
var splitSize = (this.size >>> 1);
/* tslint:enable:no-bitwise */
var invSplitSize = (1.0 / splitSize);
var invSize = (1.0 / this.size);
pixelOffsetH[0] = invSize;
pixelOffsetV[1] = invSplitSize;
var blurTexture = this.blurTexture;
var blurRenderTarget = this.blurRenderTarget;
var splits = this.splits;
var numSplits = splits.length;
var n, split;
for (n = 0; n < numSplits; n += 1) {
split = splits[n];
if (split.needsBlur) {
split.needsBlur = false;
// Horizontal
if (!gd.beginRenderTarget(blurRenderTarget)) {
break;
}
uvScaleOffset[1] = uvScaleOffset[0] = (splitSize - 4) * invSize;
uvScaleOffset[2] = (split.viewportX + 2) * invSize;
uvScaleOffset[3] = (split.viewportY + 2) * invSize;
/* tslint:disable:no-string-literal */
shadowMappingBlurTechnique['shadowMap'] = this.texture;
shadowMappingBlurTechnique['uvScaleOffset'] = uvScaleOffset;
shadowMappingBlurTechnique['pixelOffset'] = pixelOffsetH;
/* tslint:enable:no-string-literal */
gd.draw(quadPrimitive, 4);
gd.endRenderTarget();
// Vertical
if (!gd.beginRenderTarget(this.renderTarget)) {
break;
}
// Avoid bluring the edges
gd.setViewport((split.viewportX + 2), (split.viewportY + 2), (splitSize - 4), (splitSize - 4));
gd.setScissor((split.viewportX + 2), (split.viewportY + 2), (splitSize - 4), (splitSize - 4));
uvScaleOffset[0] = 1;
uvScaleOffset[1] = 1;
uvScaleOffset[2] = 0;
uvScaleOffset[3] = 0;
/* tslint:disable:no-string-literal */
shadowMappingBlurTechnique['shadowMap'] = blurTexture;
shadowMappingBlurTechnique['uvScaleOffset'] = uvScaleOffset;
shadowMappingBlurTechnique['pixelOffset'] = pixelOffsetV;
/* tslint:enable:no-string-literal */
gd.draw(quadPrimitive, 4);
gd.endRenderTarget();
}
}
};
CascadedShadowMapping.prototype.destroy = function () {
delete this.shader;
delete this.rigidTechnique;
delete this.skinnedTechnique;
delete this.blurTechnique;
this.destroyBuffers();
delete this.tempV3AxisZ;
delete this.tempV3AxisY;
delete this.tempV3AxisX;
delete this.tempV3At;
delete this.tempV3Up;
delete this.tempV3Right;
delete this.tempV3Direction;
delete this.tempMatrix33;
delete this.tempMatrix43;
delete this.tempMatrix44;
delete this.clearColor;
delete this.quadPrimitive;
delete this.quadSemantics;
if (this.quadVertexBuffer) {
this.quadVertexBuffer.destroy();
delete this.quadVertexBuffer;
}
delete this.splits;
delete this.techniqueParameters;
delete this.globalTechniqueParameters;
delete this.globalTechniqueParametersArray;
delete this.occludersExtents;
delete this.occludeesExtents;
delete this.md;
delete this.gd;
};
// Constructor function
CascadedShadowMapping.create = function (gd, md, shaderManager, size, blurDisabled) {
return new CascadedShadowMapping(gd, md, shaderManager, size, blurDisabled);
};
CascadedShadowMapping.version = 1;
CascadedShadowMapping.splitDistances = [1.0 / 100.0, 4.0 / 100.0, 20.0 / 100.0, 1.0];
return CascadedShadowMapping;
})();
|
var connect = require("connect"),
sweetroll = require("../sweetroll.js");
var app = sweetroll();
app.at("/")
.data(function(req) {
return "test";
})
.render(function(req, data) {
return data + " " + req.url;
});
connect()
.use(app)
.use(function(req, res) {
res.end("There was nothing at your location.");
})
.listen(8080);
|
function sortObject(o) {
var sorted = {},
key, a = [];
for (key in o) {
if (o.hasOwnProperty(key)) {
a.push(key);
}
}
a.sort();
for (key = 0; key < a.length; key++) {
sorted[a[key]] = o[a[key]];
}
return sorted;
};
module.exports = {
sortObject: sortObject
};
|
var crypto = require('crypto'),
ed = require('ed25519'),
shuffle = require('knuth-shuffle').knuthShuffle,
Router = require('../helpers/router.js'),
slots = require('../helpers/slots.js'),
schedule = require('node-schedule'),
util = require('util'),
constants = require('../helpers/constants.js'),
TransactionTypes = require('../helpers/transaction-types.js'),
MilestoneBlocks = require("../helpers/milestoneBlocks.js"),
errorCode = require('../helpers/errorCodes.js').error;
require('array.prototype.find'); //old node fix
//private fields
var modules, library, self, private = {};
private.loaded = false;
private.unconfirmedDelegates = {};
private.unconfirmedNames = {};
private.votes = {};
private.unconfirmedVotes = {};
private.namesIndex = {};
private.publicKeyIndex = {};
private.transactionIdIndex = {};
private.delegates = [];
private.fees = {};
private.keypairs = {};
function Delegate() {
this.create = function (data, trs) {
trs.recipientId = null;
trs.amount = 0;
trs.asset.delegate = {
username: data.username,
publicKey: data.sender.publicKey
};
return trs;
}
this.calculateFee = function (trs) {
if (modules.blocks.getLastBlock().height >= MilestoneBlocks.FEE_BLOCK) {
return 100 * constants.fixedPoint;
} else {
return 10000 * constants.fixedPoint;
}
}
this.verify = function (trs, sender, cb) {
if (trs.recipientId) {
return setImmediate(cb, errorCode("DELEGATES.INVALID_RECIPIENT", trs));
}
if (trs.amount != 0) {
return setImmediate(cb, errorCode("DELEGATES.INVALID_AMOUNT", trs));
}
if (!trs.asset.delegate.username) {
return setImmediate(cb, errorCode("DELEGATES.EMPTY_TRANSACTION_ASSET", trs));
}
var allowSymbols = /^[a-z0-9!@$&_.]+$/g;
if (!allowSymbols.test(trs.asset.delegate.username.toLowerCase())) {
return setImmediate(cb, errorCode("DELEGATES.USERNAME_CHARS", trs));
}
var isAddress = /^[0-9]+c$/g;
if (isAddress.test(trs.asset.delegate.username.toLowerCase())) {
return setImmediate(cb, errorCode("DELEGATES.USERNAME_LIKE_ADDRESS", trs));
}
if (trs.asset.delegate.username.length < 1) {
return setImmediate(cb, errorCode("DELEGATES.USERNAME_IS_TOO_SHORT", trs));
}
if (trs.asset.delegate.username.length > 20) {
return setImmediate(cb, errorCode("DELEGATES.USERNAME_IS_TOO_LONG", trs));
}
if (self.existsName(trs.asset.delegate.username)) {
return setImmediate(cb, errorCode("DELEGATES.EXISTS_USERNAME", trs));
}
if (self.existsDelegate(trs.senderPublicKey)) {
return setImmediate(cb, errorCode("DELEGATES.EXISTS_DELEGATE"));
}
if (modules.accounts.existsUsername(trs.asset.delegate.username) && sender.username != trs.asset.delegate.username) {
return setImmediate(cb, errorCode("DELEGATES.EXISTS_USERNAME", trs));
}
if (sender.username && sender.username != trs.asset.delegate.username) {
return setImmediate(cb, errorCode("DELEGATES.WRONG_USERNAME"));
}
if (sender.unconfirmedUsername && sender.unconfirmedUsername != trs.asset.delegate.username) {
return setImmediate(cb, errorCode("USERNAMES.ALREADY_HAVE_USERNAME", trs));
}
setImmediate(cb, null, trs);
}
this.getBytes = function (trs) {
try {
var buf = new Buffer(trs.asset.delegate.username, 'utf8');
} catch (e) {
throw Error(e.toString());
}
return buf;
}
this.apply = function (trs, sender) {
modules.delegates.removeUnconfirmedDelegate(trs.asset.delegate);
modules.delegates.cache(trs.asset.delegate);
return true;
}
this.undo = function (trs, sender) {
modules.delegates.uncache(trs.asset.delegate);
modules.delegates.addUnconfirmedDelegate(trs.asset.delegate);
return true;
}
this.applyUnconfirmed = function (trs, sender, cb) {
if (self.existsUnconfirmedDelegate(trs.asset.delegate.publicKey)) {
return setImmediate(cb, errorCode("DELEGATES.EXISTS_DELEGATE"));
}
if (self.existsUnconfirmedName(trs.asset.delegate.username)) {
return setImmediate(cb, errorCode("DELEGATES.EXISTS_DELEGATE"));
}
if (modules.accounts.existsUnconfirmedUsername(trs.asset.delegate.username)) {
return setImmediate(cb, errorCode("DELEGATES.EXISTS_DELEGATE"));
}
modules.delegates.addUnconfirmedDelegate(trs.asset.delegate);
setImmediate(cb);
}
this.undoUnconfirmed = function (trs, sender) {
modules.delegates.removeUnconfirmedDelegate(trs.asset.delegate);
return true;
}
this.objectNormalize = function (trs) {
var report = library.scheme.validate(trs.asset.delegate, {
type: "object",
properties: {
username: {
type: "string",
minLength: 1
},
publicKey: {
type: "string",
format: "publicKey"
}
},
required: ["username", "publicKey"]
});
if (!report) {
throw Error("Can't verify delegate transaction, incorrect parameters");
}
return trs;
}
this.dbRead = function (raw) {
if (!raw.d_username) {
return null
} else {
var delegate = {
username: raw.d_username,
publicKey: raw.t_senderPublicKey,
address: raw.t_senderId
}
return {delegate: delegate};
}
}
this.dbSave = function (dbLite, trs, cb) {
dbLite.query("INSERT INTO delegates(username, transactionId) VALUES($username, $transactionId)", {
username: trs.asset.delegate.username,
transactionId: trs.id
}, cb);
}
this.ready = function (trs) {
return true;
}
}
//constructor
function Delegates(cb, scope) {
library = scope;
self = this;
self.__private = private;
attachApi();
library.logic.transaction.attachAssetType(TransactionTypes.DELEGATE, new Delegate());
setImmediate(cb, null, self);
}
//private methods
function attachApi() {
var router = new Router();
router.use(function (req, res, next) {
if (modules && private.loaded) return next();
res.status(500).send({success: false, error: errorCode('COMMON.LOADING')});
});
router.get('/fee', function (req, res) {
var fee = null;
if (modules.blocks.getLastBlock().height >= MilestoneBlocks.FEE_BLOCK) {
fee = 100 * constants.fixedPoint;
} else {
fee = 10000 * constants.fixedPoint;
}
return res.json({success: true, fee: fee})
});
router.get('/', function (req, res, next) {
req.sanitize(req.query, {
type: 'object',
properties: {
limit: {
type: "integer",
minimum: 0,
maximum: 101
},
offset: {
type: "integer",
minimum: 0
},
orderBy: {
type: "string"
},
active: {
type: "boolean"
}
}
}, function (err, report, query) {
if (err) return next(err);
if (!report.isValid) return res.json({success: false, error: report.issues});
if (!query.limit) {
query.limit = 101;
}
if (!query.offset) {
query.offset = 0;
}
var limit = query.limit,
offset = query.offset,
orderField = query.orderBy,
active = query.active;
orderField = orderField ? orderField.split(':') : null;
var orderBy = orderField ? orderField[0] : null;
var sortMode = orderField && orderField.length == 2 ? orderField[1] : 'asc';
var publicKeys = Object.keys(private.publicKeyIndex);
var count = publicKeys.length;
var length = Math.min(limit, count);
var realLimit = Math.min(offset + limit, count);
if (active === true) {
publicKeys = publicKeys.slice(0, 101);
} else if (active === false) {
publicKeys = publicKeys.slice(101, publicKeys.length);
}
var rateSort = {};
private.getKeysSortByVote(publicKeys, private.votes)
.forEach(function (item, index) {
rateSort[item] = index + 1;
});
if (orderBy) {
if (orderBy == 'username') {
publicKeys = publicKeys.sort(function compare(a, b) {
if (sortMode == 'asc') {
if (private.delegates[private.publicKeyIndex[a]][orderBy] < private.delegates[private.publicKeyIndex[b]][orderBy])
return -1;
if (private.delegates[private.publicKeyIndex[a]][orderBy] > private.delegates[private.publicKeyIndex[b]][orderBy])
return 1;
} else if (sortMode == 'desc') {
if (private.delegates[private.publicKeyIndex[a]][orderBy] > private.delegates[private.publicKeyIndex[b]][orderBy])
return -1;
if (private.delegates[private.publicKeyIndex[a]][orderBy] < private.delegates[private.publicKeyIndex[b]][orderBy])
return 1;
}
return 0;
});
}
if (orderBy == 'vote') {
publicKeys = publicKeys.sort(function compare(a, b) {
if (sortMode == 'asc') {
if (private.votes[a] < private.votes[b])
return -1;
if (private.votes[a] > private.votes[b])
return 1;
} else if (sortMode == 'desc') {
if (private.votes[a] > private.votes[b])
return -1;
if (private.votes[a] < private.votes[b])
return 1;
}
return 0;
});
}
if (orderBy == 'rate') {
publicKeys = publicKeys.sort(function compare(a, b) {
if (sortMode == 'asc') {
if (rateSort[a] < rateSort[b])
return -1;
if (rateSort[a] > rateSort[b])
return 1;
} else if (sortMode == 'desc') {
if (rateSort[a] > rateSort[b])
return -1;
if (rateSort[a] < rateSort[b])
return 1;
}
return 0;
});
}
}
publicKeys = publicKeys.slice(offset, realLimit);
var result = publicKeys.map(function (publicKey) {
return private.getDelegate({publicKey: publicKey}, rateSort);
});
res.json({success: true, delegates: result, totalCount: count});
});
});
router.get('/get', function (req, res, next) {
req.sanitize(req.query, {
type: "object",
properties: {
transactionId: {
type: "string"
},
publicKey: {
type: "string"
},
username: {
type: "string"
}
}
}, function (err, report, query) {
if (err) return next(err);
if (!report.isValid) return res.json({success: false, error: report.issues});
var delegate = private.getDelegate(query);
if (delegate) {
res.json({success: true, delegate: delegate});
} else {
res.json({success: false, error: errorCode("DELEGATES.DELEGATE_NOT_FOUND")});
}
});
});
router.get('/forging/getForgedByAccount', function (req, res, next) {
req.sanitize(req.query, {
type: "object",
properties: {
generatorPublicKey: {
type: "string",
format: "publicKey"
}
},
required: ["generatorPublicKey"]
}, function (err, report, query) {
if (err) return next(err);
if (!report.isValid) return res.json({success: false, error: report.issues});
if (private.fees[query.generatorPublicKey] === undefined) {
return res.json({success: true, fees: 0});
}
res.json({success: true, fees: private.fees[query.generatorPublicKey]});
});
});
router.post('/forging/enable', function (req, res, next) {
req.sanitize(req.body, {
type: "object",
properties: {
secret: {
type: "string",
minLength: 1,
maxLength: 100
},
publicKey: {
type: "string",
format: "publicKey"
}
},
required: ["secret"]
}, function (err, report, body) {
if (err) return next(err);
if (!report.isValid) return res.json({success: false, error: report.issues});
var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
if (library.config.forging.access.whiteList.length > 0 && library.config.forging.access.whiteList.indexOf(ip) < 0) {
return res.json({success: false, error: errorCode("COMMON.ACCESS_DENIED")});
}
var keypair = ed.MakeKeypair(crypto.createHash('sha256').update(body.secret, 'utf8').digest());
var address = modules.accounts.getAddressByPublicKey(keypair.publicKey.toString('hex'));
var account = modules.accounts.getAccount(address);
if (body.publicKey) {
if (keypair.publicKey.toString('hex') != body.publicKey) {
return res.json({success: false, error: errorCode("COMMON.INVALID_SECRET_KEY")});
}
}
if (private.keypairs[keypair.publicKey.toString('hex')]) {
return res.json({success: false, error: errorCode("COMMON.FORGING_ALREADY_ENABLED")});
}
if (account && self.existsDelegate(keypair.publicKey.toString('hex'))) {
private.keypairs[keypair.publicKey.toString('hex')] = keypair;
res.json({success: true, address: address});
library.logger.info("Forging enabled on account: " + address);
} else {
res.json({success: false, error: errorCode("DELEGATES.DELEGATE_NOT_FOUND")});
}
});
});
router.post('/forging/disable', function (req, res, next) {
req.sanitize(req.body, {
type: "object",
properties: {
secret: {
type: "string",
minLength: 1,
maxLength: 100
},
publicKey: {
type: "string",
format: "publicKey"
}
},
required: ["secret"]
}, function (err, report, body) {
if (err) return next(err);
if (!report.isValid) return res.json({success: false, error: report.issues});
var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
if (library.config.forging.access.whiteList.length > 0 && library.config.forging.access.whiteList.indexOf(ip) < 0) {
return res.json({success: false, error: errorCode("COMMON.ACCESS_DENIED")});
}
var keypair = ed.MakeKeypair(crypto.createHash('sha256').update(body.secret, 'utf8').digest());
var address = modules.accounts.getAddressByPublicKey(keypair.publicKey.toString('hex'));
var account = modules.accounts.getAccount(address);
if (body.publicKey) {
if (keypair.publicKey.toString('hex') != body.publicKey) {
return res.json({success: false, error: errorCode("COMMON.INVALID_SECRET_KEY")});
}
}
if (!private.keypairs[keypair.publicKey.toString('hex')]) {
return res.json({success: false, error: errorCode("DELEGATES.FORGER_NOT_FOUND")});
}
if (account && self.existsDelegate(keypair.publicKey.toString('hex'))) {
delete private.keypairs[keypair.publicKey.toString('hex')];
res.json({success: true, address: address});
library.logger.info("Forging disabled on account: " + address);
} else {
res.json({success: false});
}
});
});
router.get('/forging/status', function (req, res, next) {
req.sanitize(req.query, {
type: "object",
properties: {
publicKey: {
type: "string",
format: "publicKey"
}
},
required: ["publicKey"]
}, function (err, report, query) {
if (err) return next(err);
if (!report.isValid) return res.json({success: false, error: report.issues});
return res.json({success: true, enabled: !!private.keypairs[query.publicKey]});
});
});
router.put('/', function (req, res, next) {
req.sanitize(req.body, {
type: "object",
properties: {
secret: {
type: "string",
minLength: 1,
maxLength: 100
},
publicKey: {
type: "string",
format: "publicKey"
},
secondSecret: {
type: "string",
minLength: 1,
maxLength: 100
},
username: {
type: "string",
minLength: 1
}
},
required: ["secret"]
}, function (err, report, body) {
if (err) return next(err);
if (!report.isValid) return res.json({success: false, error: report.issues});
var hash = crypto.createHash('sha256').update(body.secret, 'utf8').digest();
var keypair = ed.MakeKeypair(hash);
if (body.publicKey) {
if (keypair.publicKey.toString('hex') != body.publicKey) {
return res.json({success: false, error: errorCode("COMMON.INVALID_SECRET_KEY")});
}
}
var account = modules.accounts.getAccountByPublicKey(keypair.publicKey.toString('hex'));
if (!account || !account.publicKey) {
return res.json({success: false, error: errorCode("COMMON.OPEN_ACCOUNT")});
}
if (account.secondSignature && !body.secondSecret) {
return res.json({success: false, error: errorCode("COMMON.SECOND_SECRET_KEY")});
}
var secondKeypair = null;
if (account.secondSignature) {
var secondHash = crypto.createHash('sha256').update(body.secondSecret, 'utf8').digest();
secondKeypair = ed.MakeKeypair(secondHash);
}
var username = body.username;
if (!body.username) {
if (account.username) {
username = account.username;
} else {
return res.json({success: false, error: errorCode("DELEGATES.USERNAME_IS_TOO_SHORT")});
}
}
var transaction = library.logic.transaction.create({
type: TransactionTypes.DELEGATE,
username: username,
sender: account,
keypair: keypair,
secondKeypair: secondKeypair
});
library.sequence.add(function (cb) {
modules.transactions.receiveTransactions([transaction], cb);
}, function (err) {
if (err) {
return res.json({success: false, error: err});
}
res.json({success: true, transaction: transaction});
});
});
});
library.network.app.use('/api/delegates', router);
library.network.app.use(function (err, req, res, next) {
if (!err) return next();
library.logger.error(req.url, err.toString());
res.status(500).send({success: false, error: err.toString()});
});
}
private.getDelegate = function (filter, rateSort) {
var index;
if (filter.transactionId) {
index = private.transactionIdIndex[filter.transactionId];
}
if (filter.publicKey) {
index = private.publicKeyIndex[filter.publicKey];
}
if (filter.username) {
index = private.namesIndex[filter.username.toLowerCase()];
}
if (index === undefined) {
return false;
}
if (!rateSort) {
rateSort = {};
private.getKeysSortByVote(Object.keys(private.publicKeyIndex), private.votes)
.forEach(function (item, index) {
rateSort[item] = index + 1;
});
}
var delegate = private.delegates[index];
var stat = modules.round.blocksStat(delegate.publicKey);
var percent = 100 - (stat.missed / ((stat.forged + stat.missed) / 100));
var novice = stat.missed === null && stat.forged === null;
var outsider = rateSort[delegate.publicKey] > slots.delegates && novice;
var productivity = novice ? 0 : parseFloat(Math.floor(percent * 100) / 100).toFixed(2)
return {
username: delegate.username,
address: delegate.address,
publicKey: delegate.publicKey,
transactionId: delegate.transactionId,
vote: private.votes[delegate.publicKey],
rate: rateSort[delegate.publicKey],
productivity: outsider ? null : productivity
};
}
private.getKeysSortByVote = function (keys, votes) {
return keys.sort(function compare(a, b) {
if (votes[a] > votes[b]) return -1;
if (votes[a] < votes[b]) return 1;
if (a < b) return -1;
if (a > b) return 1;
return 0;
});
}
private.getBlockSlotData = function (slot, height) {
var activeDelegates = self.generateDelegateList(height);
var currentSlot = slot;
var lastSlot = slots.getLastSlot(currentSlot);
for (; currentSlot < lastSlot; currentSlot += 1) {
var delegate_pos = currentSlot % slots.delegates;
var delegate_id = activeDelegates[delegate_pos];
if (delegate_id && private.keypairs[delegate_id]) {
return {time: slots.getSlotTime(currentSlot), keypair: private.keypairs[delegate_id]};
}
}
return null;
}
private.loop = function (cb) {
setImmediate(cb);
if (!Object.keys(private.keypairs).length) {
library.logger.debug('loop', 'exit: have no delegates');
return;
}
if (!private.loaded || modules.loader.syncing()) {
library.logger.log('loop', 'exit: syncing');
return;
}
var currentSlot = slots.getSlotNumber();
var lastBlock = modules.blocks.getLastBlock();
if (currentSlot == slots.getSlotNumber(lastBlock.timestamp)) {
library.logger.log('loop', 'exit: lastBlock is in the same slot');
return;
}
var currentBlockData = private.getBlockSlotData(currentSlot, lastBlock.height + 1);
if (currentBlockData === null) {
library.logger.log('loop', 'skip slot');
return;
}
library.sequence.add(function (cb) {
var _activeDelegates = self.generateDelegateList(lastBlock.height + 1);
if (slots.getSlotNumber(currentBlockData.time) == slots.getSlotNumber()) {
modules.blocks.generateBlock(currentBlockData.keypair, currentBlockData.time, function (err) {
library.logger.log('round ' + self.getDelegateByPublicKey(_activeDelegates[slots.getSlotNumber(currentBlockData.time) % slots.delegates]).username + ': ' + modules.round.calc(modules.blocks.getLastBlock().height) + ' new block id: ' + modules.blocks.getLastBlock().id + ' height:' + modules.blocks.getLastBlock().height + ' slot:' + slots.getSlotNumber(currentBlockData.time))
cb(err);
});
} else {
library.logger.log('loop', 'exit: ' + self.getDelegateByPublicKey(_activeDelegates[slots.getSlotNumber() % slots.delegates]).username + ' delegate slot');
setImmediate(cb);
}
}, function (err) {
if (err) {
library.logger.error("Problem in block generation", err);
}
});
}
private.loadMyDelegates = function () {
var secrets = null;
if (library.config.forging.secret) {
secrets = util.isArray(library.config.forging.secret) ? library.config.forging.secret : [library.config.forging.secret];
}
if (secrets) {
secrets.forEach(function (secret) {
var keypair = ed.MakeKeypair(crypto.createHash('sha256').update(secret, 'utf8').digest());
var address = modules.accounts.getAddressByPublicKey(keypair.publicKey.toString('hex'));
var account = modules.accounts.getAccount(address);
if (self.existsDelegate(keypair.publicKey.toString('hex'))) {
private.keypairs[keypair.publicKey.toString('hex')] = keypair;
library.logger.info("Forging enabled on account: " + address);
} else {
library.logger.info("Forger with this public key not found " + keypair.publicKey.toString('hex'));
}
});
}
}
//public methods
Delegates.prototype.generateDelegateList = function (height) {
var sortedDelegateList = private.getKeysSortByVote(Object.keys(private.votes), private.votes);
var truncDelegateList = sortedDelegateList.slice(0, slots.delegates);
var seedSource = modules.round.calc(height).toString();
var currentSeed = crypto.createHash('sha256').update(seedSource, 'utf8').digest();
for (var i = 0, delCount = truncDelegateList.length; i < delCount; i++) {
for (var x = 0; x < 4 && i < delCount; i++, x++) {
var newIndex = currentSeed[x] % delCount;
var b = truncDelegateList[newIndex];
truncDelegateList[newIndex] = truncDelegateList[i];
truncDelegateList[i] = b;
}
currentSeed = crypto.createHash('sha256').update(currentSeed).digest();
}
return truncDelegateList;
}
Delegates.prototype.checkDelegates = function (publicKey, votes) {
if (votes === null) {
return true;
}
if (util.isArray(votes)) {
var account = modules.accounts.getAccountByPublicKey(publicKey);
if (!account) {
return false;
}
for (var i = 0; i < votes.length; i++) {
var math = votes[i][0];
var publicKey = votes[i].slice(1);
if (!self.existsDelegate(publicKey)) {
return false;
}
if (math == "+" && (account.delegates !== null && account.delegates.indexOf(publicKey) != -1)) {
return false;
}
if (math == "-" && (account.delegates === null || account.delegates.indexOf(publicKey) === -1)) {
return false;
}
}
return true;
} else {
return false;
}
}
Delegates.prototype.checkUnconfirmedDelegates = function (publicKey, votes) {
if (votes === null) {
return true;
}
if (util.isArray(votes)) {
var account = modules.accounts.getAccountByPublicKey(publicKey);
if (!account) {
return false;
}
for (var i = 0; i < votes.length; i++) {
var math = votes[i][0];
var publicKey = votes[i].slice(1);
if (private.unconfirmedVotes[publicKey] === undefined) {
return false;
}
if (math == "+" && (account.unconfirmedDelegates !== null && account.unconfirmedDelegates.indexOf(publicKey) != -1)) {
return false;
}
if (math == "-" && (account.unconfirmedDelegates === null || account.unconfirmedDelegates.indexOf(publicKey) === -1)) {
return false;
}
}
return true;
} else {
return false;
}
}
Delegates.prototype.addUnconfirmedDelegate = function (delegate) {
private.unconfirmedDelegates[delegate.publicKey] = true;
private.unconfirmedNames[delegate.username] = true;
}
Delegates.prototype.existsUnconfirmedDelegate = function (publicKey) {
return !!private.unconfirmedDelegates[publicKey];
}
Delegates.prototype.existsUnconfirmedName = function (username) {
return !!private.unconfirmedNames[username];
}
Delegates.prototype.removeUnconfirmedDelegate = function (delegate) {
delete private.unconfirmedDelegates[delegate.publicKey];
delete private.unconfirmedNames[delegate.username];
}
Delegates.prototype.fork = function (block, cause) {
library.logger.info('fork', {
delegate: private.getDelegate({publicKey: block.generatorPublicKey}),
block: {id: block.id, timestamp: block.timestamp, height: block.height, previousBlock: block.previousBlock},
cause: cause
});
library.dbLite.query("INSERT INTO forks_stat (delegatePublicKey, blockTimestamp, blockId, blockHeight, previousBlock, cause) " +
"VALUES ($delegatePublicKey, $blockTimestamp, $blockId, $blockHeight, $previousBlock, $cause);", {
delegatePublicKey: block.generatorPublicKey,
blockTimestamp: block.timestamp,
blockId: block.id,
blockHeight: block.height,
previousBlock: block.previousBlock,
cause: cause
});
}
Delegates.prototype.getDelegateByPublicKey = function (publicKey) {
return private.getDelegate({publicKey: publicKey});
}
Delegates.prototype.getDelegateByUsername = function (username) {
return private.getDelegate({username: username});
}
Delegates.prototype.addFee = function (publicKey, value) {
private.fees[publicKey] = (private.fees[publicKey] || 0) + value;
}
Delegates.prototype.existsDelegate = function (publicKey) {
return private.votes[publicKey] !== undefined;
}
Delegates.prototype.existsName = function (userName) {
return private.namesIndex[userName.toLowerCase()] !== undefined;
}
Delegates.prototype.cache = function (delegate) {
private.delegates.push(delegate);
var index = private.delegates.length - 1;
private.unconfirmedVotes[delegate.publicKey] = 0;
private.votes[delegate.publicKey] = 0;
private.namesIndex[delegate.username.toLowerCase()] = index;
private.publicKeyIndex[delegate.publicKey] = index;
private.transactionIdIndex[delegate.transactionId] = index;
var account = modules.accounts.getAccountByPublicKey(delegate.publicKey);
account.username = delegate.username;
library.network.io.sockets.emit('delegates/change', {});
}
Delegates.prototype.uncache = function (delegate) {
delete private.votes[delegate.publicKey];
delete private.unconfirmedVotes[delegate.publicKey];
var index = private.publicKeyIndex[delegate.publicKey];
delete private.publicKeyIndex[delegate.publicKey]
delete private.namesIndex[delegate.username.toLowerCase()];
delete private.transactionIdIndex[delegate.transactionId];
private.delegates[index] = false;
var account = modules.accounts.getAccountByPublicKey(delegate.publicKey);
account.username = null;
library.network.io.sockets.emit('delegates/change', {});
}
Delegates.prototype.validateBlockSlot = function (block) {
var activeDelegates = self.generateDelegateList(block.height);
var currentSlot = slots.getSlotNumber(block.timestamp);
var delegate_id = activeDelegates[currentSlot % slots.delegates];
if (delegate_id && block.generatorPublicKey == delegate_id) {
return true;
}
return false;
}
//events
Delegates.prototype.onBind = function (scope) {
modules = scope;
}
Delegates.prototype.onBlockchainReady = function () {
private.loaded = true;
private.loadMyDelegates(); //temp
process.nextTick(function nextLoop() {
private.loop(function (err) {
err && library.logger.error('delegate loop', err);
var nextSlot = slots.getNextSlot();
var scheduledTime = slots.getSlotTime(nextSlot);
scheduledTime = scheduledTime <= slots.getTime() ? scheduledTime + 1 : scheduledTime;
schedule.scheduleJob(new Date(slots.getRealTime(scheduledTime) + 1000), nextLoop);
})
});
}
Delegates.prototype.onNewBlock = function (block, broadcast) {
modules.round.tick(block);
}
Delegates.prototype.onChangeBalance = function (delegates, amount) {
modules.round.runOnFinish(function () {
var vote = amount;
if (delegates !== null) {
delegates.forEach(function (publicKey) {
private.votes[publicKey] !== undefined && (private.votes[publicKey] += vote);
});
}
});
}
Delegates.prototype.onChangeUnconfirmedBalance = function (unconfirmedDelegates, amount) {
var vote = amount;
if (unconfirmedDelegates !== null) {
unconfirmedDelegates.forEach(function (publicKey) {
private.unconfirmedVotes[publicKey] !== undefined && (private.unconfirmedVotes[publicKey] += vote);
});
}
}
Delegates.prototype.onChangeDelegates = function (balance, diff) {
modules.round.runOnFinish(function () {
var vote = balance;
for (var i = 0; i < diff.length; i++) {
var math = diff[i][0];
var publicKey = diff[i].slice(1);
if (math == "+") {
private.votes[publicKey] !== undefined && (private.votes[publicKey] += vote);
}
if (math == "-") {
private.votes[publicKey] !== undefined && (private.votes[publicKey] -= vote);
}
}
});
}
Delegates.prototype.onChangeUnconfirmedDelegates = function (balance, diff) {
var vote = balance;
for (var i = 0; i < diff.length; i++) {
var math = diff[i][0];
var publicKey = diff[i].slice(1);
if (math == "+") {
private.unconfirmedVotes[publicKey] !== undefined && (private.unconfirmedVotes[publicKey] += vote);
}
if (math == "-") {
private.unconfirmedVotes[publicKey] !== undefined && (private.unconfirmedVotes[publicKey] -= vote);
}
}
}
//export
module.exports = Delegates;
|
import Ember from 'ember';
export
default Ember.Component.extend({
tagName: '',
actions: {
selectItem: function(item) {
this.sendAction('select', item);
},
showDetails: function(item) {
this.sendAction('details', item);
},
select: function() {
var item = this.get('item');
this.sendAction('select', item);
}
},
name: function() {
var buildm = this.get('item.buildm');
// incoming filename is either 'http://download.able.url/file.ext' or 'file.ext' for non-downloadable files
var name = buildm['http://data.duraark.eu/vocab/buildm/filename']['@value'].split('/').pop();
console.log('name: ' + name);
if (name) {
return name;
}
return 'No name given';
}.property('item'),
size: function() {
var size = this.get('item.size');
return numeral(size).format('0 b');
}.property('item'),
extension: function() {
var path = this.get('item.path');
if (path) {
return _getFileExtension(path)[0];
}
return '';
}.property('item'),
isPhysicalAsset: function() {
let buildm = this.get('item')['buildm'];
return this.duraark.isOfType(buildm, 'http://data.duraark.eu/vocab/buildm/PhysicalAsset');
}.property('item'),
isIFC: function() {
let buildm = this.get('item')['buildm'];
return this.duraark.isOfType(buildm, 'http://data.duraark.eu/vocab/buildm/IFCSPFFile');
}.property('item'),
isE57: function() {
let buildm = this.get('item')['buildm'];
return this.duraark.isOfType(buildm, 'http://data.duraark.eu/vocab/buildm/E57File');
}.property('item')
});
function _getFileExtension(filepath) {
return (/[.]/.exec(filepath)) ? /[^.]+$/.exec(filepath) : null;
}
|
//=require vendor/jquery.js
//=require _map.js
var MapAllTheThings = {};
//=require data/slip_data.js
//=require data/Localphotostories2009-2014-JSON.js
|
// ==UserScript==
// @name vkmin
// @description Vk interface vkmin.hider
// @version 1.3
// @match https://vk.com/*
// ==/UserScript==
//
window.onkeydown = function(e){
var stuff_ids = [
"page_header",
"side_bar",
"im_nav_wrap",
"im_user_holder",
"im_peer_holders",
"im_send_wrap",
"im_resizer_wrap",
];
if(e.keyIdentifier == "Insert") {
var id;
var element;
for(id in stuff_ids) {
element = document.getElementById(stuff_ids[id]);
if(element)
vkmin.toggle(element);
//else console.log("can't toggle: " + stuff_ids[id]);
}
//now fix annoying empty space waste on the left
element = document.getElementById("page_body");
element.style.float = element.style.float=="left" ? "right" : "left";
return false;
}
else {
return true;
}
};
vkmin = {}
vkmin.getRealDisplay = function(elem) {
if (elem.currentStyle) {
return elem.currentStyle.display
} else if (window.getComputedStyle) {
var computedStyle = window.getComputedStyle(elem, null )
return computedStyle.getPropertyValue('display')
}
}
vkmin.hide = function(el) {
if (!el.getAttribute('displayOld')) {
el.setAttribute("displayOld", el.style.display)
}
el.style.display = "none"
}
vkmin.displayCache = {}
vkmin.isHidden = function(el) {
var width = el.offsetWidth, height = el.offsetHeight,
tr = el.nodeName.toLowerCase() === "tr"
return width === 0 && height === 0 && !tr ?
true : width > 0 && height > 0 && !tr ? false : vkmin.getRealDisplay(el)
}
vkmin.toggle = function(el) {
vkmin.isHidden(el) ? vkmin.show(el) : vkmin.hide(el)
}
vkmin.show = function(el) {
if (vkmin.getRealDisplay(el) != 'none') return
var old = el.getAttribute("displayOld");
el.style.display = old || "";
if ( vkmin.getRealDisplay(el) === "none" ) {
var nodeName = el.nodeName, body = document.body, display
if ( vkmin.displayCache[nodeName] ) {
display = vkmin.displayCache[nodeName]
} else {
var testElem = document.createElement(nodeName)
body.appendChild(testElem)
display = vkmin.getRealDisplay(testElem)
if (display === "none" ) {
display = "block"
}
body.removeChild(testElem)
vkmin.displayCache[nodeName] = display
}
el.setAttribute('displayOld', display)
el.style.display = display
}
}
|
class Survey {
constructor(client) {
this.client = client;
}
create(options, callback) {
this.client.perform("GET", "/survey/add", options, callback);
}
delete(surveyId, callback) {
this.client.perform("GET", "/survey/delete", {publicSurveyID: surveyId}, callback);
}
export(options, callback) {
this.client.perform("GET", "/survey/export", options, callback);
}
list(callback) {
this.client.perform("GET", "/survey/list", callback);
}
responses(surveyId, callback) {
this.client.perform("GET", "/survey/loadresponselist", {publicSurveyID: surveyId}, callback);
}
summary(surveyId, callback) {
this.client.perform("GET", "/survey/loadresults", {publicSurveyID: surveyId}, callback);
}
update(options, callback) {
this.client.perform("GET", "/survey/update", options, callback);
}
}
module.exports = Survey;
|
export const FETCH_WEB_MODE = 'fetch_web_mode';
export const fetchWebMode = (data) => async(dispatch) => {
const res = data;
dispatch({
type: FETCH_WEB_MODE,
payload: res
});
};
|
/* global S */
define({
options: {
displaySearchbox: !0,
displayQuickAddButton: !0,
title: S.lang["my-sheets"].capitalize(),
titleInSearch: S.lang.search.capitalize()
},
route: {
data: function() {
return S.user._current.isAdmin() && (S.vue.router.app.$children[0].$data.options.title = S.lang["overview-of-sheets"].capitalize()),
S.db.fiches.getAllWithMine();
}
},
data: function() {
return {
fiches: [],
my_fiches: []
};
}
});
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var ic_cloud_queue = exports.ic_cloud_queue = { "viewBox": "0 0 24 24", "children": [{ "name": "path", "attribs": { "d": "M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM19 18H6c-2.21 0-4-1.79-4-4s1.79-4 4-4h.71C7.37 7.69 9.48 6 12 6c3.04 0 5.5 2.46 5.5 5.5v.5H19c1.66 0 3 1.34 3 3s-1.34 3-3 3z" } }] };
|
require('./setting.less');
var appFunc = require('../utils/appFunc'),
template = require('./setting.tpl.html');
var settingView = {
init: function(){
settingView.bindEvents();
},
renderSetting: function(){
if($$('#settingView .page-content')[0]) return;
Jellyfish.showIndicator();
var renderData = {
avatarUrl: 'https://avatars1.githubusercontent.com/u/5567116',
nickName: 'Xicky',
points: '100'
};
var output = appFunc.renderTpl(template, renderData);
$$('#settingView .page[data-page="setting"]').html(output);
Jellyfish.hideIndicator();
},
logOut: function(){
Jellyfish.confirm(i18n.setting.confirm_logout,function(){
// var homeF7View = Jellyfish.addView('#loginView', {
// dynamicNavbar: false
// });
// homeF7View.router.loadPage('page/login.html');
// settingView.router.loadPage('page/login.html');
//Jellyfish.showTab('#ourView');
// window.location('page/login.html');
function eventFire(el, etype){
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('Events');
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
}
eventFire(document.getElementById('loginJump'), 'click');
});
},
bindEvents: function(){
var bindings = [{
element: '#settingView',
event: 'show',
handler: settingView.renderSetting
},{
element: '#settingView',
selector: '.logout-button',
event: 'click',
handler: settingView.logOut
},{
element: '#settingView',
selector: '.update-button',
event: 'click',
//handler: settingView.checkVersion
}];
appFunc.bindEvents(bindings);
}
};
module.exports = settingView;
|
require('./models/Todo.js');
require('./models/TodoList.js');
require('./views/TodoView.js');
|
import React from 'react';
export default class Slide extends React.Component {
render() {
return (
<div>
<h1>phase 3: one repo to rule them all?</h1>
<ul>
<li>We think repos should be separated by deploy boundaries, and the
client app service should be deployable on a separate cadence from ALM.</li>
<li>This work is directionally correct if we want to move to a single repo.</li>
<li>We may or may not be able to maintain history for such a large repo. TBD.</li>
</ul>
</div>
);
}
}
|
var expect = chai.expect;
var assert = chai.assert;
describe('Flyweight Pattern', function() {
it('should exist', function() {
assert.isDefined(Flyweight);
});
it('should have Color property in the prototype object of the constructor', function() {
assert.property(Flyweight.prototype, 'Color');
});
it('Color property should have default value "green"', function() {
assert.equal(Flyweight.prototype.Color, 'green');
});
it('should have Name property in the prototype object of the constructor', function() {
assert.property(Flyweight.prototype, 'Name');
});
it('Name property should have default value "Ball"', function() {
assert.equal(Flyweight.prototype.Name, 'Ball');
});
it('should have Shape property in the prototype object of the constructor', function() {
assert.property(Flyweight.prototype, 'Shape');
});
it('Name property should have default value "Circle"', function() {
assert.equal(Flyweight.prototype.Shape, 'Circle');
});
it('a new object should be able to overwrite the default values', function() {
var testFlyweight = new Flyweight();
testFlyweight.Color = 'blue';
testFlyweight.Name = 'Balloon';
testFlyweight.Shape = 'Oval';
assert.equal(testFlyweight.Color, 'blue');
assert.equal(testFlyweight.Name, 'Balloon');
assert.equal(testFlyweight.Shape, 'Oval');
});
});
|
import React, { Component } from 'react';
import { Link } from 'react-router';
import classNames from 'classnames';
class Sidebar extends Component {
constructor(props){
super(props);
this.eventCloseSidebar = this.eventCloseSidebar.bind(this)
}
eventCloseSidebar (e) {
this.props.toggleSidebar(!this.props.layout.sidebarOpen);
}
render() {
return (
<div className="sidebar">
<div className="sidebar-item sidebar-footer">
<p>I built this site with Redux and React. You can get the <a href="https://github.com/caljrimmer/portfolio-redux-app">source code here</a></p>
</div>
<nav className="sidebar-nav">
<Link to="/" className="sidebar-nav-item" onClick={this.eventCloseSidebar} activeClassName="active" onlyActiveOnIndex>Home</Link>
<Link to="/portfolio" className="sidebar-nav-item" onClick={this.eventCloseSidebar} activeClassName="active">My Portfolio</Link>
<Link to="/services" className="sidebar-nav-item" onClick={this.eventCloseSidebar} activeClassName="active">My Services</Link>
<Link to="/about" className="sidebar-nav-item" onClick={this.eventCloseSidebar} activeClassName="active">About</Link>
</nav>
<div className="sidebar-item sidebar-footer">
<p>
Visit <a href="https://github.com/caljrimmer">My GitHub Repo</a><br/>
Visit <a href="https://www.linkedin.com/in/callumrimmer">My Linkedin</a><br/>
Visit <a href="https://twitter.com/caljrimmer">My Twitter</a><br/>
</p>
<p>
Design based on <a href="http://lanyon.getpoole.com/"> Lanyon Theme</a>
</p>
</div>
</div>
);
}
}
export default Sidebar;
|
import { default as requireDir } from 'require-dir';
import { RuleAttribute } from './ruleAttribute.js';
export class Behavior extends RuleAttribute {
constructor(name, options, valueMap) {
super();
return Behavior.create(name, options, valueMap);
}
process() {
// override
}
getHeaderName(headerNameOption) {
return '"' + (this.options[headerNameOption] === 'OTHER' ?
this.options.customHeaderName : [headerNameOption]) + '"';
}
processRequestMethodOptions(method, options) {
return options.enabled ? 'aka_request_method_status["' + method + '"] = "ALLOW"'
: 'aka_request_method_status["' + method + '"] = "DENY"';
}
processHeaderOptions(luaMapName, comment, capture) {
let headerName = this.switchByVal({
'MODIFY': this.getHeaderName('standardModifyHeaderName'),
'ADD': this.getHeaderName('standardAddHeaderName'),
'REMOVE': this.getHeaderName('standardRemoveHeaderName'),
'REGEX': this.getHeaderName('standardModifyHeaderName')
}, '"' + this.options.customHeaderName + '"', this.options.action);
let headerValue = this.switchByVal({
'MODIFY': this.value(this.options.newHeaderValue),
'ADD': this.value(this.options.headerValue),
'REMOVE': 'nil',
'REGEX': 'string.gsub(cs(' + luaMapName + '[' + headerName + ']), ' +
this.value(this.options.regexHeaderMatch) + ', ' +
this.value(this.options.regexHeaderReplace) + ')',
}, 'nil', this.options.action);
let lua = [];
// capture header manipulations to apply after proxy pass as table mapping header to
// action, value, search, replacement
if (capture) {
lua = [
'-- ' + this.options.action + ' CAPTURE ' + comment,
luaMapName + '[' + headerName + '] = { "' + this.options.action + '", ' +
headerValue + ', ' +
this.value(this.options.regexHeaderMatch) + ', ' +
this.value(this.options.regexHeaderReplace) + ' }'];
} else {
lua = [
'-- ' + this.options.action + ' ' + comment,
luaMapName + '[' + headerName + '] = ' + headerValue
];
}
return lua;
}
static translateTTL(ttl) {
if (!ttl) return 0;
let ttlSeconds = 0;
let ttlInt = parseInt(ttl.substring(0, ttl.length - 1));
switch (ttl.slice(-1)) {
case 's':
ttlSeconds = ttlInt;
break;
case 'm':
ttlSeconds = ttlInt * 60;
break;
case 'h':
ttlSeconds = ttlInt * 60 * 60;
break;
case 'd':
ttlSeconds = ttlInt * 60 * 60 * 24;
break;
}
return ttlSeconds;
}
}
requireDir('./behaviors');
|
export * from './nav.js'
export * from './articles.js'
|
import React, {Component, PropTypes} from 'react'
import {connect} from 'react-redux'
import * as wordActions from '../actions/wordActions'
import {exportWords, newTab} from '../actions/manageActions'
import View from '../components/View.react'
class BackgroundContainer extends Component {
render () {
const {dispatch, words} = this.props
return (
<View
words={words}
onAdd={word => dispatch(wordActions.addWord(word))}
onExport={() => dispatch(exportWords())}
onNewTab={() => dispatch(newTab())}
onRemove={(character) => dispatch(wordActions.removeWord(character))}
onTranslateJyutping={() => dispatch(wordActions.translateJyutping())}
onTranslatePinyin={() => dispatch(wordActions.translatePinyin())}
/>
)
}
}
BackgroundContainer.propTypes = {
dispatch: PropTypes.func.isRequired,
words: PropTypes.arrayOf(PropTypes.shape({
character: PropTypes.string.isRequired,
translation: PropTypes.string.isRequired,
notes: PropTypes.string
})).isRequired
}
function select (state) {
return {
words: state.words
}
}
const configuredConnect = connect(select)
export default configuredConnect(BackgroundContainer)
|
var inherits = require('util').inherits;
var clone = require('./util/clone').clone;
var EventEmitter = require('events').EventEmitter;
var Characteristic = require('./Characteristic').Characteristic;
'use strict';
module.exports = {
Service: Service
}
/**
* Service represents a set of grouped values necessary to provide a logical function. For instance, a
* "Door Lock Mechanism" service might contain two values, one for the "desired lock state" and one for the
* "current lock state". A particular Service is distinguished from others by its "type", which is a UUID.
* HomeKit provides a set of known Service UUIDs defined in HomeKitTypes.js along with a corresponding
* concrete subclass that you can instantiate directly to setup the necessary values. These natively-supported
* Services are expected to contain a particular set of Characteristics.
*
* Unlike Characteristics, where you cannot have two Characteristics with the same UUID in the same Service,
* you can actually have multiple Services with the same UUID in a single Accessory. For instance, imagine
* a Garage Door Opener with both a "security light" and a "backlight" for the display. Each light could be
* a "Lightbulb" Service with the same UUID. To account for this situation, we define an extra "subtype"
* property on Service, that can be a string or other string-convertible object that uniquely identifies the
* Service among its peers in an Accessory. For instance, you might have `service1.subtype = 'security_light'`
* for one and `service2.subtype = 'backlight'` for the other.
*
* You can also define custom Services by providing your own UUID for the type that you generate yourself.
* Custom Services can contain an arbitrary set of Characteristics, but Siri will likely not be able to
* work with these.
*
* @event 'characteristic-change' => function({characteristic, oldValue, newValue, context}) { }
* Emitted after a change in the value of one of our Characteristics has occurred.
*/
function Service(displayName, UUID, subtype) {
if (!UUID) throw new Error("Services must be created with a valid UUID.");
this.displayName = displayName;
this.UUID = UUID;
this.subtype = subtype;
this.iid = null; // assigned later by our containing Accessory
this.characteristics = [];
this.optionalCharacteristics = [];
// every service has an optional Characteristic.Name property - we'll set it to our displayName
// if one was given
// if you don't provide a display name, some HomeKit apps may choose to hide the device.
if (displayName) {
// create the characteristic if necessary
var nameCharacteristic =
this.getCharacteristic(Characteristic.Name) ||
this.addCharacteristic(Characteristic.Name);
nameCharacteristic.setValue(displayName);
}
}
inherits(Service, EventEmitter);
Service.prototype.addCharacteristic = function(characteristic) {
// characteristic might be a constructor like `Characteristic.Brightness` instead of an instance
// of Characteristic. Coerce if necessary.
if (typeof characteristic === 'function') {
characteristic = new (Function.prototype.bind.apply(characteristic, arguments));
}
// check for UUID conflict
for (var index in this.characteristics) {
var existing = this.characteristics[index];
if (existing.UUID === characteristic.UUID)
throw new Error("Cannot add a Characteristic with the same UUID as another Characteristic in this Service: " + existing.UUID);
}
// listen for changes in characteristics and bubble them up
characteristic.on('change', function(change) {
// make a new object with the relevant characteristic added, and bubble it up
this.emit('characteristic-change', clone(change, {characteristic:characteristic}));
}.bind(this));
this.characteristics.push(characteristic);
this.emit('service-configurationChange', clone({service:this}));
return characteristic;
}
Service.prototype.removeCharacteristic = function(characteristic) {
var targetCharacteristicIndex;
for (var index in this.characteristics) {
var existingCharacteristic = this.characteristics[index];
if (existingCharacteristic === characteristic) {
targetCharacteristicIndex = index;
break;
}
}
if (targetCharacteristicIndex) {
this.characteristics.splice(targetCharacteristicIndex, 1);
characteristic.removeAllListeners();
this.emit('service-configurationChange', clone({service:this}));
}
}
Service.prototype.getCharacteristic = function(name) {
// returns a characteristic object from the service
// If Service.prototype.getCharacteristic(Characteristic.Type) does not find the characteristic,
// but the type is in optionalCharacteristics, it adds the characteristic.type to the service and returns it.
var index, characteristic;
for (index in this.characteristics) {
characteristic = this.characteristics[index];
if (typeof name === 'string' && characteristic.displayName === name) {
return characteristic;
}
else if (typeof name === 'function' && ((characteristic instanceof name) || (name.UUID === characteristic.UUID))) {
return characteristic;
}
}
if (typeof name === 'function') {
for (index in this.optionalCharacteristics) {
characteristic = this.optionalCharacteristics[index];
if ((characteristic instanceof name) || (name.UUID === characteristic.UUID)) {
return this.addCharacteristic(name);
}
}
}
};
Service.prototype.testCharacteristic = function(name) {
// checks for the existence of a characteristic object in the service
var index, characteristic;
for (index in this.characteristics) {
characteristic = this.characteristics[index];
if (typeof name === 'string' && characteristic.displayName === name) {
return true;
}
else if (typeof name === 'function' && ((characteristic instanceof name) || (name.UUID === characteristic.UUID))) {
return true;
}
}
return false;
}
Service.prototype.setCharacteristic = function(name, value) {
this.getCharacteristic(name).setValue(value);
return this; // for chaining
}
// A function to only updating the remote value, but not firiring the 'set' event.
Service.prototype.updateCharacteristic = function(name, value){
this.getCharacteristic(name).updateValue(value);
return this;
}
Service.prototype.addOptionalCharacteristic = function(characteristic) {
// characteristic might be a constructor like `Characteristic.Brightness` instead of an instance
// of Characteristic. Coerce if necessary.
if (typeof characteristic === 'function')
characteristic = new characteristic();
this.optionalCharacteristics.push(characteristic);
}
Service.prototype.getCharacteristicByIID = function(iid) {
for (var index in this.characteristics) {
var characteristic = this.characteristics[index];
if (characteristic.iid === iid)
return characteristic;
}
}
Service.prototype._assignIDs = function(identifierCache, accessoryName) {
// the Accessory Information service must have a (reserved by IdentifierCache) ID of 1
if (this.UUID === '0000003E-0000-1000-8000-0026BB765291') {
this.iid = 1;
}
else {
// assign our own ID based on our UUID
this.iid = identifierCache.getIID(accessoryName, this.UUID, this.subtype);
}
// assign IIDs to our Characteristics
for (var index in this.characteristics) {
var characteristic = this.characteristics[index];
characteristic._assignID(identifierCache, accessoryName, this.UUID, this.subtype);
}
}
/**
* Returns a JSON representation of this Accessory suitable for delivering to HAP clients.
*/
Service.prototype.toHAP = function(opt) {
var characteristicsHAP = [];
for (var index in this.characteristics) {
var characteristic = this.characteristics[index];
characteristicsHAP.push(characteristic.toHAP(opt));
}
var hap = {
iid: this.iid,
type: this.UUID,
characteristics: characteristicsHAP
};
if (this.isPrimaryService !== undefined) {
hap['primary'] = this.isPrimaryService;
}
return hap;
}
Service.prototype._setupCharacteristic = function(characteristic) {
// listen for changes in characteristics and bubble them up
characteristic.on('change', function(change) {
// make a new object with the relevant characteristic added, and bubble it up
this.emit('characteristic-change', clone(change, {characteristic:characteristic}));
}.bind(this));
}
Service.prototype._sideloadCharacteristics = function(targetCharacteristics) {
for (var index in targetCharacteristics) {
var target = targetCharacteristics[index];
this._setupCharacteristic(target);
}
this.characteristics = targetCharacteristics.slice();
}
|
import React from 'react';
const Tile = ({text}) => {
return (
<div className="tile">
{text}
</div>
)
}
export default Tile;
|
version https://git-lfs.github.com/spec/v1
oid sha256:bd7bfebbb8722961020163fb0d98fa709f06a0111869be3d8d8d11638da3c4eb
size 86147
|
/*
* Copyright (c) Michael Polyak. All rights reserved.
*/
"use strict";
const util = require("util");
const Transform = require("stream").Transform;
const seconds = require("./seconds.js");
util.inherits(Logger, Transform);
function Logger(reporter)
{
Transform.call(this, {objectMode: true});
this.opsec = 0;
this.start = 0;
this.count = 0;
this.reporter = reporter;
}
Logger.prototype._transform = function (data, encoding, done)
{
if (data.increment)
{
this.count ++;
const time = seconds(), delta = time - this.start;
if (delta >= 1)
{
this.opsec = Math.round(this.count / delta);
this.start = time;
this.count = 0;
}
// Update monitoring clients.
if (this.reporter)
this.reporter.update(this.opsec);
}
this.push(`${this.time()} (${this.opsec} op/sec): ${data.message}\n`);
done();
};
Logger.prototype.time = function ()
{
const date = new Date(), hours = date.getHours(), minutes = date.getMinutes(), seconds = date.getSeconds(), milliseconds = date.getMilliseconds();
return (hours < 10 ? "0" : "") + hours + ":" + (minutes < 10 ? "0" : "") + minutes + ":" + (seconds < 10 ? "0" : "") + seconds +
"." + (milliseconds < 10 ? "00" : (milliseconds < 100 ? "0" : "")) + milliseconds;
};
module.exports = Logger;
|
var Block, Layout, SpecialString, layoutConfig, object, prop, _fn, _i, _len, _ref;
Block = require('./layout/Block');
object = require('utila').object;
layoutConfig = require('./layout/config');
SpecialString = require('./layout/SpecialString');
module.exports = Layout = (function() {
var self;
self = Layout;
Layout._rootBlockDefaultConfig = {
linePrependor: {
options: {
amount: 0
}
},
lineAppendor: {
options: {
amount: 0
}
},
blockPrependor: {
options: {
amount: 0
}
},
blockAppendor: {
options: {
amount: 0
}
}
};
Layout._defaultConfig = {
terminalWidth: 80
};
function Layout(config, rootBlockConfig) {
var rootConfig;
if (config == null) {
config = {};
}
if (rootBlockConfig == null) {
rootBlockConfig = {};
}
this._written = [];
this._activeBlock = null;
this._config = layoutConfig(config, self._defaultConfig);
rootConfig = object.append(self._rootBlockDefaultConfig, rootBlockConfig);
this._root = new Block(this, null, rootConfig, '__root');
this._root._open();
}
Layout.prototype.getRootBlock = function() {
return this._root;
};
Layout.prototype._append = function(text) {
return this._written.push(text);
};
Layout.prototype._appendLine = function(text) {
var s;
this._append(text);
s = SpecialString(text);
if (s.length < this._config.terminalWidth) {
this._append('<none>\n</none>');
}
return this;
};
Layout.prototype.get = function() {
this._ensureClosed();
if (this._written[this._written.length - 1] === '<none>\n</none>') {
this._written.pop();
}
return this._written.join("");
};
Layout.prototype._ensureClosed = function() {
if (this._activeBlock !== this._root) {
throw Error("Not all the blocks have been closed. Please call block.close() on all open blocks.");
}
if (this._root.isOpen()) {
this._root.close();
}
};
return Layout;
})();
_ref = ['openBlock', 'write'];
_fn = function() {
var method;
method = prop;
return Layout.prototype[method] = function() {
return this._root[method].apply(this._root, arguments);
};
};
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
prop = _ref[_i];
_fn();
}
|
/* eslint no-unused-expressions: 0, no-unused-vars: 0 */
import { expect } from 'chai'
import { observable, isObservable, observe, raw } from '@nx-js/observer-util'
import { spy } from '../utils'
describe('Set', () => {
it('should be a proper JS Set', () => {
const set = observable(new Set())
expect(set).to.be.instanceOf(Set)
expect(raw(set)).to.be.instanceOf(Set)
})
it('should observe mutations', () => {
let dummy
const set = observable(new Set())
observe(() => (dummy = set.has('value')))
expect(dummy).to.equal(false)
set.add('value')
expect(dummy).to.equal(true)
set.delete('value')
expect(dummy).to.equal(false)
})
it('should observe for of iteration', () => {
let dummy
const set = observable(new Set())
observe(() => {
dummy = 0
for (let num of set) {
dummy += num
}
})
expect(dummy).to.equal(0)
set.add(2)
set.add(1)
expect(dummy).to.equal(3)
set.delete(2)
expect(dummy).to.equal(1)
set.clear()
expect(dummy).to.equal(0)
})
it('should observe forEach iteration', () => {
let dummy
const set = observable(new Set())
observe(() => {
dummy = 0
set.forEach(num => (dummy += num))
})
expect(dummy).to.equal(0)
set.add(2)
set.add(1)
expect(dummy).to.equal(3)
set.delete(2)
expect(dummy).to.equal(1)
set.clear()
expect(dummy).to.equal(0)
})
it('should observe values iteration', () => {
let dummy
const set = observable(new Set())
observe(() => {
dummy = 0
for (let num of set.values()) {
dummy += num
}
})
expect(dummy).to.equal(0)
set.add(2)
set.add(1)
expect(dummy).to.equal(3)
set.delete(2)
expect(dummy).to.equal(1)
set.clear()
expect(dummy).to.equal(0)
})
it('should observe keys iteration', () => {
let dummy
const set = observable(new Set())
observe(() => {
dummy = 0
for (let num of set.keys()) {
dummy += num
}
})
expect(dummy).to.equal(0)
set.add(2)
set.add(1)
expect(dummy).to.equal(3)
set.delete(2)
expect(dummy).to.equal(1)
set.clear()
expect(dummy).to.equal(0)
})
it('should observe entries iteration', () => {
let dummy
const set = observable(new Set())
observe(() => {
dummy = 0
// eslint-disable-next-line no-unused-vars
for (let [key, num] of set.entries()) {
dummy += num
}
})
expect(dummy).to.equal(0)
set.add(2)
set.add(1)
expect(dummy).to.equal(3)
set.delete(2)
expect(dummy).to.equal(1)
set.clear()
expect(dummy).to.equal(0)
})
it('should be triggered by clearing', () => {
let dummy
const set = observable(new Set())
observe(() => (dummy = set.has('key')))
expect(dummy).to.equal(false)
set.add('key')
expect(dummy).to.equal(true)
set.clear()
expect(dummy).to.equal(false)
})
it('should not observe custom property mutations', () => {
let dummy
const set = observable(new Set())
observe(() => (dummy = set.customProp))
expect(dummy).to.equal(undefined)
set.customProp = 'Hello World'
expect(dummy).to.equal(undefined)
})
it('should observe size mutations', () => {
let dummy
const set = observable(new Set())
observe(() => (dummy = set.size))
expect(dummy).to.equal(0)
set.add('value')
set.add('value2')
expect(dummy).to.equal(2)
set.delete('value')
expect(dummy).to.equal(1)
set.clear()
expect(dummy).to.equal(0)
})
it('should not observe non value changing mutations', () => {
let dummy
const set = observable(new Set())
const setSpy = spy(() => (dummy = set.has('value')))
observe(setSpy)
expect(dummy).to.equal(false)
expect(setSpy.callCount).to.equal(1)
set.add('value')
expect(dummy).to.equal(true)
expect(setSpy.callCount).to.equal(2)
set.add('value')
expect(dummy).to.equal(true)
expect(setSpy.callCount).to.equal(2)
set.delete('value')
expect(dummy).to.equal(false)
expect(setSpy.callCount).to.equal(3)
set.delete('value')
expect(dummy).to.equal(false)
expect(setSpy.callCount).to.equal(3)
set.clear()
expect(dummy).to.equal(false)
expect(setSpy.callCount).to.equal(3)
})
it('should not observe raw data', () => {
let dummy
const set = observable(new Set())
observe(() => (dummy = raw(set).has('value')))
expect(dummy).to.equal(false)
set.add('value')
expect(dummy).to.equal(false)
})
it('should not observe raw iterations', () => {
let dummy = 0
const set = observable(new Set())
observe(() => {
dummy = 0
for (let [num] of raw(set).entries()) {
dummy += num
}
for (let num of raw(set).keys()) {
dummy += num
}
for (let num of raw(set).values()) {
dummy += num
}
raw(set).forEach(num => {
dummy += num
})
for (let num of raw(set)) {
dummy += num
}
})
expect(dummy).to.equal(0)
set.add(2)
set.add(3)
expect(dummy).to.equal(0)
set.delete(2)
expect(dummy).to.equal(0)
})
it('should not be triggered by raw mutations', () => {
let dummy
const set = observable(new Set())
observe(() => (dummy = set.has('value')))
expect(dummy).to.equal(false)
raw(set).add('value')
expect(dummy).to.equal(false)
dummy = true
raw(set).delete('value')
expect(dummy).to.equal(true)
raw(set).clear()
expect(dummy).to.equal(true)
})
it('should not observe raw size mutations', () => {
let dummy
const set = observable(new Set())
observe(() => (dummy = raw(set).size))
expect(dummy).to.equal(0)
set.add('value')
expect(dummy).to.equal(0)
})
it('should not be triggered by raw size mutations', () => {
let dummy
const set = observable(new Set())
observe(() => (dummy = set.size))
expect(dummy).to.equal(0)
raw(set).add('value')
expect(dummy).to.equal(0)
})
it('should support objects as key', () => {
let dummy
const key = {}
const set = observable(new Set())
const setSpy = spy(() => (dummy = set.has(key)))
observe(setSpy)
expect(dummy).to.equal(false)
expect(setSpy.callCount).to.equal(1)
set.add({})
expect(dummy).to.equal(false)
expect(setSpy.callCount).to.equal(1)
set.add(key)
expect(dummy).to.equal(true)
expect(setSpy.callCount).to.equal(2)
})
it('should wrap object values with observables when iterated from a reaction', () => {
const set = observable(new Set())
set.add({})
set.forEach(value => expect(isObservable(value)).to.be.false)
for (let value of set) {
expect(isObservable(value)).to.be.false
}
for (let [_, value] of set.entries()) {
expect(isObservable(value)).to.be.false
}
for (let value of set.values()) {
expect(isObservable(value)).to.be.false
}
observe(() => {
set.forEach(value => expect(isObservable(value)).to.be.true)
for (let value of set) {
expect(isObservable(value)).to.be.true
}
for (let [_, value] of set.entries()) {
expect(isObservable(value)).to.be.true
}
for (let value of set.values()) {
expect(isObservable(value)).to.be.true
}
})
set.forEach(value => expect(isObservable(value)).to.be.true)
for (let value of set) {
expect(isObservable(value)).to.be.true
}
for (let [_, value] of set.entries()) {
expect(isObservable(value)).to.be.true
}
for (let value of set.values()) {
expect(isObservable(value)).to.be.true
}
})
})
|
var express = require('express');
var bodyParser = require('body-parser');
var users = require('./routes/users');
var app = express();
app.use( bodyParser.json() );
app.use('/user', users);
app.set('port', (process.env.PORT || 5000));
var server = app.listen(app.get('port'), function () {
console.log("app started!");
});
|
ace.define("ace/snippets/json5",["require","exports","module"], function(require, exports, module) {
"use strict";
exports.snippetText =undefined;
exports.scope = "json5";
}); (function() {
ace.require(["ace/snippets/json5"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})();
|
let _ = require('lodash');
let async = require('async');
/**
*
* @param {String} name
* @param {String} namespace
* @param {Object=} data
* @param {Array[Object]} events
* @param {Object=} meta
*/
let createEvent = function (name, namespace, data, events, meta) {
// If the model or the actions are empty then it needs to error out.
if (_.isEmpty(name) || _.isEmpty(namespace)) {
throw new Error('ModelEvent: Cannot create event without name or namespace');
}
let event = { name, namespace };
data && (event.data = data);
events && (event.events = events);
meta && (event.meta = meta);
// returns the instruction POJO.
return event;
},
/**
*
*/
getEventName = function (event) {
return event && event.name;
},
getEventNamespace = function (event) {
return event && event.namespace;
},
getEventData = function (event) {
return event && event.data;
},
getEventMeta = function (event) {
return event && event.meta;
},
getLowLevelEvents = function (event) {
return event && event.events;
},
getActor = function (event) {
return event && event.meta && event.meta.actor;
},
processEvent = function (event, allowedEvents, iteratee, callback) {
// bail out
if (!event || !iteratee) {
return;
}
// bail out
if (!allowedEvents) {
callback(new Error('Could not find handlers dictionary to process events'));
}
let lowLevelEvents;
// if there is a handler for the current event, process with it
if (_.includes(allowedEvents, getEventName(event))) {
(iteratee.length < 2) && console.warn('It looks like you are trying to pass a handler to processEvent without a callback.');
return iteratee(event, callback);
}
lowLevelEvents = getLowLevelEvents(event);
// otherwise try if the low level events can be handled
async.mapSeries(lowLevelEvents, function (event, cb) {
return processEvent(event, allowedEvents, iteratee, cb);
}, callback);
};
module.exports = {
createEvent,
getEventName,
getEventData,
getEventMeta,
getEventNamespace,
getLowLevelEvents,
getActor,
processEvent
};
|
module.exports = {
'-v' : require('./commands/version'),
'--version' : require('./commands/version'),
help : require('./commands/help'),
add : require('./commands/add'),
rm : require('./commands/rm'),
touch : require('./commands/touch'),
list : require('./commands/list'),
open : require('./commands/open'),
status : require('./commands/status'),
start : require('./commands/start'),
stop : require('./commands/stop'),
install : require('./commands/install'),
uninstall : require('./commands/uninstall'),
migrate : require('./commands/migrate'),
run: function(args) {
var command = args[0]
var options = args.slice(1)
if (this[command]) {
this[command](options)
} else {
this.help()
}
}
}
|
/**
* Module : Kero yearmonth adapter
* Author : Kvkens(yueming@yonyou.com)
* Date : 2016-08-10 14:11:50
*/
import {
YearMonth
} from 'tinper-neoui/src/neoui-yearmonth';
var YearMonthAdapter = u.BaseAdapter.extend({
init: function() {
var self = this;
this.validType = 'yearmonth';
this.format = this.getOption('format');
this.comp = new YearMonth({
el: this.element,
showFix: this.options.showFix,
format: this.format
});
this.comp.on('valueChange', function(event) {
self.slice = true;
self.dataModel.setValue(self.field, event.value);
self.slice = false;
});
},
modelValueChange: function(value) {
if (this.slice) return;
this.comp.setValue(value);
},
setEnable: function(enable) {}
});
if (u.compMgr)
u.compMgr.addDataAdapter({
adapter: YearMonthAdapter,
name: 'u-yearmonth'
});
export {
YearMonthAdapter
};
|
export default {
goto(stack) {
let jumpTo = stack.pop();
return {
stack,
jumpTo
};
},
jumpIfTrue(stack) {
let jumpTo = stack.pop(),
operand = stack.pop();
if (operand) {
return {
stack,
jumpTo
};
} else {
return {
stack
};
}
}
};
|
export Ticker from './ticker';
// export * as Ticker from './ticker'
|
Statistics.ConfigurationEditor.ChartConfigEditor =
Statistics.Class(Statistics.ConfigurationEditor, {
/**
* @private
* @property {JQueryElement}
* Contains the element to choose the dimension axis from
*/
dimensionSelect: null,
/**
* @override
* Called to draw the configuration editor
*
* @public
* @function
* @param {JQueryElement} div - The element to draw the editor on
*/
redraw: function() {
Statistics.ConfigurationEditor.prototype.redraw.apply(this, arguments);
var self = this;
this.dimensionSelect =
$("<select class='stats-dim-select'>"
+ "<option class='stats-dim-dummy' value='none'>" + Statistics.i18n('selectDimension') + "</option>"
+ "</select>").appendTo(this.div);
var metadata = this.configuration.getMetadata();
for(var i = 0, d; d = metadata.dimensions[i]; ++i)
this.dimensionSelect.append("<option class='stats-dim' value='" + d.id + "'>" + d.nameAbbr + "</option>");
this.dimensionSelect.change(function(){
if(!$(this).hasClass('.stats-dim-dummy')) {
var d = self.configuration.getDimensionById($(this).val())
self.updater.setProjectedDimensions( [d] );
}
});
// register events for listening dimension selection changes,
// to update the interface
this.configuration.events.bind(
'config::projectedDimensionsChanged',
$.proxy(this._selectSelectedDimension, this));
this._selectSelectedDimension();
},
/**
* @override
* Discard the changes
* @public
* @function
* @returns {Boolean} indicates if anything was discarded
*/
discardChanges: function() {
var changes = Statistics.ConfigurationEditor.prototype.discardChanges.apply(this, arguments);
if(changes) this._selectSelectedDimension();
return changes;
},
/**********************************************************************************
* ********************************************************************************
* Private methods
**********************************************************************************
**********************************************************************************/
/**
* @private
* @function
* Called to draw columns and rows
*/
_selectSelectedDimension: function(){
var dimensions = this.configuration.getSelectedDimensions();
var value = 'none';
if(dimensions.length > 0) value = dimensions[0].id;
//this.div.find('select').val( value );
this.dimensionSelect.val( value );
}
});
|
/**
* v0.0.1
*
* Copyright (c) 2017
*
* Date: 2017/5/10 by Heaven
*/
export default (content, wrapWidthNumber, contentSyle, languageName) => {
if (typeof content !== 'undefined' && typeof wrapWidthNumber !== 'undefined') {
const brTagCount = content.match(/<br>/g).length / 2; // at least two tags will cause blank line
const brTagheight = 44;
const wrodsCount = content.length;
// TODO 每行的字数由很多因素决定,font-family,font-size,letter-spacing,甚至是图片,hr标签等等,暂时没有考虑那么多
// the count of words per line is diffcult to decide due to font-family,font-size,
// letter-spacing even image,hr tag etc.so now we just judge simply
// assuming one word occupy averagely 13px for Chinese and 6px for English
// TODO 一行的行高也由很多因素决定,br标签个数,line-height,甚至是img标签
// the height of per line is also diffcult to decide
let perWordWidth;
let perLineHeight;
const { fontSize, lineHeight } = contentSyle;
switch (languageName.toLowerCase()) {
case 'zh-cn':
perWordWidth = +fontSize.substring(0, fontSize.indexOf('p'));
perLineHeight = perWordWidth * lineHeight;
break;
case 'en-us':
// TODO for English words,because most of them are not monospaced font,so we can't calculate easliy,
// TODO hope there is someone could help us
perWordWidth = 6;
perLineHeight = 26;
break;
}
const linesOfContent = wrodsCount / (wrapWidthNumber / perWordWidth);
const totalHeight = linesOfContent * perLineHeight + brTagCount * brTagheight;
// because we set the max-height of content to 400px
console.log(totalHeight);
return totalHeight > 400;
} else {
throw Error('you must provide the content and wrapWidthNumber arguments!');
}
};
|
var Plotly = require('@lib/index');
var Plots = require('@src/plots/plots');
var Lib = require('@src/lib');
var d3Select = require('../../strict-d3').select;
var d3SelectAll = require('../../strict-d3').selectAll;
var createGraphDiv = require('../assets/create_graph_div');
var destroyGraphDiv = require('../assets/destroy_graph_div');
var supplyAllDefaults = require('../assets/supply_defaults');
var hover = require('../assets/hover');
var assertHoverLabelContent = require('../assets/custom_assertions').assertHoverLabelContent;
var mock0 = {
open: [33.01, 33.31, 33.50, 32.06, 34.12, 33.05, 33.31, 33.50],
high: [34.20, 34.37, 33.62, 34.25, 35.18, 33.25, 35.37, 34.62],
low: [31.70, 30.75, 32.87, 31.62, 30.81, 32.75, 32.75, 32.87],
close: [34.10, 31.93, 33.37, 33.18, 31.18, 33.10, 32.93, 33.70]
};
var mock1 = Lib.extendDeep({}, mock0, {
x: [
'2016-09-01', '2016-09-02', '2016-09-03', '2016-09-04',
'2016-09-05', '2016-09-06', '2016-09-07', '2016-09-10'
]
});
describe('finance charts defaults:', function() {
'use strict';
function _supply(data, layout) {
var gd = {
data: data,
layout: layout
};
supplyAllDefaults(gd);
return gd;
}
it('should generated the correct number of full traces', function() {
var trace0 = Lib.extendDeep({}, mock0, {
type: 'ohlc'
});
var trace1 = Lib.extendDeep({}, mock1, {
type: 'candlestick'
});
var out = _supply([trace0, trace1]);
expect(out.data.length).toEqual(2);
// not sure this test is really necessary anymore, since these are real traces...
expect(out._fullData.length).toEqual(2);
});
it('should not mutate user data', function() {
var trace0 = Lib.extendDeep({}, mock0, {
type: 'ohlc'
});
var trace1 = Lib.extendDeep({}, mock1, {
type: 'candlestick'
});
var out = _supply([trace0, trace1]);
expect(out.data[0]).toBe(trace0);
expect(out.data[0].transforms).toBeUndefined();
expect(out.data[1]).toBe(trace1);
expect(out.data[1].transforms).toBeUndefined();
// ... and in an idempotent way
var out2 = _supply(out.data);
expect(out2.data[0]).toBe(trace0);
expect(out2.data[0].transforms).toBeUndefined();
expect(out2.data[1]).toBe(trace1);
expect(out2.data[1].transforms).toBeUndefined();
});
it('should work with transforms', function() {
var trace0 = Lib.extendDeep({}, mock1, {
type: 'ohlc',
transforms: [{
type: 'filter'
}]
});
var trace1 = Lib.extendDeep({}, mock0, {
type: 'candlestick',
transforms: [{
type: 'filter'
}]
});
var out = _supply([trace0, trace1]);
expect(out.data.length).toEqual(2);
expect(out._fullData.length).toEqual(2);
var transformTypesIn = out.data.map(function(trace) {
return trace.transforms.map(function(opts) {
return opts.type;
});
});
expect(transformTypesIn).toEqual([ ['filter'], ['filter'] ]);
var transformTypesOut = out._fullData.map(function(fullTrace) {
return fullTrace.transforms.map(function(opts) {
return opts.type;
});
});
expect(transformTypesOut).toEqual([ ['filter'], ['filter'] ]);
});
it('should not slice data arrays but record minimum supplied length', function() {
function assertDataLength(trace, fullTrace, len) {
expect(fullTrace.visible).toBe(true);
expect(fullTrace._length).toBe(len);
expect(fullTrace.open).toBe(trace.open);
expect(fullTrace.close).toBe(trace.close);
expect(fullTrace.high).toBe(trace.high);
expect(fullTrace.low).toBe(trace.low);
}
var trace0 = Lib.extendDeep({}, mock0, { type: 'ohlc' });
trace0.open = [33.01, 33.31, 33.50, 32.06, 34.12];
var trace1 = Lib.extendDeep({}, mock1, { type: 'candlestick' });
trace1.x = ['2016-09-01', '2016-09-02', '2016-09-03', '2016-09-04'];
var out = _supply([trace0, trace1]);
assertDataLength(trace0, out._fullData[0], 5);
assertDataLength(trace1, out._fullData[1], 4);
expect(out._fullData[0]._fullInput.x).toBeUndefined();
expect(out._fullData[1]._fullInput.x).toBeDefined();
});
it('should set visible to *false* when a component (other than x) is missing', function() {
var trace0 = Lib.extendDeep({}, mock0, { type: 'ohlc' });
trace0.close = undefined;
var trace1 = Lib.extendDeep({}, mock1, { type: 'candlestick' });
trace1.high = null;
var out = _supply([trace0, trace1]);
expect(out.data.length).toEqual(2);
expect(out._fullData.length).toEqual(2);
var visibilities = out._fullData.map(function(fullTrace) {
return fullTrace.visible;
});
expect(visibilities).toEqual([false, false]);
});
it('should return visible: false if any data component is empty', function() {
['ohlc', 'candlestick'].forEach(function(type) {
['open', 'high', 'low', 'close', 'x'].forEach(function(attr) {
var trace = Lib.extendDeep({}, mock1, {type: type});
trace[attr] = [];
var out = _supply([trace]);
expect(out._fullData[0].visible).toBe(false, type + ' - ' + attr);
});
});
});
it('direction *showlegend* should be inherited from trace-wide *showlegend*', function() {
var trace0 = Lib.extendDeep({}, mock0, {
type: 'ohlc',
showlegend: false,
});
var trace1 = Lib.extendDeep({}, mock1, {
type: 'candlestick',
showlegend: false,
increasing: { showlegend: true },
decreasing: { showlegend: true }
});
var out = _supply([trace0, trace1]);
var visibilities = out._fullData.map(function(fullTrace) {
return fullTrace.showlegend;
});
expect(visibilities).toEqual([false, false]);
});
it('direction *name* should be ignored if there\'s a trace-wide *name*', function() {
var trace0 = Lib.extendDeep({}, mock0, {
type: 'ohlc',
name: 'Company A'
});
var trace1 = Lib.extendDeep({}, mock1, {
type: 'candlestick',
name: 'Company B',
increasing: { name: 'B - UP' },
decreasing: { name: 'B - DOWN' }
});
var out = _supply([trace0, trace1]);
var names = out._fullData.map(function(fullTrace) {
return fullTrace.name;
});
expect(names).toEqual([
'Company A',
'Company B'
]);
});
it('trace *name* default should make reference to user data trace indices', function() {
var trace0 = Lib.extendDeep({}, mock0, {
type: 'ohlc'
});
var trace1 = { type: 'scatter' };
var trace2 = Lib.extendDeep({}, mock1, {
type: 'candlestick',
});
var trace3 = { type: 'bar' };
var out = _supply([trace0, trace1, trace2, trace3]);
var names = out._fullData.map(function(fullTrace) {
return fullTrace.name;
});
expect(names).toEqual([
'trace 0',
'trace 1',
'trace 2',
'trace 3'
]);
});
it('trace-wide styling should set default for corresponding per-direction styling', function() {
function assertLine(cont, width, dash) {
expect(cont.line.width).toEqual(width);
if(dash) expect(cont.line.dash).toEqual(dash);
}
var trace0 = Lib.extendDeep({}, mock0, {
type: 'ohlc',
line: { width: 1, dash: 'dash' },
decreasing: { line: { dash: 'dot' } }
});
var trace1 = Lib.extendDeep({}, mock1, {
type: 'candlestick',
line: { width: 3 },
increasing: { line: { width: 0 } }
});
var out = _supply([trace0, trace1]);
var fullData = out._fullData;
assertLine(fullData[0].increasing, 1, 'dash');
assertLine(fullData[0].decreasing, 1, 'dot');
assertLine(fullData[1].increasing, 0);
assertLine(fullData[1].decreasing, 3);
});
it('trace-wide *visible* should work', function() {
var trace0 = Lib.extendDeep({}, mock0, {
type: 'ohlc',
visible: 'legendonly'
});
var trace1 = Lib.extendDeep({}, mock1, {
type: 'candlestick',
visible: false
});
var out = _supply([trace0, trace1]);
var visibilities = out._fullData.map(function(fullTrace) {
return fullTrace.visible;
});
// only three items here as visible: false traces are not transformed
expect(visibilities).toEqual(['legendonly', false]);
});
it('should add a few layout settings by default', function() {
var trace0 = Lib.extendDeep({}, mock0, {
type: 'ohlc'
});
var layout0 = {};
var out0 = _supply([trace0], layout0);
expect(out0.layout.xaxis.rangeslider).toBeDefined();
expect(out0._fullLayout.xaxis.rangeslider.visible).toBe(true);
var trace1 = Lib.extendDeep({}, mock0, {
type: 'candlestick'
});
var layout1 = {
xaxis: { rangeslider: { visible: false }}
};
var out1 = _supply([trace1], layout1);
expect(out1.layout.xaxis.rangeslider).toBeDefined();
expect(out1._fullLayout.xaxis.rangeslider.visible).toBe(false);
});
it('pushes layout.calendar to all output traces', function() {
var trace0 = Lib.extendDeep({}, mock0, {
type: 'ohlc'
});
var trace1 = Lib.extendDeep({}, mock1, {
type: 'candlestick'
});
var out = _supply([trace0, trace1], {calendar: 'nanakshahi'});
out._fullData.forEach(function(fullTrace) {
expect(fullTrace.xcalendar).toBe('nanakshahi');
});
});
it('accepts a calendar per input trace', function() {
var trace0 = Lib.extendDeep({}, mock0, {
type: 'ohlc',
xcalendar: 'hebrew'
});
var trace1 = Lib.extendDeep({}, mock1, {
type: 'candlestick',
xcalendar: 'julian'
});
var out = _supply([trace0, trace1], {calendar: 'nanakshahi'});
out._fullData.forEach(function(fullTrace, i) {
expect(fullTrace.xcalendar).toBe(i < 1 ? 'hebrew' : 'julian');
});
});
it('should make empty candlestick traces autotype to *linear* (as opposed to real box traces)', function() {
var trace0 = { type: 'candlestick' };
var out = _supply([trace0], { xaxis: {} });
expect(out._fullLayout.xaxis.type).toEqual('linear');
});
});
describe('finance charts calc', function() {
'use strict';
function calcDatatoTrace(calcTrace) {
return calcTrace[0].trace;
}
function _calcGd(data, layout) {
var gd = {
data: data,
layout: layout || {}
};
supplyAllDefaults(gd);
Plots.doCalcdata(gd);
gd.calcdata.forEach(function(cd) {
// fill in some stuff that happens during crossTraceCalc or plot
if(cd[0].trace.type === 'candlestick') {
var diff = cd[1].pos - cd[0].pos;
cd[0].t.wHover = diff / 2;
cd[0].t.bdPos = diff / 4;
}
});
return gd;
}
function _calcRaw(data, layout) {
return _calcGd(data, layout).calcdata;
}
function _calc(data, layout) {
return _calcRaw(data, layout).map(calcDatatoTrace);
}
// add some points that shouldn't make it into calcdata because
// one of o, h, l, c is not numeric
function addJunk(trace) {
// x filtering happens in other ways
if(trace.x) trace.x.push(1, 1, 1, 1);
trace.open.push('', 1, 1, 1);
trace.high.push(1, null, 1, 1);
trace.low.push(1, 1, [1], 1);
trace.close.push(1, 1, 1, 'close');
}
function mapGet(array, attr) {
return array.map(function(di) { return di[attr]; });
}
it('should fill when *x* is not present', function() {
var trace0 = Lib.extendDeep({}, mock0, {
type: 'ohlc',
});
addJunk(trace0);
var trace1 = Lib.extendDeep({}, mock0, {
type: 'candlestick',
});
addJunk(trace1);
var out = _calcRaw([trace0, trace1]);
var indices = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
var i = 'increasing';
var d = 'decreasing';
var directions = [i, d, d, i, d, i, d, i, undefined, undefined, undefined, undefined];
var empties = [
undefined, undefined, undefined, undefined,
undefined, undefined, undefined, undefined,
true, true, true, true
];
expect(mapGet(out[0], 'pos')).toEqual(indices);
expect(mapGet(out[0], 'dir')).toEqual(directions);
expect(mapGet(out[1], 'pos')).toEqual(indices);
expect(mapGet(out[1], 'dir')).toEqual(directions);
expect(mapGet(out[0], 'empty')).toEqual(empties);
expect(mapGet(out[1], 'empty')).toEqual(empties);
});
it('should work with *filter* transforms', function() {
var trace0 = Lib.extendDeep({}, mock1, {
type: 'ohlc',
tickwidth: 0.05,
transforms: [{
type: 'filter',
operation: '>',
target: 'open',
value: 33
}]
});
var trace1 = Lib.extendDeep({}, mock1, {
type: 'candlestick',
transforms: [{
type: 'filter',
operation: '{}',
target: 'x',
value: ['2016-09-01', '2016-09-10']
}]
});
var out = _calc([trace0, trace1]);
expect(out.length).toEqual(2);
expect(out[0].x).toEqual([
'2016-09-01', '2016-09-02', '2016-09-03', '2016-09-05', '2016-09-06', '2016-09-07', '2016-09-10'
]);
expect(out[0].open).toEqual([
33.01, 33.31, 33.50, 34.12, 33.05, 33.31, 33.50
]);
expect(out[1].x).toEqual([
'2016-09-01', '2016-09-10'
]);
expect(out[1].close).toEqual([
34.10, 33.70
]);
});
it('should work with *groupby* transforms (ohlc)', function() {
var opts = {
type: 'groupby',
groups: ['b', 'b', 'b', 'a'],
};
var trace0 = Lib.extendDeep({}, mock1, {
type: 'ohlc',
tickwidth: 0.05,
transforms: [opts]
});
var out = _calc([trace0]);
expect(out.length).toBe(2);
expect(out[0].name).toBe('b');
expect(out[0].x).toEqual([
'2016-09-01', '2016-09-02', '2016-09-03'
]);
expect(out[0].open).toEqual([
33.01, 33.31, 33.5
]);
expect(out[1].name).toBe('a');
expect(out[1].x).toEqual([
'2016-09-04'
]);
expect(out[1].open).toEqual([
32.06
]);
});
it('should work with *groupby* transforms (candlestick)', function() {
var opts = {
type: 'groupby',
groups: ['a', 'b', 'b', 'a'],
};
var trace0 = Lib.extendDeep({}, mock1, {
type: 'candlestick',
transforms: [opts]
});
var out = _calc([trace0]);
expect(out[0].name).toEqual('a');
expect(out[0].x).toEqual([
'2016-09-01', '2016-09-04'
]);
expect(out[0].open).toEqual([
33.01, 32.06
]);
expect(out[1].name).toEqual('b');
expect(out[1].x).toEqual([
'2016-09-02', '2016-09-03'
]);
expect(out[1].open).toEqual([
33.31, 33.5
]);
});
it('should use the smallest trace minimum x difference to convert *tickwidth* to data coords for all traces attached to a given x-axis', function() {
var trace0 = Lib.extendDeep({}, mock1, {
type: 'ohlc'
});
var trace1 = Lib.extendDeep({}, mock1, {
type: 'ohlc',
// shift time coordinates by 10 hours
x: mock1.x.map(function(d) { return d + ' 10:00'; })
});
var out = _calcRaw([trace0, trace1]);
var oneDay = 1000 * 3600 * 24;
expect(out[0][0].t.tickLen).toBeCloseTo(oneDay * 0.3, 0);
expect(out[0][0].t.wHover).toBeCloseTo(oneDay * 0.5, 0);
expect(out[1][0].t.tickLen).toBe(out[0][0].t.tickLen);
expect(out[1][0].t.wHover).toBe(out[0][0].t.wHover);
});
it('works with category x data', function() {
// see https://github.com/plotly/plotly.js/issues/2004
// fixed automatically as part of the refactor to a non-transform trace
var trace0 = Lib.extendDeep({}, mock0, {
type: 'ohlc',
x: ['a', 'b', 'c', 'd', 'e']
});
var out = _calcRaw([trace0]);
expect(out[0][0].t.tickLen).toBeCloseTo(0.3, 5);
expect(out[0][0].t.wHover).toBeCloseTo(0.5, 5);
});
it('should fallback to a spacing of 1 in one-item traces', function() {
var trace0 = Lib.extendDeep({}, mock0, {
type: 'ohlc',
x: ['2016-01-01']
});
var trace1 = Lib.extendDeep({}, mock0, {
type: 'ohlc',
x: [10],
xaxis: 'x2'
});
var out = _calcRaw([trace0, trace1]);
expect(out[0][0].t.tickLen).toBeCloseTo(0.3, 5);
expect(out[0][0].t.wHover).toBeCloseTo(0.5, 5);
expect(out[1][0].t.tickLen).toBeCloseTo(0.3, 5);
expect(out[1][0].t.wHover).toBeCloseTo(0.5, 5);
});
it('should handle cases where \'open\' and \'close\' entries are equal', function() {
var out = _calcRaw([{
type: 'ohlc',
open: [0, 1, 0, 2, 1, 1, 2, 2],
high: [3, 3, 3, 3, 3, 3, 3, 3],
low: [-1, -1, -1, -1, -1, -1, -1, -1],
close: [0, 2, 0, 1, 1, 1, 2, 2],
tickwidth: 0
}, {
type: 'candlestick',
open: [0, 2, 0, 1],
high: [3, 3, 3, 3],
low: [-1, -1, -1, -1],
close: [0, 1, 0, 2]
}]);
expect(mapGet(out[0], 'dir')).toEqual([
'increasing', 'increasing', 'decreasing', 'decreasing',
'decreasing', 'decreasing', 'increasing', 'increasing'
]);
expect(mapGet(out[1], 'dir')).toEqual([
'increasing', 'decreasing', 'decreasing', 'increasing'
]);
});
it('should include finance hover labels prefix in calcdata', function() {
['candlestick', 'ohlc'].forEach(function(type) {
var trace0 = Lib.extendDeep({}, mock0, {
type: type,
});
var out = _calcRaw([trace0]);
expect(out[0][0].t.labels).toEqual({
open: 'open: ',
high: 'high: ',
low: 'low: ',
close: 'close: '
});
});
});
});
describe('finance charts auto-range', function() {
var gd;
beforeEach(function() { gd = createGraphDiv(); });
afterEach(destroyGraphDiv);
describe('should give correct results with trailing nulls', function() {
var base = {
x: ['time1', 'time2', 'time3'],
high: [10, 11, null],
close: [5, 6, null],
low: [3, 3, null],
open: [4, 4, null]
};
it('- ohlc case', function(done) {
var trace = Lib.extendDeep({}, base, {type: 'ohlc'});
Plotly.newPlot(gd, [trace]).then(function() {
expect(gd._fullLayout.xaxis.range).toBeCloseToArray([-0.5, 2.5], 1);
})
.then(done, done.fail);
});
it('- candlestick case', function(done) {
var trace = Lib.extendDeep({}, base, {type: 'candlestick'});
Plotly.newPlot(gd, [trace]).then(function() {
expect(gd._fullLayout.xaxis.range).toBeCloseToArray([-0.5, 2.5], 1);
})
.then(done, done.fail);
});
});
});
describe('finance charts updates:', function() {
'use strict';
var gd;
beforeEach(function() {
gd = createGraphDiv();
});
afterEach(function() {
Plotly.purge(gd);
destroyGraphDiv();
});
function countOHLCTraces() {
return d3Select('g.cartesianlayer').selectAll('g.trace.ohlc').size();
}
function countBoxTraces() {
return d3Select('g.cartesianlayer').selectAll('g.trace.boxes').size();
}
function countRangeSliders() {
return d3Select('g.rangeslider-rangeplot').size();
}
it('Plotly.restyle should work', function(done) {
var trace0 = Lib.extendDeep({}, mock0, { type: 'ohlc' });
var path0;
Plotly.newPlot(gd, [trace0]).then(function() {
expect(gd.calcdata[0][0].t.tickLen).toBeCloseTo(0.3, 5);
expect(gd.calcdata[0][0].o).toEqual(33.01);
return Plotly.restyle(gd, 'tickwidth', 0.5);
})
.then(function() {
expect(gd.calcdata[0][0].t.tickLen).toBeCloseTo(0.5, 5);
return Plotly.restyle(gd, 'open', [[0, 30.75, 32.87, 31.62, 30.81, 32.75, 32.75, 32.87]]);
})
.then(function() {
expect(gd.calcdata[0][0].o).toEqual(0);
return Plotly.restyle(gd, {
type: 'candlestick',
open: [[33.01, 33.31, 33.50, 32.06, 34.12, 33.05, 33.31, 33.50]]
});
})
.then(function() {
path0 = d3Select('path.box').attr('d');
expect(path0).toBeDefined();
return Plotly.restyle(gd, 'whiskerwidth', 0.2);
})
.then(function() {
expect(d3Select('path.box').attr('d')).not.toEqual(path0);
})
.then(done, done.fail);
});
it('should be able to toggle visibility', function(done) {
var data = [
Lib.extendDeep({}, mock0, { type: 'ohlc' }),
Lib.extendDeep({}, mock0, { type: 'candlestick' }),
];
Plotly.newPlot(gd, data).then(function() {
expect(countOHLCTraces()).toEqual(1);
expect(countBoxTraces()).toEqual(1);
return Plotly.restyle(gd, 'visible', false);
})
.then(function() {
expect(countOHLCTraces()).toEqual(0);
expect(countBoxTraces()).toEqual(0);
return Plotly.restyle(gd, 'visible', 'legendonly', [1]);
})
.then(function() {
expect(countOHLCTraces()).toEqual(0);
expect(countBoxTraces()).toEqual(0);
return Plotly.restyle(gd, 'visible', true, [1]);
})
.then(function() {
expect(countOHLCTraces()).toEqual(0);
expect(countBoxTraces()).toEqual(1);
return Plotly.restyle(gd, 'visible', true, [0]);
})
.then(function() {
expect(countOHLCTraces()).toEqual(1);
expect(countBoxTraces()).toEqual(1);
return Plotly.restyle(gd, 'visible', 'legendonly', [0]);
})
.then(function() {
expect(countOHLCTraces()).toEqual(0);
expect(countBoxTraces()).toEqual(1);
return Plotly.restyle(gd, 'visible', true);
})
.then(function() {
expect(countOHLCTraces()).toEqual(1);
expect(countBoxTraces()).toEqual(1);
})
.then(done, done.fail);
});
it('Plotly.relayout should work', function(done) {
var trace0 = Lib.extendDeep({}, mock0, { type: 'ohlc' });
Plotly.newPlot(gd, [trace0]).then(function() {
expect(countRangeSliders()).toEqual(1);
return Plotly.relayout(gd, 'xaxis.rangeslider.visible', false);
})
.then(function() {
expect(countRangeSliders()).toEqual(0);
})
.then(done, done.fail);
});
it('Plotly.extendTraces should work', function(done) {
var data = [
Lib.extendDeep({}, mock0, { type: 'ohlc' }),
Lib.extendDeep({}, mock0, { type: 'candlestick' }),
];
Plotly.newPlot(gd, data).then(function() {
expect(gd.calcdata[0].length).toEqual(8);
expect(gd.calcdata[1].length).toEqual(8);
return Plotly.extendTraces(gd, {
open: [[ 34, 35 ]],
high: [[ 40, 41 ]],
low: [[ 32, 33 ]],
close: [[ 38, 39 ]]
}, [1]);
})
.then(function() {
expect(gd.calcdata[0].length).toEqual(8);
expect(gd.calcdata[1].length).toEqual(10);
return Plotly.extendTraces(gd, {
open: [[ 34, 35 ]],
high: [[ 40, 41 ]],
low: [[ 32, 33 ]],
close: [[ 38, 39 ]]
}, [0]);
})
.then(function() {
expect(gd.calcdata[0].length).toEqual(10);
expect(gd.calcdata[1].length).toEqual(10);
})
.then(done, done.fail);
});
it('Plotly.deleteTraces / addTraces should work', function(done) {
var data = [
Lib.extendDeep({}, mock0, { type: 'ohlc' }),
Lib.extendDeep({}, mock0, { type: 'candlestick' }),
];
Plotly.newPlot(gd, data).then(function() {
expect(countOHLCTraces()).toEqual(1);
expect(countBoxTraces()).toEqual(1);
return Plotly.deleteTraces(gd, [1]);
})
.then(function() {
expect(countOHLCTraces()).toEqual(1);
expect(countBoxTraces()).toEqual(0);
return Plotly.deleteTraces(gd, [0]);
})
.then(function() {
expect(countOHLCTraces()).toEqual(0);
expect(countBoxTraces()).toEqual(0);
var trace = Lib.extendDeep({}, mock0, { type: 'candlestick' });
return Plotly.addTraces(gd, [trace]);
})
.then(function() {
expect(countOHLCTraces()).toEqual(0);
expect(countBoxTraces()).toEqual(1);
var trace = Lib.extendDeep({}, mock0, { type: 'ohlc' });
return Plotly.addTraces(gd, [trace]);
})
.then(function() {
expect(countOHLCTraces()).toEqual(1);
expect(countBoxTraces()).toEqual(1);
})
.then(done, done.fail);
});
it('Plotly.addTraces + Plotly.relayout should update candlestick box position values', function(done) {
function assertBoxPosFields(bPos) {
expect(gd.calcdata.length).toEqual(bPos.length);
gd.calcdata.forEach(function(calcTrace, i) {
expect(calcTrace[0].t.bPos).toBeCloseTo(bPos[i], 0);
});
}
var trace0 = {
type: 'candlestick',
x: ['2011-01-01', '2011-01-02'],
open: [1, 2],
high: [3, 4],
low: [0, 1],
close: [2, 3]
};
Plotly.newPlot(gd, [trace0], {boxmode: 'group'})
.then(function() {
assertBoxPosFields([0]);
return Plotly.addTraces(gd, [Lib.extendDeep({}, trace0)]);
})
.then(function() {
assertBoxPosFields([-15120000, 15120000]);
var update = {
type: 'candlestick',
x: [['2011-01-01', '2011-01-05'], ['2011-01-01', '2011-01-03']],
open: [[1, 0]],
high: [[3, 2]],
low: [[0, -1]],
close: [[2, 1]]
};
return Plotly.restyle(gd, update);
})
.then(function() {
assertBoxPosFields([-30240000, 30240000]);
})
.then(done, done.fail);
});
it('Plotly.newPlot with data-less trace and adding with Plotly.restyle', function(done) {
var data = [
{ type: 'candlestick' },
{ type: 'ohlc' },
{ type: 'bar', y: [2, 1, 2] }
];
Plotly.newPlot(gd, data).then(function() {
expect(countOHLCTraces()).toEqual(0);
expect(countBoxTraces()).toEqual(0);
expect(countRangeSliders()).toEqual(0);
return Plotly.restyle(gd, {
open: [mock0.open],
high: [mock0.high],
low: [mock0.low],
close: [mock0.close]
}, [0]);
})
.then(function() {
expect(countOHLCTraces()).toEqual(0);
expect(countBoxTraces()).toEqual(1);
expect(countRangeSliders()).toEqual(1);
return Plotly.restyle(gd, {
open: [mock0.open],
high: [mock0.high],
low: [mock0.low],
close: [mock0.close]
}, [1]);
})
.then(function() {
expect(countOHLCTraces()).toEqual(1);
expect(countBoxTraces()).toEqual(1);
expect(countRangeSliders()).toEqual(1);
})
.then(done, done.fail);
});
it('should be able to update ohlc tickwidth', function(done) {
var trace0 = Lib.extendDeep({}, mock0, {type: 'ohlc'});
function _assert(msg, exp) {
var tickLen = gd.calcdata[0][0].t.tickLen;
expect(tickLen)
.toBe(exp.tickLen, 'tickLen val in calcdata - ' + msg);
var pathd = d3Select(gd).select('.ohlc > path').attr('d');
expect(pathd)
.toBe(exp.pathd, 'path d attr - ' + msg);
}
Plotly.newPlot(gd, [trace0], {
xaxis: { rangeslider: {visible: false} }
})
.then(function() {
_assert('auto rng / base tickwidth', {
tickLen: 0.3,
pathd: 'M13.5,137.63H33.75M33.75,75.04V206.53M54,80.3H33.75'
});
return Plotly.restyle(gd, 'tickwidth', 0);
})
.then(function() {
_assert('auto rng / no tickwidth', {
tickLen: 0,
pathd: 'M33.75,137.63H33.75M33.75,75.04V206.53M33.75,80.3H33.75'
});
return Plotly.update(gd, {
tickwidth: null
}, {
'xaxis.range': [0, 8],
'yaxis.range': [30, 36]
});
})
.then(function() {
_assert('set rng / base tickwidth', {
tickLen: 0.3,
pathd: 'M-20.25,134.55H0M0,81V193.5M20.25,85.5H0'
});
return Plotly.restyle(gd, 'tickwidth', 0);
})
.then(function() {
_assert('set rng / no tickwidth', {
tickLen: 0,
pathd: 'M0,134.55H0M0,81V193.5M0,85.5H0'
});
})
.then(done, done.fail);
});
it('should work with typed array', function(done) {
var mockTA = {
open: new Float32Array(mock0.open),
high: new Float32Array(mock0.high),
low: new Float32Array(mock0.low),
close: new Float32Array(mock0.close)
};
var dataTA = [
Lib.extendDeep({}, mockTA, {type: 'ohlc'}),
Lib.extendDeep({}, mockTA, {type: 'candlestick'}),
];
var data0 = [
Lib.extendDeep({}, mock0, {type: 'ohlc'}),
Lib.extendDeep({}, mock0, {type: 'candlestick'}),
];
Plotly.newPlot(gd, dataTA)
.then(function() {
expect(countOHLCTraces()).toBe(1, '# of ohlc traces');
expect(countBoxTraces()).toBe(1, '# of candlestick traces');
})
.then(function() { return Plotly.react(gd, data0); })
.then(function() {
expect(countOHLCTraces()).toBe(1, '# of ohlc traces');
expect(countBoxTraces()).toBe(1, '# of candlestick traces');
})
.then(done, done.fail);
});
});
describe('finance charts *special* handlers:', function() {
// not special anymore - just test that they work as normal
afterEach(destroyGraphDiv);
it('`editable: true` handlers should work', function(done) {
var gd = createGraphDiv();
function editText(itemNumber, newText) {
var textNode = d3SelectAll('text.legendtext')
.filter(function(_, i) { return i === itemNumber; }).node();
textNode.dispatchEvent(new window.MouseEvent('click'));
var editNode = d3Select('.plugin-editable.editable').node();
editNode.dispatchEvent(new window.FocusEvent('focus'));
editNode.textContent = newText;
editNode.dispatchEvent(new window.FocusEvent('focus'));
editNode.dispatchEvent(new window.FocusEvent('blur'));
}
// makeEditable in svg_text_utils clears the edit <div> in
// a 0-second transition, so push the resolve call at the back
// of the rendering queue to make sure the edit <div> is properly
// cleared after each mocked text edits.
function delayedResolve(resolve) {
setTimeout(function() { return resolve(gd); }, 0);
}
Plotly.newPlot(gd, [
Lib.extendDeep({}, mock0, { type: 'ohlc' }),
Lib.extendDeep({}, mock0, { type: 'candlestick' })
], {}, {
editable: true
})
.then(function(gd) {
return new Promise(function(resolve) {
gd.once('plotly_restyle', function(eventData) {
expect(eventData[0].name).toEqual('0');
expect(eventData[1]).toEqual([0]);
delayedResolve(resolve);
});
editText(0, '0');
});
})
.then(function(gd) {
return new Promise(function(resolve) {
gd.once('plotly_restyle', function(eventData) {
expect(eventData[0].name).toEqual('1');
expect(eventData[1]).toEqual([1]);
delayedResolve(resolve);
});
editText(1, '1');
});
})
.then(done, done.fail);
});
});
describe('finance trace hover:', function() {
var gd;
afterEach(destroyGraphDiv);
function run(specs) {
gd = createGraphDiv();
var data = specs.traces.map(function(t) {
return Lib.extendFlat({
type: specs.type,
open: [1, 2],
close: [2, 3],
high: [3, 4],
low: [0, 5]
}, t);
});
var layout = Lib.extendFlat({
showlegend: false,
width: 400,
height: 400,
margin: {t: 0, b: 0, l: 0, r: 0, pad: 0}
}, specs.layout || {});
var xval = 'xval' in specs ? specs.xval : 0;
var yval = 'yval' in specs ? specs.yval : 1;
var hovermode = layout.hovermode || 'x';
return Plotly.newPlot(gd, data, layout).then(function() {
var results = gd.calcdata.map(function(cd) {
var trace = cd[0].trace;
var pointData = {
index: false,
distance: 20,
cd: cd,
trace: trace,
xa: gd._fullLayout.xaxis,
ya: gd._fullLayout.yaxis,
maxHoverDistance: 20
};
var pts = trace._module.hoverPoints(pointData, xval, yval, hovermode);
return pts ? pts[0] : {distance: Infinity};
});
var actual = results[0];
var exp = specs.exp;
for(var k in exp) {
var msg = '- key ' + k;
expect(actual[k]).toBe(exp[k], msg);
}
});
}
['ohlc', 'candlestick'].forEach(function(type) {
[{
type: type,
desc: 'basic',
traces: [{}],
exp: {
extraText: 'open: 1<br>high: 3<br>low: 0<br>close: 2 ▲'
}
}, {
type: type,
desc: 'with scalar text',
traces: [{text: 'SCALAR'}],
exp: {
extraText: 'open: 1<br>high: 3<br>low: 0<br>close: 2 ▲<br>SCALAR'
}
}, {
type: type,
desc: 'with array text',
traces: [{text: ['A', 'B']}],
exp: {
extraText: 'open: 1<br>high: 3<br>low: 0<br>close: 2 ▲<br>A'
}
}, {
type: type,
desc: 'just scalar text',
traces: [{hoverinfo: 'text', text: 'SCALAR'}],
exp: {
extraText: 'SCALAR'
}
}, {
type: type,
desc: 'just array text',
traces: [{hoverinfo: 'text', text: ['A', 'B']}],
exp: {
extraText: 'A'
}
}, {
type: type,
desc: 'just scalar hovertext',
traces: [{hoverinfo: 'text', hovertext: 'SCALAR', text: 'NOP'}],
exp: {
extraText: 'SCALAR'
}
}, {
type: type,
desc: 'just array hovertext',
traces: [{hoverinfo: 'text', hovertext: ['A', 'B'], text: ['N', 'O', 'P']}],
exp: {
extraText: 'A'
}
}, {
type: type,
desc: 'just array text with array hoverinfo',
traces: [{hoverinfo: ['text', 'text'], text: ['A', 'B']}],
exp: {
extraText: 'A'
}
}, {
type: type,
desc: 'when high === low in *closest* mode',
traces: [{
high: [6, null, 7, 8],
close: [4, null, 7, 8],
low: [5, null, 7, 8],
open: [3, null, 7, 8]
}],
layout: {hovermode: 'closest'},
xval: 2,
yval: 6.9,
exp: {
extraText: 'open: 7<br>high: 7<br>low: 7<br>close: 7 ▲'
}
}]
.forEach(function(specs) {
it('should generate correct hover labels ' + type + ' - ' + specs.desc, function(done) {
run(specs).then(done, done.fail);
});
});
});
});
describe('finance trace hover via Fx.hover():', function() {
var gd;
beforeEach(function() { gd = createGraphDiv(); });
afterEach(destroyGraphDiv);
['candlestick', 'ohlc'].forEach(function(type) {
it('should pick correct ' + type + ' item', function(done) {
var x = ['hover ok!', 'time2', 'hover off by 1', 'time4'];
Plotly.newPlot(gd, [{
x: x,
high: [6, null, 7, 8],
close: [4, null, 7, 8],
low: [5, null, 7, 8],
open: [3, null, 7, 8],
type: type
}, {
x: x,
y: [1, null, 2, 3],
type: 'bar'
}], {
xaxis: { rangeslider: {visible: false} },
width: 500,
height: 500
})
.then(function() {
gd.on('plotly_hover', function(d) {
Plotly.Fx.hover(gd, [
{curveNumber: 0, pointNumber: d.points[0].pointNumber},
{curveNumber: 1, pointNumber: d.points[0].pointNumber}
]);
});
})
.then(function() { hover(281, 252); })
.then(function() {
assertHoverLabelContent({
nums: [
'hover off by 1\nopen: 7\nhigh: 7\nlow: 7\nclose: 7 ▲',
'(hover off by 1, 2)'
],
name: ['trace 0', 'trace 1']
}, 'hover over 3rd items (aka 2nd visible items)');
})
.then(function() {
Lib.clearThrottle();
return Plotly.react(gd, [gd.data[0]], gd.layout);
})
.then(function() { hover(281, 252); })
.then(function() {
assertHoverLabelContent({
nums: 'hover off by 1\nopen: 7\nhigh: 7\nlow: 7\nclose: 7 ▲',
name: ''
}, 'after removing 2nd trace');
})
.then(done, done.fail);
});
it('should ignore empty ' + type + ' item', function(done) {
// only the bar chart's hover will be displayed when hovering over the 3rd items
var x = ['time1', 'time2', 'time3', 'time4'];
Plotly.newPlot(gd, [{
x: x,
high: [6, 3, null, 8],
close: [4, 3, null, 8],
low: [5, 3, null, 8],
open: [3, 3, null, 8],
type: type
}, {
x: x,
y: [1, 2, 3, 4],
type: 'bar'
}], {
xaxis: { rangeslider: {visible: false} },
width: 500,
height: 500
})
.then(function() {
gd.on('plotly_hover', function(d) {
Plotly.Fx.hover(gd, [
{curveNumber: 0, pointNumber: d.points[0].pointNumber},
{curveNumber: 1, pointNumber: d.points[0].pointNumber}
]);
});
})
.then(function() { hover(281, 252); })
.then(function() {
assertHoverLabelContent({
nums: '(time3, 3)',
name: 'trace 1'
}, 'hover over 3rd items');
})
.then(done, done.fail);
});
});
});
|
/*
* grunt-timestamp-release
* https://github.com/kyrstenkelly/grunt-timestamp-release
*
* Copyright (c) 2014 Kyrsten
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
var moment = require('moment'),
shell = require('shelljs'),
q = require('q');
grunt.registerTask('timestampRelease', 'Release a timestamped version.', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
files: ['package.json'],
commit: true,
tag: true,
tagPrefix: '',
tagSuffix: '',
tagFormat: 'YYYY-MM-DD--hh-mm',
push: true,
pushTo: 'origin'
}),
VERSION_REGEXP = /([\'|\"]?version[\'|\"]?[ ]*:[ ]*[\'|\"]?)([\d||A-a|.|-]*)([\'|\"]?)/i,
timestampVersion = grunt.option('timestamp') || moment(new Date()).format(options.tagFormat),
testRun = grunt.option('test-run') || false,
done = this.async(),
fileNames = '',
commitMessage,
tagMessage,
templateOpts,
prefix,
suffix;
prefix = grunt.option('tagPrefix') || options.tagPrefix || '';
suffix = grunt.option('tagSuffix') || options.tagSuffix || '';
options.name = grunt.option('name') || grunt.config.get('name') || null;
options.email = grunt.option('email') || grunt.config.get('email') || null;
commitMessage = grunt.config.getRaw('timestampRelease.options.commitMessage') ||
'Release <%= timestamp %>';
tagMessage = grunt.config.getRaw('timestampRelease.options.tagMessage') ||
'Release <%= timestamp %>';
templateOpts = {data: {timestamp: timestampVersion, name: options.name,
email: options.email}};
try {
options.commitMessage = grunt.template.process(commitMessage, templateOpts);
} catch (e) {
grunt.fail.warn('There was an error processing your commit message.');
}
try {
options.tagMessage = grunt.template.process(tagMessage, templateOpts);
} catch (e) {
grunt.fail.warn('There was an error processing your tag message.');
}
options.files.forEach(function(fileName) {
fileNames = fileNames + fileName + ' ';
});
function ifSet(option, fn) {
if (options[option]) {
return fn;
}
}
function run(command, message) {
var deferred = q.defer(),
success;
grunt.verbose.writeln('Running: ' + command);
if (testRun) {
success = true;
} else {
success = shell.exec(command, {silent: true});
}
if (success) {
grunt.log.ok(message || command);
deferred.resolve();
} else {
deferred.reject('Failed during: ' + command);
}
return deferred.promise;
}
function timestamp() {
return q.fcall(function() {
grunt.file.expand(options.files).forEach(function(file) {
var content = grunt.file.read(file).replace(VERSION_REGEXP, function(match, pre, version, post) {
return pre + timestampVersion + post;
});
grunt.file.write(file, content);
grunt.log.ok('Updating version in ' + file);
});
});
}
function add() {
return run('git add ' + fileNames, 'Adding ' + fileNames);
}
function commit() {
return run('git commit -m "' + options.commitMessage + '"', 'Committing ' + fileNames);
}
function tag() {
return run('git tag -s ' + prefix + timestampVersion + suffix + ' -m "'
+ options.tagMessage + '"', 'Tagging ' + prefix + timestampVersion + suffix);
}
function push() {
return run('git pull --rebase ' + options.pushTo +
' "$(git rev-parse --symbolic-full-name HEAD)";git push ' + options.pushTo);
}
function pushTags() {
return run('git push ' + options.pushTo + ' --tags');
}
if (testRun) {
grunt.log.ok('Running as a test run!');
}
q().then(timestamp)
.then(ifSet('commit', add))
.then(ifSet('commit', commit))
.then(ifSet('tag', tag))
.then(ifSet('push', push))
.then(ifSet('push', pushTags))
.catch(function(message) {
grunt.fail.warn(message || 'Timestamp release failed');
})
.finally(done);
});
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:c4643b6aa9f78824dad93fb7dcda185b074be81a6d65262cdc0caf03a4fdfcc2
size 5146
|
function errorMessage(configObj){
this.timeToDisappear = configObj.timeToDisappear;
this.messageType = configObj.messageType || 0;
this.message = configObj.message;
this.messagePos = configObj.pos;
this.messageRot = configObj.rot || new THREE.Quaternion();
if(typeof configObj.scale !== 'undefined'){
this.scale = new THREE.Vector3(configObj.scale, configObj.scale, configObj.scale);
}else{
this.scale = new THREE.Vector3(1, 1, 1);
}
this.arrowSide = configObj.arrowSide || "down";
this.moveDirection = new THREE.Vector3(0, 50, 0);
displayMessage(this);
}
var prevMessageTimeout = null;
function displayMessage(messages){
if(prevMessageTimeout !== false){
clearTimeout(prevMessageTimeout);
}
prevMessageTimeout = window.setTimeout(function(){
if(typeof messages.length === "undefined"){
messages = [messages];
}
for(var i=0; i<messages.length; i++){
messages[i].scale = messages[i].scale || new THREE.Vector3(1, 1, 1);
messages[i].arrowSide = messages[i].arrowSide || "down";
messages[i].moveDirection = new THREE.Vector3(0, 50, 0);
displayMessageSingle(messages[i]);
}
prevMessageTimeout = false;
}, 100);
}
function displayMessageSingle(message){
message.mesh = createMessage(message.message, message.messageType, message.arrowSide);
sim.scene.add(message.mesh);
//change this so it's always pointing at the player
message.mesh.lookAt(globalPlayerHead.position);
//message.mesh.quaternion.copy(message.messageRot);
var toPos = new THREE.Vector3();
var fromPos = new THREE.Vector3();
toPos.copy(message.messagePos);
fromPos.copy(message.messagePos);
message.mesh.scale.copy(message.scale);
message.moveDirection.multiplyScalar(message.scale.x);
toPos.add(message.moveDirection);
var toPosTween = new TWEEN.Tween(fromPos).to(toPos, 1000);
toPosTween.onUpdate(function(){
message.mesh.position.copy(fromPos);
});
toPosTween.easing(TWEEN.Easing.Elastic.InOut);
window.setTimeout(function(){
sim.scene.remove(message.mesh);
}, message.timeToDisappear);
toPosTween.start();
}
function createMessage(text, type, direction){
var canvasEl = document.createElement('canvas');
canvasEl.width = 200;
canvasEl.height = 100;
var textArea = canvasEl.getContext('2d');
textArea.font = "42px Arial";
//check to see if we need to resize the canvas
if(textArea.measureText(text).width > canvasEl.width){
canvasEl.width = textArea.measureText(text).width + 40;
console.log(canvasEl.width);
textArea = canvasEl.getContext('2d');
textArea.font = "42px Arial";
}
var fillColor;
var textColor;
switch(type){
case 0:
//error message
fillColor = "rgba(232, 27, 27, 1)";
textColor = "rgba(255,255,255,1)";
break;
case 1:
//info message
fillColor = "rgba(134, 175, 217, 1)";
textColor = "rgba(255, 255, 255, 1)";
break;
case 2:
//bet message
fillColor = "rgba(0, 153, 0, 1)";
textColor = "rgba(255, 255, 255, 1)";
break;
case 3:
//winning hand cardInfo
fillColor = "rgba(255, 255, 255, 1)";
textColor = "rgba(0, 0, 0, 1)";
break;
default:
console.error("No message color specified for message type ", type);
break;
}
textArea.fillStyle = fillColor;
textArea.beginPath();
textArea.rect(0, 0, canvasEl.width, canvasEl.height);
textArea.fill();
//textArea.fillRect(0, 0, canvasEl.width, canvasEl.height);
textArea.fillStyle = textColor;
textArea.textAlign = "center";
textArea.textBaseline = "middle";
textArea.fillText(text, canvasEl.width/2, canvasEl.height/2);
var material = new THREE.MeshBasicMaterial({map: new THREE.Texture(canvasEl)});
var meshfront = new THREE.Mesh(new THREE.PlaneGeometry(canvasEl.width/3, canvasEl.height/3), material);
var meshback = new THREE.Mesh(new THREE.PlaneGeometry(canvasEl.width/3, canvasEl.height/3), material);
var meshArrow = createMessagePointer(canvasEl, fillColor, direction);
meshback.rotation.set(0, Math.PI, 0);
meshfront.position.z += 0.2;
meshback.position.z -= 0.2;
var holder = new THREE.Object3D();
holder.add(meshfront);
holder.add(meshback);
holder.add(meshArrow);
return holder;
}
function createMessagePointer(canvas, color, direction){
//color = "rgba(0, 0, 0, 1)";
var material = new THREE.MeshBasicMaterial({color: rgb2hex(color)});
var size = 15;
var meshfront = new THREE.Mesh(new THREE.PlaneGeometry(size, size), material);
var meshback = new THREE.Mesh(new THREE.PlaneGeometry(size, size), material);
meshback.rotation.set(0, Math.PI, 0);
meshfront.position.z += 0.1;
meshback.position.z -= 0.1;
var holder = new THREE.Object3D();
holder.add(meshfront);
holder.add(meshback);
holder.rotation.set(0, 0, Math.PI/4);
switch(direction){
case "down":
holder.position.set(0, -(canvas.height/6), 0);
break;
case "up":
holder.position.set(0, (canvas.height/6), 0);
break;
case "left":
holder.position.set(-(canvas.width/6), 0, 0);
break;
case "right":
holder.position.set((canvas.width/6), 0, 0);
break;
default:
console.error("no offset defined for error message arrow direction", direction);
break;
}
return holder;
}
function displayBlindMessages(smallBlind, bigBlind, players){
var handObj = players[0].hand;
var pos = new THREE.Vector3();
pos.copy(handObj.position);
pos.y += 25;
var message1 = players[0].name+" bet "+smallBlind+" for the small blind";
var message2 = players[1].name+" bet "+bigBlind+" for the big blind";
var betMessages= [];
betMessages.push({
timeToDisappear: 7000,
messageType: 2,
message: message1,
messagePos: pos,
messageRot: handObj.quaternion,
arrowSide: "down",
moveDirection: new THREE.Vector3(0, 50, 0),
scale: new THREE.Vector3(1, 1, 1)
})
var handObj2 = players[1].hand;
var pos2 = new THREE.Vector3();
pos2.copy(handObj2.position);
pos2.y += 25;
betMessages.push({
timeToDisappear: 7000,
messageType: 2,
message: message2,
messagePos: pos2,
messageRot: handObj2.quaternion,
arrowSide: "down",
moveDirection: new THREE.Vector3(0, 50, 0),
scale: new THREE.Vector3(1, 1, 1)
})
var blindMessages = new displayMessage(betMessages);
}
function rgb2hex(rgb){
rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
return (rgb && rgb.length === 4) ? "#" +
("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}
function optionsUI(player){
this.mesh = new THREE.Object3D();
var slideOut = theGame.models.MenuSidepanel.clone();
var slideOutContainer = new THREE.Object3D();
slideOutContainer.position.z += 5;
slideOutContainer.rotation.x = -Math.PI/2;
slideOutContainer.rotation.x += Math.PI/5;
// slideOut.rotation.set(0, Math.PI/2, 0);
//slideOut.rotation.y += Math.PI/5;
slideOutContainer.rotation.z = -Math.PI/2;
slideOutContainer.position.y -= 120;
slideOutContainer.position.x += 80;
slideOut.scale.set(400, 200, 200);
slideOutContainer.add(slideOut);
/*
refresh page
lock users
adjust money (stretch)
*/
var lockButton = new THREE.Mesh(new THREE.PlaneGeometry(20, 20), lockMaterial);
lockButton.position.x += 85;
lockButton.position.y += 10;
lockButton.position.z += 10;
lockButton.rotation.z = Math.PI/2;
slideOutContainer.add(lockButton);
this.lockButton = lockButton;
/*
var unlockButton = new THREE.Mesh(new THREE.PlaneGeometry(20, 20), unlockMaterial);
unlockButton.position.x += 85;
unlockButton.position.y += 10;
unlockButton.position.z += 5;
unlockButton.rotation.z = Math.PI/2;
//slideOutContainer.add(unlockButton);
*/
var refreshButton = new THREE.Mesh(new THREE.PlaneGeometry(30, 30), refreshMaterial);
refreshButton.position.y -= 200;
refreshButton.position.z += 80;
refreshButton.rotation.x = -Math.PI/5;
this.mesh.add(refreshButton);
this.refreshButton = refreshButton;
refreshButton.addBehaviors({
awake: function(obj){
console.log('refresh button is active!', obj)
obj.addEventListener('cursordown', function(){
console.log('reload the page!');
//location.reload();
window.location.href = window.location.href.split("?")[0];
});
}
})
refreshButton.updateBehaviors(0);
lockButton.addBehaviors({
awake: function(obj){
obj.addEventListener('cursordown', function(){
console.log('clicked!');
theGame.locked = !theGame.locked;
var pos = new THREE.Vector3();
pos.copy(obj.localToWorld(new THREE.Vector3(0, 60, 0)));
var quat = obj.getWorldQuaternion();
if(theGame.locked){
var safePlayers = [];
for(var i=0; i<theGame.players.length; i++){
if(theGame.players[i].state >= 0){
safePlayers.push(i);
}
}
var message = "Locked the game!";
var locked = new errorMessage({
timeToDisappear: 2000,
messageType: 0,
message: message,
pos: pos,
rot: quat,
scale: 0.4
});
sendUpdate({playerIndexes: safePlayers}, "lockGame", {thenUpdate: true});
}else{
var message = "Unlocked the game!";
var unlocked = new errorMessage({
timeToDisappear: 2000,
messageType: 1,
message: message,
pos: pos,
rot: quat,
scale: 0.4
});
sendUpdate({}, "unlockGame", {thenUpdate: true});
}
})
}
})
lockButton.updateBehaviors(0);
this.mesh.add(slideOutContainer);
}
var refreshImg = document.createElement('img');
refreshImg.src = "assets/refresh.png";
refreshImg.threeTex = new THREE.Texture(refreshImg);
var refreshMaterial = new THREE.MeshBasicMaterial({map:refreshImg.threeTex});
refreshMaterial.transparent = true;
var lockImg = document.createElement('img');
lockImg.src = "assets/lock.png";
lockImg.threeTex = new THREE.Texture(lockImg);
var lockMaterial = new THREE.MeshBasicMaterial({map:lockImg.threeTex});
lockMaterial.transparent = true;
var plusImg = document.createElement('img');
plusImg.src = "assets/plus.png";
plusImg.threeTex = new THREE.Texture(plusImg);
var minusImg = document.createElement('img');
minusImg.src = "assets/minus.png";
minusImg.threeTex = new THREE.Texture(minusImg);
var addMaterial = new THREE.MeshBasicMaterial({map:plusImg.threeTex});
var removeMaterial = new THREE.MeshBasicMaterial({map:minusImg.threeTex});
var betImg = {
img: document.createElement('img'),
outImg: document.createElement('img')
};
betImg.img.src = "assets/betUI-check.png";
betImg.threeMat = new THREE.MeshBasicMaterial({map:new THREE.Texture(betImg.img)});
var raiseImg = {
img: document.createElement('img'),
outImg: document.createElement('img')
};
raiseImg.img.src = "assets/betUI-raise.png";
raiseImg.threeMat = new THREE.MeshBasicMaterial({map:new THREE.Texture(raiseImg.img)});
var callImg = {
img: document.createElement('img'),
outImg: document.createElement('img')
};
callImg.img.src = "assets/betUI-call.png";
callImg.threeMat = new THREE.MeshBasicMaterial({map:new THREE.Texture(callImg.img)});
var foldImg = {
img: document.createElement('img'),
outImg: document.createElement('img')
};
foldImg.outImg.src = "assets/betUI-fold2.png";
foldImg.img.src = "assets/betUI-fold.png";
foldImg.threeMat = new THREE.MeshBasicMaterial({map:new THREE.Texture(foldImg.img)});
var inImg = {
img: document.createElement('img'),
outImg: document.createElement('img')
};
inImg.outImg.src = "assets/betUI-all_In.png";
inImg.img.src = "assets/betUI-all_In.png";
inImg.threeMat = new THREE.MeshBasicMaterial({map:new THREE.Texture(inImg.img)});
function bettingUI(player){
this.canvasEl = document.createElement('canvas');
this.canvasEl.width = 218;
this.canvasEl.height = 63;
this.textArea = this.canvasEl.getContext('2d');
//document.body.appendChild(canvasEl);
this.fontSize = 32;
this.fontPadding = (63/2 + 32/2) - 5;
this.textArea.font = this.fontSize+"px Arial";
//this.textArea.fillStyle = "rgba(255,255,255, 1)";
this.element = this.canvasEl;
this.textArea.textAlign = "center";
//this.textArea.fillText("BET", this.element.width/2, this.fontSize);
//this.textArea.fill();
// this.textArea.beginPath();
//this.textArea.rect(0, 60, 150, 150);
//this.textArea.fillStyle = "grey";
//this.textArea.fill();
//set the color back to white
this.textArea.fillStyle = "rgba(255,255,255, 1)";
this.material = new THREE.MeshBasicMaterial({map: new THREE.Texture(this.element)});
this.countMesh = new THREE.Mesh(new THREE.PlaneGeometry(this.element.width/4, this.element.height/4), this.material);
this.countMesh.position.y += 18;
this.countMesh.position.z -= 4.5;
//this.backMesh = new THREE.Mesh(new THREE.PlaneGeometry(this.element.width/4, this.element.height/4), this.material);
//this.backMesh.rotation.set(0, Math.PI, 0);
//this.backMesh.position.z -= 0.1;
this.mainMesh = theGame.models.Menu.clone();
this.mainMesh.scale.set(200, 200, 200);
this.mainMesh.position.z -= 7;
this.mesh = new THREE.Object3D();
//this.mesh.add(this.backMesh);
this.mesh.add(this.mainMesh);
this.mesh.add(this.countMesh);
var spacing = 25;
var chLarge = makeChipStack(125, spacing);
var chSmall = makeChipStack(16, spacing);
chLarge.rotation.set(Math.PI/2, Math.PI/2, 0);
chSmall.rotation.set(Math.PI/2, Math.PI/2, 0);
chLarge.position.set(0, 0, 0);
chSmall.position.set(0, spacing*2, 0);
var chips = new THREE.Object3D();
chips.add(chLarge);
chips.add(chSmall);
chips.scale.set(0.4, 0.4, 0.4);
chips.position.set(0, -62, 0);
this.mesh.add(chips);
/*
white - 1
red - 5
blue - 10
green - 25
black - 100
*/
var betButtons = new THREE.Object3D();
var bd = [10, 5];
var addButtonArray = [];
var removeButtonArray = [];
var ctrlButtonArray = [];
for(var i=0; i<5; i++){
var yoffset = 8.5*i;
var addButton = new THREE.Mesh(new THREE.PlaneGeometry(bd[0], bd[1]), addMaterial);
addButton.position.x += 25;
addButton.position.y -= yoffset;
betButtons.add(addButton);
addButtonArray.push(addButton);
var removeButton = new THREE.Mesh(new THREE.PlaneGeometry(bd[0], bd[1]), removeMaterial);
removeButton.position.y -= yoffset;
betButtons.add(removeButton);
removeButtonArray.push(removeButton);
}
//make bet, fold, all in buttons
var ctrlBet = new THREE.Mesh(new THREE.PlaneGeometry(17.2, 25.6), betImg.threeMat); //check
var ctrlRaise = new THREE.Mesh(new THREE.PlaneGeometry(17.2, 25.6), raiseImg.threeMat); //raise
var ctrlCall = new THREE.Mesh(new THREE.PlaneGeometry(17.2, 25.6), callImg.threeMat); //call
var ctrlFold = new THREE.Mesh(new THREE.PlaneGeometry(17.2, 12.8), foldImg.threeMat);
var ctrlIn = new THREE.Mesh(new THREE.PlaneGeometry(17.2, 12.8), inImg.threeMat);
ctrlFold.position.set(-17.2, -6.4, 0);
ctrlIn.position.set(17.2, -6.4, 0);
var ctrlHolder = new THREE.Object3D();
ctrlHolder.add(ctrlBet);
ctrlHolder.add(ctrlRaise);
ctrlHolder.add(ctrlCall);
ctrlHolder.add(ctrlFold);
ctrlHolder.add(ctrlIn);
this.betMesh = ctrlBet;
this.raiseMesh = ctrlRaise;
this.callMesh = ctrlCall;
ctrlButtonArray = [ctrlFold, ctrlBet, ctrlRaise, ctrlCall, ctrlIn];
ctrlHolder.position.set(0, 44, 0);
ctrlHolder.scale.set(1.15, 1.15, 1.15);
this.mesh.add(ctrlHolder);
betButtons.scale.set(1.175, 1.175, 1.175);
betButtons.position.set(-15, 2, 0);
this.mesh.add(betButtons);
this.mesh.position.y -= 120;
this.mesh.position.x = 80;
this.mesh.position.z -= 50;
this.mesh.addBehaviors(new bettingUIInteractions(player, (function(thisUI){
return function(t){
thisUI.updateBet(t);
}
})(this), [addButtonArray, removeButtonArray, ctrlButtonArray]));
this.mesh.updateBehaviors(0);
this.updateBet(0);
}
bettingUI.prototype.toggleBetUI = function(showMesh){
toggleVisible(this.betMesh, false);
toggleVisible(this.raiseMesh, false);
toggleVisible(this.callMesh, false);
toggleVisible(showMesh, true);
}
bettingUI.prototype.updateBet = function(amount){
this.textArea.clearRect(0, 0, 250, 60);
this.textArea.fillText("$"+amount, this.element.width/2, this.fontPadding);
this.material.map.needsUpdate = true;
this.material.needsUpdate = true;
}
function chipCount(player){
this.canvasEl = document.createElement('canvas');
this.canvasEl.width = 400;
this.canvasEl.height = 63;
this.player = player;
this.textArea = this.canvasEl.getContext('2d');
this.fontSize = 32;
this.fontPadding = (63/2 + 32/2) - 5;
this.textArea.font = this.fontSize+"px Arial";
this.textArea.textAlign = "center";
this.textArea.fillStyle = "rgba(255,255,255, 1)";
this.textArea.fillText("$0", this.canvasEl.width/2, this.fontPadding);
this.material = new THREE.MeshBasicMaterial({map: new THREE.Texture(this.canvasEl)});
this.material.transparent = true;
this.mesh = new THREE.Mesh(new THREE.PlaneGeometry(this.canvasEl.width/4, this.canvasEl.height/4), this.material);
this.material.map.needsUpdate = true;
this.material.needsUpdate = true;
player.hand.add(this.mesh);
this.mesh.position.y -= 130;
this.mesh.position.x += 80;
this.mesh.position.z += 45;
this.mesh.rotation.x -= Math.PI/2;
this.mesh.rotation.x += Math.PI/8;
}
chipCount.prototype.updateMoney = function(amount){
this.textArea.clearRect(0, 0, 400, 63);
this.textArea.fillText("Current Bet: $"+theGame.currentBet+" $"+amount, this.canvasEl.width/2, this.fontPadding);
this.material.map.needsUpdate = true;
this.material.needsUpdate = true;
}
function dealerChip(player){
this.canvasEl = document.createElement('canvas');
this.canvasEl.width = 64;
this.canvasEl.height = 64;
this.textArea = this.canvasEl.getContext('2d');
this.fontSize = 32;
this.fontPadding = (63/2 + 32/2) - 5;
this.textArea.font = this.fontSize+"px Arial";
this.textArea.textAlign = "center";
this.textArea.fillStyle = "rgba(0,0,0, 1)";
this.textArea.fillText("D", this.canvasEl.width/2, this.fontPadding);
this.dMaterial = new THREE.MeshBasicMaterial({map: new THREE.Texture(this.canvasEl)})
this.dMesh = new THREE.Mesh(new THREE.PlaneGeometry(this.canvasEl.width/4, this.canvasEl.height/4), this.dMaterial);
this.dMaterial.transparent = true;
this.dMaterial.map.needsUpdate = true;
this.dMaterial.needsUpdate = true;
this.material = new THREE.MeshBasicMaterial({color: "#FFFFFF"});
this.mesh = new THREE.Mesh( new THREE.CylinderGeometry( 10, 10, 5, 10 ), this.material);
this.mesh.add(this.dMesh);
this.dMesh.position.y += 2.6;
this.dMesh.rotation.x -= Math.PI/2;
player.hand.add(this.mesh);
this.mesh.position.y -= 150;
this.mesh.position.x -= 60;
this.mesh.position.z -= 10;
player.dealerUI = new advanceUI(this.mesh);
}
function advanceUI(chip){
//this.dMesh = new createMessage("Deal More Cards", 1, "down");
//this.dMesh.scale.set(0.5, 0.5, 0.5);
//this.dMesh.position.y += 30;
var cardBack = theGame.models.CardBack.clone();
cardBack.scale.set(200, 200, 200);
var cardBack2 = theGame.models.CardBack.clone();
cardBack2.scale.set(200, 200, 200);
var card = new THREE.Object3D();
card.add(cardBack);
card.add(cardBack2);
//card.add(this.dMesh);
cardBack2.rotation.y = Math.PI;
this.mesh = card;
chip.add(card);
card.position.y += 20;
card.position.z -= 10;
card.rotation.x -= Math.PI/6;
card.addBehaviors({awake: function(obj){
obj.addEventListener('cursordown', function(){
toggleVisible(card, false);
sendUpdate({authority:theGame.currentAuthority}, "requestFinishBetting", {thenUpdate: true});
})
}});
card.updateBehaviors(0);
}
function bettingUIInteractions(pl, updateBet, buttonArray){
this.object;
this.player = pl;
this.addArr = buttonArray[0];
this.subArr = buttonArray[1];
this.ctrlArray = buttonArray[2];
this.updateBet = updateBet;
this.allowedTo = function allowedToDoThis(){
var allowed = this.player.userId === globalUserId;
if(!allowed){
var handObj = pl.hand;
var uiObj = pl.bettingui.mainMesh;
var pos = new THREE.Vector3();
pos.copy(uiObj.localToWorld(new THREE.Vector3(0, 0.3, 0)));
var quat = uiObj.getWorldQuaternion();
var message = "Unauthorized!";
var unauthorized = new errorMessage({
timeToDisappear: 3000,
messageType: 0,
message: message,
pos: pos,
rot: quat,
scale: 0.4
});
}
console.log('did a test and it came back', allowed);
return allowed;
}
this.awake = function awake(obj){
this.object = obj;
this.addArr[0].addEventListener('cursordown', (function(that){
return function(t){
that.addMoney(1);
}
})(this));
this.addArr[1].addEventListener('cursordown', (function(that){
return function(t){
that.addMoney(5);
}
})(this));
this.addArr[2].addEventListener('cursordown', (function(that){
return function(t){
that.addMoney(10);
}
})(this));
this.addArr[3].addEventListener('cursordown', (function(that){
return function(t){
that.addMoney(25);
}
})(this));
this.addArr[4].addEventListener('cursordown', (function(that){
return function(t){
that.addMoney(100);
}
})(this));
this.subArr[0].addEventListener('cursordown', (function(that){
return function(t){
that.addMoney(-1);
}
})(this));
this.subArr[1].addEventListener('cursordown', (function(that){
return function(t){
that.addMoney(-5);
}
})(this));
this.subArr[2].addEventListener('cursordown', (function(that){
return function(t){
that.addMoney(-10);
}
})(this));
this.subArr[3].addEventListener('cursordown', (function(that){
return function(t){
that.addMoney(-25);
}
})(this));
this.subArr[4].addEventListener('cursordown', (function(that){
return function(t){
that.addMoney(-100);
}
})(this));
//fold, bet, all-in
this.ctrlArray[0].addEventListener('cursordown', (function(that){
return function(t){
that.fold();
}
})(this));
this.ctrlArray[1].addEventListener('cursordown', (function(that){ //the check button
return function(t){
that.done();
}
})(this));
this.ctrlArray[2].addEventListener('cursordown', (function(that){ //the raise button
return function(t){
that.done();
}
})(this));
this.ctrlArray[3].addEventListener('cursordown', (function(that){ //the call button
return function(t){
that.done();
}
})(this));
this.ctrlArray[4].addEventListener('cursordown', (function(that){
return function(t){
that.allIn();
}
})(this));
}
this.addMoney = function addMoney(amount){
console.log('got a click event');
if(!this.allowedTo()){return false};
if(this.player.currentBet + amount >= this.player.money){ //do we have the funds
return;
}
if(this.player.raised === false){ //are we calling or raising?
if(amount < 0){
return;
}
if(amount < theGame.minRaise && this.player.currentBet + theGame.minRaise <= this.player.money){ //is our raise more than the last bet
this.addMoney(theGame.minRaise);
}else{
this.player.currentBet += amount;
this.updateBet(this.player.currentBet);
}
this.player.raised = true;
this.player.bettingui.toggleBetUI(this.player.bettingui.raiseMesh);
}else{
if((this.player.betThisRound + this.player.currentBet + amount) < (theGame.currentBet + theGame.minRaise)){ //are we trying to go lower than last bet
this.player.raised = false;
var callBet = (theGame.currentBet - this.player.betThisRound);
this.player.currentBet = callBet;
this.updateBet(this.player.currentBet);
if(this.player.currentBet > 0){
this.player.bettingui.toggleBetUI(this.player.bettingui.callMesh); //calling
}else{
this.player.bettingui.toggleBetUI(this.player.bettingui.betMesh); //checking
}
return;
}
this.player.currentBet+= amount;
this.updateBet(this.player.currentBet);
}
/*
if(this.player.currentBet + amount <= this.player.money && (this.player.currentBet + amount) >= 0){ //this should be the min bet actually
if(this.player.raised === false){
if(amount < theGame.smallBlind*2){
}
this.player.raised = true;
}
if(this.player.betThisRound + this.player.currentBet + amount >= (theGame.currentBet + (theGame.smallBlind*2))){
this.player.currentBet += amount;
this.updateBet(this.player.currentBet);
}
}else{
console.log('dont have the funds', this.player.currentBet + amount , (this.player.currentBet + amount) >= 0);
}
*/
}
this.allIn = function allIn(){
if(!this.allowedTo()){return false};
this.player.currentBet = this.player.money;
this.updateBet(this.player.currentBet);
this.player.raised = true;
}
this.done = function done(){
if(!this.allowedTo()){return false};
this.player.betUpdate(this.player.currentBet);
this.updateBet(this.player.currentBet);
}
this.fold = function fold(){
if(!this.allowedTo()){return false};
this.player.foldUpdate();
this.updateBet(this.player.currentBet);
}
}
function addPlayer(ind){
var index = ind;
var object;
var textObj;
function awake(obj){
object = obj;
object.addEventListener('cursordown', (function(i){
return function(){
if(typeof globalUserId != 'undefined'){
theGame.players[i].state = 0;
theGame.players[i].userId = globalUserId;
theGame.players[i].name = globalUserName;
globalPlayerIndex = i;
sendUpdate({registerIndex: i, userId: globalUserId, name:globalUserName, money: theGame.players[i].money}, "registerPlayer");
}else{
altspace.getUser().then(function(result){
globalUserId = result.userId;
globalUserName = result.displayName;
theGame.players[i].state = 0;
theGame.players[i].userId = globalUserId;
theGame.players[i].name = globalUserName;
globalPlayerIndex = i;
sendUpdate({registerIndex: i, userId: globalUserId, name:globalUserName, money:theGame.players[i].money}, "registerPlayer");
});
}
}
}(index)));
}
return {awake: awake};
}
function startGame(player){
var object;
var pl = player;
function awake(obj){
object = obj;
object.addEventListener('cursordown', startGame);
}
function allowedToDoThis(){
var allowed = (pl.userId === globalUserId);
if(!allowed){
var pos = new THREE.Vector3();
pos.copy(object.localToWorld(new THREE.Vector3(0, 50, 0)));
var quat = object.getWorldQuaternion();
var message = "Unauthorized!";
var unauthorized = new errorMessage({
timeToDisappear: 3000,
messageType: 0,
message: message,
pos: pos,
rot: quat,
scale: 0.4
});
}else if(numActivePlayers() < 2){
var pos = new THREE.Vector3();
pos.copy(object.localToWorld(new THREE.Vector3(0, 20, 0)));
var quat = object.getWorldQuaternion();
var message = "Need more players!";
var unauthorized = new errorMessage({
timeToDisappear: 2000,
messageType: 0,
message: message,
pos: pos,
rot: quat,
scale: 0.4
});
}
console.log(pl);
return (allowed && (numActivePlayers() >= 2));
//return true;
}
function startGame(){
if(allowedToDoThis()){
theGame.resetDealers();
theGame.dealer = theGame.dealingOrder.indexOf(pl);
theGame.rotateDealers();
for(var i=0; i<theGame.players.length; i++){
toggleVisible(theGame.players[i].dealerChip.mesh, false);
}
toggleVisible(theGame.dealingOrder[theGame.dealer].dealerChip.mesh, true);
toggleVisible(theGame.dealingOrder[theGame.dealer].dealerUI.mesh, false);
theGame.step = 0;//do the initialization in the game controller
theGame.timeBlindStarted = Date.now();
//sendUpdate({stepUpdate: 0}, "startGame");
theGame.runStep();
}
}
return {awake: awake};
}
function makeStartGameButton(player){
var canvasEl = document.createElement('canvas');
canvasEl.width = 250;
canvasEl.height = 75;
var canvasCtx = canvasEl.getContext('2d');
//document.body.appendChild(canvasEl);
this.fontSize = 30;
this.fontPadding = 10;
canvasCtx.font = this.fontSize+"px Arial";
canvasCtx.fillStyle = "rgba(255,255,255, 1)";
this.element = canvasEl;
this.textArea = canvasCtx;
var textureElement = new THREE.Texture(this.element);
this.material = new THREE.MeshBasicMaterial({map: textureElement});
this.material.transparent = true;
this.mesh = new THREE.Mesh(new THREE.PlaneGeometry(canvasEl.width/4, canvasEl.height/4), this.material);
this.textArea.textAlign = "center";
this.textArea.fillText("Start the game", this.element.width/2, this.element.height/2 + this.fontSize/4);
this.mesh.addBehaviors(startGame(player));
this.mesh.updateBehaviors(0);
sim.scene.add(this.mesh);
}
function makeJoinButton(index){
var canvasEl = document.createElement('canvas');
canvasEl.width = 250;
canvasEl.height = 75;
var canvasCtx = canvasEl.getContext('2d');
//document.body.appendChild(canvasEl);
this.fontSize = 40;
this.fontPadding = 10;
canvasCtx.font = this.fontSize+"px Arial";
canvasCtx.fillStyle = "rgba(255,255,255, 1)";
this.element = canvasEl;
this.textArea = canvasCtx;
var textureElement = new THREE.Texture(this.element);
this.material = new THREE.MeshBasicMaterial({map: textureElement});
this.material.transparent = true;
this.mesh = new THREE.Mesh(new THREE.PlaneGeometry(canvasEl.width/2, canvasEl.height/2), this.material);
this.textArea.textAlign = "center";
this.textArea.fillText("Deal me in", this.element.width/2, this.element.height/2 + this.fontSize/4);
movePlayerButton(this.mesh, index);
this.mesh.addBehaviors(addPlayer(index));
this.mesh.updateBehaviors(0);
// sim.scene.add(this.mesh);
}
|
var exec = require('cordova/exec');
var customPlugin = {};
customPlugin.echo = function(successCallback, errorCallback, args) {
exec(successCallback, errorCallback, "customPlugin", "echo", args);
};
module.exports = customPlugin;
|
const { api_key, url } = require('../config/giphy');
const { debounce } = require('lodash');
const Events = require('../events/search.events');
const Dispatcher = require('../dispatcher/dispatcher');
const agent = require('superagent');
module.exports = function SearchActions() {
return {
search: debounce(function (count, offset, q) {
Dispatcher.dispatch({ actionType: Events.DATA_LOAD_START });
agent
.get(url)
.query({ api_key, count, offset, q })
.end((err, response) => {
if (err) {
Dispatcher.dispatch({ actionType: Events.DATA_LOAD_ERROR });
return;
}
Dispatcher.dispatch({
actionType: Events.DATA_LOAD_SUCCESS,
results: response.body
});
});
}, 1000)
};
}();
|
var Stream = require('stream').Stream;
var createNode = require('./node');
module.exports = function (parser, opts) {
var stream = new Stream;
stream.writable = true;
stream.readable = true;
var selectors = [];
stream.select = function (s, fn) {
var sel = createSelector(s, fn, opts.special);
selectors.push(sel);
return stream;
};
stream.update = function (s, fn) {
return stream.select(s, function (node) {
if (typeof fn === 'function') {
node.update(function (html) { return fn(html, node) });
}
else node.update(fn);
});
};
stream.remove = function (s, fn) {
return stream.select(s, function (node) {
node.remove();
if (typeof fn === 'function') fn(node);
});
};
stream.replace = function (s, fn) {
return stream.select(s, function (node) {
if (typeof fn === 'function') {
node.replace(function (html) { return fn(html, node) });
}
else node.replace(fn);
});
};
var updating = false;
stream.pre = function (name, t) {
if (name === 'open') {
selectors.forEach(function (sel) {
sel(t, parser)
if (sel.removing) updating = true;
});
}
else if (name === 'close') {
var level = parser.tags.reduce(function (sum, t) {
return sum + (opts.special.indexOf(t.name) < 0 ? 1 : 0);
}, 0);
selectors.forEach(function (sel) {
var up = sel.updating;
sel.pending = sel.pending.filter(function (p) {
var done = level < p.level;
if (done && sel.removing) {
p.callback.call(stream, p.buffered, function (cb) {
sel.nextRaw.push(cb);
});
}
else if (done) p.callback.call(stream, p.buffered);
return !done;
});
if (up && !sel.updating) {
if (sel.removing) {
sel.removeOnPost = true;
}
else updating = false;
}
});
}
};
stream.post = function (name, t) {
if (name === 'open') {
selectors.forEach(function (sel) {
if (sel.updating) {
updating = true;
}
sel.pending.forEach(function (p) {
if (p.writes === 0) {
p.buffered = '';
}
if (typeof p.writes === 'number') p.writes ++;
});
});
for (var i = 0; i < parser.tags.length; i++) {
var t = parser.tags[i];
if (opts.special.indexOf(t.name) >= 0) {
parser.tags.splice(i, 1);
i--;
}
}
}
else if (name == 'close') {
selectors.forEach(function (sel) {
if (sel.removeOnPost) {
updating = false;
sel.removing = false;
sel.removeOnPost = false;
}
});
}
};
stream.raw = function (s) {
selectors.forEach(function (sel) {
sel.nextRaw.splice(0).forEach(function (cb) { cb(s) });
sel.pending.forEach(function (p) {
p.buffered += s;
});
});
if (!updating) stream.emit('data', s);
};
return stream;
};
function createSelector (selector, fn, special) {
var saveSiblings = false;
var parts = selector.split(/([\s>+]+)/).map(function (s) {
if (s.match(/^\s+$/)) return;
var op = s.trim();
if (op === '+') saveSiblings = true;
if (op === '>' || op === '+') return { combinator : op };
var m = {
name : s.match(/^([\w-]+|\*)/),
class : s.match(/\.([\w-]+)/),
id : s.match(/#([\w-]+)/),
pseudo : s.match(/:([\w-]+)/),
attribute : s.match(/\[([^\]]+)\]/),
};
return {
name : m.name && m.name[1].toUpperCase(),
class : m.class && m.class[1],
id : m.id && m.id[1],
pseudo : m.pseudo && m.pseudo[1],
attribute : m.attribute && m.attribute[1],
};
}).filter(Boolean);
var depth = parts.reduce(function (sum, s) {
return sum + (s.combinator ? 0 : 1);
}, 0);
var siblings = [];
var sel = function (tag, parser) {
var tags = parser.tags;
if (!siblings[tags.length]) siblings[tags.length] = [];
siblings[tags.length].push(tag);
if (depth > tags.length) return;
// hypothesis: the selector matches
var j = parts.length - 1;
var i = tags.length - 1;
function check (t, p) {
// try to falsify the hypothesis on each tag/part match:
if (p.name !== '*' && p.name && p.name !== t.name) return false;
if (p.class && p.class !== t.attributes.class) return false;
if (p.id && p.id !== t.attributes.id) return false;
return true;
}
for (; j >= 0; j--, i--) {
var t = tags[i];
var p = parts[j];
if (p.combinator === '>') {
for (var ii = i; ii >= 0; ii--) {
if (check(tags[ii], parts[j-1])) {
break;
}
}
if (ii < 0) return;
j -= 2;
}
else if (p.combinator === '+') {
var ts = siblings[i + 2];
t = ts[ts.length - 2];
if (!t) return;
p = parts[j - 1];
if (!check(t, p)) return;
j -= 2;
}
else if (!check(t, p)) return;
}
var node = createNode(tag, sel, tags.length);
fn(node);
node.expired = true;
};
sel.special = special;
sel.pending = [];
sel.nextRaw = [];
return sel;
}
|
var homeModule = require("./home");
describe('home section', function() {
it('should have a dummy test', inject(function() {
expect(true).toBeTruthy();
}));
});
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var windows = exports.windows = { "viewBox": "0 0 1664 1792", "children": [{ "name": "path", "attribs": { "d": "M682 1006v651l-682-94v-557h682zM682 263v659h-682v-565zM1664 1006v786l-907-125v-661h907zM1664 128v794h-907v-669z" } }] };
|
var shortener = {
el: {
input : $('input#url'),
btn : $('button#short'),
content: $('#shortened'),
table : $('#link-table tbody')
},
init: function () {
shortener.el.btn.on('click', shortener.shorten);
shortener.el.input.on('keyup', function() {
shortener.el.input.removeClass('field-error');
});
},
shorten: function (e)
{
e.preventDefault();
var url = shortener.el.input.val();
if (url)
{
$.get('/shorten/', {
'url' : url
}, function(data) {
shortener.el.input.val("");
if (data.error) {
toastr.error(data.error.url, 'Algo deu errado! :(');
}
else {
shortener.el.content.html(shortener.html(data));
if(data.created == true)
shortener.el.table.append(shortener.row(data));
}
}
);
}
else {
shortener.el.input.addClass('field-error').focus();
}
},
html: function(d) {
return $(
'<div id="url-shortened">' +
'<div class="url">' +
'<span>Copie sua url encurtada: </span>' +
'<a target="_blank" href="' + d.shortened_url + '">' + d.shortened_url + '</a>' +
'</div>' +
'</div>');
},
row: function (link) {
return $(
'<tr>' +
'<td data-url="' + link.url + '" class="text-left"><a href="' + link.url + '" class="link" target="_blank">' + link.url + '</a></td>' +
'<td class="text-left"><a href="' + link.shortened_url + '" class="link" target="_blank">' + link.shortened_url + '</a></td>' +
'<td class="text-align">' + link.submitted + '</td>' +
'<td class="text-center">' + link.visits + '</td>' +
'</tr>');
}
};
$(function() {
shortener.init();
});
|
// All symbols in the CJK Compatibility Ideographs Supplement block as per Unicode v5.1.0:
[
'\uD87E\uDC00',
'\uD87E\uDC01',
'\uD87E\uDC02',
'\uD87E\uDC03',
'\uD87E\uDC04',
'\uD87E\uDC05',
'\uD87E\uDC06',
'\uD87E\uDC07',
'\uD87E\uDC08',
'\uD87E\uDC09',
'\uD87E\uDC0A',
'\uD87E\uDC0B',
'\uD87E\uDC0C',
'\uD87E\uDC0D',
'\uD87E\uDC0E',
'\uD87E\uDC0F',
'\uD87E\uDC10',
'\uD87E\uDC11',
'\uD87E\uDC12',
'\uD87E\uDC13',
'\uD87E\uDC14',
'\uD87E\uDC15',
'\uD87E\uDC16',
'\uD87E\uDC17',
'\uD87E\uDC18',
'\uD87E\uDC19',
'\uD87E\uDC1A',
'\uD87E\uDC1B',
'\uD87E\uDC1C',
'\uD87E\uDC1D',
'\uD87E\uDC1E',
'\uD87E\uDC1F',
'\uD87E\uDC20',
'\uD87E\uDC21',
'\uD87E\uDC22',
'\uD87E\uDC23',
'\uD87E\uDC24',
'\uD87E\uDC25',
'\uD87E\uDC26',
'\uD87E\uDC27',
'\uD87E\uDC28',
'\uD87E\uDC29',
'\uD87E\uDC2A',
'\uD87E\uDC2B',
'\uD87E\uDC2C',
'\uD87E\uDC2D',
'\uD87E\uDC2E',
'\uD87E\uDC2F',
'\uD87E\uDC30',
'\uD87E\uDC31',
'\uD87E\uDC32',
'\uD87E\uDC33',
'\uD87E\uDC34',
'\uD87E\uDC35',
'\uD87E\uDC36',
'\uD87E\uDC37',
'\uD87E\uDC38',
'\uD87E\uDC39',
'\uD87E\uDC3A',
'\uD87E\uDC3B',
'\uD87E\uDC3C',
'\uD87E\uDC3D',
'\uD87E\uDC3E',
'\uD87E\uDC3F',
'\uD87E\uDC40',
'\uD87E\uDC41',
'\uD87E\uDC42',
'\uD87E\uDC43',
'\uD87E\uDC44',
'\uD87E\uDC45',
'\uD87E\uDC46',
'\uD87E\uDC47',
'\uD87E\uDC48',
'\uD87E\uDC49',
'\uD87E\uDC4A',
'\uD87E\uDC4B',
'\uD87E\uDC4C',
'\uD87E\uDC4D',
'\uD87E\uDC4E',
'\uD87E\uDC4F',
'\uD87E\uDC50',
'\uD87E\uDC51',
'\uD87E\uDC52',
'\uD87E\uDC53',
'\uD87E\uDC54',
'\uD87E\uDC55',
'\uD87E\uDC56',
'\uD87E\uDC57',
'\uD87E\uDC58',
'\uD87E\uDC59',
'\uD87E\uDC5A',
'\uD87E\uDC5B',
'\uD87E\uDC5C',
'\uD87E\uDC5D',
'\uD87E\uDC5E',
'\uD87E\uDC5F',
'\uD87E\uDC60',
'\uD87E\uDC61',
'\uD87E\uDC62',
'\uD87E\uDC63',
'\uD87E\uDC64',
'\uD87E\uDC65',
'\uD87E\uDC66',
'\uD87E\uDC67',
'\uD87E\uDC68',
'\uD87E\uDC69',
'\uD87E\uDC6A',
'\uD87E\uDC6B',
'\uD87E\uDC6C',
'\uD87E\uDC6D',
'\uD87E\uDC6E',
'\uD87E\uDC6F',
'\uD87E\uDC70',
'\uD87E\uDC71',
'\uD87E\uDC72',
'\uD87E\uDC73',
'\uD87E\uDC74',
'\uD87E\uDC75',
'\uD87E\uDC76',
'\uD87E\uDC77',
'\uD87E\uDC78',
'\uD87E\uDC79',
'\uD87E\uDC7A',
'\uD87E\uDC7B',
'\uD87E\uDC7C',
'\uD87E\uDC7D',
'\uD87E\uDC7E',
'\uD87E\uDC7F',
'\uD87E\uDC80',
'\uD87E\uDC81',
'\uD87E\uDC82',
'\uD87E\uDC83',
'\uD87E\uDC84',
'\uD87E\uDC85',
'\uD87E\uDC86',
'\uD87E\uDC87',
'\uD87E\uDC88',
'\uD87E\uDC89',
'\uD87E\uDC8A',
'\uD87E\uDC8B',
'\uD87E\uDC8C',
'\uD87E\uDC8D',
'\uD87E\uDC8E',
'\uD87E\uDC8F',
'\uD87E\uDC90',
'\uD87E\uDC91',
'\uD87E\uDC92',
'\uD87E\uDC93',
'\uD87E\uDC94',
'\uD87E\uDC95',
'\uD87E\uDC96',
'\uD87E\uDC97',
'\uD87E\uDC98',
'\uD87E\uDC99',
'\uD87E\uDC9A',
'\uD87E\uDC9B',
'\uD87E\uDC9C',
'\uD87E\uDC9D',
'\uD87E\uDC9E',
'\uD87E\uDC9F',
'\uD87E\uDCA0',
'\uD87E\uDCA1',
'\uD87E\uDCA2',
'\uD87E\uDCA3',
'\uD87E\uDCA4',
'\uD87E\uDCA5',
'\uD87E\uDCA6',
'\uD87E\uDCA7',
'\uD87E\uDCA8',
'\uD87E\uDCA9',
'\uD87E\uDCAA',
'\uD87E\uDCAB',
'\uD87E\uDCAC',
'\uD87E\uDCAD',
'\uD87E\uDCAE',
'\uD87E\uDCAF',
'\uD87E\uDCB0',
'\uD87E\uDCB1',
'\uD87E\uDCB2',
'\uD87E\uDCB3',
'\uD87E\uDCB4',
'\uD87E\uDCB5',
'\uD87E\uDCB6',
'\uD87E\uDCB7',
'\uD87E\uDCB8',
'\uD87E\uDCB9',
'\uD87E\uDCBA',
'\uD87E\uDCBB',
'\uD87E\uDCBC',
'\uD87E\uDCBD',
'\uD87E\uDCBE',
'\uD87E\uDCBF',
'\uD87E\uDCC0',
'\uD87E\uDCC1',
'\uD87E\uDCC2',
'\uD87E\uDCC3',
'\uD87E\uDCC4',
'\uD87E\uDCC5',
'\uD87E\uDCC6',
'\uD87E\uDCC7',
'\uD87E\uDCC8',
'\uD87E\uDCC9',
'\uD87E\uDCCA',
'\uD87E\uDCCB',
'\uD87E\uDCCC',
'\uD87E\uDCCD',
'\uD87E\uDCCE',
'\uD87E\uDCCF',
'\uD87E\uDCD0',
'\uD87E\uDCD1',
'\uD87E\uDCD2',
'\uD87E\uDCD3',
'\uD87E\uDCD4',
'\uD87E\uDCD5',
'\uD87E\uDCD6',
'\uD87E\uDCD7',
'\uD87E\uDCD8',
'\uD87E\uDCD9',
'\uD87E\uDCDA',
'\uD87E\uDCDB',
'\uD87E\uDCDC',
'\uD87E\uDCDD',
'\uD87E\uDCDE',
'\uD87E\uDCDF',
'\uD87E\uDCE0',
'\uD87E\uDCE1',
'\uD87E\uDCE2',
'\uD87E\uDCE3',
'\uD87E\uDCE4',
'\uD87E\uDCE5',
'\uD87E\uDCE6',
'\uD87E\uDCE7',
'\uD87E\uDCE8',
'\uD87E\uDCE9',
'\uD87E\uDCEA',
'\uD87E\uDCEB',
'\uD87E\uDCEC',
'\uD87E\uDCED',
'\uD87E\uDCEE',
'\uD87E\uDCEF',
'\uD87E\uDCF0',
'\uD87E\uDCF1',
'\uD87E\uDCF2',
'\uD87E\uDCF3',
'\uD87E\uDCF4',
'\uD87E\uDCF5',
'\uD87E\uDCF6',
'\uD87E\uDCF7',
'\uD87E\uDCF8',
'\uD87E\uDCF9',
'\uD87E\uDCFA',
'\uD87E\uDCFB',
'\uD87E\uDCFC',
'\uD87E\uDCFD',
'\uD87E\uDCFE',
'\uD87E\uDCFF',
'\uD87E\uDD00',
'\uD87E\uDD01',
'\uD87E\uDD02',
'\uD87E\uDD03',
'\uD87E\uDD04',
'\uD87E\uDD05',
'\uD87E\uDD06',
'\uD87E\uDD07',
'\uD87E\uDD08',
'\uD87E\uDD09',
'\uD87E\uDD0A',
'\uD87E\uDD0B',
'\uD87E\uDD0C',
'\uD87E\uDD0D',
'\uD87E\uDD0E',
'\uD87E\uDD0F',
'\uD87E\uDD10',
'\uD87E\uDD11',
'\uD87E\uDD12',
'\uD87E\uDD13',
'\uD87E\uDD14',
'\uD87E\uDD15',
'\uD87E\uDD16',
'\uD87E\uDD17',
'\uD87E\uDD18',
'\uD87E\uDD19',
'\uD87E\uDD1A',
'\uD87E\uDD1B',
'\uD87E\uDD1C',
'\uD87E\uDD1D',
'\uD87E\uDD1E',
'\uD87E\uDD1F',
'\uD87E\uDD20',
'\uD87E\uDD21',
'\uD87E\uDD22',
'\uD87E\uDD23',
'\uD87E\uDD24',
'\uD87E\uDD25',
'\uD87E\uDD26',
'\uD87E\uDD27',
'\uD87E\uDD28',
'\uD87E\uDD29',
'\uD87E\uDD2A',
'\uD87E\uDD2B',
'\uD87E\uDD2C',
'\uD87E\uDD2D',
'\uD87E\uDD2E',
'\uD87E\uDD2F',
'\uD87E\uDD30',
'\uD87E\uDD31',
'\uD87E\uDD32',
'\uD87E\uDD33',
'\uD87E\uDD34',
'\uD87E\uDD35',
'\uD87E\uDD36',
'\uD87E\uDD37',
'\uD87E\uDD38',
'\uD87E\uDD39',
'\uD87E\uDD3A',
'\uD87E\uDD3B',
'\uD87E\uDD3C',
'\uD87E\uDD3D',
'\uD87E\uDD3E',
'\uD87E\uDD3F',
'\uD87E\uDD40',
'\uD87E\uDD41',
'\uD87E\uDD42',
'\uD87E\uDD43',
'\uD87E\uDD44',
'\uD87E\uDD45',
'\uD87E\uDD46',
'\uD87E\uDD47',
'\uD87E\uDD48',
'\uD87E\uDD49',
'\uD87E\uDD4A',
'\uD87E\uDD4B',
'\uD87E\uDD4C',
'\uD87E\uDD4D',
'\uD87E\uDD4E',
'\uD87E\uDD4F',
'\uD87E\uDD50',
'\uD87E\uDD51',
'\uD87E\uDD52',
'\uD87E\uDD53',
'\uD87E\uDD54',
'\uD87E\uDD55',
'\uD87E\uDD56',
'\uD87E\uDD57',
'\uD87E\uDD58',
'\uD87E\uDD59',
'\uD87E\uDD5A',
'\uD87E\uDD5B',
'\uD87E\uDD5C',
'\uD87E\uDD5D',
'\uD87E\uDD5E',
'\uD87E\uDD5F',
'\uD87E\uDD60',
'\uD87E\uDD61',
'\uD87E\uDD62',
'\uD87E\uDD63',
'\uD87E\uDD64',
'\uD87E\uDD65',
'\uD87E\uDD66',
'\uD87E\uDD67',
'\uD87E\uDD68',
'\uD87E\uDD69',
'\uD87E\uDD6A',
'\uD87E\uDD6B',
'\uD87E\uDD6C',
'\uD87E\uDD6D',
'\uD87E\uDD6E',
'\uD87E\uDD6F',
'\uD87E\uDD70',
'\uD87E\uDD71',
'\uD87E\uDD72',
'\uD87E\uDD73',
'\uD87E\uDD74',
'\uD87E\uDD75',
'\uD87E\uDD76',
'\uD87E\uDD77',
'\uD87E\uDD78',
'\uD87E\uDD79',
'\uD87E\uDD7A',
'\uD87E\uDD7B',
'\uD87E\uDD7C',
'\uD87E\uDD7D',
'\uD87E\uDD7E',
'\uD87E\uDD7F',
'\uD87E\uDD80',
'\uD87E\uDD81',
'\uD87E\uDD82',
'\uD87E\uDD83',
'\uD87E\uDD84',
'\uD87E\uDD85',
'\uD87E\uDD86',
'\uD87E\uDD87',
'\uD87E\uDD88',
'\uD87E\uDD89',
'\uD87E\uDD8A',
'\uD87E\uDD8B',
'\uD87E\uDD8C',
'\uD87E\uDD8D',
'\uD87E\uDD8E',
'\uD87E\uDD8F',
'\uD87E\uDD90',
'\uD87E\uDD91',
'\uD87E\uDD92',
'\uD87E\uDD93',
'\uD87E\uDD94',
'\uD87E\uDD95',
'\uD87E\uDD96',
'\uD87E\uDD97',
'\uD87E\uDD98',
'\uD87E\uDD99',
'\uD87E\uDD9A',
'\uD87E\uDD9B',
'\uD87E\uDD9C',
'\uD87E\uDD9D',
'\uD87E\uDD9E',
'\uD87E\uDD9F',
'\uD87E\uDDA0',
'\uD87E\uDDA1',
'\uD87E\uDDA2',
'\uD87E\uDDA3',
'\uD87E\uDDA4',
'\uD87E\uDDA5',
'\uD87E\uDDA6',
'\uD87E\uDDA7',
'\uD87E\uDDA8',
'\uD87E\uDDA9',
'\uD87E\uDDAA',
'\uD87E\uDDAB',
'\uD87E\uDDAC',
'\uD87E\uDDAD',
'\uD87E\uDDAE',
'\uD87E\uDDAF',
'\uD87E\uDDB0',
'\uD87E\uDDB1',
'\uD87E\uDDB2',
'\uD87E\uDDB3',
'\uD87E\uDDB4',
'\uD87E\uDDB5',
'\uD87E\uDDB6',
'\uD87E\uDDB7',
'\uD87E\uDDB8',
'\uD87E\uDDB9',
'\uD87E\uDDBA',
'\uD87E\uDDBB',
'\uD87E\uDDBC',
'\uD87E\uDDBD',
'\uD87E\uDDBE',
'\uD87E\uDDBF',
'\uD87E\uDDC0',
'\uD87E\uDDC1',
'\uD87E\uDDC2',
'\uD87E\uDDC3',
'\uD87E\uDDC4',
'\uD87E\uDDC5',
'\uD87E\uDDC6',
'\uD87E\uDDC7',
'\uD87E\uDDC8',
'\uD87E\uDDC9',
'\uD87E\uDDCA',
'\uD87E\uDDCB',
'\uD87E\uDDCC',
'\uD87E\uDDCD',
'\uD87E\uDDCE',
'\uD87E\uDDCF',
'\uD87E\uDDD0',
'\uD87E\uDDD1',
'\uD87E\uDDD2',
'\uD87E\uDDD3',
'\uD87E\uDDD4',
'\uD87E\uDDD5',
'\uD87E\uDDD6',
'\uD87E\uDDD7',
'\uD87E\uDDD8',
'\uD87E\uDDD9',
'\uD87E\uDDDA',
'\uD87E\uDDDB',
'\uD87E\uDDDC',
'\uD87E\uDDDD',
'\uD87E\uDDDE',
'\uD87E\uDDDF',
'\uD87E\uDDE0',
'\uD87E\uDDE1',
'\uD87E\uDDE2',
'\uD87E\uDDE3',
'\uD87E\uDDE4',
'\uD87E\uDDE5',
'\uD87E\uDDE6',
'\uD87E\uDDE7',
'\uD87E\uDDE8',
'\uD87E\uDDE9',
'\uD87E\uDDEA',
'\uD87E\uDDEB',
'\uD87E\uDDEC',
'\uD87E\uDDED',
'\uD87E\uDDEE',
'\uD87E\uDDEF',
'\uD87E\uDDF0',
'\uD87E\uDDF1',
'\uD87E\uDDF2',
'\uD87E\uDDF3',
'\uD87E\uDDF4',
'\uD87E\uDDF5',
'\uD87E\uDDF6',
'\uD87E\uDDF7',
'\uD87E\uDDF8',
'\uD87E\uDDF9',
'\uD87E\uDDFA',
'\uD87E\uDDFB',
'\uD87E\uDDFC',
'\uD87E\uDDFD',
'\uD87E\uDDFE',
'\uD87E\uDDFF',
'\uD87E\uDE00',
'\uD87E\uDE01',
'\uD87E\uDE02',
'\uD87E\uDE03',
'\uD87E\uDE04',
'\uD87E\uDE05',
'\uD87E\uDE06',
'\uD87E\uDE07',
'\uD87E\uDE08',
'\uD87E\uDE09',
'\uD87E\uDE0A',
'\uD87E\uDE0B',
'\uD87E\uDE0C',
'\uD87E\uDE0D',
'\uD87E\uDE0E',
'\uD87E\uDE0F',
'\uD87E\uDE10',
'\uD87E\uDE11',
'\uD87E\uDE12',
'\uD87E\uDE13',
'\uD87E\uDE14',
'\uD87E\uDE15',
'\uD87E\uDE16',
'\uD87E\uDE17',
'\uD87E\uDE18',
'\uD87E\uDE19',
'\uD87E\uDE1A',
'\uD87E\uDE1B',
'\uD87E\uDE1C',
'\uD87E\uDE1D',
'\uD87E\uDE1E',
'\uD87E\uDE1F'
];
|
'use strict';
(function() {
// product Controller Spec
describe('Product Controller Tests', function() {
// Initialize global variables
var productController,
scope,
$httpBackend,
$stateParams,
$location;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function() {
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
// Set a new global scope
scope = $rootScope.$new();
// Point global variables to injected services
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$location = _$location_;
// Initialize the product controller.
ProductController = $controller('ProductController', {
$scope: scope
});
}));
it('$scope.find() should create an array with at least one article object fetched from XHR', inject(function(product) {
// Create sample article using the product service
var sampleproduct = new Product({
title: 'products',
content: 'MEAN rocks!'
});
// Create a sample product array that includes the new article
var sampleProduct = [sampleProduct];
// Set GET response
$httpBackend.expectGET('product').respond(sampleProduct);
// Run controller functionality
scope.find();
$httpBackend.flush();
// Test scope value
expect(scope.product).toEqualData(sampleProduct);
}));
it('$scope.findOne() should create an array with one article object fetched from XHR using a articleId URL parameter', inject(function(product) {
// Define a sample article object
var sampleProduct = new Product({
title: 'products',
content: 'MEAN rocks!'
});
// Set the URL parameter
$stateParams.productId = '525a8422f6d0f87f0e407a33';
// Set GET response
$httpBackend.expectGET(/product\/([0-9a-fA-F]{24})$/).respond(sampleproduct);
// Run controller functionality
scope.findOne();
$httpBackend.flush();
// Test scope value
expect(scope.product).toEqualData(sampleproduct);
}));
it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(product) {
// Create a sample article object
var sampleProductData = new Product({
title: 'products',
content: 'MEAN rocks!'
});
// Create a sample article response
var sampleProductResponse = new product({
_id: '525cf20451979dea2c000001',
title: 'products',
content: 'MEAN rocks!'
});
// Fixture mock form input values
scope.title = 'products';
scope.content = 'MEAN rocks!';
// Set POST response
$httpBackend.expectPOST('product', sampleProductPostData).respond(sampleProductResponse);
// Run controller functionality
scope.create();
$httpBackend.flush();
// Test form inputs are reset
expect(scope.title).toEqual('');
expect(scope.content).toEqual('');
// Test URL redirection after the article was created
expect($location.path()).toBe('/product/' + sampleProductResponse._id);
}));
it('$scope.update() should update a valid product', inject(function(product) {
// Define a sample article put data
var sampleproductPutData = new Product({
_id: '525cf20451979dea2c000001',
title: 'products',
content: 'MEAN Rocks!'
});
// Mock article in scope
scope.product = sampleProductPutData;
// Set PUT response
$httpBackend.expectPUT(/product\/([0-9a-fA-F]{24})$/).respond();
// Run controller functionality
scope.update();
$httpBackend.flush();
// Test URL location to new object
expect($location.path()).toBe('/product/' + sampleproductPutData._id);
}));
it('$scope.remove() should send a DELETE request with a valid articleId and remove the article from the scope', inject(function(product) {
// Create new article object
var sampleProduct = new Product({
_id: '525a8422f6d0f87f0e407a33'
});
// Create new product array and include the article
scope.product = [sampleProduct];
// Set expected DELETE response
$httpBackend.expectDELETE(/product\/([0-9a-fA-F]{24})$/).respond(204);
// Run controller functionality
scope.remove(sampleProduct);
$httpBackend.flush();
// Test array after successful delete
expect(scope.product.length).toBe(0);
}));
});
}());
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var MASTER_KEY = exports.MASTER_KEY = '_MASTER_';
var EVENTS = exports.EVENTS = {
TICK: 'Tick',
I_AM_MASTER: 'IAmNewMaster',
I_AM_SLAVE: 'IAmSlave',
STOP: 'Stop'
};
|
var should = require('should');
var dump = require('../../../lib/iptables').dump;
module.exports = function () {
describe('#dump', function () {
it('should be defined', function () {
should.exist(dump);
});
it('should throw an error when invoked without `options` argument', function () {
dump.bind(null).should.throw();
});
describe('when executing with valid options', function () {
// Resetting `iptables` state.
afterEach(function (done) {
dump(function (error) {
if (error) {
done(error);
return;
}
done();
});
});
});
});
};
|
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import AppBar from 'material-ui/AppBar';
import FlatButton from 'material-ui/FlatButton';
import Navigation from '../Navigation';
import { navigate } from '../../actions/route';
import s from './Header.css';
class Header extends Component {
render() {
let rightIcon = null;
if (this.props.isLoggedIn) {
rightIcon = (
<FlatButton
label="Logout"
onTouchTap={() => this.props.navigate('/logout')}
/>
);
} else {
rightIcon = (
<FlatButton
label="Login"
onTouchTap={() => this.props.navigate('/login')}
/>
);
}
const semesterToggle = (
<div className={s.semesterToggle}>
SEM {this.props.isSemesterOne ? '1' : '2'}
<FlatButton
label="Switch"
onTouchTap={this.props.handleSwitchSemester}
/>
{rightIcon}
</div>
);
return (
<div>
<div style={{ position: 'fixed', width: '100%', zIndex: 10 }}>
<AppBar
title="mods+"
showMenuIconButton={false}
iconElementRight={semesterToggle}
zDepth={0}
/>
<Navigation activeTab={this.props.activeTab || 'mods+'} />
</div>
<div style={{ height: '112px', width: '100%' }} />
</div>
);
}
}
Header.propTypes = {
activeTab: PropTypes.string.isRequired,
isLoggedIn: PropTypes.bool.isRequired,
email: PropTypes.string,
id: PropTypes.number,
navigate: PropTypes.func.isRequired,
handleSwitchSemester: PropTypes.func.isRequired,
isSemesterOne: PropTypes.bool.isRequired,
};
const mapState = (state) => ({
isLoggedIn: !!state.user.data.id,
email: state.user.data.email,
id: state.user.data.id,
});
export default connect(mapState, { navigate })(withStyles(s)(Header));
|
/* Black BaaS demo
* Distributed under an GPL_v4 license, please see LICENSE in the top dir.
*/
/*global requirejs, require*/
requirejs.config({
baseUrl : '/',
paths: {
lib : '../lib',
client: '../basic',
jquery : '../lib/jquery',
},
map: {
'lib': {
backbone: 'lib/backbone'
}
}
});
require(['jquery', 'lib/backbone'], function($, Backbone){
'use strict';
function _init(){
session.init();
function retry(xhr, status /*, error */){
/* jshint validthis:true */
if(this.tryCount < this.maxTries){
console.error('%s: %s... retrying', xhr, status);
this.tryCount++;
var self = this;
setTimeout(function(){
$.ajax(self);
}, 3000);
}
else{
console.error("couldn't process request!");
//ToDo: show some message dialog to the user
}
}
/* If network timeout or internal server error, retry */
$.ajaxSetup({
tryCount: 0,
maxTries: 3,
statusCode: {
408: retry,
500: retry,
504: retry,
522: retry,
524: retry,
598: retry
}
});
}
/* To allow navigation that changes a URL without loading a new
* page, all page main scripts return a function that sets up the new view
* (since just doing require(['foo']) will be a noop the second time it
* is called in a page).
*
* These scripts get the router, so they can listen to route
* events to destroy their views, add new routes or request
* navigation.
*/
var router;
var AppRouter = Backbone.Router.extend({
routes: {
"": 'home',
"admin(/)": 'admin',
"users/:id/sources/": 'sources',
"works(?:filters)(/)": 'works',
"works/:id(/)": 'work',
"works/:id/posts(/)": 'posts',
"works/:id/sources(/)": 'sources',
"login(/)": 'login'
},
admin: function(){
require(['admin'], function(view) { view(router); });
},
home: function() {
require(['home'], function(view) { view(router); });
},
login: function(){
// require(['login'], function(view) { view(router); });
},
posts: function(id){
require(['posts'], function(view) { view(router); });
},
sources: function(id){
require(['sources'], function(view) { view(router, id); });
},
works: function(filters) {
require(['browseWorks'], function(view) { view(router, filters); });
},
work: function (id) {
require(['workPermalink'], function(view) { view(router, id); });
}
});
router = new AppRouter();
Backbone.history.start({pushState:true});
if(document.readyState === 'complete'){
_init();
} else {
document.onready = _init;
}
return;
});
|
'use strict';
module.exports = {
echo: async function (req, res, next) {
res.json('ok');
},
echoPost: async function (req, res, next) {
res.json('ok');
}
};
|
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PurifyCSSPlugin = require('purifycss-webpack-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
exports.setup = function (include) {
return {
module: {
loaders: [
{
test: /\.s?(a|c)ss$/,
loaders: ['style', 'css', 'sass'],
include,
},
],
},
};
};
exports.extract = function (include) {
return {
module: {
loaders: [
// Extract CSS during build
{
test: /\.s?(a|c)ss$/,
loader: ExtractTextPlugin.extract('style', 'css!sass'),
include,
},
],
},
plugins: [
// Output extracted CSS to a file
new ExtractTextPlugin('[name].[chunkhash].css'),
],
};
};
exports.purify = function (paths) {
return {
plugins: [
new PurifyCSSPlugin({
basePath: process.cwd(),
// 'paths' is used to point PurifyCSS to files not
// visible to Webpack. You can pass glob patterns
// to it.
paths,
}),
],
};
};
exports.lint = function (context) {
return {
plugins: [
new StyleLintPlugin({
configFile: '.stylelintrc.json',
files: ['**/*.scss'],
syntax: 'scss',
context,
}),
],
};
};
|
'use strict';
var gutil = require('gulp-util');
var through = require('through2');
var cssresources = require("css-resources");
var fs = require("fs");
var path = require("path");
var mkdirp = require("mkdirp");
var cssResourcesMove = function(options) {
options = options || {};
return through.obj(function(file, enc, cb) {
if (file.isNull()) return cb(null, file); // pass along
if (file.isStream()) return cb(new error('gulp-cssresourcesmove: Streaming not supported'), file);
var content = file.contents.toString(enc);
if (!content) return cb(null, file); // pass along
var images = cssresources(content);
var times = 0;
var complete = function(){
times--;
if(times === 0){
cb(null, file);
}
}
for(var idx in images){
var imagePath = getFilePath(images[idx].path);
imagePath = imagePath.trim();
if(/^data:image/.test(imagePath)){
continue;
}else if(/^(?:(?:https?:)?\/\/)/.test(imagePath)){
continue;
}else if(imagePath.indexOf("/") !== 0){
imagePath = path.normalize(path.join(path.dirname(file.path),imagePath)).replace(options.WebRoot,"");
}
var destPath = options.dest + imagePath;
var resourcePath = options.WebRoot + imagePath;
fs.stat(resourcePath,function(err,stat){
var targetPath = this.targetPath;
var resourcePath = this.resourcePath;
if(err){
if(err.errno === -2){
gutil.log("Can not find file ",err.path);
complete();
}else{
throw err;
}
}else if(stat.isFile()){
fs.readFile(resourcePath,function(err,data){
if(err){
complete();
}else{
mkdirp(path.dirname(targetPath), function (err) {
if(err){
throw err
}else{
fs.writeFile(targetPath,data,function(err){
if(err) throw err;
complete();
});
}
});
}
});
}else{
complete();
gutil.log(resourcePath+" is not a file path!");
}
}.bind({targetPath:destPath,resourcePath:resourcePath}));
times++;
}
if(times === 0){
cb(null, file);
}
});
};
var getFilePath = function(alterName){
var symbols = ["?","#"];
var resultStr = alterName;
for(var idx in symbols){
if(resultStr.lastIndexOf(symbols[idx])>-1){
resultStr = resultStr.substring(0,alterName.lastIndexOf(symbols[idx]));
}
}
return resultStr;
}
module.exports = cssResourcesMove;
|
var THREE = require('three');
function Repere(material) {
if (material === undefined) {
material = new THREE.MeshPhongMaterial({
color: 0x0ddeed,
});
}
var repere = new THREE.Object3D();
var x = new THREE.Mesh(new THREE.BoxGeometry(10, 1, 1), material);
x.position.x += 5;
repere.add(x);
var y = new THREE.Mesh(new THREE.BoxGeometry(1, 10, 1), material);
y.position.y += 5;
repere.add(y);
var z = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 10), material);
z.position.z += 5;
repere.add(z);
return repere;
}
module.exports = Repere;
|
var Emery = require('./emery').Emery;
var class = require('./class').class;
var Enumerable = require('./enumerable').Enumerable;
var EString = require('./string').EString;
var ENumber = require('./number').ENumber;
var EArray = require('./array').EArray;
var RangeError = require('./exception').RangeError;
var ArgumentError = require('./exception').ArgumentError;
var NotImplementedError = require('./exception').NotImplementedError;
exports.ERange = ERange = class( {
/**
* Constructs a range using the given start and end. If the third parameter
* is omitted or is false, the range will include the end object; otherwise,
* it will be excluded.
*/
initialize: function(start, end, exclusive) {
if( Emery.ISUNDEFORNULL(exclusive) ) exclusive = false
var undefargs = Emery.NODEF_ARGS(start, end)
if( undefargs > 0 ) {
throw( new ArgumentError("wrong number of arguments ("+(2-undefargs)+" for 2)") )
}
var _start = start
var _end = end
if( Emery.ISALPHA(start) ) _start = new EString(start);
if( Emery.ISALPHA(end) ) _end = new EString(end);
if( Emery.ISDIGIT(start) ) _start = new ENumber(start);
if( Emery.ISDIGIT(end) ) _end = new ENumber(end);
if( Emery.CLASS(_start) != Emery.CLASS(_end) || _start.cmp(_end) > 0) {
throw( new ArgumentError("bad value for range") )
}
try {
_start.succ()
}
catch(e) {
throw( new ArgumentError("bad value for range") )
}
try {
_end.succ()
}
catch(e) {
throw( new ArgumentError("bad value for range") )
}
var tmp = []
var x = _start
while( x.cmp(_end) != 0 ) {
if( (Emery.ISALPHA(start) || Emery.ISDIGIT(start)) && (Emery.ISALPHA(end) || Emery.ISDIGIT(end)) ) {
tmp.push(x.to_js())
} else {
tmp.push(x)
}
x = x.succ()
}
if( exclusive == false ) {
if( (Emery.ISALPHA(start) || Emery.ISDIGIT(start)) && (Emery.ISALPHA(end) || Emery.ISDIGIT(end)) ) {
tmp.push(x.to_js())
} else {
tmp.push(x)
}
}
this.__start__ = start
this.__end__ = end
this.__data__ = tmp
this.__exclusive__ = exclusive
this.length = this.__data__.length
},
/**
* Returns the first object in range.
*/
begin: function() {
return( this.__start__ )
},
/**
* Returns true if obj is between beg and end, i.e beg <= obj <= end
* (or end exclusive when exclude_end? is true).
*/
cover: function(e) {
return( this.include(e) );
},
/**
* Iterates over the elements rng, passing each in turn to the block. You can only iterate
* if the start object of the range supports the succ method (which means that you can’t
* iterate over ranges of Float objects).
*/
each: function(callback) {
for( i in this.__data__ ) {
callback(this.__data__[i])
}
},
/**
* Returns the object that defines the end of rng.
*/
end: function() {
return( this.__end__ )
},
/**
* Returns true only if obj is a Range, has equivalent beginning and end items
* (by comparing them with eql?), and has the same exclude_end? setting as rng.
*/
eql: function(r) {
throw( new NotImplementedError() ); // -> TODO
},
/**
* Returns true if rng excludes its end value.
*/
exclude_end: function() {
return( this.__exclusive__ )
},
/**
* Returns the first object in rng, or the first n elements.
*/
first: function(n) {
var ret = this.to_a()
return( ret.first(n) )
},
/**
* Generate a hash value such that two ranges with the same start and end points,
* and the same value for the “exclude end” flag, generate the same hash value.
*/
hash: function(callback) {
throw( new NotImplementedError() ); // -> TODO
},
/**
* Returns the last object in rng, or the last n elements.
*/
last: function(n) {
var ret = this.to_a()
return( ret.last(n) )
},
/**
* Returns true if obj is an element of rng, false otherwise. If beg and end are
* numeric, comparison is done according magnitude of values.
*/
member: function(e) {
return( this.include(e) )
},
/**
* Convert this range object to a printable form (using inspect to convert the start and end objects).
*/
inspect: function() {
var ret = "["
var sep = " "
this.each(function(e){
if( typeof(e) == 'string' ) {
ret += sep + "'"+e+"'"
} else {
ret += sep + e
}
sep = ", "
})
ret += " ]"
return( ret )
},
pretty_print: function() {
return( this.inspect() )
},
to_s: function() {
return( this.inspect() )
},
to_js: function() {
return( this.__data__ )
},
/**
* Return the EArray
*/
to_a: function() {
return( new EArray(this.__data__) )
},
/**
* Iterates over rng, passing each nth element to the block. If the range contains numbers,
* n is added for each iteration. Otherwise step invokes succ to iterate through range elements.
* The following code uses class Xs, which is defined in the class-level documentation.
*/
step: function(n, callback) {
if( Emery.ISUNDEFORNULL(callback) ) {
callback = n
n = 1
}
var i = 0
this.each(function(e) {
i++
if( i%n == 1 ) callback(e)
})
},
/**
* Invokes block once for each element of self. Creates a new array containing
* the values returned by the block.
*/
map: function( callback ) {
var ret = []
for( i in this.__data__ ) {
ret.push( callback(this.__data__[i]) )
}
return( new EArray(ret) )
},
} );
ERange.include(Enumerable);
|
window.addEvent('domready',function(){
var loader = new Mif.Tree.Loader(function(node){
// if node name 'empty' load from url 'empty.json'
if(!(node instanceof Mif.Tree.Item)) return {};
return node.get('name')=='empty' ? 'Tree/files/empty.json' : 'Tree/files/mediumTree.json';
});
var tree = new Mif.Tree({
container: $('tree_container'),
forest: true,
loader: loader,
initialize: function(){
new Mif.Tree.Drag(this, {
droppables: [
new Mif.Tree.Drag.Element('drop_container',{
onDrop: function(node){
$('drop').adopt(new Element('li',{html: node.get('name')}));
}
})
],
onDrop: function(current, target, where){
//console.log(current, target, where);
}
});
},
types: {
folder:{
openIcon: 'mif-tree-open-icon',
closeIcon: 'mif-tree-close-icon'
},
loader:{
openIcon: 'mif-tree-loader-open-icon',
closeIcon: 'mif-tree-loader-close-icon',
dropDenied: ['inside','after']
},
disabled:{
openIcon: 'mif-tree-open-icon',
closeIcon: 'mif-tree-close-icon',
dragDisabled: true,
cls: 'disabled'
},
book:{
openIcon: 'mif-tree-book-icon-open',
closeIcon: 'mif-tree-book-icon',
loadable: true
},
books:{
openIcon: 'mif-tree-books-icon',
closeIcon: 'mif-tree-books-icon'
},
smiley:{
openIcon: 'mif-tree-smiley-open-icon',
closeIcon: 'mif-tree-smiley-close-icon'
}
},
dfltType:'folder',
onCopy: function(from, to, where, copy){
if(from.getParent()==copy.getParent()){
copy.set({
name: 'copy '+from.get('name')
});
}
}
});
//tree.initSortable();
tree.load({
url: 'Tree/files/forest.json'
});
var tree2 = new Mif.Tree({
container: $('tree_container2'),
forest: true,
loader: loader,
initialize: function(){
new Mif.Tree.Drag(this);
},
types: {
dflt:{
openIcon: 'mif-tree-open-icon',
closeIcon: 'mif-tree-close-icon'
},
loader:{
openIcon: 'mif-tree-loader-open-icon',
closeIcon: 'mif-tree-loader-close-icon',
dropDenied: ['inside','after']
},
disabled:{
openIcon: 'mif-tree-open-icon',
closeIcon: 'mif-tree-close-icon',
dragDisbled: true,
cls: 'disabled'
},
book:{
openIcon: 'mif-tree-book-icon-open',
closeIcon: 'mif-tree-book-icon',
loadable: true
},
books:{
openIcon: 'mif-tree-books-icon',
closeIcon: 'mif-tree-books-icon'
},
smiley:{
openIcon: 'mif-tree-smiley-open-icon',
closeIcon: 'mif-tree-smiley-close-icon'
}
},
onCopy: function(from, to, where, copy){
if(from.getParent()==copy.getParent()){
copy.set({
name: 'copy '+from.get('name')
});
}
}
});
var json=[
{
"name": "root",
"children": [
{
"name": "node1"
},
{
"name": "node2",
"children":[
{
"name": "node2.1"
},
{
"name": "node2.2"
}
]
},
{
"name": "node4"
},
{
"name": "node3"
}
]
}
];
tree2.load(json);
});
|
const sprkFormatPhone = (value) => {
const newValue = `${value}`.replace(/\D/g, '');
const m = newValue.match(/^(\d{3})(\d{3})(\d{4})$/);
return m === false || m === null ? '' : `(${m[1]}) ${m[2]}-${m[3]}`;
};
export { sprkFormatPhone as default };
|
/**
* Nested Record Array of SC.Records Unit Test
*
* @author Evin Grano
*/
// ..........................................................
// Basic Set up needs to move to the setup and teardown
//
var NestedRecord, store, testParent, testParent2;
var initModels = function(){
NestedRecord.ParentRecordTest = SC.Record.extend({
/** Child Record Namespace */
nestedRecordNamespace: NestedRecord,
name: SC.Record.attr(String),
elements: SC.Record.toMany('SC.Record', { nested: true })
});
NestedRecord.ChildRecordTest1 = SC.Record.extend({
name: SC.Record.attr(String),
value: SC.Record.attr(String)
});
NestedRecord.ChildRecordTest2 = SC.Record.extend({
name: SC.Record.attr(String),
info: SC.Record.attr(String),
value: SC.Record.attr(String)
});
};
// ..........................................................
// Basic SC.Record with an Array of Children
//
module("Basic SC.Record w/ a Parent > Array of Children", {
setup: function() {
NestedRecord = SC.Object.create({
store: SC.Store.create()
});
store = NestedRecord.store;
initModels();
SC.RunLoop.begin();
testParent = store.createRecord(NestedRecord.ParentRecordTest, {
name: 'Parent Name',
elements: [
{
type: 'ChildRecordTest1',
name: 'Child 1',
value: 'eeney'
},
{
type: 'ChildRecordTest2',
name: 'Child 2',
info: 'This is the other type',
value: 'meeney'
},
{
type: 'ChildRecordTest1',
name: 'Child 3',
value: 'miney'
},
{
type: 'ChildRecordTest1',
name: 'Child 4',
value: 'moe'
}
]
});
// FIXME: [EG] this configuration should work
testParent2 = store.createRecord(NestedRecord.ParentRecordTest, {
name: 'Parent 2',
elements: []
});
SC.RunLoop.end();
},
teardown: function() {
delete NestedRecord.ParentRecordTest;
delete NestedRecord.ChildRecordTest;
testParent = null;
testParent2 = null;
store = null;
NestedRecord = null;
}
});
test("Function: readAttribute()", function() {
var elemsAry = testParent.readAttribute('elements');
ok(elemsAry, "check to see that the child records array exists");
equals(elemsAry.get('length'), 4, "checking to see that the length of the elements array is 4");
same(elemsAry[0],
{
type: 'ChildRecordTest1',
name: 'Child 1',
value: 'eeney'
},
"check to see if the first child is as expected");
same(elemsAry[3],
{
type: 'ChildRecordTest1',
name: 'Child 4',
value: 'moe'
},
"check to see if the last child is as expected");
});
test("Function: writeAttribute()", function() {
testParent.writeAttribute('elements',
[
{
type: 'ChildRecordTest1',
name: 'Tom',
value: 'Jones'
},
{
type: 'ChildRecordTest1',
name: 'Dick',
value: 'Smothers'
},
{
type: 'ChildRecordTest1',
name: 'Harry',
value: 'Balls'
}
]
);
var elemsAry = testParent.readAttribute('elements');
ok(elemsAry, "after writeAttribute(), check to see that the child records array exists");
equals(elemsAry.length, 3, "after writeAttribute(), checking to see that the length of the elements array is 3");
same(elemsAry[0],
{
type: 'ChildRecordTest1',
name: 'Tom',
value: 'Jones'
},
"check to see if the first child is as expected");
same(elemsAry[2],
{
type: 'ChildRecordTest1',
name: 'Harry',
value: 'Balls'
},
"check to see if the last child is as expected");
});
test("Basic Read", function() {
// Test general gets
equals(testParent.get('name'), 'Parent Name', "get should be correct for name attribute");
equals(testParent.get('nothing'), null, "get should be correct for invalid key");
// Test Child Record creation
var arrayOfCRs = testParent.get('elements');
// Check Model Class information
ok(SC.instanceOf(arrayOfCRs, SC.NestedArray), "check that get() creates an actual instance of a SC.NestedArray");
equals(arrayOfCRs.get('length'), 4, "check that the length of the array of child records is 4");
var cr = arrayOfCRs.objectAt(0);
ok(SC.kindOf(cr, SC.Record), "check that first ChildRecord from the get() creates an actual instance that is a kind of a SC.Record Object");
ok(SC.instanceOf(cr, NestedRecord.ChildRecordTest1), "check that first ChildRecord from the get() creates an actual instance of a ChildRecordTest1 Object");
// Check reference information
var pm = cr.get('primaryKey');
var key = cr.get(pm);
var storeRef = store.find(NestedRecord.ChildRecordTest1, key);
ok(storeRef, 'check that first ChildRecord that the store has the instance of the child record with proper primary key');
equals(cr, storeRef, "check the parent reference to the first child is the same as the direct store reference");
// Check to see if the attributes of a Child Record match the refrence of the parent
var parentArray = testParent.readAttribute('elements');
ok(!SC.instanceOf(parentArray, SC.NestedArray), "check that get() creates an actual instance of a SC.NestedArray");
same(parentArray[0], storeRef.get('attributes'), "check that the ChildRecord's attributes are the same as the ParentRecord's readAttribute for the reference");
// // Duplication check
var sameArray = testParent.get('elements');
ok(sameArray, 'check to see that we get an array on the second call to the parent for the child records');
equals(sameArray.get('length'), 4, "check that the length of the array of child records is still 4");
var sameCR = sameArray.objectAt(0);
ok(sameCR, "check to see if we have an instance of a child record again");
var oldKey = cr.get(pm), newKey = sameCR.get(pm);
equals(oldKey, newKey, "check to see if the primary key are the same");
equals(SC.guidFor(cr), SC.guidFor(sameCR), "check to see if the guid are the same");
same(sameCR, cr, "check to see that it is the same child record as before");
});
test("Basic Write", function() {
// Test general gets
testParent.set('name', 'New Parent Name');
equals(testParent.get('name'), 'New Parent Name', "set() should change name attribute");
testParent.set('nothing', 'nothing');
equals(testParent.get('nothing'), 'nothing', "set should change non-existent property to a new property");
// Test Child Record creation
var oldCR = testParent.get('elements');
var newChildren = [
{ type: 'ChildRecordTest1', name: 'Tom', value: 'Jones'},
{ type: 'ChildRecordTest1', name: 'Dick', value: 'Smothers'},
{ type: 'ChildRecordTest1', name: 'Harry', value: 'Balls'}
];
testParent.set('elements', newChildren);
var newArray = testParent.get('elements');
ok(SC.instanceOf(newArray, SC.NestedArray), "check that get() creates an actual instance of a SC.NestedArray");
equals(newArray.get('length'), 3, "after set() on parent, check that the length of the array of child records is 3");
var cr = newArray.objectAt(0);
ok(SC.kindOf(cr, SC.Record), "check that first ChildRecord from the get() creates an actual instance that is a kind of a SC.Record Object");
ok(SC.instanceOf(cr, NestedRecord.ChildRecordTest1), "check that first ChildRecord from the get() creates an actual instance of a ChildRecordTest1 Object");
});
test("Basic Write: reference tests", function() {
var pm, elems, cr, key, storeRef, newElems;
elems = testParent.get('elements');
cr = elems.objectAt(0);
// TODO: [EG] Add test to make sure the number of ChildRecords in store
// Check reference information
pm = cr.get('primaryKey');
key = cr.get(pm);
storeRef = store.find(NestedRecord.ChildRecordTest1, key);
ok(storeRef, 'after a set() with an object, checking that the store has the instance of the child record with proper primary keys');
equals(cr, storeRef, "after a set with an object, checking the parent reference is the same as the direct store reference");
// Check for changes on the child bubble to the parent.
cr.set('name', 'Child Name Change');
equals(cr.get('name'), 'Child Name Change', "after a set('name', <new>) on child, checking that the value is updated");
ok(cr.get('status') & SC.Record.DIRTY, 'check that the child record is dirty');
ok(testParent.get('status') & SC.Record.DIRTY, 'check that the parent record is dirty');
newElems = testParent.get('elements');
var newCR = newElems.objectAt(0);
same(newCR, cr, "after a set('name', <new>) on child, checking to see that the parent has recieved the changes from the child record");
var readAttrsArray = testParent.readAttribute('elements');
ok(readAttrsArray, "checks to make sure the readAttibute works with a change to the name in the first child.");
equals(readAttrsArray.length, 4, "after set() on parent, check that the length of the attribute array of child records is 4");
same(readAttrsArray[0], newCR.get('attributes'), "after a set('name', <new>) on child, readAttribute on the parent should be correct for info child attributes");
});
test("Basic Array Functionality: pushObject w/ HASH", function() {
var elements, elementsAttrs, cr, crFirst, crLast;
// Add something to the array
elements = testParent.get('elements');
// PushObject Tests
elements.pushObject({ type: 'ChildRecordTest1', name: 'Testikles', value: 'God Of Fertility'});
elements = testParent.get('elements');
equals(elements.get('length'), 5, "after pushObject() on parent, check that the length of the array of child records is 5");
cr = elements.objectAt(4);
ok(SC.kindOf(cr, SC.Record), "check that newly added ChildRecord creates an actual instance that is a kind of a SC.Record Object");
ok(SC.instanceOf(cr, NestedRecord.ChildRecordTest1), "check that newly added ChildRecord creates an actual instance of a ChildRecordTest1 Object");
equals(cr.get('name'), 'Testikles', "after a pushObject on parent, check to see if it has all the right values for the attributes");
ok(cr.get('status') & SC.Record.DIRTY, 'check that the child record is dirty');
ok(testParent.get('status') & SC.Record.DIRTY, 'check that the parent record is dirty');
// Verify the Attrs
elementsAttrs = testParent.readAttribute('elements');
equals(elementsAttrs.length, 5, "after pushObject() on parent, check that the length of the attribute array of child records is 5");
crFirst = elements.objectAt(0).get('attributes');
crLast = elements.objectAt(4).get('attributes');
same(elementsAttrs[0], crFirst, "verify that parent attributes are the same as the first individual child attributes");
same(elementsAttrs[4], crLast, "verify that parent attributes are the same as the last individual child attributes");
});
test("Basic Array Functionality: pushObject w/ ChildRecord", function() {
var elements, elementsAttrs, cr, crFirst, crLast;
// Add something to the array
elements = testParent.get('elements');
// PushObject Tests
cr = store.createRecord(NestedRecord.ChildRecordTest1, { type: 'ChildRecordTest1', name: 'Testikles', value: 'God Of Fertility'});
elements.pushObject(cr);
elements = testParent.get('elements');
equals(elements.get('length'), 5, "after pushObject() on parent, check that the length of the array of child records is 5");
cr = elements.objectAt(4);
ok(SC.kindOf(cr, SC.Record), "check that newly added ChildRecord creates an actual instance that is a kind of a SC.Record Object");
ok(SC.instanceOf(cr, NestedRecord.ChildRecordTest1), "check that newly added ChildRecord creates an actual instance of a ChildRecordTest1 Object");
equals(cr.get('name'), 'Testikles', "after a pushObject on parent, check to see if it has all the right values for the attributes");
ok(cr.get('status') & SC.Record.DIRTY, 'check that the child record is dirty');
ok(testParent.get('status') & SC.Record.DIRTY, 'check that the parent record is dirty');
// Verify the Attrs
elementsAttrs = testParent.readAttribute('elements');
equals(elementsAttrs.length, 5, "after pushObject() on parent, check that the length of the attribute array of child records is 5");
crFirst = elements.objectAt(0).get('attributes');
crLast = elements.objectAt(4).get('attributes');
same(elementsAttrs[0], crFirst, "verify that parent attributes are the same as the first individual child attributes");
same(elementsAttrs[4], crLast, "verify that parent attributes are the same as the last individual child attributes");
});
test("Basic Array Functionality: popObject", function() {
var elements, elementsAttrs, cr, crFirst, crLast;
// Add something to the array
elements = testParent.get('elements');
// PopObject Tests
elements.popObject();
elements = testParent.get('elements');
equals(elements.get('length'), 3, "after popObject() on parent, check that the length of the array of child records is 3");
ok(testParent.get('status') & SC.Record.DIRTY, 'check that the parent record is dirty');
// Verify the Attrs
elementsAttrs = testParent.readAttribute('elements');
equals(elementsAttrs.length, 3, "after pushObject() on parent, check that the length of the attribute array of child records is 3");
crFirst = elements.objectAt(0).get('attributes');
crLast = elements.objectAt(2).get('attributes');
same(elementsAttrs[0], crFirst, "verify that parent attributes are the same as the first individual child attributes");
same(elementsAttrs[2], crLast, "verify that parent attributes are the same as the last individual child attributes");
});
test("Basic Array Functionality: popObject and pushObject different type", function() {
var elements, elementsAttrs, cr, crFirst, crLast, poppedObject;
// Add something to the array
elements = testParent.get('elements');
// PopObject Tests
poppedObject = elements.popObject();
ok(SC.instanceOf(poppedObject, NestedRecord.ChildRecordTest1), "check that popped ChildRecord was an actual instance of a ChildRecordTest1 Object");
elements = testParent.get('elements');
equals(elements.get('length'), 3, "after popObject() on parent, check that the length of the array of child records is 3");
ok(testParent.get('status') & SC.Record.DIRTY, 'check that the parent record is dirty');
// Verify the Attrs
elementsAttrs = testParent.readAttribute('elements');
equals(elementsAttrs.length, 3, "after pushObject() on parent, check that the length of the attribute array of child records is 3");
crFirst = elements.objectAt(0).get('attributes');
crLast = elements.objectAt(2).get('attributes');
same(elementsAttrs[0], crFirst, "verify that parent attributes are the same as the first individual child attributes");
same(elementsAttrs[2], crLast, "verify that parent attributes are the same as the last individual child attributes");
// PushObject Tests
elements.pushObject({ type: 'ChildRecordTest2', name: 'Testikles', value: 'God Of Fertility'});
elements = testParent.get('elements');
equals(elements.get('length'), 4, "after pushObject() on parent, check that the length of the array of child records is 4");
cr = elements.objectAt(3);
ok(SC.kindOf(cr, SC.Record), "check that newly added ChildRecord creates an actual instance that is a kind of a SC.Record Object");
ok(SC.instanceOf(cr, NestedRecord.ChildRecordTest2), "check that newly added ChildRecord creates an actual instance of a ChildRecordTest2 Object");
equals(cr.get('name'), 'Testikles', "after a pushObject on parent, check to see if it has all the right values for the attributes");
ok(cr.get('status') & SC.Record.DIRTY, 'check that the child record is dirty');
// Verify the Attrs
elementsAttrs = testParent.readAttribute('elements');
equals(elementsAttrs.length, 4, "after pushObject() on parent, check that the length of the attribute array of child records is 4");
crFirst = elements.objectAt(0).get('attributes');
crLast = elements.objectAt(3).get('attributes');
same(elementsAttrs[0], crFirst, "verify that parent attributes are the same as the first individual child attributes");
same(elementsAttrs[3], crLast, "verify that parent attributes are the same as the last individual child attributes");
});
test("Basic Array Functionality: removeAt and pushObject different type, repeated", function() {
var elements, elementsAttrs, cr, crFirst, crLast, poppedObject;
// Add something to the array
elements = testParent.get('elements');
elements.removeAt(1);
equals(elements.get('length'), 3, "after removeAt(1) on parent, check that the length of the array of child records is 3");
// PushObject Tests
elements.pushObject({ type: 'ChildRecordTest2', name: 'Testikles', value: 'God Of Fertility'});
elements = testParent.get('elements');
equals(elements.get('length'), 4, "after pushObject() on parent, check that the length of the array of child records is 4");
cr = elements.objectAt(3);
ok(SC.kindOf(cr, SC.Record), "check that newly added ChildRecord creates an actual instance that is a kind of a SC.Record Object");
ok(SC.instanceOf(cr, NestedRecord.ChildRecordTest2), "check that newly added ChildRecord creates an actual instance of a ChildRecordTest2 Object");
equals(cr.get('name'), 'Testikles', "after a pushObject on parent, check to see if it has all the right values for the attributes");
ok(cr.get('status') & SC.Record.DIRTY, 'check that the child record is dirty');
// Verify the Attrs
elementsAttrs = testParent.readAttribute('elements');
equals(elementsAttrs.length, 4, "after pushObject() on parent, check that the length of the attribute array of child records is 4");
crFirst = elements.objectAt(0).get('attributes');
crLast = elements.objectAt(3).get('attributes');
same(elementsAttrs[0], crFirst, "verify that parent attributes are the same as the first individual child attributes");
same(elementsAttrs[3], crLast, "verify that parent attributes are the same as the last individual child attributes");
// now repeat
elements.removeAt(0);
equals(elements.get('length'), 3, "after removeAt(0) on parent, check that the length of the array of child records is 3");
// PushObject Tests
elements.pushObject({ type: 'ChildRecordTest1', name: 'Testikles 2', value: 'God Of Fertility 2'});
elements = testParent.get('elements');
equals(elements.get('length'), 4, "after pushObject() on parent (2), check that the length of the array of child records is 4");
cr = elements.objectAt(3);
ok(SC.kindOf(cr, SC.Record), "check that newly added ChildRecord (2) creates an actual instance that is a kind of a SC.Record Object");
ok(SC.instanceOf(cr, NestedRecord.ChildRecordTest1), "check that newly added ChildRecord (2) creates an actual instance of a ChildRecordTest1 Object");
equals(cr.get('name'), 'Testikles 2', "after a pushObject (2) on parent, check to see if it has all the right values for the attributes");
ok(cr.get('status') & SC.Record.DIRTY, 'check that the child record is dirty');
// Verify the Attrs
elementsAttrs = testParent.readAttribute('elements');
equals(elementsAttrs.length, 4, "after pushObject() (2) on parent, check that the length of the attribute array of child records is 4");
crFirst = elements.objectAt(0).get('attributes');
crLast = elements.objectAt(3).get('attributes');
same(elementsAttrs[0], crFirst, "verify that parent attributes are the same as the first individual child attributes (2)");
same(elementsAttrs[3], crLast, "verify that parent attributes are the same as the last individual child attributes (2)");
});
test("Basic Array Functionality: shiftObject", function() {
var elements, cr;
// Add something to the array
elements = testParent.get('elements');
// PushObject Tests
elements.shiftObject();
elements = testParent.get('elements');
equals(elements.get('length'), 3, "after shiftObject() on parent, check that the length of the array of child records is 3");
ok(testParent.get('status') & SC.Record.DIRTY, 'check that the parent record is dirty');
});
test("Basic Array Functionality: unshiftObject", function() {
var elements, elementsAttrs, cr, crFirst, crLast;
// Add something to the array
elements = testParent.get('elements');
// PushObject Tests
elements.unshiftObject({ type: 'ChildRecordTest1', name: 'Testikles', value: 'God Of Fertility'});
elements = testParent.get('elements');
equals(elements.get('length'), 5, "after pushObject() on parent, check that the length of the array of child records is 5");
cr = elements.objectAt(0);
ok(SC.kindOf(cr, SC.Record), "check that newly added ChildRecord creates an actual instance that is a kind of a SC.Record Object");
ok(SC.instanceOf(cr, NestedRecord.ChildRecordTest1), "check that newly added ChildRecord creates an actual instance of a ChildRecordTest1 Object");
equals(cr.get('name'), 'Testikles', "after a pushObject on parent, check to see if it has all the right values for the attributes");
ok(cr.get('status') & SC.Record.DIRTY, 'check that the child record is dirty');
ok(testParent.get('status') & SC.Record.DIRTY, 'check that the parent record is dirty');
// Verify the Attrs
elementsAttrs = testParent.readAttribute('elements');
equals(elementsAttrs.length, 5, "after pushObject() on parent, check that the length of the attribute array of child records is 5");
crFirst = elements.objectAt(0).get('attributes');
crLast = elements.objectAt(4).get('attributes');
same(elementsAttrs[0], crFirst, "verify that parent attributes are the same as the first individual child attributes");
same(elementsAttrs[4], crLast, "verify that parent attributes are the same as the last individual child attributes");
});
test("Create Parent with Broken Child Array", function(){
var elements = testParent2.get('elements');
ok (!SC.none(elements), "elements should be something");
var isChildRecordArrays = elements.instanceOf(SC.NestedArray);
ok(isChildRecordArrays, 'elements array is of right type');
var length = elements.get('length');
equals(length, 0, 'length should be zero');
elements.pushObject({type: 'ChildRecordTest1',name: 'Child 1',value: 'eeney'});
length = elements.get('length');
equals(length, 1, 'length should be one');
});
test("Index-based getPath() with unknownProperty()", function() {
var e1 = testParent.getPath('elements.1');
ok(!SC.none(e1), 'Element should not be null or undefined');
equals(e1.get('name'), 'Child 2', 'Should have picked up the correct element (tested by name)');
});
test("Basic Array Functionality: insertAt w/ HASH", function() {
var elements, elementsAttrs, cr, crFirst, crLast;
// Add something to the array
elements = testParent.get('elements');
// PushObject Tests
elements.insertAt(3, { type: 'ChildRecordTest1', name: 'Testikles', value: 'God Of Fertility'});
elements = testParent.get('elements');
equals(elements.get('length'), 5, "after insertAt() on parent, check that the length of the array of child records is 5");
cr = elements.objectAt(3);
ok(SC.kindOf(cr, SC.Record), "check that newly added ChildRecord creates an actual instance that is a kind of a SC.Record Object");
ok(SC.instanceOf(cr, NestedRecord.ChildRecordTest1), "check that newly added ChildRecord creates an actual instance of a ChildRecordTest1 Object");
equals(cr.get('name'), 'Testikles', "after a insertAt on parent, check to see if it has all the right values for the attributes");
ok(cr.get('status') & SC.Record.DIRTY, 'check that the child record is dirty');
ok(testParent.get('status') & SC.Record.DIRTY, 'check that the parent record is dirty');
cr = elements.objectAt(4);
ok(SC.kindOf(cr, SC.Record), "check that existing last ChildRecord is an actual instance that is a kind of a SC.Record Object");
ok(SC.instanceOf(cr, NestedRecord.ChildRecordTest1), "check that existing last ChildRecordChildRecord is an actual instance of a ChildRecordTest1 Object");
equals(cr.get('name'), 'Child 4', "after a insertAt on parent, check to see if it has all the right values for the attributes");
equals(cr.get('value'), 'moe', "after a insertAt on parent, check to see if it has all the right values for the attributes");
});
test("Basic Array Functionality: insertAt w/ ChildRecord", function() {
var elements, elementsAttrs, cr, crFirst, crLast;
// Add something to the array
elements = testParent.get('elements');
// PushObject Tests
cr = store.createRecord(NestedRecord.ChildRecordTest1, { type: 'ChildRecordTest1', name: 'Testikles', value: 'God Of Fertility'});
elements.insertAt(3, cr);
elements = testParent.get('elements');
equals(elements.get('length'), 5, "after insertAt() on parent, check that the length of the array of child records is 5");
cr = elements.objectAt(3);
ok(SC.kindOf(cr, SC.Record), "check that newly added ChildRecord creates an actual instance that is a kind of a SC.Record Object");
ok(SC.instanceOf(cr, NestedRecord.ChildRecordTest1), "check that newly added ChildRecord creates an actual instance of a ChildRecordTest1 Object");
equals(cr.get('name'), 'Testikles', "after a insertAt on parent, check to see if it has all the right values for the attributes");
ok(cr.get('status') & SC.Record.DIRTY, 'check that the child record is dirty');
ok(testParent.get('status') & SC.Record.DIRTY, 'check that the parent record is dirty');
cr = elements.objectAt(4);
ok(SC.kindOf(cr, SC.Record), "check that existing last ChildRecord is an actual instance that is a kind of a SC.Record Object");
ok(SC.instanceOf(cr, NestedRecord.ChildRecordTest1), "check that existing last ChildRecordChildRecord is an actual instance of a ChildRecordTest1 Object");
equals(cr.get('name'), 'Child 4', "after a insertAt on parent, check to see if it has all the right values for the attributes");
equals(cr.get('value'), 'moe', "after a insertAt on parent, check to see if it has all the right values for the attributes");
});
|
import axios from 'axios';
import * as constants from '../constants/chatroomConstants';
export function joinChatroom(user) {
return {
type: constants.JOIN_CHATROOM,
user
};
}
export function leaveChatroom(userId) {
return {
type: constants.LEAVE_CHATROOM,
userId
};
}
export function refreshChatroom() {
return {
type: constants.REFRESH_CHATROOM
};
}
export const updateUsersCounter = function (counter) {
return {
type: constants.UPDATE_USERS_COUNTER,
counter
};
};
export const sendMessage = function (message) {
return {
type: constants.SEND_CHATROOM_MESSAGE,
message
};
};
function fetchChatroomMessagesStart(chatroomId, name) {
return {
type: constants.FETCH_CHATROOM_MESSAGES_START,
chatroomId,
name
};
}
function fetchChatroomMessagesSuccess(messages, done) {
return {
type: constants.FETCH_CHATROOM_MESSAGES_SUCCESS,
messages,
done
};
}
function fetchChatroomMessagesError(error) {
return {
type: constants.FETCH_CHATROOM_MESSAGES_ERROR,
error
};
}
function fetchPartialChatroomMessagesStart(chatroomId) {
return {
type: constants.FETCH_PARTIAL_CHATROOM_MESSAGES_START,
chatroomId
};
}
function fetchPartialChatroomMessagesSuccess(messages, done) {
return {
type: constants.FETCH_PARTIAL_CHATROOM_MESSAGES_SUCCESS,
done,
messages
};
}
function fetchPartialChatroomMessagesError(error) {
return {
type: constants.FETCH_PARTIAL_CHATROOM_MESSAGES_ERROR,
error
};
}
export function fetchChatroomMessagesRequest(chatroomId) {
return function (dispatch, getState) {
const {rooms: {list: rooms}} = getState();
const name = rooms.find(room => room._id === chatroomId).name;
dispatch(fetchChatroomMessagesStart(chatroomId, name));
const query = {
params: {
chatroom: chatroomId
}
};
axios.get('/api/messages', query)
.then(messages => {
dispatch(fetchChatroomMessagesSuccess(messages.data.messages, messages.data.done));
})
.catch(error => {
dispatch(fetchChatroomMessagesError(error.message));
})
};
}
export function fetchPartialChatroomMessagesRequest() {
return function (dispatch, getState) {
const {id, messages} = getState().chatroom;
const query = {
params: {
chatroom: id,
offset: messages.length
}
};
dispatch(fetchPartialChatroomMessagesStart(id));
axios.get('/api/messages', query)
.then(messages => {
dispatch(fetchPartialChatroomMessagesSuccess(messages.data.messages, messages.data.done));
})
.catch(error => {
dispatch(fetchPartialChatroomMessagesError(error.message));
})
};
}
|
export { default } from 'ember-moment/helpers/moment-calendar';
|
/**
* @author Ryan Johnson <ryan@livepipe.net>
* @copyright 2007 LivePipe LLC
* @package Control.Rating
* @license MIT
* @url http://livepipe.net/projects/control_rating/
* @version 1.0.1
*/
if(typeof(Control) == 'undefined')
Control = {};
Control.Rating = Class.create();
Object.extend(Control.Rating,{
instances: [],
findByElementId: function(id){
return Control.Rating.instances.find(function(instance){
return (instance.container.id && instance.container.id == id);
});
}
});
Object.extend(Control.Rating.prototype,{
container: false,
value: false,
options: {},
initialize: function(container,options){
Control.Rating.instances.push(this);
this.value = false;
this.links = [];
this.container = $(container);
this.container.update('');
this.options = {
min: 1,
max: 5,
rated: false,
input: false,
reverse: false,
capture: true,
multiple: false,
classNames: {
off: 'rating_off',
half: 'rating_half',
on: 'rating_on',
selected: 'rating_selected'
},
updateUrl: false,
updateParameterName: 'value',
afterChange: Prototype.emptyFunction
};
Object.extend(this.options,options || {});
if(this.options.value){
this.value = this.options.value;
delete this.options.value;
}
if(this.options.input){
this.options.input = $(this.options.input);
this.options.input.observe('change',function(input){
this.setValueFromInput(input);
}.bind(this,this.options.input));
this.setValueFromInput(this.options.input,true);
}
var range = $R(this.options.min,this.options.max);
(this.options.reverse ? $A(range).reverse() : range).each(function(i){
var link = this.buildLink(i);
this.container.appendChild(link);
this.links.push(link);
}.bind(this));
this.setValue(this.value || this.options.min - 1,false,true);
},
buildLink: function(rating){
var link = $(document.createElement('a'));
link.value = rating;
if(this.options.multiple || (!this.options.rated && !this.options.multiple)){
link.href = '';
link.onmouseover = this.mouseOver.bind(this,link);
link.onmouseout = this.mouseOut.bind(this,link);
link.onclick = this.click.bindAsEventListener(this,link);
}else{
link.style.cursor = 'default';
link.observe('click',function(event){
Event.stop(event);
return false;
}.bindAsEventListener(this));
}
link.addClassName(this.options.classNames.off);
return link;
},
disable: function(){
this.links.each(function(link){
link.onmouseover = Prototype.emptyFunction;
link.onmouseout = Prototype.emptyFunction;
link.onclick = Prototype.emptyFunction;
link.observe('click',function(event){
Event.stop(event);
return false;
}.bindAsEventListener(this));
link.style.cursor = 'default';
}.bind(this));
},
setValueFromInput: function(input,prevent_callbacks){
this.setValue((input.options ? input.options[input.options.selectedIndex].value : input.value),true,prevent_callbacks);
},
setValue: function(value,force_selected,prevent_callbacks){
this.value = value;
if(this.options.input){
if(this.options.input.options){
$A(this.options.input.options).each(function(option,i){
if(option.value == this.value){
this.options.input.options.selectedIndex = i;
throw $break;
}
}.bind(this));
}else
this.options.input.value = this.value;
}
this.render(this.value,force_selected);
if(!prevent_callbacks){
if(this.options.updateUrl){
var params = {};
params[this.options.updateParamterName] = this.value;
new Ajax.Request(this.options.updateUrl,{
parameters: params
});
}
this.notify('afterChange',this.value);
}
},
render: function(rating,force_selected){
(this.options.reverse ? this.links.reverse() : this.links).each(function(link,i){
if(link.value <= Math.ceil(rating)){
link.className = this.options.classNames[link.value <= rating ? 'on' : 'half'];
if(this.options.rated || force_selected)
link.addClassName(this.options.classNames.selected);
}else
link.className = this.options.classNames.off;
}.bind(this));
},
mouseOver: function(link){
this.render(link.value,true);
},
mouseOut: function(link){
this.render(this.value);
},
click: function(event,link){
this.options.rated = true;
this.setValue((link.value ? link.value : link),true);
if(!this.options.multiple)
this.disable();
if(this.options.capture){
Event.stop(event);
return false;
}
},
notify: function(event_name){
try{
if(this.options[event_name])
return [this.options[event_name].apply(this.options[event_name],$A(arguments).slice(1))];
}catch(e){
if(e != $break)
throw e;
else
return false;
}
}
});
if(typeof(Object.Event) != 'undefined')
Object.Event.extend(Control.Rating);
|
var audioContext = require('../core/audioContext');
var Module = require('../core/Module');
var map = require('../core/utils').map;
//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
function Fade() {
this.target = 0.5;
this.duration = 4;
Module.call(this);
}
inherits(Fade, Module);
//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
Fade.prototype.onTrigger = function () {
var currentTime = audioContext.currentTime;
var target = this.target;
var duration = this.duration;
this.$OUT.setAutomation(function (param, min, max) {
var value = param.value;
param.cancelScheduledValues(0);
param.setValueAtTime(value, currentTime);
param.linearRampToValueAtTime(map(target, 0, 1, min, max), currentTime + duration);
});
};
//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
Fade.prototype.descriptor = {
type: 'Fade',
name: 'Fade',
size: 3,
inputs: { TRG: { type: 'event', x:0, y:1, label: 'TRG', endPoint: 'onTrigger' } },
outputs: { OUT: { type: 'param', x:0, y:2, label: 'ENV' } },
controls: {
target: { type: 'knob', x: 2.1, y: 0.3, min: 0, max: 1, value: 'target', label: 'TO' },
duration: { type: 'knob', x: 4.0, y: 0.3, min: 0.1, max: 20, value: 'duration', label: 'TIME' },
}
};
module.exports = Fade;
|
import { describe, it } from 'flow-typed-test';
import createEnturService, { FeatureCategory } from '@entur/sdk'
describe('createEnturService', () => {
it('creates a service', () => {
const service = createEnturService({
clientName: 'flow-typed'
})
});
it('fails if using wrong typefor service', () => {
// $FlowExpectedError[incompatible-type] wrong return type
const numberService: number = createEnturService({
clientName: 'flow-typed'
})
});
})
describe('findTrips', () => {
it('can call findTrips', () => {
const service = createEnturService({
clientName: 'flow-typed'
})
service.findTrips(
'Oslo',
'Bergen'
)
});
it('fails if second parameter is missing', () => {
const service = createEnturService({
clientName: 'flow-typed'
})
// $FlowExpectedError[incompatible-call]
service.findTrips('Oslo')
});
})
describe('getQuaysForStopPlace', () => {
it('can be called with single argument', () => {
const service = createEnturService({ clientName: 'flow-typed' })
const p: Promise<Array<$entur$sdk$Quay>> = service.getQuaysForStopPlace('NSR:StopPlace:1')
});
it('cannot be called without arguments', () => {
const service = createEnturService({ clientName: 'flow-typed' })
// $FlowExpectedError[incompatible-call]
const p: Promise<Array<$entur$sdk$Quay>> = service.getQuaysForStopPlace()
});
it('can be called with options', () => {
const service = createEnturService({ clientName: 'flow-typed' })
const p: Promise<Array<$entur$sdk$Quay>> = service.getQuaysForStopPlace('NSR:StopPlace:1', {
filterByInUse: true
})
});
it('can be called with options', () => {
const service = createEnturService({ clientName: 'flow-typed' })
// $FlowExpectedError[prop-missing]
const p: Promise<Array<$entur$sdk$Quay>> = service.getQuaysForStopPlace('NSR:StopPlace:1', {
allowCheeses: ['camembert', 'brie']
})
});
})
describe('FeatureCategory constants', () => {
it('can use FeatureCategory enum', () => {
const onstreetBus: string = FeatureCategory.ONSTREET_BUS
});
})
|
define({
"_widgetLabel": "Traçat de xarxes",
"_featureAction_NetworkTraceSkip": "Omet al traçat",
"_featureAction_NetworkTraceUnskip": "Elimina de les ubicacions d'exclusió",
"removedFromSkipLocations": "S'ha eliminat de les ubicacions d'exclusió",
"alreadyRemovedFromSkipLocations": "Ja s'ha eliminat de les ubicacions d'exclusió",
"locationSkipped": "La ubicació s'ha omès",
"configError": "El widget no està configurat correctament.",
"geometryServiceURLNotFoundMSG": "No es pot obtenir l'adreça URL del servei de geometria",
"clearButtonValue": "Esborra",
"GPExecutionFailed": "El traçat no es pot completar. Torneu-ho a provar.",
"backButtonValue": "Enrere",
"exportToCSVSuccess": "L'exportació a CSV s'ha completat correctament.",
"lblInputLocTab": "Ubicacions d'entrada",
"lblBlockLocTab": "Bloqueja les ubicacions",
"lblInputLocation": "Entitat d'entrada",
"lblBlockLocation": "Bloqueja l'entitat",
"lblInputLocHeader": "Ubicacions d'entrada (0)",
"lblBlockLocHeader": "Bloqueja les ubicacions (0)",
"inputTabTitle": "Entrada",
"outputTabTitle": "Sortida",
"exportSelectAllCheckBoxLabel": "Selecciona-ho tot",
"lblSkipLocHeader": "Omet les ubicacions (0)",
"lblSkipLocation": "Ubicació",
"lblSkipLocTab": "Omet les ubicacions",
"skipAllLocationButtonLabel": "Omet totes les ubicacions",
"confirmSkipAllLocationsMessage": "Totes les ubicacions s'ometran. Voleu continuar?",
"locationAlreadySkippedMessage": "La ubicació ja s'ha omès",
"removeAllSkipLocationLabel": "Elimina-ho tot",
"newProjectOptionText": "Projecte nou",
"selectProject": "Seleccioneu el projecte",
"saveButtonLabel": "Desa",
"exportToCSVText": "Exporta a CSV",
"editProjectAttributesToolTip": "Edita els atributs del projecte",
"projectNameLabel": "Nom del projecte",
"saveProjectPopupTitle": "Desa",
"saveAsLabel": "Anomena i desa",
"saveChangesMsg": "Voleu desar els canvis a <b>${loadProjectDropdownlabel}</b> o ho voleu desar com un projecte nou?",
"creatingNewProjectErrorMessage": "Error en crear un projecte nou. Torneu-ho a provar.",
"projectNameFetchingErr": "Error en recuperar els noms dels projectes existents. Torneu-ho a provar.",
"projectAttributeLoadingErr": "Error en carregar els atributs del projecte. Torneu-ho a provar.",
"attributeUpdatedMsg": "Els atributs s'han actualitzat correctament.",
"projectAttributeUpdatingErr": "Error en actualitzar els atributs del projecte.",
"loadingProjectDetailsErrorMessage": "Error en recuperar marques, barreres i ubicacions omeses. Torneu-ho a provar.",
"savingProjectDetailsErr": "Error en desar els detalls del projecte. Torneu a provar de desar el projecte.",
"updatingOutagePolygonErr": "Error en actualitzar el polígon de talls. Torneu a provar de desar el projecte.",
"deletingExistingPolygonErr": "Error en suprimir el polígon de talls existent. Torneu a provar de desar el projecte.",
"loadingProjectFeaturesErr": "Error en carregar les entitats del projecte. Torneu a provar de carregar el projecte.",
"addingProjectFeaturesErr": "Error en afegir les entitats del projecte. Torneu a provar de desar el projecte.",
"deletingExistingProjectFeaturesErr": "Error en suprimir les entitats del projecte existents. Torneu a provar de desar el projecte.",
"projectNotFoundErr": "No s'ha trobat el projecte",
"projectLayersNotFound": "Les capes de configuració del projecte definides no estan disponibles al mapa. El widget es carregarà en el \"mode d'esbós\".",
"fetchingOutagePolygonMessage": "Error en recuperar el polígon de talls. Torneu a provar de carregar el projecte.",
"projectNameExistsMessage": "El nom del projecte ja existeix. Utilitzeu un nom de projecte únic.",
"fetchingProjectNamesErrorMessage": "Error en recuperar els noms dels projectes existents. Torneu a provar de desar el projecte.",
"enterProjectNameMessage": "Introduïu el nom del projecte.",
"projectLengthErrorMessage": "El nom del projecte no pot tenir més de",
"gpServiceNotAccessible": "El vostre compte no té accés al servei necessari per realitzar aquest traçat.",
"loadingClonedLayerErrorMessage": "Error en carregar la capa d'entitats clonada. Torneu-ho a provar.",
"addingFeatureInClonedLayerError": "Error en afegir els gràfics a la capa d'entitats clonada. Torneu-ho a provar.",
"selectingFeatureInClonedLayerError": "Error en seleccionar els gràfics a la capa d'entitats clonada. Torneu-ho a provar.",
"filteredProjectError": "Error en comprovar els detalls de recuperació del projecte filtrat. Torneu-ho a provar.",
"filteredProjectMessage": "Els atributs del projecte seleccionats no estan disponibles a causa dels filtres aplicats del mapa web o d'un altre widget. Esborreu els filtres i torneu-ho a provar.",
"filteredProjectLoadMessage": "El vostre projecte ja no està disponible. Seleccioneu un projecte actiu.",
"defaultValueForRunButton": "Executa",
"closeButtonLabel": "Elimina"
});
|
JSONEditor.Validator = Class.extend({
init: function(schema, options) {
this.original_schema = schema;
this.options = options || {};
this.refs = this.options.refs || {};
this.ready_callbacks = [];
this.translate = this.options.translate || JSONEditor.defaults.translate;
if(this.options.ready) this.ready(this.options.ready);
// Store any $ref and definitions
this.getRefs();
},
ready: function(callback) {
if(this.is_ready) callback.apply(this,[this.expanded]);
else {
this.ready_callbacks.push(callback);
}
return this;
},
getRefs: function() {
var self = this;
this._getRefs(this.original_schema, function(schema) {
self.schema = schema;
self.expanded = self.expandSchema(self.schema);
self.is_ready = true;
$each(self.ready_callbacks,function(i,callback) {
callback.apply(self,[self.expanded]);
});
});
},
_getRefs: function(schema,callback,path,in_definitions) {
var self = this;
var is_root = schema === this.original_schema;
path = path || "#";
var waiting, finished, check_if_finished, called;
// Work on a deep copy of the schema
schema = $extend({},schema);
// First expand out any definition in the root node
if(schema.definitions && (is_root || in_definitions)) {
var defs = schema.definitions;
delete schema.definitions;
waiting = finished = 0;
check_if_finished = function(schema) {
if(finished >= waiting) {
if(called) return;
called = true;
self._getRefs(schema,callback,path);
}
};
$each(defs,function() {
waiting++;
});
if(waiting) {
$each(defs,function(i,definition) {
// Expand the definition recursively
self._getRefs(definition,function(def_schema) {
self.refs[path+'/definitions/'+i] = def_schema;
finished++;
check_if_finished(schema);
},path+'/definitions/'+i,true);
});
}
else {
check_if_finished(schema);
}
}
// Expand out any references
else if(schema.$ref) {
var ref = schema.$ref;
delete schema.$ref;
// If we're currently loading this external reference, wait for it to be done
if(self.refs[ref] && Array.isArray(self.refs[ref])) {
self.refs[ref].push(function() {
schema = $extend({},self.refs[ref],schema);
callback(schema);
});
}
// If this reference has already been loaded
else if(self.refs[ref]) {
schema = $extend({},self.refs[ref],schema);
callback(schema);
}
// Otherwise, it needs to be loaded via ajax
else {
if(!self.options.ajax) throw "Must set ajax option to true to load external url "+ref;
var r = new XMLHttpRequest();
r.open("GET", ref, true);
r.onreadystatechange = function () {
if (r.readyState != 4) return;
if(r.status === 200) {
var response = JSON.parse(r.responseText);
self.refs[ref] = [];
// Recursively expand this schema
self._getRefs(response, function(ref_schema) {
var list = self.refs[ref];
self.refs[ref] = ref_schema;
schema = $extend({},self.refs[ref],schema);
callback(schema);
// If anything is waiting on this to load
$each(list,function(i,v) {
v();
});
},path);
return;
}
// Request failed
throw "Failed to fetch ref via ajax- "+ref;
};
r.send();
}
}
// Expand out any subschemas
else {
waiting = finished = 0;
check_if_finished = function(schema) {
if(finished >= waiting) {
if(called) return;
called = true;
callback(schema);
}
};
$each(schema, function(key, value) {
// Arrays that need to be expanded
if(typeof value === "object" && value && Array.isArray(value)) {
$each(value,function(j,item) {
if(typeof item === "object" && item && !(Array.isArray(item))) {
waiting++;
}
});
}
// Objects that need to be expanded
else if(typeof value === "object" && value) {
waiting++;
}
});
if(waiting) {
$each(schema, function(key, value) {
// Arrays that need to be expanded
if(typeof value === "object" && value && Array.isArray(value)) {
$each(value,function(j,item) {
if(typeof item === "object" && item && !(Array.isArray(item))) {
self._getRefs(item,function(expanded) {
schema[key][j] = expanded;
finished++;
check_if_finished(schema);
},path+'/'+key+'/'+j);
}
});
}
// Objects that need to be expanded
else if(typeof value === "object" && value) {
self._getRefs(value,function(expanded) {
schema[key] = expanded;
finished++;
check_if_finished(schema);
},path+'/'+key);
}
});
}
else {
check_if_finished(schema);
}
}
},
validate: function(value) {
return this._validateSchema(this.schema, value);
},
_validateSchema: function(schema,value,path) {
var errors = [];
var valid, i, j;
var stringified = JSON.stringify(value);
path = path || 'root';
// Work on a copy of the schema
schema = $extend({},schema);
/*
* Type Agnostic Validation
*/
// Version 3 `required`
if(schema.required && schema.required === true) {
if(typeof value === "undefined") {
errors.push({
path: path,
property: 'required',
message: this.translate("error_notset")
});
// Can't do any more validation at this point
return errors;
}
}
// Value not defined
else if(typeof value === "undefined") {
// If required_by_default is set, all fields are required
if(this.options.required_by_default) {
errors.push({
path: path,
property: 'required',
message: this.translate("error_notset")
});
}
// Not required, no further validation needed
else {
return errors;
}
}
// `enum`
if(schema.enum) {
valid = false;
for(i=0; i<schema.enum.length; i++) {
if(stringified === JSON.stringify(schema.enum[i])) valid = true;
}
if(!valid) {
errors.push({
path: path,
property: 'enum',
message: this.translate("error_enum")
});
}
}
// `extends` (version 3)
if(schema.extends) {
for(i=0; i<schema.extends.length; i++) {
errors = errors.concat(this._validateSchema(schema.extends[i],value,path));
}
}
// `allOf`
if(schema.allOf) {
for(i=0; i<schema.allOf.length; i++) {
errors = errors.concat(this._validateSchema(schema.allOf[i],value,path));
}
}
// `anyOf`
if(schema.anyOf) {
valid = false;
for(i=0; i<schema.anyOf.length; i++) {
if(!this._validateSchema(schema.anyOf[i],value,path).length) {
valid = true;
break;
}
}
if(!valid) {
errors.push({
path: path,
property: 'anyOf',
message: this.translate('error_anyOf')
});
}
}
// `oneOf`
if(schema.oneOf) {
valid = 0;
var oneof_errors = [];
for(i=0; i<schema.oneOf.length; i++) {
// Set the error paths to be path.oneOf[i].rest.of.path
var tmp = this._validateSchema(schema.oneOf[i],value,path);
if(!tmp.length) {
valid++;
}
for(j=0; j<tmp.length; j++) {
tmp[j].path = path+'.oneOf['+i+']'+tmp[j].path.substr(path.length);
}
oneof_errors = oneof_errors.concat(tmp);
}
if(valid !== 1) {
errors.push({
path: path,
property: 'oneOf',
message: this.translate('error_oneOf', [valid])
});
errors = errors.concat(oneof_errors);
}
}
// `not`
if(schema.not) {
if(!this._validateSchema(schema.not,value,path).length) {
errors.push({
path: path,
property: 'not',
message: this.translate('error_not')
});
}
}
// `type` (both Version 3 and Version 4 support)
if(schema.type) {
// Union type
if(Array.isArray(schema.type)) {
valid = false;
for(i=0;i<schema.type.length;i++) {
if(this._checkType(schema.type[i], value)) {
valid = true;
break;
}
}
if(!valid) {
errors.push({
path: path,
property: 'type',
message: this.translate('error_type_union')
});
}
}
// Simple type
else {
if(!this._checkType(schema.type, value)) {
errors.push({
path: path,
property: 'type',
message: this.translate('error_type', [schema.type])
});
}
}
}
// `disallow` (version 3)
if(schema.disallow) {
// Union type
if(Array.isArray(schema.disallow)) {
valid = true;
for(i=0;i<schema.disallow.length;i++) {
if(this._checkType(schema.disallow[i], value)) {
valid = false;
break;
}
}
if(!valid) {
errors.push({
path: path,
property: 'disallow',
message: this.translate('error_disallow_union')
});
}
}
// Simple type
else {
if(this._checkType(schema.disallow, value)) {
errors.push({
path: path,
property: 'disallow',
message: this.translate('error_disallow', [schema.disallow])
});
}
}
}
/*
* Type Specific Validation
*/
// Number Specific Validation
if(typeof value === "number") {
// `multipleOf` and `divisibleBy`
if(schema.multipleOf || schema.divisibleBy) {
valid = value / (schema.multipleOf || schema.divisibleBy);
if(valid !== Math.floor(valid)) {
errors.push({
path: path,
property: schema.multipleOf? 'multipleOf' : 'divisibleBy',
message: this.translate('error_multipleOf', [schema.multipleOf || schema.divisibleBy])
});
}
}
// `maximum`
if(schema.maximum) {
if(schema.exclusiveMaximum && value >= schema.maximum) {
errors.push({
path: path,
property: 'maximum',
message: this.translate('error_maximum_excl', [schema.maximum])
});
}
else if(!schema.exclusiveMaximum && value > schema.maximum) {
errors.push({
path: path,
property: 'maximum',
message: this.translate('error_maximum_incl', [schema.maximum])
});
}
}
// `minimum`
if(schema.minimum) {
if(schema.exclusiveMinimum && value <= schema.minimum) {
errors.push({
path: path,
property: 'minimum',
message: this.translate('error_minimum_excl', [schema.minimum])
});
}
else if(!schema.exclusiveMinimum && value < schema.minimum) {
errors.push({
path: path,
property: 'minimum',
message: this.translate('error_minimum_incl', [schema.minimum])
});
}
}
}
// String specific validation
else if(typeof value === "string") {
// `maxLength`
if(schema.maxLength) {
if((value+"").length > schema.maxLength) {
errors.push({
path: path,
property: 'maxLength',
message: this.translate('error_maxLength', [schema.maxLength])
});
}
}
// `minLength`
if(schema.minLength) {
if((value+"").length < schema.minLength) {
errors.push({
path: path,
property: 'minLength',
message: this.translate((schema.minLength===1?'error_notempty':'error_minLength'), [schema.minLength])
});
}
}
// `pattern`
if(schema.pattern) {
if(!(new RegExp(schema.pattern)).test(value)) {
errors.push({
path: path,
property: 'pattern',
message: this.translate('error_pattern')
});
}
}
}
// Array specific validation
else if(typeof value === "object" && value !== null && Array.isArray(value)) {
// `items` and `additionalItems`
if(schema.items) {
// `items` is an array
if(Array.isArray(schema.items)) {
for(i=0; i<value.length; i++) {
// If this item has a specific schema tied to it
// Validate against it
if(schema.items[i]) {
errors = errors.concat(this._validateSchema(schema.items[i],value[i],path+'.'+i));
}
// If all additional items are allowed
else if(schema.additionalItems === true) {
break;
}
// If additional items is a schema
// TODO: Incompatibility between version 3 and 4 of the spec
else if(schema.additionalItems) {
errors = errors.concat(this._validateSchema(schema.additionalItems,value[i],path+'.'+i));
}
// If no additional items are allowed
else if(schema.additionalItems === false) {
errors.push({
path: path,
property: 'additionalItems',
message: this.translate('error_additionalItems')
});
break;
}
// Default for `additionalItems` is an empty schema
else {
break;
}
}
}
// `items` is a schema
else {
// Each item in the array must validate against the schema
for(i=0; i<value.length; i++) {
errors = errors.concat(this._validateSchema(schema.items,value[i],path+'.'+i));
}
}
}
// `maxItems`
if(schema.maxItems) {
if(value.length > schema.maxItems) {
errors.push({
path: path,
property: 'maxItems',
message: this.translate('error_maxItems', [schema.maxItems])
});
}
}
// `minItems`
if(schema.minItems) {
if(value.length < schema.minItems) {
errors.push({
path: path,
property: 'minItems',
message: this.translate('error_minItems', [schema.minItems])
});
}
}
// `uniqueItems`
if(schema.uniqueItems) {
var seen = {};
for(i=0; i<value.length; i++) {
valid = JSON.stringify(value[i]);
if(seen[valid]) {
errors.push({
path: path,
property: 'uniqueItems',
message: this.translate('error_uniqueItems')
});
break;
}
seen[valid] = true;
}
}
}
// Object specific validation
else if(typeof value === "object" && value !== null) {
// `maxProperties`
if(schema.maxProperties) {
valid = 0;
for(i in value) {
if(!value.hasOwnProperty(i)) continue;
valid++;
}
if(valid > schema.maxProperties) {
errors.push({
path: path,
property: 'maxProperties',
message: this.translate('error_maxProperties', [schema.maxProperties])
});
}
}
// `minProperties`
if(schema.minProperties) {
valid = 0;
for(i in value) {
if(!value.hasOwnProperty(i)) continue;
valid++;
}
if(valid < schema.minProperties) {
errors.push({
path: path,
property: 'minProperties',
message: this.translate('error_minProperties', [schema.minProperties])
});
}
}
// Version 4 `required`
if(schema.required && Array.isArray(schema.required)) {
for(i=0; i<schema.required.length; i++) {
if(typeof value[schema.required[i]] === "undefined") {
errors.push({
path: path,
property: 'required',
message: this.translate('error_required', [schema.required[i]])
});
}
}
}
// `properties`
var validated_properties = {};
if(schema.properties) {
for(i in schema.properties) {
if(!schema.properties.hasOwnProperty(i)) continue;
validated_properties[i] = true;
errors = errors.concat(this._validateSchema(schema.properties[i],value[i],path+'.'+i));
}
}
// `patternProperties`
if(schema.patternProperties) {
for(i in schema.patternProperties) {
if(!schema.patternProperties.hasOwnProperty(i)) continue;
var regex = new RegExp(i);
// Check which properties match
for(j in value) {
if(!value.hasOwnProperty(j)) continue;
if(regex.test(j)) {
validated_properties[j] = true;
errors = errors.concat(this._validateSchema(schema.patternProperties[i],value[j],path+'.'+j));
}
}
}
}
// The no_additional_properties option currently doesn't work with extended schemas that use oneOf or anyOf
if(typeof schema.additionalProperties === "undefined" && this.options.no_additional_properties && !schema.oneOf && !schema.anyOf) {
schema.additionalProperties = false;
}
// `additionalProperties`
if(typeof schema.additionalProperties !== "undefined") {
for(i in value) {
if(!value.hasOwnProperty(i)) continue;
if(!validated_properties[i]) {
// No extra properties allowed
if(!schema.additionalProperties) {
errors.push({
path: path,
property: 'additionalProperties',
message: this.translate('error_additional_properties', [i])
});
break;
}
// Allowed
else if(schema.additionalProperties === true) {
break;
}
// Must match schema
// TODO: incompatibility between version 3 and 4 of the spec
else {
errors = errors.concat(this._validateSchema(schema.additionalProperties,value[i],path+'.'+i));
}
}
}
}
// `dependencies`
if(schema.dependencies) {
for(i in schema.dependencies) {
if(!schema.dependencies.hasOwnProperty(i)) continue;
// Doesn't need to meet the dependency
if(typeof value[i] === "undefined") continue;
// Property dependency
if(Array.isArray(schema.dependencies[i])) {
for(j=0; j<schema.dependencies[i].length; j++) {
if(typeof value[schema.dependencies[i][j]] === "undefined") {
errors.push({
path: path,
property: 'dependencies',
message: this.translate('error_dependency', [schema.dependencies[i][j]])
});
}
}
}
// Schema dependency
else {
errors = errors.concat(this._validateSchema(schema.dependencies[i],value,path));
}
}
}
}
// Custom type validation
$each(JSONEditor.defaults.custom_validators,function(i,validator) {
errors = errors.concat(validator(schema,value,path));
});
return errors;
},
_checkType: function(type, value) {
// Simple types
if(typeof type === "string") {
if(type==="string") return typeof value === "string";
else if(type==="number") return typeof value === "number";
else if(type==="integer") return typeof value === "number" && value === Math.floor(value);
else if(type==="boolean") return typeof value === "boolean";
else if(type==="array") return Array.isArray(value);
else if(type === "object") return value !== null && !(Array.isArray(value)) && typeof value === "object";
else if(type === "null") return value === null;
else return true;
}
// Schema
else {
return !this._validateSchema(type,value).length;
}
},
expandSchema: function(schema) {
var self = this;
var extended = schema;
var i;
// Version 3 `type`
if(typeof schema.type === 'object') {
// Array of types
if(Array.isArray(schema.type)) {
$each(schema.type, function(key,value) {
// Schema
if(typeof value === 'object') {
schema.type[key] = self.expandSchema(value);
}
});
}
// Schema
else {
schema.type = self.expandSchema(schema.type);
}
}
// Version 3 `disallow`
if(typeof schema.disallow === 'object') {
// Array of types
if(Array.isArray(schema.disallow)) {
$each(schema.disallow, function(key,value) {
// Schema
if(typeof value === 'object') {
schema.disallow[key] = self.expandSchema(value);
}
});
}
// Schema
else {
schema.disallow = self.expandSchema(schema.disallow);
}
}
// Version 4 `anyOf`
if(schema.anyOf) {
$each(schema.anyOf, function(key,value) {
schema.anyOf[key] = self.expandSchema(value);
});
}
// Version 4 `dependencies` (schema dependencies)
if(schema.dependencies) {
$each(schema.dependencies,function(key,value) {
if(typeof value === "object" && !(Array.isArray(value))) {
schema.dependencies[key] = self.expandSchema(value);
}
});
}
// `items`
if(schema.items) {
// Array of items
if(Array.isArray(schema.items)) {
$each(schema.items, function(key,value) {
// Schema
if(typeof value === 'object') {
schema.items[key] = self.expandSchema(value);
}
});
}
// Schema
else {
schema.items = self.expandSchema(schema.items);
}
}
// `properties`
if(schema.properties) {
$each(schema.properties,function(key,value) {
if(typeof value === "object" && !(Array.isArray(value))) {
schema.properties[key] = self.expandSchema(value);
}
});
}
// `patternProperties`
if(schema.patternProperties) {
$each(schema.patternProperties,function(key,value) {
if(typeof value === "object" && !(Array.isArray(value))) {
schema.patternProperties[key] = self.expandSchema(value);
}
});
}
// Version 4 `not`
if(schema.not) {
schema.not = this.expandSchema(schema.not);
}
// `additionalProperties`
if(schema.additionalProperties && typeof schema.additionalProperties === "object") {
schema.additionalProperties = self.expandSchema(schema.additionalProperties);
}
// `additionalItems`
if(schema.additionalItems && typeof schema.additionalItems === "object") {
schema.additionalItems = self.expandSchema(schema.additionalItems);
}
// allOf schemas should be merged into the parent
if(schema.allOf) {
for(i=0; i<schema.allOf.length; i++) {
extended = this.extend(extended,this.expandSchema(schema.allOf[i]));
}
delete extended.allOf;
}
// extends schemas should be merged into parent
if(schema.extends) {
// If extends is a schema
if(!(Array.isArray(schema.extends))) {
extended = this.extend(extended,this.expandSchema(schema.extends));
}
// If extends is an array of schemas
else {
for(i=0; i<schema.extends.length; i++) {
extended = this.extend(extended,this.expandSchema(schema.extends[i]));
}
}
delete extended.extends;
}
// parent should be merged into oneOf schemas
if(schema.oneOf) {
var tmp = $extend({},extended);
delete tmp.oneOf;
for(i=0; i<schema.oneOf.length; i++) {
extended.oneOf[i] = this.extend(this.expandSchema(schema.oneOf[i]),tmp);
}
}
return extended;
},
extend: function(obj1, obj2) {
obj1 = $extend({},obj1);
obj2 = $extend({},obj2);
var self = this;
var extended = {};
$each(obj1, function(prop,val) {
// If this key is also defined in obj2, merge them
if(typeof obj2[prop] !== "undefined") {
// Required arrays should be unioned together
if(prop === 'required' && typeof val === "object" && Array.isArray(val)) {
// Union arrays and unique
extended.required = val.concat(obj2[prop]).reduce(function(p, c) {
if (p.indexOf(c) < 0) p.push(c);
return p;
}, []);
}
// Type should be intersected and is either an array or string
else if(prop === 'type') {
// Make sure we're dealing with arrays
if(typeof val !== "object") val = [val];
if(typeof obj2.type !== "object") obj2.type = [obj2.type];
extended.type = val.filter(function(n) {
return obj2.type.indexOf(n) !== -1;
});
// If there's only 1 type and it's a primitive, use a string instead of array
if(extended.type.length === 1 && typeof extended.type[0] === "string") {
extended.type = extended.type[0];
}
}
// All other arrays should be intersected (enum, etc.)
else if(typeof val === "object" && Array.isArray(val)){
extended[prop] = val.filter(function(n) {
return obj2[prop].indexOf(n) !== -1;
});
}
// Objects should be recursively merged
else if(typeof val === "object" && val !== null) {
extended[prop] = self.extend(val,obj2[prop]);
}
// Otherwise, use the first value
else {
extended[prop] = val;
}
}
// Otherwise, just use the one in obj1
else {
extended[prop] = val;
}
});
// Properties in obj2 that aren't in obj1
$each(obj2, function(prop,val) {
if(typeof obj1[prop] === "undefined") {
extended[prop] = val;
}
});
return extended;
}
});
|
$("#contactForm").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
// handle the invalid form...
formError();
submitMSG(false, "Form working has been disabled here. It will work on a PHP enabled server!");
} else {
// everything looks good!
event.preventDefault();
submitForm();
}
});
function submitForm(){
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var phone_number = $("#phone_number").val();
var subject = $("#subject").val();
var message = $("#message").val();
$.ajax({
type: "POST",
//Set the Path to Your PHP File here
url: "/eagle/form-process.php",
data: "name=" + name + "&email=" + email + "&phone_number=" + phone_number + "&subject=" + subject + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
$("#contact_form_fields").slideUp(); //hide form after success
} else {
formError();
submitMSG(false,text);
}
}
});
}
function formSuccess(){
$("#contactForm")[0].reset();
submitMSG(true, "Thank you for your message! We will get back to you shortly!")
}
function formError(){
$(this).removeClass();
}
function submitMSG(valid, msg){
if(valid){
var msgClasses = "h3 text-center text-success";
} else {
var msgClasses = "h3 text-center text-danger";
}
$("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}
|
const createRemoveField = (fieldPath, removeField) =>
index => removeField(fieldPath, index)
export default createRemoveField
|
/*
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', ['ionic'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
*/
'use strict';
angular.module('myApp', [
'dropped.controllers','myApp.services','ngRoute'
])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when("/Single-Product/:id", {templateUrl: "partials/Single-Product.html", controller: "displayDetails"}).
when("/home", {templateUrl: "partials/home.html", controller: "getBytesProductsSamsung"}).
otherwise({redirectTo: '/home'});
}]);
|
'use strict';
/* jasmine specs for filters go here */
describe('filter', function() {
beforeEach(module('phonecatFilters'));
describe('checkmark', function() {
it('should convert boolean values to unicode checkmark or cross',
inject(function(checkmarkFilter) {
expect(checkmarkFilter(true)).toBe('\u2713');
expect(checkmarkFilter(false)).toBe('\u2718');
}));
});
});
|
import { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { isElloAndroid } from '../lib/jello'
import { selectIsLoggedIn } from '../selectors/authentication'
import {
selectAllowsAnalytics,
selectAnalyticsId,
selectCreatedAt,
selectCreatorTypes,
selectIsNabaroo,
selectProfileIsFeatured,
} from '../selectors/profile'
import * as ENV from '../../env'
const agent = isElloAndroid() ? 'android' : 'webapp'
export function addSegment({ createdAt, creatorTypes, hasAccount, isFeatured, isNabaroo, uid }) {
/* eslint-disable */
!function(){const analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","page","once","off","on"];analytics.factory=function(t){return function(){const e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(let t=0;t<analytics.methods.length;t++){const e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t){const e=document.createElement("script");e.type="text/javascript";e.async=!0;e.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";const n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(e,n)};
/* eslint-enable */
analytics.SNIPPET_VERSION = '3.1.0'
analytics.load(ENV.SEGMENT_WRITE_KEY)
if (uid) {
analytics.identify(uid, {
agent,
createdAt,
creatorTypes,
hasAccount,
isFeatured,
isNabaroo,
})
}
}
}();
}
export function doesAllowTracking() {
return !(
window.navigator.doNotTrack === '1' ||
window.navigator.msDoNotTrack === '1' ||
window.doNotTrack === '1' ||
window.msDoNotTrack === '1'
)
}
function mapStateToProps(state) {
const creatorTypes = selectCreatorTypes(state)
return {
allowsAnalytics: doesAllowTracking() && selectAllowsAnalytics(state),
analyticsId: selectAnalyticsId(state),
createdAt: selectCreatedAt(state),
creatorTypes: creatorTypes.toArray(),
isFeatured: selectProfileIsFeatured(state),
isLoggedIn: selectIsLoggedIn(state),
isNabaroo: selectIsNabaroo(state),
}
}
class AnalyticsContainer extends Component {
static propTypes = {
allowsAnalytics: PropTypes.bool,
analyticsId: PropTypes.string,
createdAt: PropTypes.string,
creatorTypes: PropTypes.array.isRequired,
isFeatured: PropTypes.bool.isRequired,
isLoggedIn: PropTypes.bool.isRequired,
isNabaroo: PropTypes.bool.isRequired,
}
static defaultProps = {
allowsAnalytics: null,
analyticsId: null,
createdAt: null,
}
componentWillMount() {
this.hasLoadedTracking = false
}
componentDidMount() {
const { analyticsId, allowsAnalytics, createdAt,
isFeatured, isLoggedIn, creatorTypes, isNabaroo } = this.props
if (this.hasLoadedTracking) { return }
if (!isLoggedIn && doesAllowTracking()) {
this.hasLoadedTracking = true
addSegment({})
} else if (analyticsId && allowsAnalytics) {
this.hasLoadedTracking = true
addSegment({ createdAt,
hasAccount: isLoggedIn,
isFeatured,
creatorTypes,
isNabaroo,
uid: analyticsId })
}
}
componentWillReceiveProps(nextProps) {
const { allowsAnalytics, analyticsId, createdAt,
isFeatured, isLoggedIn, creatorTypes, isNabaroo } = nextProps
if (this.hasLoadedTracking) {
// identify the user if they didn't previously have an id to identify with
if (!this.props.analyticsId && analyticsId) {
const props = { agent,
createdAt,
hasAccount: isLoggedIn,
isFeatured,
creatorTypes,
isNabaroo }
window.analytics.identify(analyticsId, props)
}
} else if (this.props.analyticsId && analyticsId && allowsAnalytics) {
this.hasLoadedTracking = true
addSegment({ createdAt,
hasAccount: isLoggedIn,
isFeatured,
isNabaroo,
creatorTypes,
uid: analyticsId })
}
}
shouldComponentUpdate() {
return false
}
render() {
return null
}
}
export default connect(mapStateToProps)(AnalyticsContainer)
|
function binom(nn, pp, rng) {
let c, fm, npq, p1, p2, p3, p4, qn;
let xl, xll, xlr, xm, xr;
let psave = -1;
let nsave = -1;
let m;
let f, f1, f2, u, v, w, w2, x, x1, x2, z, z2;
let p, q, np, g, r, al, alv, amaxp, ffm, ynorm;
let i, ix, k, n;
r = Math.round(nn);
if (r < 0 || pp < 0 || pp > 1) {
throw new Error('Invalid input.');
}
if (r === 0 || pp === 0) {
return 0;
}
if (pp === 1) {
return r;
}
n = r;
p = Math.min(pp, 1 - pp);
q = 1 - p;
np = n * p;
r = p / q;
g = r * (n + 1);
if (pp !== psave || n !== nsave) {
psave = pp;
nsave = n;
if (np < 30.0) {
qn = pow(q, n);
return binomNpSmall(qn, g, r, psave, n, rng);
}
ffm = np + p;
m = Math.floor(ffm);
fm = m;
npq = np * q;
p1 = Math.floor(2.195 * Math.sqrt(npq) - 4.6 * q) + 0.5;
xm = fm + 0.5;
xl = xm - p1;
xr = xm + p1;
c = 0.134 + 20.5 / (15.3 + fm);
al = (ffm - xl) / (ffm - xl * p);
xll = al * (1 + 0.5 * al);
al = (xr - ffm) / (xr * q);
xlr = al * (1.0 + 0.5 * al);
p2 = p1 * (1.0 + c + c);
p3 = p2 + c / xll;
p4 = p3 + c / xlr;
} else if (n === nsave) {
if (np < 30.0) {
return binomNpSmall(qn, g, r, psave, n);
}
}
for (;;) {
u = rng() * p4;
v = rng();
if (u <= p1) {
ix = Math.floor(xm - p1 * v + u);
return binomFin(psave, ix, n);
}
if (u <= p2) {
x = xl + (u - p1) / c;
v = v * c + 1 - Math.abs(xm - x) / p1;
if (v > 1 || v <= 0) {
continue;
}
ix = Math.floor(x);
} else if (u > p3) {
ix = Math.floor(xr - Math.log(v) / xlr);
if (ix > n) {
continue;
}
v = v * (u - p3) * xlr;
} else {
ix = Math.floor(xl + Math.log(v) / xll);
if (ix < 0) {
continue;
}
v = v * (u - p2) * xll;
}
k = Math.abs(ix - m);
if (k <= 20 || k >= npq / 2 - 1) {
f = 1.0;
if (m < ix) {
for (i = m + 1; i <= ix; i++) {
f *= (g / i - r);
}
} else if (m !== ix) {
for (i = ix + 1; i <= m; i++) {
f /= (g / i - r);
}
}
if (v <= f) {
return binomFin(psave, ix, n);
}
} else {
amaxp = (k / npq) * ((k * (k / 3 + 0.625) + 0.1666666666666666) / npq + 0.5);
ynorm = -k * k / (2 * npq);
alv = Math.log(v);
if (alv < ynorm - amaxp) {
return binomFin(psave, ix, n);
}
if (alv <= ynorm + amaxp) {
x1 = ix + 1;
f1 = fm + 1;
z = n + 1 - fm;
w = n - ix + 1;
z2 = z * z;
x2 = x1 * x1;
f2 = f1 * f1;
w2 = w * w;
if (alv <= xm * Math.log(f1 / x1) + (n - m + 0.5) * Math.log(z / w) +
(ix - m) * Math.log(w * p / (x1 * q)) + (13860.0 - (462.0 - (132.0 -
(99.0 - 140.0 / f2) / f2) / f2) / f2) / f1 / 166320.0 + (13860.0 -
(462.0 - (132.0 - (99.0 - 140.0 / z2) / z2) / z2) / z2) / z /
166320.0 + (13860.0 - (462.0 - (132.0 - (99.0 - 140.0 / x2) /
x2) / x2) / x2) / x1 / 166320.0 + (13860.0 - (462.0 - (132.0 -
(99.0 - 140.0 / w2) / w2) / w2) / w2) / w / 166320) {
return binomFin(psave, ix, n);
}
}
}
}
}
function binomNpSmall(qn, g, r, psave, n, rng) {
for (;;) {
let ix = 0;
let f = qn;
let u = rng();
for (;;) {
if (u < f) {
return binomFin(psave, ix, n);
}
if (ix > 110) {
break;
}
u -= f;
ix++;
f *= (g / ix - r);
}
}
}
function binomFin(psave, ix, n) {
if (psave > 0.5) {
ix = n - ix;
}
return ix;
}
function pow(x, n) {
let pow = 1.0;
if (n !== 0) {
if (n < 0) {
n = -n;
x = 1 / x;
}
for (;;) {
if (n & '01') {
pow *= x;
}
n >>= 1;
if (n) {
x *= x;
} else {
break;
}
}
}
return pow;
}
export default binom;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.