code stringlengths 2 1.05M |
|---|
YUI.add("lang/datatype-date-format_de",function(A){A.Intl.add("datatype-date-format","de",{"a":["So.","Mo.","Di.","Mi.","Do.","Fr.","Sa."],"A":["Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag"],"b":["Jan","Feb","Mär","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez"],"B":["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"],"c":"%a, %d. %b %Y %H:%M:%S %Z","p":["VORM.","NACHM."],"P":["vorm.","nachm."],"x":"%d.%m.%y","X":"%H:%M:%S"});},"@VERSION@"); |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { ApplicationRef, NgZone, Optional, RootRenderer, getDebugNode, isDevMode } from '@angular/core';
import { StringMapWrapper } from '../../facade/collection';
import { DebugDomRootRenderer } from '../../private_import_core';
import { getDOM } from '../dom_adapter';
import { DomRootRenderer } from '../dom_renderer';
var CORE_TOKENS = {
'ApplicationRef': ApplicationRef,
'NgZone': NgZone
};
var INSPECT_GLOBAL_NAME = 'ng.probe';
var CORE_TOKENS_GLOBAL_NAME = 'ng.coreTokens';
/**
* Returns a {@link DebugElement} for the given native DOM element, or
* null if the given native element does not have an Angular view associated
* with it.
*/
export function inspectNativeElement(element /** TODO #9100 */) {
return getDebugNode(element);
}
/**
* @experimental
*/
export var NgProbeToken = (function () {
function NgProbeToken(name, token) {
this.name = name;
this.token = token;
}
return NgProbeToken;
}());
export function _createConditionalRootRenderer(rootRenderer /** TODO #9100 */, extraTokens) {
if (isDevMode()) {
return _createRootRenderer(rootRenderer, extraTokens);
}
return rootRenderer;
}
function _createRootRenderer(rootRenderer /** TODO #9100 */, extraTokens) {
getDOM().setGlobalVar(INSPECT_GLOBAL_NAME, inspectNativeElement);
getDOM().setGlobalVar(CORE_TOKENS_GLOBAL_NAME, StringMapWrapper.merge(CORE_TOKENS, _ngProbeTokensToMap(extraTokens || [])));
return new DebugDomRootRenderer(rootRenderer);
}
function _ngProbeTokensToMap(tokens) {
return tokens.reduce(function (prev, t) { return (prev[t.name] = t.token, prev); }, {});
}
/**
* Providers which support debugging Angular applications (e.g. via `ng.probe`).
*/
export var ELEMENT_PROBE_PROVIDERS = [{
provide: RootRenderer,
useFactory: _createConditionalRootRenderer,
deps: [DomRootRenderer, [NgProbeToken, new Optional()]]
}];
export var ELEMENT_PROBE_PROVIDERS_PROD_MODE = [{
provide: RootRenderer,
useFactory: _createRootRenderer,
deps: [DomRootRenderer, [NgProbeToken, new Optional()]]
}];
//# sourceMappingURL=ng_probe.js.map |
/* NUGET: BEGIN LICENSE TEXT
*
* Microsoft grants you the right to use these script files for the sole
* purpose of either: (i) interacting through your browser with the Microsoft
* website or online service, subject to the applicable licensing or use
* terms; or (ii) using the files as included with a Microsoft product subject
* to that product's license terms. Microsoft reserves all other rights to the
* files not expressly granted by Microsoft, whether by implication, estoppel
* or otherwise. Insofar as a script file is dual licensed under GPL,
* Microsoft neither took the code under GPL nor distributes it thereunder but
* under the terms set out in this paragraph. All notices and licenses
* below are for informational purposes only.
*
* NUGET: END LICENSE TEXT */
/*!
** Unobtrusive validation support library for jQuery and jQuery Validate
** Copyright (C) Microsoft Corporation. All rights reserved.
*/
/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */
/*global document: false, jQuery: false */
(function ($) {
var $jQval = $.validator,
adapters,
data_validation = "unobtrusiveValidation";
function setValidationValues(options, ruleName, value) {
options.rules[ruleName] = value;
if (options.message) {
options.messages[ruleName] = options.message;
}
}
function splitAndTrim(value) {
return value.replace(/^\s+|\s+$/g, "").split(/\s*,\s*/g);
}
function escapeAttributeValue(value) {
// As mentioned on http://api.jquery.com/category/selectors/
return value.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g, "\\$1");
}
function getModelPrefix(fieldName) {
return fieldName.substr(0, fieldName.lastIndexOf(".") + 1);
}
function appendModelPrefix(value, prefix) {
if (value.indexOf("*.") === 0) {
value = value.replace("*.", prefix);
}
return value;
}
function onError(error, inputElement) { // 'this' is the form element
var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
replaceAttrValue = container.attr("data-valmsg-replace"),
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) !== false : null;
container.removeClass("field-validation-valid").addClass("field-validation-error");
error.data("unobtrusiveContainer", container);
if (replace) {
container.empty();
error.removeClass("input-validation-error").appendTo(container);
}
else {
error.hide();
}
}
function onErrors(event, validator) { // 'this' is the form element
var container = $(this).find("[data-valmsg-summary=true]"),
list = container.find("ul");
if (list && list.length && validator.errorList.length) {
list.empty();
container.addClass("validation-summary-errors").removeClass("validation-summary-valid");
$.each(validator.errorList, function () {
$("<li />").html(this.message).appendTo(list);
});
}
}
function onSuccess(error) { // 'this' is the form element
var container = error.data("unobtrusiveContainer"),
replaceAttrValue = container.attr("data-valmsg-replace"),
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) : null;
if (container) {
container.addClass("field-validation-valid").removeClass("field-validation-error");
error.removeData("unobtrusiveContainer");
if (replace) {
container.empty();
}
}
}
function onReset(event) { // 'this' is the form element
var $form = $(this);
$form.data("validator").resetForm();
$form.find(".validation-summary-errors")
.addClass("validation-summary-valid")
.removeClass("validation-summary-errors");
$form.find(".field-validation-error")
.addClass("field-validation-valid")
.removeClass("field-validation-error")
.removeData("unobtrusiveContainer")
.find(">*") // If we were using valmsg-replace, get the underlying error
.removeData("unobtrusiveContainer");
}
function validationInfo(form) {
var $form = $(form),
result = $form.data(data_validation),
onResetProxy = $.proxy(onReset, form);
if (!result) {
result = {
options: { // options structure passed to jQuery Validate's validate() method
errorClass: "input-validation-error",
errorElement: "span",
errorPlacement: $.proxy(onError, form),
invalidHandler: $.proxy(onErrors, form),
messages: {},
rules: {},
success: $.proxy(onSuccess, form)
},
attachValidation: function () {
$form
.unbind("reset." + data_validation, onResetProxy)
.bind("reset." + data_validation, onResetProxy)
.validate(this.options);
},
validate: function () { // a validation function that is called by unobtrusive Ajax
$form.validate();
return $form.valid();
}
};
$form.data(data_validation, result);
}
return result;
}
$jQval.unobtrusive = {
adapters: [],
parseElement: function (element, skipAttach) {
/// <summary>
/// Parses a single HTML element for unobtrusive validation attributes.
/// </summary>
/// <param name="element" domElement="true">The HTML element to be parsed.</param>
/// <param name="skipAttach" type="Boolean">[Optional] true to skip attaching the
/// validation to the form. If parsing just this single element, you should specify true.
/// If parsing several elements, you should specify false, and manually attach the validation
/// to the form when you are finished. The default is false.</param>
var $element = $(element),
form = $element.parents("form")[0],
valInfo, rules, messages;
if (!form) { // Cannot do client-side validation without a form
return;
}
valInfo = validationInfo(form);
valInfo.options.rules[element.name] = rules = {};
valInfo.options.messages[element.name] = messages = {};
$.each(this.adapters, function () {
var prefix = "data-val-" + this.name,
message = $element.attr(prefix),
paramValues = {};
if (message !== undefined) { // Compare against undefined, because an empty message is legal (and falsy)
prefix += "-";
$.each(this.params, function () {
paramValues[this] = $element.attr(prefix + this);
});
this.adapt({
element: element,
form: form,
message: message,
params: paramValues,
rules: rules,
messages: messages
});
}
});
$.extend(rules, { "__dummy__": true });
if (!skipAttach) {
valInfo.attachValidation();
}
},
parse: function (selector) {
/// <summary>
/// Parses all the HTML elements in the specified selector. It looks for input elements decorated
/// with the [data-val=true] attribute value and enables validation according to the data-val-*
/// attribute values.
/// </summary>
/// <param name="selector" type="String">Any valid jQuery selector.</param>
var $forms = $(selector)
.parents("form")
.andSelf()
.add($(selector).find("form"))
.filter("form");
// :input is a psuedoselector provided by jQuery which selects input and input-like elements
// combining :input with other selectors significantly decreases performance.
$(selector).find(":input").filter("[data-val=true]").each(function () {
$jQval.unobtrusive.parseElement(this, true);
});
$forms.each(function () {
var info = validationInfo(this);
if (info) {
info.attachValidation();
}
});
}
};
adapters = $jQval.unobtrusive.adapters;
adapters.add = function (adapterName, params, fn) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
/// <param name="params" type="Array" optional="true">[Optional] An array of parameter names (strings) that will
/// be extracted from the data-val-nnnn-mmmm HTML attributes (where nnnn is the adapter name, and
/// mmmm is the parameter name).</param>
/// <param name="fn" type="Function">The function to call, which adapts the values from the HTML
/// attributes into jQuery Validate rules and/or messages.</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
if (!fn) { // Called with no params, just a function
fn = params;
params = [];
}
this.push({ name: adapterName, params: params, adapt: fn });
return this;
};
adapters.addBool = function (adapterName, ruleName) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
/// the jQuery Validate validation rule has no parameter values.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
/// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
/// of adapterName will be used instead.</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
return this.add(adapterName, function (options) {
setValidationValues(options, ruleName || adapterName, true);
});
};
adapters.addMinMax = function (adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
/// the jQuery Validate validation has three potential rules (one for min-only, one for max-only, and
/// one for min-and-max). The HTML parameters are expected to be named -min and -max.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
/// <param name="minRuleName" type="String">The name of the jQuery Validate rule to be used when you only
/// have a minimum value.</param>
/// <param name="maxRuleName" type="String">The name of the jQuery Validate rule to be used when you only
/// have a maximum value.</param>
/// <param name="minMaxRuleName" type="String">The name of the jQuery Validate rule to be used when you
/// have both a minimum and maximum value.</param>
/// <param name="minAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
/// contains the minimum value. The default is "min".</param>
/// <param name="maxAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
/// contains the maximum value. The default is "max".</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
return this.add(adapterName, [minAttribute || "min", maxAttribute || "max"], function (options) {
var min = options.params.min,
max = options.params.max;
if (min && max) {
setValidationValues(options, minMaxRuleName, [min, max]);
}
else if (min) {
setValidationValues(options, minRuleName, min);
}
else if (max) {
setValidationValues(options, maxRuleName, max);
}
});
};
adapters.addSingleVal = function (adapterName, attribute, ruleName) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
/// the jQuery Validate validation rule has a single value.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute(where nnnn is the adapter name).</param>
/// <param name="attribute" type="String">[Optional] The name of the HTML attribute that contains the value.
/// The default is "val".</param>
/// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
/// of adapterName will be used instead.</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
return this.add(adapterName, [attribute || "val"], function (options) {
setValidationValues(options, ruleName || adapterName, options.params[attribute]);
});
};
$jQval.addMethod("__dummy__", function (value, element, params) {
return true;
});
$jQval.addMethod("regex", function (value, element, params) {
var match;
if (this.optional(element)) {
return true;
}
match = new RegExp(params).exec(value);
return (match && (match.index === 0) && (match[0].length === value.length));
});
$jQval.addMethod("nonalphamin", function (value, element, nonalphamin) {
var match;
if (nonalphamin) {
match = value.match(/\W/g);
match = match && match.length >= nonalphamin;
}
return match;
});
if ($jQval.methods.extension) {
adapters.addSingleVal("accept", "mimtype");
adapters.addSingleVal("extension", "extension");
} else {
// for backward compatibility, when the 'extension' validation method does not exist, such as with versions
// of JQuery Validation plugin prior to 1.10, we should use the 'accept' method for
// validating the extension, and ignore mime-type validations as they are not supported.
adapters.addSingleVal("extension", "extension", "accept");
}
adapters.addSingleVal("regex", "pattern");
adapters.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");
adapters.addMinMax("length", "minlength", "maxlength", "rangelength").addMinMax("range", "min", "max", "range");
adapters.addMinMax("minlength", "minlength").addMinMax("maxlength", "minlength", "maxlength");
adapters.add("equalto", ["other"], function (options) {
var prefix = getModelPrefix(options.element.name),
other = options.params.other,
fullOtherName = appendModelPrefix(other, prefix),
element = $(options.form).find(":input").filter("[name='" + escapeAttributeValue(fullOtherName) + "']")[0];
setValidationValues(options, "equalTo", element);
});
adapters.add("required", function (options) {
// jQuery Validate equates "required" with "mandatory" for checkbox elements
if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
setValidationValues(options, "required", true);
}
});
adapters.add("remote", ["url", "type", "additionalfields"], function (options) {
var value = {
url: options.params.url,
type: options.params.type || "GET",
data: {}
},
prefix = getModelPrefix(options.element.name);
$.each(splitAndTrim(options.params.additionalfields || options.element.name), function (i, fieldName) {
var paramName = appendModelPrefix(fieldName, prefix);
value.data[paramName] = function () {
return $(options.form).find(":input").filter("[name='" + escapeAttributeValue(paramName) + "']").val();
};
});
setValidationValues(options, "remote", value);
});
adapters.add("password", ["min", "nonalphamin", "regex"], function (options) {
if (options.params.min) {
setValidationValues(options, "minlength", options.params.min);
}
if (options.params.nonalphamin) {
setValidationValues(options, "nonalphamin", options.params.nonalphamin);
}
if (options.params.regex) {
setValidationValues(options, "regex", options.params.regex);
}
});
$(function () {
$jQval.unobtrusive.parse(document);
});
}(jQuery)); |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE, MMMM d, y",
"longDate": "MMMM d, y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "M/d/yy h:mm a",
"shortDate": "M/d/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-dg",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"ERANAMES": [
"Before Christ",
"Anno Domini"
],
"ERAS": [
"BC",
"AD"
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"STANDALONEMONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y h:mm:ss a",
"mediumDate": "d MMM y",
"mediumTime": "h:mm:ss a",
"short": "dd/MM/y h:mm a",
"shortDate": "dd/MM/y",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-\u00a4",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-io",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
window.MapBBCodeConfig.include({ strings: {
"view": "View",
"editor": "Editor",
"editInWindow": "Window",
"editInPanel": "Panel",
"viewNormal": "Normal",
"viewFull": "Full width only",
"viewTitle": "Adjusting browsing panel",
"editorTitle": "Adjusting editor panel or window",
"editInWindowTitle": "Editor will be opened in a popup window",
"editInPanelTitle": "Editor will appear inside a page",
"viewNormalTitle": "Map panel will have \"fullscreen\" button",
"viewFullTitle": "Map panel will always have maximum size",
"growTitle": "Click to grow the panel",
"shrinkTitle": "Click to shrink the panel",
"zoomInTitle": "Zoom in",
"zoomOutTitle": "Zoom out",
"selectLayer": "Select layer",
"addLayer": "Add layer",
"keyNeeded": "This layer needs a developer key (<a href=\"%s\" target=\"devkey\">how to get it</a>)",
"keyNeededAlert": "This layer needs a developer key"
}}); |
module.exports = "replaced"; |
//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
//// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
//// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//// PARTICULAR PURPOSE.
////
//// Copyright (c) Microsoft Corporation. All rights reserved
(function () {
"use strict";
var output;
var page = WinJS.UI.Pages.define("/html/scenario6.html", {
ready: function (element, options) {
output = document.getElementById('output');
WinJS.Resources.processAll(output);
WinJS.Resources.addEventListener("contextchanged", refresh, false);
},
unload: function () {
WinJS.Resources.removeEventListener("contextchanged", refresh, false);
}
});
function refresh(e) {
WinJS.Resources.processAll(output); // Refetch string resources
// If a page contains img elements and the images have scale or other variations,
// the HTML layout engine does not automatically reload those images if the scale
// is changed (e.g., if a view is moved to a different display that has a
// different DPI). The call to WinJS.Resources.processAll() will reload strings
// resources bound using data-win-res attributes, but does not reload images. The
// following will reload images that are referenced using a URI with the ms-appx
// schema.
// The contextchanged event can occur in relation to several different qualifiers.
// If only certain qualifiers or qualifier values are relevant for an app, e.detail
// can be tested to filter for relevant changes. This sample has image variants for
// scale and language, so we will test for those particular changes.
if (e.detail.qualifier === "Language" || e.detail.qualifier === "Scale") {
var imageElements = document.getElementsByTagName("img");
for (var i = 0, l = imageElements.length; i < l; i++) {
var previousSource = imageElements[i].src;
var uri = new Windows.Foundation.Uri(document.location, previousSource);
if (uri.schemeName === "ms-appx") {
imageElements[i].src = "";
imageElements[i].src = previousSource;
}
}
}
}
})();
|
/* =============================================================
* bootstrap-scrollspy.js v2.2.1
* http://twitter.github.com/bootstrap/javascript.html#scrollspy
* =============================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* SCROLLSPY CLASS DEFINITION
* ========================== */
function ScrollSpy(element, options) {
var process = $.proxy(this.process, this)
, $element = $(element).is('body') ? $(window) : $(element)
, href
this.options = $.extend({}, $.fn.scrollspy.defaults, options)
this.$scrollElement = $element.on('scroll.scroll-spy.data-api', process)
this.selector = (this.options.target
|| ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
|| '') + ' .nav li > a'
this.$body = $('body')
this.refresh()
this.process()
}
ScrollSpy.prototype = {
constructor: ScrollSpy
, refresh: function () {
var self = this
, $targets
this.offsets = $([])
this.targets = $([])
$targets = this.$body
.find(this.selector)
.map(function () {
var $el = $(this)
, href = $el.data('target') || $el.attr('href')
, $href = /^#\w/.test(href) && $(href)
return ( $href
&& $href.length
&& [[ $href.position().top, href ]] ) || null
})
.sort(function (a, b) { return a[0] - b[0] })
.each(function () {
self.offsets.push(this[0])
self.targets.push(this[1])
})
}
, process: function () {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
, scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight
, maxScroll = scrollHeight - this.$scrollElement.height()
, offsets = this.offsets
, targets = this.targets
, activeTarget = this.activeTarget
, i
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets.last()[0])
&& this.activate ( i )
}
for (i = offsets.length; i--;) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (!offsets[i + 1] || scrollTop <= offsets[i + 1])
&& this.activate( targets[i] )
}
}
, activate: function (target) {
var active
, selector
this.activeTarget = target
$(this.selector)
.parent('.active')
.removeClass('active')
selector = this.selector
+ '[data-target="' + target + '"],'
+ this.selector + '[href="' + target + '"]'
active = $(selector)
.parent('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active.closest('li.dropdown').addClass('active')
}
active.trigger('activate')
}
}
/* SCROLLSPY PLUGIN DEFINITION
* =========================== */
$.fn.scrollspy = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('scrollspy')
, options = typeof option == 'object' && option
if (!data) $this.data('scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.scrollspy.Constructor = ScrollSpy
$.fn.scrollspy.defaults = {
offset: 10
}
/* SCROLLSPY DATA-API
* ================== */
$(window).on('load', function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
$spy.scrollspy($spy.data())
})
})
}(window.jQuery); |
/**
* angular-strap
* @version v2.0.0-rc.2 - 2014-01-29
* @link http://mgcrea.github.io/angular-strap
* @author [object Object]
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
'use strict';
angular.module('mgcrea.ngStrap.scrollspy', [
'mgcrea.ngStrap.helpers.debounce',
'mgcrea.ngStrap.helpers.dimensions'
]).provider('$scrollspy', function () {
var spies = this.$$spies = {};
var defaults = this.defaults = {
debounce: 150,
throttle: 100,
offset: 100
};
this.$get = [
'$window',
'$document',
'$rootScope',
'dimensions',
'debounce',
'throttle',
function ($window, $document, $rootScope, dimensions, debounce, throttle) {
var windowEl = angular.element($window);
var docEl = angular.element($document.prop('documentElement'));
var bodyEl = angular.element($window.document.body);
function nodeName(element, name) {
return element[0].nodeName && element[0].nodeName.toLowerCase() === name.toLowerCase();
}
function ScrollSpyFactory(config) {
var options = angular.extend({}, defaults, config);
if (!options.element)
options.element = bodyEl;
var isWindowSpy = nodeName(options.element, 'body');
var scrollEl = isWindowSpy ? windowEl : options.element;
var scrollId = isWindowSpy ? 'window' : options.id;
if (spies[scrollId]) {
spies[scrollId].$$count++;
return spies[scrollId];
}
var $scrollspy = {};
var trackedElements = $scrollspy.$trackedElements = [];
var sortedElements = [];
var activeTarget;
var debouncedCheckPosition;
var throttledCheckPosition;
var debouncedCheckOffsets;
var viewportHeight;
var scrollTop;
$scrollspy.init = function () {
this.$$count = 1;
debouncedCheckPosition = debounce(this.checkPosition, options.debounce);
throttledCheckPosition = throttle(this.checkPosition, options.throttle);
scrollEl.on('click', this.checkPositionWithEventLoop);
windowEl.on('resize', debouncedCheckPosition);
scrollEl.on('scroll', throttledCheckPosition);
debouncedCheckOffsets = debounce(this.checkOffsets, options.debounce);
$rootScope.$on('$viewContentLoaded', debouncedCheckOffsets);
$rootScope.$on('$includeContentLoaded', debouncedCheckOffsets);
debouncedCheckOffsets();
if (scrollId) {
spies[scrollId] = $scrollspy;
}
};
$scrollspy.destroy = function () {
this.$$count--;
if (this.$$count > 0) {
return;
}
scrollEl.off('click', this.checkPositionWithEventLoop);
windowEl.off('resize', debouncedCheckPosition);
scrollEl.off('scroll', debouncedCheckPosition);
$rootScope.$off('$viewContentLoaded', debouncedCheckOffsets);
$rootScope.$off('$includeContentLoaded', debouncedCheckOffsets);
};
$scrollspy.checkPosition = function () {
if (!sortedElements.length)
return;
scrollTop = (isWindowSpy ? $window.pageYOffset : scrollEl.prop('scrollTop')) || 0;
viewportHeight = Math.max($window.innerHeight, docEl.prop('clientHeight'));
if (scrollTop < sortedElements[0].offsetTop && activeTarget !== sortedElements[0].target) {
return $scrollspy.$activateElement(sortedElements[0]);
}
for (var i = sortedElements.length; i--;) {
if (angular.isUndefined(sortedElements[i].offsetTop) || sortedElements[i].offsetTop === null)
continue;
if (activeTarget === sortedElements[i].target)
continue;
if (scrollTop < sortedElements[i].offsetTop)
continue;
if (sortedElements[i + 1] && scrollTop > sortedElements[i + 1].offsetTop)
continue;
return $scrollspy.$activateElement(sortedElements[i]);
}
};
$scrollspy.checkPositionWithEventLoop = function () {
setTimeout(this.checkPosition, 1);
};
$scrollspy.$activateElement = function (element) {
if (activeTarget) {
var activeElement = $scrollspy.$getTrackedElement(activeTarget);
if (activeElement) {
activeElement.source.removeClass('active');
if (nodeName(activeElement.source, 'li') && nodeName(activeElement.source.parent().parent(), 'li')) {
activeElement.source.parent().parent().removeClass('active');
}
}
}
activeTarget = element.target;
element.source.addClass('active');
if (nodeName(element.source, 'li') && nodeName(element.source.parent().parent(), 'li')) {
element.source.parent().parent().addClass('active');
}
};
$scrollspy.$getTrackedElement = function (target) {
return trackedElements.filter(function (obj) {
return obj.target === target;
})[0];
};
$scrollspy.checkOffsets = function () {
angular.forEach(trackedElements, function (trackedElement) {
var targetElement = document.querySelector(trackedElement.target);
trackedElement.offsetTop = targetElement ? dimensions.offset(targetElement).top : null;
if (options.offset && trackedElement.offsetTop !== null)
trackedElement.offsetTop -= options.offset * 1;
});
sortedElements = trackedElements.filter(function (el) {
return el.offsetTop !== null;
}).sort(function (a, b) {
return a.offsetTop - b.offsetTop;
});
debouncedCheckPosition();
};
$scrollspy.trackElement = function (target, source) {
trackedElements.push({
target: target,
source: source
});
};
$scrollspy.untrackElement = function (target, source) {
var toDelete;
for (var i = trackedElements.length; i--;) {
if (trackedElements[i].target === target && trackedElements[i].source === source) {
toDelete = i;
break;
}
}
trackedElements = trackedElements.splice(toDelete, 1);
};
$scrollspy.activate = function (i) {
trackedElements[i].addClass('active');
};
$scrollspy.init();
return $scrollspy;
}
return ScrollSpyFactory;
}
];
}).directive('bsScrollspy', [
'$rootScope',
'debounce',
'dimensions',
'$scrollspy',
function ($rootScope, debounce, dimensions, $scrollspy) {
return {
restrict: 'EAC',
link: function postLink(scope, element, attr) {
var options = { scope: scope };
angular.forEach([
'offset',
'target'
], function (key) {
if (angular.isDefined(attr[key]))
options[key] = attr[key];
});
var scrollspy = $scrollspy(options);
scrollspy.trackElement(options.target, element);
scope.$on('$destroy', function () {
scrollspy.untrackElement(options.target, element);
scrollspy.destroy();
options = null;
scrollspy = null;
});
}
};
}
]).directive('bsScrollspyList', [
'$rootScope',
'debounce',
'dimensions',
'$scrollspy',
function ($rootScope, debounce, dimensions, $scrollspy) {
return {
restrict: 'A',
compile: function postLink(element, attr) {
var children = element[0].querySelectorAll('li > a[href]');
angular.forEach(children, function (child) {
var childEl = angular.element(child);
childEl.parent().attr('bs-scrollspy', '').attr('data-target', childEl.attr('href'));
});
}
};
}
]); |
/*!
* # Semantic UI 2.0.1 - Shape
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ( $, window, document, undefined ) {
"use strict";
$.fn.shape = function(parameters) {
var
$allModules = $(this),
$body = $('body'),
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
requestAnimationFrame = window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(callback) { setTimeout(callback, 0); },
returnedValue
;
$allModules
.each(function() {
var
moduleSelector = $allModules.selector || '',
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.shape.settings, parameters)
: $.extend({}, $.fn.shape.settings),
// internal aliases
namespace = settings.namespace,
selector = settings.selector,
error = settings.error,
className = settings.className,
// define namespaces for modules
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
// selector cache
$module = $(this),
$sides = $module.find(selector.sides),
$side = $module.find(selector.side),
// private variables
nextIndex = false,
$activeSide,
$nextSide,
// standard module
element = this,
instance = $module.data(moduleNamespace),
module
;
module = {
initialize: function() {
module.verbose('Initializing module for', element);
module.set.defaultSide();
module.instantiate();
},
instantiate: function() {
module.verbose('Storing instance of module', module);
instance = module;
$module
.data(moduleNamespace, instance)
;
},
destroy: function() {
module.verbose('Destroying previous module for', element);
$module
.removeData(moduleNamespace)
.off(eventNamespace)
;
},
refresh: function() {
module.verbose('Refreshing selector cache for', element);
$module = $(element);
$sides = $(this).find(selector.shape);
$side = $(this).find(selector.side);
},
repaint: function() {
module.verbose('Forcing repaint event');
var
shape = $sides[0] || document.createElement('div'),
fakeAssignment = shape.offsetWidth
;
},
animate: function(propertyObject, callback) {
module.verbose('Animating box with properties', propertyObject);
callback = callback || function(event) {
module.verbose('Executing animation callback');
if(event !== undefined) {
event.stopPropagation();
}
module.reset();
module.set.active();
};
settings.beforeChange.call($nextSide[0]);
if(module.get.transitionEvent()) {
module.verbose('Starting CSS animation');
$module
.addClass(className.animating)
;
$sides
.css(propertyObject)
.one(module.get.transitionEvent(), callback)
;
module.set.duration(settings.duration);
requestAnimationFrame(function() {
$module
.addClass(className.animating)
;
$activeSide
.addClass(className.hidden)
;
});
}
else {
callback();
}
},
queue: function(method) {
module.debug('Queueing animation of', method);
$sides
.one(module.get.transitionEvent(), function() {
module.debug('Executing queued animation');
setTimeout(function(){
$module.shape(method);
}, 0);
})
;
},
reset: function() {
module.verbose('Animating states reset');
$module
.removeClass(className.animating)
.attr('style', '')
.removeAttr('style')
;
// removeAttr style does not consistently work in safari
$sides
.attr('style', '')
.removeAttr('style')
;
$side
.attr('style', '')
.removeAttr('style')
.removeClass(className.hidden)
;
$nextSide
.removeClass(className.animating)
.attr('style', '')
.removeAttr('style')
;
},
is: {
complete: function() {
return ($side.filter('.' + className.active)[0] == $nextSide[0]);
},
animating: function() {
return $module.hasClass(className.animating);
}
},
set: {
defaultSide: function() {
$activeSide = $module.find('.' + settings.className.active);
$nextSide = ( $activeSide.next(selector.side).length > 0 )
? $activeSide.next(selector.side)
: $module.find(selector.side).first()
;
nextIndex = false;
module.verbose('Active side set to', $activeSide);
module.verbose('Next side set to', $nextSide);
},
duration: function(duration) {
duration = duration || settings.duration;
duration = (typeof duration == 'number')
? duration + 'ms'
: duration
;
module.verbose('Setting animation duration', duration);
if(settings.duration || settings.duration === 0) {
$sides.add($side)
.css({
'-webkit-transition-duration': duration,
'-moz-transition-duration': duration,
'-ms-transition-duration': duration,
'-o-transition-duration': duration,
'transition-duration': duration
})
;
}
},
currentStageSize: function() {
var
$activeSide = $module.find('.' + settings.className.active),
width = $activeSide.outerWidth(true),
height = $activeSide.outerHeight(true)
;
$module
.css({
width: width,
height: height
})
;
},
stageSize: function() {
var
$clone = $module.clone().addClass(className.loading),
$activeSide = $clone.find('.' + settings.className.active),
$nextSide = (nextIndex)
? $clone.find(selector.side).eq(nextIndex)
: ( $activeSide.next(selector.side).length > 0 )
? $activeSide.next(selector.side)
: $clone.find(selector.side).first(),
newSize = {}
;
module.set.currentStageSize();
$activeSide.removeClass(className.active);
$nextSide.addClass(className.active);
$clone.insertAfter($module);
newSize = {
width : $nextSide.outerWidth(true),
height : $nextSide.outerHeight(true)
};
$clone.remove();
$module
.css(newSize)
;
module.verbose('Resizing stage to fit new content', newSize);
},
nextSide: function(selector) {
nextIndex = selector;
$nextSide = $side.filter(selector);
nextIndex = $side.index($nextSide);
if($nextSide.length === 0) {
module.set.defaultSide();
module.error(error.side);
}
module.verbose('Next side manually set to', $nextSide);
},
active: function() {
module.verbose('Setting new side to active', $nextSide);
$side
.removeClass(className.active)
;
$nextSide
.addClass(className.active)
;
settings.onChange.call($nextSide[0]);
module.set.defaultSide();
}
},
flip: {
up: function() {
if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) {
module.debug('Side already visible', $nextSide);
return;
}
if( !module.is.animating()) {
module.debug('Flipping up', $nextSide);
module.set.stageSize();
module.stage.above();
module.animate( module.get.transform.up() );
}
else {
module.queue('flip up');
}
},
down: function() {
if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) {
module.debug('Side already visible', $nextSide);
return;
}
if( !module.is.animating()) {
module.debug('Flipping down', $nextSide);
module.set.stageSize();
module.stage.below();
module.animate( module.get.transform.down() );
}
else {
module.queue('flip down');
}
},
left: function() {
if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) {
module.debug('Side already visible', $nextSide);
return;
}
if( !module.is.animating()) {
module.debug('Flipping left', $nextSide);
module.set.stageSize();
module.stage.left();
module.animate(module.get.transform.left() );
}
else {
module.queue('flip left');
}
},
right: function() {
if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) {
module.debug('Side already visible', $nextSide);
return;
}
if( !module.is.animating()) {
module.debug('Flipping right', $nextSide);
module.set.stageSize();
module.stage.right();
module.animate(module.get.transform.right() );
}
else {
module.queue('flip right');
}
},
over: function() {
if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) {
module.debug('Side already visible', $nextSide);
return;
}
if( !module.is.animating()) {
module.debug('Flipping over', $nextSide);
module.set.stageSize();
module.stage.behind();
module.animate(module.get.transform.over() );
}
else {
module.queue('flip over');
}
},
back: function() {
if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) {
module.debug('Side already visible', $nextSide);
return;
}
if( !module.is.animating()) {
module.debug('Flipping back', $nextSide);
module.set.stageSize();
module.stage.behind();
module.animate(module.get.transform.back() );
}
else {
module.queue('flip back');
}
}
},
get: {
transform: {
up: function() {
var
translate = {
y: -(($activeSide.outerHeight(true) - $nextSide.outerHeight(true)) / 2),
z: -($activeSide.outerHeight(true) / 2)
}
;
return {
transform: 'translateY(' + translate.y + 'px) translateZ('+ translate.z + 'px) rotateX(-90deg)'
};
},
down: function() {
var
translate = {
y: -(($activeSide.outerHeight(true) - $nextSide.outerHeight(true)) / 2),
z: -($activeSide.outerHeight(true) / 2)
}
;
return {
transform: 'translateY(' + translate.y + 'px) translateZ('+ translate.z + 'px) rotateX(90deg)'
};
},
left: function() {
var
translate = {
x : -(($activeSide.outerWidth(true) - $nextSide.outerWidth(true)) / 2),
z : -($activeSide.outerWidth(true) / 2)
}
;
return {
transform: 'translateX(' + translate.x + 'px) translateZ(' + translate.z + 'px) rotateY(90deg)'
};
},
right: function() {
var
translate = {
x : -(($activeSide.outerWidth(true) - $nextSide.outerWidth(true)) / 2),
z : -($activeSide.outerWidth(true) / 2)
}
;
return {
transform: 'translateX(' + translate.x + 'px) translateZ(' + translate.z + 'px) rotateY(-90deg)'
};
},
over: function() {
var
translate = {
x : -(($activeSide.outerWidth(true) - $nextSide.outerWidth(true)) / 2)
}
;
return {
transform: 'translateX(' + translate.x + 'px) rotateY(180deg)'
};
},
back: function() {
var
translate = {
x : -(($activeSide.outerWidth(true) - $nextSide.outerWidth(true)) / 2)
}
;
return {
transform: 'translateX(' + translate.x + 'px) rotateY(-180deg)'
};
}
},
transitionEvent: function() {
var
element = document.createElement('element'),
transitions = {
'transition' :'transitionend',
'OTransition' :'oTransitionEnd',
'MozTransition' :'transitionend',
'WebkitTransition' :'webkitTransitionEnd'
},
transition
;
for(transition in transitions){
if( element.style[transition] !== undefined ){
return transitions[transition];
}
}
},
nextSide: function() {
return ( $activeSide.next(selector.side).length > 0 )
? $activeSide.next(selector.side)
: $module.find(selector.side).first()
;
}
},
stage: {
above: function() {
var
box = {
origin : (($activeSide.outerHeight(true) - $nextSide.outerHeight(true)) / 2),
depth : {
active : ($nextSide.outerHeight(true) / 2),
next : ($activeSide.outerHeight(true) / 2)
}
}
;
module.verbose('Setting the initial animation position as above', $nextSide, box);
$sides
.css({
'transform' : 'translateZ(-' + box.depth.active + 'px)'
})
;
$activeSide
.css({
'transform' : 'rotateY(0deg) translateZ(' + box.depth.active + 'px)'
})
;
$nextSide
.addClass(className.animating)
.css({
'top' : box.origin + 'px',
'transform' : 'rotateX(90deg) translateZ(' + box.depth.next + 'px)'
})
;
},
below: function() {
var
box = {
origin : (($activeSide.outerHeight(true) - $nextSide.outerHeight(true)) / 2),
depth : {
active : ($nextSide.outerHeight(true) / 2),
next : ($activeSide.outerHeight(true) / 2)
}
}
;
module.verbose('Setting the initial animation position as below', $nextSide, box);
$sides
.css({
'transform' : 'translateZ(-' + box.depth.active + 'px)'
})
;
$activeSide
.css({
'transform' : 'rotateY(0deg) translateZ(' + box.depth.active + 'px)'
})
;
$nextSide
.addClass(className.animating)
.css({
'top' : box.origin + 'px',
'transform' : 'rotateX(-90deg) translateZ(' + box.depth.next + 'px)'
})
;
},
left: function() {
var
height = {
active : $activeSide.outerWidth(true),
next : $nextSide.outerWidth(true)
},
box = {
origin : ( ( height.active - height.next ) / 2),
depth : {
active : (height.next / 2),
next : (height.active / 2)
}
}
;
module.verbose('Setting the initial animation position as left', $nextSide, box);
$sides
.css({
'transform' : 'translateZ(-' + box.depth.active + 'px)'
})
;
$activeSide
.css({
'transform' : 'rotateY(0deg) translateZ(' + box.depth.active + 'px)'
})
;
$nextSide
.addClass(className.animating)
.css({
'left' : box.origin + 'px',
'transform' : 'rotateY(-90deg) translateZ(' + box.depth.next + 'px)'
})
;
},
right: function() {
var
height = {
active : $activeSide.outerWidth(true),
next : $nextSide.outerWidth(true)
},
box = {
origin : ( ( height.active - height.next ) / 2),
depth : {
active : (height.next / 2),
next : (height.active / 2)
}
}
;
module.verbose('Setting the initial animation position as left', $nextSide, box);
$sides
.css({
'transform' : 'translateZ(-' + box.depth.active + 'px)'
})
;
$activeSide
.css({
'transform' : 'rotateY(0deg) translateZ(' + box.depth.active + 'px)'
})
;
$nextSide
.addClass(className.animating)
.css({
'left' : box.origin + 'px',
'transform' : 'rotateY(90deg) translateZ(' + box.depth.next + 'px)'
})
;
},
behind: function() {
var
height = {
active : $activeSide.outerWidth(true),
next : $nextSide.outerWidth(true)
},
box = {
origin : ( ( height.active - height.next ) / 2),
depth : {
active : (height.next / 2),
next : (height.active / 2)
}
}
;
module.verbose('Setting the initial animation position as behind', $nextSide, box);
$activeSide
.css({
'transform' : 'rotateY(0deg)'
})
;
$nextSide
.addClass(className.animating)
.css({
'left' : box.origin + 'px',
'transform' : 'rotateY(-180deg)'
})
;
}
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
settings[name] = value;
}
else {
return settings[name];
}
},
internal: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, module, name);
}
else if(value !== undefined) {
module[name] = value;
}
else {
return module[name];
}
},
debug: function() {
if(settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.debug.apply(console, arguments);
}
}
},
verbose: function() {
if(settings.verbose && settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.verbose.apply(console, arguments);
}
}
},
error: function() {
module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
module.error.apply(console, arguments);
},
performance: {
log: function(message) {
var
currentTime,
executionTime,
previousTime
;
if(settings.performance) {
currentTime = new Date().getTime();
previousTime = time || currentTime;
executionTime = currentTime - previousTime;
time = currentTime;
performance.push({
'Name' : message[0],
'Arguments' : [].slice.call(message, 1) || '',
'Element' : element,
'Execution Time' : executionTime
});
}
clearTimeout(module.performance.timer);
module.performance.timer = setTimeout(module.performance.display, 500);
},
display: function() {
var
title = settings.name + ':',
totalTime = 0
;
time = false;
clearTimeout(module.performance.timer);
$.each(performance, function(index, data) {
totalTime += data['Execution Time'];
});
title += ' ' + totalTime + 'ms';
if(moduleSelector) {
title += ' \'' + moduleSelector + '\'';
}
if($allModules.length > 1) {
title += ' ' + '(' + $allModules.length + ')';
}
if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
console.groupCollapsed(title);
if(console.table) {
console.table(performance);
}
else {
$.each(performance, function(index, data) {
console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
});
}
console.groupEnd();
}
performance = [];
}
},
invoke: function(query, passedArguments, context) {
var
object = instance,
maxDepth,
found,
response
;
passedArguments = passedArguments || queryArguments;
context = element || context;
if(typeof query == 'string' && object !== undefined) {
query = query.split(/[\. ]/);
maxDepth = query.length - 1;
$.each(query, function(depth, value) {
var camelCaseValue = (depth != maxDepth)
? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
: query
;
if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
object = object[camelCaseValue];
}
else if( object[camelCaseValue] !== undefined ) {
found = object[camelCaseValue];
return false;
}
else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
object = object[value];
}
else if( object[value] !== undefined ) {
found = object[value];
return false;
}
else {
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.shape.settings = {
// module info
name : 'Shape',
// debug content outputted to console
debug : false,
// verbose debug output
verbose : false,
// performance data output
performance: true,
// event namespace
namespace : 'shape',
// callback occurs on side change
beforeChange : function() {},
onChange : function() {},
// allow animation to same side
allowRepeats: false,
// animation duration
duration : false,
// possible errors
error: {
side : 'You tried to switch to a side that does not exist.',
method : 'The method you called is not defined'
},
// classnames used
className : {
animating : 'animating',
hidden : 'hidden',
loading : 'loading',
active : 'active'
},
// selectors used
selector : {
sides : '.sides',
side : '.side'
}
};
})( jQuery, window , document ); |
define([
"./core",
"./var/slice",
"./callbacks"
], function( jQuery, slice ) {
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
return jQuery;
});
|
'use strict';
// B.2.3.11 String.prototype.small()
require('./_string-html')('small', function (createHTML) {
return function small() {
return createHTML(this, 'small', '', '');
};
});
|
/*! esri-leaflet - v0.0.1-beta.7 - 2014-10-13
* Copyright (c) 2014 Environmental Systems Research Institute, Inc.
* Apache License*/
(function (factory) {
//define an AMD module that relies on 'leaflet'
if (typeof define === 'function' && define.amd) {
define(['leaflet', 'esri-leaflet'], function (L, Esri) {
return (exports = factory(L, Esri));
});
//define a common js module that relies on 'leaflet'
} else if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = factory(require('leaflet'), require('esri-leaflet'));
}
}(function (L, Esri) {
L.esri.Layers.HeatmapFeatureLayer = L.esri.Layers.FeatureManager.extend({
/**
* Constructor
*/
initialize: function (url, options) {
L.esri.Layers.FeatureManager.prototype.initialize.call(this, url, options);
options = L.setOptions(this, options);
this._cache = {};
this._active = {};
this.heat = new window.L.heatLayer([], options);
},
/**
* Layer Interface
*/
onAdd: function(map){
L.esri.Layers.FeatureManager.prototype.onAdd.call(this, map);
this._map.addLayer(this.heat);
},
onRemove: function(map){
L.esri.Layers.FeatureManager.prototype.onRemove.call(this, map);
this._map.removeLayer(this.heat);
},
/**
* Feature Managment Methods
*/
createLayers: function(features){
for (var i = features.length - 1; i >= 0; i--) {
var geojson = features[i];
var id = geojson.id;
var latlng = new L.LatLng(geojson.geometry.coordinates[1], geojson.geometry.coordinates[0]);
this._cache[id] = latlng;
// add the layer if it is within the time bounds or our layer is not time enabled
if(!this._active[id] && (!this.options.timeField || (this.options.timeField && this._featureWithinTimeRange(geojson)))){
this._active[id] = latlng;
this.heat._latlngs.push(latlng);
}
}
this.heat.redraw();
},
addLayers: function(ids){
for (var i = ids.length - 1; i >= 0; i--) {
var id = ids[i];
if(!this._active[id]){
var latlng = this._cache[id];
this.heat._latlngs.push(latlng);
this._active[id] = latlng;
}
}
this.heat.redraw();
},
removeLayers: function(ids, permanent){
var newLatLngs = [];
for (var i = ids.length - 1; i >= 0; i--) {
var id = ids[i];
if(this._active[id]){
delete this._active[id];
}
if(this._cache[id] && permanent){
delete this._cache[id];
}
}
for (var latlng in this._active){
newLatLngs.push(this._active[latlng]);
}
this.heat.setLatLngs(newLatLngs);
}
});
L.esri.HeatmapFeatureLayer = L.esri.Layers.HeatmapFeatureLayer;
L.esri.Layers.heatmapFeatureLayer = function(url, options){
return new L.esri.Layers.HeatmapFeatureLayer(url, options);
};
L.esri.heatmapFeatureLayer = function(url, options){
return new L.esri.Layers.heatmapFeatureLayer(url, options);
};
return EsriLeaflet;
}));
//# sourceMappingURL=esri-leaflet-heatmap-feature-layer-src.js.map |
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* Constructor - no need to invoke directly, call initBackgroundPage instead.
* @constructor
* @param {String} url_request_token The OAuth request token URL.
* @param {String} url_auth_token The OAuth authorize token URL.
* @param {String} url_access_token The OAuth access token URL.
* @param {String} consumer_key The OAuth consumer key.
* @param {String} consumer_secret The OAuth consumer secret.
* @param {String} oauth_scope The OAuth scope parameter.
* @param {Object} opt_args Optional arguments. Recognized parameters:
* "app_name" {String} Name of the current application
* "callback_page" {String} If you renamed chrome_ex_oauth.html, the name
* this file was renamed to.
*/
function ChromeExOAuth(url_request_token, url_auth_token, url_access_token,
consumer_key, consumer_secret, oauth_scope, opt_args) {
this.url_request_token = url_request_token;
this.url_auth_token = url_auth_token;
this.url_access_token = url_access_token;
this.consumer_key = consumer_key;
this.consumer_secret = consumer_secret;
this.oauth_scope = oauth_scope;
this.app_name = opt_args && opt_args['app_name'] ||
"ChromeExOAuth Library";
this.key_token = "oauth_token";
this.key_token_secret = "oauth_token_secret";
this.callback_page = opt_args && opt_args['callback_page'] ||
"chrome_ex_oauth.html";
this.auth_params = {};
if (opt_args && opt_args['auth_params']) {
for (key in opt_args['auth_params']) {
if (opt_args['auth_params'].hasOwnProperty(key)) {
this.auth_params[key] = opt_args['auth_params'][key];
}
}
}
};
/*******************************************************************************
* PUBLIC API METHODS
* Call these from your background page.
******************************************************************************/
/**
* Initializes the OAuth helper from the background page. You must call this
* before attempting to make any OAuth calls.
* @param {Object} oauth_config Configuration parameters in a JavaScript object.
* The following parameters are recognized:
* "request_url" {String} OAuth request token URL.
* "authorize_url" {String} OAuth authorize token URL.
* "access_url" {String} OAuth access token URL.
* "consumer_key" {String} OAuth consumer key.
* "consumer_secret" {String} OAuth consumer secret.
* "scope" {String} OAuth access scope.
* "app_name" {String} Application name.
* "auth_params" {Object} Additional parameters to pass to the
* Authorization token URL. For an example, 'hd', 'hl', 'btmpl':
* http://code.google.com/apis/accounts/docs/OAuth_ref.html#GetAuth
* @return {ChromeExOAuth} An initialized ChromeExOAuth object.
*/
ChromeExOAuth.initBackgroundPage = function(oauth_config) {
window.chromeExOAuthConfig = oauth_config;
window.chromeExOAuth = ChromeExOAuth.fromConfig(oauth_config);
window.chromeExOAuthRedirectStarted = false;
window.chromeExOAuthRequestingAccess = false;
var url_match = chrome.extension.getURL(window.chromeExOAuth.callback_page);
var tabs = {};
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.url &&
changeInfo.url.substr(0, url_match.length) === url_match &&
changeInfo.url != tabs[tabId] &&
window.chromeExOAuthRequestingAccess == false) {
chrome.tabs.create({ 'url' : changeInfo.url }, function(tab) {
tabs[tab.id] = tab.url;
chrome.tabs.remove(tabId);
});
}
});
return window.chromeExOAuth;
};
/**
* Authorizes the current user with the configued API. You must call this
* before calling sendSignedRequest.
* @param {Function} callback A function to call once an access token has
* been obtained. This callback will be passed the following arguments:
* token {String} The OAuth access token.
* secret {String} The OAuth access token secret.
*/
ChromeExOAuth.prototype.authorize = function(callback) {
if (this.hasToken()) {
callback(this.getToken(), this.getTokenSecret());
} else {
window.chromeExOAuthOnAuthorize = function(token, secret) {
callback(token, secret);
};
chrome.tabs.create({ 'url' :chrome.extension.getURL(this.callback_page) });
}
};
/**
* Clears any OAuth tokens stored for this configuration. Effectively a
* "logout" of the configured OAuth API.
*/
ChromeExOAuth.prototype.clearTokens = function() {
delete localStorage[this.key_token + encodeURI(this.oauth_scope)];
delete localStorage[this.key_token_secret + encodeURI(this.oauth_scope)];
};
/**
* Returns whether a token is currently stored for this configuration.
* Effectively a check to see whether the current user is "logged in" to
* the configured OAuth API.
* @return {Boolean} True if an access token exists.
*/
ChromeExOAuth.prototype.hasToken = function() {
return !!this.getToken();
};
/**
* Makes an OAuth-signed HTTP request with the currently authorized tokens.
* @param {String} url The URL to send the request to. Querystring parameters
* should be omitted.
* @param {Function} callback A function to be called once the request is
* completed. This callback will be passed the following arguments:
* responseText {String} The text response.
* xhr {XMLHttpRequest} The XMLHttpRequest object which was used to
* send the request. Useful if you need to check response status
* code, etc.
* @param {Object} opt_params Additional parameters to configure the request.
* The following parameters are accepted:
* "method" {String} The HTTP method to use. Defaults to "GET".
* "body" {String} A request body to send. Defaults to null.
* "parameters" {Object} Query parameters to include in the request.
* "headers" {Object} Additional headers to include in the request.
*/
ChromeExOAuth.prototype.sendSignedRequest = function(url, callback,
opt_params) {
var method = opt_params && opt_params['method'] || 'GET';
var body = opt_params && opt_params['body'] || null;
var params = opt_params && opt_params['parameters'] || {};
var headers = opt_params && opt_params['headers'] || {};
var signedUrl = this.signURL(url, method, params);
ChromeExOAuth.sendRequest(method, signedUrl, headers, body, function (xhr) {
if (xhr.readyState == 4) {
callback(xhr.responseText, xhr);
}
});
};
/**
* Adds the required OAuth parameters to the given url and returns the
* result. Useful if you need a signed url but don't want to make an XHR
* request.
* @param {String} method The http method to use.
* @param {String} url The base url of the resource you are querying.
* @param {Object} opt_params Query parameters to include in the request.
* @return {String} The base url plus any query params plus any OAuth params.
*/
ChromeExOAuth.prototype.signURL = function(url, method, opt_params) {
var token = this.getToken();
var secret = this.getTokenSecret();
if (!token || !secret) {
throw new Error("No oauth token or token secret");
}
var params = opt_params || {};
var result = OAuthSimple().sign({
action : method,
path : url,
parameters : params,
signatures: {
consumer_key : this.consumer_key,
shared_secret : this.consumer_secret,
oauth_secret : secret,
oauth_token: token
}
});
return result.signed_url;
};
/**
* Generates the Authorization header based on the oauth parameters.
* @param {String} url The base url of the resource you are querying.
* @param {Object} opt_params Query parameters to include in the request.
* @return {String} An Authorization header containing the oauth_* params.
*/
ChromeExOAuth.prototype.getAuthorizationHeader = function(url, method,
opt_params) {
var token = this.getToken();
var secret = this.getTokenSecret();
if (!token || !secret) {
throw new Error("No oauth token or token secret");
}
var params = opt_params || {};
return OAuthSimple().getHeaderString({
action: method,
path : url,
parameters : params,
signatures: {
consumer_key : this.consumer_key,
shared_secret : this.consumer_secret,
oauth_secret : secret,
oauth_token: token
}
});
};
/*******************************************************************************
* PRIVATE API METHODS
* Used by the library. There should be no need to call these methods directly.
******************************************************************************/
/**
* Creates a new ChromeExOAuth object from the supplied configuration object.
* @param {Object} oauth_config Configuration parameters in a JavaScript object.
* The following parameters are recognized:
* "request_url" {String} OAuth request token URL.
* "authorize_url" {String} OAuth authorize token URL.
* "access_url" {String} OAuth access token URL.
* "consumer_key" {String} OAuth consumer key.
* "consumer_secret" {String} OAuth consumer secret.
* "scope" {String} OAuth access scope.
* "app_name" {String} Application name.
* "auth_params" {Object} Additional parameters to pass to the
* Authorization token URL. For an example, 'hd', 'hl', 'btmpl':
* http://code.google.com/apis/accounts/docs/OAuth_ref.html#GetAuth
* @return {ChromeExOAuth} An initialized ChromeExOAuth object.
*/
ChromeExOAuth.fromConfig = function(oauth_config) {
return new ChromeExOAuth(
oauth_config['request_url'],
oauth_config['authorize_url'],
oauth_config['access_url'],
oauth_config['consumer_key'],
oauth_config['consumer_secret'],
oauth_config['scope'],
{
'app_name' : oauth_config['app_name'],
'auth_params' : oauth_config['auth_params']
}
);
};
/**
* Initializes chrome_ex_oauth.html and redirects the page if needed to start
* the OAuth flow. Once an access token is obtained, this function closes
* chrome_ex_oauth.html.
*/
ChromeExOAuth.initCallbackPage = function() {
var background_page = chrome.extension.getBackgroundPage();
var oauth_config = background_page.chromeExOAuthConfig;
var oauth = ChromeExOAuth.fromConfig(oauth_config);
background_page.chromeExOAuthRedirectStarted = true;
oauth.initOAuthFlow(function (token, secret) {
background_page.chromeExOAuthOnAuthorize(token, secret);
background_page.chromeExOAuthRedirectStarted = false;
chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
chrome.tabs.remove(tabs[0].id);
});
});
};
/**
* Sends an HTTP request. Convenience wrapper for XMLHttpRequest calls.
* @param {String} method The HTTP method to use.
* @param {String} url The URL to send the request to.
* @param {Object} headers Optional request headers in key/value format.
* @param {String} body Optional body content.
* @param {Function} callback Function to call when the XMLHttpRequest's
* ready state changes. See documentation for XMLHttpRequest's
* onreadystatechange handler for more information.
*/
ChromeExOAuth.sendRequest = function(method, url, headers, body, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(data) {
callback(xhr, data);
}
xhr.open(method, url, true);
if (headers) {
for (var header in headers) {
if (headers.hasOwnProperty(header)) {
xhr.setRequestHeader(header, headers[header]);
}
}
}
xhr.send(body);
};
/**
* Decodes a URL-encoded string into key/value pairs.
* @param {String} encoded An URL-encoded string.
* @return {Object} An object representing the decoded key/value pairs found
* in the encoded string.
*/
ChromeExOAuth.formDecode = function(encoded) {
var params = encoded.split("&");
var decoded = {};
for (var i = 0, param; param = params[i]; i++) {
var keyval = param.split("=");
if (keyval.length == 2) {
var key = ChromeExOAuth.fromRfc3986(keyval[0]);
var val = ChromeExOAuth.fromRfc3986(keyval[1]);
decoded[key] = val;
}
}
return decoded;
};
/**
* Returns the current window's querystring decoded into key/value pairs.
* @return {Object} A object representing any key/value pairs found in the
* current window's querystring.
*/
ChromeExOAuth.getQueryStringParams = function() {
var urlparts = window.location.href.split("?");
if (urlparts.length >= 2) {
var querystring = urlparts.slice(1).join("?");
return ChromeExOAuth.formDecode(querystring);
}
return {};
};
/**
* Binds a function call to a specific object. This function will also take
* a variable number of additional arguments which will be prepended to the
* arguments passed to the bound function when it is called.
* @param {Function} func The function to bind.
* @param {Object} obj The object to bind to the function's "this".
* @return {Function} A closure that will call the bound function.
*/
ChromeExOAuth.bind = function(func, obj) {
var newargs = Array.prototype.slice.call(arguments).slice(2);
return function() {
var combinedargs = newargs.concat(Array.prototype.slice.call(arguments));
func.apply(obj, combinedargs);
};
};
/**
* Encodes a value according to the RFC3986 specification.
* @param {String} val The string to encode.
*/
ChromeExOAuth.toRfc3986 = function(val){
return encodeURIComponent(val)
.replace(/\!/g, "%21")
.replace(/\*/g, "%2A")
.replace(/'/g, "%27")
.replace(/\(/g, "%28")
.replace(/\)/g, "%29");
};
/**
* Decodes a string that has been encoded according to RFC3986.
* @param {String} val The string to decode.
*/
ChromeExOAuth.fromRfc3986 = function(val){
var tmp = val
.replace(/%21/g, "!")
.replace(/%2A/g, "*")
.replace(/%27/g, "'")
.replace(/%28/g, "(")
.replace(/%29/g, ")");
return decodeURIComponent(tmp);
};
/**
* Adds a key/value parameter to the supplied URL.
* @param {String} url An URL which may or may not contain querystring values.
* @param {String} key A key
* @param {String} value A value
* @return {String} The URL with URL-encoded versions of the key and value
* appended, prefixing them with "&" or "?" as needed.
*/
ChromeExOAuth.addURLParam = function(url, key, value) {
var sep = (url.indexOf('?') >= 0) ? "&" : "?";
return url + sep +
ChromeExOAuth.toRfc3986(key) + "=" + ChromeExOAuth.toRfc3986(value);
};
/**
* Stores an OAuth token for the configured scope.
* @param {String} token The token to store.
*/
ChromeExOAuth.prototype.setToken = function(token) {
localStorage[this.key_token + encodeURI(this.oauth_scope)] = token;
};
/**
* Retrieves any stored token for the configured scope.
* @return {String} The stored token.
*/
ChromeExOAuth.prototype.getToken = function() {
return localStorage[this.key_token + encodeURI(this.oauth_scope)];
};
/**
* Stores an OAuth token secret for the configured scope.
* @param {String} secret The secret to store.
*/
ChromeExOAuth.prototype.setTokenSecret = function(secret) {
localStorage[this.key_token_secret + encodeURI(this.oauth_scope)] = secret;
};
/**
* Retrieves any stored secret for the configured scope.
* @return {String} The stored secret.
*/
ChromeExOAuth.prototype.getTokenSecret = function() {
return localStorage[this.key_token_secret + encodeURI(this.oauth_scope)];
};
/**
* Starts an OAuth authorization flow for the current page. If a token exists,
* no redirect is needed and the supplied callback is called immediately.
* If this method detects that a redirect has finished, it grabs the
* appropriate OAuth parameters from the URL and attempts to retrieve an
* access token. If no token exists and no redirect has happened, then
* an access token is requested and the page is ultimately redirected.
* @param {Function} callback The function to call once the flow has finished.
* This callback will be passed the following arguments:
* token {String} The OAuth access token.
* secret {String} The OAuth access token secret.
*/
ChromeExOAuth.prototype.initOAuthFlow = function(callback) {
if (!this.hasToken()) {
var params = ChromeExOAuth.getQueryStringParams();
if (params['chromeexoauthcallback'] == 'true') {
var oauth_token = params['oauth_token'];
var oauth_verifier = params['oauth_verifier']
this.getAccessToken(oauth_token, oauth_verifier, callback);
} else {
var request_params = {
'url_callback_param' : 'chromeexoauthcallback'
}
this.getRequestToken(function(url) {
window.location.href = url;
}, request_params);
}
} else {
callback(this.getToken(), this.getTokenSecret());
}
};
/**
* Requests an OAuth request token.
* @param {Function} callback Function to call once the authorize URL is
* calculated. This callback will be passed the following arguments:
* url {String} The URL the user must be redirected to in order to
* approve the token.
* @param {Object} opt_args Optional arguments. The following parameters
* are accepted:
* "url_callback" {String} The URL the OAuth provider will redirect to.
* "url_callback_param" {String} A parameter to include in the callback
* URL in order to indicate to this library that a redirect has
* taken place.
*/
ChromeExOAuth.prototype.getRequestToken = function(callback, opt_args) {
if (typeof callback !== "function") {
throw new Error("Specified callback must be a function.");
}
var url = opt_args && opt_args['url_callback'] ||
window && window.top && window.top.location &&
window.top.location.href;
var url_param = opt_args && opt_args['url_callback_param'] ||
"chromeexoauthcallback";
var url_callback = ChromeExOAuth.addURLParam(url, url_param, "true");
var result = OAuthSimple().sign({
path : this.url_request_token,
parameters: {
"xoauth_displayname" : this.app_name,
"scope" : this.oauth_scope,
"oauth_callback" : url_callback
},
signatures: {
consumer_key : this.consumer_key,
shared_secret : this.consumer_secret
}
});
var onToken = ChromeExOAuth.bind(this.onRequestToken, this, callback);
ChromeExOAuth.sendRequest("GET", result.signed_url, null, null, onToken);
};
/**
* Called when a request token has been returned. Stores the request token
* secret for later use and sends the authorization url to the supplied
* callback (for redirecting the user).
* @param {Function} callback Function to call once the authorize URL is
* calculated. This callback will be passed the following arguments:
* url {String} The URL the user must be redirected to in order to
* approve the token.
* @param {XMLHttpRequest} xhr The XMLHttpRequest object used to fetch the
* request token.
*/
ChromeExOAuth.prototype.onRequestToken = function(callback, xhr) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var params = ChromeExOAuth.formDecode(xhr.responseText);
var token = params['oauth_token'];
this.setTokenSecret(params['oauth_token_secret']);
var url = ChromeExOAuth.addURLParam(this.url_auth_token,
"oauth_token", token);
for (var key in this.auth_params) {
if (this.auth_params.hasOwnProperty(key)) {
url = ChromeExOAuth.addURLParam(url, key, this.auth_params[key]);
}
}
callback(url);
} else {
throw new Error("Fetching request token failed. Status " + xhr.status);
}
}
};
/**
* Requests an OAuth access token.
* @param {String} oauth_token The OAuth request token.
* @param {String} oauth_verifier The OAuth token verifier.
* @param {Function} callback The function to call once the token is obtained.
* This callback will be passed the following arguments:
* token {String} The OAuth access token.
* secret {String} The OAuth access token secret.
*/
ChromeExOAuth.prototype.getAccessToken = function(oauth_token, oauth_verifier,
callback) {
if (typeof callback !== "function") {
throw new Error("Specified callback must be a function.");
}
var bg = chrome.extension.getBackgroundPage();
if (bg.chromeExOAuthRequestingAccess == false) {
bg.chromeExOAuthRequestingAccess = true;
var result = OAuthSimple().sign({
path : this.url_access_token,
parameters: {
"oauth_token" : oauth_token,
"oauth_verifier" : oauth_verifier
},
signatures: {
consumer_key : this.consumer_key,
shared_secret : this.consumer_secret,
oauth_secret : this.getTokenSecret(this.oauth_scope)
}
});
var onToken = ChromeExOAuth.bind(this.onAccessToken, this, callback);
ChromeExOAuth.sendRequest("GET", result.signed_url, null, null, onToken);
}
};
/**
* Called when an access token has been returned. Stores the access token and
* access token secret for later use and sends them to the supplied callback.
* @param {Function} callback The function to call once the token is obtained.
* This callback will be passed the following arguments:
* token {String} The OAuth access token.
* secret {String} The OAuth access token secret.
* @param {XMLHttpRequest} xhr The XMLHttpRequest object used to fetch the
* access token.
*/
ChromeExOAuth.prototype.onAccessToken = function(callback, xhr) {
if (xhr.readyState == 4) {
var bg = chrome.extension.getBackgroundPage();
if (xhr.status == 200) {
var params = ChromeExOAuth.formDecode(xhr.responseText);
var token = params["oauth_token"];
var secret = params["oauth_token_secret"];
this.setToken(token);
this.setTokenSecret(secret);
bg.chromeExOAuthRequestingAccess = false;
callback(token, secret);
} else {
bg.chromeExOAuthRequestingAccess = false;
throw new Error("Fetching access token failed with status " + xhr.status);
}
}
}; |
var fstream = require('../fstream.js')
var tap = require('tap')
var fs = require('fs')
var path = require('path')
var dir = path.dirname(__dirname)
tap.test('reader test', function (t) {
var children = -1
var gotReady = false
var ended = false
var r = fstream.Reader({
path: dir,
filter: function () {
// return this.parent === r
return this.parent === r || this === r
}
})
r.on('ready', function () {
gotReady = true
children = fs.readdirSync(dir).length
console.error('Setting expected children to ' + children)
t.equal(r.type, 'Directory', 'should be a directory')
})
r.on('entry', function (entry) {
children--
if (!gotReady) {
t.fail('children before ready!')
}
t.equal(entry.dirname, r.path, 'basename is parent dir')
})
r.on('error', function (er) {
t.fail(er)
t.end()
process.exit(1)
})
r.on('end', function () {
t.equal(children, 0, 'should have seen all children')
ended = true
})
var closed = false
r.on('close', function () {
t.ok(ended, 'saw end before close')
t.notOk(closed, 'close should only happen once')
closed = true
t.end()
})
})
tap.test('reader error test', function (t) {
// assumes non-root on a *nix system
var r = fstream.Reader({ path: '/etc/shadow' })
r.once('error', function (er) {
t.ok(true)
t.end()
})
r.on('end', function () {
t.fail('reader ended without error')
t.end()
})
})
|
/*
* /MathJax/localization/pt/pt.js
*
* Copyright (c) 2009-2015 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Localization.addTranslation("pt",null,{menuTitle:"portugus\u00EA",version:"2.6.0-beta",isLoaded:true,domains:{_:{version:"2.6.0-beta",isLoaded:true,strings:{MathProcessingError:"Erro no processamento das f\u00F3rmulas",MathError:"Erro de matem\u00E1tica",LoadFile:"A carregar %1",Loading:"A carregar",LoadFailed:"O ficheiro n\u00E3o pode ser carregado: %1",ProcessMath:"Processando f\u00F3rmula: %1%%",Processing:"Processando",TypesetMath:"Formatando f\u00F3rmulas: %1%%",Typesetting:"Formatando",MathJaxNotSupported:"O seu navegador n\u00E3o suporta MathJax"}},FontWarnings:{},"HTML-CSS":{},HelpDialog:{},MathML:{},MathMenu:{},TeX:{}},plural:function(a){if(a===1){return 1}return 2},number:function(a){return String(a).replace(".",",")}});MathJax.Ajax.loadComplete("[MathJax]/localization/pt/pt.js");
|
(function(angular, factory) {
if (typeof define === 'function' && define.amd) {
define('angular-file-upload', ['angular'], function(angular) {
return factory(angular);
});
} else {
return factory(angular);
}
}(angular || null, function(angular) {
/**
* The angular file upload module
* @author: nerv
* @version: 0.2.5.2, 2012-09-25
*/
var app = angular.module('angularFileUpload', []);
/**
* The angular file upload module
* @author: nerv
* @version: 0.2.8.1, 2012-10-21
*/
// It is attached to an element that catches the event drop file
app.directive('ngFileDrop', function () {
'use strict';
return {
// don't use drag-n-drop files in IE9, because not File API support
link: !window.File ? angular.noop : function (scope, element, attributes) {
element
.bind('drop', function (event) {
var dataTransfer = event.dataTransfer ?
event.dataTransfer :
event.originalEvent.dataTransfer; // jQuery fix;
event.preventDefault();
event.stopPropagation();
scope.$broadcast('file:removeoverclass');
scope.$emit('file:add', dataTransfer.files, scope.$eval(attributes.ngFileDrop));
})
.bind('dragover', function (event) {
var dataTransfer = event.dataTransfer ?
event.dataTransfer :
event.originalEvent.dataTransfer; // jQuery fix;
event.preventDefault();
event.stopPropagation();
dataTransfer.dropEffect = 'copy';
scope.$broadcast('file:addoverclass');
})
.bind('dragleave', function () {
scope.$broadcast('file:removeoverclass');
});
}
};
})
/**
* The angular file upload module
* @author: nerv
* @version: 0.2.8.1, 2012-10-21
*/
// It is attached to an element which will be assigned to a class "ng-file-over" or ng-file-over="className"
app.directive('ngFileOver', function () {
'use strict';
return {
link: function (scope, element, attributes) {
scope.$on('file:addoverclass', function () {
element.addClass(attributes.ngFileOver || 'ng-file-over');
});
scope.$on('file:removeoverclass', function () {
element.removeClass(attributes.ngFileOver || 'ng-file-over');
});
}
};
});
/**
* The angular file upload module
* @author: nerv
* @version: 0.2.8.1, 2012-10-21
*/
// It is attached to <input type="file"> element like <ng-file-select="options">
app.directive('ngFileSelect', function () {
'use strict';
return {
link: function (scope, element, attributes) {
if (!window.File || !window.FormData) {
element.removeAttr('multiple');
}
element.bind('change', function () {
scope.$emit('file:add', this.files ? this.files : this, scope.$eval(attributes.ngFileSelect));
window.File && element.prop('value', null);
});
}
};
});
/**
* The angular file upload module
* @author: nerv
* @version: 0.2.8.1, 2012-10-21
*/
app.factory('$fileUploader', [ '$compile', '$rootScope', '$http', function ($compile, $rootScope, $http) {
'use strict';
function Uploader(params) {
angular.extend(this, {
scope: $rootScope,
url: '/',
alias: 'file',
queue: [],
headers: {},
progress: null,
autoUpload: false,
removeAfterUpload: false,
filters: [],
formData: [],
isUploading: false,
_uploadNext: false,
_timestamp: Date.now()
}, params);
this._observer = this.scope.$new(true);
// add the base filter
this.filters.unshift(this._filter);
$rootScope.$on('file:add', function (event, items, options) {
event.stopPropagation();
this.addToQueue(items, options);
}.bind(this));
this.bind('beforeupload', Item.prototype._beforeupload);
this.bind('in:progress', Item.prototype._progress);
this.bind('in:success', Item.prototype._success);
this.bind('in:error', Item.prototype._error);
this.bind('in:complete', Item.prototype._complete);
this.bind('changedqueue', this._changedQueue);
this.bind('in:progress', this._progress);
this.bind('in:complete', this._complete);
}
Uploader.prototype = {
/**
* The base filter. If returns "true" an item will be added to the queue
* @param {File|Input} item
* @returns {boolean}
*/
_filter: function (item) {
return angular.isElement(item) ? true : !!item.size;
},
/**
* Registers a event handler
* @param {String} event
* @param {Function} handler
*/
bind: function (event, handler) {
this._observer.$on(this._timestamp + ':' + event, handler.bind(this));
return this;
},
/**
* Triggers events
* @param {String} event
* @param {...*} [some]
*/
trigger: function (event, some) {
var params = Array.prototype.slice.call(arguments, 1);
params.unshift(this._timestamp + ':' + event);
this._observer.$emit.apply(this._observer, params);
return this;
},
/**
* Checks a support the html5 uploader
* @returns {Boolean}
*/
hasHTML5: function () {
return !!(window.File && window.FormData);
},
/**
* Adds items to the queue
* @param {FileList|File|Input} items
* @param {Object} [options]
*/
addToQueue: function (items, options) {
var length = this.queue.length;
angular.forEach('length' in items ? items : [ items ], function (item) {
var isValid = !this.filters.length ? true : this.filters.every(function (filter) {
return filter.call(this, item);
}, this);
if (isValid) {
item = new Item(angular.extend({
url: this.url,
alias: this.alias,
headers: angular.copy(this.headers),
formData: angular.copy(this.formData),
removeAfterUpload: this.removeAfterUpload,
uploader: this,
file: item
}, options));
this.queue.push(item);
this.trigger('afteraddingfile', item);
}
}, this);
if (this.queue.length !== length) {
this.trigger('afteraddingall', this.queue);
this.trigger('changedqueue', this.queue);
}
this.autoUpload && this.uploadAll();
return this;
},
/**
* Remove items from the queue. Remove last: index = -1
* @param {Item|Number} value
*/
removeFromQueue: function (value) {
var index = angular.isObject(value) ? this.getIndexOfItem(value) : value;
var item = this.queue.splice(index, 1)[ 0 ];
item.file._form && item.file._form.remove();
this.trigger('changedqueue', item);
return this;
},
/**
* Clears the queue
*/
clearQueue: function () {
angular.forEach(this.queue, function (item) {
item.file._form && item.file._form.remove();
}, this);
this.queue.length = 0;
this.trigger('changedqueue', this.queue);
return this;
},
/**
* Returns a index of item from the queue
* @param item
* @returns {Number}
*/
getIndexOfItem: function (item) {
return this.queue.indexOf(item);
},
/**
* Returns not uploaded items
* @returns {Array}
*/
getNotUploadedItems: function () {
return this.queue.filter(function (item) {
return !item.isUploaded;
});
},
/**
* Upload a item from the queue
* @param {Item|Number} value
*/
uploadItem: function (value) {
if (this.isUploading) {
return this;
}
var index = angular.isObject(value) ? this.getIndexOfItem(value) : value;
var item = this.queue[ index ];
var transport = item.file._form ? '_iframeTransport' : '_xhrTransport';
this.isUploading = true;
this[ transport ](item);
return this;
},
/**
* Uploads all items of queue
*/
uploadAll: function () {
var item = this.getNotUploadedItems()[ 0 ];
this._uploadNext = !!item;
this._uploadNext && this.uploadItem(item);
return this;
},
/**
* Returns the total progress
* @param {Number} [value]
* @returns {Number}
*/
_getTotalProgress: function (value) {
if (this.removeAfterUpload) {
return value || 0;
}
var notUploaded = this.getNotUploadedItems().length;
var uploaded = notUploaded ? this.queue.length - notUploaded : this.queue.length;
var ratio = 100 / this.queue.length;
var current = ( value || 0 ) * ratio / 100;
return Math.round(uploaded * ratio + current);
},
/**
* The 'in:progress' handler
*/
_progress: function (event, item, progress) {
var result = this._getTotalProgress(progress);
this.progress = result;
this.trigger('progressall', result);
this.scope.$$phase || this.scope.$apply();
},
/**
* The 'in:complete' handler
*/
_complete: function () {
this.isUploading = false;
this._uploadNext && this.uploadAll();
this._uploadNext || this.trigger('completeall', this.queue);
( this._uploadNext && this.scope.$$phase ) || this.scope.$apply();
},
/**
* The 'changedqueue' handler
*/
_changedQueue: function () {
this.progress = this._getTotalProgress();
this.scope.$$phase || this.scope.$apply();
},
/**
* The XMLHttpRequest transport
*/
_xhrTransport: function (item) {
var xhr = new XMLHttpRequest();
var form = new FormData();
var that = this;
angular.forEach(item.formData, function(obj) {
angular.forEach(obj, function(value, key) {
form.append(key, value);
});
});
form.append(item.alias, item.file);
xhr.upload.addEventListener('progress', function (event) {
var progress = event.lengthComputable ? event.loaded * 100 / event.total : 0;
that.trigger('in:progress', item, Math.round(progress));
}, false);
xhr.addEventListener('load', function () {
var response = that._transformResponse(xhr.response);
xhr.status === 200 && that.trigger('in:success', xhr, item, response);
xhr.status !== 200 && that.trigger('in:error', xhr, item, response);
that.trigger('in:complete', xhr, item, response);
}, false);
xhr.addEventListener('error', function () {
that.trigger('in:error', xhr, item);
that.trigger('in:complete', xhr, item);
}, false);
xhr.addEventListener('abort', function () {
that.trigger('in:complete', xhr, item);
}, false);
this.trigger('beforeupload', item);
xhr.open('POST', item.url, true);
angular.forEach(item.headers, function (value, name) {
xhr.setRequestHeader(name, value);
});
xhr.send(form);
},
/**
* The IFrame transport
*/
_iframeTransport: function (item) {
var form = item.file._form;
var iframe = form.find('iframe');
var input = form.find('input');
var that = this;
// remove all but the INPUT file type
angular.forEach(input, function(element) {
element.type !== 'file' && element.parentNode.removeChild(element);
});
input.prop('name', item.alias);
angular.forEach(item.formData, function(obj) {
angular.forEach(obj, function(value, key) {
form.append(
angular.element('<input type="hidden" name="' + key + '" value="' + value + '" />')
);
});
});
form.prop({
action: item.url,
method: 'post',
target: iframe.prop('name'),
enctype: 'multipart/form-data',
encoding: 'multipart/form-data' // old IE
});
iframe.unbind().bind('load', function () {
var xhr = { response: iframe.contents()[ 0 ].body.innerHTML, status: 200, dummy: true };
var response = that._transformResponse(xhr.response);
that.trigger('in:complete', xhr, item, response);
});
this.trigger('beforeupload', item);
form[ 0 ].submit();
},
/**
* Transforms the server response
*/
_transformResponse: function (response) {
angular.forEach($http.defaults.transformResponse, function (transformFn) {
response = transformFn(response);
});
return response;
}
};
// item of queue
function Item(params) {
// fix for old browsers
if (angular.isElement(params.file)) {
var input = angular.element(params.file);
var clone = $compile(input.clone())(params.uploader.scope.$new(true));
var form = angular.element('<form style="display: none;" />');
var iframe = angular.element('<iframe name="iframeTransport' + +new Date() + '">');
var value = input.val();
params.file = {
lastModifiedDate: null,
size: null,
type: 'like/' + value.replace(/^.+\.(?!\.)|.*/, ''),
name: value.match(/[^\\]+$/)[ 0 ],
_form: form
};
input.after(clone).after(form);
form.append(input).append(iframe);
}
angular.extend(this, {
progress: null,
isUploading: false,
isUploaded: false
}, params);
}
Item.prototype = {
remove: function () {
this.uploader.removeFromQueue(this);
},
upload: function () {
this.uploader.uploadItem(this);
},
_beforeupload: function (event, item) {
item.isUploaded = false;
item.isUploading = true;
item.progress = null;
},
_progress: function (event, item, progress) {
item.progress = progress;
item.uploader.trigger('progress', item, progress);
},
_success: function (event, xhr, item, response) {
item.isUploaded = true;
item.isUploading = false;
item.uploader.trigger('success', xhr, item, response);
},
_error: function (event, xhr, item, response) {
item.isUploaded = true;
item.isUploading = false;
item.uploader.trigger('error', xhr, item, response);
},
_complete: function (event, xhr, item, response) {
item.isUploaded = true;
item.isUploading = false;
item.uploader.trigger('complete', xhr, item, response);
item.removeAfterUpload && item.remove();
}
};
return {
create: function (params) {
return new Uploader(params);
}
};
}])
return app;
})); |
/**
* @author Jason Dobry <jason.dobry@gmail.com>
* @file js-data-localforage.js
* @version 1.0.0-alpha.2 - Homepage <http://www.js-data.iojs-data-localforage/>
* @copyright (c) 2014 Jason Dobry
* @license MIT <https://github.com/js-data/js-data-localforage/blob/master/LICENSE>
*
* @overview localforage adapter for js-data.
*/
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var o;"undefined"!=typeof window?o=window:"undefined"!=typeof global?o=global:"undefined"!=typeof self&&(o=self),o.DSLocalForageAdapter=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var isKind = require('./isKind');
/**
*/
var isArray = Array.isArray || function (val) {
return isKind(val, 'Array');
};
module.exports = isArray;
},{"./isKind":2}],2:[function(require,module,exports){
var kindOf = require('./kindOf');
/**
* Check if value is from a specific "kind".
*/
function isKind(val, kind){
return kindOf(val) === kind;
}
module.exports = isKind;
},{"./kindOf":3}],3:[function(require,module,exports){
var _rKind = /^\[object (.*)\]$/,
_toString = Object.prototype.toString,
UNDEF;
/**
* Gets the "kind" of value. (e.g. "String", "Number", etc)
*/
function kindOf(val) {
if (val === null) {
return 'Null';
} else if (val === UNDEF) {
return 'Undefined';
} else {
return _rKind.exec( _toString.call(val) )[1];
}
}
module.exports = kindOf;
},{}],4:[function(require,module,exports){
/**
* @constant Maximum 32-bit signed integer value. (2^31 - 1)
*/
module.exports = 2147483647;
},{}],5:[function(require,module,exports){
/**
* @constant Minimum 32-bit signed integer value (-2^31).
*/
module.exports = -2147483648;
},{}],6:[function(require,module,exports){
var hasOwn = require('./hasOwn');
var _hasDontEnumBug,
_dontEnums;
function checkDontEnum(){
_dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
_hasDontEnumBug = true;
for (var key in {'toString': null}) {
_hasDontEnumBug = false;
}
}
/**
* Similar to Array/forEach but works over object properties and fixes Don't
* Enum bug on IE.
* based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
*/
function forIn(obj, fn, thisObj){
var key, i = 0;
// no need to check if argument is a real object that way we can use
// it for arrays, functions, date, etc.
//post-pone check till needed
if (_hasDontEnumBug == null) checkDontEnum();
for (key in obj) {
if (exec(fn, obj, key, thisObj) === false) {
break;
}
}
if (_hasDontEnumBug) {
var ctor = obj.constructor,
isProto = !!ctor && obj === ctor.prototype;
while (key = _dontEnums[i++]) {
// For constructor, if it is a prototype object the constructor
// is always non-enumerable unless defined otherwise (and
// enumerated above). For non-prototype objects, it will have
// to be defined on this object, since it cannot be defined on
// any prototype objects.
//
// For other [[DontEnum]] properties, check if the value is
// different than Object prototype value.
if (
(key !== 'constructor' ||
(!isProto && hasOwn(obj, key))) &&
obj[key] !== Object.prototype[key]
) {
if (exec(fn, obj, key, thisObj) === false) {
break;
}
}
}
}
}
function exec(fn, obj, key, thisObj){
return fn.call(thisObj, obj[key], key, obj);
}
module.exports = forIn;
},{"./hasOwn":8}],7:[function(require,module,exports){
var hasOwn = require('./hasOwn');
var forIn = require('./forIn');
/**
* Similar to Array/forEach but works over object properties and fixes Don't
* Enum bug on IE.
* based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
*/
function forOwn(obj, fn, thisObj){
forIn(obj, function(val, key){
if (hasOwn(obj, key)) {
return fn.call(thisObj, obj[key], key, obj);
}
});
}
module.exports = forOwn;
},{"./forIn":6,"./hasOwn":8}],8:[function(require,module,exports){
/**
* Safer Object.hasOwnProperty
*/
function hasOwn(obj, prop){
return Object.prototype.hasOwnProperty.call(obj, prop);
}
module.exports = hasOwn;
},{}],9:[function(require,module,exports){
var forOwn = require('./forOwn');
/**
* Get object keys
*/
var keys = Object.keys || function (obj) {
var keys = [];
forOwn(obj, function(val, key){
keys.push(key);
});
return keys;
};
module.exports = keys;
},{"./forOwn":7}],10:[function(require,module,exports){
var randInt = require('./randInt');
var isArray = require('../lang/isArray');
/**
* Returns a random element from the supplied arguments
* or from the array (if single argument is an array).
*/
function choice(items) {
var target = (arguments.length === 1 && isArray(items))? items : arguments;
return target[ randInt(0, target.length - 1) ];
}
module.exports = choice;
},{"../lang/isArray":1,"./randInt":14}],11:[function(require,module,exports){
var randHex = require('./randHex');
var choice = require('./choice');
/**
* Returns pseudo-random guid (UUID v4)
* IMPORTANT: it's not totally "safe" since randHex/choice uses Math.random
* by default and sequences can be predicted in some cases. See the
* "random/random" documentation for more info about it and how to replace
* the default PRNG.
*/
function guid() {
return (
randHex(8)+'-'+
randHex(4)+'-'+
// v4 UUID always contain "4" at this position to specify it was
// randomly generated
'4' + randHex(3) +'-'+
// v4 UUID always contain chars [a,b,8,9] at this position
choice(8, 9, 'a', 'b') + randHex(3)+'-'+
randHex(12)
);
}
module.exports = guid;
},{"./choice":10,"./randHex":13}],12:[function(require,module,exports){
var random = require('./random');
var MIN_INT = require('../number/MIN_INT');
var MAX_INT = require('../number/MAX_INT');
/**
* Returns random number inside range
*/
function rand(min, max){
min = min == null? MIN_INT : min;
max = max == null? MAX_INT : max;
return min + (max - min) * random();
}
module.exports = rand;
},{"../number/MAX_INT":4,"../number/MIN_INT":5,"./random":15}],13:[function(require,module,exports){
var choice = require('./choice');
var _chars = '0123456789abcdef'.split('');
/**
* Returns a random hexadecimal string
*/
function randHex(size){
size = size && size > 0? size : 6;
var str = '';
while (size--) {
str += choice(_chars);
}
return str;
}
module.exports = randHex;
},{"./choice":10}],14:[function(require,module,exports){
var MIN_INT = require('../number/MIN_INT');
var MAX_INT = require('../number/MAX_INT');
var rand = require('./rand');
/**
* Gets random integer inside range or snap to min/max values.
*/
function randInt(min, max){
min = min == null? MIN_INT : ~~min;
max = max == null? MAX_INT : ~~max;
// can't be max + 0.5 otherwise it will round up if `rand`
// returns `max` causing it to overflow range.
// -0.5 and + 0.49 are required to avoid bias caused by rounding
return Math.round( rand(min - 0.5, max + 0.499999999999) );
}
module.exports = randInt;
},{"../number/MAX_INT":4,"../number/MIN_INT":5,"./rand":12}],15:[function(require,module,exports){
/**
* Just a wrapper to Math.random. No methods inside mout/random should call
* Math.random() directly so we can inject the pseudo-random number
* generator if needed (ie. in case we need a seeded random or a better
* algorithm than the native one)
*/
function random(){
return random.get();
}
// we expose the method so it can be swapped if needed
random.get = Math.random;
module.exports = random;
},{}],16:[function(require,module,exports){
var JSData;
try {
JSData = require('js-data');
} catch (e) {
}
if (!JSData) {
try {
JSData = window.JSData;
} catch (e) {
}
}
if (!JSData) {
throw new Error('js-data must be loaded!');
} else if (!localforage) {
throw new Error('localforage must be loaded!');
}
var emptyStore = new JSData.DS();
var DSUtils = JSData.DSUtils;
var makePath = DSUtils.makePath;
var deepMixIn = DSUtils.deepMixIn;
var forEach = DSUtils.forEach;
var filter = emptyStore.defaults.defaultFilter;
var guid = require('mout/random/guid');
var keys = require('mout/object/keys');
var P = DSUtils.Promise;
function Defaults() {
}
Defaults.prototype.basePath = '';
function DSLocalForageAdapter(options) {
options = options || {};
this.defaults = new Defaults();
deepMixIn(this.defaults, options);
}
var dsLocalForageAdapterPrototype = DSLocalForageAdapter.prototype;
dsLocalForageAdapterPrototype.getPath = function (resourceConfig, options) {
return makePath(options.basePath || this.defaults.basePath || resourceConfig.basePath, resourceConfig.name);
};
dsLocalForageAdapterPrototype.getIdPath = function (resourceConfig, options, id) {
return makePath(options.basePath || this.defaults.basePath || resourceConfig.basePath, resourceConfig.getEndpoint(id, options), id);
};
dsLocalForageAdapterPrototype.getIds = function (resourceConfig, options) {
var idsPath = this.getPath(resourceConfig, options);
return new P(function (resolve, reject) {
localforage.getItem(idsPath, function (err, ids) {
if (err) {
return reject(err);
} else if (ids) {
return resolve(ids);
} else {
return localforage.setItem(idsPath, {}, function (err, v) {
if (err) {
reject(err);
} else {
resolve(v);
}
});
}
});
});
};
dsLocalForageAdapterPrototype.saveKeys = function (ids, resourceConfig, options) {
var keysPath = this.getPath(resourceConfig, options);
return new P(function (resolve, reject) {
localforage.setItem(keysPath, ids, function (err, v) {
if (err) {
reject(err);
} else {
resolve(v);
}
});
});
};
dsLocalForageAdapterPrototype.ensureId = function (id, resourceConfig, options) {
var _this = this;
return _this.getIds(resourceConfig, options).then(function (ids) {
ids[id] = 1;
return _this.saveKeys(ids, resourceConfig, options);
});
};
dsLocalForageAdapterPrototype.removeId = function (id, resourceConfig, options) {
var _this = this;
return _this.getIds(resourceConfig, options).then(function (ids) {
delete ids[id];
return _this.saveKeys(ids, resourceConfig, options);
});
};
dsLocalForageAdapterPrototype.GET = function (key) {
return new P(function (resolve, reject) {
localforage.getItem(key, function (err, v) {
if (err) {
reject(err);
} else {
resolve(v);
}
});
});
};
dsLocalForageAdapterPrototype.PUT = function (key, value) {
return this.GET(key).then(function (item) {
if (item) {
deepMixIn(item, value);
}
return new P(function (resolve, reject) {
localforage.setItem(key, item || value, function (err, v) {
if (err) {
reject(err);
} else {
resolve(v);
}
});
});
});
};
dsLocalForageAdapterPrototype.DEL = function (key) {
return new P(function (resolve) {
localforage.removeItem(key, resolve);
});
};
dsLocalForageAdapterPrototype.find = function find(resourceConfig, id, options) {
options = options || {};
return this.GET(this.getIdPath(resourceConfig, options, id)).then(function (item) {
if (!item) {
return P.reject(new Error('Not Found!'));
} else {
return item;
}
});
};
dsLocalForageAdapterPrototype.findAll = function (resourceConfig, params, options) {
var _this = this;
options = options || {};
return _this.getIds(resourceConfig, options).then(function (ids) {
var idsArray = keys(ids);
if (!('allowSimpleWhere' in options)) {
options.allowSimpleWhere = true;
}
var tasks = [];
forEach(idsArray, function (id) {
tasks.push(_this.GET(_this.getIdPath(resourceConfig, options, id)));
});
return P.all(tasks);
}).then(function (items) {
return filter.call(emptyStore, items, resourceConfig.name, params, options);
});
};
dsLocalForageAdapterPrototype.create = function (resourceConfig, attrs, options) {
var _this = this;
var i;
attrs[resourceConfig.idAttribute] = attrs[resourceConfig.idAttribute] || guid();
options = options || {};
return _this.PUT(
makePath(this.getIdPath(resourceConfig, options, attrs[resourceConfig.idAttribute])),
attrs
).then(function (item) {
i = item;
return _this.ensureId(item[resourceConfig.idAttribute], resourceConfig, options);
}).then(function () {
return i;
});
};
dsLocalForageAdapterPrototype.update = function (resourceConfig, id, attrs, options) {
var _this = this;
var i;
options = options || {};
return _this.PUT(_this.getIdPath(resourceConfig, options, id), attrs).then(function (item) {
i = item;
return _this.ensureId(item[resourceConfig.idAttribute], resourceConfig, options);
}).then(function () {
return i;
});
};
dsLocalForageAdapterPrototype.updateAll = function (resourceConfig, attrs, params, options) {
var _this = this;
return _this.findAll(resourceConfig, params, options).then(function (items) {
var tasks = [];
forEach(items, function (item) {
tasks.push(_this.update(resourceConfig, item[resourceConfig.idAttribute], attrs, options));
});
return P.all(tasks);
});
};
dsLocalForageAdapterPrototype.destroy = function (resourceConfig, id, options) {
var _this = this;
options = options || {};
return _this.DEL(_this.getIdPath(resourceConfig, options, id)).then(function () {
return _this.removeId(id, resourceConfig, options);
}).then(function () {
return null;
});
};
dsLocalForageAdapterPrototype.destroyAll = function (resourceConfig, params, options) {
var _this = this;
return _this.findAll(resourceConfig, params, options).then(function (items) {
var tasks = [];
forEach(items, function (item) {
tasks.push(_this.destroy(resourceConfig, item[resourceConfig.idAttribute], options));
});
return P.all(tasks);
});
};
module.exports = DSLocalForageAdapter;
},{"js-data":"js-data","mout/object/keys":9,"mout/random/guid":11}]},{},[16])(16)
}); |
!function(t){"use strict";function n(t,n){return t+" "+n+(5>t%10&&t%10>0&&(5>t%100||t%100>19)?t%10>1?"и":"":"ів")}t.fn.select2.locales.uk={formatMatches:function(t){return n(t,"результат")+" знайдено, використовуйте клавіші зі стрілками вверх та вниз для навігації."},formatNoMatches:function(){return"Нічого не знайдено"},formatInputTooShort:function(t,o){return"Введіть буль ласка ще "+n(o-t.length,"символ")},formatInputTooLong:function(t,o){return"Введіть буль ласка на "+n(t.length-o,"символ")+" менше"},formatSelectionTooBig:function(t){return"Ви можете вибрати лише "+n(t,"елемент")},formatLoadMore:function(){return"Завантаження даних…"},formatSearching:function(){return"Пошук…"}},t.extend(t.fn.select2.defaults,t.fn.select2.locales.uk)}(jQuery); |
require('babel-polyfill');
require('babel-core/register');
require('./lib/SupervisorStarter.js').startSupervisor();
|
'use strict';
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
const path = require('path');
const url = require('url');
const express = require('express');
const spawn = require('child_process').spawn;
const mkdirp = Promise.promisifyAll(require('mkdirp'));
const semver = require('semver');
const SourceNode = require('source-map').SourceNode;
const SourceMapConsumer = require('source-map').SourceMapConsumer;
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const waitForSocket = require('socket-retry-connect').waitForSocket;
const fetch = require('./fetch');
const ENTRY_JS = 'global.React = require("react-native");';
const SOURCEMAP_REGEX = /\/\/[#@] sourceMappingURL=([^\s'"]*)/;
const makeExternals = require('../packager/lib/makeExternals');
function staticImageTransform(context, request, callback) {
if (/^image!/.test(request)) {
return callback(null, JSON.stringify({
uri: request.replace('image!', ''),
isStatic: true,
}));
}
callback();
}
function makeHotConfig(webpackConfig) {
webpackConfig.plugins = webpackConfig.plugins || [];
webpackConfig.plugins.unshift(
new webpack.BannerPlugin(
'if (typeof navigator.userAgent === \'undefined\') {\n' +
' throw new Error(\'Hot module replacement only works with RCTWebSocketExecutor; use Cmd + D, "Debug in Chrome"\')' +
'}\n',
{raw: true, entryOnly: true}
)
);
}
class Server {
/**
* Create a new server with the following options:
* @param {String} hostname
* @param {Number} port
* @param {Number} packagerPort
* @param {Number} webpackPort
* @param {Boolean} android Enable Android support
* @param {Boolean} ios Enable iOS support
* @param {String} androidEntry
* @param {String} iosEntry
* @param {Object} webpackConfig The webpack config to use for webpack-dev-server
* @param {Boolean} hot Enable hot module replacement
*
* @constructor
* @param {Object} options
*/
constructor(options) {
this.hostname = options.hostname;
this.port = options.port;
this.packagerPort = options.packagerPort;
this.webpackPort = options.webpackPort;
this.entries = {
android: options.androidEntry,
ios: options.iosEntry,
};
this.platforms = options.platforms;
this.projectRoots = options.projectRoots;
this.assetRoots = options.assetRoots;
this.resetCache = !!options.resetCache;
this.hot = !!options.hot;
this.webpackConfig = options.webpackConfig;
this.dev = !!options.dev;
this.serverRouter = options.serverRouter ? path.resolve(process.cwd(),options.serverRouter) : null;
this.makerExt = new makeExternals({
projectRoots :options.projectRoots,
assetRoots :options.assetRoots,
dev: this.dev
})
this.fetch = fetch;
// Check for local react-native.
try {
require.resolve('react-native');
} catch (err) {
throw new Error('Could not find react-native. Try `npm install react-native`.');
}
// Construct resource URLs up-front
this.webpackBaseURL = url.format({
protocol: 'http',
hostname: this.hostname,
port: this.webpackPort,
});
this.packagerBaseURL = url.format({
protocol: 'http',
hostname: this.hostname,
port: this.packagerPort,
});
}
start() {
// Create a stub entry module for the RN packager.
///Users/baidu/projects/react-native-webpack-server/Examples/BabelES6/node_modules/react-native-webpack-server/_entry
this.entryDir = path.resolve(__dirname, '../packager/entry');
//return this._writeEntryFiles().then(() => {
// Re-throw error if server fails to handle a promise rejection
process.on('unhandledRejection', reason => {
throw reason;
});
// Make sure to clean up when the process is terminated.
process.on('exit', () => this.handleProcessExit());
process.on('SIGINT', () => {
this.handleProcessExit();
process.exit(1);
});
// Construct a promise waiting for both servers to fully start...
const readyPromise = this._startWebpackDevServer().then(() =>
// We need to start this one second to prevent races between the bundlers.
this._startPackageServer()
);
// Setup the express server
this.server = express();
this.server.use((req, res, next) => {
// Wait until packager has started before serving requests
readyPromise
.then(() => next())
.catch(err => next(err));
});
this.server.get('/*.bundle', this.handleBundleRequest.bind(this));
this.server.get('/*.map', this.handleMapRequest.bind(this));
this.server.use((err, req, res, next) => {
console.error(err.stack);
next(err);
});
const listenPromise = new Promise(resolve => {
this.httpServer = this.server.listen(this.port, () => {
console.log(`Server listening at http://${this.hostname}:${this.port}`);
resolve();
});
// Disable any kind of automatic timeout behavior on incoming connections.
this.httpServer.timeout = 0;
});
// if exists outer router ,we just use it
if (this.serverRouter && fs.existsSync(this.serverRouter)) {
require(this.serverRouter)(this);
}
return Promise.all([listenPromise, readyPromise]);
//});
}
stop() {
this.handleProcessExit();
this.httpServer && this.httpServer.close();
this.webpackServer && this.webpackServer.close();
}
handleBundleRequest(req, res, next) {
const parsedUrl = url.parse(req.url, /* parse query */ true);
const urlSearch = parsedUrl.search;
const platform = parsedUrl.query.platform;
// Forward URL params to RN packager
const reactCodeURL = this._getReactCodeURL(platform) + urlSearch;
const appCodeURL = this._getAppCodeURL(platform);
//console.log(reactCodeURL,' ' ,appCodeURL);
//reactCodeURL: http://localhost:8081/index.ios.bundle?platform=ios&dev=false&minify=false
//appCodeURL: http://localhost:8082/index.ios.js
Promise.props({
reactCode: fetch(reactCodeURL),
appCode: fetch(appCodeURL),
}).then(r =>
this._createBundleCode(r.reactCode, r.appCode, urlSearch, platform)
).then(bundleCode => {
res.set('Content-Type', 'application/javascript');
res.send(bundleCode);
}).catch(err => next(err));
}
handleMapRequest(req, res, next) {
const parsedUrl = url.parse(req.url, /* parse query */ true);
const urlSearch = parsedUrl.search;
const platform = parsedUrl.query.platform;
// Forward URL params to RN packager
const reactCodeURL = this._getReactCodeURL(platform) + urlSearch;
const reactMapURL = this._getReactMapURL(platform) + urlSearch;
const appCodeURL = this._getAppCodeURL(platform);
const appMapURL = this._getAppMapURL(platform);
Promise.props({
reactCode: fetch(reactCodeURL),
reactMap: fetch(reactMapURL),
appCode: fetch(appCodeURL),
appMap: fetch(appMapURL),
}).then(r =>
this._createBundleMap(r.reactCode, r.reactMap, r.appCode, r.appMap)
).then(bundleMap => {
res.set('Content-Type', 'application/json');
res.send(bundleMap);
}).catch(err => next(err));
}
handleProcessExit() {
// Clean up temp files
const entryDir = this.entryDir;
if (fs.existsSync(entryDir)) {
fs.readdirSync(entryDir).forEach(file => {
fs.unlinkSync(path.join(entryDir, file));
});
fs.rmdirSync(entryDir);
}
// Kill the package server
if (this.packageServer) {
this.packageServer.kill();
}
}
_getReactCodeURL(platform) {
return url.resolve(this.packagerBaseURL, `index.${platform}.bundle`);
}
_getReactMapURL(platform) {
return url.resolve(this.packagerBaseURL, `index.${platform}.map`);
}
_getAppCodeURL(platform) {
return url.resolve(this.webpackBaseURL, `${this.entries[platform]}.js`);
}
_getAppMapURL(platform) {
return url.resolve(this.webpackBaseURL, `${this.entries[platform]}.js.map`);
}
_createBundleCode(reactCode, appCode, urlSearch, platform) {
reactCode = reactCode.replace(SOURCEMAP_REGEX, '');
appCode = appCode.replace(SOURCEMAP_REGEX, '');
return reactCode + appCode + `//# sourceMappingURL=/${this.entries[platform]}.map${urlSearch}`;
}
_createBundleMap(reactCode, reactMap, appCode, appMap) {
const node = new SourceNode();
node.add(SourceNode.fromStringWithSourceMap(
reactCode,
new SourceMapConsumer(reactMap)
));
node.add(SourceNode.fromStringWithSourceMap(
appCode,
new SourceMapConsumer(appMap)
));
return node.join('').toStringWithSourceMap().map.toString();
}
_writeEntryFiles() {
const source = ENTRY_JS + '\n';
return mkdirp.mkdirpAsync(this.entryDir).then(() => Promise.all([
fs.writeFileAsync(path.resolve(this.entryDir, 'index.android.js'), source, 'utf8'),
fs.writeFileAsync(path.resolve(this.entryDir, 'index.ios.js'), source, 'utf8'),
]));
}
_startPackageServer() {
/**
* Starting the server is neither fast nor completely reliable we end up
* hitting its public api over http periodically so we must wait for it to
* be actually ready.
*/
return new Promise((resolve, reject) => {
// Easier to just shell out to the packager than use the JS API.
// XXX: Uses the node only invocation so we don't have to deal with bash
// as well... Fixes issues where server cannot be killed cleanly.
const cmd = 'node';
const reactNativeVersion = require('react-native/package.json').version;
const script =
semver.lt(reactNativeVersion, '0.14.0')
? ['./node_modules/react-native/packager/packager.js']
: ['./node_modules/react-native/local-cli/cli.js', 'start'];
const args = script.concat([
'--root', this.entryDir,
'--port', this.packagerPort,
]).concat(
this.projectRoots ? ['--projectRoots', this.projectRoots.join(',')] : []
).concat(
this.assetRoots ? ['--assetRoots', this.assetRoots.join(',')] : []
).concat(
this.resetCache ? '--reset-cache' : []
);
const opts = {stdio: 'inherit'};
this.packageServer = spawn(cmd, args, opts);
function handleError(err) {
reject(err);
}
this.packageServer.on('error', handleError);
// waitForSocket retries the port every 250ms. Let's give the
// React Native server up to 30 seconds to come online. watchman
// can be slow to ramp up, especially on CI machines.
waitForSocket({ port: this.packagerPort, tries: 120 }, err => {
console.log('react-native packager ready...');
this.packageServer.removeListener('error', handleError);
if (err) {
handleError(err);
return;
}
resolve();
});
});
}
_startWebpackDevServer() {
const webpackConfig = this.webpackConfig;
const hot = this.hot;
return this.makerExt.start().then((reactNativeExternals)=>{
// Coerce externals into an array, without clobbering it
webpackConfig.externals = Array.isArray(webpackConfig.externals)
? webpackConfig.externals
: [(webpackConfig.externals || {})];
// Inject react native externals
webpackConfig.externals.push(reactNativeExternals);
// Transform static image references
webpackConfig.externals.push(staticImageTransform);
// By default webpack uses webpack://[resource-path]?[hash] in the source
// map which is handled by its dev server. Use absolute path instead so
// React Native's exception manager can load the source maps.
webpackConfig.output = webpackConfig.output || {};
if (!webpackConfig.output.devtoolModuleFilenameTemplate) {
webpackConfig.output.devtoolModuleFilenameTemplate = '[absolute-resource-path]';
}
// Update webpack config for hot mode.
if (hot) {
makeHotConfig(webpackConfig);
}
// Plug into webpack compilation to extract webpack dependency tree.
// Any React Native externals from the application source need to be
// require()'d in the RN packager's entry file. This allows for RN
// modules that aren't part of the main 'react-native' dependency tree
// to be included in the generated bundle (e.g. AdSupportIOS).
const compiler = webpack(webpackConfig);
const compilerPromise = new Promise(resolve => {
compiler.plugin('done', () => {
// Write out the RN packager's entry file
this._writeEntryFiles().then(resolve);
});
});
this.webpackServer = new WebpackDevServer(compiler, {
hot: hot,
headers: {
'Access-Control-Allow-Origin': '*',
},
stats: {colors: true, chunkModules: false},
});
const serverPromise = new Promise(resolve => {
this.webpackServer.listen(this.webpackPort, this.hostname, () => {
console.log('Webpack dev server listening at ', this.webpackBaseURL);
resolve();
});
// Disable any kind of automatic timeout behavior on incoming connections.
this.webpackServer.timeout = 0;
});
// Ensure that both the server is up and the compiler's entry
// file has been written for the React Native packager.
return Promise.all([compilerPromise, serverPromise]);
});
}
}
module.exports = Server;
|
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2016 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.m.ViewSettingsDialog.
sap.ui.define(['jquery.sap.global', './library', 'sap/ui/core/Control', 'sap/ui/core/IconPool', './Toolbar', './CheckBox', './SearchField'],
function(jQuery, library, Control, IconPool, Toolbar, CheckBox, SearchField) {
"use strict";
/**
* Constructor for a new ViewSettingsDialog.
*
* @param {string} [sId] ID for the new control, generated automatically if no ID is given
* @param {object} [mSettings] Initial settings for the new control
*
* @class
* The ViewSettingsDialog control provides functionality to easily select the options for sorting, grouping, and filtering data. It is a composite control, consisting of a modal popover and several internal lists. There are three different tabs (Sort, Group, Filter) in the dialog that can be activated by filling the respective associations. If only one association is filled, the other tabs are automatically hidden. The selected options can be used to create sorters and filters for the table.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.36.5
*
* @constructor
* @public
* @since 1.16
* @alias sap.m.ViewSettingsDialog
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var ViewSettingsDialog = Control.extend("sap.m.ViewSettingsDialog", /** @lends sap.m.ViewSettingsDialog.prototype */ { metadata : {
library : "sap.m",
properties : {
/**
* Defines the title of the dialog. If not set and there is only one active tab, the dialog uses the default "View" or "Sort", "Group", "Filter" respectively.
*/
title : {type : "string", group : "Behavior", defaultValue : null},
/**
* Determines whether the sort order is descending or ascending (default).
*/
sortDescending : {type : "boolean", group : "Behavior", defaultValue : false},
/**
* Determines whether the group order is descending or ascending (default).
*/
groupDescending : {type : "boolean", group : "Behavior", defaultValue : false}
},
aggregations : {
/**
* The list of items with key and value that can be sorted over (for example, a list of columns for a table).
* @since 1.16
*/
sortItems : {type : "sap.m.ViewSettingsItem", multiple : true, singularName : "sortItem", bindable : "bindable"},
/**
* The list of items with key and value that can be grouped on (for example, a list of columns for a table).
* @since 1.16
*/
groupItems : {type : "sap.m.ViewSettingsItem", multiple : true, singularName : "groupItem", bindable : "bindable"},
/**
* The list of items with key and value that can be filtered on (for example, a list of columns for a table). A filterItem is associated with one or more detail filters.
* @since 1.16
*/
filterItems : {type : "sap.m.ViewSettingsItem", multiple : true, singularName : "filterItem", bindable : "bindable"},
/**
* The list of preset filter items that allows the selection of more complex or custom filters. These entries are displayed at the top of the filter tab.
* @since 1.16
*/
presetFilterItems : {type : "sap.m.ViewSettingsItem", multiple : true, singularName : "presetFilterItem", bindable : "bindable"},
/**
* The list of all the custom tabs.
* @since 1.30
*/
customTabs: {type: "sap.m.ViewSettingsCustomTab", multiple: true, singularName: "customTab", bindable : "bindable"}
},
associations : {
/**
* The sort item that is selected. It can be set by either passing a key or the item itself to the function setSelectedSortItem.
*/
selectedSortItem : {type : "sap.m.ViewSettingsItem", multiple : false},
/**
* The group item that is selected. It can be set by either passing a key or the item itself to the function setSelectedGroupItem.
*/
selectedGroupItem : {type : "sap.m.ViewSettingsItem", multiple : false},
/**
* The preset filter item that is selected. It can be set by either passing a key or the item itself to the function setSelectedPresetFilterItem. Note that either a preset filter OR multiple detail filters can be active at the same time.
*/
selectedPresetFilterItem : {type : "sap.m.ViewSettingsItem", multiple : false}
},
events : {
/**
* Indicates that the user has pressed the OK button and the selected sort, group, and filter settings should be applied to the data on this page.
* </br></br><b>Note:</b> Custom tabs are not converted to event parameters automatically. For custom tabs, you have to read the state of your controls inside the callback of this event.
*/
confirm : {
parameters : {
/**
* The selected sort item.
*/
sortItem : {type : "sap.m.ViewSettingsItem"},
/**
* The selected sort order (true = descending, false = ascending).
*/
sortDescending : {type : "boolean"},
/**
* The selected group item.
*/
groupItem : {type : "sap.m.ViewSettingsItem"},
/**
* The selected group order (true = descending, false = ascending).
*/
groupDescending : {type : "boolean"},
/**
* The selected preset filter item.
*/
presetFilterItem : {type : "sap.m.ViewSettingsItem"},
/**
* The selected filters in an array of ViewSettingsItem.
*/
filterItems : {type : "sap.m.ViewSettingsItem[]"},
/**
* The selected filter items in an object notation format: { key: boolean }. If a custom control filter was displayed (for example, the user clicked on the filter item), the value for its key is set to true to indicate that there has been an interaction with the control.
*/
filterKeys : {type : "object"},
/**
* The selected filter items in a string format to display in the control's header bar in format "Filtered by: key (subkey1, subkey2, subkey3)".
*/
filterString : {type : "string"}
}
},
/**
* Called when the Cancel button is pressed. It can be used to set the state of custom filter controls.
*/
cancel : {},
/**
* Called when the reset filters button is pressed. It can be used to clear the state of custom filter controls.
*/
resetFilters : {}
}
}});
/* =========================================================== */
/* begin: API methods */
/* =========================================================== */
ViewSettingsDialog.prototype.init = function() {
this._rb = sap.ui.getCore().getLibraryResourceBundle("sap.m");
this._sDialogWidth = "350px";
this._sDialogHeight = "434px";
/* this control does not have a
renderer, so we need to take care of
adding it to the ui tree manually */
this._bAppendedToUIArea = false;
this._showSubHeader = false;
this._filterDetailList = undefined;
this._vContentPage = -1;
this._oContentItem = null;
this._oPreviousState = {};
this._sCustomTabsButtonsIdPrefix = '-custom-button-';
};
ViewSettingsDialog.prototype.exit = function() {
// helper variables
this._rb = null;
this._sDialogWidth = null;
this._sDialogHeight = null;
this._bAppendedToUIArea = null;
this._showSubHeader = null;
this._vContentPage = null;
this._oContentItem = null;
this._oPreviousState = null;
this._sortContent = null;
this._groupContent = null;
this._filterContent = null;
this._sCustomTabsButtonsIdPrefix = null;
// sap.ui.core.Popup removes its content on close()/destroy() automatically from the static UIArea,
// but only if it added it there itself. As we did that, we have to remove it also on our own
if ( this._bAppendedToUIArea ) {
var oStatic = sap.ui.getCore().getStaticAreaRef();
oStatic = sap.ui.getCore().getUIArea(oStatic);
oStatic.removeContent(this, true);
}
// controls that are internally managed and may or may not be assigned to an
// aggregation (have to be destroyed manually to be sure)
// dialog
if (this._dialog) {
this._dialog.destroy();
this._dialog = null;
}
if (this._navContainer) {
this._navContainer.destroy();
this._navContainer = null;
}
if (this._titleLabel) {
this._titleLabel.destroy();
this._titleLabel = null;
}
// page1 (sort/group/filter)
if (this._page1) {
this._page1.destroy();
this._page1 = null;
}
if (this._header) {
this._header.destroy();
this._header = null;
}
if (this._resetButton) {
this._resetButton.destroy();
this._resetButton = null;
}
if (this._subHeader) {
this._subHeader.destroy();
this._subHeader = null;
}
if (this._segmentedButton) {
this._segmentedButton.destroy();
this._segmentedButton = null;
}
if (this._sortButton) {
this._sortButton.destroy();
this._sortButton = null;
}
if (this._groupButton) {
this._groupButton.destroy();
this._groupButton = null;
}
if (this._filterButton) {
this._filterButton.destroy();
this._filterButton = null;
}
if (this._sortList) {
this._sortList.destroy();
this._sortList = null;
this._ariaSortListInvisibleText.destroy();
this._ariaSortListInvisibleText = null;
}
if (this._sortOrderList) {
this._sortOrderList.destroy();
this._sortOrderList = null;
this._ariaSortOrderInvisibleText.destroy();
this._ariaSortOrderInvisibleText = null;
}
if (this._oGroupingNoneItem) {
this._oGroupingNoneItem.destroy();
this._oGroupingNoneItem = null;
}
if (this._groupList) {
this._groupList.destroy();
this._groupList = null;
this._ariaGroupListInvisibleText.destroy();
this._ariaGroupListInvisibleText = null;
}
if (this._groupOrderList) {
this._groupOrderList.destroy();
this._groupOrderList = null;
this._ariaGroupOrderInvisibleText.destroy();
this._ariaGroupOrderInvisibleText = null;
}
if (this._presetFilterList) {
this._presetFilterList.destroy();
this._presetFilterList = null;
}
if (this._filterList) {
this._filterList.destroy();
this._filterList = null;
}
// page2 (filter details)
if (this._page2) {
this._page2.destroy();
this._page2 = null;
}
if (this._detailTitleLabel) {
this._detailTitleLabel.destroy();
this._detailTitleLabel = null;
}
if (this._filterDetailList) {
this._filterDetailList.destroy();
this._filterDetailList = null;
}
};
/**
* Overwrites the aggregation setter in order to have ID validation logic as some strings
* are reserved for the predefined tabs.
*
* @overwrite
* @public
* @param {object} oCustomTab The custom tab to be added
* @returns {sap.m.ViewSettingsDialog} this pointer for chaining
*/
ViewSettingsDialog.prototype.addCustomTab = function (oCustomTab) {
var sId = oCustomTab.getId();
if (sId === 'sort' || sId === 'filter' || sId === 'group') {
throw 'Id "' + sId + '" is reserved and cannot be used as custom tab id.';
}
this.addAggregation('customTabs', oCustomTab);
return this;
};
/**
* Invalidates the control (suppressed as there is no renderer).
* @overwrite
* @public
*/
ViewSettingsDialog.prototype.invalidate = function() {
// CSN #80686/2014: only invalidate inner dialog if call does not come from inside
if (this._dialog && (!arguments[0] || arguments[0] && arguments[0].getId() !== this.getId() + "-dialog")) {
this._dialog.invalidate(arguments);
} else {
Control.prototype.invalidate.apply(this, arguments);
}
};
/**
* Forward method to the inner dialog method: addStyleClass.
* @public
* @override
* @returns {sap.m.ViewSettingsDialog} this pointer for chaining
*/
ViewSettingsDialog.prototype.addStyleClass = function () {
var oDialog = this._getDialog();
oDialog.addStyleClass.apply(oDialog, arguments);
return this;
};
/**
* Forward method to the inner dialog method: removeStyleClass.
* @public
* @override
* @returns {sap.m.ViewSettingsDialog} this pointer for chaining
*/
ViewSettingsDialog.prototype.removeStyleClass = function () {
var oDialog = this._getDialog();
oDialog.removeStyleClass.apply(oDialog, arguments);
return this;
};
/**
* Forward method to the inner dialog method: toggleStyleClass.
* @public
* @override
* @returns {sap.m.ViewSettingsDialog} this pointer for chaining
*/
ViewSettingsDialog.prototype.toggleStyleClass = function () {
var oDialog = this._getDialog();
oDialog.toggleStyleClass.apply(oDialog, arguments);
return this;
};
/**
* Forward method to the inner dialog method: hasStyleClass.
* @public
* @override
* @returns {boolean} true if the class is set, false otherwise
*/
ViewSettingsDialog.prototype.hasStyleClass = function () {
var oDialog = this._getDialog();
return oDialog.hasStyleClass.apply(oDialog, arguments);
};
/**
* Forward method to the inner dialog method: getDomRef.
* @public
* @override
* @return {Element} The Element's DOM Element sub DOM Element or null
*/
ViewSettingsDialog.prototype.getDomRef = function () {
// this is also called on destroy to remove the DOM element, therefore we directly check the reference instead of the internal getter
if (this._dialog) {
return this._dialog.getDomRef.apply(this._dialog, arguments);
} else {
return null;
}
};
/**
* Sets the title of the internal dialog.
*
* @overwrite
* @public
* @param {string} sTitle The title text for the dialog
* @return {sap.m.ViewSettingsDialog} this pointer for chaining
*/
ViewSettingsDialog.prototype.setTitle = function(sTitle) {
this._getTitleLabel().setText(sTitle);
this.setProperty("title", sTitle, true);
return this;
};
/**
* Override the method in order to attach an event handler responsible for propagating item property changes.
* @override
* @param {string} sAggregationName Name of the added aggregation
* @param {object} oObject Intance that is going to be added
* @param {boolean} bSuppressInvalidate Flag indicating whether invalidation should be supressed
* @returns {object} This instance for chaining
*/
ViewSettingsDialog.prototype.addAggregation = function (sAggregationName, oObject, bSuppressInvalidate) {
sap.ui.base.ManagedObject.prototype.addAggregation.apply(this, arguments);
// perform the following logic only for the items aggregations, except custom tabs
if (sAggregationName !== 'sortItems' && sAggregationName !== 'groupItems' && sAggregationName !== 'filterItems') {
return this;
}
var sType = sAggregationName.replace('Items', ''); // extract "filter"/"group"/"sort"
sType = sType.charAt(0).toUpperCase() + sType.slice(1); // capitalize
// Attach 'itemPropertyChaged' handler, that will re-initiate (specific) dialog content
oObject.attachEvent('itemPropertyChanged', function (sAggregationName, oEvent) {
/* If the the changed item was a 'sap.m.ViewSettingsItem'
* then threat it differently as filter detail item.
* */
if (sAggregationName === 'filterItems' &&
oEvent.getParameter('changedItem').getMetadata().getName() === 'sap.m.ViewSettingsItem') {
// handle the select differently
if (oEvent.getParameter('propertyKey') !== 'selected') {
// if on filter details page for a concrete filter item
if (this._vContentPage === 3 && this._oContentItem) {
this._setFilterDetailTitle(this._oContentItem);
this._initFilterDetailItems(this._oContentItem);
}
} else {
// Change only the "select" property on the concrete item (instead calling _initFilterDetailItems() all over) to avoid re-rendering
// ToDo: make this optimization for all properties
if (this._filterDetailList) {
var aItems = this._filterDetailList.getItems();
aItems.forEach(function (oItem) {
if (oItem.data('item').getId() === oEvent.getParameter('changedItem').getId()) {
oItem.setSelected(oEvent.getParameter('propertyValue'));
}
});
this._updateSelectAllCheckBoxState();
}
}
} else {
// call _initFilterContent and _initFilterItems methods, where "Filter" might be also "Group" or "Sort"
if (typeof this['_init' + sType + 'Content'] === 'function') {
this['_init' + sType + 'Content']();
}
if (typeof this['_init' + sType + 'Items'] === 'function') {
this['_init' + sType + 'Items']();
}
}
}.bind(this, sAggregationName));
// Attach 'filterDetailItemsAggregationChange' handler, that will re-initiate (specific) dialog content
oObject.attachEvent('filterDetailItemsAggregationChange', function (oEvent) {
if (this._vContentPage === 3 && this._oContentItem) {
this._setFilterDetailTitle(this._oContentItem);
this._initFilterDetailItems(this._oContentItem);
}
}.bind(this));
};
/**
* Set header title for the filter detail page.
* @param {object} oItem Item that will serve as a title
* @private
*/
ViewSettingsDialog.prototype._setFilterDetailTitle = function (oItem) {
this._getDetailTitleLabel().setText(
this._rb.getText("VIEWSETTINGS_TITLE_FILTERBY") + " "
+ oItem.getText());
};
/**
* Take care to update the internal instances when any of the corresponding aggregation is being updated.
*
* @override
* @param {string} sAggregationName Name of the updated aggregation
* @returns {ViewSettingsDialog} this instance for chaining
*/
ViewSettingsDialog.prototype.updateAggregation = function (sAggregationName) {
sap.ui.base.ManagedObject.prototype.updateAggregation.apply(this, arguments);
// perform the following logic only for the items aggregations, except custom tabs
if (sAggregationName !== 'sortItems' && sAggregationName !== 'groupItems' && sAggregationName !== 'filterItems') {
return this;
}
var sType = sAggregationName.replace('Items', ''); // extract "filter"/"group"/"sort"
sType = sType.charAt(0).toUpperCase() + sType.slice(1); // capitalize
// call _initFilterContent and _initFilterItems methods, where "Filter" might be also "Group" or "Sort"
if (typeof this['_init' + sType + 'Content'] === 'function') {
this['_init' + sType + 'Content']();
}
if (typeof this['_init' + sType + 'Items'] === 'function') {
this['_init' + sType + 'Items']();
}
};
/**
* Adds a sort item and sets the association to reflect the selected state.
*
* @overwrite
* @public
* @param {sap.m.ViewSettingsItem} oItem The item to be added to the aggregation
* @return {sap.m.ViewSettingsDialog} this pointer for chaining
*/
ViewSettingsDialog.prototype.addSortItem = function(oItem) {
this.addAggregation("sortItems", oItem);
if (oItem.getSelected()) {
this.setSelectedSortItem(oItem);
}
return this;
};
/**
* Adds a group item and sets the association to reflect the selected state.
*
* @overwrite
* @public
* @param {sap.m.ViewSettingsItem} oItem The item to be added to the group items
* @return {sap.m.ViewSettingsDialog} this pointer for chaining
*/
ViewSettingsDialog.prototype.addGroupItem = function(oItem) {
this.addAggregation("groupItems", oItem);
if (oItem.getSelected()) {
this.setSelectedGroupItem(oItem);
}
return this;
};
/**
* Adds a preset filter item and sets the association to reflect the selected state.
*
* @overwrite
* @public
* @param {sap.m.ViewSettingsItem} oItem The selected item or a string with the key
* @return {sap.m.ViewSettingsDialog} this pointer for chaining
*/
ViewSettingsDialog.prototype.addPresetFilterItem = function(oItem) {
this.addAggregation("presetFilterItems", oItem);
if (oItem.getSelected()) {
this.setSelectedPresetFilterItem(oItem);
}
return this;
};
/**
* Sets the selected sort item (either by key or by item).
*
* @overwrite
* @public
* @param {sap.m.ViewSettingsItem|string} vItemOrKey The selected item or the item's key string
* @return {sap.m.ViewSettingsDialog} this pointer for chaining
*/
ViewSettingsDialog.prototype.setSelectedSortItem = function(vItemOrKey) {
var aItems = this.getSortItems(),
i = 0,
oItem = findViewSettingsItemByKey(
vItemOrKey,
aItems,
"Could not set selected sort item. Item is not found: '" + vItemOrKey + "'"
);
//change selected item only if it is found among the sort items
if (validateViewSettingsItem(oItem)) {
// set selected = true for this item & selected = false for all others items
for (i = 0; i < aItems.length; i++) {
if (aItems[i].getId() !== oItem.getId()) {
aItems[i].setProperty('selected', false, true);
}
}
if (oItem.getProperty('selected') !== true) {
oItem.setProperty('selected', true, true);
}
// update the list selection
if (this._getDialog().isOpen()) {
this._updateListSelection(this._sortList, oItem);
}
this.setAssociation("selectedSortItem", oItem, true);
}
return this;
};
/**
* Sets the selected group item (either by key or by item).
*
* @overwrite
* @public
* @param {sap.m.ViewSettingsItem|string} vItemOrKey The selected item or the item's key string
* @return {sap.m.ViewSettingsDialog} this pointer for chaining
*/
ViewSettingsDialog.prototype.setSelectedGroupItem = function(vItemOrKey) {
var aItems = this.getGroupItems(),
i = 0,
oItem = findViewSettingsItemByKey(
vItemOrKey,
aItems,
"Could not set selected group item. Item is not found: '" + vItemOrKey + "'"
);
//change selected item only if it is found among the group items
if (validateViewSettingsItem(oItem)) {
// set selected = true for this item & selected = false for all others items
for (i = 0; i < aItems.length; i++) {
aItems[i].setProperty('selected', false, true);
}
oItem.setProperty('selected', true, true);
// update the list selection
if (this._getDialog().isOpen()) {
this._updateListSelection(this._groupList, oItem);
}
this.setAssociation("selectedGroupItem", oItem, true);
}
return this;
};
/**
* Sets the selected preset filter item.
*
* @overwrite
* @public
* @param {sap.m.ViewSettingsItem|string} vItemOrKey The selected item or the item's key string
* @return {sap.m.ViewSettingsDialog} this pointer for chaining
*/
ViewSettingsDialog.prototype.setSelectedPresetFilterItem = function(vItemOrKey) {
var aItems = this.getPresetFilterItems(),
i = 0,
oItem = findViewSettingsItemByKey(
vItemOrKey,
aItems,
"Could not set selected preset filter item. Item is not found: '" + vItemOrKey + "'"
);
//change selected item only if it is found among the preset filter items
if (validateViewSettingsItem(oItem)) {
// set selected = true for this item & selected = false for all others items
for (i = 0; i < aItems.length; i++) {
aItems[i].setProperty('selected', false, true);
}
oItem.setProperty('selected', true, true);
// clear filters (only one mode is allowed, preset filters or filters)
this._clearSelectedFilters();
this.setAssociation("selectedPresetFilterItem", oItem, true);
}
return this;
};
/**
* Opens the ViewSettingsDialog relative to the parent control.
*
* @public
* @param {string} [sPageId] The ID of the initial page to be opened in the dialog.
* The available values are "sort", "group", "filter" or IDs of custom tabs.
*
* @return {sap.m.ViewSettingsDialog} this pointer for chaining
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
ViewSettingsDialog.prototype.open = function(sPageId) {
// add to static UI area manually because we don't have a renderer
if (!this.getParent() && !this._bAppendedToUIArea) {
var oStatic = sap.ui.getCore().getStaticAreaRef();
oStatic = sap.ui.getCore().getUIArea(oStatic);
oStatic.addContent(this, true);
this._bAppendedToUIArea = true;
}
// if there is a default tab and the user has been at filter details view on page2, go back to page1
if (sPageId && this._vContentPage === 3) {
jQuery.sap.delayedCall(0, this._getNavContainer(), "to", [
this._getPage1().getId(), "show" ]);
}
// init the dialog content based on the aggregations
this._initDialogContent(sPageId);
// store the current dialog state to be able to reset it on cancel
this._oPreviousState = {
sortItem : sap.ui.getCore().byId(this.getSelectedSortItem()),
sortDescending : this.getSortDescending(),
groupItem : sap.ui.getCore().byId(this.getSelectedGroupItem()),
groupDescending : this.getGroupDescending(),
presetFilterItem : sap.ui.getCore().byId(
this.getSelectedPresetFilterItem()),
filterKeys : this.getSelectedFilterKeys(),
navPage : this._getNavContainer().getCurrentPage(),
contentPage : this._vContentPage,
contentItem : this._oContentItem
};
//focus the first focusable item in current page's content
if (sap.ui.Device.system.desktop) {
this._getDialog().attachEventOnce("afterOpen", function () {
var oCurrentPage = this._getNavContainer().getCurrentPage(),
$firstFocusable;
if (oCurrentPage) {
$firstFocusable = oCurrentPage.$("cont").firstFocusableDomRef();
if ($firstFocusable) {
if (jQuery($firstFocusable).hasClass('sapMListUl')) {
var $aListItems = jQuery($firstFocusable).find('.sapMLIB');
$aListItems.length && $aListItems[0].focus();
return;
}
$firstFocusable.focus();
}
}
}, this);
}
// open dialog
this._getDialog().open();
return this;
};
/**
* Returns the selected filters as an array of ViewSettingsItems.
*
* It can be used to create matching sorters and filters to apply the selected settings to the data.
* @overwrite
* @public
* @return {sap.m.ViewSettingsItem[]} An array of selected filter items
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
ViewSettingsDialog.prototype.getSelectedFilterItems = function() {
var aSelectedFilterItems = [], aFilterItems = this.getFilterItems(), aSubFilterItems, bMultiSelect = true, i = 0, j;
for (; i < aFilterItems.length; i++) {
if (aFilterItems[i] instanceof sap.m.ViewSettingsCustomItem) {
if (aFilterItems[i].getSelected()) {
aSelectedFilterItems.push(aFilterItems[i]);
}
} else if (aFilterItems[i] instanceof sap.m.ViewSettingsFilterItem) {
aSubFilterItems = aFilterItems[i].getItems();
bMultiSelect = aFilterItems[i].getMultiSelect();
for (j = 0; j < aSubFilterItems.length; j++) {
if (aSubFilterItems[j].getSelected()) {
aSelectedFilterItems.push(aSubFilterItems[j]);
if (!bMultiSelect) {
break; // only first item is added to the selection on
// single select items
}
}
}
}
}
return aSelectedFilterItems;
};
/**
* Gets the filter string in format: "filter name (subfilter1 name, subfilter2
* name, ...), ...".
* For custom and preset filters it will only add the filter name to the resulting string.
*
* @public
* @return {string} The selected filter string
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
ViewSettingsDialog.prototype.getSelectedFilterString = function() {
var sFilterString = "",
sSubfilterString,
oPresetFilterItem = this.getSelectedPresetFilterItem(),
aFilterItems = this.getFilterItems(),
aSubFilterItems,
bMultiSelect = true,
i = 0,
j;
if (oPresetFilterItem) {
// preset filter: add "filter name"
sFilterString = this._rb.getText("VIEWSETTINGS_FILTERTEXT").concat(" " + sap.ui.getCore().byId(oPresetFilterItem).getText());
} else { // standard & custom filters
for (; i < aFilterItems.length; i++) {
if (aFilterItems[i] instanceof sap.m.ViewSettingsCustomItem) {
// custom filter: add "filter name,"
if (aFilterItems[i].getSelected()) {
sFilterString += aFilterItems[i].getText() + ", ";
}
} else if (aFilterItems[i] instanceof sap.m.ViewSettingsFilterItem) {
// standard filter: add "filter name (sub filter 1 name, sub
// filter 2 name, ...), "
aSubFilterItems = aFilterItems[i].getItems();
bMultiSelect = aFilterItems[i].getMultiSelect();
sSubfilterString = "";
for (j = 0; j < aSubFilterItems.length; j++) {
if (aSubFilterItems[j].getSelected()) {
sSubfilterString += aSubFilterItems[j].getText() + ", ";
if (!bMultiSelect) {
break; // only first item is added to the selection
// on single select items
}
}
}
// remove last comma
sSubfilterString = sSubfilterString.substring(0,
sSubfilterString.length - 2);
// add surrounding brackets and comma
if (sSubfilterString) {
sSubfilterString = " (" + sSubfilterString + ")";
sFilterString += aFilterItems[i].getText()
+ sSubfilterString + ", ";
}
}
}
// remove last comma
sFilterString = sFilterString.substring(0, sFilterString.length - 2);
// add "Filtered by: " text
if (sFilterString) {
sFilterString = this._rb.getText("VIEWSETTINGS_FILTERTEXT").concat(" " + sFilterString);
}
}
return sFilterString;
};
/**
* Gets the selected filter object in format {key: boolean}.
*
* It can be used to create matching sorters and filters to apply the selected settings to the data.
*
* @public
* @return {object} An object with item and subitem keys
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
ViewSettingsDialog.prototype.getSelectedFilterKeys = function() {
var oSelectedFilterKeys = {}, aSelectedFilterItems = this
.getSelectedFilterItems(), i = 0;
for (; i < aSelectedFilterItems.length; i++) {
oSelectedFilterKeys[aSelectedFilterItems[i].getKey()] = aSelectedFilterItems[i]
.getSelected();
}
return oSelectedFilterKeys;
};
/**
* Sets the selected filter object in format {key: boolean}.
*
* @public
* @param {object} oSelectedFilterKeys
* A configuration object with filter item and sub item keys in the format: { key: boolean }.
* Setting boolean to true will set the filter to true, false or omitting an entry will set the filter to false.
* It can be used to set the dialog state based on presets.
* @return {sap.m.ViewSettingsDialog} this pointer for chaining
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
ViewSettingsDialog.prototype.setSelectedFilterKeys = function(oSelectedFilterKeys) {
var sKey = "",
aFilterItems = this.getFilterItems(),
aSubFilterItems = {},
oFilterItem,
bMultiSelect,
i,
j,
k;
// clear preset filters (only one mode is allowed, preset filters or
// filters)
if (Object.keys(oSelectedFilterKeys).length) {
this._clearPresetFilter();
}
// loop through the provided object array {key -> subKey -> boolean}
for (sKey in oSelectedFilterKeys) { // filter key
oFilterItem = null;
if (oSelectedFilterKeys.hasOwnProperty(sKey)) {
for (i = 0; i < aFilterItems.length; i++) {
if (aFilterItems[i] instanceof sap.m.ViewSettingsCustomItem) {
// just compare the key of this control
if (aFilterItems[i].getKey() === sKey) {
oFilterItem = aFilterItems[i];
aFilterItems[i].setProperty('selected', oSelectedFilterKeys[sKey], true);
}
} else if (aFilterItems[i] instanceof sap.m.ViewSettingsFilterItem) {
// find the sub filter item with the specified key
aSubFilterItems = aFilterItems[i].getItems();
bMultiSelect = aFilterItems[i].getMultiSelect();
for (j = 0; j < aSubFilterItems.length; j++) {
if (aSubFilterItems[j].getKey() === sKey) {
oFilterItem = aSubFilterItems[j];
// set all other entries to false for single select
// entries
if (!bMultiSelect) {
for (k = 0; k < aSubFilterItems.length; k++) {
aSubFilterItems[k].setProperty('selected', false, true);
}
}
break;
}
}
}
if (oFilterItem) {
break;
}
}
// skip if we don't have an item with this key
if (oFilterItem === null) {
jQuery.sap.log.warning('Cannot set state for key "' + sKey
+ '" because there is no filter with these keys');
continue;
}
// set the the selected state on the item
oFilterItem.setProperty('selected', oSelectedFilterKeys[sKey], true);
}
}
return this;
};
/* =========================================================== */
/* end: API methods */
/* =========================================================== */
/* =========================================================== */
/* begin: internal methods and properties */
/* =========================================================== */
/**
* Lazy initialization of the internal dialog.
* @private
*/
ViewSettingsDialog.prototype._getDialog = function() {
var that = this;
// create an internal instance of a dialog
if (this._dialog === undefined) {
this._dialog = new sap.m.Dialog(this.getId() + "-dialog", {
showHeader : false,
stretch : sap.ui.Device.system.phone,
verticalScrolling : true,
horizontalScrolling : false,
contentWidth : this._sDialogWidth,
contentHeight : this._sDialogHeight,
content : this._getNavContainer(),
beginButton : new sap.m.Button(this.getId() + "-acceptbutton", {
text : this._rb.getText("VIEWSETTINGS_ACCEPT")
}).attachPress(this._onConfirm, this),
endButton : new sap.m.Button(this.getId() + "-cancelbutton", {
text : this._rb.getText("VIEWSETTINGS_CANCEL")
}).attachPress(this._onCancel, this)
}).addStyleClass("sapMVSD");
// CSN# 3696452/2013: ESC key should also cancel dialog, not only close
// it
var fnDialogEscape = this._dialog.onsapescape;
this._dialog.onsapescape = function(oEvent) {
// call original escape function of the dialog
if (fnDialogEscape) {
fnDialogEscape.call(that._dialog, oEvent);
}
// execute cancel action
that._onCancel();
};
// [SHIFT]+[ENTER] triggers the “Back” button of the dialog
this._dialog.onsapentermodifiers = function (oEvent) {
if (oEvent.shiftKey && !oEvent.ctrlKey && !oEvent.altKey ) {
that._pressBackButton();
}
};
}
return this._dialog;
};
/**
* Lazy initialization of the internal nav container.
* @private
*/
ViewSettingsDialog.prototype._getNavContainer = function() {
// create an internal instance of a dialog
if (this._navContainer === undefined) {
this._navContainer = new sap.m.NavContainer(this.getId()
+ '-navcontainer', {
pages : []
});
}
return this._navContainer;
};
/**
* Lazy initialization of the internal title label.
* @private
*/
ViewSettingsDialog.prototype._getTitleLabel = function() {
if (this._titleLabel === undefined) {
this._titleLabel = new sap.m.Label(this.getId() + "-title", {
text : this._rb.getText("VIEWSETTINGS_TITLE")
}).addStyleClass("sapMVSDTitle");
}
return this._titleLabel;
};
/**
* Lazy initialization of the internal reset button.
* @private
*/
ViewSettingsDialog.prototype._getResetButton = function() {
var that = this;
if (this._resetButton === undefined) {
this._resetButton = new sap.m.Button(this.getId() + "-resetbutton", {
icon : IconPool.getIconURI("refresh"),
press : function() {
that._onClearFilters();
},
tooltip : this._rb.getText("VIEWSETTINGS_CLEAR_FILTER_TOOLTIP")
});
}
return this._resetButton;
};
/**
* Lazy initialization of the internal detail title label.
* @private
*/
ViewSettingsDialog.prototype._getDetailTitleLabel = function() {
if (this._detailTitleLabel === undefined) {
this._detailTitleLabel = new sap.m.Label(this.getId() + "-detailtitle",
{
text : this._rb.getText("VIEWSETTINGS_TITLE_FILTERBY")
}).addStyleClass("sapMVSDTitle");
}
return this._detailTitleLabel;
};
/**
* Lazy initialization of the internal header.
* @private
*/
ViewSettingsDialog.prototype._getHeader = function() {
if (this._header === undefined) {
this._header = new sap.m.Bar({
contentMiddle : [ this._getTitleLabel() ]
}).addStyleClass("sapMVSDBar");
}
return this._header;
};
/**
* Lazy initialization of the internal sub header.
* @private
*/
ViewSettingsDialog.prototype._getSubHeader = function() {
if (this._subHeader === undefined) {
this._subHeader = new sap.m.Bar({
contentLeft : [ this._getSegmentedButton() ]
}).addStyleClass("sapMVSDBar");
}
return this._subHeader;
};
/**
* Lazy initialization of the internal segmented button.
* @private
*/
ViewSettingsDialog.prototype._getSegmentedButton = function() {
var that = this,
aCustomTabs = this.getCustomTabs(),
iCustomTabsLength = aCustomTabs.length,
i = 0;
if (this._segmentedButton === undefined) {
this._segmentedButton = new sap.m.SegmentedButton({
select : function(oEvent) {
var selectedId = oEvent.getParameter('id');
if (selectedId === that.getId() + "-sortbutton") {
that._switchToPage(0);
} else if (selectedId === that.getId() + "-groupbutton") {
that._switchToPage(1);
} else if (selectedId === that.getId() + "-filterbutton") {
that._switchToPage(2);
} else {
for (i = 0; i < iCustomTabsLength; i++) {
var oCustomTab = aCustomTabs[i];
if (!that._isEmptyTab(oCustomTab) && selectedId === oCustomTab.getTabButton().getId()) {
that._switchToPage(oCustomTab.getId());
break;
}
}
}
jQuery.sap.log.info('press event segmented: '
+ oEvent.getParameter('id'));
}
}).addStyleClass("sapMVSDSeg");
// workaround to fix flickering caused by css measurement in SegmentedButton. Temporary solution that
// may be removed once VSD current page rendering implementation is changed.
this._segmentedButton._bPreventWidthRecalculationOnAfterRendering = true;
}
return this._segmentedButton;
};
/**
* Lazy initialization of the internal sort button.
* @private
*/
ViewSettingsDialog.prototype._getSortButton = function() {
if (this._sortButton === undefined) {
this._sortButton = new sap.m.Button(this.getId() + "-sortbutton", {
visible : false, // controlled by update state method
icon : IconPool.getIconURI("sort"),
tooltip : this._rb.getText("VIEWSETTINGS_TITLE_SORT")
});
}
return this._sortButton;
};
/**
* Lazy initialization of the internal group button.
* @private
*/
ViewSettingsDialog.prototype._getGroupButton = function() {
if (this._groupButton === undefined) {
this._groupButton = new sap.m.Button(this.getId() + "-groupbutton", {
visible : false, // controlled by update state method
icon : IconPool.getIconURI("group-2"),
tooltip : this._rb.getText("VIEWSETTINGS_TITLE_GROUP")
});
}
return this._groupButton;
};
/**
* Lazy initialization of the internal filter button.
* @private
*/
ViewSettingsDialog.prototype._getFilterButton = function() {
if (this._filterButton === undefined) {
this._filterButton = new sap.m.Button(this.getId() + "-filterbutton", {
visible : false, // controlled by update state method
icon : IconPool.getIconURI("filter"),
tooltip : this._rb.getText("VIEWSETTINGS_TITLE_FILTER")
});
}
return this._filterButton;
};
/**
* Lazy initialization of the internal page1 (sort/group/filter).
* @param {boolean} bSuppressCreation If true, no page will be create in case it doesn't exist.
* @private
*/
ViewSettingsDialog.prototype._getPage1 = function(bSuppressCreation) {
if (this._page1 === undefined && !bSuppressCreation) {
this._page1 = new sap.m.Page(this.getId() + '-page1', {
title : this._rb.getText("VIEWSETTINGS_TITLE"),
customHeader : this._getHeader()
});
this._getNavContainer().addPage(this._page1); // sort, group, filter
}
return this._page1;
};
/**
* Lazy initialization of the internal page2 (detail filters).
* @private
*/
ViewSettingsDialog.prototype._getPage2 = function() {
var that = this, oDetailHeader, oBackButton, oDetailResetButton;
if (this._page2 === undefined) {
// init internal page content
oBackButton = new sap.m.Button(this.getId() + "-backbutton", {
icon : IconPool.getIconURI("nav-back"),
press : [this._pressBackButton, this]
});
oDetailResetButton = new sap.m.Button(this.getId()
+ "-detailresetbutton", {
icon : IconPool.getIconURI("refresh"),
press : function() {
that._onClearFilters();
},
tooltip : this._rb.getText("VIEWSETTINGS_CLEAR_FILTER_TOOLTIP")
});
oDetailHeader = new sap.m.Bar({
contentLeft : [ oBackButton ],
contentMiddle : [ this._getDetailTitleLabel() ],
contentRight : [ oDetailResetButton ]
}).addStyleClass("sapMVSDBar");
this._page2 = new sap.m.Page(this.getId() + '-page2', {
title : this._rb.getText("VIEWSETTINGS_TITLE_FILTERBY"),
customHeader : oDetailHeader
});
this._getNavContainer().addPage(this._page2); // filter details
}
return this._page2;
};
/**
* Create list item instance for each filter detail item.
* @param {object} oItem Filter item instance for which the details should be displayed
* @private
*/
ViewSettingsDialog.prototype._initFilterDetailItems = function(oItem) {
var oListItem;
var bMultiSelectMode = oItem.getMultiSelect();
var aSubFilters = oItem.getItems();
var that = this;
if (this._filterDetailList) { // destroy previous list
this._filterDetailList.destroy();
}
this._getPage2().removeAllAggregation('content');
this._filterDetailList = new sap.m.List(
{
mode : (bMultiSelectMode ? sap.m.ListMode.MultiSelect
: sap.m.ListMode.SingleSelectLeft),
includeItemInSelection : true,
selectionChange : function(oEvent) {
var oSubItem,
aEventListItems = oEvent.getParameter("listItems"),
aSubItems,
i = 0,
bNewProperty;
that._clearPresetFilter();
if (bMultiSelectMode) {
this._updateSelectAllCheckBoxState();
}
// check if multiple items are selected - [CTRL] + [A] combination from the list
if (aEventListItems.length > 1 && bMultiSelectMode){
aSubItems = oItem.getItems();
for (; i < aSubItems.length; i++) {
for (var j = 0; j < aEventListItems.length; j++){
if (aSubItems[i].getKey() === aEventListItems[j].getCustomData()[0].getValue().getKey()){
aSubItems[i].setProperty('selected', aEventListItems[j].getSelected(), true);
}
}
}
} else {
oSubItem = oEvent.getParameter("listItem").data("item");
// clear selection of all subitems if this is a
// single select item
if (!oItem.getMultiSelect()) {
aSubItems = oItem.getItems();
for (; i < aSubItems.length; i++) {
if (aSubItems[i].getId() !== oSubItem.getId()) {
aSubItems[i].setProperty('selected', false, true);
}
}
}
bNewProperty = oEvent.getParameter("listItem").getSelected();
if (oSubItem.getProperty('selected') !== bNewProperty) {
oSubItem.setProperty('selected', oEvent.getParameter("listItem").getSelected(), true);
}
}
}.bind(this)
});
for (var i = 0; i < aSubFilters.length; i++) {
// use name if there is no key defined
oListItem = new sap.m.StandardListItem({
title : aSubFilters[i].getText(),
type : sap.m.ListType.Active,
selected : aSubFilters[i].getSelected()
}).data("item", aSubFilters[i]);
this._filterDetailList.addItem(oListItem);
}
if (bMultiSelectMode) {
this._filterSearchField = this._getFilterSearchField(this._filterDetailList);
this._selectAllCheckBox = this._getSelectAllCheckbox(aSubFilters, this._filterDetailList);
this._getPage2().addContent(this._filterSearchField.addStyleClass('sapMVSDFilterSearchField'));
this._filterDetailList.setHeaderToolbar(new Toolbar({
content: [ this._selectAllCheckBox ]
}).addStyleClass('sapMVSDFilterHeaderToolbar'));
}
this._getPage2().addContent(this._filterDetailList);
};
/**
* Create list item instance for each sort item.
* @private
*/
ViewSettingsDialog.prototype._initSortItems = function() {
var aSortItems,
oListItem;
this._sortList.removeAllItems();
aSortItems = this.getSortItems();
if (aSortItems.length) {
aSortItems.forEach(function(oItem) {
oListItem = new sap.m.StandardListItem({
title : oItem.getText(),
type : sap.m.ListType.Active,
selected : oItem.getSelected()
}).data("item", oItem);
this._sortList.addItem(oListItem);
}, this);
}
};
/**
* Creates and initializes the sort content controls.
* @private
*/
ViewSettingsDialog.prototype._initSortContent = function() {
var that = this;
if (this._sortContent) {
return;
}
this._vContentPage = -1;
// Aria - used to label the sort order list
this._ariaSortOrderInvisibleText = new sap.ui.core.InvisibleText(this.getId() + "-sortOrderLabel", {
text: this._rb.getText("VIEWSETTINGS_SORT_DIRECTION").concat(":")
});
this._sortOrderList = new sap.m.List(this.getId() + "-sortorderlist", {
mode : sap.m.ListMode.SingleSelectLeft,
includeItemInSelection : true,
selectionChange : function(oEvent) {
that.setProperty('sortDescending', oEvent.getParameter("listItem").data("item"), true);
},
ariaLabelledBy: this._ariaSortOrderInvisibleText
}).addStyleClass("sapMVSDUpperList");
this._sortOrderList.addItem(new sap.m.StandardListItem({
title : this._rb.getText("VIEWSETTINGS_ASCENDING_ITEM")
}).data("item", false).setSelected(true));
this._sortOrderList.addItem(new sap.m.StandardListItem({
title : this._rb.getText("VIEWSETTINGS_DESCENDING_ITEM")
}).data("item", true));
// Aria - used to label the sort list
this._ariaSortListInvisibleText = new sap.ui.core.InvisibleText(this.getId() + "-sortListLabel", {
text: this._rb.getText("VIEWSETTINGS_TITLE_SORT").concat(":")
});
this._sortList = new sap.m.List(this.getId() + "-sortlist", {
mode : sap.m.ListMode.SingleSelectLeft,
includeItemInSelection : true,
selectionChange : function(oEvent) {
var oSelectedSortItem = sap.ui.getCore().byId(that.getSelectedSortItem());
var item = oEvent.getParameter("listItem").data("item");
if (item) {
if (oSelectedSortItem) {
oSelectedSortItem.setSelected(!oEvent.getParameter("listItem").getSelected());
}
item.setProperty('selected', oEvent.getParameter("listItem").getSelected(), true);
}
that.setAssociation("selectedSortItem", item, true);
},
ariaLabelledBy: this._ariaSortListInvisibleText
});
this._sortContent = [ this._ariaSortOrderInvisibleText, this._sortOrderList, this._ariaSortListInvisibleText, this._sortList ];
};
/**
* Create list item instance for each group item.
* @private
*/
ViewSettingsDialog.prototype._initGroupItems = function () {
var oListItem,
bHasSelections,
aGroupItems = this.getGroupItems();
this._groupList.removeAllItems();
if (!!aGroupItems.length) {
aGroupItems.forEach(function (oItem) {
oListItem = new sap.m.StandardListItem({
title: oItem.getText(),
type: sap.m.ListType.Active,
selected: oItem.getSelected()
}).data("item", oItem);
this._groupList.addItem(oListItem);
}, this);
if (!this._oGroupingNoneItem || this._oGroupingNoneItem.bIsDestroyed) {
bHasSelections = !!this.getSelectedGroupItem();
this._oGroupingNoneItem = new sap.m.ViewSettingsItem({
text: this._rb.getText("VIEWSETTINGS_NONE_ITEM"),
selected: !bHasSelections,
/**
* Set properly selections. ViewSettingsItem-s are attached
* to that listener when addAggregation is executed
*/
itemPropertyChanged: function () {
this._initGroupContent();
this._initGroupItems();
}.bind(this)
});
!bHasSelections && this.setAssociation("selectedGroupItem", this._oGroupingNoneItem, true);
}
// Append the None button to the list
oListItem = new sap.m.StandardListItem({
title: this._oGroupingNoneItem.getText(),
type: sap.m.ListType.Active,
selected: this._oGroupingNoneItem.getSelected()
}).data("item", this._oGroupingNoneItem);
this._groupList.addItem(oListItem);
}
};
/**
* Creates and initializes the group content controls.
* @private
*/
ViewSettingsDialog.prototype._initGroupContent = function() {
var that = this;
if (this._groupContent) {
return;
}
this._vContentPage = -1;
// Aria - used to label the group order
this._ariaGroupOrderInvisibleText = new sap.ui.core.InvisibleText(this.getId() + "-groupOrderLabel", {
text: this._rb.getText("VIEWSETTINGS_GROUP_DIRECTION").concat(":")
});
this._groupOrderList = new sap.m.List(this.getId() + "-grouporderlist", {
mode : sap.m.ListMode.SingleSelectLeft,
includeItemInSelection : true,
selectionChange : function(oEvent) {
that.setProperty('groupDescending', oEvent.getParameter("listItem").data("item"), true);
},
ariaLabelledBy: this._ariaGroupOrderInvisibleText
}).addStyleClass("sapMVSDUpperList");
this._groupOrderList.addItem(new sap.m.StandardListItem({
title : this._rb.getText("VIEWSETTINGS_ASCENDING_ITEM")
}).data("item", false).setSelected(true));
this._groupOrderList.addItem(new sap.m.StandardListItem({
title : this._rb.getText("VIEWSETTINGS_DESCENDING_ITEM")
}).data("item", true));
// Aria - used to label the group list
this._ariaGroupListInvisibleText = new sap.ui.core.InvisibleText(this.getId() + "-groupListLabel", {
text: this._rb.getText("VIEWSETTINGS_TITLE_GROUP").concat(":")
});
this._groupList = new sap.m.List(this.getId() + "-grouplist",
{
mode : sap.m.ListMode.SingleSelectLeft,
includeItemInSelection : true,
selectionChange: function (oEvent) {
var oSelectedGroupItem = sap.ui.getCore().byId(that.getSelectedGroupItem()),
item = oEvent.getParameter("listItem").data("item");
if (!!item) {
if (!!oSelectedGroupItem) {
oSelectedGroupItem.setSelected(!oEvent.getParameter("listItem").getSelected());
}
item.setProperty('selected', oEvent.getParameter("listItem").getSelected(), true);
}
that.setAssociation("selectedGroupItem", item, true);
},
ariaLabelledBy: this._ariaGroupListInvisibleText
});
this._groupContent = [ this._ariaGroupOrderInvisibleText, this._groupOrderList, this._ariaGroupListInvisibleText, this._groupList ];
};
/**
* Create list instance for each filter item.
* @private
*/
ViewSettingsDialog.prototype._initFilterItems = function() {
var aPresetFilterItems,
aFilterItems,
oListItem,
that = this;
this._presetFilterList.removeAllItems();
aPresetFilterItems = this.getPresetFilterItems();
if (aPresetFilterItems.length) {
aPresetFilterItems.forEach(function(oItem) {
oListItem = new sap.m.StandardListItem({
title : oItem.getText(),
type : sap.m.ListType.Active,
selected : oItem.getSelected()
}).data("item", oItem);
this._presetFilterList.addItem(oListItem);
}, this);
}
// add none item to preset filter list
if (aPresetFilterItems.length) {
oListItem = new sap.m.StandardListItem({
title : this._rb.getText("VIEWSETTINGS_NONE_ITEM"),
selected : !!this.getSelectedPresetFilterItem()
});
this._presetFilterList.addItem(oListItem);
}
this._filterList.removeAllItems();
aFilterItems = this.getFilterItems();
if (aFilterItems.length) {
aFilterItems.forEach(function(oItem) {
oListItem = new sap.m.StandardListItem(
{
title : oItem.getText(),
type : sap.m.ListType.Active,
press : (function(oItem) {
return function(oEvent) {
// navigate to details page
if (that._navContainer.getCurrentPage() .getId() !== that.getId() + '-page2') {
that._switchToPage(3, oItem);
that._prevSelectedFilterItem = this;
jQuery.sap.delayedCall(0, that._navContainer, "to", [ that.getId() + '-page2', "slide" ]);
}
if (sap.ui.Device.system.desktop && that._filterDetailList && that._filterDetailList.getItems()[0]) {
that._getNavContainer().attachEventOnce("afterNavigate", function() {
that._filterDetailList.getItems()[0].focus();
});
}
};
}(oItem))
}).data("item", oItem);
this._filterList.addItem(oListItem);
}, this);
}
};
/**
* Creates and initializes the filter content controls.
* @private
*/
ViewSettingsDialog.prototype._initFilterContent = function() {
var that = this;
if (this._filterContent) {
return;
}
this._vContentPage = -1;
this._presetFilterList = new sap.m.List(
this.getId() + "-predefinedfilterlist",
{
mode : sap.m.ListMode.SingleSelectLeft,
includeItemInSelection : true,
selectionChange : function(oEvent) {
var item = oEvent.getParameter("listItem").data("item");
if (item) {
item.setProperty('selected', oEvent.getParameter("listItem").getSelected(), true);
}
that.setAssociation("selectedPresetFilterItem", item, true);
that._clearSelectedFilters();
}
}).addStyleClass("sapMVSDUpperList");
this._filterList = new sap.m.List(this.getId() + "-filterlist", {});
this._filterContent = [ this._presetFilterList, this._filterList ];
};
/**
* Fills the dialog with the aggregation data.
* @param {string} [sPageId] The ID of the page to be opened in the dialog
* @private
*/
ViewSettingsDialog.prototype._initDialogContent = function(sPageId) {
var bSort = !!this.getSortItems().length,
bGroup = !!this.getGroupItems().length,
bPredefinedFilter = !!this.getPresetFilterItems().length,
bFilter = !!this.getFilterItems().length;
// sort
if (bSort) {
this._initSortContent();
this._initSortItems();
}
// group
if (bGroup) {
this._initGroupContent();
this._initGroupItems();
}
// filters
if (bPredefinedFilter || bFilter) {
this._initFilterContent();
this._initFilterItems();
}
// hide elements that are not visible and set the active content
this._updateDialogState(sPageId);
// select the items that are reflected in the control's properties
this._updateListSelections();
};
/**
* Sets the state of the dialog when it is opened.
* If content for only one tab is defined, then tabs are not displayed, otherwise,
* a SegmentedButton is displayed and the button for the initially displayed page is focused.
* @param {string} [sPageId] The ID of the page to be opened in the dialog
* @private
*/
ViewSettingsDialog.prototype._updateDialogState = function(sPageId) {
var bSort = !!this.getSortItems().length,
bGroup = !!this.getGroupItems().length,
bPredefinedFilter = !!this.getPresetFilterItems().length,
bFilter = !!this.getFilterItems().length,
bCustomTabs = !!this.getCustomTabs().length,
oSegmentedButton = this._getSegmentedButton(),
sSelectedButtonId = null,
bIsPageIdOfPredefinedPage = false,
oDefaultPagesIds = {
"sort" : 0,
"group" : 1,
"filter" : 2
};
// reset state
oSegmentedButton.removeAllButtons();
if (this._filterContent) {
this._presetFilterList.setVisible(true);
this._filterList.setVisible(true);
}
// add segmented button segments
if (bSort) {
oSegmentedButton.addButton(this._getSortButton());
}
if (bPredefinedFilter || bFilter) {
oSegmentedButton.addButton(this._getFilterButton());
if (!bPredefinedFilter) {
this._presetFilterList.setVisible(false);
this._presetFilterList.addStyleClass("sapMVSDUpperList");
}
if (!bFilter) {
this._filterList.setVisible(false);
this._presetFilterList.removeStyleClass("sapMVSDUpperList");
}
}
if (bGroup) {
oSegmentedButton.addButton(this._getGroupButton());
}
if (bCustomTabs) {
this.getCustomTabs().forEach(function (oCustomTab) {
if (!this._isEmptyTab(oCustomTab)) {
var oButton = oCustomTab.getTabButton({
'idPrefix': this.getId() + this._sCustomTabsButtonsIdPrefix
});
// add custom tab to segmented button
oSegmentedButton.addButton(oButton);
}
}.bind(this));
}
// show header only when there are multiple tabs active
this._showSubHeader = this._hasSubHeader();
// make sure to reopen the a page if it was opened before but only if no specific page is requested
if (sPageId === undefined && this._vContentPage !== -1) {
sPageId = this._vContentPage;
switch (sPageId) {
case 0:
sPageId = 'sort';
break;
case 1:
sPageId = 'group';
break;
case 2:
sPageId = 'filter';
break;
}
}
// CSN# 3802530/2013: if filters were modified by API we need to refresh the
// filter detail page
if (sPageId === this._vContentPage && this._vContentPage === 3) {
this._vContentPage = -1;
this._switchToPage(3, this._oContentItem);
} else {
// i.e. page id may be undefined or an invalid string, or the page might have no content
sPageId = this._determineValidPageId(sPageId);
// if the selected page id is of a predefined page - translate it to a numeric id for the switchToPage() method
// and construct corresponding segmented button id
for (var sPageName in oDefaultPagesIds) {
if (sPageId === sPageName) {
bIsPageIdOfPredefinedPage = true;
sSelectedButtonId = this.getId() + '-' + sPageId + 'button';
sPageId = oDefaultPagesIds[sPageName];
break;
}
}
if (!bIsPageIdOfPredefinedPage) {
// construct segmented button id corresponding to custom tab
sSelectedButtonId = this.getId() + this._sCustomTabsButtonsIdPrefix + sPageId;
}
this._getSegmentedButton().setSelectedButton(sSelectedButtonId);
this._switchToPage(sPageId);
/* 1580045867 2015: make sure navContainer's current page is always page1,
because at this point we are always switching to sort,group,filter or custom tab.*/
if (this._getNavContainer().getCurrentPage() !== this._getPage1()) {
this._getNavContainer().to(this._getPage1().getId());
}
}
};
/**
* Determines the page ID of a valid page to load.
* @param {string} [sPageId] The ID of the page to be opened in the dialog
* @returns {string} sPageId
* @private
*/
ViewSettingsDialog.prototype._determineValidPageId = function (sPageId) {
var sDefaultPageId = 'sort',
bHasMatch = false,
aValidPageIds = [];
// get a list of 'valid' page ids - meaning that each one exists and has content
aValidPageIds = this._fetchValidPagesIds();
if (aValidPageIds.length) {
// use the first valid page as default page id
sDefaultPageId = aValidPageIds[0];
} else {
jQuery.sap.log.warning('No available pages to load - missing items.');
}
// if no specific page id is wanted give a default one
if (!sPageId) {
sPageId = sDefaultPageId;
} else {
// if specific page id is wanted - make sure it exists in the valid pages array
aValidPageIds.filter(function (sValidPageId) {
if (sValidPageId === sPageId) {
bHasMatch = true;
return false;
}
return true;
});
if (!bHasMatch) {
// if specific page is required but no such valid page exists, use the default page id
sPageId = sDefaultPageId;
}
}
return sPageId;
};
/**
* Fetches a list of valid pages IDs - each page must have valid content.
* @returns {Array} aValidPageIds List of valid page IDs
* @private
*/
ViewSettingsDialog.prototype._fetchValidPagesIds = function () {
var i,
aCustomTabs = this.getCustomTabs(),
aCustomTabsLength = aCustomTabs.length,
aValidPageIds = [];
/* make sure to push the predefined pages ids before the custom tabs as the order is important - if the control
* has to determine which page to load it takes the first valid page id */
/* check all predefined pages that could be opened and make sure they have content */
var aPredefinedPageNames = ['sort', 'filter', 'group']; // order is important
aPredefinedPageNames.forEach( function (sPageName) {
if (this._isValidPredefinedPageId(sPageName)) {
aValidPageIds.push(sPageName);
}
}, this);
/* check all custom tabs and make sure they have content */
for (i = 0; i < aCustomTabsLength; i++) {
var oCustomTab = aCustomTabs[i];
if (!this._isEmptyTab(oCustomTab)) {
aValidPageIds.push(oCustomTab.getId());
}
}
return aValidPageIds;
};
/**
* Checks whether a custom tab instance is not empty.
* @param {object} oCustomTab
* @returns {*|boolean}
* @private
*/
ViewSettingsDialog.prototype._isEmptyTab = function (oCustomTab) {
/* if the tab has no content check if the content aggregation
is not currently transferred to the main page instance - if the last page content
corresponds to the tab id that must be the case */
return !(oCustomTab.getContent().length || this._vContentPage === oCustomTab.getId() && this._getPage1().getContent().length);
};
/**
* Checks whether a given page name corresponds to a valid predefined page ID.
* The meaning of valid would be for the predefined page to also have content.
* @param {string} sName The page name
* @returns {boolean}
* @private
*/
ViewSettingsDialog.prototype._isValidPredefinedPageId = function (sName) {
if (!sName) {
jQuery.sap.log.warning('Missing mandatory parameter.');
return false;
}
var bHasContents = false;
// make sure the desired predefined page id has contents
switch (sName) {
case 'sort':
bHasContents = !!this.getSortItems().length;
break;
case 'filter':
bHasContents = !!this.getFilterItems().length || !!this.getPresetFilterItems().length;
break;
case 'group':
bHasContents = !!this.getGroupItems().length;
break;
}
return bHasContents;
};
sap.m.ViewSettingsDialog.prototype._pressBackButton = function() {
var that = this;
if (this._vContentPage === 3) {
this._updateFilterCounters();
this._getNavContainer().attachEvent("afterNavigate", function(){
if (that._prevSelectedFilterItem) {
that._prevSelectedFilterItem.focus();
}
});
jQuery.sap.delayedCall(0, this._getNavContainer(), 'back');
this._switchToPage(2);
this._segmentedButton.setSelectedButton(this._filterButton);
}
};
/**
* Overwrites the model setter to reset the remembered page in case it was a filter detail page, to make sure
* that the dialog is not trying to re-open a page for a removed item.
*
* @param {object} oModel
* @param {string} sName
* @returns {sap.m.ViewSettingsDialog} this pointer for chaining
*/
ViewSettingsDialog.prototype.setModel = function (oModel, sName) {
// BCP 1570030370
if (this._vContentPage === 3 && this._oContentItem) {
resetFilterPage.call(this);
}
return sap.ui.base.ManagedObject.prototype.setModel.call(this, oModel, sName);
};
/**
* Removes a filter Item and resets the remembered page if it was the filter detail page of the removed filter.
*
* @overwrite
* @public
* @param { int| sap.m.ViewSettingsFilterItem | string } vFilterItem The filter item's index, or the item itself, or its id
* @returns {sap.m.ViewSettingsDialog} this pointer for chaining
*/
ViewSettingsDialog.prototype.removeFilterItem = function (vFilterItem) {
var sFilterItemId = "";
if (this._vContentPage === 3 && this._oContentItem) {
if (typeof (vFilterItem) === "object") {
sFilterItemId = vFilterItem.getId();
} else if (typeof (vFilterItem) === "string") {
sFilterItemId = vFilterItem;
} else if (typeof (vFilterItem) === "number") {
sFilterItemId = this.getFilterItems()[vFilterItem].getId();
}
if (this._oContentItem.getId() === sFilterItemId) {
resetFilterPage.call(this);
}
}
return this.removeAggregation('filterItems', vFilterItem);
};
/**
* Removes all filter Items and resets the remembered page if it was a filter detail page and all of its filter items are being removed.
*
* @overwrite
* @public
* @returns {sap.m.ViewSettingsDialog} this pointer for chaining
*/
ViewSettingsDialog.prototype.removeAllFilterItems = function () {
if (this._vContentPage === 3 && this._oContentItem) {
resetFilterPage.call(this);
}
return this.removeAllAggregation('filterItems');
};
/**
* Switches to a dialog page (0 = sort, 1 = group, 2 = filter, 3 = subfilter and custom pages).
* @param {int|string} vWhich The page to be navigated to
* @param {sap.m.FilterItem} oItem The filter item for the detail page (optional, only used for page 3).
*
* @private
*/
ViewSettingsDialog.prototype._switchToPage = function(vWhich, oItem) {
var i = 0,
oTitleLabel = this._getTitleLabel(),
oResetButton = this._getResetButton(),
oHeader = this._getHeader(),
oSubHeader = this._getSubHeader();
// nothing to do if we are already on the requested page (except for filter detail page)
if (this._vContentPage === vWhich && vWhich !== 3) {
// On switching to different pages, the content (Reset Button) of the header and sub-header is removed and added again
// only if vWhich is not 3(filter detail page). So when opening the dialog and navigating to
// filter detail page the Reset Button is only removed from page1. On clicking Ok and opening the dialog again vWhich is 2 and
// is equal to this._vContentPage so we skip all the following logic that should add the reset button again.
// Added logic for adding the Reset Button explicitly when we going into this state and there is no Reset Button.
// BCP 0020079747 0000728077 2015
if (oHeader.getContentRight().length === 0 && oSubHeader.getContentRight().length === 0) {
this._addResetButtonToPage1();
}
return false;
}
// needed because the content aggregation is changing it's owner control from custom tab to page and vice-versa
// if there is existing page content and the last opened page was a custom tab
if (isLastPageContentCustomTab.call(this)) {
restoreCustomTabContentAggregation.call(this);
}
// reset controls
oHeader.removeAllContentRight();
oSubHeader.removeAllContentRight();
this._vContentPage = vWhich;
this._oContentItem = oItem;
// purge the current content & reset pages
if (vWhich !== 3 /* filter detail */) {
// purge page contents
this._getPage1().removeAllAggregation("content", true);
// set subheader when there are multiple tabs active
this._addResetButtonToPage1();
} else if (vWhich === 3) {
this._getPage2().removeAllAggregation("content", true);
}
if (this.getTitle()) { // custom title
oTitleLabel.setText(this.getTitle());
} else { // default title
oTitleLabel.setText(this._rb.getText("VIEWSETTINGS_TITLE"));
}
switch (vWhich) {
case 1: // grouping
oResetButton.setVisible(false);
if (!this._showSubHeader && !this.getTitle()) {
oTitleLabel.setText(this._rb.getText("VIEWSETTINGS_TITLE_GROUP"));
}
for (; i < this._groupContent.length; i++) {
this._getPage1().addContent(this._groupContent[i]);
}
break;
case 2: // filtering
// only show reset button when there are detail filters available
oResetButton.setVisible(!!this.getFilterItems().length);
if (!this._showSubHeader && !this.getTitle()) {
oTitleLabel.setText(this._rb.getText("VIEWSETTINGS_TITLE_FILTER"));
}
// update status (something could have been changed on a detail filter
// page or by API
this._updateListSelection(this._presetFilterList, sap.ui.getCore()
.byId(this.getSelectedPresetFilterItem()));
this._updateFilterCounters();
for (; i < this._filterContent.length; i++) {
this._getPage1().addContent(this._filterContent[i]);
}
break;
case 3: // filtering details
// display filter title
this._setFilterDetailTitle(oItem);
// fill detail page
if (oItem instanceof sap.m.ViewSettingsCustomItem
&& oItem.getCustomControl()) {
this._clearPresetFilter();
this._getPage2().addContent(oItem.getCustomControl());
} else if (oItem instanceof sap.m.ViewSettingsFilterItem
&& oItem.getItems()) {
this._initFilterDetailItems(oItem);
}
break;
case 0: // sorting
oResetButton.setVisible(false);
if (!this._getPage1().getSubHeader() && !this.getTitle()) {
oTitleLabel.setText(this._rb.getText("VIEWSETTINGS_TITLE_SORT"));
}
if (this._sortContent) {
for (; i < this._sortContent.length; i++) {
this._getPage1().addContent(this._sortContent[i]);
}
}
break;
default:
// custom tabs
oResetButton.setVisible(false);
this._getPage1().removeAllAggregation("content", true);
var sTitle = "VIEWSETTINGS_TITLE";
var aCustomTabs = this.getCustomTabs();
if (aCustomTabs.length < 2) {
// use custom tab title only if there is a single custom tab
sTitle = aCustomTabs[0].getTitle();
}
if (!this._getPage1().getSubHeader() && !this.getTitle()) {
oTitleLabel.setText(sTitle);
}
aCustomTabs.forEach(function (oCustomTab) {
if (oCustomTab.getId() === vWhich) {
oCustomTab.getContent().forEach(function (oContent) {
this._getPage1().addContent(oContent);
}, this);
}
}, this);
break;
}
};
/**
* Creates the Select All checkbox.
*
* @param {Array} aFilterSubItems The detail filter items
* @param oFilterDetailList The actual list created for the detail filter page
* @returns {sap.m.CheckBox} A checkbox instance
* @private
*/
ViewSettingsDialog.prototype._getSelectAllCheckbox = function(aFilterSubItems, oFilterDetailList) {
var oSelectAllCheckBox = new CheckBox({
text: 'Select All',
selected: aFilterSubItems.every(function(oItem) { return oItem.getSelected(); }),
select: function(oEvent) {
var bSelected = oEvent.getParameter('selected');
//update the list items
//and corresponding view settings items
oFilterDetailList.getItems().filter(function(oItem) {
return oItem.getVisible();
}).forEach(function(oItem) {
var oVSDItem = oItem.data("item");
oVSDItem.setSelected(bSelected);
});
}
});
return oSelectAllCheckBox;
};
/**
* Updates the state of the select all checkbox after selecting a single item or after filtering items.
*
* @private
*/
ViewSettingsDialog.prototype._updateSelectAllCheckBoxState = function() {
var bAllSelected = this._filterDetailList.getItems().filter(function(oItem) {
return oItem.getVisible();
}).every(function(oItem) {
return oItem.getSelected();
});
if (this._selectAllCheckBox) {
this._selectAllCheckBox.setSelected(bAllSelected);
}
};
/**
* Creates the filter items search field.
*
* @param {Array} oFilterDetailList The actual list created for the detail filter page
* @returns {sap.m.SearchField} A search field instance
* @private
*/
ViewSettingsDialog.prototype._getFilterSearchField = function(oFilterDetailList) {
var that = this,
oFilterSearchField = new SearchField({
search: function(oEvent) {
var sQuery = oEvent.getParameter('query').toLowerCase();
//update the list items visibility
oFilterDetailList.getItems().forEach(function(oItem) {
var bStartsWithQuery = oItem.getTitle().toLowerCase().indexOf(sQuery) === 0;
oItem.setVisible(bStartsWithQuery);
});
//update Select All checkbox
that._updateSelectAllCheckBoxState();
}
});
return oFilterSearchField;
};
/**
* Updates the internal lists based on the dialogs state.
* @private
*/
ViewSettingsDialog.prototype._updateListSelections = function() {
this._updateListSelection(this._sortList, sap.ui.getCore().byId(this.getSelectedSortItem()));
this._updateListSelection(this._sortOrderList, this.getSortDescending());
this._updateListSelection(this._groupList, sap.ui.getCore().byId(this.getSelectedGroupItem()));
this._updateListSelection(this._groupOrderList, this.getGroupDescending());
this._updateListSelection(this._presetFilterList, sap.ui.getCore().byId(this.getSelectedPresetFilterItem()));
this._updateFilterCounters();
};
/**
* Sets selected item on single selection lists based on the item data.
* @private
*/
ViewSettingsDialog.prototype._updateListSelection = function(oList, oItem) {
var items, i = 0;
if (!oList) {
return false;
}
items = oList.getItems();
oList.removeSelections();
for (; i < items.length; i++) {
if (items[i].data("item") === oItem || items[i].data("item") === null) { // null
// is
// "None"
// item
oList.setSelectedItem(items[i], (oItem && oItem.getSelected ? oItem
.getSelected() : true)); // true or the selected state if
// it is a ViewSettingsItem
return true;
}
}
return false;
};
/**
* Updates the amount of selected filters in the filter list.
* @private
*/
ViewSettingsDialog.prototype._updateFilterCounters = function() {
var aListItems = (this._filterList ? this._filterList.getItems() : []),
oItem,
aSubItems,
iFilterCount = 0,
i = 0,
j;
for (; i < aListItems.length; i++) {
oItem = aListItems[i].data("item");
iFilterCount = 0;
if (oItem) {
if (oItem instanceof sap.m.ViewSettingsCustomItem) {
// for custom filter oItems the oItem is directly selected
iFilterCount = oItem.getFilterCount();
} else if (oItem instanceof sap.m.ViewSettingsFilterItem) {
// for filter oItems the oItem counter has to be calculated from
// the sub oItems
iFilterCount = 0;
aSubItems = oItem.getItems();
for (j = 0; j < aSubItems.length; j++) {
if (aSubItems[j].getSelected()) {
iFilterCount++;
}
}
}
}
aListItems[i].setCounter(iFilterCount);
}
};
ViewSettingsDialog.prototype._clearSelectedFilters = function() {
var items = this.getFilterItems(), subItems, i = 0, j;
// reset all items to selected = false
for (; i < items.length; i++) {
if (items[i] instanceof sap.m.ViewSettingsFilterItem) {
subItems = items[i].getItems();
for (j = 0; j < subItems.length; j++) {
subItems[j].setProperty('selected', false, true);
}
}
items[i].setProperty('selected', false, true);
}
// update counters if visible
if (this._vContentPage === 2 && this._getDialog().isOpen()) {
this._updateFilterCounters();
}
};
/**
* Clears preset filter item.
* @private
*/
ViewSettingsDialog.prototype._clearPresetFilter = function() {
if (this.getSelectedPresetFilterItem()) {
this.setSelectedPresetFilterItem(null);
}
};
/**
* Determines the number of pages (tabs).
* @private
* @return {int} iActivePages The number of pages in the dialog
*/
ViewSettingsDialog.prototype._calculateNumberOfPages = function () {
var iActivePages = 0,
bSort = !!this.getSortItems().length,
bGroup = !!this.getGroupItems().length,
bPredefinedFilter = !!this.getPresetFilterItems().length,
bFilter = !!this.getFilterItems().length;
if (bSort) {
iActivePages++;
}
if (bPredefinedFilter || bFilter) {
iActivePages++;
}
if (bGroup) {
iActivePages++;
}
this.getCustomTabs().forEach(function (oCustomTab) {
if (!this._isEmptyTab(oCustomTab)) {
iActivePages++;
}
}, this);
return iActivePages;
};
/**
* Determines if a sub header should be displayed or not.
* @private
* @return {boolean}
*/
ViewSettingsDialog.prototype._hasSubHeader = function () {
return !(this._calculateNumberOfPages() < 2);
};
/**
* Sets the current page to the filter page, clears info about the last opened page (content),
* and navigates to the filter page.
* @private
*/
function resetFilterPage() {
this._vContentPage = 2;
this._oContentItem = null;
this._navContainer.to(this._getPage1().getId(), "show");
}
/**
* Gets a sap.m.ViewSettingsItem from a list of items by a given key.
*
* @param aViewSettingsItems The list of sap.m.ViewSettingsItem objects to be searched
* @param sKey
* @returns {*} The sap.m.ViewSettingsItem found in the list of items
* @private
*/
function getViewSettingsItemByKey(aViewSettingsItems, sKey) {
var i, oItem;
// convenience, also allow strings
// find item with this key
for (i = 0; i < aViewSettingsItems.length; i++) {
if (aViewSettingsItems[i].getKey() === sKey) {
oItem = aViewSettingsItems[i];
break;
}
}
return oItem;
}
/**
* Finds a sap.m.ViewSettingsItem from a list of items by a given key.
* If it does not succeed logs an error.
*
* @param {sap.m.ViewSettingsItem|string}
* @param aViewSettingsItems The list of sap.m.ViewSettingsItem objects to be searched
* @param {string} sErrorMessage The error message that will be logged if the item is not found
* @returns {*} The sap.m.ViewSettingsItem found in the list of items
* @private
*/
function findViewSettingsItemByKey(vItemOrKey, aViewSettingsItems, sErrorMessage) {
var oItem;
// convenience, also allow strings
if (typeof vItemOrKey === "string") {
// find item with this key
oItem = getViewSettingsItemByKey(aViewSettingsItems, vItemOrKey);
if (!oItem) {
jQuery.sap.log.error(sErrorMessage);
}
} else {
oItem = vItemOrKey;
}
return oItem;
}
/**
* Checks if the item is a sap.m.ViewSettingsItem.
*
* @param {*} oItem The item to be validated
* @returns {*|boolean} Returns true if the item is a sap.m.ViewSettingsItem
* @private
*/
function validateViewSettingsItem(oItem) {
return oItem && oItem instanceof sap.m.ViewSettingsItem;
}
/* =========================================================== */
/* end: internal methods */
/* =========================================================== */
/* =========================================================== */
/* begin: event handlers */
/* =========================================================== */
/**
* Internal event handler for the Confirm button.
* @private
*/
ViewSettingsDialog.prototype._onConfirm = function(oEvent) {
var that = this,
oDialog = this._getDialog(),
fnAfterClose = function() {
var oSettingsState = {
sortItem : sap.ui.getCore().byId(that.getSelectedSortItem()),
sortDescending : that.getSortDescending(),
groupItem : sap.ui.getCore().byId(that.getSelectedGroupItem()),
groupDescending : that.getGroupDescending(),
presetFilterItem : sap.ui.getCore().byId(that.getSelectedPresetFilterItem()),
filterItems : that.getSelectedFilterItems(),
filterKeys : that.getSelectedFilterKeys(),
filterString : that.getSelectedFilterString()
};
// detach this function
that._dialog.detachAfterClose(fnAfterClose);
// fire confirm event
that.fireConfirm(oSettingsState);
};
// attach the reset function to afterClose to hide the dialog changes from
// the end user
oDialog.attachAfterClose(fnAfterClose);
oDialog.close();
};
/**
* Internal event handler for the Cancel button.
* @private
*/
ViewSettingsDialog.prototype._onCancel = function(oEvent) {
var that = this, oDialog = this._getDialog(), fnAfterClose = function() {
// reset the dialog to the previous state
that.setSelectedSortItem(that._oPreviousState.sortItem);
that.setSortDescending(that._oPreviousState.sortDescending);
that.setSelectedGroupItem(that._oPreviousState.groupItem);
that.setGroupDescending(that._oPreviousState.groupDescending);
that.setSelectedPresetFilterItem(that._oPreviousState.presetFilterItem);
// selected filters need to be cleared before
that._clearSelectedFilters();
that.setSelectedFilterKeys(that._oPreviousState.filterKeys);
// navigate to old page if necessary
if (that._navContainer.getCurrentPage() !== that._oPreviousState.navPage) {
jQuery.sap.delayedCall(0, that._navContainer, "to", [
that._oPreviousState.navPage.getId(), "show" ]);
}
// navigate to old tab if necessary
that._switchToPage(that._oPreviousState.contentPage,
that._oPreviousState.contentItem);
// detach this function
that._dialog.detachAfterClose(fnAfterClose);
// fire cancel event
that.fireCancel();
};
// attach the reset function to afterClose to hide the dialog changes from
// the end user
oDialog.attachAfterClose(fnAfterClose);
oDialog.close();
};
/**
* Internal event handler for the reset filter button.
* @private
*/
ViewSettingsDialog.prototype._onClearFilters = function() {
// clear data and update selections
this._clearSelectedFilters();
this._clearPresetFilter();
// fire event to allow custom controls to react and reset
this.fireResetFilters();
// update counters
this._updateFilterCounters();
// page updates
if (this._vContentPage === 3) { // go to filter overview page if necessary
jQuery.sap.delayedCall(0, this._getNavContainer(), 'to', [this._getPage1().getId()]);
this._switchToPage(2);
this._getSegmentedButton().setSelectedButton(this._getFilterButton());
}
// update preset list selection
this._updateListSelection(this._presetFilterList, sap.ui.getCore().byId(
this.getSelectedPresetFilterItem()));
};
/**
* Adds the Reset Button to the header/subheader of page1.
* @private
*/
ViewSettingsDialog.prototype._addResetButtonToPage1 = function() {
var oHeader = this._getHeader(),
oSubHeader = this._getSubHeader(),
oResetButton = this._getResetButton();
// set subheader when there are multiple tabs active
if (this._showSubHeader) {
if (!this._getPage1().getSubHeader()) {
this._getPage1().setSubHeader(oSubHeader);
}
// show reset button in subheader
oSubHeader.addContentRight(oResetButton);
} else {
if (this._getPage1().getSubHeader()) {
this._getPage1().setSubHeader();
}
// show reset button in header
oHeader.addContentRight(oResetButton);
}
};
/* =========================================================== */
/* end: event handlers */
/* =========================================================== */
/**
* Overwrite the method to make sure the proper internal managing of the aggregations takes place.
* @param {string} sAggregationName The string identifying the aggregation that the given object should be removed from
* @param {int | string | sap.ui.base.ManagedObject} vObject The position or ID of the ManagedObject that should be removed or that ManagedObject itself
* @param {boolean} bSuppressInvalidate If true, this ManagedObject is not marked as changed
* @returns {sap.m.ViewSettingsDialog} This pointer for chaining
*/
ViewSettingsDialog.prototype.removeAggregation = function (sAggregationName, vObject, bSuppressInvalidate) {
// custom tabs aggregation needs special handling - make sure it happens
restoreCustomTabContentAggregation.call(this, sAggregationName, vObject);
return sap.ui.core.Control.prototype.removeAggregation.call(this, sAggregationName, vObject,
bSuppressInvalidate);
};
/**
* Overwrite the method to make sure the proper internal managing of the aggregations takes place.
* @param {string} sAggregationName The string identifying the aggregation that the given object should be removed from
* @param {int | string | sap.ui.base.ManagedObject} vObject tThe position or ID of the ManagedObject that should be removed or that ManagedObject itself
* @param {boolean} bSuppressInvalidate If true, this ManagedObject is not marked as changed
* @returns {sap.m.ViewSettingsDialog} This pointer for chaining
*/
ViewSettingsDialog.prototype.removeAllAggregation = function (sAggregationName, bSuppressInvalidate) {
// custom tabs aggregation needs special handling - make sure it happens
restoreCustomTabContentAggregation.call(this);
return sap.ui.core.Control.prototype.removeAllAggregation.call(this, sAggregationName, bSuppressInvalidate);
};
/**
* Overwrite the method to make sure the proper internal managing of the aggregations takes place.
* @param {string} sAggregationName The string identifying the aggregation that the given object should be removed from
* @param {int | string | sap.ui.base.ManagedObject} vObject tThe position or ID of the ManagedObject that should be removed or that ManagedObject itself
* @param {boolean} bSuppressInvalidate If true, this ManagedObject is not marked as changed
* @returns {sap.m.ViewSettingsDialog} This pointer for chaining
*/
ViewSettingsDialog.prototype.destroyAggregation = function (sAggregationName, bSuppressInvalidate) {
// custom tabs aggregation needs special handling - make sure it happens
restoreCustomTabContentAggregation.call(this);
return sap.ui.core.Control.prototype.destroyAggregation.call(this, sAggregationName, bSuppressInvalidate);
};
/**
* Handle the "content" aggregation of a custom tab, as the items in it might be transferred to the dialog page
* instance.
* @param {string} sAggregationName The string identifying the aggregation that the given object should be removed from
* @param {object} oCustomTab Custom tab instance
* @private
*/
function restoreCustomTabContentAggregation(sAggregationName, oCustomTab) {
// Make sure page1 exists, as this method may be called on destroy(), after the page was destroyed
// Suppress creation of new page as the following logic is needed only when a page already exists
if (!this._getPage1(true)) {
return;
}
// only the 'customTabs' aggregation is manipulated with shenanigans
if (sAggregationName === 'customTabs' && oCustomTab) {
/* oCustomTab must be an instance of the "customTab" aggregation type and must be the last opened page */
if (oCustomTab.getMetadata().getName() === this.getMetadata().getManagedAggregation(sAggregationName).type &&
this._vContentPage === oCustomTab.getId()) {
/* the iContentPage property corresponds to the custom tab id - set the custom tab content aggregation
back to the custom tab instance */
var oPage1Content = this._getPage1().getContent();
oPage1Content.forEach(function (oContent) {
oCustomTab.addAggregation('content', oContent, true);
});
}
} else if (!sAggregationName && !oCustomTab) {
/* when these parameters are missing, cycle through all custom tabs and detect if any needs manipulation */
var oPage1Content = this._getPage1().getContent();
/* the vContentPage property corresponds to a custom tab id - set the custom tab content aggregation back
to the corresponding custom tab instance, so it can be reused later */
this.getCustomTabs().forEach(function (oCustomTab) {
if (this._vContentPage === oCustomTab.getId()) {
oPage1Content.forEach(function (oContent) {
oCustomTab.addAggregation('content', oContent, true);
});
}
}, this);
}
}
/**
* Determine if the last opened page has custom tab contents
* @private
* @returns {boolean}
*/
function isLastPageContentCustomTab() {
// ToDo: make this into enumeration
var aPageIds = [
-1, // not set
0, // sort
1, // group
2, // filter
3 // filter detail
];
return (this._getPage1().getContent().length && aPageIds.indexOf(this._vContentPage) === -1);
}
return ViewSettingsDialog;
}, /* bExport= */ true);
|
var async = require('async')
var fs = require('fs')
var docopt = require('docopt').docopt
var version = require('../package.json').version
var nrs = require('./index.js')
var args = docopt(fs.readFileSync(__dirname + '/usage.txt', 'utf-8'),
{ version: version })
if (args.test) {
nrs.run({
uri: args['<url>'],
statusCode: parseInt(args['--status'], 10)
}, function (err, res) {
console.log('LOG: testing site', args['<url>'])
console.error('ERR:', err)
console.log('RES:', res)
return
})
}
if (args.speed) {
nrs.netspeed(function (err, data) {
console.log('ERR:', err)
console.log('RES:', data)
return
})
}
if (args.check) {
var sites = require('./default.json')
async.eachSeries(sites, function (site, cb) {
console.log('tests on ', site)
nrs.run(site, function (err, res) {
console.log('LOG: testing site', site.uri)
console.error('ERR:', err)
console.log('RES:', res)
return cb(null, res)
})
}, function done () {
console.log('finished')
})
}
|
var async = require('neo-async');
/**
* Patches the given stores so that they have all of the expected methods
* by using the mandatory ones `set` and `get`
*/
module.exports = function(store) {
if (!store.setAll) {
store.setAll = function(map, cb) {
async.eachSeries(Object.keys(map), function(key, cb) {
store.set(key, map[key], cb);
}, cb);
};
}
if (!store.getAll) {
store.getAll = function(keys, cb) {
var result = {};
async.eachSeries(keys, function(key, cb) {
store.get(key, function(err, value) {
if (err) return cb(err);
result[key] = value;
cb();
});
}, function(err) {
if (err) return cb(err);
cb(null, result);
});
};
}
//putAll treats values of undefined as deletes
if (!store.putAll) {
store.putAll = function(map, cb) {
async.eachSeries(Object.keys(map), function(key, cb) {
var val = map[key];
if (val === undefined) {
store.remove(key, cb);
} else {
store.set(key, val, cb);
}
}, cb);
};
}
return store;
};
|
export { default } from "./SearchForNodesModal";
|
import _debounce from 'lodash-es/debounce';
import {
descending as d3_descending,
ascending as d3_ascending
} from 'd3-array';
import {
event as d3_event,
select as d3_select
} from 'd3-selection';
import { t, textDirection } from '../util/locale';
import { svgIcon } from '../svg';
import { uiBackgroundDisplayOptions } from './background_display_options';
import { uiBackgroundOffset } from './background_offset';
import { uiCmd } from './cmd';
import { uiDisclosure } from './disclosure';
import { uiMapInMap } from './map_in_map';
import { uiSettingsCustomBackground } from './settings/custom_background';
import { uiTooltipHtml } from './tooltipHtml';
import { utilCallWhenIdle } from '../util';
import { tooltip } from '../util/tooltip';
export function uiBackground(context) {
var key = t('background.key');
var _pane = d3_select(null), _toggleButton = d3_select(null);
var _customSource = context.background().findSource('custom');
var _previousBackground = context.background().findSource(context.storage('background-last-used-toggle'));
var _backgroundList = d3_select(null);
var _overlayList = d3_select(null);
var _displayOptionsContainer = d3_select(null);
var _offsetContainer = d3_select(null);
var backgroundDisplayOptions = uiBackgroundDisplayOptions(context);
var backgroundOffset = uiBackgroundOffset(context);
var settingsCustomBackground = uiSettingsCustomBackground(context)
.on('change', customChanged);
function setTooltips(selection) {
selection.each(function(d, i, nodes) {
var item = d3_select(this).select('label');
var span = item.select('span');
var placement = (i < nodes.length / 2) ? 'bottom' : 'top';
var description = d.description();
var isOverflowing = (span.property('clientWidth') !== span.property('scrollWidth'));
item.call(tooltip().destroyAny);
if (d === _previousBackground) {
item.call(tooltip()
.placement(placement)
.html(true)
.title(function() {
var tip = '<div>' + t('background.switch') + '</div>';
return uiTooltipHtml(tip, uiCmd('⌘' + key));
})
);
} else if (description || isOverflowing) {
item.call(tooltip()
.placement(placement)
.title(description || d.name())
);
}
});
}
function updateLayerSelections(selection) {
function active(d) {
return context.background().showsLayer(d);
}
selection.selectAll('li')
.classed('active', active)
.classed('switch', function(d) { return d === _previousBackground; })
.call(setTooltips)
.selectAll('input')
.property('checked', active);
}
function chooseBackground(d) {
if (d.id === 'custom' && !d.template()) {
return editCustom();
}
d3_event.preventDefault();
_previousBackground = context.background().baseLayerSource();
context.storage('background-last-used-toggle', _previousBackground.id);
context.storage('background-last-used', d.id);
context.background().baseLayerSource(d);
_backgroundList.call(updateLayerSelections);
document.activeElement.blur();
}
function customChanged(d) {
if (d && d.template) {
_customSource.template(d.template);
chooseBackground(_customSource);
} else {
_customSource.template('');
chooseBackground(context.background().findSource('none'));
}
}
function editCustom() {
d3_event.preventDefault();
context.container()
.call(settingsCustomBackground);
}
function chooseOverlay(d) {
d3_event.preventDefault();
context.background().toggleOverlayLayer(d);
_overlayList.call(updateLayerSelections);
document.activeElement.blur();
}
function drawListItems(layerList, type, change, filter) {
var sources = context.background()
.sources(context.map().extent())
.filter(filter);
var layerLinks = layerList.selectAll('li')
.data(sources, function(d) { return d.name(); });
layerLinks.exit()
.remove();
var enter = layerLinks.enter()
.append('li')
.classed('layer-custom', function(d) { return d.id === 'custom'; })
.classed('best', function(d) { return d.best(); });
enter.filter(function(d) { return d.id === 'custom'; })
.append('button')
.attr('class', 'layer-browse')
.call(tooltip()
.title(t('settings.custom_background.tooltip'))
.placement((textDirection === 'rtl') ? 'right' : 'left')
)
.on('click', editCustom)
.call(svgIcon('#iD-icon-more'));
enter.filter(function(d) { return d.best(); })
.append('div')
.attr('class', 'best')
.call(tooltip()
.title(t('background.best_imagery'))
.placement((textDirection === 'rtl') ? 'right' : 'left')
)
.append('span')
.html('★');
var label = enter
.append('label');
label
.append('input')
.attr('type', type)
.attr('name', 'layers')
.on('change', change);
label
.append('span')
.text(function(d) { return d.name(); });
layerList.selectAll('li')
.sort(sortSources)
.style('display', layerList.selectAll('li').data().length > 0 ? 'block' : 'none');
layerList
.call(updateLayerSelections);
function sortSources(a, b) {
return a.best() && !b.best() ? -1
: b.best() && !a.best() ? 1
: d3_descending(a.area(), b.area()) || d3_ascending(a.name(), b.name()) || 0;
}
}
function renderBackgroundList(selection) {
// the background list
var container = selection.selectAll('.layer-background-list')
.data([0]);
_backgroundList = container.enter()
.append('ul')
.attr('class', 'layer-list layer-background-list')
.attr('dir', 'auto')
.merge(container);
// add minimap toggle below list
var minimapEnter = selection.selectAll('.minimap-toggle-list')
.data([0])
.enter()
.append('ul')
.attr('class', 'layer-list minimap-toggle-list')
.append('li')
.attr('class', 'minimap-toggle-item');
var minimapLabelEnter = minimapEnter
.append('label')
.call(tooltip()
.html(true)
.title(uiTooltipHtml(t('background.minimap.tooltip'), t('background.minimap.key')))
.placement('top')
);
minimapLabelEnter
.append('input')
.attr('type', 'checkbox')
.on('change', function() {
d3_event.preventDefault();
uiMapInMap.toggle();
});
minimapLabelEnter
.append('span')
.text(t('background.minimap.description'));
// "Info / Report a Problem" link
selection.selectAll('.imagery-faq')
.data([0])
.enter()
.append('div')
.attr('class', 'imagery-faq')
.append('a')
.attr('target', '_blank')
.attr('tabindex', -1)
.call(svgIcon('#iD-icon-out-link', 'inline'))
.attr('href', 'https://github.com/openstreetmap/iD/blob/master/FAQ.md#how-can-i-report-an-issue-with-background-imagery')
.append('span')
.text(t('background.imagery_source_faq'));
updateBackgroundList();
}
function renderOverlayList(selection) {
var container = selection.selectAll('.layer-overlay-list')
.data([0]);
_overlayList = container.enter()
.append('ul')
.attr('class', 'layer-list layer-overlay-list')
.attr('dir', 'auto')
.merge(container);
updateOverlayList();
}
function updateBackgroundList() {
_backgroundList
.call(drawListItems, 'radio', chooseBackground, function(d) { return !d.isHidden() && !d.overlay; });
}
function updateOverlayList() {
_overlayList
.call(drawListItems, 'checkbox', chooseOverlay, function(d) { return !d.isHidden() && d.overlay; });
}
function update() {
if (!_pane.select('.disclosure-wrap-background_list').classed('hide')) {
updateBackgroundList();
}
if (!_pane.select('.disclosure-wrap-overlay_list').classed('hide')) {
updateOverlayList();
}
_displayOptionsContainer
.call(backgroundDisplayOptions);
_offsetContainer
.call(backgroundOffset);
}
function quickSwitch() {
if (d3_event) {
d3_event.stopImmediatePropagation();
d3_event.preventDefault();
}
if (_previousBackground) {
chooseBackground(_previousBackground);
}
}
var paneTooltip = tooltip()
.placement((textDirection === 'rtl') ? 'right' : 'left')
.html(true)
.title(uiTooltipHtml(t('background.description'), key));
uiBackground.togglePane = function() {
if (d3_event) d3_event.preventDefault();
paneTooltip.hide(_toggleButton);
context.ui().togglePanes(!_pane.classed('shown') ? _pane : undefined);
};
function hidePane() {
context.ui().togglePanes();
}
uiBackground.renderToggleButton = function(selection) {
_toggleButton = selection
.append('button')
.attr('tabindex', -1)
.on('click', uiBackground.togglePane)
.call(svgIcon('#iD-icon-layers', 'light'))
.call(paneTooltip);
};
uiBackground.renderPane = function(selection) {
_pane = selection
.append('div')
.attr('class', 'fillL map-pane background-pane hide')
.attr('pane', 'background');
var heading = _pane
.append('div')
.attr('class', 'pane-heading');
heading
.append('h2')
.text(t('background.title'));
heading
.append('button')
.on('click', hidePane)
.call(svgIcon('#iD-icon-close'));
var content = _pane
.append('div')
.attr('class', 'pane-content');
// background list
content
.append('div')
.attr('class', 'background-background-list-container')
.call(uiDisclosure(context, 'background_list', true)
.title(t('background.backgrounds'))
.content(renderBackgroundList)
);
// overlay list
content
.append('div')
.attr('class', 'background-overlay-list-container')
.call(uiDisclosure(context, 'overlay_list', true)
.title(t('background.overlays'))
.content(renderOverlayList)
);
// display options
_displayOptionsContainer = content
.append('div')
.attr('class', 'background-display-options');
// offset controls
_offsetContainer = content
.append('div')
.attr('class', 'background-offset');
// add listeners
context.map()
.on('move.background-update', _debounce(utilCallWhenIdle(update), 1000));
context.background()
.on('change.background-update', update);
update();
context.keybinding()
.on(key, uiBackground.togglePane)
.on(uiCmd('⌘' + key), quickSwitch);
};
return uiBackground;
}
|
var Bowline = require('bowline');
var adapter = {};
adapter.sensorName = 'twine';
adapter.types = [
{
id: 'string',
name: 'twine',
fields: {
timestamp: 'date',
celcius: 'float',
meta: {
sensor: 'string',
battery: 'string',
wifiSignal: 'string'
},
measureTime: {
age: 'float',
timestamp: 'integer'
},
values: {
batteryVoltage: 'float',
firmwareVersion: 'string',
isVibrating: 'boolean',
orientation: 'string',
temperature: 'integer',
updateMode: 'string',
vibration: 'integer'
}
}
}
];
adapter.promptProps = {
properties: {
email: {
description: 'Enter your Twine account (e-mail address)'.magenta
},
password: {
description: 'Enter your password'.magenta
},
deviceId: {
description: 'Enter your Twine device ID'.magenta
}
}
};
adapter.storeConfig = function(c8, result) {
return c8.config(result).then(function(){
console.log('Configuration stored.');
c8.release();
});
}
adapter.importData = function(c8, conf, opts) {
// console.log("1");
return new Promise(function (fulfill, reject){
// console.log("2");
if (conf.deviceId) {
// console.log("3");
let twine = new Bowline(conf);
twine.fetch(function(err, response){
// console.log("4");
if (err) {
reject(err);
return;
}
response.id = response.time.timestamp + '-' + conf.deviceId;
response.meta.sensor = conf.deviceId;
response.timestamp = new Date(response.time.timestamp * 1000);
response.measureTime = response.time;
response.values.isVibrating = response.values.isVibrating ? true : false;
response.celcius = (response.values.temperature - 32) * 5 / 9;
delete(response.time);
// console.log("5");
c8.insert(response).then(function(result) {
// console.log("6");
// console.log(result);
// console.log(response.timestamp + ': ' + result.result);
// console.log('Indexed ' + result.items.length + ' documents in ' + result.took + ' ms.');
fulfill(response.timestamp + ': ' + result.result)
}).catch(function(error) {
reject(error);
});
});
}
else {
reject('Configure first.');
}
});
};
module.exports = adapter;
|
'use strict';
(function(){
var ui = {};
function sortValues(a,b){
return a - b;
}
function uniq(a) {
return a.sort(sortValues).filter(function(item, pos, ary) {
return !pos || item != ary[pos - 1];
})
}
/**
* Constructor
*/
var Gauge = function(element, value, intervals, options) {
this.element = element;
this.value = value;
this.intervals = intervals;
//Sort and remove duplicated values
this.intervals.values = uniq(this.intervals.values);
this.colors = [];
this.options = options;
this.size;
this.svg;
this.inDrag = false;
this.outerRadius;
};
/**
* Convert from value to radians
*/
Gauge.prototype.valueToRadians = function(value, valueEnd, angleEnd, angleStart, valueStart) {
valueEnd = valueEnd || 100;
valueStart = valueStart || 0;
angleEnd = angleEnd || 360;
angleStart = angleStart || 0;
return (Math.PI/180) * ((((value - valueStart) * (angleEnd - angleStart)) / (valueEnd - valueStart)) + angleStart);
};
/**
* Convert from radians to value
*/
Gauge.prototype.radiansToValue = function(radians, valueEnd, valueStart, angleEnd, angleStart) {
valueEnd = valueEnd || 100;
valueStart = valueStart || 0;
angleEnd = angleEnd || 360;
angleStart = angleStart || 0;
return ((((((180/Math.PI) * radians) - angleStart) * (valueEnd - valueStart)) / (angleEnd - angleStart)) + valueStart);
};
/**
* Create the arc
*/
Gauge.prototype.createArc = function(innerRadius, outerRadius, startAngle, endAngle, cornerRadius) {
var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius)
.startAngle(startAngle)
.endAngle(endAngle)
.cornerRadius(cornerRadius);
return arc;
};
/**
* Draw the needle in the svg component
*/
Gauge.prototype.drawNeedle = function(svg, label, angle){
var data = [
"M " + this.size/2 + "," + this.size/10 +
"L " + (this.size/2 - this.size/2 * 0.02) + "," + this.size/2 +
"L " + (this.size/2 + this.size/2 * 0.02) + "," + this.size/2 +
"L " + this.size/2 + "," + this.size/10 +
"Z"
];
var elem = svg.append("path")
.attr('id', label)
.attr('d', data)
.attr("stroke", this.options.needleColor)
.attr("fill", this.options.needleColor)
.attr("transform", "rotate(" + angle + " " + this.size/2 + " " + this.size/2 + ")");
return elem;
};
/**
* Draw the needles's axis in the middle of the gauge
*/
Gauge.prototype.drawAxis = function(svg, label){
var elem = svg.append('circle')
.attr("id", label)
.attr("cx", this.size/2)
.attr("cy", this.size/2)
.attr("r", this.size*0.02)
.attr("fill", this.options.needleColor)
return elem;
};
/**
* Draw the arc
*/
Gauge.prototype.drawArc = function(svg, arc, label, style, click, drag) {
var elem = svg.append('path')
.attr('id', label)
.attr('d', arc)
.style(style)
.attr('transform', 'translate(' + (this.size / 2) + ', ' + (this.size / 2) + ')');
if(this.options.readOnly === false) {
if (click) {
elem.on('click', click);
}
if (drag) {
elem.call(drag);
}
}
return elem;
};
/**
* Create the arcs
*/
Gauge.prototype.createArcs = function() {
this.svg = d3.select(this.element)
.append('svg')
.attr({
"width": '100%',
"height": '100%'
});
this.size = Math.min(parseInt(this.svg.style("width"),10), parseInt(this.svg.style("height"),10));
this.svg.attr('viewBox', '0 0 '+this.size+' '+this.size);
this.outerRadius = parseInt((this.size / 2), 10);
var startAngle = this.valueToRadians(this.options.startAngle, 360),
endAngle = this.valueToRadians(this.options.endAngle, 360);
var trackInnerRadius = this.outerRadius - this.options.trackWidth,
changeInnerRadius = this.outerRadius - this.options.barWidth,
valueInnerRadius = this.outerRadius - this.options.barWidth,
interactInnerRadius = 1,
trackOuterRadius = this.outerRadius,
changeOuterRadius = this.outerRadius,
valueOuterRadius = this.outerRadius,
interactOuterRadius = this.outerRadius,
diff;
if(this.options.barWidth > this.options.trackWidth) {
diff = (this.options.barWidth - this.options.trackWidth) / 2;
trackInnerRadius -= diff;
trackOuterRadius -= diff;
} else if(this.options.barWidth < this.options.trackWidth) {
diff = (this.options.trackWidth - this.options.barWidth) / 2;
changeOuterRadius -= diff;
valueOuterRadius -= diff;
changeInnerRadius -= diff;
valueInnerRadius -= diff;
}
this.intervalArcs = [];
if(this.intervals.values.length != 0){
// Creating colors if no colors have been set
if(this.options.intervalColors.length == 0){
var v, hue, minHue=0, maxHue=120;
this.colors = [];
for(var i=0; i < this.intervals.values.length-1; i++){
v = (this.intervals.values[i] + this.intervals.values[i+1])/2;
hue = ((((v - this.options.min) * (maxHue - minHue)) / (this.options.max - this.options.min)) + minHue);
this.colors.push("hsl("+hue+",60%,50%)");
}
}
// Repeating colors if there are more values than colors
else if(this.options.intervalColors.length < this.intervals.values.length-1){
var colors = [];
for(var i=0; i < this.intervals.values.length - this.options.intervalColors.length-1; i++){
colors.push(this.options.intervalColors[i % this.options.intervalColors.length]);
}
this.colors = this.options.intervalColors.concat(colors);
}
// There are enough colors already
else{
this.colors = this.options.intervalColors.slice();
}
// Creating arcs
var intervalWidth = this.outerRadius/18 ;
for(var i=0; i < this.intervals.values.length-1; i++){
this.intervalArcs.push(this.createArc(this.outerRadius - intervalWidth, this.outerRadius,
this.valueToRadians(this.intervals.values[i], this.options.max, this.options.endAngle, this.options.startAngle, this.options.min),
this.valueToRadians(this.intervals.values[i+1], this.options.max, this.options.endAngle, this.options.startAngle, this.options.min)
));
}
}
if(this.options.bgColor) {
if(this.options.bgFull){
this.bgArc = this.createArc(0, this.outerRadius, 0, Math.PI*2);
}
else{
this.bgArc = this.createArc(0, this.outerRadius, startAngle, endAngle);
}
}
this.trackArc = this.createArc(trackInnerRadius, trackOuterRadius, startAngle, endAngle, this.options.trackCap);
this.changeArc = this.createArc(changeInnerRadius, changeOuterRadius, startAngle, startAngle, this.options.barCap);
this.valueArc = this.createArc(valueInnerRadius, valueOuterRadius, startAngle, startAngle, this.options.barCap);
this.interactArc = this.createArc(interactInnerRadius, interactOuterRadius, startAngle, endAngle);
};
/**
* Draw the arcs
*/
Gauge.prototype.drawArcs = function(clickInteraction, dragBehavior) {
// Draws the background arc
if(this.options.bgColor) {
this.drawArc(this.svg, this.bgArc, 'bgArc', { "fill": this.options.bgColor });
}
// Draws the intervals arcs
if(this.intervalArcs.length != 0){
for(var i in this.intervalArcs){
if(this.intervalArcs.hasOwnProperty(i)){
this.drawArc(this.svg, this.intervalArcs[i], 'intervalArc' + i, { "fill": this.colors[i] });
}
}
}
if(this.options.displayInput) {
// Display intervals
for(var i = 0; i < this.intervals.values.length; i++){
if(this.options.displayInput){
if(this.intervals.values.hasOwnProperty(i)){
var v = this.intervals.values[i];
if (typeof this.options.intervalFormatter === "function"){
v = this.options.intervalFormatter(v);
}
if(i < this.intervalArcs.length){
// get the start angle of the arc
var f = this.intervalArcs[i].startAngle();
}
else{
// get the end angle of the arc
var f = this.intervalArcs[i-1].endAngle();
}
var angle = (f() + Math.PI / 2);
var fontSize = (this.size*0.05) + "px";
this.svg.append('text')
.attr('id', 'intervalText'+i)
.attr('text-anchor', 'middle')
.attr('font-size', fontSize)
.attr('transform', 'translate(' + (this.size/2 - Math.cos(angle) * this.size/2.65) + ', ' + (this.size/2 - Math.sin(angle) * this.size/2.65) + ')')
.style('fill', this.options.textColor)
.text(v);
}
}
}
var fontSize = (this.size*0.20) + "px";
if(this.options.fontSize !== 'auto') {
fontSize = this.options.fontSize + "px";
}
if(this.options.step < 1) {
this.value = this.value.toFixed(1);
}
var v = this.value;
if (typeof this.options.mainFormatter === "function"){
v = this.options.mainFormatter(v);
}
this.svg.append('text')
.attr('id', 'text')
.attr("text-anchor", "middle")
.attr("font-size", fontSize)
.style("fill", this.options.textColor)
.text(v + this.options.unit || "")
.attr('transform', 'translate(' + ((this.size / 2)) + ', ' + ((this.size / 2) + (this.size*0.18)) + ')');
v = this.options.subText.text;
if (typeof this.options.subTextFormatter === "function"){
v = this.options.subTextFormatter(v);
}
if(this.options.subText.enabled) {
fontSize = (this.size*0.07) + "px";
if(this.options.subText.font !== 'auto') {
fontSize = this.options.subText.font + "px";
}
this.svg.append('text')
.attr('class', 'sub-text')
.attr("text-anchor", "middle")
.attr("font-size", fontSize)
.style("fill", this.options.subText.color)
.text(v)
.attr('transform', 'translate(' + ((this.size / 2)) + ', ' + ((this.size / 2) + (this.size*0.24)) + ')');
}
}
if(this.options.scale.enabled) {
var radius, quantity, count = 0, angle = 0, data,
startRadians = this.valueToRadians(this.options.min, this.options.max, this.options.endAngle, this.options.startAngle, this.options.min),
endRadians = this.valueToRadians(this.options.max, this.options.max, this.options.endAngle, this.options.startAngle, this.options.min),
diff = 0;
if(this.options.startAngle !== 0 || this.options.endAngle !== 360) {
diff = 1;
}
var height = this.outerRadius;
radius = (this.size / 2);
quantity = this.options.max+1;
data = d3.range(quantity).map(function () {
angle = (count * (endRadians - startRadians)) - (Math.PI / 2) + startRadians;
count = count + (1 / (quantity-diff));
return {
x1: radius + Math.cos(angle) * (radius - height*0.07),
y1: radius + Math.sin(angle) * (radius - height*0.07),
x2: radius + Math.cos(angle) * (radius - height*0.12),
y2: radius + Math.sin(angle) * (radius - height*0.12)
};
});
this.svg.selectAll("line.values")
.data(data)
.enter()
.append("line")
.attr({
x1: function (d) {
return d.x1;
},
y1: function (d) {
return d.y1;
},
x2: function (d) {
return d.x2;
},
y2: function (d) {
return d.y2;
},
"stroke-width": this.options.scale.width,
"stroke": this.options.scale.color
});
var outerrad = this.outerRadius;
radius = (this.size / 2);
data = [];
for(var i=0; i<this.intervals.values.length; i++){
angle = this.valueToRadians(this.intervals.values[i], this.options.max, this.options.endAngle, this.options.startAngle, this.options.min) - Math.PI / 2;
data.push({
x1: radius + Math.cos(angle) * (radius - outerrad*0.07),
y1: radius + Math.sin(angle) * (radius - outerrad*0.07),
x2: radius + Math.cos(angle) * (radius - outerrad*0.16),
y2: radius + Math.sin(angle) * (radius - outerrad*0.16)
});
}
this.svg.selectAll("line.intervals")
.data(data)
.enter()
.append("line")
.attr({
x1: function (d) {
return d.x1;
},
y1: function (d) {
return d.y1;
},
x2: function (d) {
return d.x2;
},
y2: function (d) {
return d.y2;
},
"stroke-width": this.options.scale.width*2,
"stroke": this.options.scale.color
});
}
this.drawArc(this.svg, this.trackArc, 'trackArc', { "fill": this.options.trackColor });
if(this.options.displayPrevious) {
this.changeElem = this.drawArc(this.svg, this.changeArc, 'changeArc', { "fill": this.options.prevBarColor });
} else {
this.changeElem = this.drawArc(this.svg, this.changeArc, 'changeArc', { "fill-opacity": 0 });
}
this.valueElem = this.drawArc(this.svg, this.valueArc, 'valueArc', { "fill": this.options.barColor });
var cursor = "pointer";
if(this.options.readOnly) {
cursor = "default";
}
this.drawArc(this.svg, this.interactArc, 'interactArc', { "fill-opacity": 0, "cursor": cursor }, clickInteraction, dragBehavior);
// Draw the needle
var value = this.valueToRadians(this.value, this.options.max, this.options.endAngle, this.options.startAngle, this.options.min) * 180/Math.PI;
this.valueNeedle = this.drawNeedle(this.svg, 'needle', value);
this.drawAxis(this.svg, 'axis');
};
/**
* Draw gauge component
*/
Gauge.prototype.draw = function(update) {
d3.select(this.element).select("svg").remove();
var that = this;
that.createArcs();
var dragBehavior = d3.behavior.drag()
.on('drag', dragInteraction)
.on('dragend', clickInteraction);
that.drawArcs(clickInteraction, dragBehavior);
if(that.options.animate.enabled) {
that.valueElem.transition().ease(that.options.animate.ease).duration(that.options.animate.duration).tween('',function() {
var i = d3.interpolate(that.valueToRadians(that.options.startAngle, 360), that.valueToRadians(that.value, that.options.max, that.options.endAngle, that.options.startAngle, that.options.min));
return function(t) {
var val = i(t);
that.valueElem.attr('d', that.valueArc.endAngle(val));
that.changeElem.attr('d', that.changeArc.endAngle(val));
// Update the needle's position
var angle = val * 180/Math.PI;
that.valueNeedle.attr("transform", "rotate(" + angle + " " + that.size/2 + " " + that.size/2 + ")");
};
});
} else {
that.changeArc.endAngle(this.valueToRadians(this.value, this.options.max, this.options.endAngle, this.options.startAngle, this.options.min));
that.changeElem.attr('d', that.changeArc);
that.valueArc.endAngle(this.valueToRadians(this.value, this.options.max, this.options.endAngle, this.options.startAngle, this.options.min));
that.valueElem.attr('d', that.valueArc);
}
function dragInteraction() {
that.inDrag = true;
var x = d3.event.x - (that.size / 2);
var y = d3.event.y - (that.size / 2);
interaction(x,y, false);
}
function clickInteraction() {
that.inDrag = false;
var coords = d3.mouse(this.parentNode);
var x = coords[0] - (that.size / 2);
var y = coords[1] - (that.size / 2);
interaction(x,y, true);
}
function interaction(x,y, isFinal) {
var arc = Math.atan(y/x)/(Math.PI/180), radians, delta;
if ((x >= 0 && y <= 0) || (x >= 0 && y >= 0)) {
delta = 90;
} else {
delta = 270;
if(that.options.startAngle < 0) {
delta = -90;
}
}
radians = (delta + arc) * (Math.PI/180);
that.value = that.radiansToValue(radians, that.options.max, that.options.min, that.options.endAngle, that.options.startAngle);
if(that.value >= that.options.min && that.value <= that.options.max) {
that.value = Math.round(((~~ (((that.value < 0) ? -0.5 : 0.5) + (that.value/that.options.step))) * that.options.step) * 100) / 100;
if(that.options.step < 1) {
that.value = that.value.toFixed(1);
}
update(that.value);
that.valueArc.endAngle(that.valueToRadians(that.value, that.options.max, that.options.endAngle, that.options.startAngle, that.options.min));
that.valueElem.attr('d', that.valueArc);
// Update the needle's position
var angle = that.valueToRadians(that.value, that.options.max, that.options.endAngle, that.options.startAngle, that.options.min) * 180/Math.PI;
that.valueNeedle.attr("transform", "rotate(" + angle + " " + that.size/2 + " " + that.size/2 + ")");
if (isFinal) {
that.changeArc.endAngle(that.valueToRadians(that.value, that.options.max, that.options.endAngle, that.options.startAngle, that.options.min));
that.changeElem.attr('d', that.changeArc);
}
if(that.options.displayInput) {
var v = that.value;
if (typeof that.options.mainFormatter === "function"){
v = that.options.mainFormatter(v);
}
d3.select(that.element).select('#text').text(v + that.options.unit || "");
}
}
}
};
/**
* Set a value
*/
Gauge.prototype.setValue = function(newValue) {
if ((!this.inDrag) && this.value >= this.options.min && this.value <= this.options.max) {
var radians = this.valueToRadians(newValue, this.options.max, this.options.endAngle, this.options.startAngle, this.options.min);
this.value = Math.round(((~~ (((newValue < 0) ? -0.5 : 0.5) + (newValue/this.options.step))) * this.options.step) * 100) / 100;
if(this.options.step < 1) {
this.value = this.value.toFixed(1);
}
this.changeArc.endAngle(radians);
d3.select(this.element).select('#changeArc').attr('d', this.changeArc);
this.valueArc.endAngle(radians);
d3.select(this.element).select('#valueArc').attr('d', this.valueArc);
// Update the needle's position
var angle = this.valueToRadians(this.value, this.options.max, this.options.endAngle, this.options.startAngle, this.options.min) * 180/Math.PI;
this.valueNeedle.attr("transform", "rotate(" + angle + " " + this.size/2 + " " + this.size/2 + ")");
if(this.options.displayInput) {
var v = this.value;
if (typeof this.options.mainFormatter === "function"){
v = this.options.mainFormatter(v);
}
d3.select(this.element).select('#text').text(v + this.options.unit || "");
}
}
};
ui.Gauge = Gauge;
/**
* Angular gauge directive
*/
ui.gaugeDirective = function() {
return {
restrict: 'E',
scope: {
value: '=',
intervals: '=',
options: '='
},
link: function (scope, element) {
scope.value = scope.value || 0;
var defaultIntervals = {
values : [],
};
scope.intervals = angular.merge(defaultIntervals, scope.intervals);
var defaultOptions = {
needleColor: 'grey',
min: 0,
max: 100,
startAngle:-120,
endAngle:120,
intervalColors: [],
animate: {
enabled: true,
duration: 1000,
ease: 'bounce'
},
unit: "",
displayInput: true,
mainFormatter: function(v){return "main " + v;},
subTextFormatter: function(v){return "sub " + v;},
intervalFormatter: function(v){return "intr" + v;},
readOnly: true,
trackWidth: 0,
barWidth: 0,
trackColor: "rgba(0,0,0,0)",
barColor: "rgba(255,0,0,.5)",
prevBarColor: "rgba(0,0,0,0)",
textColor: '#212121',
fontSize: 'auto',
subText: {
enabled: false,
text: "",
color: "grey",
font: "auto"
},
scale: {
enabled: true,
color: 'gray',
width: 1,
},
step: 1,
displayPrevious: false,
dynamicOptions: false
};
scope.options = angular.merge(defaultOptions, scope.options);
var gauge = new ui.Gauge(element[0], scope.value, scope.intervals, scope.options);
scope.$watch('value', function(newValue, oldValue) {
if((newValue !== null || typeof newValue !== 'undefined') && typeof oldValue !== 'undefined' && newValue !== oldValue) {
gauge.setValue(newValue);
}
});
var isFirstWatchOnIntervals = true;
scope.$watch('intervals', function() {
if (isFirstWatchOnIntervals) {
isFirstWatchOnIntervals = false;
} else {
var newIntervals = angular.merge(defaultIntervals, scope.intervals);
gauge = new ui.Gauge(element[0], scope.value, newIntervals, scope.options);
drawGauge();
}
}, true);
if(scope.options.dynamicOptions) {
var isFirstWatchOnOptions = true;
scope.$watch('options', function() {
if (isFirstWatchOnOptions) {
isFirstWatchOnOptions = false;
} else {
var newOptions = angular.merge(defaultOptions, scope.options);
gauge = new ui.Gauge(element[0], scope.value, scope.intervals, newOptions);
drawGauge();
}
}, true);
}
var drawGauge = function(){
gauge.draw(function(value) {
scope.$apply(function() {
scope.value = value;
});
});
};
drawGauge();
}
};
};
angular.module('ui.gauge', []).directive('uiGauge', ui.gaugeDirective);
})();
|
import {List, Map} from 'immutable'
import {expect} from 'chai'
import {setEntries} from '../src/core'
describe('Application logic', () => {
describe('setEntries', () => {
it('adds the entries to the state', () => {
const state = Map()
const entries = List.of('Trainspotting')
const nextState = setEntries(state, entries);
expect(nextState).to.equal(Map({
entries: List.of('Trainspotting')
}))
})
})
}) |
'use strict';
const findPkgDir = require('find-pkg-dir');
const npmCliPath = require('npm-cli-path');
let path;
const firstTry = (async () => {
try {
path = findPkgDir(await npmCliPath());
} catch {
return false;
}
return true;
})();
module.exports = async function npmCliDir() {
if (!path && !await firstTry) {
path = findPkgDir(await npmCliPath());
}
return path;
};
|
// To make obj fully immutable, freeze each object in obj.
// Also makes Array, Map and Set read-only.
export default function deepFreeze(obj) {
if (obj instanceof Map) {
obj.clear = obj.delete = obj.set = function () {
throw new Error('map is read-only');
};
} else if (obj instanceof Set) {
obj.add = obj.clear = obj.delete = function () {
throw new Error('set is read-only');
};
}
Object.getOwnPropertyNames(obj).forEach((name) => {
let prop = obj[name];
// Freeze prop if it is an object
if (typeof prop == 'object' && !Object.isFrozen(prop)) {
deepFreeze(prop);
}
});
// Freeze self
return Object.freeze(obj);
}
|
import { randRange } from '../utils'
function addIndices(result, sampleSize, nodes, recursionLimit, _recursiveCalls) {
// TODO: verify that this handles empty arrays, falsey values, etc.
let recursiveCalls = _recursiveCalls || 0
for (let i = 0; i < sampleSize; i++) {
const randIndex = randRange(0, nodes.length - 1)
if (result.indexOf(nodes[randIndex]) < 0) {
recursiveCalls = 0
result.push(nodes[randIndex])
} else {
// recurse to find unique index to add. pass `sampleSize` as 1 since it'll call itself
recursiveCalls += 1
if (recursiveCalls >= recursionLimit) {
throw new Error('Exceeded stack limit')
}
addIndices(result, 1, nodes, recursionLimit, recursiveCalls)
}
}
return result
}
// sample:
// [ [ 1, 2, 3, 4, 5 ], [ 1, 2, 3, 4, 5, 6, 7, 8 ], [ 1, 2, 3 ], [] ]
// get rand between
function getIndices(nodes, { minSample, maxSample, limit }) {
// select between min-max% of the indices from nodes
const pct = randRange(minSample * 100, maxSample * 100) / 100 // get multiplier
const sampleSize = Math.ceil(nodes.length * pct) // get number of indices to add
// create a new array of random indices
// sample:
// [ [ 5, 4, 3 ], [ 1, 4, 8, 2 ], [ 3 ], [] ]
const result = []
let err = null
try {
addIndices(result, sampleSize, nodes, limit)
} catch (e) {
err = e
}
return err || result
}
function randBoundaries(options = {}, done) {
const defaults = {
minSample: 0.25, // % of indices to collect, default 25-50%
maxSample: 0.5,
limit: 10, // number of recursive calls to run when looking for unique key
nodes: [], // TODO: required, should throw if not passed in
}
// // TODO: use callback with above two fns as walker
// const settings = Object.assign({}, defaults, options)
// return factory(settings, done)
const settings = Object.assign({}, defaults, options)
const { nodes } = settings
const map = nodes.map(_ => getIndices(_, settings))
let err = null
if (done && typeof done === 'function') {
return done(err, map)
}
return err || map
}
export default randBoundaries
|
require('babel-register');
var app = require('express')();
var serveStatic = require('serve-static');
var ejs = require('consolidate').ejs;
var routes = require('./routes');
app.engine('html', ejs);
app.set('view engine', 'html');
app.set('views', '.');
// Register routes
routes(app);
// Serve static assets
app.use('/static', serveStatic('.'));
// Start server
app.listen('1234', function () {
console.log('Listening on 1234');
});
|
import Promise from 'bluebird';
import moment from 'moment';
export default class Sender {
// https://github.com/justintv/Twitch-API/blob/master/IRC.md#command--message-limit
static interval = {
mod: moment.duration(30, 'seconds').asMilliseconds() / 100,
user: moment.duration(30, 'seconds').asMilliseconds() / 20
};
async limit(server) {
while (this.limiter.has(server)) {
await this.limiter.get(server);
}
const interval = Sender.interval[server.rate] || Sender.interval.user;
this.limiter.set(server, Promise.delay(interval).then(() => {
this.limiter.delete(server);
}));
}
// sends all messages in source as soon as it safe and
// resolves after sending the last message
async send(server, send, transform, ...source) {
if (typeof transform !== 'function') {
source.unshift(transform);
transform = (...args) => args;
}
while (this.sends.has(server)) {
await this.sends.get(server);
}
this.sends.set(server, (async () => {
try {
let data = source;
const stack = [];
do {
// keep track of how deep the sent message is so
// the hierarchy can be emptied upwards
while (typeof data[0] !== 'string') {
stack.push(data);
data = data[0];
}
await this.limit(server);
// send
await send(...transform(...data));
// empty the sent array
do {
data.shift()
} while (data.length);
if (stack.length) {
data = stack.pop();
data.shift();
}
} while (data.length);
} finally {
this.sends.delete(server);
}
})());
return this.sends.get(server);
}
limiter = new Map();
sends = new Map();
}
|
var inherits = require('inherits');
function Model(){}
var undef = function(val){
return typeof val === 'undefined' || val === null;
};
var falsey = function(val){
switch(typeof val){
case 'string':
return val !== 'false' && val !== '';
default:
return !!val;
}
};
var setProperties = function(schema,model,defaults){
Object.keys(schema || {}).forEach(function(name){
var property = schema[name];
if(typeof property === 'function' || typeof property === 'string'){
var obj = {};
switch (property){
case Boolean:
case String:
case Number:
case 'Any':
obj.type = property;
}
property = obj;
}
if(typeof property !== 'object'){
throw new Error('Tried to initialize a property with an invalid value : ' + (model && model.constructor.prototype.name) + '.' + name);
}
if(property.type){
var getter = function(){
if(property.get){
return property.get.call(this);
} else {
return defaults[name];
}
};
var setter = function(val){
if(!undef(val) && property.type !== 'Any' && val.constructor !== property.type){
switch(property.type){
case Boolean:
val = falsey(val);
break;
case Number:
val = parseFloat(val,10);
break;
case String:
val = val.toString();
break;
}
}
if(property.set){
property.set.call(this,val);
} else {
defaults[name] = val;
}
};
Object.defineProperty(model,name,{
get : getter,
set : setter,
enumerable : true,
configurable : true
});
// define the default value if it exists
if(defaults[name]){
model[name] = defaults[name];
}
} else {
model[name] = setProperties(schema[name],model[name],defaults[name]);
}
});
return model;
};
var toObject = function(){
var model = this;
var object = Object.keys(model).reduce(function(o,key){
var val = model[key];
if(typeof val !== 'undefined' && val !== ''){
o[key] = val;
}
return o;
},{});
return object;
};
module.exports = function(name,schema,collection){
if(typeof name !== 'string') throw new Error('You must provide a name when creating a new model.');
if(typeof schema !== 'object') throw new Error('You must provide a schema object when creating a new model.');
if(typeof collection !== 'string') throw new Error('You must provide a collection name when creating a new model.');
var SubModel = function(object){
var sub = Model.call(this);
var values = object || {};
setProperties(schema,this,values);
return sub;
};
inherits(SubModel, Model);
SubModel.prototype.schema = schema;
SubModel.prototype.collection = collection;
SubModel.prototype.toObject = toObject;
SubModel.subclass = function(){
var SubClass = function(obj){
return SubModel.call(this,obj);
};
inherits(SubClass,SubModel);
return SubClass;
};
return SubModel;
};
|
/* *************************************************
// Copyright 2010-2012, Anthony Hand
//
// BETA NOTICE
// Previous versions of the JavaScript code for MobileESP were 'regular'
// JavaScript. The strength of it was that it was really easy to code and use.
// Unfortunately, regular JavaScript means that all variables and functions
// are in the global namespace. There can be collisions with other code libraries
// which may have similar variable or function names. Collisions cause bugs as each
// library changes a variable's definition or functionality unexpectedly.
// As a result, we thought it wise to switch to an "object oriented" style of code.
// This 'literal notation' technique keeps all MobileESP variables and functions fully self-contained.
// It avoids potential for collisions with other JavaScript libraries.
// This technique allows the developer continued access to any desired function or property.
//
// This beta testing period is temporary. Please monitor the www.MobileESP.org web site
// for the latest announcements. When the testing period is over, the switch to the Object Oriented
// model will be announced on the web site.
// Please send feedback to project founder Anthony Hand: anthony.hand@gmail.com
//
//
//
// File version 2012.07.22 (July 22, 2012)
// - Switched to an Object-Oriented programming model using the literal notation technique.
// - NOTE: The literal notation technique allows only 1 instance of this object per web page.
// - Named the JavaScript object "MobileEsp" rather than the old "mDetect."
// - Applied many small tweaks and a few refactorings. The most notable ones are listed here...
// - Added a variable for Obigo, an embedded browser. Added a lookup for Obigo to DetectMobileQuick().
// - Added global variables for quick access to these very useful Boolean values:
// - IsWebkit, IsMobilePhone, IsIphone, IsAndroid, IsAndroidPhone, IsTierTablet, IsTierIphone, IsTierRichCss, IsTierGenericMobile
// - Updated & simplified DetectSonyMylo(). Updated the variable mylocom2's value to handle both versions.
// - Removed the variable qtembedded, which was only used in Mylo and unnecessary.
// - Simplified OperaMobile().
// - Reorganized DetectMobileQuick().
// - Moved the following from DetectMobileQuick() to DetectMobileLong():
// - DetectDangerHiptop(), DetectMaemoTablet(), DetectGarminNuvifone(), devicePda
// - Added DetectBada(). Added it to DetectSmartphone & iPhone Tier, too.
// - Updated DetectSymbian() to support Opera Mobile 10.
// - Removed variable for OpenWeb. Removed its detection from DetectMobileQuick().
// It's not clear whether Sprint is still using the OpenWeb transcoding service from OpenWave.
//
//
//
// LICENSE INFORMATION
// 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.
//
//
// ABOUT THIS PROJECT
// Project Owner: Anthony Hand
// Email: anthony.hand@gmail.com
// Web Site: http://www.mobileesp.com
// Source Files: http://code.google.com/p/mobileesp/
// blog announcement: http://blog.mobileesp.com/?p=306
//
// Versions of this code are available for:
// PHP, JavaScript, Java, ASP.NET (C#), Ruby and others
//
//
// WARNING:
// These JavaScript-based device detection features may ONLY work
// for the newest generation of smartphones, such as the iPhone,
// Android and Palm WebOS devices.
// These device detection features may NOT work for older smartphones
// which had poor support for JavaScript, including
// older BlackBerry, PalmOS, and Windows Mobile devices.
// Additionally, because JavaScript support is extremely poor among
// 'feature phones', these features may not work at all on such devices.
// For better results, consider using a server-based version of this code,
// such as Java, APS.NET, PHP, or Ruby.
//
// *******************************************
*/
var MobileEsp = {
//GLOBALLY USEFUL VARIABLES
//Note: These values are set automatically during the Init function.
//Stores whether we're currently initializing the most popular functions.
InitCompleted : false,
//Stores whether the browser is WebKit-based on *ANY* device (mobile, laptop, PC, etc.).
IsWebkit : false,
//Stores whether the device is *ANY* mobile phone (excludes tablets).
IsMobilePhone : false,
//Stores whether the device is an iPhone or iPod Touch.
IsIphone : false,
//Stores whether the device is *ANY* Android device.
IsAndroid : false,
//Stores whether the device is an Android phone or multi-media player.
IsAndroidPhone : false,
//Stores whether is the Tablet (HTML5-capable, larger screen) tier of devices.
IsTierTablet : false,
//Stores whether is the iPhone Tier of devices, including Android, Windows Phone 7 and WebOS phones.
IsTierIphone : false,
//Stores whether the device can probably support Rich CSS, but JavaScript support is NOT assumed. (e.g., Symbian, newer BlackBerry)
IsTierRichCss : false,
//Stores whether it is another mobile device, which cannot be assumed to support CSS or JS (eg, Feature Phones, older BlackBerries)
IsTierGenericMobile : false,
//INTERNALLY USED DETECTION STRING VARIABLES
engineWebKit : 'webkit',
deviceIphone : 'iphone',
deviceIpod : 'ipod',
deviceIpad : 'ipad',
deviceMacPpc : 'macintosh', //Used for disambiguation
deviceAndroid : 'android',
deviceGoogleTV : 'googletv',
deviceXoom : 'xoom', //Motorola Xoom
deviceHtcFlyer : 'htc_flyer', //HTC Flyer
deviceNuvifone : 'nuvifone', //Garmin Nuvifone
deviceSymbian : 'symbian',
deviceSymbos : 'symbos', //Opera 10 on Symbian
deviceS60 : 'series60',
deviceS70 : 'series70',
deviceS80 : 'series80',
deviceS90 : 'series90',
deviceWinPhone7 : 'windows phone os 7',
deviceWinMob : 'windows ce',
deviceWindows : 'windows',
deviceIeMob : 'iemobile',
devicePpc : 'ppc', //Stands for PocketPC
enginePie : 'wm5 pie', //An old Windows Mobile
deviceBB : 'blackberry',
vndRIM : 'vnd.rim', //Detectable when BB devices emulate IE or Firefox
deviceBBStorm : 'blackberry95', //Storm 1 and 2
deviceBBBold : 'blackberry97', //Bold 97x0 (non-touch)
deviceBBBoldTouch : 'blackberry 99', //Bold 99x0 (touchscreen)
deviceBBTour : 'blackberry96', //Tour
deviceBBCurve : 'blackberry89', //Curve 2
deviceBBCurveTouch : 'blackberry 938', //Curve Touch 9380
deviceBBTorch : 'blackberry 98', //Torch
deviceBBPlaybook : 'playbook', //PlayBook tablet
devicePalm : 'palm',
deviceWebOS : 'webos', //For Palm's line of WebOS devices
deviceWebOShp : 'hpwos', //For HP's line of WebOS devices
deviceBada : 'bada', //Samsung's line of Bada OS devices
engineBlazer : 'blazer', //Old Palm browser
engineXiino : 'xiino',
deviceKindle : 'kindle', //Amazon eInk Kindle
engineSilk : 'silk', //Amazon's accelerated Silk browser for Kindle Fire
//Initialize variables for mobile-specific content.
vndwap : 'vnd.wap',
wml : 'wml',
//Initialize variables for random devices and mobile browsers.
//Some of these may not support JavaScript
deviceTablet : 'tablet', //Generic term for slate and tablet devices
deviceBrew : 'brew',
deviceDanger : 'danger',
deviceHiptop : 'hiptop',
devicePlaystation : 'playstation',
deviceNintendoDs : 'nitro',
deviceNintendo : 'nintendo',
deviceWii : 'wii',
deviceXbox : 'xbox',
deviceArchos : 'archos',
engineOpera : 'opera', //Popular browser
engineNetfront : 'netfront', //Common embedded OS browser
engineUpBrowser : 'up.browser', //common on some phones
deviceMidp : 'midp', //a mobile Java technology
uplink : 'up.link',
engineTelecaQ : 'teleca q', //a modern feature phone browser
engineObigo : 'obigo', //W 10 is a modern feature phone browser
devicePda : 'pda',
mini : 'mini', //Some mobile browsers put 'mini' in their names
mobile : 'mobile', //Some mobile browsers put 'mobile' in their user agent strings
mobi : 'mobi', //Some mobile browsers put 'mobi' in their user agent strings
//Use Maemo, Tablet, and Linux to test for Nokia's Internet Tablets.
maemo : 'maemo',
linux : 'linux',
mylocom2 : 'sony/com', // for Sony Mylo 1 and 2
//In some UserAgents, the only clue is the manufacturer
manuSonyEricsson : 'sonyericsson',
manuericsson : 'ericsson',
manuSamsung1 : 'sec-sgh',
manuSony : 'sony',
manuHtc : 'htc', //Popular Android and WinMo manufacturer
//In some UserAgents, the only clue is the operator
svcDocomo : 'docomo',
svcKddi : 'kddi',
svcVodafone : 'vodafone',
//Disambiguation strings.
disUpdate : 'update', //pda vs. update
//Holds the User Agent string value.
uagent : '',
//Initializes key MobileEsp variables
InitDeviceScan : function() {
this.InitCompleted = false;
if (navigator && navigator.userAgent)
this.uagent = navigator.userAgent.toLowerCase();
//Save these 4 properties to speed processing
this.IsWebkit = this.DetectWebkit();
this.IsIphone = this.DetectIphone();
this.IsAndroid = this.DetectAndroid();
this.IsAndroidPhone = this.DetectAndroidPhone();
//Generally, these 3 tiers are the most useful for web development
this.IsTierTablet = this.DetectTierTablet();
this.IsMobilePhone = this.DetectMobileQuick();
this.IsTierIphone = this.DetectTierIphone();
//Comment out these 2 to save time if you don't need these tiers
this.IsTierRichCss = this.DetectTierRichCss();
this.IsTierGenericMobile = this.DetectTierOtherPhones();
this.InitCompleted = true;
},
//APPLE IOS
//**************************
// Detects if the current device is an iPhone.
DetectIphone : function() {
if (this.InitCompleted || this.IsIphone)
return this.IsIphone;
if (this.uagent.search(this.deviceIphone) > -1)
{
//The iPad and iPod Touch say they're an iPhone! So let's disambiguate.
if (this.DetectIpad() || this.DetectIpod())
return false;
//Yay! It's an iPhone!
else
return true;
}
else
return false;
},
//**************************
// Detects if the current device is an iPod Touch.
DetectIpod : function() {
if (this.uagent.search(this.deviceIpod) > -1)
return true;
else
return false;
},
//**************************
// Detects if the current device is an iPhone or iPod Touch.
DetectIphoneOrIpod : function() {
//We repeat the searches here because some iPods
// may report themselves as an iPhone, which is ok.
if (this.uagent.search(this.deviceIphone) > -1 ||
this.uagent.search(this.deviceIpod) > -1)
return true;
else
return false;
},
//**************************
// Detects if the current device is an iPad tablet.
DetectIpad : function() {
if (this.uagent.search(this.deviceIpad) > -1 && this.DetectWebkit())
return true;
else
return false;
},
//**************************
// Detects *any* iOS device: iPhone, iPod Touch, iPad.
DetectIos : function() {
if (this.DetectIphoneOrIpod() || this.DetectIpad())
return true;
else
return false;
},
//ANDROID
//**************************
// Detects *any* Android OS-based device: phone, tablet, and multi-media player.
// Also detects Google TV.
DetectAndroid : function() {
if (this.InitCompleted || this.IsAndroid)
return this.IsAndroid;
if ((this.uagent.search(this.deviceAndroid) > -1) || this.DetectGoogleTV())
return true;
//Special check for the HTC Flyer 7" tablet. It should report here.
if (this.uagent.search(this.deviceHtcFlyer) > -1)
return true;
else
return false;
},
//**************************
// Detects if the current device is a (small-ish) Android OS-based device
// used for calling and/or multi-media (like a Samsung Galaxy Player).
// Google says these devices will have 'Android' AND 'mobile' in user agent.
// Ignores tablets (Honeycomb and later).
DetectAndroidPhone : function() {
if (this.InitCompleted || this.IsAndroidPhone)
return this.IsAndroidPhone;
if (this.DetectAndroid() && (this.uagent.search(this.mobile) > -1))
return true;
//Special check for Android phones with Opera Mobile. They should report here.
if (this.DetectOperaAndroidPhone())
return true;
//Special check for the HTC Flyer 7" tablet. It should report here.
if (this.uagent.search(this.deviceHtcFlyer) > -1)
return true;
else
return false;
},
//**************************
// Detects if the current device is a (self-reported) Android tablet.
// Google says these devices will have 'Android' and NOT 'mobile' in their user agent.
DetectAndroidTablet : function() {
//First, let's make sure we're on an Android device.
if (!this.DetectAndroid())
return false;
//Special check for Opera Android Phones. They should NOT report here.
if (this.DetectOperaMobile())
return false;
//Special check for the HTC Flyer 7" tablet. It should NOT report here.
if (this.uagent.search(this.deviceHtcFlyer) > -1)
return false;
//Otherwise, if it's Android and does NOT have 'mobile' in it, Google says it's a tablet.
if (this.uagent.search(this.mobile) > -1)
return false;
else
return true;
},
//**************************
// Detects if the current device is an Android OS-based device and
// the browser is based on WebKit.
DetectAndroidWebKit : function() {
if (this.DetectAndroid() && this.DetectWebkit())
return true;
else
return false;
},
//**************************
// Detects if the current device is a GoogleTV.
DetectGoogleTV : function() {
if (this.uagent.search(this.deviceGoogleTV) > -1)
return true;
else
return false;
},
//**************************
// Detects if the current browser is based on WebKit.
DetectWebkit : function() {
if (this.InitCompleted || this.IsWebkit)
return this.IsWebkit;
if (this.uagent.search(this.engineWebKit) > -1)
return true;
else
return false;
},
//SYMBIAN
//**************************
// Detects if the current browser is the Nokia S60 Open Source Browser.
DetectS60OssBrowser : function() {
if (this.DetectWebkit())
{
if ((this.uagent.search(this.deviceS60) > -1 ||
this.uagent.search(this.deviceSymbian) > -1))
return true;
else
return false;
}
else
return false;
},
//**************************
// Detects if the current device is any Symbian OS-based device,
// including older S60, Series 70, Series 80, Series 90, and UIQ,
// or other browsers running on these devices.
DetectSymbianOS : function() {
if (this.uagent.search(this.deviceSymbian) > -1 ||
this.uagent.search(this.deviceS60) > -1 ||
((this.uagent.search(this.deviceSymbos) > -1) &&
(this.DetectOperaMobile)) || //Opera 10
this.uagent.search(this.deviceS70) > -1 ||
this.uagent.search(this.deviceS80) > -1 ||
this.uagent.search(this.deviceS90) > -1)
return true;
else
return false;
},
//WINDOWS MOBILE AND PHONE
//**************************
// Detects if the current browser is a Windows Phone 7 device.
DetectWindowsPhone7 : function() {
if (this.uagent.search(this.deviceWinPhone7) > -1)
return true;
else
return false;
},
//**************************
// Detects if the current browser is a Windows Mobile device.
// Excludes Windows Phone 7 devices.
// Focuses on Windows Mobile 6.xx and earlier.
DetectWindowsMobile : function() {
//Exclude new Windows Phone 7.
if (this.DetectWindowsPhone7())
return false;
//Most devices use 'Windows CE', but some report 'iemobile'
// and some older ones report as 'PIE' for Pocket IE.
if (this.uagent.search(this.deviceWinMob) > -1 ||
this.uagent.search(this.deviceIeMob) > -1 ||
this.uagent.search(this.enginePie) > -1)
return true;
//Test for Windows Mobile PPC but not old Macintosh PowerPC.
if ((this.uagent.search(this.devicePpc) > -1) &&
!(this.uagent.search(this.deviceMacPpc) > -1))
return true;
//Test for Windwos Mobile-based HTC devices.
if (this.uagent.search(this.manuHtc) > -1 &&
this.uagent.search(this.deviceWindows) > -1)
return true;
else
return false;
},
//BLACKBERRY
//**************************
// Detects if the current browser is a BlackBerry of some sort.
// Includes the PlayBook.
DetectBlackBerry : function() {
if ((this.uagent.search(this.deviceBB) > -1) ||
(this.uagent.search(this.vndRIM) > -1))
return true;
else
return false;
},
//**************************
// Detects if the current browser is on a BlackBerry tablet device.
// Example: PlayBook
DetectBlackBerryTablet : function() {
if (this.uagent.search(this.deviceBBPlaybook) > -1)
return true;
else
return false;
},
//**************************
// Detects if the current browser is a BlackBerry device AND uses a
// WebKit-based browser. These are signatures for the new BlackBerry OS 6.
// Examples: Torch. Includes the Playbook.
DetectBlackBerryWebKit : function() {
if (this.DetectBlackBerry() &&
this.uagent.search(this.engineWebKit) > -1)
return true;
else
return false;
},
//**************************
// Detects if the current browser is a BlackBerry Touch
// device, such as the Storm, Torch, and Bold Touch. Excludes the Playbook.
DetectBlackBerryTouch : function() {
if (this.DetectBlackBerry() &&
((this.uagent.search(this.deviceBBStorm) > -1) ||
(this.uagent.search(this.deviceBBTorch) > -1) ||
(this.uagent.search(this.deviceBBBoldTouch) > -1) ||
(this.uagent.search(this.deviceBBCurveTouch) > -1) ))
return true;
else
return false;
},
//**************************
// Detects if the current browser is a BlackBerry OS 5 device AND
// has a more capable recent browser. Excludes the Playbook.
// Examples, Storm, Bold, Tour, Curve2
// Excludes the new BlackBerry OS 6 and 7 browser!!
DetectBlackBerryHigh : function() {
//Disambiguate for BlackBerry OS 6 or 7 (WebKit) browser
if (this.DetectBlackBerryWebKit())
return false;
if ((this.DetectBlackBerry()) &&
(this.DetectBlackBerryTouch() ||
this.uagent.search(this.deviceBBBold) > -1 ||
this.uagent.search(this.deviceBBTour) > -1 ||
this.uagent.search(this.deviceBBCurve) > -1))
return true;
else
return false;
},
//**************************
// Detects if the current browser is a BlackBerry device AND
// has an older, less capable browser.
// Examples: Pearl, 8800, Curve1.
DetectBlackBerryLow : function() {
if (this.DetectBlackBerry())
{
//Assume that if it's not in the High tier or has WebKit, then it's Low.
if (this.DetectBlackBerryHigh() || this.DetectBlackBerryWebKit())
return false;
else
return true;
}
else
return false;
},
//WEBOS AND PALM
//**************************
// Detects if the current browser is on a PalmOS device.
DetectPalmOS : function() {
//Make sure it's not WebOS first
if (this.DetectPalmWebOS())
return false;
//Most devices nowadays report as 'Palm',
// but some older ones reported as Blazer or Xiino.
if (this.uagent.search(this.devicePalm) > -1 ||
this.uagent.search(this.engineBlazer) > -1 ||
this.uagent.search(this.engineXiino) > -1)
return true;
else
return false;
},
//**************************
// Detects if the current browser is on a Palm device
// running the new WebOS.
DetectPalmWebOS : function()
{
if (this.uagent.search(this.deviceWebOS) > -1)
return true;
else
return false;
},
//**************************
// Detects if the current browser is on an HP tablet running WebOS.
DetectWebOSTablet : function() {
if (this.uagent.search(this.deviceWebOShp) > -1 &&
this.uagent.search(this.deviceTablet) > -1)
return true;
else
return false;
},
//OPERA
//**************************
// Detects if the current browser is Opera Mobile or Mini.
// Note: Older embedded Opera on mobile devices didn't follow these naming conventions.
// Like Archos media players, they will probably show up in DetectMobileQuick or -Long instead.
DetectOperaMobile : function() {
if ((this.uagent.search(this.engineOpera) > -1) &&
((this.uagent.search(this.mini) > -1 ||
this.uagent.search(this.mobi) > -1)))
return true;
else
return false;
},
//**************************
// Detects if the current browser is Opera Mobile
// running on an Android phone.
DetectOperaAndroidPhone : function () {
if ((this.uagent.search(this.engineOpera) > -1) &&
(this.uagent.search(this.deviceAndroid) > -1) &&
(this.uagent.search(this.mobi) > -1))
return true;
else
return false;
},
//**************************
// Detects if the current browser is Opera Mobile
// running on an Android tablet.
DetectOperaAndroidTablet : function() {
if ((this.uagent.search(this.engineOpera) > -1) &&
(this.uagent.search(this.deviceAndroid) > -1) &&
(this.uagent.search(this.deviceTablet) > -1))
return true;
else
return false;
},
//MISCELLANEOUS DEVICES
//**************************
// Detects if the current device is an Amazon Kindle (eInk devices only).
// Note: For the Kindle Fire, use the normal Android methods.
DetectKindle : function() {
if (this.uagent.search(this.deviceKindle) > -1 &&
!this.DetectAndroid())
return true;
else
return false;
},
//**************************
// Detects if the current Amazon device is using the Silk Browser.
// Note: Typically used by the the Kindle Fire.
DetectAmazonSilk : function() {
if (this.uagent.search(this.engineSilk) > -1)
return true;
else
return false;
},
//**************************
// Detects if the current browser is a
// Samsung Bada OS device.
DetectBada : function() {
if (this.uagent.search(this.deviceBada) > -1)
return true;
else
return false;
},
//**************************
// Detects if the current browser is a
// Garmin Nuvifone.
DetectGarminNuvifone : function() {
if (this.uagent.search(this.deviceNuvifone) > -1)
return true;
else
return false;
},
//**************************
// Detects if the current device is an Archos media player/Internet tablet.
DetectArchos : function() {
if (this.uagent.search(this.deviceArchos) > -1)
return true;
else
return false;
},
//**************************
// Detects if the current device is on one of
// the Maemo-based Nokia Internet Tablets.
DetectMaemoTablet : function() {
if (this.uagent.search(this.maemo) > -1)
return true;
//For Nokia N810, must be Linux + Tablet, or else it could be something else.
if ((this.uagent.search(this.linux) > -1)
&& (this.uagent.search(this.deviceTablet) > -1)
&& !this.DetectWebOSTablet()
&& !this.DetectAndroid())
return true;
else
return false;
},
//**************************
// Detects if the current browser is a Sony Mylo device.
DetectSonyMylo : function() {
if (this.uagent.search(this.mylocom2) > -1)
return true;
else
return false;
},
// FEATURE PHONES
//**************************
// Detects whether the device is a Brew-powered device.
// Note: Limited to older Brew-powered feature phones.
// Ignores newer Brew versions like MP. Refer to DetectMobileQuick().
DetectBrewDevice : function() {
if (this.uagent.search(this.deviceBrew) > -1)
return true;
else
return false;
},
//**************************
// Detects the Danger Hiptop device.
DetectDangerHiptop : function() {
if (this.uagent.search(this.deviceDanger) > -1 ||
this.uagent.search(this.deviceHiptop) > -1)
return true;
else
return false;
},
// GAME CONSOLES
//**************************
// Detects if the current device is an Internet-capable game console.
// Includes both TV and handheld styles.
DetectGameConsole : function() {
if (this.DetectSonyPlaystation() ||
this.DetectNintendo() ||
this.DetectXbox())
return true;
else
return false;
},
//**************************
// Detects if the current device is a Sony Playstation.
DetectSonyPlaystation : function() {
if (this.uagent.search(this.devicePlaystation) > -1)
return true;
else
return false;
},
//**************************
// Detects if the current device is a Nintendo game device.
DetectNintendo : function() {
if (this.uagent.search(this.deviceNintendo) > -1 ||
this.uagent.search(this.deviceWii) > -1 ||
this.uagent.search(this.deviceNintendoDs) > -1)
return true;
else
return false;
},
//**************************
// Detects if the current device is a Microsoft Xbox.
DetectXbox : function() {
if (this.uagent.search(this.deviceXbox) > -1)
return true;
else
return false;
},
// DEVICE CLASSES
//**************************
// Check to see whether the device is *any* 'smartphone'.
// Note: It's generally better to use DetectTierIphone() for modern touchscreen devices.
DetectSmartphone : function() {
if (this.DetectIphoneOrIpod() ||
this.DetectAndroidPhone() ||
this.DetectS60OssBrowser() ||
this.DetectSymbianOS() ||
this.DetectWindowsMobile() ||
this.DetectWindowsPhone7() ||
this.DetectBlackBerry() ||
this.DetectPalmWebOS() ||
this.DetectPalmOS() ||
this.DetectBada())
return true;
//Otherwise, return false.
return false;
},
//**************************
// Detects if the current device is a mobile device.
// This method catches most of the popular modern devices.
// Excludes Apple iPads and other modern tablets.
DetectMobileQuick : function() {
if (this.InitCompleted || this.IsMobilePhone)
return this.IsMobilePhone;
//Let's exclude tablets.
if (this.DetectTierTablet())
return false;
//Most mobile browsing is done on smartphones
if (this.DetectSmartphone())
return true;
if (this.DetectKindle() ||
this.DetectAmazonSilk())
return true;
//Catch all for many mobile devices
if (this.uagent.search(this.mobile) > -1)
return true;
if (this.uagent.search(this.deviceMidp) > -1 ||
this.DetectBrewDevice())
return true;
if (this.DetectOperaMobile() ||
this.DetectArchos())
return true;
if ((this.uagent.search(this.engineObigo) > -1) ||
(this.uagent.search(this.engineNetfront) > -1) ||
(this.uagent.search(this.engineUpBrowser) > -1))
return true;
return false;
},
//**************************
// Detects in a more comprehensive way if the current device is a mobile device.
DetectMobileLong : function() {
if (this.DetectMobileQuick())
return true;
if (this.DetectGameConsole())
return true;
if (this.DetectDangerHiptop() ||
this.DetectMaemoTablet() ||
this.DetectSonyMylo() ||
this.DetectGarminNuvifone())
return true;
if ((this.uagent.search(this.devicePda) > -1) &&
!(this.uagent.search(this.disUpdate) > -1))
return true;
//Detect for certain very old devices with stupid useragent strings.
if (this.uagent.search(this.manuSamsung1) > -1 ||
this.uagent.search(this.manuSonyEricsson) > -1 ||
this.uagent.search(this.manuericsson) > -1)
return true;
if ((this.uagent.search(this.svcDocomo) > -1) ||
(this.uagent.search(this.svcKddi) > -1) ||
(this.uagent.search(this.svcVodafone) > -1))
return true;
return false;
},
//*****************************
// For Mobile Web Site Design
//*****************************
//**************************
// The quick way to detect for a tier of devices.
// This method detects for the new generation of
// HTML 5 capable, larger screen tablets.
// Includes iPad, Android (e.g., Xoom), BB Playbook, WebOS, etc.
DetectTierTablet : function() {
if (this.InitCompleted || this.IsTierTablet)
return this.IsTierTablet;
if (this.DetectIpad() ||
this.DetectAndroidTablet() ||
this.DetectBlackBerryTablet() ||
this.DetectWebOSTablet())
return true;
else
return false;
},
//**************************
// The quick way to detect for a tier of devices.
// This method detects for devices which can
// display iPhone-optimized web content.
// Includes iPhone, iPod Touch, Android, Windows Phone 7, WebOS, etc.
DetectTierIphone : function() {
if (this.InitCompleted || this.IsTierIphone)
return this.IsTierIphone;
if (this.DetectIphoneOrIpod() ||
this.DetectAndroidPhone() ||
this.DetectWindowsPhone7() ||
(this.DetectBlackBerryWebKit() && this.DetectBlackBerryTouch()) ||
this.DetectPalmWebOS() ||
this.DetectBada() ||
this.DetectGarminNuvifone())
return true;
else
return false;
},
//**************************
// The quick way to detect for a tier of devices.
// This method detects for devices which are likely to be
// capable of viewing CSS content optimized for the iPhone,
// but may not necessarily support JavaScript.
// Excludes all iPhone Tier devices.
DetectTierRichCss : function() {
if (this.InitCompleted || this.IsTierRichCss)
return this.IsTierRichCss;
//Exclude iPhone and Tablet Tiers and e-Ink Kindle devices
if (this.DetectTierIphone() ||
this.DetectKindle() ||
this.DetectTierTablet())
return false;
//Exclude if not mobile
if (!this.DetectMobileQuick())
return false;
//If it's a mobile webkit browser on any other device, it's probably OK.
if (this.DetectWebkit())
return true;
//The following devices are also explicitly ok.
if (this.DetectS60OssBrowser() ||
this.DetectBlackBerryHigh() ||
this.DetectWindowsMobile() ||
(this.uagent.search(this.engineTelecaQ) > -1))
return true;
else
return false;
},
//**************************
// The quick way to detect for a tier of devices.
// This method detects for all other types of phones,
// but excludes the iPhone and RichCSS Tier devices.
// NOTE: This method probably won't work due to poor
// support for JavaScript among other devices.
DetectTierOtherPhones : function() {
if (this.InitCompleted || this.IsTierGenericMobile)
return this.IsTierGenericMobile;
//Exclude iPhone, Rich CSS and Tablet Tiers
if (this.DetectTierIphone() ||
this.DetectTierRichCss() ||
this.DetectTierTablet())
return false;
//Otherwise, if it's mobile, it's OK
if (this.DetectMobileLong())
return true;
else
return false;
}
};
//Initialize the MobileEsp object
MobileEsp.InitDeviceScan();
|
function generateDOM(childNodes) {
return childNodes.map(function(childNode) {
if (childNode['#name'] == '__text__') {
return childNode._;
}
var obj = {
tag: childNode['#name']
};
if (childNode.$) {
Object.keys(childNode.$).forEach(function(attr) {
obj[attr] = childNode.$[attr];
});
}
if (childNode.$$) {
obj.children = generateDOM(childNode.$$);
} else if (childNode._) {
obj.children = [childNode._];
} else {
obj.children = [];
}
return obj;
});
}
module.exports = generateDOM; |
const express = require('express');
//const favicon = require('serve-favicon');
const log = require('./log')("express");
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const partials = require('express-partials');
const config = require('./config');
const indexRouter = require('../routes/index');
const apiRouter = require('../routes/api');
const queueApiRouter = require("../routes/queueApi");
const cors = require('cors');
async function init() {
var app = express();
// view engine setup
app.set('views', 'src/views');
app.use(partials());
app.set('view engine', 'ejs');
app.set('view options', {
layout: 'layout'
});
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static('public'));
// CORS:
app.use(cors());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'DELETE, PUT, GET, POST');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use((req, res, next) => {
req.rawUrl = `${req.method} ${req.protocol}://${req.get('host')}${req.originalUrl}`;
var originEnd = res.end;
res.end = function (chunk, encoding) {
res.end = originEnd;
if (res.statusCode == 200) {
log.info(`${req.rawUrl} -> OK`);
}
res.end(chunk, encoding);
};
next();
});
app.use('/', indexRouter);
app.use('/api', apiRouter);
app.use('/api', queueApiRouter);
// catch 404 and forward to error handler
app.use((req, res, next) => {
let err = new Error('Not Found');
err.status = 404;
//
next(err);
});
// error handler
// eslint-disable-next-line no-unused-vars
app.use((err, req, res, next) => {
const status = err.status || 500;
log.debug(`${req.rawUrl} -> ${status} ${err.message}`);
if (status === 500) {
log.error(err);
res.status(500).json(err);
}
else {
res.status(status).json({ error: err.message })
}
});
return app;
}
module.exports = { init }; |
/*jslint node: true, nomen: true, plusplus: true, stupid: true, vars: true, indent: 2 */
/*global describe, it, before, beforeEach, after, afterEach */
'use strict';
var zipcode = require('../');
var assert = require('assert');
var async = require('async');
var datas = require('./datas.json');
describe('Lookup zipcode', function () {
async.each(datas, function (addrItem, callback) {
it('Lookup ' + addrItem.address + ' should return ' + addrItem.zipcode, function (done) {
zipcode.find(addrItem.address, function (zipcode) {
assert.equal(addrItem.zipcode, zipcode.zipcode);
done();
});
});
callback();
});
}); |
import roundWidth from '../../src/util/roundWidth';
test('Does not round under 100', () => {
expect(roundWidth(0)).toBe(0);
expect(roundWidth(1)).toBe(1);
expect(roundWidth(2)).toBe(2);
expect(roundWidth(6)).toBe(6);
expect(roundWidth(51)).toBe(51);
expect(roundWidth(99)).toBe(99);
});
test('Rounds to the next multiple of 5 under 500', () => {
expect(roundWidth(101)).toBe(100);
expect(roundWidth(102)).toBe(100);
expect(roundWidth(103)).toBe(105);
expect(roundWidth(104)).toBe(105);
expect(roundWidth(105)).toBe(105);
expect(roundWidth(497)).toBe(495);
expect(roundWidth(499)).toBe(500);
expect(roundWidth(500)).toBe(500);
});
test('Rounds to the next multiple of 10 over 500', () => {
expect(roundWidth(500)).toBe(500);
expect(roundWidth(500)).toBe(500);
expect(roundWidth(503)).toBe(500);
expect(roundWidth(504)).toBe(500);
expect(roundWidth(505)).toBe(510);
expect(roundWidth(1230)).toBe(1230);
expect(roundWidth(1234)).toBe(1230);
expect(roundWidth(1235)).toBe(1240);
expect(roundWidth(1240)).toBe(1240);
});
test('Rounds to the next power of two', () => {
expect(roundWidth(126)).toBe(125);
expect(roundWidth(127)).toBe(128);
expect(roundWidth(128)).toBe(128);
expect(roundWidth(129)).toBe(130);
expect(roundWidth(255)).toBe(255);
expect(roundWidth(256)).toBe(256);
expect(roundWidth(257)).toBe(256);
expect(roundWidth(258)).toBe(260);
expect(roundWidth(511)).toBe(510);
expect(roundWidth(512)).toBe(512);
expect(roundWidth(513)).toBe(512);
expect(roundWidth(514)).toBe(512);
expect(roundWidth(515)).toBe(512);
expect(roundWidth(516)).toBe(520);
expect(roundWidth(1022)).toBe(1020);
expect(roundWidth(1023)).toBe(1024);
expect(roundWidth(1024)).toBe(1024);
expect(roundWidth(1025)).toBe(1024);
expect(roundWidth(1026)).toBe(1024);
expect(roundWidth(1027)).toBe(1030);
});
|
var reddit = require('../index.js');
// reddit._addSimpleRequest = function(name, endpoint, method, args, constArgs, callback)
// reddit._addListingRequest = function(name, endpoint, path, args, cb)
reddit._addSimpleRequest("block", "block", "POST", ["id"], null, "_noResponse");
reddit.prototype.message = function(options, callback) {
var self = this;
this._apiRequest("compose", {"method": "POST", "form": {
"api_type": "json",
"iden": (options.captcha) ? self._captchaIdent : undefined,
"captcha": options.captcha,
"to": options.to,
"subject": options.subject,
"text": options.text
}}, function(err, response, body) {
self._multipleErrors(err, body, callback);
});
};
reddit.prototype.markRead = function(ids, callback) {
if(typeof ids == 'object') {
ids = ids.join(',');
}
var self = this;
this._apiRequest("read_message", {"method": "POST", "form": {"id": ids}}, function(err, response, body) {
self._noResponse(err, body, callback);
});
};
reddit.prototype.markUnread = function(ids, callback) {
if(typeof ids == 'object') {
ids = ids.join(',');
}
var self = this;
this._apiRequest("unread_message", {"method": "POST", "form": {"id": ids}}, function(err, response, body) {
self._noResponse(err, body, callback);
});
};
reddit._addListingRequest("inbox", "inbox.json", "/message", ["mark", "mid"]);
reddit._addListingRequest("unread", "unread.json", "/message", ["mark", "mid"]);
reddit._addListingRequest("sent", "sent.json", "/message", ["mark", "mid"]);
reddit._addListingRequest("messages", "messages.json", "/message", ["mark", "mid"]);
reddit._addListingRequest("commentReplies", "comments.json", "/message", ["mark", "mid"]);
reddit._addListingRequest("postReplies", "selfreply.json", "/message", ["mark", "mid"]);
reddit._addListingRequest("mentions", "mentions.json", "/message", ["mark", "mid"]); |
'use strict';
/**
* Module dependencies.
*/
var should = require('should');
var request = require('supertest-as-promised');
var path = require('path');
var mongoose = require('mongoose');
var User = mongoose.model('User');
var File = mongoose.model('File');
var Directory = mongoose.model('Directory');
var express = require(path.resolve('./config/lib/express'));
var chalk = require('chalk');
/**
* Unit tests
*/
describe('网盘文件 CRUD 测试', function () {
var app, agent, credentials, user, rootDirectory, fileId, extension, userId, newName, fileObj;
before(function (done) {
app = express.init(mongoose);
agent = request.agent(app);
done();
});
beforeEach(function (done) {
credentials = {
username: 'testuser',
password: 'testuser'
};
user = {
username: 'testuser',
password: 'testuser',
firstName: 'firstname',
lastName: 'lastname',
email: 'user@iccnu.net'
};
extension = '.png';
newName = {
name: 'test2.png'
};
agent.post('/api/auth/signup')
.send(user)
.expect(200)
.then(function () {
return agent.post('/api/auth/signin')
.send(credentials)
.expect(200);
})
.then(function (res) {
userId = res.body._id;
rootDirectory = res.body.rootDirectory;
fileObj = new File({
contentType: 'image/png',
name: 'test.png',
size: 45245,
user: mongoose.Types.ObjectId(userId),
parent: mongoose.Types.ObjectId(rootDirectory)
});
fileObj.save(function (err, fileSaved) {
if (err) {
done(err);
}
else {
fileId = fileSaved._id;
done();
}
});
});
});
describe('未登录用户应该不能对网盘文件进行CRUD操作', function () {
beforeEach(function (done) {
agent.get('/api/auth/signout')
.send(user)
.expect(302)
.then(function () {
done();
})
.catch(function (err) {
done(err);
});
});
it('未登录用户应该不能创建网盘文件', function (done) {
agent.post('/api/diskUpload/' + rootDirectory)
.send(fileObj)
.attach('image', 'test_resources/' + fileObj.name)
.expect(401)
.then(function () {
done();
})
.catch(function (err) {
done(err);
});
});
it('未登录用户应该不能查看网盘文件', function (done) {
agent.get('/api/disk/' + rootDirectory + '/' + fileId)
.expect(401)
.then(function () {
done();
})
.catch(function (err) {
done(err);
});
});
it('未登录用户应该不能修改网盘文件名', function (done) {
agent.put('/api/disk/' + rootDirectory + '/' + fileId)
.send(newName)
.expect(401)
.then(function () {
done();
})
.catch(function (err) {
done(err);
});
});
it('未登录用户应该不能删除网盘文件', function (done) {
agent.delete('/api/disk/' + rootDirectory + '/' + fileId)
.expect(401)
.then(function () {
done();
})
.catch(function (err) {
done(err);
});
});
});
describe('登录用户应该不能对他人的网盘文件进行CRUD操作', function () {
beforeEach(function (done) {
var user1 = {
username: 'testuser1',
password: 'testuser1',
firstName: 'firstname1',
lastName: 'lastname1',
email: 'user1@iccnu.net'
};
var credentials1 = {
username: 'testuser1',
password: 'testuser1'
};
agent.get('/api/auth/signout')
.send(user)
.expect(302)
.then(function () {
agent.post('/api/auth/signup')
.send(user1)
.expect(200)
.then(function () {
return agent.post('/api/auth/signin')
.send(credentials1)
.expect(200)
.then(function () {
done();
})
.catch(function (err) {
done(err);
});
});
});
});
it('登录用户应该不能对他人的网盘创建文件', function (done) {
agent.post('/api/diskUpload/' + rootDirectory)
.send(fileObj)
.attach('image', 'test_resources/' + fileObj.name)
.expect(500)
.then(function () {
done();
})
.catch(function (err) {
done(err);
});
});
it('登录用户应该不能查看他人网盘文件', function (done) {
agent.get('/api/disk/' + rootDirectory + '/' + fileId)
.expect(500)
.then(function () {
done();
})
.catch(function (err) {
done(err);
});
});
it('登录用户应该不能修改他人的网盘文件名', function (done) {
agent.put('/api/disk/' + rootDirectory + '/' + fileId)
.send(newName)
.expect(500)
.then(function () {
done();
})
.catch(function (err) {
done(err);
});
});
it('登录用户应该不能删除他人的网盘文件', function (done) {
agent.delete('/api/disk/' + rootDirectory + '/' + fileId)
.expect(500)
.then(function () {
done();
})
.catch(function (err) {
done(err);
});
});
});
describe('登录用户应该能对自己的网盘文件进行CRUD操作', function () {
it('登录用户应该能正确的上传网盘文件', function (done) {
agent.post('/api/diskUpload/' + rootDirectory)
.send(fileObj)
.attach('image', 'test_resources/' + fileObj.name)
.expect(201)
.then(function () {
return agent.get('/api/disk/' + rootDirectory)
.expect(200);
})
.then(function (res) {
(res.body.subFiles[0].name).should.equal(fileObj.name);
(res.body.subFiles[0].size).should.equal(fileObj.size);
(res.body.subFiles[0].extension).should.equal(extension);
})
.then(function () {
done();
})
.catch(function (err) {
done(err);
});
});
it('登录用户应该能查看网盘文件', function (done) {
agent.get('/api/disk/' + rootDirectory + '/' + fileId)
.expect(200)
.then(function (res) {
(res.body.name).should.equal(fileObj.name);
(res.body.size).should.equal(fileObj.size);
})
.then(function () {
done();
})
.catch(function (err) {
done(err);
});
});
it('登录用户应该能修改自己的网盘文件名,但不能修改其扩展名', function (done) {
var invalidNewName1 = 'test2.pn';
var invalidNewName2 = 'test2.png1';
var invalidNewName3 = 'test';
agent.put('/api/disk/' + rootDirectory + '/' + fileId)
.send(newName)
.expect(200)
.then(function (res) {
(res.body.name).should.equal(newName.name);
(res.body.extension).should.equal(extension);
})
.then(function () {
agent.put('/api/disk/' + rootDirectory + '/' + fileId)
.send(invalidNewName1)
.expect(400);
})
.then(function () {
agent.put('/api/disk/' + rootDirectory + '/' + fileId)
.send(invalidNewName2)
.expect(400);
})
.then(function () {
agent.put('/api/disk/' + rootDirectory + '/' + fileId)
.send(invalidNewName3)
.expect(400);
})
.then(function () {
done();
})
.catch(function (err) {
done(err);
});
});
it('登录用户应该能下载自己的网盘文件', function (done) {
var uploadedFileId;
agent.post('/api/diskUpload/' + rootDirectory)
.send(fileObj)
.attach('image', 'test_resources/' + fileObj.name)
.expect(201)
.then(function (res) {
uploadedFileId = res.body._id;
})
.then(function () {
agent.get('/api/diskDownload/' + rootDirectory + '/' + uploadedFileId)
.expect(200)
.then(function (res) {
done();
})
.catch(function (err) {
done(err);
});
});
});
it('登录用户应该能删除自己的网盘文件', function (done) {
agent.delete('/api/disk/' + rootDirectory + '/' + fileId)
.expect(200)
.then(function () {
done();
})
.catch(function (err) {
done(err);
});
});
});
afterEach(function (done) {
User.remove().exec(function () {
Directory.remove().exec(function () {
File.remove().exec(done);
});
});
});
});
|
const main = require('nei/main');
const Builder = require('nei/lib/nei/builder');
const EventEmitter = require('events');
const _fs = require('nei/lib/util/file');
const fs = require('fs');
const path = require('path');
const _util = require('nei/lib/util/util');
const { logger } = require('nei/lib/util/logger');
logger.setLevel('ERROR');
let subMain = main;
Object.assign(subMain, EventEmitter.prototype);
/**
* 构建项目
* @param arg
* @param action
* @param args
*/
subMain.build = function(arg, action, args) {
this.args = args;
this.config = {
action: action
};
/**
* 项目nei根路径
* @type {string}
*/
this.config.outputRoot = args.basedir;
this.checkConfig();
let loadedHandler = ds => {
this.config.pid = ds.project.id;
this.ds = ds;
this.fillArgs();
// 合并完参数后, 需要重新 format 一下, 并且此时需要取默认值
this.args = arg.format(this.config.action, this.args, true);
this.config.neiConfigRoot =
path.resolve(
this.config.outputRoot,
`nei.${this.config.pid}.${this.args.key}`
) + '/';
new Builder({
config: this.config,
args: this.args,
ds: this.ds
});
this.emit('buildSuccess', this.config);
};
this.loadData(loadedHandler);
};
/**
* 更新 nei 工程规范
* @param {object} arg - 参数类的实例
* @param {string} action - 操作命令
* @param {object} args - 命令行参数对象
*/
subMain.update = function(arg, action, args) {
let dir = args.basedir;
let projects = this.findProjects(args);
let buildProject = (neiProjectDir, exitIfNotExist) => {
let config = _util.file2json(
`${neiProjectDir}/nei.json`,
exitIfNotExist
);
let mergedArgs = Object.assign({}, config.args, args);
this.build(arg, action, mergedArgs);
};
if (args.key) {
if (projects.length == 0) {
logger.error(`在 ${dir} 中找不到 key 为 ${args.key} 的项目, 请检查`);
return process.exit(1);
} else if (projects.length > 1) {
logger.error(`存在多个 key 为 ${args.key} 的项目, 请检查`);
return process.exit(1);
} else {
buildProject(projects[0], true);
}
} else {
if (projects.length > 1) {
if (!args.all) {
logger.error(
'存在多个 nei 项目, 请通过 key 参数指定需要更新的项目, 或者使用 --all 参数更新所有项目'
);
return process.exit(1);
} else {
projects.forEach(buildProject);
}
} else {
buildProject(projects[0], true);
}
}
};
subMain.findProjects = function(args) {
let dir = args.basedir;
if (!_fs.exist(dir)) {
// 目录不存在, 退出程序
logger.error(`项目目录 ${dir} 不存在, 请检查`);
return process.exit(1);
}
let files = fs.readdirSync(dir);
let projects = [];
files.forEach(file => {
if (args.key) {
if (file.startsWith('nei') && file.endsWith(args.key)) {
projects.push(`${dir}/${file}`);
}
} else if (file.startsWith('nei') && file.length >= 42) {
// 疑是 nei 项目, 42 是 nei 配置文件的长度, 考虑到项目有可能会超过 5 位, 这里使用 >=
projects.push(`${dir}/${file}`);
}
});
return projects;
};
module.exports = subMain;
|
BookManager.Views.Books = Backbone.View.extend({
template: _.template($("#tpl-books").html()),
renderOne: function(book) {
var itemView = new BookManager.Views.Book({model: book});
this.$(".books-container").append(itemView.render().$el);
},
render: function() {
var html = this.template();
this.$el.html(html);
this.collection.each(this.renderOne, this);
return this;
}
}); |
import React from 'react';
import { FormattedMessage } from 'react-intl';
import A from 'components/A';
import Wrapper from './Wrapper';
import messages from './messages';
function Footer() {
return (
<Wrapper>
<div style={{width: '100%', background: '#141d26', height: '100px' }}> </div>
{/*<section>*/}
{/*<FormattedMessage*/}
{/*{...messages.authorMessage}*/}
{/*values={{*/}
{/*author: <A href="http://andyfrith.com">Andy Frith</A>,*/}
{/*}}*/}
{/*/>*/}
{/*</section>*/}
</Wrapper>
);
}
export default Footer;
|
/**
* Created by Jilion on 2017/3/10.
*/
import alt from '../common/alt';
import SizeActions from '../actions/SizeActions';
import { message } from 'antd';
import Util from '../common/Util';
class SizeStore {
constructor() {
this.bindActions(SizeActions);
this.state = {
dataSource: [],
isLoad: false,
sizeName: '',
sizes: [] // for filter page to load all sizes
}
}
createDataSource(store) {
return store.map((item, index) => {
return {
key: index,
id: {
editable: false,
value: item.id,
changeable: false
},
sizeName: {
editable: false,
value: item.sizeName,
changeable: true
},
createTime: {
editable: false,
value: item.createTime,
changeable: false
}
}
});
}
onGetAllSizesSuccess(data) {
this.setState({
sizes: data,
dataSource: this.createDataSource(data),
isLoad: true
});
}
onUpdateSizeSuccess(data) {
message.info(data.isCancel ? '已取消修改.' : '修改成功. ');
this.setState({ dataSource : data.dataSource });
}
onUpdateSizeFail(data) {
message.error('修改失败: ' + data);
setTimeout(function() {
Util.changLocation("/zhijian/sizes")
}, 500);
}
onUpdateSizeName(event) {
this.setState({
sizeName: event.target.value
});
}
onAddSizeSuccess(data) {
message.info('添加成功: ' + data.sizeName);
let dataSource = [...this.state.dataSource];
let newSize = {
key: dataSource.length,
id: {
editable: false,
value: data.id,
changeable: false
},
sizeName: {
editable: false,
value: data.sizeName,
changeable: true
},
createTime: {
editable: false,
value: data.createTime,
changeable: false
}
};
this.setState({
dataSource: [...dataSource, newSize]
});
}
onAddSizeFail(data) {
message.error(data);
}
onDeleteSizeSuccess(data) {
message.info('删除成功. ');
const dataSource = [...this.state.dataSource];
dataSource.splice(data.index, 1);
this.setState({ dataSource });
}
onDeleteSizeFail(data) {
message.error('删除失败: ' + data);
}
}
export default alt.createStore(SizeStore); |
//------A-----------
function LetterA() {
this.randomCol = floor(random(0, 7));
this.topEdge = random(0, width);
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[1]);
line(letterwidth / 2, 0, 0, letterheight);
stroke(palettebluepink[6]);
line(letterwidth / 2, 0, letterwidth, letterheight);
stroke(palettebluepink[5]);
line(letterwidth * .26, letterxheight, letterwidth * .66, letterxheight); //crossbar
//line to edges
noFill();
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
line(letterwidth / 2, 0, this.topEdge, -y);
pop();
}
this.update = function() {
//center the alphabet here? redraw the line conenctions here?
}
}
//-----B-------
function LetterB() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[2]);
line(0, 0, 0, letterheight); //left
stroke(palettebluepink[0]);
rect(0, 0, letterwidth, letterxheight, 0, letterrounding, letterrounding, 0); //top round
stroke(palettebluepink[4]);
rect(0, letterxheight, letterwidth, letterheight - letterxheight, 0, letterrounding, letterrounding, 0); //bottom round
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
line(0, 0, this.topEdge, -y); //reverse translate the y
pop();
}
this.update = function() {
}
}
//-----C---------
function LetterC() { //define arguments and then use them inside the function to be updated in draw
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
ellipseMode(CENTER);
noFill();
strokeWeight(letterstroke);
angleMode(DEGREES);
stroke(palettebluepink[6]);
arc(letterwidth / 2, letterheight / 2.5, letterwidth, letterheight * .8, 180, 350);
stroke(palettebluepink[0]);
arc(letterwidth / 2, letterheight - letterheight / 2.5, letterwidth, letterheight * .8, 360, 180);
stroke(palettebluepink[2]);
line(0, letterheight * .4, 0, letterheight * .6); //left straight line
strokeWeight(letterstrokeB);
// stroke(240, 90);
angleMode(DEGREES);
arc(letterwidth / 2, letterheight / 3, letterwidth / 1.7, letterwidth / 1.7, 180, 360); //G
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
}
this.update = function() {
}
}
//---------D--------
function LetterD() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[5]);
rect(0, 0, letterwidth, letterheight, 0, letterrounding, letterrounding, 0);
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
line(0, 0, this.topEdge, -y); //reverse translate the y
line(0, letterheight, -x, this.sideEdge); //reverse translate the y
pop();
}
this.update = function() {
}
}
//-----E-------
function LetterE() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[5]);
line(0, 0, 0, letterheight);
stroke(palettebluepink[6]);
line(0, letterheight, letterwidth, letterheight); //bottom
stroke(palettebluepink[3]);
line(0, 0, letterwidth, 0); //top
stroke(palettebluepink[2]);
line(0, letterxheight, letterwidth, letterxheight); //center
strokeWeight(letterstrokeB);
stroke(240, 90);
line(letterwidth / 5, 0 + letterheight / 3, letterwidth / 5, letterheight * .8); //N
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
line(0, 0, this.topEdge, -y); //reverse translate the y
line(0, letterheight, -x, this.sideEdge); //reverse translate the y
line(letterwidth, 0,this.topEdge, -y); //reverse translate the y
line(0, letterheight, -x, this.sideEdge); //reverse translate the y
pop();
}
this.update = function() {
}
}
//-----F-------
function LetterF(xPos, yPos) {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[1]);
line(0, 0, 0, letterheight);
stroke(palettebluepink[0]);
line(0, 0, letterwidth, 0); //top bar
stroke(palettebluepink[3]);
line(0, letterxheight, letterwidth, letterxheight); //bottombar
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
}
this.update = function() {
}
}
//-----G---------
function LetterG() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[1]);
angleMode(DEGREES);
arc(letterwidth / 2, letterheight / 2.5, letterwidth, letterheight * .8, 180, 350);
stroke(palettebluepink[2]);
arc(letterwidth / 2, letterheight - letterheight / 2.5, letterwidth, letterheight * .8, 360, 180);
stroke(palettebluepink[7]);
line(letterwidth / 2, letterxheight, letterwidth, letterxheight); //cross line
stroke(palettebluepink[4]);
line(0, letterheight * .45, 0, letterheight * .55); //left straight line
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
}
this.update = function() {
}
}
//-----H-------
function LetterH() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[5]);
line(0, 0, 0, letterheight); //left
stroke(palettebluepink[6]);
line(0, letterxheight, letterwidth, letterxheight); //top bar
stroke(palettebluepink[1]);
line(letterwidth, 0, letterwidth, letterheight); //right
strokeWeight(letterstrokeB);
stroke(240, 90);
// line(letterwidth / 5, 0 + letterheight / 3, letterwidth / 5, letterheight * .8); //N
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
}
this.update = function() {
}
}
//-----I-------
function LetterI() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[6]);
line(0, 0, letterwidth, 0); //top
line(0, letterheight, letterwidth, letterheight); //bottom
stroke(palettebluepink[3]);
line(letterwidth / 2, 0, letterwidth / 2, letterheight); //long
stroke(palettebluepink[2]);
// line(0, letterxheight, letterwidth, letterxheight); //center
// strokeWeight(letterstrokeB);
// stroke(240, 90);
// line(letterwidth / 5, 0 + letterheight / 3, letterwidth / 5, letterheight * .8); //N
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
}
this.update = function() {
}
}
//-----J-------
function LetterJ() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[6]);
line(0, 0, letterwidth, 0); //top
stroke(palettebluepink[4]);
// arc(0, letterxheight, letterwidth, letterxheight, PI + (QUARTER_PI / 3), OPEN);
angleMode(DEGREES);
arc(letterwidth / 2, letterheight - letterheight / 2.5, letterwidth, letterheight * .8, 360, 180);
stroke(palettebluepink[3]);
line(letterwidth, 0, letterwidth, letterxheight); //long
stroke(palettebluepink[2]);
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
}
this.update = function() {
}
}
//-----K-------
function LetterK() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[6]);
line(0, 0, 0, letterheight); //left
stroke(palettebluepink[7]);
line(0, letterxheight, letterwidth, 0); //towards top
stroke(palettebluepink[0]);
line(letterwidth * .5, letterheight * .4, letterwidth, letterheight); //bottom
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
}
this.update = function() {
}
}
//-----L-------
function LetterL() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[5]);
line(0, 0, 0, letterheight);
stroke(palettebluepink[6]);
line(0, letterheight, letterwidth, letterheight); //top bar
strokeWeight(letterstrokeB);
stroke(240, 90);
line(letterwidth / 5, 0 + letterheight / 3, letterwidth / 5, letterheight * .8); //N
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
}
this.update = function() {
}
}
//------M-----
function LetterM() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[0]);
line(0, 0, 0, letterheight); //left
stroke(palettebluepink[2]);
line(0, 0, letterwidth * .6, letterxheight); //across bottom left
stroke(palettebluepink[5]);
line(letterwidth, 0, letterwidth, letterheight); //right
stroke(palettebluepink[3]);
line(letterwidth, 0, letterwidth * .4, letterxheight); //across bottom left
// strokeWeight(letterstrokeB);
// stroke(240, 90);
// line(letterwidth / 5, 0 + letterheight / 3, letterwidth / 5, letterheight); //N
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
}
this.update = function() {
}
}
//------N-----
function LetterN() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[5]);
line(0, 0, 0, letterheight);
stroke(palettebluepink[0]);
line(0, 0, letterwidth, letterheight);
stroke(palettebluepink[2]);
line(letterwidth, 0, letterwidth, letterheight);
strokeWeight(letterstrokeB);
stroke(240, 90);
line(letterwidth / 5, 0 + letterheight / 3, letterwidth / 5, letterheight); //N
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
}
this.update = function() {
}
}
//------O------
function LetterO() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
rectMode(CORNER);
ellipseMode(CENTER);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[5]);
rect(0, 0, letterwidth, letterheight, letterrounding, letterrounding, letterrounding, letterrounding);
strokeWeight(letterstrokeB);
stroke(240, 90);
angleMode(DEGREES);
arc(letterwidth / 2, letterheight / 3, letterwidth / 1.7, letterwidth / 1.7, 180, 360); //O
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
}
this.update = function() {
}
}
//-----P-------
function LetterP(xPos, yPos) {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[2]);
line(0, 0, 0, letterheight); //left
stroke(palettebluepink[0]);
rect(0, 0, letterwidth, letterxheight, 0, letterrounding, letterrounding, 0);
// line(0, letterxheight, letterwidth, letterxheight); //top bar
// line(letterwidth, 0, letterwidth, letterheight); //right
// strokeWeight(letterstrokeB);
// stroke(240, 90);
// line(letterwidth / 5, 0 + letterheight / 3, letterwidth / 5, letterheight * .8); //N
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
}
this.update = function() {
}
}
//------Q------
function LetterQ() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
rectMode(CORNER);
ellipseMode(CENTER);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[5]);
rect(0, 0, letterwidth, letterheight, letterrounding, letterrounding, letterrounding, letterrounding);
stroke(palettebluepink[0]);
line(letterwidth / 2, letterxheight, letterwidth, letterheight);
strokeWeight(letterstrokeB);
stroke(240, 90);
angleMode(DEGREES);
arc(letterwidth / 2, letterheight / 3, letterwidth / 1.7, letterwidth / 1.7, 180, 360); //O
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
}
this.update = function() {
}
}
//-----R-------
function LetterR() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[6]);
line(0, 0, 0, letterheight); //left
stroke(palettebluepink[7]);
rect(0, 0, letterwidth, letterxheight, 0, letterrounding, letterrounding, 0); //rounded
stroke(palettebluepink[0]);
line(letterwidth * .7, letterxheight, letterwidth, letterheight);
// line(0, letterxheight, letterwidth, letterxheight); //top bar
// line(letterwidth, 0, letterwidth, letterheight); //right
// strokeWeight(letterstrokeB);
// stroke(240, 90);
// line(letterwidth / 5, 0 + letterheight / 3, letterwidth / 5, letterheight * .8); //N
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
}
this.update = function() {
}
}
//-----S-------
function LetterS() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[2]);
bezier(letterwidth, 0, 0, 0, letterwidth, letterheight, 0, letterheight); //temporary
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
}
this.update = function() {
}
}
//-----T-------
function LetterT() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[6]);
line(0, 0, letterwidth, 0); //top
stroke(palettebluepink[6]);
// line(0, letterheight, letterwidth, letterheight); //bottom
stroke(palettebluepink[3]);
line(letterwidth / 2, 0, letterwidth / 2, letterheight); //long
stroke(palettebluepink[2]);
// line(0, letterxheight, letterwidth, letterxheight); //center
// strokeWeight(letterstrokeB);
// stroke(240, 90);
// line(letterwidth / 5, 0 + letterheight / 3, letterwidth / 5, letterheight * .8); //N
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
}
this.update = function() {
}
}
//------U-----------
function LetterU() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[6]);
line(0, 0, 0, letterxheight);
stroke(palettebluepink[1]);
line(letterwidth, 0, letterwidth, letterxheight);
stroke(palettebluepink[0]);
angleMode(DEGREES);
stroke(palettebluepink[4]);
arc(letterwidth / 2, letterheight - letterheight / 2.5, letterwidth, letterheight * .8, 360, 180);
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
}
this.update = function() {
}
}
//------V-----------
function LetterV() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[6]);
line(letterwidth / 2, letterheight, 0, 0);
stroke(palettebluepink[1]);
line(letterwidth / 2, letterheight, letterwidth, 0);
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
}
this.update = function() {
}
}
//------W-----
function LetterW() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[0]);
line(0, 0, 0, letterheight); //left
stroke(palettebluepink[2]);
line(0, letterheight, letterwidth * .6, letterxheight); //across bottom left
stroke(palettebluepink[5]);
line(letterwidth, 0, letterwidth, letterheight); //right
stroke(palettebluepink[3]);
line(letterwidth, letterheight, letterwidth * .4, letterxheight); //across bottom left
// strokeWeight(letterstrokeB);
// stroke(240, 90);
// line(letterwidth / 5, 0 + letterheight / 3, letterwidth / 5, letterheight); //N
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
}
this.update = function() {
}
}
//------X-----
function LetterX() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[5]);
line(letterwidth, 0, 0, letterheight);
stroke(palettebluepink[0]);
line(0, 0, letterwidth, letterheight);
stroke(palettebluepink[2]);
strokeWeight(letterstrokeB);
stroke(240, 90);
line(letterwidth / 5, 0 + letterheight / 3, letterwidth / 5, letterheight); //N
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
}
this.update = function() {
}
}
//-----Y---------
function LetterY() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[0]);
angleMode(DEGREES);
arc(letterwidth / 2, 0, letterwidth, letterheight * .8, 360, 180);
stroke(palettebluepink[1]);
line(letterwidth / 2, letterheight, letterwidth / 2, letterheight * .4); //left straight line
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
}
this.update = function() {
}
}
//-----Z-------
function LetterZ() {
this.topEdge = random(0, width);
this.sideEdge = random(0, height);
this.randomCol = floor(random(0, 7));
this.display = function(x, y) {
push();
translate(x, y);
noFill();
strokeWeight(letterstroke);
stroke(palettebluepink[6]);
line(0, 0, letterwidth, 0); //top
stroke(palettebluepink[2]);
line(0, letterheight, letterwidth, letterheight); //bottom
stroke(palettebluepink[3]);
line(letterwidth, 0, 0, letterheight); //across
stroke(palettebluepink[this.randomCol]);
strokeWeight(letterstrokeB);
pop();
};
this.update = function() {
};
} |
'use strict';
const mongoose = require('mongoose');
const utils = require('./entryUtils');
const entrySchema = new mongoose.Schema({
date: { type: Date, default: Date.now },
creator: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
type: { type: String, required: true },
contents: mongoose.Schema.Types.Mixed,
message: String,
loc: {
type: { type: String },
coordinates: [Number]
}
});
entrySchema.pre('save', utils.validateFields);
entrySchema.statics.findEntries = utils.findEntries;
module.exports = mongoose.model('Entry', entrySchema);
|
// Sample Text
var Datamatrix = require('./lib/datamatrix').Datamatrix;
var dm = new Datamatrix();
var ascii = dm.getDigit('http://tualo.de',{rectangular:false,addFNC1:false});
console.log(ascii.toString());
var ascii2 = dm.getDigit('http://tualo.de',{rectangular:false,addFNC1:true});
console.log(ascii2.toString());
var ascii3 = dm.getDigit('http://tualo.de',{rectangular:false,addFNC1:false,length:144 /* 44x44 Matrix */});
console.log(ascii3.toString()); |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { ScrollView, StyleSheet } from 'react-native';
import { ListItem } from 'react-native-elements';
import ActionSheet from 'react-native-actionsheet';
import {
ViewContainer,
SectionList,
UserListItem,
LabelListItem,
} from 'components';
import { emojifyText, translate, openURLInView } from 'utils';
import { colors, fonts } from 'config';
import { getLabels } from 'repository';
import { editIssue, changeIssueLockStatus } from '../issue.action';
const mapStateToProps = state => ({
locale: state.auth.locale,
authUser: state.auth.user,
repository: state.repository.repository,
labels: state.repository.labels,
issue: state.issue.issue,
isMerged: state.issue.isMerged,
isEditingIssue: state.issue.isEditingIssue,
isPendingLabels: state.repository.isPendingLabels,
});
const mapDispatchToProps = dispatch =>
bindActionCreators(
{
editIssue,
changeIssueLockStatus,
getLabels,
},
dispatch
);
const styles = StyleSheet.create({
listItemTitle: {
color: colors.black,
...fonts.fontPrimary,
},
closeActionTitle: {
color: colors.red,
...fonts.fontPrimary,
},
openActionTitle: {
color: colors.green,
...fonts.fontPrimary,
},
});
class IssueSettings extends Component {
props: {
editIssue: Function,
changeIssueLockStatus: Function,
getLabels: Function,
locale: string,
authUser: Object,
repository: Object,
labels: Array,
issue: Object,
isMerged: boolean,
// isEditingIssue: boolean,
isPendingLabels: boolean,
navigation: Object,
};
componentDidMount() {
this.props.getLabels(
this.props.repository.labels_url.replace('{/name}', '')
);
}
showChangeIssueStateActionSheet = () => {
this.IssueActionSheet.show();
};
showLockIssueActionSheet = () => {
this.LockIssueActionSheet.show();
};
showAddLabelActionSheet = () => {
if (!this.props.isPendingLabels) {
this.AddLabelActionSheet.show();
}
};
handleIssueActionPress = index => {
const { issue, navigation } = this.props;
const newState = issue.state === 'open' ? 'close' : 'open';
if (index === 0) {
this.editIssue({ state: newState }).then(() => {
navigation.goBack();
});
}
};
handleLockIssueActionPress = index => {
const { issue, repository } = this.props;
const repoName = repository.name;
const owner = repository.owner.login;
if (index === 0) {
this.props.changeIssueLockStatus(
owner,
repoName,
issue.number,
issue.locked
);
}
};
handleAddLabelActionPress = index => {
const { issue, labels } = this.props;
const labelChoices = [...labels.map(label => label.name)];
if (
index !== labelChoices.length &&
!issue.labels.some(label => label.name === labelChoices[index])
) {
this.editIssue(
{
labels: [
...issue.labels.map(label => label.name),
labelChoices[index],
],
},
{ labels: [...issue.labels, labels[index]] }
);
}
};
editIssue = (editParams, stateChangeParams) => {
const { issue, repository } = this.props;
const repoName = repository.name;
const owner = repository.owner.login;
const updateStateParams = stateChangeParams || editParams;
return this.props.editIssue(
owner,
repoName,
issue.number,
editParams,
updateStateParams
);
};
openURLInBrowser = () => openURLInView(this.props.issue.html_url);
render() {
const { issue, isMerged, locale, authUser, navigation } = this.props;
const issueType = issue.pull_request
? translate('issue.settings.pullRequestType', locale)
: translate('issue.settings.issueType', locale);
return (
<ViewContainer>
<ScrollView>
<SectionList
showButton
buttonTitle={translate('issue.settings.applyLabelButton', locale)}
buttonAction={this.showAddLabelActionSheet}
style={{
borderBottomWidth: 1,
borderBottomColor: colors.grey,
}}
noItems={issue.labels.length === 0}
noItemsMessage={translate('issue.settings.noneMessage', locale)}
title={translate('issue.settings.labelsTitle', locale)}
>
{issue.labels.map(item => (
<LabelListItem
label={item}
key={item.id}
removeLabel={labelToRemove =>
this.editIssue(
{
labels: [
...issue.labels
.map(label => label.name)
.filter(
labelName => labelName !== labelToRemove.name
),
],
},
{
labels: issue.labels.filter(
label => label.name !== labelToRemove.name
),
}
)
}
/>
))}
</SectionList>
<SectionList
showButton={
!issue.assignees.some(
assignee => assignee.login === authUser.login
)
}
buttonTitle={translate(
'issue.settings.assignYourselfButton',
locale
)}
buttonAction={() =>
this.editIssue(
{
assignees: [
...issue.assignees.map(user => user.login),
authUser.login,
],
},
{ assignees: [...issue.assignees, authUser] }
)
}
noItems={issue.assignees.length === 0}
noItemsMessage={translate('issue.settings.noneMessage', locale)}
title={translate('issue.settings.assigneesTitle', locale)}
>
{issue.assignees.map(item => (
<UserListItem
user={item}
key={item.id}
navigation={navigation}
icon="x"
iconAction={userToRemove =>
this.editIssue(
{
assignees: [
...issue.assignees
.map(user => user.login)
.filter(user => user !== userToRemove),
],
},
{
assignees: issue.assignees.filter(
assignee => assignee.login !== userToRemove
),
}
)
}
/>
))}
</SectionList>
<SectionList title={translate('issue.settings.actionsTitle', locale)}>
<ListItem
title={
issue.locked
? translate('issue.settings.unlockIssue', locale, {
issueType,
})
: translate('issue.settings.lockIssue', locale, {
issueType,
})
}
hideChevron
underlayColor={colors.greyLight}
titleStyle={styles.listItemTitle}
onPress={this.showLockIssueActionSheet}
/>
{!isMerged && (
<ListItem
title={
issue.state === 'open'
? translate('issue.settings.closeIssue', locale, {
issueType,
})
: translate('issue.settings.reopenIssue', locale, {
issueType,
})
}
hideChevron
underlayColor={colors.greyLight}
titleStyle={
issue.state === 'open'
? styles.closeActionTitle
: styles.openActionTitle
}
onPress={this.showChangeIssueStateActionSheet}
/>
)}
</SectionList>
<SectionList>
<ListItem
title={translate('common.openInBrowser', locale)}
hideChevron
underlayColor={colors.greyLight}
titleStyle={styles.listItemTitle}
onPress={this.openURLInBrowser}
/>
</SectionList>
</ScrollView>
<ActionSheet
ref={o => {
this.IssueActionSheet = o;
}}
title={translate('issue.settings.areYouSurePrompt', locale)}
options={[
translate('common.yes', locale),
translate('common.cancel', locale),
]}
cancelButtonIndex={1}
onPress={this.handleIssueActionPress}
/>
<ActionSheet
ref={o => {
this.LockIssueActionSheet = o;
}}
title={translate('issue.settings.areYouSurePrompt', locale)}
options={[
translate('common.yes', locale),
translate('common.cancel', locale),
]}
cancelButtonIndex={1}
onPress={this.handleLockIssueActionPress}
/>
<ActionSheet
ref={o => {
this.AddLabelActionSheet = o;
}}
title={translate('issue.settings.applyLabelTitle', locale)}
options={[
...this.props.labels.map(label => emojifyText(label.name)),
translate('common.cancel', locale),
]}
cancelButtonIndex={this.props.labels.length}
onPress={this.handleAddLabelActionPress}
/>
</ViewContainer>
);
}
}
export const IssueSettingsScreen = connect(mapStateToProps, mapDispatchToProps)(
IssueSettings
);
|
import * as schema from './Schema';
import {
getReferential,
postReferential,
delReferential,
fileSave,
fileDownload,
} from '../utils/Action';
export const fetchFiles = () => (dispatch) => {
const uri = '/api/files';
return getReferential(schema.arrayOfFiles, uri)(dispatch);
};
export const addFile = (data) => (dispatch) => {
const uri = '/api/files';
return postReferential(schema.file, uri, data)(dispatch);
};
export const deleteFile = (fileId) => (dispatch) => {
const uri = `/api/files/${fileId}`;
return delReferential(uri, 'files', fileId)(dispatch);
};
export const downloadFile = (fileId, filename) => (dispatch) => fileSave(`/api/files/${fileId}`, filename)(dispatch);
export const dataFile = (fileId) => (dispatch) => fileDownload(`/api/files/${fileId}`)(dispatch);
export const getImportFileSheetsName = (fileId) => (dispatch) => {
const uri = `/api/files/sheets/${fileId}`;
return getReferential(schema.fileSheet, uri)(dispatch);
};
|
function HTTPFluxAPI_UserLoadFromContextToken(ctx, cbs){
if(ctx.token && ctx.token.user_id){
ctx.store.read(ctx.models.users, {where:{id: ctx.token.user_id}}, {
success: function(res){
if(res && res.length==1){
ctx.user = res[0];
}
if(cbs.success){
cbs.success(ctx);
}
},
error: function(err){
if(cbs && cbs.error){
cbs.error(err);
}
}
});
}else{
if(cbs.success){
cbs.success(ctx);
}
}
}
HTTPFluxAPI_UserLoadFromContextToken.flux_pipe = {
name: 'FluxHTTPAPI : User : LoadFromToken',
description: 'Loads the User defined in ctx.token.user_id, if it exists',
configs:[]
};
module.exports = HTTPFluxAPI_UserLoadFromContextToken; |
//File: controllers/Application.js
//Author: Daniel Seijo
//Version: 1.0
var mongoose = require('mongoose');
var Application = mongoose.model('Application');
//GET - Return all applications in the DB
exports.findAllApplications = function(req, res) {
Application.find(function(err, applications) {
if(err) return res.status(500).send(err);
console.log('GET /application')
res.status(200).jsonp(applications);
});
};
//GET - Return an Application with specified ID
exports.findById = function(req, res) {
Application.findById(req.params.id, function(err, application) {
if(err) return res.status(500).send(err);
console.log('GET /application/' + req.params.id);
res.status(200).jsonp(application);
});
};
//GET - Return an Application with specified UUID
exports.findByUUID = function(req, res) {
Application.findOne({uuid: req.params.uuid}, function(err, application) {
if(err) return res.status(500).send(err);
console.log('GET /application/beacon/' + req.params.uuid);
res.status(200).jsonp(application);
});
};
//POST - Insert a new Application in the DB
exports.addApplication = function(req, res) {
console.log('POST');
console.log(req.body);
var application = new Application({
name: req.body.name,
description: req.body.description,
uuid: req.body.uuid
});
application.save(function(err, application) {
if(err) return res.status(500).send(err);
res.status(200).jsonp(application);
});
};
//PUT - Update a register that already exists
exports.updateApplication = function(req, res) {
Application.findById(req.params.id, function(err, application) {
application.name = req.body.name,
application.description = req.body.description,
application.uuid = req.body.uuid
application.save(function(err) {
if(err) return res.status(500).send(err);
res.status(200).jsonp(application);
});
});
};
//DELETE - Delete an Application with specified ID
exports.deleteApplication = function(req, res) {
Application.findByIdAndRemove(req.params.id, function(err, application) {
if(err) return res.status(500).send(err);
res.status(200).jsonp(application);
});
};
|
class DataEvaluator {
evaluate(metadata, model) {
if(!model) {
return undefined;
}
if(model.hasOwnProperty(metadata.name)) {
return model[metadata.name];
}
return undefined;
}
}
export default new DataEvaluator(); |
/*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Web Client
* Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
/**
* @overview
*/
/**
* @class
* Creates a stack of undoable actions (ZmAction objects)
*
* @param {int} [maxLength] The maximum size of the stack. Defaults to 0, meaning no limit
*
* Adding actions to a full stack will pop the oldest actions off
*/
ZmActionStack = function(maxLength) {
this._stack = [];
this._pointer = -1;
this._maxLength = maxLength || 0; // 0 means no limit
};
ZmEvent.S_ACTION = "ACTION";
ZmActionStack.validTypes = [ZmId.ORG_FOLDER, ZmId.ITEM_MSG, ZmId.ITEM_CONV,
ZmId.ITEM_CONTACT, ZmId.ITEM_GROUP,
ZmId.ITEM_BRIEFCASE, ZmId.ORG_BRIEFCASE,
ZmId.ITEM_TASK, ZmId.ORG_TASKS
]; // Set ZmActionStack.validTypes to false to allow all item types
ZmActionStack.prototype.toString = function() {
return "ZmActionStack";
};
/**
* Logs a raw action, interpreting the params and creates a ZmAction object that is pushed onto the stack and returned
*
* @param {String} op operation to perform. Currently supported are "move", "trash", "spam" and "!spam"
* @param {Hash} [attrs] attributes for the operation. Pretty much the same as what the backend expects, e.g. "l" for the destination folderId of a move
* @param {String} [items] array of items to perform the action for. Valid types are specified in ZmActionStack.validTypes. Only one of [items],[item],[ids] or [id] should be specified; the first one found is used, ignoring the rest.
* @param {String} [item] item to perform the action for, if there is only one item. Accomplishes the same as putting the item in an array and giving it as [items]
* @param {String} [ids] array of ids of items to perform the action for.
* @param {String} [id] id of item to perform the action for, if there is only one. Accomplishes the same as putting the id in an array and giving it as [ids].
*/
ZmActionStack.prototype.logAction = function(params) {
var op = params.op;
var items = [];
if (params.items) {
for (var i=0; i<params.items.length; i++) {
var item = params.items[i];
if (item && (!ZmActionStack.validTypes || AjxUtil.indexOf(ZmActionStack.validTypes, item.type)!=-1)) {
items.push(item);
}
}
} else if (params.item) {
if (params.item && (!ZmActionStack.validTypes || AjxUtil.indexOf(ZmActionStack.validTypes, params.item.type)!=-1)) {
items.push(params.item);
}
} else if (params.ids) {
for (var i=0; i<params.ids.length; i++) {
var item = appCtxt.getById(params.ids[i]);
if (item && (!ZmActionStack.validTypes || AjxUtil.indexOf(ZmActionStack.validTypes, item.type)!=-1)) {
items.push(item);
}
}
} else if (params.id) {
var item = appCtxt.getById(params.id);
if (item && (!ZmActionStack.validTypes || AjxUtil.indexOf(ZmActionStack.validTypes, item.type)!=-1)) {
items.push(item);
}
}
for (var i=0; i<items.length; i++) {
if (items[i] instanceof ZmConv) { // For conversation moves, also log the messages within
var msgs = items[i].getMsgList();
for (var j=0; j<msgs.length; j++) {
if (AjxUtil.indexOf(msgs[j])==-1) {
items.push(msgs[j]);
}
}
}
}
var attrs = params.attrs;
var multi = items.length>1;
var action = null;
var folderId;
switch (op) {
case "trash":
folderId = ZmFolder.ID_TRASH;
break;
case "spam":
folderId = ZmFolder.ID_SPAM;
break;
case "move":
case "!spam":
folderId = attrs.l;
break;
}
var folder = appCtxt.getById(folderId);
if (folder && !folder.isRemote()) { // Enable undo only when destination folder exists (it should!!) and is not remote (bug #51656)
switch (op) {
case "trash":
case "move":
case "spam":
case "!spam":
for (var i=0; i<items.length; i++) {
var item = items[i];
var moveAction;
if (item instanceof ZmItem) {
if (!item.isShared()) // Moving shared items is not undoable
moveAction = new ZmItemMoveAction(item, item.getFolderId(), folderId, op);
} else if (item instanceof ZmOrganizer) {
if (!item.isRemote()) // Moving remote organizers is not undoable
moveAction = new ZmOrganizerMoveAction(item, item.parent.id, folderId, op);
}
if (moveAction) {
if (multi) {
if (!action) action = new ZmCompositeAction(folderId);
action.addAction(moveAction);
} else {
action = moveAction;
}
}
}
break;
}
if (action) {
this._push(action);
}
}
return action;
};
/**
* Returns whether there are actions that can be undone
*/
ZmActionStack.prototype.canUndo = function() {
return this._pointer >= 0;
};
/**
* Returns whether there are actions that can be redone
*/
ZmActionStack.prototype.canRedo = function() {
return this._pointer < this._stack.length - 1;
};
/**
* Undoes the current action (if applicable) and moves the internal pointer
*/
ZmActionStack.prototype.undo = function() {
if (this.canUndo()) {
var action = this._pop();
action.undo();
}
};
/**
* Redoes the current action (if applicable) and moves the internal pointer
*/
ZmActionStack.prototype.redo = function() {
if (this.canRedo()) {
var action = this._stack[++this._pointer];
action.redo();
}
};
/**
* Puts an action into the stack at the current position
* If we're not at the top of the stack (ie. undoes have been performed), we kill all later actions (so redoing the undone actions is no longer possible)
*/
ZmActionStack.prototype._push = function(action) {
if (action && action instanceof ZmAction) {
var next = this._pointer + 1;
while (this._maxLength && next>=this._maxLength) {
// Stack size is reached, shift off actions until we're under the limit
this._stack.shift();
next--;
}
this._stack[next] = action;
this._stack.length = next+1; // Kill all actions after pointer
this._pointer = next;
}
};
/**
* Returns the action at the current position and moves the pointer
*/
ZmActionStack.prototype._pop = function() {
return this.canUndo() ? this._stack[this._pointer--] : null;
};
|
let AlgorithmsJsonList;
export default (AlgorithmsJsonList = [
{
id: "BinaryGap",
name: "Binary Gap",
author: "Mateo Guzmán"
},
{
id: "OddOccurrencesInArray",
name: "Odd Occurrences In Array",
author: "Mateo Guzmán"
},
{
id: "Dominator",
name: "Dominator",
author: "Mateo Guzmán"
},
{
id: "CyclicRotation",
name: "Cyclic Rotation",
author: "Mateo Guzmán"
},
{
id: "PermMissingElem",
name: "Perm Missing Elem",
author: "Mateo Guzmán"
},
{
id: "FrogJump",
name: "Frog Jump",
author: "Mateo Guzmán"
}
]);
|
const langsData = require('../langs.json');
const languages = {
0: '',
1: 'ruby',
2: 'c-gcc',
3: 'perl',
4: 'golfscript',
5: 'node',
6: 'rust',
7: 'd-dmd',
8: '',
9: 'python3',
10: '',
11: 'php',
12: 'csharp',
13: 'unlambda',
14: 'powershell',
15: 'nadesiko',
16: 'ruby0.49',
17: 'alice',
18: 'gs2',
19: 'whitespace',
20: 'i4004asm',
21: 'java',
22: 'ocaml',
23: 'crystal',
24: 'cy',
25: 'kotlin',
26: 'braille',
27: 'vim',
28: 'element',
29: 'wierd',
30: 'cubix',
31: 'make',
32: 'function2d',
33: 'labyrinth',
34: 'z80',
35: 'swift',
36: 'convex',
37: 'stuck',
38: 'fish',
39: 'bash-busybox',
40: 'cmd',
41: 'lua',
42: 'verilog',
43: 'zucchini',
44: 'doubleplusungood',
45: 'jq',
46: 'japt',
47: 'snowman',
48: 'taxi',
49: 'emojicode',
50: 'grass',
51: 'htms',
52: 'sceql',
53: 'adjust',
54: 'stop',
55: 'brainfuck-bfi',
56: 'rprogn',
57: 'wordcpu',
58: 'rail',
59: 'typhon',
60: 'dis',
61: 'aheui',
62: 'apl',
63: 'asciidots',
64: 'wake',
65: 'minus',
66: 'sqlite3',
67: 'maybelater',
68: 'minimal2d',
69: 'slashes',
70: 'width',
71: 'floater',
72: 'simula',
73: 'malbolge',
74: 'suzy',
75: 'path',
76: 'whenever',
77: 'aubergine',
78: 'beam',
79: 'goruby',
80: 'wat',
81: 'x86asm-nasm',
82: 'llvm-ir',
83: 'brainfuck-esotope',
84: 'fernando',
85: 'blc',
86: 'piet',
87: 'pure-folders',
88: 'stackcats',
89: 'fugue',
90: 'lazyk',
91: 'befunge98',
};
module.exports = Array(92)
.fill()
.map((_, index) => {
if (index === 0) {
return {
type: 'base',
team: 0,
};
}
if (index === 8) {
return {
type: 'base',
team: 1,
};
}
if (index === 10) {
return {
type: 'base',
team: 2,
};
}
const langDatum = langsData.find((lang) => lang.slug === languages[index]);
return {
type: 'language',
slug: languages[index],
name: langDatum ? langDatum.name : '',
link: langDatum ? langDatum.link : '',
};
});
|
var nodes = []; // un tableau pour stocker les position en 3D
var stems = [];
var cam // une variable pour notre caméra
var maxRad = 25
var maxIteration = 150
var niteration = 0
var seed
var settings // une variable pour la librairie quicksettings
function setup() {
createCanvas(windowWidth, windowHeight, WEBGL); // on utilise le mode webgl : on peut donc faire de la 3D
background(0);
stems.push(new Stem(0, 0, 0, maxRad, 0.000, 0.0, 0.0))
// initialisation de la position de notre camera
cam = new EasyCam()
// création des élément de gui pour manipuler la caméra
// chaque élément dispose d'une fonction callback : càd qui est executée quand lorsqu'il y a une
// interaction de l'utilisateur avec l'élément en question
settings = QuickSettings.create(5, 5, "Controls");
settings.addButton("camera reset", function () {
cam.resetCam()
});
settings.addButton("regenerate tree", regenerate);
}
function regenerate() {
nodes = [];
stems = [];
maxRad = 25
stems.push(new Stem(0, 0, 0, maxRad, 0.00, 0.0, 0.0))
niteration = 0
sphereDetail(5)
}
function draw() {
background(0);
var locY = (mouseX / width - 0.5) * (5);
var locX = (mouseY / height - 0.5) * (-5);
ambientLight(55, 85, 3);
directionalLight(100, 100, 100, 0.55, 0.25, 0.25);
pointLight(90, 80, 10, locY, locX, 0);
pointLight(25, 50, 25, -locY, -locX, 0);
//ambientLight(55, 45, 3);
cam.update()
// on pousse un nouveau repère pour garder les transformation de la caméra mais pouvoir quand même
// dessiner la base de l'arbre plus bas, mais de garder le fait de se déplace en abscisses pour faire
// tourner l'abre sur lui même !
push()
translate(0, 800, 0) // on se décalle
push()// on pousse un nouveau repère dans lequel on force l'orientation
rotateY(0);
rotateX(-PI / 2);
// initialisation de la position de notre camera
// on dessine l'ensemble des objets stockés
for (var i = 0; i < stems.length; i++) {
stems[i].update();
}
// on dessine l'ensemble des objets stockés
for (var i = 0; i < nodes.length; i++) {
nodes[i].draw();
}
pop()
pop()
}
// Cette classe définit une branche, au départ il n'y en a qu'une, puis elle se sépare en 4, puis en 3, puis en 2
// à chaque fois que la branche se sépare : cela signifie qu'on ajoute un certain nombres d'objet de type Stem au tableau
// "stems", mais aussi qu'on enlève la branche en question.
// Chaque branche se déplace en 3D avec un noise comme nos tentacules précédement et dispose des instances de l'objet Node
// au bon endroit
function Stem(x, y, z, rad, noiseIncr, theta, phi) {
// coordonnées cartésiennes du node à créer
this.x = x
this.y = y
this.z = z
this.rad = rad // rayon du node à créer
// on garde en mémoire le rayon de départ, pour pouvoir comparer le rayon actuel au rayon de départ et déclencher les embranchements
this.startRad = rad
this.noiseF = random(1000) // un facteur de bruit pour le déplacement à l'aide d'un bruit de Perlin
this.noiseIncr = noiseIncr // on fera en sorte que les branches basses tournent peu et les branches hautes un peu plus
//variables pour stocker les coordonnées sphériques !
this.theta = theta;
this.phi = phi;
this.r = 1
this.update = function () {
// on limite le nombre d'éléments crées et la vitesse à laquelle ils se créent
if (nodes.length < 9000) {
this.rad -= this.rad * 0.01 // on diminue le rayon par le nombre d'or divisé par 10 au carré
this.rad = constrain(this.rad, maxRad / 30, maxRad);
console.log(this.rad)
this.r = this.rad // on s'éloigne du centre à vitesse
this.r = constrain(this.r, 10, maxRad);
// avec une orientation dépendant d'un bruit de Perlin
this.noiseF += this.noiseIncr
this.theta += map(noise(this.noiseF, 10, 20), 0, 1, -0.15, 0.15)
this.phi += map(noise(66, this.noiseF, 42), 0, 1, -0.25, 0.25)
// on convertit nos coordonnées sphériques en coordonnées cartésiennes
// https://en.wikipedia.org/wiki/Spherical_coordinate_system#Cartesian_coordinates
this.x += this.r * sin(this.theta) * cos(this.phi)
this.y += this.r * sin(this.theta) * sin(this.phi)
this.z += this.r * cos(this.theta)
nodes.push(new Node(this.x, this.y, this.z, this.rad))
// on va créer des embranchement en comparant le rayon au rayon initial avec pour limite un nombre d'embranchement
// maximum (définit tout en haut)
if (this.rad > maxRad / 25 && this.rad < this.startRad * 0.719 && niteration < maxIteration) {
var i = stems.indexOf(this);
stems.splice(i, 1)
// en fonction de l'iteration on crée différents types d'embranchements
if (niteration < 20) {
stems.push(new Stem(this.x, this.y, this.z, this.rad, 0.065, random(-PI / 4, PI / 4), random(-PI / 4, PI / 4)))
stems.push(new Stem(this.x, this.y, this.z, this.rad, 0.065, random(-PI / 4, PI / 4), random(-PI / 4, PI / 4)))
stems.push(new Stem(this.x, this.y, this.z, this.rad, 0.065, random(-PI / 4, PI / 4), random(-PI / 4, PI / 4)))
stems.push(new Stem(this.x, this.y, this.z, this.rad, 0.065, random(-PI / 4, PI / 4), random(-PI / 4, PI / 4)))
}
else if (niteration > 20 && niteration < 45) {
stems.push(new Stem(this.x, this.y, this.z, this.rad, 0.119, random(-PI / 3, PI / 3), random(-PI / 3, PI / 3)))
stems.push(new Stem(this.x, this.y, this.z, this.rad, 0.119, random(-PI / 3, PI / 3), random(-PI / 3, PI / 3)))
stems.push(new Stem(this.x, this.y, this.z, this.rad, 0.119, random(-PI / 3, PI / 3), random(-PI / 3, PI / 3)))
}
else {
stems.push(new Stem(this.x, this.y, this.z, this.rad, 0.492, random(-PI / 3, PI / 3), random(-PI / 3, PI / 3)))
stems.push(new Stem(this.x, this.y, this.z, this.rad, 0.492, random(-PI / 3, PI / 3), random(-PI / 3, PI / 3)))
}
niteration += 1
}
//console.log(nodes.length, stems.length, niteration)
}
}
}
// Cette classe ne fait que stocker des valeurs
// et dessiner une sphère à l'endroit et à la taille définie par ces valeurs.
function Node(x, y, z, rad) {
this.xpos = x;
this.ypos = y;
this.zpos = z;
this.rad = rad;
this.draw = function () {
push()
specularMaterial(180)
translate(this.xpos, this.ypos, this.zpos)
sphere(this.rad,8,4)
pop()
}
}
// appeler les fonction de EazyCam pour en fonction des actions de l'utilisateur
function mouseDragged() {
cam.drag(mouseX, mouseY, pmouseX, pmouseY)
}
function mouseWheel(val) {
// val.deltaY récupère la variation de déplacement à deux doigts
// sur le touch pad de haut en bas
cam.move(val.deltaY)
}
// une classe pour manipuler la caméra 3D avec la souris.
// maintenir cliqué et déplacer la souris pour regarder autour
// molette de la souris pour se rapprocher ou s'éloigner.
function EasyCam() {
// 3 variables d'états + 3 cibles pour interpolation
this.xrot = 0
this.zpos = 0
this.yrot = 0
this.xrotTarget = 0
this.yrotTarget = 0
this.zposTarget = -1600
this.update = function () {
// interpolation des varaibales d'état
this.xrot += (this.xrotTarget - this.xrot) * 0.05
this.yrot += (this.yrotTarget - this.yrot) * 0.05
this.zpos += (this.zposTarget - this.zpos) * 0.1
// orientation des dessin qui suiveront l'appel de cette fonction
translate(0, 0, this.zpos);
rotateX(this.xrot)
rotateY(this.yrot)
}
this.resetCam = function () {
this.xrot = 0
this.zpos = 0
this.yrot = 0
this.xrotTarget = 0
this.yrotTarget = 0
this.zposTarget = -1600
}
this.drag = function (x, y, px, py) {
// changer la valeur de la cible en fonction du déplacement de la souris
// en abscisses et en ordonées
this.xrotTarget += (y - py) / 100;
this.yrotTarget += (x - px) / 100;
}
this.move = function (val) {
//changer la valeur de la position cible le long de l'axe z
this.zposTarget += val
}
}
|
const NodeWebcam = require('node-webcam')
const _ = require('lodash')
//Default options
const webcamOpt = {
width: 1280,
height: 720,
delay: 0,
quality: 1,
output: 'png',
verbose: true
}
const Webcam = NodeWebcam.create(webcamOpt)
//Will automatically append location output type
// setInterval(() => {
const time = new Date().toISOString()
Webcam.capture('shot', (err, data) => {
if (err) console.error(err)
Webcam.getLastShot((err, data) => {
if (err) console.error(err)
Webcam.getBase64(0, (err, data) => {
console.log(data)
})
})
})
// Webcam.getShot(1, (err, data) => {
// console.log(err)
// console.log(data)
// })
// }, 500) |
// Regular expression that matches all symbols in the `Lydian` script as per Unicode v9.0.0:
/\uD802[\uDD20-\uDD39\uDD3F]/; |
define(['exports', './abstract-type-strategy'], function (exports, _abstractTypeStrategy) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.NumberStrategy = undefined;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
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 english = '([0-9]*(,[0-9]{3})*)(\\.[0-9]+)?';
var german = '([0-9]*(\\.[0-9]{3})*)(,[0-9]+)?';
var strip = function strip(str) {
return str.replace(/[.,]/g, '');
};
var NumberStrategy = exports.NumberStrategy = function (_AbstractTypeStrategy) {
_inherits(NumberStrategy, _AbstractTypeStrategy);
function NumberStrategy(options) {
_classCallCheck(this, NumberStrategy);
var _this = _possibleConstructorReturn(this, (NumberStrategy.__proto__ || Object.getPrototypeOf(NumberStrategy)).call(this, options));
_this.locale = options.locale;
return _this;
}
_createClass(NumberStrategy, [{
key: 'validate',
value: function validate(value) {
if (!value) {
return false;
}
if (this.locale) {
return NumberStrategy.getPattern(this.locale).test(value);
}
return NumberStrategy.getPattern('en').test(value) || NumberStrategy.getPattern('de').test(value);
}
}, {
key: 'convert',
value: function convert(value) {
var simple = void 0;
if (this.locale) {
simple = value.replace(NumberStrategy.getPattern(this.locale), NumberStrategy.convertToDecimal);
} else if (NumberStrategy.getPattern('en').test(value)) {
simple = value.replace(NumberStrategy.getPattern('en'), NumberStrategy.convertToDecimal);
} else if (NumberStrategy.getPattern('de').test(value)) {
simple = value.replace(NumberStrategy.getPattern('de'), NumberStrategy.convertToDecimal);
}
return parseFloat(simple);
}
}], [{
key: 'getPattern',
value: function getPattern(locale) {
switch (locale) {
case 'de':
return new RegExp('^' + german + '$');
case 'en':
return new RegExp('^' + english + '$');
default:
return new RegExp('^' + english + '$');
}
}
}, {
key: 'convertToDecimal',
value: function convertToDecimal(match) {
var combined = strip((arguments.length <= 1 ? undefined : arguments[1]) || (arguments.length <= 4 ? undefined : arguments[4]));
if ((arguments.length <= 3 ? undefined : arguments[3]) || (arguments.length <= 6 ? undefined : arguments[6])) {
combined += '.' + strip((arguments.length <= 3 ? undefined : arguments[3]) || (arguments.length <= 6 ? undefined : arguments[6]));
}
return combined;
}
}]);
return NumberStrategy;
}(_abstractTypeStrategy.AbstractTypeStrategy);
}); |
// Generated by CoffeeScript 1.7.1
(function() {
var Crawler, cheerio, fs, http;
http = require('http');
cheerio = require('cheerio');
fs = require('fs');
if (typeof String.prototype.endsWith !== 'function') {
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
if (typeof String.prototype.truncate !== 'function') {
String.prototype.truncate = function(limit, append) {
var parts;
if (typeof append === 'undefined') {
append = '...';
}
parts = this.match(/\S+/g);
if (parts !== null && parts.length > limit) {
parts.length = limit;
parts.push(append);
return parts.join(' ');
}
return this;
};
}
Crawler = (function() {
function Crawler(processPage, outputFile) {
this.processPage = processPage;
this.outputFile = outputFile != null ? outputFile : "output.json";
this.visited = {};
this.counter = 0;
this.queue = [];
this.records = [];
this.running = [];
this.maxSockets = 10;
http.globalAgent.maxSockets = this.maxSockets;
}
Crawler.prototype.restart = function(seed) {
var error, error2, l, output, r, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2;
this.seed = seed;
try {
output = fs.readFileSync(this.outputFile);
this.records = JSON.parse(output);
} catch (_error) {
error = _error;
if (error.code !== "ENOENT") {
try {
this.records = JSON.parse(output + "]");
} catch (_error) {
error2 = _error;
console.log(error2.message);
return;
}
}
}
_ref = this.records;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
r = _ref[_i];
this.visited[r.uri] = "visited";
}
fs.writeFile(this.outputFile, "[\n");
_ref1 = this.records;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
r = _ref1[_j];
fs.appendFile(this.outputFile, (this.counter++ > 0 ? ",\n" : "") + JSON.stringify(r, null, 1));
if (r.links) {
_ref2 = r.links;
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
l = _ref2[_k];
this.checkForQueue(l.href);
}
}
}
console.log("Queued URLs: " + this.queue.length);
console.log("Records loaded: " + this.records.length);
this.checkForQueue(this.seed);
return console.log(new Date());
};
Crawler.prototype.checkForQueue = function(url) {
if (this.visited[url] === void 0 && this.queue.indexOf(url) < 0 && this.running.indexOf(url) < 0) {
console.log("Queued: '" + url + "' (" + this.visited[url] + "/" + (this.queue.indexOf(url)) + "/" + (this.running.indexOf(url)) + ")");
this.queue.push(url);
this.processQueue();
}
};
Crawler.prototype.request = function(url, callback, redirect) {
var req;
console.log("Running: " + url + ", redirect: " + redirect);
this.running.push(url);
if (redirect === void 0) {
redirect = url;
}
req = http.get(redirect, (function(_this) {
return function(res) {
var e, html;
if (res.statusCode >= 300 && res.statusCode < 307) {
_this.request(url, callback, res.headers["location"]);
res.on("data", function() {});
return;
}
if (res.statusCode !== 200) {
e = new Error("Server Error: " + res.statusCode + ", URL: " + url + ", Requested: " + redirect);
e.url = url;
callback(e);
res.on("data", function() {});
_this.requestComplete();
return;
}
html = "";
res.on("data", function(chunk) {
return html += chunk;
});
return res.on("end", function() {
var record;
if (res.data === void 0) {
res.data = html;
}
res.url = url;
record = callback(null, res, cheerio.load(html));
if (record !== null) {
_this.records.push(record);
fs.appendFile(_this.outputFile, (_this.counter++ > 0 ? ",\n" : "") + JSON.stringify(record, null, 1));
_this.visited[record.uri] = "visited";
_this.visited[url] = "visited";
_this.visited[redirect] = "visited";
console.log("" + _this.counter + ". Processed " + record.uri + " (id=" + record.id + ") (R/Q=" + _this.running.length + "/" + _this.queue.length + ")");
}
return _this.requestComplete(url);
});
};
})(this));
return req.on("error", (function(_this) {
return function(e) {
e.url = url;
callback(e);
return _this.requestComplete(url);
};
})(this));
};
Crawler.prototype.requestComplete = function(url) {
this.running.splice(this.running.indexOf(url), 1);
if (this.running.length === 0) {
return this.processQueue();
}
};
Crawler.prototype.processQueue = function() {
var q, toProcess, _i, _len;
if (this.queue.length === 0 && this.running.length === 0) {
this.finish();
return;
}
if (this.running.length === 0) {
toProcess = this.queue.splice(0, this.maxSockets);
for (_i = 0, _len = toProcess.length; _i < _len; _i++) {
q = toProcess[_i];
this.request(q, this.processPage);
}
}
};
Crawler.prototype.finish = function() {
fs.appendFile(this.outputFile, "]\n");
return console.log("Finished: " + new Date());
};
return Crawler;
})();
module.exports = Crawler;
}).call(this);
|
import styled from 'styled-components';
import themeProp from '../utils/theme';
import { borderRadius } from '../utils/border-radius';
import { boxShadow } from '../utils/box-shadow';
import {
dropdownMinWidth,
dropdownPaddingY,
dropdownSpacer,
fontSizeBase,
bodyColor,
dropdownBg,
dropdownBorderWidth,
dropdownBorderColor,
dropdownBorderRadius,
dropdownBoxShadow,
zIndexDropdown
} from './default-theme';
const DropdownMenu = styled.div`
position: absolute;
top: 100%;
z-index: ${themeProp('zIndexDropdown', zIndexDropdown)};
display: none;
float: left;
min-width: ${themeProp('dropdownMinWidth', dropdownMinWidth)};
padding: ${themeProp('dropdownPaddingY', dropdownPaddingY)} 0;
margin: ${themeProp('dropdownSpacer', dropdownSpacer)} 0 0;
font-size: ${themeProp('fontSizeBase', fontSizeBase)};
color: ${themeProp('bodyColor', bodyColor)};
text-align: left;
list-style: none;
background-color: ${themeProp('dropdownBg', dropdownBg)};
background-clip: padding-box;
border: ${themeProp('dropdownBorderWidth', dropdownBorderWidth)} solid
${themeProp('dropdownBorderColor', dropdownBorderColor)};
${borderRadius(themeProp('dropdownBorderRadius', dropdownBorderRadius))};
${boxShadow(themeProp('dropdownBoxShadow', dropdownBoxShadow))};
`;
DropdownMenu.defaultProps = {};
export default DropdownMenu;
|
// const MockPointer = require('../interaction/MockPointer');
const { Renderer, BatchRenderer, Texture } = require('@pixi/core');
const { Graphics, GRAPHICS_CURVES, FillStyle, LineStyle, graphicsUtils } = require('../');
const { FILL_COMMANDS, buildLine } = graphicsUtils;
const { BLEND_MODES } = require('@pixi/constants');
const { Point, Matrix, SHAPES, Polygon } = require('@pixi/math');
const { skipHello } = require('@pixi/utils');
Renderer.registerPlugin('batch', BatchRenderer);
skipHello();
describe('PIXI.Graphics', function ()
{
describe('constructor', function ()
{
it('should set defaults', function ()
{
const graphics = new Graphics();
expect(graphics.fill.color).to.be.equals(0xFFFFFF);
expect(graphics.fill.alpha).to.be.equals(1);
expect(graphics.line.width).to.be.equals(0);
expect(graphics.line.color).to.be.equals(0);
expect(graphics.tint).to.be.equals(0xFFFFFF);
expect(graphics.blendMode).to.be.equals(BLEND_MODES.NORMAL);
});
});
describe('lineStyle', function ()
{
it('should support a list of parameters', function ()
{
const graphics = new Graphics();
graphics.lineStyle(1, 0xff0000, 0.5, 1, true);
expect(graphics.line.width).to.equal(1);
expect(graphics.line.color).to.equal(0xff0000);
expect(graphics.line.alignment).to.equal(1);
expect(graphics.line.alpha).to.equal(0.5);
expect(graphics.line.native).to.equal(true);
graphics.destroy();
});
it('should default color to black if texture not present and white if present', function ()
{
const graphics = new Graphics();
graphics.lineStyle(1);
expect(graphics.line.color).to.equal(0x0);
graphics.lineTextureStyle({ texture: Texture.WHITE, width: 1 });
expect(graphics.line.color).to.equal(0xFFFFFF);
graphics.destroy();
});
it('should support object parameter', function ()
{
const graphics = new Graphics();
graphics.lineStyle({
width: 1,
alpha: 0.5,
color: 0xff0000,
alignment: 1,
native: true,
});
expect(graphics.line.width).to.equal(1);
expect(graphics.line.color).to.equal(0xff0000);
expect(graphics.line.alignment).to.equal(1);
expect(graphics.line.alpha).to.equal(0.5);
expect(graphics.line.native).to.equal(true);
expect(graphics.line.visible).to.equal(true);
graphics.lineStyle();
expect(graphics.line.width).to.equal(0);
expect(graphics.line.color).to.equal(0);
expect(graphics.line.alignment).to.equal(0.5);
expect(graphics.line.alpha).to.equal(1);
expect(graphics.line.native).to.equal(false);
expect(graphics.line.visible).to.equal(false);
graphics.destroy();
});
});
describe('lineTextureStyle', function ()
{
it('should support object parameter', function ()
{
const graphics = new Graphics();
const matrix = new Matrix();
const texture = Texture.BLACK;
graphics.lineTextureStyle({
width: 1,
alpha: 0.5,
color: 0xff0000,
matrix,
texture,
alignment: 1,
native: true,
});
expect(graphics.line.width).to.equal(1);
expect(graphics.line.texture).to.equal(texture);
expect(graphics.line.matrix).to.be.okay;
expect(graphics.line.color).to.equal(0xff0000);
expect(graphics.line.alignment).to.equal(1);
expect(graphics.line.alpha).to.equal(0.5);
expect(graphics.line.native).to.equal(true);
expect(graphics.line.visible).to.equal(true);
graphics.lineTextureStyle();
expect(graphics.line.width).to.equal(0);
expect(graphics.line.texture).to.equal(Texture.WHITE);
expect(graphics.line.matrix).to.equal(null);
expect(graphics.line.color).to.equal(0);
expect(graphics.line.alignment).to.equal(0.5);
expect(graphics.line.alpha).to.equal(1);
expect(graphics.line.native).to.equal(false);
expect(graphics.line.visible).to.equal(false);
graphics.destroy();
});
});
describe('beginTextureFill', function ()
{
it('should pass texture to batches', function ()
{
const graphics = new Graphics();
const canvas1 = document.createElement('canvas');
const validTex1 = Texture.from(canvas1);
const canvas2 = document.createElement('canvas');
const validTex2 = Texture.from(canvas2);
canvas1.width = 10;
canvas1.height = 10;
canvas2.width = 10;
canvas2.height = 10;
validTex1.update();
validTex2.update();
graphics.beginTextureFill({ texture: validTex1 });
graphics.drawRect(0, 0, 10, 10);
graphics.beginTextureFill(validTex2); // old 5.0-5.1 style
graphics.drawRect(20, 20, 10, 10);
graphics.geometry.updateBatches();
const batches = graphics.geometry.batches;
expect(batches.length).to.equal(2);
expect(batches[0].style.texture).to.equal(validTex1);
expect(batches[1].style.texture).to.equal(validTex2);
});
});
describe('utils', function ()
{
it('FILL_COMMADS should be filled', function ()
{
expect(FILL_COMMANDS).to.not.be.null;
expect(FILL_COMMANDS[SHAPES.POLY]).to.not.be.null;
expect(FILL_COMMANDS[SHAPES.CIRC]).to.not.be.null;
expect(FILL_COMMANDS[SHAPES.ELIP]).to.not.be.null;
expect(FILL_COMMANDS[SHAPES.RECT]).to.not.be.null;
expect(FILL_COMMANDS[SHAPES.RREC]).to.not.be.null;
});
it('buildLine should execute without throws', function ()
{
const graphics = new Graphics();
graphics.lineStyle({ width: 2, color: 0xff0000 });
graphics.drawRect(0, 0, 10, 10);
const geometry = graphics.geometry;
const data = geometry.graphicsData[0];
// native = false
expect(function () { buildLine(data, geometry); }).to.not.throw();
data.lineStyle.native = true;
// native = true
expect(function () { buildLine(data, geometry); }).to.not.throw();
});
});
describe('lineTo', function ()
{
it('should return correct bounds - north', function ()
{
const graphics = new Graphics();
graphics.lineStyle(1);
graphics.moveTo(0, 0);
graphics.lineTo(0, 10);
expect(graphics.width).to.be.closeTo(1, 0.0001);
expect(graphics.height).to.be.closeTo(11, 0.0001);
});
it('should return correct bounds - south', function ()
{
const graphics = new Graphics();
graphics.moveTo(0, 0);
graphics.lineStyle(1);
graphics.lineTo(0, -10);
expect(graphics.width).to.be.closeTo(1, 0.0001);
expect(graphics.height).to.be.closeTo(11, 0.0001);
});
it('should return correct bounds - east', function ()
{
const graphics = new Graphics();
graphics.moveTo(0, 0);
graphics.lineStyle(1);
graphics.lineTo(10, 0);
expect(graphics.height).to.be.closeTo(1, 0.0001);
expect(graphics.width).to.be.closeTo(11, 0.0001);
});
it('should return correct bounds - west', function ()
{
const graphics = new Graphics();
graphics.moveTo(0, 0);
graphics.lineStyle(1);
graphics.lineTo(-10, 0);
expect(graphics.height).to.be.closeTo(1, 0.0001);
expect(graphics.width).to.be.closeTo(11, 0.0001);
});
it('should return correct bounds when stacked with circle', function ()
{
const graphics = new Graphics();
graphics.beginFill(0xFF0000);
graphics.drawCircle(50, 50, 50);
graphics.endFill();
expect(graphics.width).to.be.equals(100);
expect(graphics.height).to.be.equals(100);
graphics.lineStyle(20, 0);
graphics.moveTo(25, 50);
graphics.lineTo(75, 50);
expect(graphics.width).to.be.equals(100);
expect(graphics.height).to.be.equals(100);
});
it('should return correct bounds when square', function ()
{
const graphics = new Graphics();
graphics.lineStyle(20, 0, 0.5);
graphics.moveTo(0, 0);
graphics.lineTo(50, 0);
graphics.lineTo(50, 50);
graphics.lineTo(0, 50);
graphics.lineTo(0, 0);
expect(graphics.width).to.be.equals(70);
expect(graphics.height).to.be.equals(70);
});
it('should ignore duplicate calls', function ()
{
const graphics = new Graphics();
graphics.moveTo(0, 0);
graphics.lineTo(0, 0);
graphics.lineTo(10, 0);
graphics.lineTo(10, 0);
expect(graphics.currentPath.points).to.deep.equal([0, 0, 10, 0]);
});
});
describe('containsPoint', function ()
{
it('should return true when point inside', function ()
{
const point = new Point(1, 1);
const graphics = new Graphics();
graphics.beginFill(0);
graphics.drawRect(0, 0, 10, 10);
expect(graphics.containsPoint(point)).to.be.true;
});
it('should return false when point outside', function ()
{
const point = new Point(20, 20);
const graphics = new Graphics();
graphics.beginFill(0);
graphics.drawRect(0, 0, 10, 10);
expect(graphics.containsPoint(point)).to.be.false;
});
it('should return false when no fill', function ()
{
const point = new Point(1, 1);
const graphics = new Graphics();
graphics.drawRect(0, 0, 10, 10);
expect(graphics.containsPoint(point)).to.be.false;
});
it('should return false with hole', function ()
{
const point1 = new Point(1, 1);
const point2 = new Point(5, 5);
const graphics = new Graphics();
graphics.beginFill(0)
.moveTo(0, 0)
.lineTo(10, 0)
.lineTo(10, 10)
.lineTo(0, 10)
.beginHole()
.moveTo(2, 2)
.lineTo(8, 2)
.lineTo(8, 8)
.lineTo(2, 8)
.endHole();
expect(graphics.containsPoint(point1)).to.be.true;
expect(graphics.containsPoint(point2)).to.be.false;
});
it('should handle extra shapes in holes', function ()
{
const graphics = new Graphics();
graphics.beginFill(0)
.moveTo(3, 3)
.lineTo(5, 3)
.lineTo(5, 5)
.lineTo(3, 5)
.beginFill(0)
.moveTo(0, 0)
.lineTo(10, 0)
.lineTo(10, 10)
.lineTo(0, 10)
.beginHole()
.moveTo(2, 2)
.lineTo(8, 2)
.lineTo(8, 8)
.lineTo(2, 8)
.endHole()
.beginFill(0)
.moveTo(5, 5)
.lineTo(7, 5)
.lineTo(7, 7)
.lineTo(5, 7)
.endFill();
expect(graphics.containsPoint(new Point(1, 1))).to.be.true;
expect(graphics.containsPoint(new Point(4, 4))).to.be.true;
expect(graphics.containsPoint(new Point(4, 6))).to.be.false;
expect(graphics.containsPoint(new Point(6, 4))).to.be.false;
expect(graphics.containsPoint(new Point(6, 6))).to.be.true;
});
it('should take a matrix into account', function ()
{
const g = new Graphics();
const m = new Matrix();
g.beginFill(0xffffff, 1.0);
m.identity().translate(0, 100);
g.setMatrix(m.clone());
g.drawRect(0, 0, 10, 10);
m.identity().translate(200, 0);
g.setMatrix(m.clone());
g.drawRect(0, 0, 10, 10);
g.setMatrix(null);
g.drawRect(30, 40, 10, 10);
expect(g.containsPoint(new Point(5, 5))).to.be.false;
expect(g.containsPoint(new Point(5, 105))).to.be.true;
expect(g.containsPoint(new Point(205, 5))).to.be.true;
expect(g.containsPoint(new Point(35, 45))).to.be.true;
});
});
describe('chaining', function ()
{
it('should chain draw commands', function ()
{
// complex drawing #1: draw triangle, rounder rect and an arc (issue #3433)
const graphics = new Graphics().beginFill(0xFF3300)
.lineStyle(4, 0xffd900, 1)
.moveTo(50, 50)
.lineTo(250, 50)
.endFill()
.drawRoundedRect(150, 450, 300, 100, 15)
.beginHole()
.endHole()
.quadraticCurveTo(1, 1, 1, 1)
.bezierCurveTo(1, 1, 1, 1)
.arcTo(1, 1, 1, 1, 1)
.arc(1, 1, 1, 1, 1, false)
.drawRect(1, 1, 1, 1)
.drawRoundedRect(1, 1, 1, 1, 0.1)
.drawCircle(1, 1, 20)
.drawEllipse(1, 1, 1, 1)
.drawPolygon([1, 1, 1, 1, 1, 1])
.drawStar(1, 1, 1, 1, 1, 1)
.clear();
expect(graphics).to.be.not.null;
});
});
describe('drawPolygon', function ()
{
before(function ()
{
this.numbers = [0, 0, 10, 10, 20, 20];
this.points = [new Point(0, 0), new Point(10, 10), new Point(20, 20)];
this.poly = new Polygon(this.points);
});
it('should support polygon argument', function ()
{
const graphics = new Graphics();
expect(graphics.currentPath).to.be.null;
graphics.drawPolygon(this.poly);
expect(graphics.geometry.graphicsData[0]).to.be.not.null;
const result = graphics.geometry.graphicsData[0].shape.points;
expect(result).to.deep.equals(this.numbers);
});
it('should support array of numbers', function ()
{
const graphics = new Graphics();
expect(graphics.currentPath).to.be.null;
graphics.drawPolygon(this.numbers);
expect(graphics.geometry.graphicsData[0]).to.be.not.null;
const result = graphics.geometry.graphicsData[0].shape.points;
expect(result).to.deep.equals(this.numbers);
});
it('should support array of points', function ()
{
const graphics = new Graphics();
graphics.drawPolygon(this.points);
expect(graphics.geometry.graphicsData[0]).to.be.not.null;
const result = graphics.geometry.graphicsData[0].shape.points;
expect(result).to.deep.equals(this.numbers);
});
it('should support flat arguments of numbers', function ()
{
const graphics = new Graphics();
expect(graphics.currentPath).to.be.null;
graphics.drawPolygon(...this.numbers);
expect(graphics.geometry.graphicsData[0]).to.be.not.null;
const result = graphics.geometry.graphicsData[0].shape.points;
expect(result).to.deep.equals(this.numbers);
});
it('should support flat arguments of points', function ()
{
const graphics = new Graphics();
expect(graphics.currentPath).to.be.null;
graphics.drawPolygon(...this.points);
expect(graphics.geometry.graphicsData[0]).to.be.not.null;
const result = graphics.geometry.graphicsData[0].shape.points;
expect(result).to.deep.equals(this.numbers);
});
});
describe('arc', function ()
{
it('should draw an arc', function ()
{
const graphics = new Graphics();
expect(graphics.currentPath).to.be.null;
expect(() => graphics.arc(100, 30, 20, 0, Math.PI)).to.not.throw();
expect(graphics.currentPath).to.be.not.null;
});
it('should not throw with other shapes', function ()
{
// complex drawing #1: draw triangle, rounder rect and an arc (issue #3433)
const graphics = new Graphics();
// set a fill and line style
graphics.beginFill(0xFF3300);
graphics.lineStyle(4, 0xffd900, 1);
// draw a shape
graphics.moveTo(50, 50);
graphics.lineTo(250, 50);
graphics.lineTo(100, 100);
graphics.lineTo(50, 50);
graphics.endFill();
graphics.lineStyle(2, 0xFF00FF, 1);
graphics.beginFill(0xFF00BB, 0.25);
graphics.drawRoundedRect(150, 450, 300, 100, 15);
graphics.endFill();
graphics.beginFill();
graphics.lineStyle(4, 0x00ff00, 1);
expect(() => graphics.arc(300, 100, 20, 0, Math.PI)).to.not.throw();
});
it('should do nothing when startAngle and endAngle are equal', function ()
{
const graphics = new Graphics();
expect(graphics.currentPath).to.be.null;
graphics.arc(0, 0, 10, 0, 0);
expect(graphics.currentPath).to.be.null;
});
it('should do nothing if sweep equals zero', function ()
{
const graphics = new Graphics();
expect(graphics.currentPath).to.be.null;
graphics.arc(0, 0, 10, 10, 10);
expect(graphics.currentPath).to.be.null;
});
});
describe('_calculateBounds', function ()
{
it('should only call updateLocalBounds once when not empty', function ()
{
const graphics = new Graphics();
graphics.drawRect(0, 0, 10, 10);
const spy = sinon.spy(graphics.geometry, 'calculateBounds');
graphics._calculateBounds();
expect(spy).to.have.been.calledOnce;
graphics._calculateBounds();
expect(spy).to.have.been.calledOnce;
});
it('should not call updateLocalBounds when empty', function ()
{
const graphics = new Graphics();
const spy = sinon.spy(graphics.geometry, 'calculateBounds');
graphics._calculateBounds();
expect(spy).to.not.have.been.called;
graphics._calculateBounds();
expect(spy).to.not.have.been.called;
});
});
describe('getBounds', function ()
{
it('should use getBounds without stroke', function ()
{
const graphics = new Graphics();
graphics.beginFill(0x0).drawRect(10, 20, 100, 200);
const { x, y, width, height } = graphics.getBounds();
expect(x).to.equal(10);
expect(y).to.equal(20);
expect(width).to.equal(100);
expect(height).to.equal(200);
});
it('should use getBounds with stroke', function ()
{
const graphics = new Graphics();
graphics
.lineStyle(4, 0xff0000)
.beginFill(0x0)
.drawRect(10, 20, 100, 200);
const { x, y, width, height } = graphics.getBounds();
expect(x).to.equal(8);
expect(y).to.equal(18);
expect(width).to.equal(104);
expect(height).to.equal(204);
});
it('should be zero for empty Graphics', function ()
{
const graphics = new Graphics();
const { x, y, width, height } = graphics.getBounds();
expect(x).to.equal(0);
expect(y).to.equal(0);
expect(width).to.equal(0);
expect(height).to.equal(0);
});
it('should be zero after clear', function ()
{
const graphics = new Graphics();
graphics
.lineStyle(4, 0xff0000)
.beginFill(0x0)
.drawRect(10, 20, 100, 200)
.clear();
const { x, y, width, height } = graphics.getBounds();
expect(x).to.equal(0);
expect(y).to.equal(0);
expect(width).to.equal(0);
expect(height).to.equal(0);
});
it('should be equal of childs bounds when empty', function ()
{
const graphics = new Graphics();
const child = new Graphics();
child
.beginFill(0x0)
.drawRect(10, 20, 100, 200);
graphics.addChild(child);
const { x, y, width, height } = graphics.getBounds();
expect(x).to.equal(10);
expect(y).to.equal(20);
expect(width).to.equal(100);
expect(height).to.equal(200);
});
});
describe('drawCircle', function ()
{
it('should have no gaps in line border', function ()
{
const renderer = new Renderer(200, 200, {});
try
{
const graphics = new Graphics();
graphics.lineStyle(15, 0x8FC7E6);
graphics.drawCircle(100, 100, 30);
renderer.render(graphics);
const points = graphics.geometry.graphicsData[0].points;
// The first point is center, not first point on circumference
const firstX = points[0];
const firstY = points[1];
const lastX = points[points.length - 2];
const lastY = points[points.length - 1];
expect(firstX).to.equals(lastX);
expect(firstY).to.equals(lastY);
}
finally
{
renderer.destroy();
}
});
});
describe('startPoly', function ()
{
it('should fill two triangles', function ()
{
const graphics = new Graphics();
graphics.beginFill(0xffffff, 1.0);
graphics.moveTo(50, 50);
graphics.lineTo(250, 50);
graphics.lineTo(100, 100);
graphics.lineTo(50, 50);
graphics.moveTo(250, 50);
graphics.lineTo(450, 50);
graphics.lineTo(300, 100);
graphics.lineTo(250, 50);
graphics.endFill();
const data = graphics.geometry.graphicsData;
expect(data.length).to.equals(2);
expect(data[0].shape.points).to.eql([50, 50, 250, 50, 100, 100, 50, 50]);
expect(data[1].shape.points).to.eql([250, 50, 450, 50, 300, 100, 250, 50]);
});
it('should honor lineStyle break', function ()
{
const graphics = new Graphics();
graphics.lineStyle(1.0, 0xffffff);
graphics.moveTo(50, 50);
graphics.lineTo(250, 50);
graphics.lineStyle(2.0, 0xffffff);
graphics.lineTo(100, 100);
graphics.lineTo(50, 50);
graphics.lineStyle(0.0);
const data = graphics.geometry.graphicsData;
expect(data.length).to.equals(2);
expect(data[0].shape.points).to.eql([50, 50, 250, 50]);
expect(data[1].shape.points).to.eql([250, 50, 100, 100, 50, 50]);
});
});
describe('should support adaptive curves', function ()
{
const defMode = GRAPHICS_CURVES.adaptive;
const defMaxLen = GRAPHICS_CURVES.maxLength;
const myMaxLen = GRAPHICS_CURVES.maxLength = 1.0;
const graphics = new Graphics();
GRAPHICS_CURVES.adaptive = true;
graphics.beginFill(0xffffff, 1.0);
graphics.moveTo(610, 500);
graphics.quadraticCurveTo(600, 510, 590, 500);
graphics.endFill();
const pointsLen = graphics.geometry.graphicsData[0].shape.points.length / 2;
const arcLen = Math.PI / 2 * Math.sqrt(200);
const estimate = Math.ceil(arcLen / myMaxLen) + 1;
expect(pointsLen).to.be.closeTo(estimate, 2.0);
GRAPHICS_CURVES.adaptive = defMode;
GRAPHICS_CURVES.maxLength = defMaxLen;
});
describe('geometry', function ()
{
it('validateBatching should return false if any of textures is invalid', function ()
{
const graphics = new Graphics();
const invalidTex = Texture.EMPTY;
const validTex = Texture.WHITE;
graphics.beginTextureFill({ texture: invalidTex });
graphics.drawRect(0, 0, 10, 10);
graphics.beginTextureFill({ texture: validTex });
graphics.drawRect(0, 0, 10, 10);
const geometry = graphics.geometry;
expect(geometry.validateBatching()).to.be.false;
});
it('validateBatching should return true if all textures is valid', function ()
{
const graphics = new Graphics();
const validTex = Texture.WHITE;
graphics.beginTextureFill({ texture: validTex });
graphics.drawRect(0, 0, 10, 10);
graphics.beginTextureFill({ texture: validTex });
graphics.drawRect(0, 0, 10, 10);
const geometry = graphics.geometry;
expect(geometry.validateBatching()).to.be.true;
});
it('should be batchable if graphicsData is empty', function ()
{
const graphics = new Graphics();
const geometry = graphics.geometry;
geometry.updateBatches();
expect(geometry.batchable).to.be.true;
});
it('_compareStyles should return true for identical styles', function ()
{
const graphics = new Graphics();
const geometry = graphics.geometry;
const first = new FillStyle();
first.color = 0xff00ff;
first.alpha = 0.1;
first.visible = true;
const second = first.clone();
expect(geometry._compareStyles(first, second)).to.be.true;
const firstLine = new LineStyle();
firstLine.color = 0xff00ff;
firstLine.native = false;
firstLine.alignment = 1;
const secondLine = firstLine.clone();
expect(geometry._compareStyles(firstLine, secondLine)).to.be.true;
});
it('should be 1 batch for same styles', function ()
{
const graphics = new Graphics();
graphics.beginFill(0xff00ff, 0.5);
graphics.drawRect(0, 0, 20, 20);
graphics.drawRect(100, 0, 20, 20);
const geometry = graphics.geometry;
geometry.updateBatches();
expect(geometry.batches).to.have.lengthOf(1);
});
it('should be 2 batches for 2 different styles', function ()
{
const graphics = new Graphics();
// first style
graphics.beginFill(0xff00ff, 0.5);
graphics.drawRect(0, 0, 20, 20);
// second style
graphics.beginFill(0x0, 0.5);
graphics.drawRect(100, 0, 20, 20);
// third shape with same style
graphics.drawRect(0, 0, 20, 20);
const geometry = graphics.geometry;
geometry.updateBatches();
expect(geometry.batches).to.have.lengthOf(2);
});
it('should be 1 batch if fill and line are the same', function ()
{
const graphics = new Graphics();
graphics.lineStyle(10.0, 0x00ffff);
graphics.beginFill(0x00ffff);
graphics.drawRect(50, 50, 100, 100);
graphics.drawRect(150, 150, 100, 100);
const geometry = graphics.geometry;
geometry.updateBatches();
expect(geometry.batches).to.have.lengthOf(1);
});
it('should not use fill if triangulation does nothing', function ()
{
const graphics = new Graphics();
graphics
.lineStyle(2, 0x00ff00)
.beginFill(0xff0000)
.drawRect(0, 0, 100, 100)
.moveTo(200, 0)
.lineTo(250, 200);
const geometry = graphics.geometry;
geometry.updateBatches();
expect(geometry.batches).to.have.lengthOf(2);
expect(geometry.batches[0].style.color).to.equals(0xff0000);
expect(geometry.batches[0].size).to.equal(6);
expect(geometry.batches[1].style.color).to.equals(0x00ff00);
expect(geometry.batches[1].size).to.equal(30);
});
});
});
|
/*jslint node:true */
module.exports = {
fields: {
id: {required:true,createoptional:true,mutable:false},
text: {}
},
delete: {children:"deletechild",policy:"cascade"}
}; |
function isRegex(spec) {
return (spec && spec.op) ? spec : null;
}
module.exports = isRegex;
|
var config = require('../config/config.json');
var errorRoutes = require('../routes/ErrorRoutes.js');
var log = require('../models/rt_log.js').log;
module.exports = function(app){
app.get('/database/:dbType', function(req, res) {
var param = {};
param.title = req.params.dbType;
param.version = config.version;
if (req.user){
param.user = req.user;
}
log.distinct("Tag", function(error, results){
if (error) return handleError(error);
if ((results.indexOf(req.params.dbType) > -1)){
log.aggregate(
{ $match : { Tag: [ param.title ]}},
{ $sort : { _id : -1 } },
{ $group: { _id: { id: '$id', name: '$Name' } } })
.exec(function (err, result) {
if (err) return handleError(err);
param.data = [];
result.forEach(function(item) {
param.data.push(item._id);
});
res.render('database', param);
});
}
else{
errorRoutes.FileNotFound(req, res);
}
});
});
} |
require.config({
paths: {
"jquery": "lib/jquery-2.1.0.min",
"underscore": "lib/underscore-min",
"sockets": "sockets",
},
shim: {
"bootstrap": ["jquery"]
}
});
define([
"jquery",
"underscore",
"sockets",
], function($, _, socket) {
function getProgressBar() {
var elementId = Math.floor((Math.random()*10000000000000000)+1); // Generate random id
var uploadBox = $('<div class="col-sm-3 upload_box" id="' + elementId + '"></div>');
var progressBar = $('<div class="progress progress-info progress-striped active"><div class="progress-bar"></div></div>');
uploadBox.html(progressBar);
$('#uploads').prepend(uploadBox);
return progressBar;
};
function createDeleteAlbum() {
socket.emit('create-album', {
album: $('#album').val(),
create: $('#album-create i').hasClass('fa-check-square'),
delete: !$('#album-create i').hasClass('fa-check-square'),
pics: _.map($('.post'), function(post) { return $(post).attr('id') }).join(',')
});
};
function createDeleteAlbumClicked() {
var btn = $('#album-create i');
if (btn.hasClass('fa-square-o')) {
btn.removeClass('fa-square-o');
btn.addClass('fa-check-square');
btn.parent().removeClass('btn-default').addClass('btn-info');
} else {
btn.removeClass('fa-check-square');
btn.addClass('fa-square-o');
btn.parent().removeClass('btn-info').addClass('btn-default');
}
createDeleteAlbum();
};
$(document).ready(function() {
$(document).keyup(function(e) {
if ($('#back').length && e.keyCode == 27) {
window.location = $('#back').attr('href');
}
});
if ($('#album-create').length > 0) {
// Run this only if on new post page, not album pages
createDeleteAlbum();
$('#album-create').on('click', function(e) {
createDeleteAlbumClicked();
});
}
$('#upload').on('click', function(e){
e.preventDefault();
_.each($("#image")[0].files, function(file) {
var progressBar = getProgressBar(),
stream = socket.ss.createStream(),
blobStream = socket.ss.createBlobReadStream(file),
size = 0;
socket.ss(socket).emit('image-upload', stream, {
elementId: progressBar.parent()[0].id,
name: file,
size: file.size,
city: $('#city').val(),
restaurant: $('#restaurant').val(),
category: $('#category').val(),
item: $('#item').val(),
album: $('#album').val(),
pics: _.map($('.post'), function(post) { return $(post).attr('id') }).join(',')
});
blobStream.on('data', function(chunk) {
size += chunk.length;
progressBar.find('.progress-bar').css("width", Math.floor(size / file.size * 100) + '%');
});
blobStream.pipe(stream);
});
// Clear input values
var newInput = $('#image').clone();
$('#image').replaceWith(newInput);
// Grab image from url input
$('.image-url').each(function(index, image_input) {
if(!!$(image_input).val()) {
var progressBar = getProgressBar(),
stream = socket.ss.createStream(),
size = 0;
socket.ss(socket).emit('image-upload', stream, {
elementId: progressBar.parent()[0].id,
link: $(image_input).val(),
city: $('#city').val(),
restaurant: $('#restaurant').val(),
category: $('#category').val(),
item: $('#item').val(),
album: $('#album').val(),
pics: _.map($('.post'), function(post) { return $(post).attr('id') }).join(',')
});
socket.on('downloadProgress', function(data) {
progressBar.find('.progress-bar').css('width', data.progress);
});
$(image_input).val('');
}
});
});
});
});
|
var yoAssert = require('yeoman-assert')
var yoTest = require('yeoman-test')
var path = require('path')
var files = require('./files.json')
describe('generator-swill-boilerplate:app', function () {
before(function () {
return yoTest
.run(path.join(__dirname, '../app'))
.withPrompts({
preprocessor: 'stylus',
features: [],
options: [],
files: [],
license: 'unlicense'
})
.toPromise()
})
it('Base settings with Stylus', function () {
yoAssert.file(
files.base.concat(files.stylus)
)
})
})
|
function weatherReducer(state = [], action){
return state;
}
export default weatherReducer; |
"use strict";
const fs = require('fs-extra');
const ncp = require('ncp');
const path = require('path');
const config = require('./config');
const zipFolder = require('zip-folder');
const execSync = require('child_process').execSync;
const prompt = require('prompt');
const chokidar = require('chokidar');
const ap = require('c2-addon-parser');
ncp.limit = 0;
const dirs = {
HERE: path.join(process.cwd(), '/'),
SOURCE: path.join(process.cwd(), '/source'),
C2ADDON: path.join(process.cwd(), '/source/c2addon'),
C3ADDON: path.join(process.cwd(), '/source/c3addon'),
CAPX: path.join(process.cwd(), '/capx'),
VERSIONS: path.join(process.cwd(), '/versions'),
RELEASES: path.join(process.cwd(), '/releases')
};
const ADDON_NAME = process.cwd().split(path.sep).pop().replace(' ', '_');
const allowedTypes = { PLUGIN: 'plugin', BEHAVIOR: 'behavior' };
const dist = { C2: 'C2', C3: 'C3'};
function init(addonType)
{
if ( ! config.isReady())
{
_forceSetup();
return;
}
const allowedTypesArr = Object.keys(allowedTypes).map(function(key_)
{
return allowedTypes[key_];
});
if (allowedTypesArr.indexOf(addonType) === -1)
{
return console.error("'" + addonType + "' type is not supported, please use one of following instead: " + allowedTypesArr.join(", "));
}
console.log('Initializing addon "' + ADDON_NAME + '"');
if (_addonExists())
{
return console.error('ERROR: can\'t create addon, it already exists in this directory');
}
fs.mkdirSync(dirs.SOURCE);
fs.mkdirSync(dirs.C2ADDON);
fs.mkdirSync(dirs.C3ADDON);
fs.mkdirSync(dirs.CAPX);
fs.mkdirSync(dirs.VERSIONS);
fs.mkdirSync(dirs.RELEASES);
ncp(path.join(__dirname , '../templates' , addonType), dirs.C2ADDON, (err) =>
{
if (err) return console.error(err);
console.log("Template prepared successfully");
fs.renameSync(path.join(dirs.C2ADDON, 'files/my' + addonType), path.join(dirs.C2ADDON, 'files', ADDON_NAME));
var fileEditTime = path.join(dirs.C2ADDON, 'files', _getAddonName(), 'edittime.js');
_replaceInFile(fileEditTime, new RegExp(/<your website or a manual entry on Scirra\.com>/, 'g'), config.getWebsite(), () =>
{
_replaceInFile(fileEditTime, new RegExp(/<your name\/organisation>/, 'g'), config.getAuthor(), () =>
{
_replaceInFile(fileEditTime, new RegExp(/MyPlugin/, 'g'), ADDON_NAME);
});
});
var fileInfoXML = path.join(dirs.C2ADDON, 'info.xml');
_replaceInFile(fileInfoXML, new RegExp(/name>(.*)<\/name/, 'g'), 'name>' + ADDON_NAME + '</name', () =>
{
_replaceInFile(fileInfoXML, new RegExp(/author>(.*)<\/author/, 'g'), 'author>' + config.getAuthor() + '</author', () =>
{
_replaceInFile(fileInfoXML, new RegExp(/website>(.*)<\/website/, 'g'), 'website>' + config.getWebsite() + '</website', () =>
{
_replaceInFile(fileInfoXML, new RegExp(/documentation>(.*)<\/documentation/, 'g'), 'documentation>' + config.getWebsite() + '</documentation');
});
});
});
var fileRuntime = path.join(dirs.C2ADDON, 'files', _getAddonName(), 'runtime.js');
_replaceInFile(fileRuntime, new RegExp(/MyPlugin/, 'g'), ADDON_NAME);
});
ncp(path.join(__dirname, '../templates/capx'), dirs.CAPX, (err) =>
{
if (err) return console.error(err);
console.log("Capx prepared successfully");
fs.renameSync(path.join(dirs.CAPX, 'capx.capx'), path.join(dirs.CAPX, ADDON_NAME + '.capx'));
});
ncp(path.join(__dirname, '../templates/bat'), dirs.HERE, (err) =>
{
if (err) return console.error(err);
console.log("Bats prepared successfully");
});
}
function _forceSetup()
{
console.log('------ C2 Addon Assistant SETUP -----');
console.log('Before using "c2addona" you must complete the c2-addon-assistant setup');
config.startPrompt();
}
function update()
{
if ( ! config.isReady())
return _forceSetup();
if ( ! _addonExists())
return console.error('ERR: You are not in the root directory of the addon or addon does not exist');
//_runC2C3Converter();
_createAddonFile(dist.C2, 'beta-' + ADDON_NAME);
_createAddonFile(dist.C3, 'beta-' + ADDON_NAME);
_generateACE();
_updateC2Root();
}
function _generateACE()
{
var ace = ap.export(path.join(dirs.C2ADDON, 'files', _getAddonName()), 'markdown');
fs.writeFile(path.join(dirs.HERE, 'ACE.md'), ace, 'utf8', (err) =>
{
if (err) return console.error(err);
console.log('ACE.md created');
});
}
function release()
{
if ( ! config.isReady())
return _forceSetup();
if ( ! _addonExists())
return console.error('ERR: You are not in the root directory of the addon or addon does not exist');
if ( ! fs.existsSync('beta-' + ADDON_NAME + '.c2addon'))
return console.error('Can\'t find "' + 'beta-' + ADDON_NAME + '.c2addon" file. Please run "c2addona update" before attempting to release.');
var version = _getCurrentVersion();
var versionsDir = dirs.VERSIONS + '/v' + version;
if ( ! fs.existsSync(versionsDir))
{
fs.mkdirSync(versionsDir);
}
try
{
fs.copySync(path.join(dirs.HERE, '/beta-' + ADDON_NAME + '.c2addon'), path.join(versionsDir, ADDON_NAME + '_v' + version + '.c2addon'));
fs.copySync(path.join(dirs.HERE, '/beta-' + ADDON_NAME + '.c3addon'), path.join(versionsDir, ADDON_NAME + '_v' + version + '.c3addon'));
console.log('success!')
}
catch (err)
{
console.error(err)
}
fs.mkdirSync(path.join(versionsDir, '/capx'));
ncp(dirs.CAPX, path.join(versionsDir, '/capx'), (err) =>
{
if (err) return console.error(err);
var releaseFile = path.join(dirs.RELEASES, ADDON_NAME + '_v' + version + '.zip');
zipFolder(versionsDir, releaseFile, (err) =>
{
if(err)
{
console.log('ERR: Could not create ' + releaseFile + ' file. ERROR-MESSAGE: ' + err);
}
else
{
console.log(releaseFile + ' created successfully');
}
fs.removeSync(path.join(versionsDir, 'capx'));
});
});
}
function _updateC2Root()
{
var infoXML = path.join(dirs.C2ADDON, 'info.xml');
infoXML = fs.readFileSync(infoXML, 'utf8');
var addonType = (/type>plugin<\/type/.test(infoXML) ? allowedTypes.PLUGIN : allowedTypes.BEHAVIOR) + 's';
ncp(path.join(dirs.C2ADDON, 'files'), path.join(config.getC2Root(), 'exporters/html5', addonType), (err) =>
{
if (err) return console.error(err);
console.log("New version updated to C2");
});
}
/*function _runC2C3Converter()
{
console.log("Converting to C3...");
execSync('"' + path.join(__dirname, '../C2C3AddonConverter/C2C3AddonConverter.exe') + '" "' + path.join(dirs.C2ADDON, 'files', _getAddonName()) + '" "' + dirs.C3ADDON + '"', {stdio: [0, 1, 2]});
if (fs.existsSync(path.join(dirs.SOURCE, '/edittime.clean')))
{
fs.unlinkSync(path.join(dirs.SOURCE, '/edittime.clean'));
}
if (fs.existsSync(path.join(dirs.SOURCE, '/edittime.cleaner')))
{
fs.unlinkSync(path.join(dirs.SOURCE, '/edittime.cleaner'));
}
if (fs.existsSync(path.join(dirs.SOURCE, '/edittime.cleanest')))
{
fs.unlinkSync(path.join(dirs.SOURCE, '/edittime.cleanest'));
}
}*/
function _createAddonFile(dist_, filename_)
{
var source, fileExt;
switch (dist_)
{
case dist.C2:
source = dirs.C2ADDON;
fileExt = '.c2addon';
break;
case dist.C3:
source = dirs.C3ADDON;
fileExt = '.c3addon';
break;
}
filename_ += fileExt;
zipFolder(source, path.join(dirs.HERE, filename_), (err) =>
{
if(err)
{
console.log('ERR: Could not create ' + filename_ + ' file. ERROR-MESSAGE: ' + err);
}
else
{
console.log(filename_ + ' created successfully');
}
});
}
function _getAddonName()
{
return process.cwd().split(path.sep).pop().replace(' ', '_');
}
function _addonExists()
{
return fs.existsSync(dirs.C2ADDON);
}
function _replaceInFile(file_, search_, replace_, callback)
{
fs.readFile(file_, 'utf8', (err, data) =>
{
if (err) return console.error(err);
var result = data.replace(search_, replace_);
fs.writeFile(file_, result, 'utf8', (err) =>
{
if (err) return console.error(err);
if (callback) callback();
});
});
}
function _updateVersionInFiles(version_)
{
var versionXML = 'version>' + version_ + '</version';
var versionEdittime = '"version": "' + version_ + '"';
var fileInfoXML = path.join(dirs.C2ADDON, 'info.xml');
var fileEditTime = path.join(dirs.C2ADDON, 'files', _getAddonName(), 'edittime.js');
_replaceInFile(fileInfoXML, new RegExp(/version>(.*)<\/version/, 'g'), versionXML);
_replaceInFile(fileEditTime, new RegExp(/"version":\s*"[0-9\.]+"/, 'g'), versionEdittime);
}
function _getCurrentVersion()
{
var infoXML = path.join(dirs.C2ADDON, 'info.xml');
infoXML = fs.readFileSync(infoXML, 'utf8');
return infoXML.match(/<version>(.*)<\/version>/)[1];
}
function setVersion(version_)
{
if ( ! _addonExists())
return console.error('ERR: You are not in the root directory of the addon or addon does not exist');
if (version_)
{
if ( ! /[0-9\.]+/.test(version_))
return console.error('ERR: Invalid characters in version number "' + version_ + '". Only 0-9 and "." allowed.');
_updateVersionInFiles(version_);
}
else
{
console.log('Current version: ' + _getCurrentVersion());
var schema =
{
properties:
{
version:
{
pattern: /^[0-9\.]+$/,
message: 'Name must be only digits and dots',
required: true,
description: 'New version'
}
}
};
prompt.start();
prompt.get(schema, (err, result) =>
{
_updateVersionInFiles(result.version);
});
}
}
function watch()
{
console.log("Watching sources files...");
chokidar.watch(path.join(dirs.C2ADDON, 'files', ADDON_NAME), {
ignored: /(^|[\/\\])\../,
ignoreInitial: true
}).on('all', (event, path) => {
//console.log(event, path);
console.log("Updating plugin");
update();
});
}
module.exports = {
init: init,
update: update,
release: function()
{
console.log('It happens often that we forget to update the version number, therefore extra check here.');
var currentVersion = _getCurrentVersion();
var schema =
{
properties:
{
answer:
{
description: 'Release as version ' + currentVersion + '? (Y/n)',
required: true,
default: 'Y'
}
}
};
prompt.start();
prompt.get(schema, (err, result) =>
{
if (result.answer.toLowerCase() === 'y')
{
release();
}
});
},
setVersion: setVersion,
watch: watch,
};
|
$(function() {
var pageWrapper = $('.user-fill-profile');
/*
SELECT ALL DAYS
*/
pageWrapper.on('change', '.js-user-fill-profile-days input', function(e) {
var daysCheckbox = $(this);
pageWrapper
.find('.js-user-fill-profile-day input')
.each(function() {
$(this).prop('checked', daysCheckbox.prop('checked'));
});
});
/*
CHANGE ALL HOURS-FROM
*/
pageWrapper.on('change', '.js-user-fill-profile-hours-from-main select', function() {
var selected = $(this).prop('selectedIndex');
pageWrapper
.find('.js-user-fill-profile-hours-from .selectbox__list')
.each(function() {
$(this)
.find('.selectbox__item')
.eq(selected)
.trigger('click');
});
});
/*
CHANGE ALL HOURS-TO
*/
pageWrapper.on('change', '.js-user-fill-profile-hours-to-main select', function() {
var selected = $(this).prop('selectedIndex');
pageWrapper
.find('.js-user-fill-profile-hours-to .selectbox__list')
.each(function() {
$(this)
.find('.selectbox__item')
.eq(selected)
.trigger('click');
});
});
});
|
define(['./module'], function(services) {
'use strict';
services.factory('energyCalendarServ', ['$http', 'basicInfoServ',
function($http, basicInfo) {
return {
getMonthState: function(date) {
return $http.post('/GetEnergyCalendar', {
bodySign: basicInfo.bodySign,
time: Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', date)
});
},
getDayInfo: function(date) {
return $http.post('/GetWorkEnergy', {
bodySign: basicInfo.bodySign,
time: Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', date)
});
}
};
}
]);
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:86576568326ad97cb3cd192a708f6878ba653150b47af5b54c0dadefe1868c56
size 4048
|
const _ = require('lodash');
const chai = require('chai');
const expect = require('expect.js');
const Promise = require('bluebird');
const { inheritModel } = require('../../lib/model/inheritModel');
const { expectPartialEqual: expectPartEql } = require('./../../testUtils/testUtils');
const { Model, ValidationError, raw } = require('../../');
const { isPostgres, isSqlite } = require('../../lib/utils/knexUtils');
const mockKnexFactory = require('../../testUtils/mockKnex');
module.exports = (session) => {
const Model1 = session.models.Model1;
const Model2 = session.models.Model2;
describe('Model patch queries', () => {
describe('.query().patch()', () => {
beforeEach(() => {
return session.populate([
{
id: 1,
model1Prop1: 'hello 1',
model1Relation2: [
{
idCol: 1,
model2Prop1: 'text 1',
model2Prop2: 2,
},
{
idCol: 2,
model2Prop1: 'text 2',
model2Prop2: 1,
},
],
},
{
id: 2,
model1Prop1: 'hello 2',
},
{
id: 3,
model1Prop1: 'hello 3',
},
]);
});
it('should patch a model (1)', () => {
let model = Model1.fromJson({ model1Prop1: 'updated text' });
return Model1.query()
.patch(model)
.where('id', '=', 2)
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
expect(model.$beforeInsertCalled).to.equal(undefined);
expect(model.$afterInsertCalled).to.equal(undefined);
expect(model.$beforeDeleteCalled).to.equal(undefined);
expect(model.$afterDeleteCalled).to.equal(undefined);
expect(model.$beforeUpdateCalled).to.equal(1);
expect(model.$beforeUpdateOptions).to.eql({ patch: true });
expect(model.$afterUpdateCalled).to.equal(1);
expect(model.$afterUpdateOptions).to.eql({ patch: true });
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(3);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'updated text' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'hello 3' });
});
});
it('should patch a model (2)', () => {
let model = Model2.fromJson({ model2Prop1: 'updated text' });
return Model2.query()
.patch(model)
.where('id_col', '=', 1)
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
expect(model.$beforeInsertCalled).to.equal(undefined);
expect(model.$afterInsertCalled).to.equal(undefined);
expect(model.$beforeDeleteCalled).to.equal(undefined);
expect(model.$afterDeleteCalled).to.equal(undefined);
expect(model.$beforeUpdateCalled).to.equal(1);
expect(model.$beforeUpdateOptions).to.eql({ patch: true });
expect(model.$afterUpdateCalled).to.equal(1);
expect(model.$afterUpdateOptions).to.eql({ patch: true });
return session.knex('model2').orderBy('id_col');
})
.then((rows) => {
expect(rows).to.have.length(2);
expectPartEql(rows[0], { id_col: 1, model2_prop1: 'updated text', model2_prop2: 2 });
expectPartEql(rows[1], { id_col: 2, model2_prop1: 'text 2', model2_prop2: 1 });
});
});
it('should accept json', () => {
return Model1.query()
.patch({ model1Prop1: 'updated text' })
.where('id', '=', 2)
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(3);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'updated text' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'hello 3' });
});
});
it('should ignore non-objects in relation properties', () => {
return Model1.query()
.patch({
model1Prop1: 'updated text',
model1Relation1: 1,
model1Relation2: [1, 2, null, undefined, 5],
})
.where('id', '=', 2)
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(3);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'updated text' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'hello 3' });
});
});
it('should accept subqueries and raw expressions (1)', () => {
return Model1.query()
.patch({
model1Prop1: Model2.raw('(select max(??) from ??)', ['model2_prop1', 'model2']),
model1Prop2: Model2.query().sum('model2_prop2'),
})
.where('id', '=', 1)
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(3);
expectPartEql(rows[0], { id: 1, model1Prop1: 'text 2', model1Prop2: 3 });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'hello 3' });
});
});
it('should accept subqueries and raw expressions (2)', () => {
return Model1.query()
.patch({
model1Prop1: 'Morten',
model1Prop2: Model2.knexQuery().sum('model2_prop2'),
})
.where('id', '=', 1)
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(3);
expectPartEql(rows[0], { id: 1, model1Prop1: 'Morten', model1Prop2: 3 });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'hello 3' });
});
});
it('should patch multiple', () => {
return Model1.query()
.patch({ model1Prop1: 'updated text' })
.where('model1Prop1', '<', 'hello 3')
.then((numUpdated) => {
expect(numUpdated).to.equal(2);
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(3);
expectPartEql(rows[0], { id: 1, model1Prop1: 'updated text' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'updated text' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'hello 3' });
});
});
if (session.isPostgres()) {
it('should patch multiple and return updated rows if returning is useed', () => {
return Model1.query()
.patch({ model1Prop1: 'updated text' })
.where('model1Prop1', '<', 'hello 3')
.returning('*')
.then((updatedRows) => {
expect(updatedRows).to.have.length(2);
chai.expect(updatedRows).to.containSubset([
{
id: 1,
model1Id: null,
model1Prop1: 'updated text',
model1Prop2: null,
},
{
id: 2,
model1Id: null,
model1Prop1: 'updated text',
model1Prop2: null,
},
]);
});
});
}
it('increment should create patch', () => {
return Model2.query()
.increment('model2Prop2', 10)
.where('id_col', '=', 2)
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
return session.knex('model2').orderBy('id_col');
})
.then((rows) => {
expect(rows).to.have.length(2);
expectPartEql(rows[0], { id_col: 1, model2_prop2: 2 });
expectPartEql(rows[1], { id_col: 2, model2_prop2: 11 });
});
});
it('decrement should create patch', () => {
return Model2.query()
.decrement('model2Prop2', 10)
.where('id_col', '=', 2)
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
return session.knex('model2').orderBy('id_col');
})
.then((rows) => {
expect(rows).to.have.length(2);
expectPartEql(rows[0], { id_col: 1, model2_prop2: 2 });
expectPartEql(rows[1], { id_col: 2, model2_prop2: -9 });
});
});
it('should validate (1)', (done) => {
let ModelWithSchema = subClassWithSchema(Model1, {
type: 'object',
required: ['model1Prop2'],
properties: {
id: { type: ['number', 'null'] },
model1Prop1: { type: 'string' },
model1Prop2: { type: 'number' },
},
});
ModelWithSchema.query()
.patch({ model1Prop1: 100 })
.then(() => {
done(new Error('should not get here'));
})
.catch((err) => {
expect(err).to.be.a(ValidationError);
expect(err.type).to.equal('ModelValidation');
expect(err.data).to.eql({
model1Prop1: [
{
message: 'must be string',
keyword: 'type',
params: {
type: 'string',
},
},
],
});
return session.knex(Model1.getTableName());
})
.then((rows) => {
expect(_.map(rows, 'model1Prop1').sort()).to.eql(['hello 1', 'hello 2', 'hello 3']);
done();
})
.catch(done);
});
it('should skip requirement validation', (done) => {
let ModelWithSchema = subClassWithSchema(Model1, {
type: 'object',
required: ['model1Prop2'],
properties: {
id: { type: ['number', 'null'] },
model1Prop1: { type: 'string' },
model1Prop2: { type: 'number' },
},
});
ModelWithSchema.query()
.patch({ model1Prop1: 'text' })
.then(() => {
return session.knex(Model1.getTableName());
})
.then((rows) => {
expect(_.map(rows, 'model1Prop1').sort()).to.eql(['text', 'text', 'text']);
done();
})
.catch(done);
});
it('should be able to use objection.raw in hooks', () => {
class Test extends Model {
static get tableName() {
return 'Model1';
}
$beforeUpdate(opt, ctx) {
this.model1Prop2 = raw(`100 + 200`);
}
}
return Test.query(session.knex)
.findById(2)
.patch({
model1Prop1: 'updated',
})
.then(() => {
return Test.query(session.knex).findById(2);
})
.then((model) => {
expect(model).to.eql({
id: 2,
model1Id: null,
model1Prop1: 'updated',
model1Prop2: 300,
});
});
});
});
describe('.query().patchAndFetchById()', () => {
beforeEach(() => {
return session.populate([
{
id: 1,
model1Prop1: 'hello 1',
model1Relation2: [
{
idCol: 1,
model2Prop1: 'text 1',
model2Prop2: 2,
},
{
idCol: 2,
model2Prop1: 'text 2',
model2Prop2: 1,
},
],
},
{
id: 2,
model1Prop1: 'hello 2',
},
{
id: 3,
model1Prop1: 'hello 3',
},
]);
});
it('should patch and fetch a model', () => {
let model = Model1.fromJson({ model1Prop1: 'updated text' });
return Model1.query()
.patchAndFetchById(2, model)
.then((fetchedModel) => {
expect(model.$beforeInsertCalled).to.equal(undefined);
expect(model.$afterInsertCalled).to.equal(undefined);
expect(model.$beforeDeleteCalled).to.equal(undefined);
expect(model.$afterDeleteCalled).to.equal(undefined);
expect(model.$beforeUpdateCalled).to.equal(1);
expect(model.$beforeUpdateOptions).to.eql({ patch: true });
expect(model.$afterUpdateCalled).to.equal(1);
expect(model.$afterUpdateOptions).to.eql({ patch: true });
expect(fetchedModel).to.equal(model);
expect(fetchedModel).eql({
id: 2,
model1Prop1: 'updated text',
model1Prop2: null,
model1Id: null,
$beforeUpdateCalled: true,
$beforeUpdateOptions: { patch: true },
$afterUpdateCalled: true,
$afterUpdateOptions: { patch: true },
});
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(3);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'updated text' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'hello 3' });
});
});
it('should work with `eager` method', () => {
let model = Model1.fromJson({ model1Prop1: 'updated text' });
return Model1.query()
.patchAndFetchById(1, model)
.withGraphFetched('model1Relation2')
.modifyGraph('model1Relation2', (qb) => qb.orderBy('id_col'))
.then((fetchedModel) => {
expect(fetchedModel).eql({
id: 1,
model1Prop1: 'updated text',
model1Prop2: null,
model1Id: null,
$beforeUpdateCalled: true,
$beforeUpdateOptions: { patch: true },
$afterUpdateCalled: true,
$afterUpdateOptions: { patch: true },
model1Relation2: [
{
idCol: 1,
model1Id: 1,
model2Prop1: 'text 1',
model2Prop2: 2,
$afterFindCalled: 1,
},
{
idCol: 2,
model1Id: 1,
model2Prop1: 'text 2',
model2Prop2: 1,
$afterFindCalled: 1,
},
],
});
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(3);
expectPartEql(rows[0], { id: 1, model1Prop1: 'updated text' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'hello 3' });
});
});
it('should fetch nothing if nothing is updated', () => {
return Model1.query()
.patchAndFetchById(2, { model1Prop1: 'updated text' })
.where('id', -1)
.then((fetchedModel) => {
expect(fetchedModel).to.equal(undefined);
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(3);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'hello 3' });
});
});
});
describe('.$query().patch()', () => {
beforeEach(() => {
return session.populate([
{
id: 1,
model1Prop1: 'hello 1',
},
{
id: 2,
model1Prop1: 'hello 2',
},
]);
});
it('should patch a model (1)', () => {
let model = Model1.fromJson({ id: 1 });
return model
.$query()
.patch({ model1Prop1: 'updated text', undefinedShouldBeIgnored: undefined })
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
expect(model.model1Prop1).to.equal('updated text');
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(2);
expectPartEql(rows[0], { id: 1, model1Prop1: 'updated text' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
});
});
if (isPostgres(session.knex)) {
it('should work with returning', () => {
let model = Model1.fromJson({ id: 1 });
return model
.$query()
.patch({ model1Prop1: 'updated text' })
.returning('model1Prop1', 'model1Prop2')
.then((patched) => {
const expected = { model1Prop1: 'updated text', model1Prop2: null };
expect(patched).to.be.a(Model1);
expect(patched).to.eql(expected);
expect(model).to.eql(Object.assign({}, expected, { id: 1 }));
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(2);
expectPartEql(rows[0], { id: 1, model1Prop1: 'updated text' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
});
});
it('should work with returning *', () => {
const model = Model1.fromJson({ id: 1 });
return model
.$query()
.patch({ model1Prop1: 'updated text' })
.returning('*')
.then((patched) => {
const expected = {
id: 1,
model1Id: null,
model1Prop1: 'updated text',
model1Prop2: null,
};
expect(patched).to.be.a(Model1);
expect(patched).to.eql(expected);
expect(model).to.eql(expected);
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(2);
expectPartEql(rows[0], { id: 1, model1Prop1: 'updated text' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
});
});
}
it('should patch a model (2)', () => {
return Model1.fromJson({ id: 1, model1Prop1: 'updated text' })
.$query()
.patch()
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(2);
expectPartEql(rows[0], { id: 1, model1Prop1: 'updated text' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
});
});
it('should pass the old values to $beforeUpdate and $afterUpdate hooks in options.old', () => {
let patch = Model1.fromJson({ model1Prop1: 'updated text' });
return Model1.fromJson({ id: 1 })
.$query()
.patch(patch)
.then(() => {
expect(patch.$beforeInsertCalled).to.equal(undefined);
expect(patch.$afterInsertCalled).to.equal(undefined);
expect(patch.$beforeDeleteCalled).to.equal(undefined);
expect(patch.$afterDeleteCalled).to.equal(undefined);
expect(patch.$beforeUpdateCalled).to.equal(1);
expect(patch.$beforeUpdateOptions).to.eql({ patch: true, old: { id: 1 } });
expect(patch.$afterUpdateCalled).to.equal(1);
expect(patch.$afterUpdateOptions).to.eql({ patch: true, old: { id: 1 } });
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(2);
expectPartEql(rows[0], { id: 1, model1Prop1: 'updated text' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
});
});
it('model edits in $beforeUpdate should get into database query', () => {
let model = Model1.fromJson({ id: 1 });
model.$beforeUpdate = function () {
let self = this;
return Promise.delay(1).then(() => {
self.model1Prop1 = 'updated text';
});
};
return model
.$query()
.patch()
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(2);
expectPartEql(rows[0], { id: 1, model1Prop1: 'updated text' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
});
});
it('should throw if the id is undefined', (done) => {
let model = Model1.fromJson({ model1Prop2: 1 });
model
.$query()
.patch({ model1Prop1: 'updated text', undefinedShouldBeIgnored: undefined })
.then(() => {
done(new Error('should not get here'));
})
.catch((err) => {
expect(err.message).to.equal(
`one of the identifier columns [id] is null or undefined. Have you specified the correct identifier column for the model 'Model1' using the 'idColumn' property?`
);
done();
})
.catch(done);
});
it('should throw if the id is null', (done) => {
let model = Model1.fromJson({ id: null });
model
.$query()
.patch({ model1Prop1: 'updated text', undefinedShouldBeIgnored: undefined })
.then(() => {
done(new Error('should not get here'));
})
.catch((err) => {
expect(err.message).to.equal(
`one of the identifier columns [id] is null or undefined. Have you specified the correct identifier column for the model 'Model1' using the 'idColumn' property?`
);
done();
})
.catch(done);
});
});
describe('.$query().patchAndFetch()', () => {
let ModelOne;
let queries = [];
before(() => {
const knex = mockKnexFactory(session.knex, function (mock, oldImpl, args) {
queries.push(this.toString());
return oldImpl.apply(this, args);
});
ModelOne = session.unboundModels.Model1.bindKnex(knex);
});
beforeEach(() => {
queries = [];
return session.populate([
{
id: 1,
model1Prop1: 'hello 1',
},
{
id: 2,
model1Prop1: 'hello 2',
},
]);
});
it('should patch and fetch a model', () => {
let model = ModelOne.fromJson({ id: 1 });
return model
.$query()
.patchAndFetch({ model1Prop2: 10, undefinedShouldBeIgnored: undefined })
.then((updated) => {
expect(updated.id).to.equal(1);
expect(updated.model1Id).to.equal(null);
expect(updated.model1Prop1).to.equal('hello 1');
expect(updated.model1Prop2).to.equal(10);
expectPartEql(model, {
id: 1,
model1Prop1: 'hello 1',
model1Prop2: 10,
model1Id: null,
});
if (session.isPostgres()) {
expect(queries).to.eql([
'update "Model1" set "model1Prop2" = 10 where "Model1"."id" = 1',
'select "Model1".* from "Model1" where "Model1"."id" = 1',
]);
}
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(2);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1', model1Prop2: 10 });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2', model1Prop2: null });
});
});
});
describe('.$relatedQuery().patch()', () => {
describe('belongs to one relation', () => {
let parent1;
let parent2;
beforeEach(() => {
return session.populate([
{
id: 1,
model1Prop1: 'hello 1',
model1Relation1: {
id: 2,
model1Prop1: 'hello 2',
},
},
{
id: 3,
model1Prop1: 'hello 3',
model1Relation1: {
id: 4,
model1Prop1: 'hello 4',
},
},
]);
});
beforeEach(() => {
return Model1.query().then((parents) => {
parent1 = _.find(parents, { id: 1 });
parent2 = _.find(parents, { id: 3 });
});
});
it('should patch a related object (1)', () => {
const model = Model1.fromJson({ model1Prop1: 'updated text' });
return parent1
.$relatedQuery('model1Relation1')
.patch(model)
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(4);
expect(model.$beforeInsertCalled).to.equal(undefined);
expect(model.$afterInsertCalled).to.equal(undefined);
expect(model.$beforeDeleteCalled).to.equal(undefined);
expect(model.$afterDeleteCalled).to.equal(undefined);
expect(model.$beforeUpdateCalled).to.equal(1);
expect(model.$beforeUpdateOptions).to.eql({ patch: true });
expect(model.$afterUpdateCalled).to.equal(1);
expect(model.$afterUpdateOptions).to.eql({ patch: true });
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'updated text' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'hello 3' });
expectPartEql(rows[3], { id: 4, model1Prop1: 'hello 4' });
});
});
it('should patch a related object (2)', () => {
return parent2
.$relatedQuery('model1Relation1')
.patch({ model1Prop1: 'updated text', model1Prop2: 1000 })
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(4);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'hello 3' });
expectPartEql(rows[3], { id: 4, model1Prop1: 'updated text', model1Prop2: 1000 });
});
});
});
describe('has many relation', () => {
let parent1;
let parent2;
beforeEach(() => {
return session.populate([
{
id: 1,
model1Prop1: 'hello 1',
model1Relation2: [
{
idCol: 1,
model2Prop1: 'text 1',
model2Prop2: 6,
},
{
idCol: 2,
model2Prop1: 'text 2',
model2Prop2: 5,
},
{
idCol: 3,
model2Prop1: 'text 3',
model2Prop2: 4,
},
],
},
{
id: 2,
model1Prop1: 'hello 2',
model1Relation2: [
{
idCol: 4,
model2Prop1: 'text 4',
model2Prop2: 3,
},
{
idCol: 5,
model2Prop1: 'text 5',
model2Prop2: 2,
},
{
idCol: 6,
model2Prop1: 'text 6',
model2Prop2: 1,
},
],
},
]);
});
beforeEach(() => {
return Model1.query().then((parents) => {
parent1 = _.find(parents, { id: 1 });
parent2 = _.find(parents, { id: 2 });
});
});
it('should patch a related object', () => {
const model = Model2.fromJson({ model2Prop1: 'updated text' });
return parent1
.$relatedQuery('model1Relation2')
.patch(model)
.where('id_col', 2)
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
expect(model.$beforeInsertCalled).to.equal(undefined);
expect(model.$afterInsertCalled).to.equal(undefined);
expect(model.$beforeDeleteCalled).to.equal(undefined);
expect(model.$afterDeleteCalled).to.equal(undefined);
expect(model.$beforeUpdateCalled).to.equal(1);
expect(model.$beforeUpdateOptions).to.eql({ patch: true });
expect(model.$afterUpdateCalled).to.equal(1);
expect(model.$afterUpdateOptions).to.eql({ patch: true });
return session.knex('model2').orderBy('id_col');
})
.then((rows) => {
expect(rows).to.have.length(6);
expectPartEql(rows[0], { id_col: 1, model2_prop1: 'text 1' });
expectPartEql(rows[1], {
id_col: 2,
model2_prop1: 'updated text',
model2_prop2: 5,
});
expectPartEql(rows[2], { id_col: 3, model2_prop1: 'text 3' });
expectPartEql(rows[3], { id_col: 4, model2_prop1: 'text 4' });
expectPartEql(rows[4], { id_col: 5, model2_prop1: 'text 5' });
expectPartEql(rows[5], { id_col: 6, model2_prop1: 'text 6' });
});
});
it('should patch multiple related objects', () => {
return parent1
.$relatedQuery('model1Relation2')
.patch({ model2Prop1: 'updated text' })
.where('model2_prop2', '<', 6)
.where('model2_prop1', 'like', 'text %')
.then((numUpdated) => {
expect(numUpdated).to.equal(2);
return session.knex('model2').orderBy('id_col');
})
.then((rows) => {
expect(rows).to.have.length(6);
expectPartEql(rows[0], { id_col: 1, model2_prop1: 'text 1' });
expectPartEql(rows[1], {
id_col: 2,
model2_prop1: 'updated text',
model2_prop2: 5,
});
expectPartEql(rows[2], {
id_col: 3,
model2_prop1: 'updated text',
model2_prop2: 4,
});
expectPartEql(rows[3], { id_col: 4, model2_prop1: 'text 4' });
expectPartEql(rows[4], { id_col: 5, model2_prop1: 'text 5' });
expectPartEql(rows[5], { id_col: 6, model2_prop1: 'text 6' });
});
});
});
describe('many to many relation', () => {
let parent1;
let parent2;
beforeEach(() => {
return session.populate([
{
id: 1,
model1Prop1: 'hello 1',
model1Relation2: [
{
idCol: 1,
model2Prop1: 'text 1',
model2Relation1: [
{
id: 3,
model1Prop1: 'blaa 1',
model1Prop2: 6,
model1Relation1: {
id: 9,
model1Prop1: 'hoot',
},
},
{
id: 4,
model1Prop1: 'blaa 2',
model1Prop2: 5,
},
{
id: 5,
model1Prop1: 'blaa 3',
model1Prop2: 4,
},
],
},
],
model1Relation3: [
{
idCol: 3,
model2Prop1: 'foo 1',
extra1: 'extra 11',
extra2: 'extra 21',
},
{
idCol: 4,
model2Prop1: 'foo 2',
extra1: 'extra 12',
extra2: 'extra 22',
},
{
idCol: 5,
model2Prop1: 'foo 3',
extra1: 'extra 13',
extra2: 'extra 23',
},
],
},
{
id: 2,
model1Prop1: 'hello 2',
model1Relation2: [
{
idCol: 2,
model2Prop1: 'text 2',
model2Relation1: [
{
id: 6,
model1Prop1: 'blaa 4',
model1Prop2: 3,
},
{
id: 7,
model1Prop1: 'blaa 5',
model1Prop2: 2,
},
{
id: 8,
model1Prop1: 'blaa 6',
model1Prop2: 1,
},
],
},
],
model1Relation3: [
{
idCol: 6,
model2Prop1: 'foo 4',
extra1: 'extra 14',
extra2: 'extra 24',
},
{
idCol: 7,
model2Prop1: 'foo 5',
extra1: 'extra 15',
extra2: 'extra 25',
},
{
idCol: 8,
model2Prop1: 'foo 6',
extra1: 'extra 16',
extra2: 'extra 26',
},
],
},
]);
});
beforeEach(() => {
return Model2.query().then((parents) => {
parent1 = _.find(parents, { idCol: 1 });
parent2 = _.find(parents, { idCol: 2 });
});
});
it('should patch a related object', () => {
const model = Model1.fromJson({ model1Prop1: 'updated text' });
return parent1
.$relatedQuery('model2Relation1')
.patch(model)
.where('Model1.id', 5)
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
expect(model.$beforeInsertCalled).to.equal(undefined);
expect(model.$afterInsertCalled).to.equal(undefined);
expect(model.$beforeDeleteCalled).to.equal(undefined);
expect(model.$afterDeleteCalled).to.equal(undefined);
expect(model.$beforeUpdateCalled).to.equal(1);
expect(model.$beforeUpdateOptions).to.eql({ patch: true });
expect(model.$afterUpdateCalled).to.equal(1);
expect(model.$afterUpdateOptions).to.eql({ patch: true });
return session.knex('Model1').orderBy('Model1.id');
})
.then((rows) => {
expect(rows).to.have.length(9);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'blaa 1' });
expectPartEql(rows[3], { id: 4, model1Prop1: 'blaa 2' });
expectPartEql(rows[4], { id: 5, model1Prop1: 'updated text' });
expectPartEql(rows[5], { id: 6, model1Prop1: 'blaa 4' });
expectPartEql(rows[6], { id: 7, model1Prop1: 'blaa 5' });
expectPartEql(rows[7], { id: 8, model1Prop1: 'blaa 6' });
expectPartEql(rows[8], { id: 9, model1Prop1: 'hoot' });
});
});
it('should patch a related object with extras using patchAndFetchById', () => {
return Model1.query()
.findById(1)
.then((parent) => {
return parent.$relatedQuery('model1Relation3').patchAndFetchById(4, {
model2Prop1: 'iam updated',
extra1: 'updated extra 1',
// Test query properties. sqlite doesn't have `concat` function. Use a literal for it.
extra2: isSqlite(session.knex)
? 'updated extra 2'
: raw(`CONCAT('updated extra ', '2')`),
});
})
.then((result) => {
chai.expect(result).to.containSubset({
model2Prop1: 'iam updated',
extra1: 'updated extra 1',
extra2: 'updated extra 2',
idCol: 4,
});
return Model1.query().findById(1).withGraphFetched('model1Relation3');
})
.then((model1) => {
chai.expect(model1).to.containSubset({
id: 1,
model1Id: null,
model1Prop1: 'hello 1',
model1Prop2: null,
model1Relation3: [
{
idCol: 5,
model1Id: null,
model2Prop1: 'foo 3',
model2Prop2: null,
extra1: 'extra 13',
extra2: 'extra 23',
$afterFindCalled: 1,
},
{
idCol: 4,
model1Id: null,
model2Prop1: 'iam updated',
model2Prop2: null,
extra1: 'updated extra 1',
extra2: 'updated extra 2',
$afterFindCalled: 1,
},
{
idCol: 3,
model1Id: null,
model2Prop1: 'foo 1',
model2Prop2: null,
extra1: 'extra 11',
extra2: 'extra 21',
$afterFindCalled: 1,
},
],
$afterFindCalled: 1,
});
});
});
it('should patch a related object with extras', () => {
return Model1.query()
.findById(1)
.then((parent) => {
return parent
.$relatedQuery('model1Relation3')
.where('id_col', '>', 3)
.patch({
model2Prop1: 'iam updated',
extra1: 'updated extra 1',
// Test query properties. sqlite doesn't have `concat` function. Use a literal for it.
extra2: isSqlite(session.knex)
? 'updated extra 2'
: raw(`CONCAT('updated extra ', '2')`),
})
.where('id_col', '<', 5)
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
return Promise.all([
session.knex('model2').orderBy('id_col'),
session
.knex('Model1Model2')
.select('model1Id', 'model2Id', 'extra1', 'extra2')
.orderBy(['model1Id', 'model2Id']),
]);
})
.then(([model2, model1Model2]) => {
expect(model2.length).to.equal(8);
expect(model1Model2.length).to.equal(12);
expectPartEql(model2[0], { id_col: 1, model2_prop1: 'text 1' });
expectPartEql(model2[1], { id_col: 2, model2_prop1: 'text 2' });
expectPartEql(model2[2], { id_col: 3, model2_prop1: 'foo 1' });
expectPartEql(model2[3], { id_col: 4, model2_prop1: 'iam updated' });
expectPartEql(model2[4], { id_col: 5, model2_prop1: 'foo 3' });
expectPartEql(model2[5], { id_col: 6, model2_prop1: 'foo 4' });
expectPartEql(model2[6], { id_col: 7, model2_prop1: 'foo 5' });
expectPartEql(model2[7], { id_col: 8, model2_prop1: 'foo 6' });
expectPartEql(model1Model2[0], {
model1Id: 1,
extra1: 'extra 11',
extra2: 'extra 21',
});
expectPartEql(model1Model2[1], {
model1Id: 1,
extra1: 'updated extra 1',
extra2: 'updated extra 2',
});
expectPartEql(model1Model2[2], {
model1Id: 1,
extra1: 'extra 13',
extra2: 'extra 23',
});
expectPartEql(model1Model2[3], {
model1Id: 2,
extra1: 'extra 14',
extra2: 'extra 24',
});
expectPartEql(model1Model2[4], {
model1Id: 2,
extra1: 'extra 15',
extra2: 'extra 25',
});
expectPartEql(model1Model2[5], {
model1Id: 2,
extra1: 'extra 16',
extra2: 'extra 26',
});
expectPartEql(model1Model2[6], { extra1: null, extra2: null });
expectPartEql(model1Model2[7], { extra1: null, extra2: null });
expectPartEql(model1Model2[8], { extra1: null, extra2: null });
expectPartEql(model1Model2[9], { extra1: null, extra2: null });
expectPartEql(model1Model2[10], { extra1: null, extra2: null });
expectPartEql(model1Model2[11], { extra1: null, extra2: null });
});
});
});
it('should patch all related objects with extras', () => {
return Model1.query()
.findById(1)
.then((parent) => {
return parent
.$relatedQuery('model1Relation3')
.patch({
model2Prop1: 'iam updated',
extra1: 'updated extra 1',
extra2: 'updated extra 2',
})
.then((numUpdated) => {
expect(numUpdated).to.equal(3);
return Promise.all([
session.knex('model2').orderBy('id_col'),
session
.knex('Model1Model2')
.select('model1Id', 'model2Id', 'extra1', 'extra2')
.orderBy(['model1Id', 'model2Id']),
]);
})
.then(([model2, model1Model2]) => {
expect(model2.length).to.equal(8);
expect(model1Model2.length).to.equal(12);
expectPartEql(model2[0], { id_col: 1, model2_prop1: 'text 1' });
expectPartEql(model2[1], { id_col: 2, model2_prop1: 'text 2' });
expectPartEql(model2[2], { id_col: 3, model2_prop1: 'iam updated' });
expectPartEql(model2[3], { id_col: 4, model2_prop1: 'iam updated' });
expectPartEql(model2[4], { id_col: 5, model2_prop1: 'iam updated' });
expectPartEql(model2[5], { id_col: 6, model2_prop1: 'foo 4' });
expectPartEql(model2[6], { id_col: 7, model2_prop1: 'foo 5' });
expectPartEql(model2[7], { id_col: 8, model2_prop1: 'foo 6' });
expectPartEql(model1Model2[0], {
model1Id: 1,
extra1: 'updated extra 1',
extra2: 'updated extra 2',
});
expectPartEql(model1Model2[1], {
model1Id: 1,
extra1: 'updated extra 1',
extra2: 'updated extra 2',
});
expectPartEql(model1Model2[2], {
model1Id: 1,
extra1: 'updated extra 1',
extra2: 'updated extra 2',
});
expectPartEql(model1Model2[3], {
model1Id: 2,
extra1: 'extra 14',
extra2: 'extra 24',
});
expectPartEql(model1Model2[4], {
model1Id: 2,
extra1: 'extra 15',
extra2: 'extra 25',
});
expectPartEql(model1Model2[5], {
model1Id: 2,
extra1: 'extra 16',
extra2: 'extra 26',
});
expectPartEql(model1Model2[6], { extra1: null, extra2: null });
expectPartEql(model1Model2[7], { extra1: null, extra2: null });
expectPartEql(model1Model2[8], { extra1: null, extra2: null });
expectPartEql(model1Model2[9], { extra1: null, extra2: null });
expectPartEql(model1Model2[10], { extra1: null, extra2: null });
expectPartEql(model1Model2[11], { extra1: null, extra2: null });
});
});
});
it('should patch all related objects', () => {
return parent2
.$relatedQuery('model2Relation1')
.patch({ model1Prop1: 'updated text', model1Prop2: 123 })
.then((numUpdated) => {
expect(numUpdated).to.equal(3);
return session.knex('Model1').orderBy('Model1.id');
})
.then((rows) => {
expect(rows).to.have.length(9);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'blaa 1' });
expectPartEql(rows[3], { id: 4, model1Prop1: 'blaa 2' });
expectPartEql(rows[4], { id: 5, model1Prop1: 'blaa 3' });
expectPartEql(rows[5], { id: 6, model1Prop1: 'updated text', model1Prop2: 123 });
expectPartEql(rows[6], { id: 7, model1Prop1: 'updated text', model1Prop2: 123 });
expectPartEql(rows[7], { id: 8, model1Prop1: 'updated text', model1Prop2: 123 });
});
});
it('should patch multiple objects (1)', () => {
return parent2
.$relatedQuery('model2Relation1')
.patch({ model1Prop1: 'updated text', model1Prop2: 123 })
.where('model1Prop1', 'like', 'blaa 4')
.orWhere('model1Prop1', 'like', 'blaa 6')
.then((numUpdated) => {
expect(numUpdated).to.equal(2);
return session.knex('Model1').orderBy('Model1.id');
})
.then((rows) => {
expect(rows).to.have.length(9);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'blaa 1' });
expectPartEql(rows[3], { id: 4, model1Prop1: 'blaa 2' });
expectPartEql(rows[4], { id: 5, model1Prop1: 'blaa 3' });
expectPartEql(rows[5], { id: 6, model1Prop1: 'updated text', model1Prop2: 123 });
expectPartEql(rows[6], { id: 7, model1Prop1: 'blaa 5' });
expectPartEql(rows[7], { id: 8, model1Prop1: 'updated text', model1Prop2: 123 });
});
});
it('should patch multiple objects (2)', () => {
return parent1
.$relatedQuery('model2Relation1')
.patch({ model1Prop1: 'updated text', model1Prop2: 123 })
.where('model1Prop2', '<', 6)
.then((numUpdated) => {
expect(numUpdated).to.equal(2);
return session.knex('Model1').orderBy('Model1.id');
})
.then((rows) => {
expect(rows).to.have.length(9);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'blaa 1' });
expectPartEql(rows[3], { id: 4, model1Prop1: 'updated text', model1Prop2: 123 });
expectPartEql(rows[4], { id: 5, model1Prop1: 'updated text', model1Prop2: 123 });
expectPartEql(rows[5], { id: 6, model1Prop1: 'blaa 4' });
expectPartEql(rows[6], { id: 7, model1Prop1: 'blaa 5' });
expectPartEql(rows[7], { id: 8, model1Prop1: 'blaa 6' });
});
});
it('should be able to use `joinRelated`', () => {
return parent1
.$relatedQuery('model2Relation1')
.innerJoinRelated('model1Relation1')
.patch({ model1Prop1: 'updated text', model1Prop2: 123 })
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
return session.knex('Model1').orderBy('Model1.id');
})
.then((rows) => {
expect(rows).to.have.length(9);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'updated text', model1Prop2: 123 });
expectPartEql(rows[3], { id: 4, model1Prop1: 'blaa 2' });
expectPartEql(rows[4], { id: 5, model1Prop1: 'blaa 3' });
expectPartEql(rows[5], { id: 6, model1Prop1: 'blaa 4' });
expectPartEql(rows[6], { id: 7, model1Prop1: 'blaa 5' });
expectPartEql(rows[7], { id: 8, model1Prop1: 'blaa 6' });
});
});
});
describe('has one through relation', () => {
let parent;
beforeEach(() => {
return session.populate([
{
id: 1,
model1Prop1: 'hello 1',
model1Relation2: [
{
idCol: 1,
model2Prop1: 'text 1',
model2Relation2: {
id: 3,
model1Prop1: 'blaa 1',
model1Prop2: 6,
},
},
],
},
{
id: 2,
model1Prop1: 'hello 2',
model1Relation2: [
{
idCol: 2,
model2Prop1: 'text 2',
model2Relation2: {
id: 7,
model1Prop1: 'blaa 5',
model1Prop2: 2,
},
},
],
},
]);
});
beforeEach(() => {
return Model2.query().then((parents) => {
parent = _.find(parents, { idCol: 1 });
});
});
it('should patch the related object', () => {
return parent
.$relatedQuery('model2Relation2')
.patch({ model1Prop1: 'updated text' })
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
return session.knex('Model1').orderBy('Model1.id');
})
.then((rows) => {
expect(rows).to.have.length(4);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'updated text' });
expectPartEql(rows[3], { id: 7, model1Prop1: 'blaa 5' });
});
});
});
});
describe('.relatedQuery().patch()', () => {
describe('belongs to one relation', () => {
beforeEach(() => {
return session.populate([
{
id: 1,
model1Prop1: 'hello 1',
model1Relation1: {
id: 2,
model1Prop1: 'hello 2',
},
},
{
id: 3,
model1Prop1: 'hello 3',
model1Relation1: {
id: 4,
model1Prop1: 'hello 4',
},
},
]);
});
it('should patch a related object by id (1)', () => {
const model = Model1.fromJson({ model1Prop1: 'updated text' });
return Model1.relatedQuery('model1Relation1')
.for(1)
.patch(model)
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(4);
expect(model.$beforeInsertCalled).to.equal(undefined);
expect(model.$afterInsertCalled).to.equal(undefined);
expect(model.$beforeDeleteCalled).to.equal(undefined);
expect(model.$afterDeleteCalled).to.equal(undefined);
expect(model.$beforeUpdateCalled).to.equal(1);
expect(model.$beforeUpdateOptions).to.eql({ patch: true });
expect(model.$afterUpdateCalled).to.equal(1);
expect(model.$afterUpdateOptions).to.eql({ patch: true });
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'updated text' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'hello 3' });
expectPartEql(rows[3], { id: 4, model1Prop1: 'hello 4' });
});
});
it('should patch a related object by id (2)', () => {
return Model1.relatedQuery('model1Relation1')
.for(3)
.patch({ model1Prop1: 'updated text', model1Prop2: 1000 })
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(4);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'hello 3' });
expectPartEql(rows[3], { id: 4, model1Prop1: 'updated text', model1Prop2: 1000 });
});
});
it('should patch a related object by two ids', () => {
return Model1.relatedQuery('model1Relation1')
.for([1, 3])
.patch({ model1Prop1: 'updated text', model1Prop2: 1000 })
.then((numUpdated) => {
expect(numUpdated).to.equal(2);
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(4);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'updated text', model1Prop2: 1000 });
expectPartEql(rows[2], { id: 3, model1Prop1: 'hello 3' });
expectPartEql(rows[3], { id: 4, model1Prop1: 'updated text', model1Prop2: 1000 });
});
});
it('should patch a related object by subquery', () => {
return Model1.relatedQuery('model1Relation1')
.for(Model1.query().where('id', 1))
.patch({ model1Prop1: 'updated text', model1Prop2: 1000 })
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
return session.knex('Model1').orderBy('id');
})
.then((rows) => {
expect(rows).to.have.length(4);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'updated text', model1Prop2: 1000 });
expectPartEql(rows[2], { id: 3, model1Prop1: 'hello 3' });
expectPartEql(rows[3], { id: 4, model1Prop1: 'hello 4' });
});
});
});
describe('has many relation', () => {
beforeEach(() => {
return session.populate([
{
id: 1,
model1Prop1: 'hello 1',
model1Relation2: [
{
idCol: 1,
model2Prop1: 'text 1',
model2Prop2: 6,
},
{
idCol: 2,
model2Prop1: 'text 2',
model2Prop2: 5,
},
{
idCol: 3,
model2Prop1: 'text 3',
model2Prop2: 4,
},
],
},
{
id: 2,
model1Prop1: 'hello 2',
model1Relation2: [
{
idCol: 4,
model2Prop1: 'text 4',
model2Prop2: 3,
},
{
idCol: 5,
model2Prop1: 'text 5',
model2Prop2: 2,
},
{
idCol: 6,
model2Prop1: 'text 6',
model2Prop2: 1,
},
],
},
{
id: 3,
model1Prop1: 'hello 3',
model1Relation2: [
{
idCol: 7,
model2Prop1: 'text 7',
model2Prop2: 0,
},
],
},
]);
});
it('should patch a related object', () => {
const model = Model2.fromJson({ model2Prop1: 'updated text' });
return Model1.relatedQuery('model1Relation2')
.for(1)
.patch(model)
.where('id_col', 2)
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
expect(model.$beforeInsertCalled).to.equal(undefined);
expect(model.$afterInsertCalled).to.equal(undefined);
expect(model.$beforeDeleteCalled).to.equal(undefined);
expect(model.$afterDeleteCalled).to.equal(undefined);
expect(model.$beforeUpdateCalled).to.equal(1);
expect(model.$beforeUpdateOptions).to.eql({ patch: true });
expect(model.$afterUpdateCalled).to.equal(1);
expect(model.$afterUpdateOptions).to.eql({ patch: true });
return session.knex('model2').orderBy('id_col');
})
.then((rows) => {
expect(rows).to.have.length(7);
expectPartEql(rows[0], { id_col: 1, model2_prop1: 'text 1' });
expectPartEql(rows[1], {
id_col: 2,
model2_prop1: 'updated text',
model2_prop2: 5,
});
expectPartEql(rows[2], { id_col: 3, model2_prop1: 'text 3' });
expectPartEql(rows[3], { id_col: 4, model2_prop1: 'text 4' });
expectPartEql(rows[4], { id_col: 5, model2_prop1: 'text 5' });
expectPartEql(rows[5], { id_col: 6, model2_prop1: 'text 6' });
expectPartEql(rows[6], { id_col: 7, model2_prop1: 'text 7' });
});
});
it('should patch multiple related objects', () => {
return Model1.relatedQuery('model1Relation2')
.for(1)
.patch({ model2Prop1: 'updated text' })
.where('model2_prop2', '<', 6)
.where('model2_prop1', 'like', 'text %')
.then((numUpdated) => {
expect(numUpdated).to.equal(2);
return session.knex('model2').orderBy('id_col');
})
.then((rows) => {
expect(rows).to.have.length(7);
expectPartEql(rows[0], { id_col: 1, model2_prop1: 'text 1' });
expectPartEql(rows[1], {
id_col: 2,
model2_prop1: 'updated text',
model2_prop2: 5,
});
expectPartEql(rows[2], {
id_col: 3,
model2_prop1: 'updated text',
model2_prop2: 4,
});
expectPartEql(rows[3], { id_col: 4, model2_prop1: 'text 4' });
expectPartEql(rows[4], { id_col: 5, model2_prop1: 'text 5' });
expectPartEql(rows[5], { id_col: 6, model2_prop1: 'text 6' });
expectPartEql(rows[6], { id_col: 7, model2_prop1: 'text 7' });
});
});
it('should patch multiple related objects for multiple parents', () => {
return Model1.relatedQuery('model1Relation2')
.for([1, 2])
.patch({ model2Prop1: 'updated text' })
.where('model2_prop1', '!=', 'text 4')
.then((numUpdated) => {
expect(numUpdated).to.equal(5);
return session.knex('model2').orderBy('id_col');
})
.then((rows) => {
expect(rows).to.have.length(7);
expectPartEql(rows[0], { id_col: 1, model2_prop1: 'updated text' });
expectPartEql(rows[1], { id_col: 2, model2_prop1: 'updated text' });
expectPartEql(rows[2], { id_col: 3, model2_prop1: 'updated text' });
expectPartEql(rows[3], { id_col: 4, model2_prop1: 'text 4' });
expectPartEql(rows[4], { id_col: 5, model2_prop1: 'updated text' });
expectPartEql(rows[5], { id_col: 6, model2_prop1: 'updated text' });
expectPartEql(rows[6], { id_col: 7, model2_prop1: 'text 7' });
});
});
it('should patch multiple related objects for multiple parents using a subquery', () => {
return Model1.relatedQuery('model1Relation2')
.for(Model1.query().findByIds([1, 2]))
.patch({ model2Prop1: 'updated text' })
.where('model2_prop1', '!=', 'text 4')
.then((numUpdated) => {
expect(numUpdated).to.equal(5);
return session.knex('model2').orderBy('id_col');
})
.then((rows) => {
expect(rows).to.have.length(7);
expectPartEql(rows[0], { id_col: 1, model2_prop1: 'updated text' });
expectPartEql(rows[1], { id_col: 2, model2_prop1: 'updated text' });
expectPartEql(rows[2], { id_col: 3, model2_prop1: 'updated text' });
expectPartEql(rows[3], { id_col: 4, model2_prop1: 'text 4' });
expectPartEql(rows[4], { id_col: 5, model2_prop1: 'updated text' });
expectPartEql(rows[5], { id_col: 6, model2_prop1: 'updated text' });
expectPartEql(rows[6], { id_col: 7, model2_prop1: 'text 7' });
});
});
});
describe('many to many relation', () => {
beforeEach(() => {
return session.populate([
{
id: 1,
model1Prop1: 'hello 1',
model1Relation2: [
{
idCol: 1,
model2Prop1: 'text 1',
model2Relation1: [
{
id: 3,
model1Prop1: 'blaa 1',
model1Prop2: 6,
model1Relation1: {
id: 9,
model1Prop1: 'hoot',
},
},
{
id: 4,
model1Prop1: 'blaa 2',
model1Prop2: 5,
},
{
id: 5,
model1Prop1: 'blaa 3',
model1Prop2: 4,
},
],
},
],
model1Relation3: [
{
idCol: 3,
model2Prop1: 'foo 1',
extra1: 'extra 11',
extra2: 'extra 21',
},
{
idCol: 4,
model2Prop1: 'foo 2',
extra1: 'extra 12',
extra2: 'extra 22',
},
{
idCol: 5,
model2Prop1: 'foo 3',
extra1: 'extra 13',
extra2: 'extra 23',
},
],
},
{
id: 2,
model1Prop1: 'hello 2',
model1Relation2: [
{
idCol: 2,
model2Prop1: 'text 2',
model2Relation1: [
{
id: 6,
model1Prop1: 'blaa 4',
model1Prop2: 3,
},
{
id: 7,
model1Prop1: 'blaa 5',
model1Prop2: 2,
},
{
id: 8,
model1Prop1: 'blaa 6',
model1Prop2: 1,
},
],
},
],
model1Relation3: [
{
idCol: 6,
model2Prop1: 'foo 4',
extra1: 'extra 14',
extra2: 'extra 24',
},
{
idCol: 7,
model2Prop1: 'foo 5',
extra1: 'extra 15',
extra2: 'extra 25',
},
{
idCol: 8,
model2Prop1: 'foo 6',
extra1: 'extra 16',
extra2: 'extra 26',
},
],
},
]);
});
it('should patch a related object', () => {
const model = Model1.fromJson({ model1Prop1: 'updated text' });
return Model2.relatedQuery('model2Relation1')
.for(1)
.patch(model)
.where('Model1.id', 5)
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
expect(model.$beforeInsertCalled).to.equal(undefined);
expect(model.$afterInsertCalled).to.equal(undefined);
expect(model.$beforeDeleteCalled).to.equal(undefined);
expect(model.$afterDeleteCalled).to.equal(undefined);
expect(model.$beforeUpdateCalled).to.equal(1);
expect(model.$beforeUpdateOptions).to.eql({ patch: true });
expect(model.$afterUpdateCalled).to.equal(1);
expect(model.$afterUpdateOptions).to.eql({ patch: true });
return session.knex('Model1').orderBy('Model1.id');
})
.then((rows) => {
expect(rows).to.have.length(9);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'blaa 1' });
expectPartEql(rows[3], { id: 4, model1Prop1: 'blaa 2' });
expectPartEql(rows[4], { id: 5, model1Prop1: 'updated text' });
expectPartEql(rows[5], { id: 6, model1Prop1: 'blaa 4' });
expectPartEql(rows[6], { id: 7, model1Prop1: 'blaa 5' });
expectPartEql(rows[7], { id: 8, model1Prop1: 'blaa 6' });
expectPartEql(rows[8], { id: 9, model1Prop1: 'hoot' });
});
});
it('should patch a related object with extras', () => {
return Model1.relatedQuery('model1Relation3')
.for(1)
.where('id_col', '>', 3)
.patch({
model2Prop1: 'iam updated',
extra1: 'updated extra 1',
// Test query properties. sqlite doesn't have `concat` function. Use a literal for it.
extra2: isSqlite(session.knex)
? 'updated extra 2'
: raw(`CONCAT('updated extra ', '2')`),
})
.where('id_col', '<', 5)
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
return Promise.all([
session.knex('model2').orderBy('id_col'),
session
.knex('Model1Model2')
.select('model1Id', 'model2Id', 'extra1', 'extra2')
.orderBy(['model1Id', 'model2Id']),
]);
})
.then(([model2, model1Model2]) => {
expect(model2.length).to.equal(8);
expect(model1Model2.length).to.equal(12);
expectPartEql(model2[0], { id_col: 1, model2_prop1: 'text 1' });
expectPartEql(model2[1], { id_col: 2, model2_prop1: 'text 2' });
expectPartEql(model2[2], { id_col: 3, model2_prop1: 'foo 1' });
expectPartEql(model2[3], { id_col: 4, model2_prop1: 'iam updated' });
expectPartEql(model2[4], { id_col: 5, model2_prop1: 'foo 3' });
expectPartEql(model2[5], { id_col: 6, model2_prop1: 'foo 4' });
expectPartEql(model2[6], { id_col: 7, model2_prop1: 'foo 5' });
expectPartEql(model2[7], { id_col: 8, model2_prop1: 'foo 6' });
expectPartEql(model1Model2[0], {
model1Id: 1,
extra1: 'extra 11',
extra2: 'extra 21',
});
expectPartEql(model1Model2[1], {
model1Id: 1,
extra1: 'updated extra 1',
extra2: 'updated extra 2',
});
expectPartEql(model1Model2[2], {
model1Id: 1,
extra1: 'extra 13',
extra2: 'extra 23',
});
expectPartEql(model1Model2[3], {
model1Id: 2,
extra1: 'extra 14',
extra2: 'extra 24',
});
expectPartEql(model1Model2[4], {
model1Id: 2,
extra1: 'extra 15',
extra2: 'extra 25',
});
expectPartEql(model1Model2[5], {
model1Id: 2,
extra1: 'extra 16',
extra2: 'extra 26',
});
expectPartEql(model1Model2[6], { extra1: null, extra2: null });
expectPartEql(model1Model2[7], { extra1: null, extra2: null });
expectPartEql(model1Model2[8], { extra1: null, extra2: null });
expectPartEql(model1Model2[9], { extra1: null, extra2: null });
expectPartEql(model1Model2[10], { extra1: null, extra2: null });
expectPartEql(model1Model2[11], { extra1: null, extra2: null });
});
});
it('should patch all related objects with extras', () => {
return Model1.relatedQuery('model1Relation3')
.for(1)
.patch({
model2Prop1: 'iam updated',
extra1: 'updated extra 1',
extra2: 'updated extra 2',
})
.then((numUpdated) => {
expect(numUpdated).to.equal(3);
return Promise.all([
session.knex('model2').orderBy('id_col'),
session
.knex('Model1Model2')
.select('model1Id', 'model2Id', 'extra1', 'extra2')
.orderBy(['model1Id', 'model2Id']),
]);
})
.then(([model2, model1Model2]) => {
expect(model2.length).to.equal(8);
expect(model1Model2.length).to.equal(12);
expectPartEql(model2[0], { id_col: 1, model2_prop1: 'text 1' });
expectPartEql(model2[1], { id_col: 2, model2_prop1: 'text 2' });
expectPartEql(model2[2], { id_col: 3, model2_prop1: 'iam updated' });
expectPartEql(model2[3], { id_col: 4, model2_prop1: 'iam updated' });
expectPartEql(model2[4], { id_col: 5, model2_prop1: 'iam updated' });
expectPartEql(model2[5], { id_col: 6, model2_prop1: 'foo 4' });
expectPartEql(model2[6], { id_col: 7, model2_prop1: 'foo 5' });
expectPartEql(model2[7], { id_col: 8, model2_prop1: 'foo 6' });
expectPartEql(model1Model2[0], {
model1Id: 1,
extra1: 'updated extra 1',
extra2: 'updated extra 2',
});
expectPartEql(model1Model2[1], {
model1Id: 1,
extra1: 'updated extra 1',
extra2: 'updated extra 2',
});
expectPartEql(model1Model2[2], {
model1Id: 1,
extra1: 'updated extra 1',
extra2: 'updated extra 2',
});
expectPartEql(model1Model2[3], {
model1Id: 2,
extra1: 'extra 14',
extra2: 'extra 24',
});
expectPartEql(model1Model2[4], {
model1Id: 2,
extra1: 'extra 15',
extra2: 'extra 25',
});
expectPartEql(model1Model2[5], {
model1Id: 2,
extra1: 'extra 16',
extra2: 'extra 26',
});
expectPartEql(model1Model2[6], { extra1: null, extra2: null });
expectPartEql(model1Model2[7], { extra1: null, extra2: null });
expectPartEql(model1Model2[8], { extra1: null, extra2: null });
expectPartEql(model1Model2[9], { extra1: null, extra2: null });
expectPartEql(model1Model2[10], { extra1: null, extra2: null });
expectPartEql(model1Model2[11], { extra1: null, extra2: null });
});
});
it('should patch all related objects', () => {
return Model2.relatedQuery('model2Relation1')
.for(2)
.patch({ model1Prop1: 'updated text', model1Prop2: 123 })
.then((numUpdated) => {
expect(numUpdated).to.equal(3);
return session.knex('Model1').orderBy('Model1.id');
})
.then((rows) => {
expect(rows).to.have.length(9);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'blaa 1' });
expectPartEql(rows[3], { id: 4, model1Prop1: 'blaa 2' });
expectPartEql(rows[4], { id: 5, model1Prop1: 'blaa 3' });
expectPartEql(rows[5], { id: 6, model1Prop1: 'updated text', model1Prop2: 123 });
expectPartEql(rows[6], { id: 7, model1Prop1: 'updated text', model1Prop2: 123 });
expectPartEql(rows[7], { id: 8, model1Prop1: 'updated text', model1Prop2: 123 });
});
});
it('should patch multiple related objects for multiple parents', () => {
return Model2.relatedQuery('model2Relation1')
.for([1, 2])
.patch({ model1Prop1: 'updated text' })
.where('model1Prop1', '!=', 'blaa 2')
.then((numUpdated) => {
expect(numUpdated).to.equal(5);
return session.knex('Model1').orderBy('Model1.id');
})
.then((rows) => {
expect(rows).to.have.length(9);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'updated text' });
expectPartEql(rows[3], { id: 4, model1Prop1: 'blaa 2' });
expectPartEql(rows[4], { id: 5, model1Prop1: 'updated text' });
expectPartEql(rows[5], { id: 6, model1Prop1: 'updated text' });
expectPartEql(rows[6], { id: 7, model1Prop1: 'updated text' });
expectPartEql(rows[7], { id: 8, model1Prop1: 'updated text' });
});
});
it('should patch multiple related objects for multiple parents using a subquery', () => {
return Model2.relatedQuery('model2Relation1')
.for(Model2.query().findByIds([1, 2]))
.patch({ model1Prop1: 'updated text' })
.where('model1Prop1', '!=', 'blaa 2')
.then((numUpdated) => {
expect(numUpdated).to.equal(5);
return session.knex('Model1').orderBy('Model1.id');
})
.then((rows) => {
expect(rows).to.have.length(9);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'updated text' });
expectPartEql(rows[3], { id: 4, model1Prop1: 'blaa 2' });
expectPartEql(rows[4], { id: 5, model1Prop1: 'updated text' });
expectPartEql(rows[5], { id: 6, model1Prop1: 'updated text' });
expectPartEql(rows[6], { id: 7, model1Prop1: 'updated text' });
expectPartEql(rows[7], { id: 8, model1Prop1: 'updated text' });
});
});
it('should patch multiple objects (1)', () => {
return Model2.relatedQuery('model2Relation1')
.for(2)
.patch({ model1Prop1: 'updated text', model1Prop2: 123 })
.where('model1Prop1', 'like', 'blaa 4')
.orWhere('model1Prop1', 'like', 'blaa 6')
.then((numUpdated) => {
expect(numUpdated).to.equal(2);
return session.knex('Model1').orderBy('Model1.id');
})
.then((rows) => {
expect(rows).to.have.length(9);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'blaa 1' });
expectPartEql(rows[3], { id: 4, model1Prop1: 'blaa 2' });
expectPartEql(rows[4], { id: 5, model1Prop1: 'blaa 3' });
expectPartEql(rows[5], { id: 6, model1Prop1: 'updated text', model1Prop2: 123 });
expectPartEql(rows[6], { id: 7, model1Prop1: 'blaa 5' });
expectPartEql(rows[7], { id: 8, model1Prop1: 'updated text', model1Prop2: 123 });
});
});
it('should patch multiple objects (2)', () => {
return Model2.relatedQuery('model2Relation1')
.for(1)
.patch({ model1Prop1: 'updated text', model1Prop2: 123 })
.where('model1Prop2', '<', 6)
.then((numUpdated) => {
expect(numUpdated).to.equal(2);
return session.knex('Model1').orderBy('Model1.id');
})
.then((rows) => {
expect(rows).to.have.length(9);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'blaa 1' });
expectPartEql(rows[3], { id: 4, model1Prop1: 'updated text', model1Prop2: 123 });
expectPartEql(rows[4], { id: 5, model1Prop1: 'updated text', model1Prop2: 123 });
expectPartEql(rows[5], { id: 6, model1Prop1: 'blaa 4' });
expectPartEql(rows[6], { id: 7, model1Prop1: 'blaa 5' });
expectPartEql(rows[7], { id: 8, model1Prop1: 'blaa 6' });
});
});
it('should be able to use `joinRelated`', () => {
return Model2.relatedQuery('model2Relation1')
.for(1)
.innerJoinRelated('model1Relation1')
.patch({ model1Prop1: 'updated text', model1Prop2: 123 })
.then((numUpdated) => {
expect(numUpdated).to.equal(1);
return session.knex('Model1').orderBy('Model1.id');
})
.then((rows) => {
expect(rows).to.have.length(9);
expectPartEql(rows[0], { id: 1, model1Prop1: 'hello 1' });
expectPartEql(rows[1], { id: 2, model1Prop1: 'hello 2' });
expectPartEql(rows[2], { id: 3, model1Prop1: 'updated text', model1Prop2: 123 });
expectPartEql(rows[3], { id: 4, model1Prop1: 'blaa 2' });
expectPartEql(rows[4], { id: 5, model1Prop1: 'blaa 3' });
expectPartEql(rows[5], { id: 6, model1Prop1: 'blaa 4' });
expectPartEql(rows[6], { id: 7, model1Prop1: 'blaa 5' });
expectPartEql(rows[7], { id: 8, model1Prop1: 'blaa 6' });
});
});
});
});
describe('hooks', () => {
let ModelOne;
let ModelTwo;
let beforeUpdateCalled = '';
let afterUpdateCalled = '';
let beforeUpdateOpt = null;
let afterUpdateOpt = null;
before(() => {
// Create a new knex object by wrapping session.knex so that we get a new
// instance instead of a cached one from `bindKnex`.
const knex = mockKnexFactory(session.knex, function (mock, oldImpl, args) {
return oldImpl.apply(this, args);
});
ModelOne = session.unboundModels.Model1.bindKnex(knex);
ModelTwo = ModelOne.getRelation('model1Relation2').relatedModelClass;
expect(ModelOne).to.not.equal(Model1);
expect(ModelTwo).to.not.equal(Model2);
expect(ModelOne).to.not.equal(session.unboundModels.Model1);
expect(ModelTwo).to.not.equal(session.unboundModels.Model2);
ModelOne.prototype.$beforeUpdate = function (opt, ctx) {
beforeUpdateCalled += 'ModelOne';
beforeUpdateOpt = _.cloneDeep(opt);
};
ModelOne.prototype.$afterUpdate = function (opt, ctx) {
afterUpdateCalled += 'ModelOne';
afterUpdateOpt = _.cloneDeep(opt);
};
ModelTwo.prototype.$beforeUpdate = function (opt, ctx) {
beforeUpdateCalled += 'ModelTwo';
beforeUpdateOpt = _.cloneDeep(opt);
};
ModelTwo.prototype.$afterUpdate = function (opt, ctx) {
afterUpdateCalled += 'ModelTwo';
afterUpdateOpt = _.cloneDeep(opt);
};
});
beforeEach(() => {
beforeUpdateCalled = '';
afterUpdateCalled = '';
beforeUpdateOpt = null;
afterUpdateOpt = null;
});
beforeEach(() => {
return session.populate([
{
id: 1,
model1Prop1: 'hello 1',
model1Relation1: {
id: 2,
model1Prop1: 'hello 2',
},
model1Relation2: [
{
idCol: 1,
model2Prop1: 'foo 1',
},
],
model1Relation3: [
{
idCol: 2,
model2Prop1: 'foo 2',
},
],
},
]);
});
it('.query().patch()', () => {
return ModelOne.query()
.findById(1)
.patch({ model1Prop1: 'updated text' })
.then(() => {
expect(beforeUpdateCalled).to.equal('ModelOne');
expect(beforeUpdateOpt).to.eql({ patch: true });
expect(afterUpdateCalled).to.equal('ModelOne');
expect(afterUpdateOpt).to.eql({ patch: true });
});
});
it('.$query().patch()', () => {
return ModelOne.query()
.findById(1)
.then((model) => {
return model.$query().patch({ model1Prop1: 'updated text' });
})
.then(() => {
expect(beforeUpdateCalled).to.equal('ModelOne');
expect(beforeUpdateOpt).to.eql({
patch: true,
old: {
$afterFindCalled: 1,
id: 1,
model1Id: 2,
model1Prop1: 'hello 1',
model1Prop2: null,
},
});
expect(afterUpdateCalled).to.equal('ModelOne');
expect(afterUpdateOpt).to.eql({
patch: true,
old: {
$afterFindCalled: 1,
id: 1,
model1Id: 2,
model1Prop1: 'hello 1',
model1Prop2: null,
},
});
});
});
describe('$relatedQuery().patch()', () => {
it('belongs to one relation', () => {
return ModelOne.query()
.findById(1)
.then((model) => {
return model.$relatedQuery('model1Relation1').patch({ model1Prop1: 'updated text' });
})
.then(() => {
expect(beforeUpdateCalled).to.equal('ModelOne');
expect(beforeUpdateOpt).to.eql({ patch: true });
expect(afterUpdateCalled).to.equal('ModelOne');
expect(afterUpdateOpt).to.eql({ patch: true });
});
});
it('has many relation', () => {
return ModelOne.query()
.findById(1)
.then((model) => {
return model.$relatedQuery('model1Relation2').patch({ model2Prop1: 'updated text' });
})
.then(() => {
expect(beforeUpdateCalled).to.equal('ModelTwo');
expect(beforeUpdateOpt).to.eql({ patch: true });
expect(afterUpdateCalled).to.equal('ModelTwo');
expect(afterUpdateOpt).to.eql({ patch: true });
});
});
it('many to many relation', () => {
return ModelOne.query()
.findById(1)
.then((model) => {
return model.$relatedQuery('model1Relation3').patch({ model2Prop1: 'updated text' });
})
.then(() => {
expect(beforeUpdateCalled).to.equal('ModelTwo');
expect(beforeUpdateOpt).to.eql({ patch: true });
expect(afterUpdateCalled).to.equal('ModelTwo');
expect(afterUpdateOpt).to.eql({ patch: true });
});
});
});
});
function subClassWithSchema(Model, schema) {
let SubModel = inheritModel(Model);
SubModel.jsonSchema = schema;
return SubModel;
}
});
};
|
const { app, globalShortcut } = require('electron')
angular.module('puraApp').component('services', {
templateUrl: './src/services/services.html',
controller: servicesController,
bindings: {}
})
.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
$stateProvider
.state('services', {
url: '/services',
component: 'services'
})
$urlRouterProvider.otherwise('/');
})
function servicesController($sce, $uibModal, User, $log, Services, $rootScope, $timeout, $scope) {
var self = this;
this.userServices = User.getServices();
this.getWebViews = getWebViews;
this.availableServices = Services.get();
$timeout(() => {
getWebViews();
}, 1000);
$rootScope.$on('newService', (event, newService) => {
console.log("refreshServices called" + newService);
this.userServices.push(newService);
// need to add webview listener
});
this.trustSrc = (src) => {
return $sce.trustAsResourceUrl(src);
}
this.getPreloadJS = (service) => {
if (service.has_preloader) {
return './src/services/preloaders/' + service.name + '.js';
}
}
function hideTabsPane() {
$('.tab-pane').css('display', 'none');
$('.tab-pane .active').css('display', 'block');
}
function getWebViews() {
const webviews = document.getElementsByClassName('service_views');
angular.forEach(webviews, (webview) => {
var serviceName = webview.id;
var service = _.find(self.availableServices, { name: serviceName });
if (service.has_preloader) {
webview.addEventListener("dom-ready", function() {
console.log('webview dom loaded');
//webview.openDevTools();
webview.executeJavaScript(service.name + '.init()');
});
webview.addEventListener('ipc-message', (event) => {
ipcMessageHandler(event);
})
}
});
}
function ipcMessageHandler(event) {
if (event.channel === 'notification-count') {
var notification = event.args[0];
var targetWebview = event.target;
var label = targetWebview.attributes.label.value;
var service = _.find(self.userServices, { label: label });
updateCountInService(service, notification);
}
if (event.channel === 'notification-message') {
var notification = event.args[0];
var targetWebview = event.target;
var label = targetWebview.attributes.label.value;
var service = _.find(self.userServices, { label: label });
updateOverViewInService(service, notification);
}
if (event.channel === 'notification-click') {
var targetWebview = event.target;
var label = targetWebview.attributes.label.value;
var service = _.find(self.userServices, { label: label });
focusService(service);
}
}
function updateCountInService(service, notification) {
service.notification = notification;
$scope.$apply(service);
}
function updateOverViewInService() {
console.log('updateOnverview called');
}
function focusService(service) {
console.log("trying to focus window");
window.focus();
app.focus();
}
}
angular.module('puraApp').controller('ModalInstanceCtrl', function($uibModalInstance, service) {
var $ctrl = this;
$ctrl.service = service;
$ctrl.ok = function() {
};
$ctrl.cancel = function() {
$uibModalInstance.dismiss('cancel');
};
$ctrl.addService = function() {
var userConfig = {
name: $ctrl.name,
serviceURL: $ctrl.serviceURL
}
if ($ctrl.service.isTeamRequired) {
userConfig.serviceURL = 'https://' + $ctrl.domain + $ctrl.serviceURL;
}
var data = {
service: $ctrl.service,
userConfig: userConfig
}
$uibModalInstance.close(data);
}
})
angular.module('puraApp').directive('sortableTab', function($timeout, $document) {
return {
link: function(scope, element, attrs, controller) {
// Attempt to integrate with ngRepeat
// https://github.com/angular/angular.js/blob/master/src/ng/directive/ngRepeat.js#L211
var match = attrs.ngRepeat.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
var tabs;
scope.$watch(match[2], function(newTabs) {
tabs = newTabs;
});
var index = scope.$index;
scope.$watch('$index', function(newIndex) {
index = newIndex;
});
attrs.$set('draggable', true);
// Wrapped in $apply so Angular reacts to changes
var wrappedListeners = {
// On item being dragged
dragstart: function(e) {
e.originalEvent.dataTransfer.effectAllowed = 'move';
e.originalEvent.dataTransfer.dropEffect = 'move';
e.originalEvent.dataTransfer.setData('application/json', index);
element.addClass('dragging');
},
dragend: function(e) {
//e.stopPropagation();
element.removeClass('dragging');
},
// On item being dragged over / dropped onto
dragenter: function(e) {},
dragleave: function(e) {
element.removeClass('hover');
},
drop: function(e) {
e.preventDefault();
e.stopPropagation();
var sourceIndex = e.originalEvent.dataTransfer.getData('application/json');
move(sourceIndex, index);
element.removeClass('hover');
}
};
// For performance purposes, do not
// call $apply for these
var unwrappedListeners = {
dragover: function(e) {
e.preventDefault();
element.addClass('hover');
},
/* Use .hover instead of :hover. :hover doesn't play well with
moving DOM from under mouse when hovered */
mouseenter: function() {
element.addClass('hover');
},
mouseleave: function() {
element.removeClass('hover');
}
};
angular.forEach(wrappedListeners, function(listener, event) {
element.on(event, wrap(listener));
});
angular.forEach(unwrappedListeners, function(listener, event) {
element.on(event, listener);
});
function wrap(fn) {
return function(e) {
scope.$apply(function() {
fn(e);
});
};
}
function move(fromIndex, toIndex) {
// http://stackoverflow.com/a/7180095/1319998
tabs.splice(toIndex, 0, tabs.splice(fromIndex, 1)[0]);
};
}
}
});
|
var inside = require('turf-inside');
/**
* Calculates the maximum value of a field for a set of {@link Point|points} within a set of {@link Polygon|polygons}.
*
* @module turf/max
* @category aggregation
* @param {FeatureCollection<Polygon>} polygons input polygons
* @param {FeatureCollection<Point>} points input points
* @param {String} inField the field in input data to analyze
* @param {String} outField the field in which to store results
* @return {FeatureCollection<Polygon>} polygons
* with properties listed as `outField` values
* @example
* var polygons = {
* "type": "FeatureCollection",
* "features": [
* {
* "type": "Feature",
* "properties": {},
* "geometry": {
* "type": "Polygon",
* "coordinates": [[
* [101.551437, 3.150114],
* [101.551437, 3.250208],
* [101.742324, 3.250208],
* [101.742324, 3.150114],
* [101.551437, 3.150114]
* ]]
* }
* }, {
* "type": "Feature",
* "properties": {},
* "geometry": {
* "type": "Polygon",
* "coordinates": [[
* [101.659927, 3.011612],
* [101.659927, 3.143944],
* [101.913986, 3.143944],
* [101.913986, 3.011612],
* [101.659927, 3.011612]
* ]]
* }
* }
* ]
* };
* var points = {
* "type": "FeatureCollection",
* "features": [
* {
* "type": "Feature",
* "properties": {
* "population": 200
* },
* "geometry": {
* "type": "Point",
* "coordinates": [101.56105, 3.213874]
* }
* }, {
* "type": "Feature",
* "properties": {
* "population": 600
* },
* "geometry": {
* "type": "Point",
* "coordinates": [101.709365, 3.211817]
* }
* }, {
* "type": "Feature",
* "properties": {
* "population": 100
* },
* "geometry": {
* "type": "Point",
* "coordinates": [101.645507, 3.169311]
* }
* }, {
* "type": "Feature",
* "properties": {
* "population": 200
* },
* "geometry": {
* "type": "Point",
* "coordinates": [101.708679, 3.071266]
* }
* }, {
* "type": "Feature",
* "properties": {
* "population": 300
* },
* "geometry": {
* "type": "Point",
* "coordinates": [101.826782, 3.081551]
* }
* }
* ]
* };
*
* var aggregated = turf.max(
* polygons, points, 'population', 'max');
*
* var resultFeatures = points.features.concat(
* aggregated.features);
* var result = {
* "type": "FeatureCollection",
* "features": resultFeatures
* };
*
* //=result
*/
module.exports = function(polyFC, ptFC, inField, outField) {
polyFC.features.forEach(function(poly) {
if(!poly.properties) {
poly.properties = {};
}
var values = [];
ptFC.features.forEach(function(pt) {
if (inside(pt, poly)) {
values.push(pt.properties[inField]);
}
});
poly.properties[outField] = max(values);
});
return polyFC;
};
function max(x) {
var value;
for (var i = 0; i < x.length; i++) {
// On the first iteration of this loop, max is
// undefined and is thus made the maximum element in the array
if (x[i] > value || value === undefined) value = x[i];
}
return value;
}
|
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Promotions = require('../models/promotions');
var promoRouter = express.Router();
promoRouter.use(bodyParser.json());
promoRouter.route('/')
.get(function(req,res,next){
Promotions.find({}, function (err, promotion) {
if (err) throw err;
res.json(promotion);
});
})
.post(function(req, res, next){
Promotions.create(req.body, function (err, promotion) {
if (err) throw err;
console.log('Promotion created!');
var id = promotion._id;
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Added the promotion with id: ' + id);
});
})
.delete(function(req, res, next){
Promotions.remove({}, function (err, resp) {
if (err) throw err;
res.json(resp);
});
});
promoRouter.route('/:promotionId')
.get(function(req,res,next){
Promotions.findById(req.params.promotionId, function (err, promotion) {
if (err) throw err;
res.json(promotion);
});
})
.put(function(req, res, next){
Promotions.findByIdAndUpdate(req.params.promotionId, {
$set: req.body
}, {
new: true
}, function (err, promotion) {
if (err) throw err;
res.json(promotion);
});
})
.delete(function(req, res, next){
Dishes.findByIdAndRemove(req.params.promotionId, function (err, resp){
if (err) throw err;
res.json(resp);
});
});
module.exports = promoRouter;
|
require=function r(e,o,n){function t(i,f){if(!o[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=o[i]={exports:{}};e[i][0].call(p.exports,function(r){var o=e[i][1][r];return t(o?o:r)},p,p.exports,r,e,o,n)}return o[i].exports}for(var u="function"==typeof require&&require,i=0;i<n.length;i++)t(n[i]);return t}({5:[function(r,e,o){var n=r("colors");e.exports=n.red},{colors:6}]},{},[5]);
|
//Building a basic Synth UI using jQuery
//Uses a 2D synth pad to control frequency and volume of basic additive synthesis
define(["inheritance", "./synthPad"], function(Inheritance, SynthPad){'use strict';
var basicUI = Class.extend({
init : function(synth){
var container = $("#main-container");
this.pad = new SynthPad(synth.minFreq, synth.maxFreq, 0, 100);
var infoDiv = $('<div />', {
'id' : 'info'
});
var infoTitle = $('<h1 />', {
'html' : 'Theremin-like Synth Pad'
});
var description = $('<p />', {
'html' : "Click and drag the mouse over the synth pad to generate a sound"
});
var frequencyLabel = $('<p />', {
'html' : 'Frequency '
});
var volumeLabel = $('<p />', {
'html' : 'Volume '
});
this.frequency = $("<span />",{
'html' : 'n/a'
});
this.volume = $("<span />", {
'html' : 'n/a'
});
this.setupEvents(synth);
frequencyLabel.append(this.frequency);
volumeLabel.append(this.volume);
infoDiv.append(infoTitle);
infoDiv.append(description);
infoDiv.append(frequencyLabel);
infoDiv.append(volumeLabel);
container.append(this.pad.canvasElement);
container.append(infoDiv);
},
setupEvents : function(synth){
// Disables scrolling on touch devices.
document.body.addEventListener('touchmove', function(event) {
event.preventDefault();
}, false);
var frequency = this.frequency[0]; //expose frequency
var volume = this.volume[0]; //expose volume
var pad = this.pad; //expose pad;
//this is where we'll define the various extra functions that a pad calls
this.pad.update = function(evt){
var trueYVal = 1 - (evt.yVal / 100);
synth.updateFrequency(evt.xVal);
synth.updateVolume(trueYVal);
frequency.innerHTML = Math.floor(evt.xVal) + " Hz";
volume.innerHTML = Math.floor(trueYVal * 100) + "%";
};
this.pad.startControl = function(evt){
//FIXME:force an update position call
pad.handlers.handleUpdatePosition(evt);
console.log('freq', synth.getFrequency());
synth.playSound();
};
this.pad.endControl = function(evt){
synth.stopSound();
};
console.log('pad', this.pad);
}
});
return basicUI;
});
|
"use strict";
var fs = require('fs');
var cat_1 = require('./cat');
var insider;
(function (insider) {
var res = require('[response]');
var c = new cat_1.Cat();
c.name = 'tom';
var value = fs.readFileSync(__dirname + '/cat.ts').toString();
res.writeHead(200, {
"Content-Type": "text/plain"
});
res.end(JSON.stringify(c) + '\n' + value);
})(insider || (insider = {}));
//# sourceMappingURL=test.cgi.js.map |
define(['require', 'jquery', 'hammer'], function (require, $, Hammer) {
var environment = require('modules/environment');
var reader = require('modules/reader');
var settings = require('modules/settings');
var events = require('modules/events');
var Mobile = function () {
settings.el.css('overflow-y', 'scroll');
var el = document.getElementsByTagName('body')[0],
frame = document.getElementById('main'),
controls = document.getElementsByClassName('controls')[0],
wasScrolling = reader.isScrolling,
doubleTapped = false,
wasHolding = false,
touchTimer,
options = {
behavior: {
doubleTapInterval: 200,
contentZooming: 'none',
touchAction: 'none',
touchCallout: 'none',
userDrag: 'none'
},
dragLockToAxis: true,
dragBlockHorizontal: true
},
hammer = new Hammer(el, options);
hammer.on('touch release pinchin pinchout dragend doubletap tap', function (e) {
console.log(e);
var target = $(e.target);
doubleTapped = false;
clearTimeout(touchTimer);
if (!target.is('.control-btn') && !target.is('.chapter-nav') && !target.is(frame) && !target.parents().is(frame)) {
e.preventDefault();
e.stopPropagation();
e.gesture.preventDefault();
e.gesture.stopPropagation();
e.gesture.stopDetect();
} else if (target.is(frame) || target.parents().is(frame)) {
if (e.type === 'doubletap') {
doubleTapped = true;
e.stopPropagation();
e.gesture.stopPropagation();
wasScrolling = reader.isScrolling;
if (wasScrolling) {
events.stopScrolling();
} else {
events.startScrolling();
}
} else if (e.type === 'touch' && e.gesture.touches.length < 2) {
touchTimer = setTimeout(function () {
e.stopPropagation();
e.gesture.stopPropagation();
wasScrolling = reader.isScrolling;
wasHolding = true;
if (wasScrolling && !doubleTapped) {
events.stopScrolling();
}
}, 150);
} else if (e.type === 'release') {
if (wasHolding) {
e.gesture.stopPropagation();
events.countPages();
if (wasScrolling && wasHolding) {
setTimeout(function () {
wasHolding = false;
events.startScrolling();
}, 200);
}
}
} else if (e.type === 'pinchin') {
console.log('pinchin');
e.stopPropagation();
e.gesture.stopPropagation();
events.fontDecrement();
if (wasScrolling) {
events.startScrolling();
}
e.gesture.stopDetect();
} else if (e.type === 'pinchout') {
e.stopPropagation();
e.gesture.stopPropagation();
events.fontIncrement();
if (wasScrolling) {
events.startScrolling();
}
e.gesture.stopDetect();
} else if (e.type === 'dragend' && e.gesture.touches.length < 2) {
e.preventDefault();
e.stopPropagation();
e.gesture.preventDefault();
e.gesture.stopPropagation();
if (e.gesture.distance >= 70 && e.gesture.direction === 'right') {
e.gesture.stopDetect();
events.speedIncrement();
} else if (e.gesture.distance >= 70 && e.gesture.direction === 'left') {
e.gesture.stopDetect();
events.speedDecrement();
}
}
} else if (target.parents().is(controls)) {
e.stopPropagation();
e.gesture.stopPropagation();
}
});
};
if (environment.isMobile()) {
return new Mobile();
} else {
return Mobile;
}
});
|
var url = require('url'),
start = require('./common'),
assert = require('power-assert'),
mongoose = start.mongoose,
Mongoose = mongoose.Mongoose,
Schema = mongoose.Schema,
random = require('../lib/utils').random,
collection = 'blogposts_' + random();
describe('mongoose module:', function() {
describe('default connection works', function() {
it('without options', function(done) {
var goose = new Mongoose;
var db = goose.connection,
uri = 'mongodb://localhost/mongoose_test';
goose.connect(process.env.MONGOOSE_TEST_URI || uri);
db.on('open', function() {
db.close(function() {
done();
});
});
});
it('with options', function(done) {
var goose = new Mongoose;
var db = goose.connection,
uri = 'mongodb://localhost/mongoose_test';
goose.connect(process.env.MONGOOSE_TEST_URI || uri, {db: {safe: false}});
db.on('open', function() {
db.close(function() {
done();
});
});
});
it('with promise (gh-3790)', function(done) {
var goose = new Mongoose;
var db = goose.connection,
uri = 'mongodb://localhost/mongoose_test';
goose.connect(process.env.MONGOOSE_TEST_URI || uri).then(function() {
db.close(done);
});
});
});
it('{g,s}etting options', function(done) {
var mongoose = new Mongoose();
mongoose.set('a', 'b');
mongoose.set('long option', 'c');
assert.equal(mongoose.get('a'), 'b');
assert.equal(mongoose.set('a'), 'b');
assert.equal(mongoose.get('long option'), 'c');
done();
});
it('declaring global plugins (gh-5690)', function(done) {
var mong = new Mongoose();
var subSchema = new Schema({ name: String });
var schema = new Schema({
test: [subSchema]
});
var called = 0;
var calls = [];
var preSaveCalls = 0;
mong.plugin(function(s) {
calls.push(s);
s.pre('save', function(next) {
++preSaveCalls;
next();
});
s.methods.testMethod = function() { return 42; };
});
schema.plugin(function(s) {
assert.equal(s, schema);
called++;
});
var M = mong.model('GlobalPlugins', schema);
assert.equal(called, 1);
assert.equal(calls.length, 2);
assert.equal(calls[0], schema);
assert.equal(calls[1], subSchema);
assert.equal(preSaveCalls, 0);
mong.connect(start.uri, { useMongoClient: true });
M.create({ test: [{ name: 'Val' }] }, function(error, doc) {
assert.ifError(error);
assert.equal(preSaveCalls, 2);
assert.equal(doc.testMethod(), 42);
assert.equal(doc.test[0].testMethod(), 42);
mong.disconnect();
done();
});
});
describe('disconnection of all connections', function() {
describe('no callback', function() {
it('works', function(done) {
var mong = new Mongoose(),
uri = 'mongodb://localhost/mongoose_test',
connections = 0,
disconnections = 0,
pending = 4;
mong.connect(process.env.MONGOOSE_TEST_URI || uri);
var db = mong.connection;
function cb() {
if (--pending) return;
assert.equal(connections, 2);
assert.equal(disconnections, 2);
done();
}
db.on('open', function() {
connections++;
cb();
});
db.on('close', function() {
disconnections++;
cb();
});
var db2 = mong.createConnection(process.env.MONGOOSE_TEST_URI || uri);
db2.on('open', function() {
connections++;
cb();
});
db2.on('close', function() {
disconnections++;
cb();
});
mong.disconnect();
});
it('properly handles errors', function(done) {
var mong = new Mongoose(),
uri = 'mongodb://localhost/mongoose_test';
mong.connect(process.env.MONGOOSE_TEST_URI || uri);
var db = mong.connection;
// forced failure
db.close = function(cb) {
cb(new Error('bam'));
};
mong.disconnect().connection.
on('error', function(error) {
assert.equal(error.message, 'bam');
});
done();
});
});
it('with callback', function(done) {
var mong = new Mongoose(),
uri = 'mongodb://localhost/mongoose_test';
mong.connect(process.env.MONGOOSE_TEST_URI || uri);
mong.connection.on('open', function() {
mong.disconnect(function() {
done();
});
});
});
it('with promise (gh-3790)', function(done) {
var mong = new Mongoose();
var uri = 'mongodb://localhost/mongoose_test';
mong.connect(process.env.MONGOOSE_TEST_URI || uri);
mong.connection.on('open', function() {
mong.disconnect().then(function() { done(); });
});
});
});
describe('model()', function() {
it('accessing a model that hasn\'t been defined', function(done) {
var mong = new Mongoose(),
thrown = false;
try {
mong.model('Test');
} catch (e) {
assert.ok(/hasn't been registered/.test(e.message));
thrown = true;
}
assert.equal(thrown, true);
done();
});
it('returns the model at creation', function(done) {
var Named = mongoose.model('Named', new Schema({name: String}));
var n1 = new Named();
assert.equal(n1.name, null);
var n2 = new Named({name: 'Peter Bjorn'});
assert.equal(n2.name, 'Peter Bjorn');
var schema = new Schema({number: Number});
var Numbered = mongoose.model('Numbered', schema, collection);
var n3 = new Numbered({number: 1234});
assert.equal(n3.number.valueOf(), 1234);
done();
});
it('prevents overwriting pre-existing models', function(done) {
var m = new Mongoose;
m.model('A', new Schema);
assert.throws(function() {
m.model('A', new Schema);
}, /Cannot overwrite `A` model/);
done();
});
it('allows passing identical name + schema args', function(done) {
var m = new Mongoose;
var schema = new Schema;
m.model('A', schema);
assert.doesNotThrow(function() {
m.model('A', schema);
});
done();
});
it('throws on unknown model name', function(done) {
assert.throws(function() {
mongoose.model('iDoNotExist!');
}, /Schema hasn't been registered/);
done();
});
describe('passing collection name', function() {
describe('when model name already exists', function() {
it('returns a new uncached model', function(done) {
var m = new Mongoose;
var s1 = new Schema({a: []});
var name = 'non-cached-collection-name';
var A = m.model(name, s1);
var B = m.model(name);
var C = m.model(name, 'alternate');
assert.ok(A.collection.name === B.collection.name);
assert.ok(A.collection.name !== C.collection.name);
assert.ok(m.models[name].collection.name !== C.collection.name);
assert.ok(m.models[name].collection.name === A.collection.name);
done();
});
});
});
describe('passing object literal schemas', function() {
it('works', function(done) {
var m = new Mongoose;
var A = m.model('A', {n: [{age: 'number'}]});
var a = new A({n: [{age: '47'}]});
assert.strictEqual(47, a.n[0].age);
done();
});
});
});
it('connecting with a signature of host, database, function', function(done) {
var mong = new Mongoose(),
uri = process.env.MONGOOSE_TEST_URI || 'mongodb://localhost/mongoose_test';
uri = url.parse(uri);
mong.connect(uri.hostname, uri.pathname.substr(1), function(err) {
assert.ifError(err);
mong.connection.close();
done();
});
});
describe('connecting with a signature of uri, options, function', function() {
it('with single mongod', function(done) {
var mong = new Mongoose(),
uri = process.env.MONGOOSE_TEST_URI || 'mongodb://localhost/mongoose_test';
mong.connect(uri, {db: {safe: false}}, function(err) {
assert.ifError(err);
mong.connection.close();
done();
});
});
it('with replica set', function(done) {
var mong = new Mongoose(),
uri = process.env.MONGOOSE_SET_TEST_URI;
if (!uri) return done();
mong.connect(uri, {db: {safe: false}}, function(err) {
assert.ifError(err);
mong.connection.close();
done();
});
});
});
it('goose.connect() to a replica set', function(done) {
var uri = process.env.MONGOOSE_SET_TEST_URI;
if (!uri) {
console.log('\033[31m', '\n', 'You\'re not testing replica sets!'
, '\n', 'Please set the MONGOOSE_SET_TEST_URI env variable.', '\n'
, 'e.g: `mongodb://localhost:27017/db,localhost…`', '\n'
, '\033[39m');
return done();
}
var mong = new Mongoose();
mong.connect(uri, function(err) {
assert.ifError(err);
mong.model('Test', new mongoose.Schema({
test: String
}));
var Test = mong.model('Test'),
test = new Test();
test.test = 'aa';
test.save(function(err) {
assert.ifError(err);
Test.findById(test._id, function(err, doc) {
assert.ifError(err);
assert.equal(doc.test, 'aa');
mong.connection.close();
complete();
});
});
});
mong.connection.on('fullsetup', complete);
var pending = 2;
function complete() {
if (--pending) return;
done();
}
});
it('goose.createConnection() to a replica set', function(done) {
var uri = process.env.MONGOOSE_SET_TEST_URI;
if (!uri) return done();
var mong = new Mongoose();
var conn = mong.createConnection(uri, function(err) {
assert.ifError(err);
mong.model('ReplSetTwo', new mongoose.Schema({
test: String
}));
var Test = conn.model('ReplSetTwo'),
test = new Test();
test.test = 'aa';
test.save(function(err) {
assert.ifError(err);
Test.findById(test._id, function(err, doc) {
assert.ifError(err);
assert.equal(doc.test, 'aa');
conn.close();
complete();
});
});
});
conn.on('fullsetup', complete);
var pending = 2;
function complete() {
if (--pending) return;
done();
}
});
describe('exports', function() {
function test(mongoose) {
assert.equal(typeof mongoose.version, 'string');
assert.equal(typeof mongoose.Mongoose, 'function');
assert.equal(typeof mongoose.Collection, 'function');
assert.equal(typeof mongoose.Connection, 'function');
assert.equal(typeof mongoose.Schema, 'function');
assert.ok(mongoose.Schema.Types);
assert.equal(typeof mongoose.SchemaType, 'function');
assert.equal(typeof mongoose.Query, 'function');
assert.equal(typeof mongoose.Promise, 'function');
assert.equal(typeof mongoose.Model, 'function');
assert.equal(typeof mongoose.Document, 'function');
assert.equal(typeof mongoose.Error, 'function');
assert.equal(typeof mongoose.Error.CastError, 'function');
assert.equal(typeof mongoose.Error.ValidationError, 'function');
assert.equal(typeof mongoose.Error.ValidatorError, 'function');
assert.equal(typeof mongoose.Error.VersionError, 'function');
}
it('of module', function(done) {
test(mongoose);
done();
});
it('of new Mongoose instances', function(done) {
test(new mongoose.Mongoose);
done();
});
it('of result from .connect() (gh-3940)', function(done) {
var m = new mongoose.Mongoose;
test(m.connect('mongodb://localhost:27017'));
m.disconnect();
done();
});
});
});
|
export default (value) => {
return Math.ceil(value * 10000) / 100;
};
|
var polybool = require('../bool')
var a = [[[-1,-1], [-1,1], [1,1], [1,-1]]]
var b = [[[0, 0], [0,2], [2,2], [2,0]]]
console.log(polybool(a, b, 'sub'))
|
module.exports=require("tiv")*100; |
app.controller('backend-people', ["$scope", "Auth", "$location", "$firebaseArray", "getAuthData", "$firebaseObject",
function($scope, Auth, $location, $firebaseArray, getAuthData, $firebaseObject) {
console.log("I see backend-activity controller!");
var ref = new Firebase("https://clocker.firebaseio.com/");
var currentAuthData = ref.getAuth();
var adminUid = currentAuthData.uid;
var pastVisitorsRef = new Firebase("https://clocker.firebaseio.com/" + adminUid + "/visitors");
var activityLogRef = new Firebase("https://clocker.firebaseio.com/" + adminUid + "/activityLog");
var groupsRef = new Firebase("https://clocker.firebaseio.com/" + adminUid + "/groups");
var activityNamesRef = new Firebase("https://clocker.firebaseio.com/" + adminUid + "/activityNames");
console.log("adminUid", adminUid);
$scope.activityLogArray = $firebaseArray(activityLogRef);
$scope.activityLogArray.$loaded().then(function(returnedActivityArray) {
$scope.allActivitiesArray = returnedActivityArray.reverse();
})
$scope.groupsArray = $firebaseArray(groupsRef);
$scope.activityNamesArray = $firebaseArray(activityNamesRef);
$scope.startDateText = "";
//Start-date Picker functionality:
var startDate = "";
var convertDate = function(oldFormat) {
return $.datepicker.formatDate("yy-mm-dd", oldFormat).toString();
};
$scope.filteredResults = [];
$scope.filteredSum = 0;
$scope.$watch(function() {
//console.log("new filteredResults", $scope.filteredResults);
var sum = 0;
//total hours calc:
// var filteredSecsArray = _.pull($scope.filteredResults.totalSecs, undefined);
// console.log("filteredSecsArray", filteredSecsArray);
$scope.filteredResults.forEach(function (r) {
if (r.totalSecs === undefined) {
} else {
sum += r.totalSecs;
}
});
$scope.filteredSum = Number(Math.round((sum / 3600)+'e2') +'e-2')
console.log("$$scope.filteredSum", $scope.filteredSum);
//total events calc:
var allEvents = $scope.filteredResults.map(function(activity) {
return activity.activity;
})
//console.log("allEvents", allEvents);
var uniqueEvents = _.uniq(allEvents);
// console.log("uniqueEvents", uniqueEvents);
$scope.eventsTotal = uniqueEvents.length;
//total groups calc:
var allGroups = $scope.filteredResults.map(function(activity) {
return activity.group;
})
//console.log("allGroups", allGroups);
var uniqueGroups = _.uniq(allGroups);
$scope.groupTotal = uniqueGroups.length;
//total people calc:
var allPeople = $scope.filteredResults.map(function(activity) {
var firstName = activity.firstName;
var lastName = activity.lastName;
var fullName = firstName + " " + lastName;
return fullName;
})
var uniquePeople = _.uniq(allPeople);
// console.log("uniquePeople", uniquePeople);
$scope.peopleTotal = uniquePeople.length;
})
$(function() {
$("#start-date-picker").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: "D, M dd, yy",
onSelect: function(dateText, selectedDateObj) {
startDate = $("#start-date-picker").datepicker( "getDate" );
console.log("startDate", startDate);
console.log("converted Date:", convertDate(startDate));
var convertedDate = convertDate(startDate);
$scope.selectedStart = convertDate(startDate);
$scope.startDateText = $scope.selectedStart;
$scope.$apply();
var timeTest = moment(convertedDate).isAfter("2015-12-14T12:17:10-06:00");
console.log("before/after test:", timeTest);
console.log("dateText", dateText);
console.log("selectedDateObj", selectedDateObj);
}
});
});
//"before" date Picker functionality:
$(function() {
$("#before-date-picker").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: "D, M dd, yy",
onSelect: function(dateText, selectedDateObj) {
beforeDate = $("#before-date-picker").datepicker( "getDate" );
console.log("before date:", beforeDate);
console.log("converted before Date:", convertDate(beforeDate));
var convertedDate = convertDate(beforeDate);
$scope.selectedEnd = convertDate(beforeDate);
$scope.beforeDateText = $scope.selectedEnd;
$scope.$apply();
var timeTest = moment(convertedDate).isBefore("2015-12-14T12:17:10-06:00");
console.log("before or after test:", timeTest);
console.log("dateText", dateText);
console.log("selectedDateObj", selectedDateObj);
}
});
});
$scope.compareActivities = function(currentActivity) {
// console.log("currentActivity", currentActivity);
// console.log("$scope.filteredResults", $scope.filteredResults);
var currentIndex = $scope.filteredResults.indexOf(currentActivity);
//console.log("currentIndex", currentIndex);
// console.log("$scope.filteredResults[currentIndex + 1]", $scope.filteredResults[currentIndex + 1]);
var prevActivity = $scope.filteredResults[currentIndex - 1]
if (prevActivity === undefined) {
return true
};
var currentMoment = moment(currentActivity.in);
// console.log("currentMoment", currentMoment);
var nextActMoment = moment(prevActivity.in)
// console.log("nextActMoment", nextActMoment);
if (currentMoment.isSame(nextActMoment, 'd')) {
// console.log("SAME day");
return false;
} else {
// console.log("++++++++PREVIOUS DAY++++++++++");
return true;
};
}
$scope.selectedGroups = [];
$scope.setSelectedGroup = function () {
var groupName = this.group.$value;
console.log("groupName", groupName);
if (_.contains($scope.selectedGroups, groupName)) {
$scope.selectedGroups = _.without($scope.selectedGroups, groupName);
} else {
$scope.selectedGroups.push(groupName);
}
return false;
};
$scope.isChecked = function (groupName) {
console.log("groupName", groupName);
if (_.contains($scope.selectedGroups, groupName)) {
console.log("want to add checkmark!");
return 'glyphicon glyphicon-ok';
}
return false;
};
$scope.checkAllGroups = function () {
$scope.selectedGroups = _.pluck($scope.groupsArray, '$value');
};
$scope.selectedActivities = [];
$scope.setSelectedActivity = function () {
var selectedActivity = this.activityName.$value;
console.log("selectedActivity", selectedActivity);
if (_.contains($scope.selectedActivities, selectedActivity)) {
$scope.selectedActivities = _.without($scope.selectedActivities, selectedActivity);
} else {
$scope.selectedActivities.push(selectedActivity);
}
return false;
};
$scope.checkAllActivities = function () {
$scope.selectedActivities = _.pluck($scope.activityNamesArray, '$value');
};
$scope.activityIsChecked = function (activityName) {
console.log("activityName", activityName);
if (_.contains($scope.selectedActivities, activityName)) {
console.log("want to add checkmark!");
return 'glyphicon glyphicon-ok';
}
return false;
};
$scope.closeDropdowns = function() {
//console.log("you clicked on the body!!");
console.log("event", event.target.id);
}
}]);
|
/**
* @file foundation-setup.js
*
* This is required for any foundation functionality. It should be imported at the top
* of any file that is implementing a foundation component. Webpack determines
* dependencies so this will only be added once. Keep in mind this is where the global
* Foundation is being initialized `$(document).foudnation()`, so it's probably reasonable
* to include this in the `theme.js` file first, as well as Foundation component files.
*/
import { Foundation } from 'foundation-sites/js/foundation.core';
import { rtl, GetYoDigits, transitionend } from 'foundation-sites/js/foundation.util.core';
import { Box } from 'foundation-sites/js/foundation.util.box';
import { onImagesLoaded } from 'foundation-sites/js/foundation.util.imageLoader';
import { Keyboard } from 'foundation-sites/js/foundation.util.keyboard';
import { MediaQuery } from 'foundation-sites/js/foundation.util.mediaQuery';
import { Motion, Move } from 'foundation-sites/js/foundation.util.motion';
import { Nest } from 'foundation-sites/js/foundation.util.nest';
import { Timer } from 'foundation-sites/js/foundation.util.timer';
window.$ = jQuery;
Foundation.addToJquery(jQuery);
// Add Foundation Utils to Foundation global namespace for backwards
// compatibility.
Foundation.rtl = rtl;
Foundation.GetYoDigits = GetYoDigits;
Foundation.transitionend = transitionend;
Foundation.Box = Box;
Foundation.onImagesLoaded = onImagesLoaded;
Foundation.Keyboard = Keyboard;
Foundation.MediaQuery = MediaQuery;
Foundation.Motion = Motion;
Foundation.Move = Move;
Foundation.Nest = Nest;
Foundation.Timer = Timer;
// Initializing foundation - if you are relying on components generated from classes or attributes,
// you may need to make sure to appropriate modules are included beforehand
jQuery(document).foundation();
|
/**
* Created by vadimsky on 10/06/16.
*/
var winston = require('winston');
var ENV = process.env.NODE_ENV;
function getLogger(module) {
var path = module.filename.split('/').slice(-2).join('/'); //using filename in log statements
return new winston.Logger({
transports: [
new winston.transports.Console({
colorize: true,
level: ENV == 'development' ? 'debug': 'error',
label: path
})
]
});
}
module.exports = getLogger;
|
game.module(
'game.pile'
).
body(function() {
var Debug = 3;
game.createClass('Pile', {
/* 17 pass cards
* 5 left/right goal shot cards
* 5 defence cards each
* total 42 cards
*/
NoPass: 17,
NoLeftShot: 5,
NoRightShot: 5,
NoIntercept: 5,
NoLeftBlock: 5,
NoRightBlock: 5,
//=================================
cards: [],
init: function(piletype, c_gone){ // c_gone means the cards had been taken away
switch(piletype){
case "home": case "Home":
console.log('create homepile');
this.HomePile(c_gone);
break;
case "away": case "Away":
console.log('create awaypile');
this.AwayPile(c_gone);
break;
default:
if (Debug >= 1)
{
console.log('Unknown pile type');
}
break;
}
this.Shuffle();
this.Shuffle();
},
HomePile: function(c_gone){
var i,j;
for(i = 0; i < c_gone.length; i++){
switch(c_gone[i]){
case 1: this.NoPass--; break;
case 2: this.NoLeftShot--; break;
case 3: this.NoRightShot--; break;
case 4: this.NoIntercept--; break;
case 5: this.NoLeftBlock--; break;
case 6: this.NoRightBlock--; break;
default:
if (Debug >= 1)
{
console.log('Undefined card type in cards has been taken away');
}
break;
}
}
/*
console.log('After taken away cards');
console.log(this.NoPass);
console.log(this.NoLeftShot);
console.log(this.NoRightShot);
console.log(this.NoIntercept);
console.log(this.NoLeftBlock);
console.log(this.NoRightBlock);
*/
/* 1. write down all the cards in order */
for(i = 0; i < this.NoPass; i++){
this.cards.push(1);
}
for(i = 2; i <= 6; i++){
for(j = 0; j < 5; j++){
this.cards.push(i);
}
}
// ================
},
AwayPile: function(c_gone){
var i,j;
for(i = 0; i < c_gone.length; i++){
switch(c_gone[i]){
case 11: this.NoPass--; break;
case 12: this.NoLeftShot--; break;
case 13: this.NoRightShot--; break;
case 14: this.NoIntercept--; break;
case 15: this.NoLeftBlock--; break;
case 16: this.NoRightBlock--; break;
default:
if (Debug >= 1)
{
console.log('Undefined card type in cards has been taken away');
}
break;
}
}
/*
console.log('After taken away cards');
console.log(this.NoPass);
console.log(this.NoLeftShot);
console.log(this.NoRightShot);
console.log(this.NoIntercept);
console.log(this.NoLeftBlock);
console.log(this.NoRightBlock);
*/
/* 1. write down all the cards in order */
for(i = 0; i < this.NoPass; i++){
this.cards.push(11);
}
for(i = 2; i <= 6; i++){
for(j = 0; j < 5; j++){
this.cards.push(i+10);
}
}
},
Shuffle: function(){ // Fisher-Yates shuffle
var i,j;
var tmp;
for(i = this.cards.length-1; i >= 1; i--){
j = ~~Math.randomBetween(0, i);
tmp = this.cards[i];
this.cards[i] = this.cards[j];
this.cards[j] = tmp;
}
},
DrawCard: function(){
if(this.cards.length > 0){
var cardtype = this.cards[this.cards.length-1];
this.cards.pop();
switch(cardtype){
case 1: case 11: this.NoPass--; break;
case 2: case 12: this.NoLeftShot--; break;
case 3: case 13: this.NoRightShot--; break;
case 4: case 14: this.NoIntercept--; break;
case 5: case 15: this.NoLeftBlock--; break;
case 6: case 16: this.NoRightBlock--; break;
default: if (Debug >= 1){console.log('Unknown type of card when drawing');} break;
}
return cardtype;
}else{
if (Debug >= 2)
{
console.log();
console.log('Pile is Empty now');
}
return null;
}
},
NoCards: function(){
return this.cards.length;
},
IsEmpty: function(){
if(this.cards.length == 0) return true;
else return false;
}
});
}); |
var indexSectionsWithContent =
{
0: "acdefhimnpstv~",
1: "afhmp",
2: "ampt",
3: "acdeimnpstv~"
};
var indexSectionNames =
{
0: "all",
1: "classes",
2: "files",
3: "functions"
};
var indexSectionLabels =
{
0: "All",
1: "Classes",
2: "Files",
3: "Functions"
};
|
import React, { View,TouchableNativeFeedback,TextInput,Text } from 'react-native';
import { shallow } from 'enzyme';
import { expect } from 'chai';
import CommentForm from '../CommentForm.js';
import CommentBox from '../CommentBox.js';
import Sinon from 'sinon';
describe('<CommentForm>', ()=>{
beforeEach(function(){
wrapper = shallow(<CommentForm/>);
});
it('should be view component',()=>{
expect(wrapper.type()).to.equal(View);
});
it('should have 2 TextInput components',() =>{
expect(wrapper.find(TextInput)).to.have.length(3);
});
it('should have a submit button',()=>{
expect(wrapper.find(TouchableNativeFeedback)).to.have.length(1);
expect(wrapper.find(TouchableNativeFeedback).containsMatchingElement(<Text>Submit</Text>)).to.equal(true);
});
it('should have author input component with value dependent on state',()=>{
wrapper.setState({name:'JK'});
expect(wrapper.find(TextInput).first().props().value).to.equal('JK');
});
it('should have the comment input component with value dependent on state',() =>{
wrapper.setState({comment: 'An awesome comment'});
expect(wrapper.find(TextInput).at(1).props().value).to.equal('An awesome comment');
});
it('should change state when the text of author input component changes',() =>{
const authorInputComponent = wrapper.find('TextInput').first();
authorInputComponent.simulate('Change','wenger');
expect(wrapper.state('name')).to.equal('wenger');
});
it('should change state when the text of comment input component changes',() =>{
const commentInputComponent = wrapper.find('TextInput').at(1);
commentInputComponent.simulate('Change','arsenal');
expect(wrapper.state('comment')).to.equal('arsenal');
});
it('invokes handleCommitSubmit method of CommentBox with author and comment', () => {
Sinon.stub(CommentBox.prototype, "handleCommentSubmit");
const wrapper = shallow(<CommentForm onCommentSubmit={CommentBox.prototype.handleCommentSubmit}/>);
const submitButton = wrapper.find('TouchableNativeFeedback').first();
wrapper.setState({name: 'JK '});
wrapper.setState({comment: ' Arsenal is the best'});
submitButton.simulate('press');
expect(CommentBox.prototype.handleCommentSubmit.calledWith({author: 'JK', text: 'Arsenal is the best'})).to.be.true;
expect(wrapper.state('name')).to.equal("");
expect(wrapper.state('comment')).to.equal("");
CommentBox.prototype.handleCommentSubmit.restore();
});
it('sets the state of two input fields to the initial state on press',() => {
Sinon.stub(CommentBox.prototype,"handleCommentSubmit");
const wrapper = shallow(<CommentForm onCommentSubmit={CommentBox.prototype.handleCommentSubmit}/>);
const submitButton = wrapper.find('TouchableNativeFeedback').first();
wrapper.setState({name: 'JK'});
wrapper.setState({comment: 'Arsenal is the best'});
submitButton.simulate('press');
expect(wrapper.state('name')).to.equal("");
expect(wrapper.state('comment')).to.equal("");
CommentBox.prototype.handleCommentSubmit.restore();
});
});
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import apiClient from '../api/apiClient';
import CONSTANTS from '../shared/constants';
class Shop extends Component {
constructor() {
super();
this.state = {
username: "username"
};
}
componentWillMount() {
apiClient.callCreditCardsApi(CONSTANTS.HTTP_METHODS.GET, '/users/profile', (response) => {
this.setState({ username: response.data.user.firstName });
});
}
render()
{
return (
<h1>Hello {this.state.username}. This is the shop page</h1>
);
}
}
const mapStateToProps = (state) => {
return {
sessionId: state.session.sessionId
};
};
export default connect(mapStateToProps)(Shop);
|
import {combineReducers} from "redux";
import typeList from "./defaultTypes"
import thingList from "./thingList"
const things = (state = thingList, action) => {
switch (action.type) {
default:
return state
}
}
const types = (state = typeList, action) => {
switch (action.type) {
case"ADD_TYPE":
return [...state, {name: action.payload, namespace: "me.moazzam.types"}]
case"ADD_PROPERTY":
return state.map((type) => {
if (action.payload.type === type.name) {
return {
name: type.name,
properties: (type.properties || []).concat(action.payload.properties)
}
} else {
return type
}
})
default:
return state
}
}
const ginApp = combineReducers({things, types});
export default ginApp |
/**
* User.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/#!documentation/models
*/
var bcrypt = require('bcrypt');
module.exports = {
attributes: {
email: {
type: 'email',
required: true,
unique: true
},
password: {
type: 'string',
minLength: 6,
required: true
},
toJSON: function() {
var obj = this.toObject();
delete obj.password;
return obj;
}
},
beforeCreate: function(user, cb) {
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) {
console.log(err);
cb(err);
} else {
user.password = hash;
cb();
}
});
});
}
};
|
/**
* Created by fastjur on 14-1-16.
*/
var db = require("./mysqlconn.js");
var url = require("url");
var getLists = function(res) {
db.connection.query("SELECT Id, Title, Text, DueDate, Completed, Priority FROM ToDoItem;", function(err, rows) {
if(!err) {
var todos = [];
for (var i in rows) {
var todo = {
id: rows[i].Id,
title: rows[i].Title,
text: rows[i].Text,
duedate: new Date(rows[i].DueDate).getTime() / 1000,
done: rows[i].Completed,
priority: rows[i].Priority
};
todos.push(todo);
}
res.render('lists', {todo_array: todos});
//res.json(todos);
} else {
console.log("alltodos query error", err);
}
});
};
var getAllTodos = function(res) {
db.connection.query("SELECT Id, Title, Text, DueDate, Completed, Priority FROM ToDoItem;", function(err, rows) {
if(!err) {
var todos = [];
for (var i in rows) {
var todo = {
id: rows[i].Id,
title: rows[i].Title,
text: rows[i].Text,
duedate: new Date(rows[i].DueDate).getTime() / 1000,
done: rows[i].Completed,
priority: rows[i].Priority
};
todos.push(todo);
}
//res.render('todos', {todo_array: todos});
res.json(todos);
} else {
console.log("alltodos query error", err);
}
});
};
var addTodo = function(req, res) {
var url_parts = url.parse(req.url, true),
query = url_parts.query;
if(query["title"] !== undefined && query["text"] !== undefined && query["duedate"] !== undefined &&
query["done"] !== undefined && query["priority"] !== undefined) {
db.connection.query("INSERT INTO ToDoItem(Title, Text, DueDate, Completed, Priority) VALUES (\""+query["title"]+"\",\""+
query["text"]+"\",\""+query["duedate"]+"\",\""+query["done"]+"\",\""+query["priority"]+"\")", function(err, data) {
if(err){
console.log("Addtodo error", err);
res.writeHeader(200);
res.end(data);
} else {
res.writeHeader(200);
res.end("true");
}
});
}
};
var removeTodo = function(req, res) {
var url_parts = url.parse(req.url, true),
query = url_parts.query;
if(query["id"] !== undefined) {
db.connection.query("DELETE FROM ToDoItem WHERE id = ?", query["id"], function(err, data) {
if(err) {
console.log("Remove todo error", err);
res.writeHeader(200);
res.end("false");
} else {
res.writeHeader(200);
res.end("true");
}
});
} else {
res.writeHeader(200);
res.end("false");
}
};
var updateTodo = function(req, res) {
var url_parts = url.parse(req.url, true),
query = url_parts.query,
mysqlQuery = "UPDATE ToDoItem SET Title=\""+query["title"]+"\", Text=\""+query["text"]+"\"," +
" DueDate=\""+query["duedate"]+"\", Completed=\""+query["done"]+"\","+" Priority=\""+query["priority"] +
"\" " +"WHERE Id=\""+query["id"]+"\"";
db.connection.query(mysqlQuery, function(err, data) {
if(err) {
console.log("Update Todo error", err);
res.writeHeader(200);
res.end("false");
} else {
res.writeHeader(200);
res.end("true");
}
})
};
module.exports.getLists = getLists;
module.exports.getAllTodos = getAllTodos;
module.exports.addTodo = addTodo;
module.exports.removeTodo = removeTodo;
module.exports.updateTodo = updateTodo; |
!(function($) {
var upload;
upload = require('upload');
return $.ender({
isubmit: upload.isubmit,
upload: upload.upload
});
})(ender); |
import React from 'react';
import styles from '../styles/modal.scss';
export default React.createClass({
getInitialState () {
return {
visible: true
}
},
componentDidMount () {
let modalToggle = document.getElementById('modal-toggle');
modalToggle.addEventListener('click', this.toggleVisible)
window.addEventListener('keypress', (e) => {
if (e.keyCode === 100) {
this.setState({
visible: false
})
}
});
},
toggleVisible () {
let showState;
if (this.state.visible === false) {
showState = true;
} else {
showState = false;
}
this.setState({
visible: showState
});
},
render () {
return (
<div className={this.state.visible ? 'modal' : 'modal hidden'}>
<h3>Lines</h3>
<i className="fa fa-times-circle" id='modal-toggle'></i>
<div className='content text'>
<span>Click the background to make Lines</span>
<p> </p>
<span>Press D to toggle the control panel</span>
</div>
</div>
)
}
}) |
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
globals: {
'ts-jest': {
diagnostics: false
}
}
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.