code stringlengths 2 1.05M |
|---|
"use strict";
var Lab = require("lab");
var plugin = require("..");
var describe = Lab.describe;
var expect = Lab.expect;
var it = Lab.it;
describe("The plugin", function () {
it("has a name", function (done) {
expect(plugin.register.attributes, "no name")
.to.have.property("name", "badge");
done();
});
it("has a version", function (done) {
expect(plugin.register.attributes, "no version")
.to.have.property("version");
done();
});
});
|
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["react-syntax-highlighter_languages_highlight_dos"],{
/***/ "./node_modules/highlight.js/lib/languages/dos.js":
/*!********************************************************!*\
!*** ./node_modules/highlight.js/lib/languages/dos.js ***!
\********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = function(hljs) {
var COMMENT = hljs.COMMENT(
/^\s*@?rem\b/, /$/,
{
relevance: 10
}
);
var LABEL = {
className: 'symbol',
begin: '^\\s*[A-Za-z._?][A-Za-z0-9_$#@~.?]*(:|\\s+label)',
relevance: 0
};
return {
aliases: ['bat', 'cmd'],
case_insensitive: true,
illegal: /\/\*/,
keywords: {
keyword:
'if else goto for in do call exit not exist errorlevel defined ' +
'equ neq lss leq gtr geq',
built_in:
'prn nul lpt3 lpt2 lpt1 con com4 com3 com2 com1 aux ' +
'shift cd dir echo setlocal endlocal set pause copy ' +
'append assoc at attrib break cacls cd chcp chdir chkdsk chkntfs cls cmd color ' +
'comp compact convert date dir diskcomp diskcopy doskey erase fs ' +
'find findstr format ftype graftabl help keyb label md mkdir mode more move path ' +
'pause print popd pushd promt rd recover rem rename replace restore rmdir shift' +
'sort start subst time title tree type ver verify vol ' +
// winutils
'ping net ipconfig taskkill xcopy ren del'
},
contains: [
{
className: 'variable', begin: /%%[^ ]|%[^ ]+?%|![^ ]+?!/
},
{
className: 'function',
begin: LABEL.begin, end: 'goto:eof',
contains: [
hljs.inherit(hljs.TITLE_MODE, {begin: '([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*'}),
COMMENT
]
},
{
className: 'number', begin: '\\b\\d+',
relevance: 0
},
COMMENT
]
};
};
/***/ })
}]);
//# sourceMappingURL=react-syntax-highlighter_languages_highlight_dos.js.map |
class Class1 {
constructor(x) { this.x = x; }
}
new Class1(42, 23); // NOT OK: `23` is ignored
class Sup {
constructor(x) { this.x = x; }
}
class Sub extends Sup {
}
new Sub(42); // OK: synthetic constructor delegates to super constructor
class Other {}
new Other(42); // NOT OK: `42` is ignored
var args = [];
f(...args); // OK
f(42, ...args); // NOT OK |
'use strict';
module.exports = function (t, a) {
a(t({}), 0, "NaN");
a(t(20), 20, "Positive integer");
a(t('-20'), -20, "String negative integer");
a(t(Infinity), Infinity, "Infinity");
a(t(15.343), 15, "Float");
a(t(-15.343), -15, "Negative float");
};
//# sourceMappingURL=to-integer-compiled.js.map |
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@angular/core");
var project_request_component_1 = require("./project-request.component");
var invitation_component_1 = require("./invitation.component");
var InvitationModule = (function () {
function InvitationModule() {
}
return InvitationModule;
}());
InvitationModule = __decorate([
core_1.NgModule({
imports: [],
declarations: [
project_request_component_1.ProjectRequestComponent,
invitation_component_1.InvitationComponent
],
exports: [
project_request_component_1.ProjectRequestComponent,
invitation_component_1.InvitationComponent
],
})
], InvitationModule);
exports.InvitationModule = InvitationModule;
//# sourceMappingURL=invitation.module.js.map |
var highscoreList = new Array();
var highscoreNameList = new Array();
var highscoreLadderList = new Array();
/**
* @Class
* @name highscoreState
* @desc state that shows the highscores you have obtained.
* @property {fontStyle} style - style of the font in the score.
* @property {text} titleStyle - style of the font in the screen.
*/
var highscoreState = {
// Custom "variables".
style: null,
titleStyle: null,
// Phaser functions.
create: function() {
var highscoreBackground = game.add.sprite(0, 0,'highscoreBackground');
style = {};
// Font style
style.font = 'Passion One';
style.fontSize = 75;
style.fontWeight = 'bold';
// Stroke color and thickness
style.stroke = '#FFFF00';
style.strokeThickness = 3;
style.fill = '#FF2828';
titleText = game.add.text(game.world.centerX - 150, 70, "HIGHSCORES");
// Font style
titleText.font = 'Passion One';
titleText.fontSize = 50;
titleText.fontWeight = 'bold';
// Stroke color and thickness
titleText.stroke = '#0020C2';
titleText.strokeThickness = 5;
titleText.fill = '#2B65EC';
var escKey = game.input.keyboard.addKey(Phaser.Keyboard.Q);
escKey.onDown.add(this.goToMain, this);
var str_highscore = JSON.parse(localStorage.getItem('highScore'));
if (str_highscore == null || str_highscore == "null") {
} else {
highscoreList = str_highscore;
this.checkScoreValues();
}
var backButton;
backButton = game.add.button(100, 100, 'backButton', function() {
game.state.start('mainMenu');
}, this);
backButton.anchor.setTo(0.5, 0.5);
},
/** @method
* @name addScore
* @memberof highscoreState
* @description this is a function that adds a score to the highscore list
*/
addScore: function(scoreToAdd) {
if(typeof scoreToAdd === 'number') {
if(highscoreList.length >= 9)
{
highscoreList.splice(10,1);
}
highscoreList.push("\n" +scoreToAdd );
}
},
/** @method
* @name checkScoreValues
* @memberof highscoreState
* @description this is a function checks the scores and in the arrays and displays them on the screen.
*/
checkScoreValues: function(){
highscoreLadderList = []
var sortedList = highscoreList;
sortedList.sort( function(a,b) { return b - a; } );
console.log(sortedList);
for (var i = 0; i < sortedList.length; i++) {
highscoreLadderList.push("" + (i+1) + ".\n");
}
var scoreText = game.add.text(game.world.centerX - 100 + 100, 200, '', style);
scoreText.parseList(sortedList);
var ladderText = game.add.text(game.world.centerX - 100, 300, '', style);
ladderText.parseList(highscoreLadderList);
},
goToMain: function() {
game.state.start('mainMenu');
},
};
|
/*!
** 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) + "']"),
replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false;
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"),
replace = $.parseJSON(container.attr("data-valmsg-replace"));
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");
$(selector).find(":input[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;
});
adapters.addSingleVal("accept", "exts").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.add("equalto", ["other"], function (options) {
var prefix = getModelPrefix(options.element.name),
other = options.params.other,
fullOtherName = appendModelPrefix(other, prefix),
element = $(options.form).find(":input[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[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));
// SIG // Begin signature block
// SIG // MIIauwYJKoZIhvcNAQcCoIIarDCCGqgCAQExCzAJBgUr
// SIG // DgMCGgUAMGcGCisGAQQBgjcCAQSgWTBXMDIGCisGAQQB
// SIG // gjcCAR4wJAIBAQQQEODJBs441BGiowAQS9NQkAIBAAIB
// SIG // AAIBAAIBAAIBADAhMAkGBSsOAwIaBQAEFIzPMomVzyar
// SIG // fZ0FkHXb/h2kPh8noIIVgjCCBMMwggOroAMCAQICEzMA
// SIG // AAA0JDFAyaDBeY0AAAAAADQwDQYJKoZIhvcNAQEFBQAw
// SIG // dzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0
// SIG // b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1p
// SIG // Y3Jvc29mdCBDb3Jwb3JhdGlvbjEhMB8GA1UEAxMYTWlj
// SIG // cm9zb2Z0IFRpbWUtU3RhbXAgUENBMB4XDTEzMDMyNzIw
// SIG // MDgyNVoXDTE0MDYyNzIwMDgyNVowgbMxCzAJBgNVBAYT
// SIG // AlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQH
// SIG // EwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29y
// SIG // cG9yYXRpb24xDTALBgNVBAsTBE1PUFIxJzAlBgNVBAsT
// SIG // Hm5DaXBoZXIgRFNFIEVTTjpCOEVDLTMwQTQtNzE0NDEl
// SIG // MCMGA1UEAxMcTWljcm9zb2Z0IFRpbWUtU3RhbXAgU2Vy
// SIG // dmljZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
// SIG // ggEBAOUaB60KlizUtjRkyzQg8rwEWIKLtQncUtRwn+Jc
// SIG // LOf1aqT1ti6xgYZZAexJbCkEHvU4i1cY9cAyDe00kOzG
// SIG // ReW7igolqu+he4fY8XBnSs1q3OavBZE97QVw60HPq7El
// SIG // ZrurorcY+XgTeHXNizNcfe1nxO0D/SisWGDBe72AjTOT
// SIG // YWIIsY9REmWPQX7E1SXpLWZB00M0+peB+PyHoe05Uh/4
// SIG // 6T7/XoDJBjYH29u5asc3z4a1GktK1CXyx8iNr2FnitpT
// SIG // L/NMHoMsY8qgEFIRuoFYc0KE4zSy7uqTvkyC0H2WC09/
// SIG // L88QXRpFZqsC8V8kAEbBwVXSg3JCIoY6pL6TUAECAwEA
// SIG // AaOCAQkwggEFMB0GA1UdDgQWBBRfS0LeDLk4oNRmNo1W
// SIG // +3RZSWaBKzAfBgNVHSMEGDAWgBQjNPjZUkZwCu1A+3b7
// SIG // syuwwzWzDzBUBgNVHR8ETTBLMEmgR6BFhkNodHRwOi8v
// SIG // Y3JsLm1pY3Jvc29mdC5jb20vcGtpL2NybC9wcm9kdWN0
// SIG // cy9NaWNyb3NvZnRUaW1lU3RhbXBQQ0EuY3JsMFgGCCsG
// SIG // AQUFBwEBBEwwSjBIBggrBgEFBQcwAoY8aHR0cDovL3d3
// SIG // dy5taWNyb3NvZnQuY29tL3BraS9jZXJ0cy9NaWNyb3Nv
// SIG // ZnRUaW1lU3RhbXBQQ0EuY3J0MBMGA1UdJQQMMAoGCCsG
// SIG // AQUFBwMIMA0GCSqGSIb3DQEBBQUAA4IBAQAPQlCg1R6t
// SIG // Fz8fCqYrN4pnWC2xME8778JXaexl00zFUHLycyX25IQC
// SIG // xXUccVhDq/HJqo7fym9YPInnL816Nexm19Veuo6fV4aU
// SIG // EKDrUTetV/YneyNPGdjgbXYEJTBhEq2ljqMmtkjlU/JF
// SIG // TsW4iScQnanjzyPpeWyuk2g6GvMTxBS2ejqeQdqZVp7Q
// SIG // 0+AWlpByTK8B9yQG+xkrmLJVzHqf6JI6azF7gPMOnleL
// SIG // t+YFtjklmpeCKTaLOK6uixqs7ufsLr9LLqUHNYHzEyDq
// SIG // tEqTnr+cg1Z/rRUvXClxC5RnOPwwv2Xn9Tne6iLth4yr
// SIG // sju1AcKt4PyOJRUMIr6fDO0dMIIE7DCCA9SgAwIBAgIT
// SIG // MwAAALARrwqL0Duf3QABAAAAsDANBgkqhkiG9w0BAQUF
// SIG // ADB5MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGlu
// SIG // Z3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMV
// SIG // TWljcm9zb2Z0IENvcnBvcmF0aW9uMSMwIQYDVQQDExpN
// SIG // aWNyb3NvZnQgQ29kZSBTaWduaW5nIFBDQTAeFw0xMzAx
// SIG // MjQyMjMzMzlaFw0xNDA0MjQyMjMzMzlaMIGDMQswCQYD
// SIG // VQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G
// SIG // A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0
// SIG // IENvcnBvcmF0aW9uMQ0wCwYDVQQLEwRNT1BSMR4wHAYD
// SIG // VQQDExVNaWNyb3NvZnQgQ29ycG9yYXRpb24wggEiMA0G
// SIG // CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDor1yiIA34
// SIG // KHy8BXt/re7rdqwoUz8620B9s44z5lc/pVEVNFSlz7SL
// SIG // qT+oN+EtUO01Fk7vTXrbE3aIsCzwWVyp6+HXKXXkG4Un
// SIG // m/P4LZ5BNisLQPu+O7q5XHWTFlJLyjPFN7Dz636o9UEV
// SIG // XAhlHSE38Cy6IgsQsRCddyKFhHxPuRuQsPWj/ov0DJpO
// SIG // oPXJCiHiquMBNkf9L4JqgQP1qTXclFed+0vUDoLbOI8S
// SIG // /uPWenSIZOFixCUuKq6dGB8OHrbCryS0DlC83hyTXEmm
// SIG // ebW22875cHsoAYS4KinPv6kFBeHgD3FN/a1cI4Mp68fF
// SIG // SsjoJ4TTfsZDC5UABbFPZXHFAgMBAAGjggFgMIIBXDAT
// SIG // BgNVHSUEDDAKBggrBgEFBQcDAzAdBgNVHQ4EFgQUWXGm
// SIG // WjNN2pgHgP+EHr6H+XIyQfIwUQYDVR0RBEowSKRGMEQx
// SIG // DTALBgNVBAsTBE1PUFIxMzAxBgNVBAUTKjMxNTk1KzRm
// SIG // YWYwYjcxLWFkMzctNGFhMy1hNjcxLTc2YmMwNTIzNDRh
// SIG // ZDAfBgNVHSMEGDAWgBTLEejK0rQWWAHJNy4zFha5TJoK
// SIG // HzBWBgNVHR8ETzBNMEugSaBHhkVodHRwOi8vY3JsLm1p
// SIG // Y3Jvc29mdC5jb20vcGtpL2NybC9wcm9kdWN0cy9NaWND
// SIG // b2RTaWdQQ0FfMDgtMzEtMjAxMC5jcmwwWgYIKwYBBQUH
// SIG // AQEETjBMMEoGCCsGAQUFBzAChj5odHRwOi8vd3d3Lm1p
// SIG // Y3Jvc29mdC5jb20vcGtpL2NlcnRzL01pY0NvZFNpZ1BD
// SIG // QV8wOC0zMS0yMDEwLmNydDANBgkqhkiG9w0BAQUFAAOC
// SIG // AQEAMdduKhJXM4HVncbr+TrURE0Inu5e32pbt3nPApy8
// SIG // dmiekKGcC8N/oozxTbqVOfsN4OGb9F0kDxuNiBU6fNut
// SIG // zrPJbLo5LEV9JBFUJjANDf9H6gMH5eRmXSx7nR2pEPoc
// SIG // sHTyT2lrnqkkhNrtlqDfc6TvahqsS2Ke8XzAFH9IzU2y
// SIG // RPnwPJNtQtjofOYXoJtoaAko+QKX7xEDumdSrcHps3Om
// SIG // 0mPNSuI+5PNO/f+h4LsCEztdIN5VP6OukEAxOHUoXgSp
// SIG // Rm3m9Xp5QL0fzehF1a7iXT71dcfmZmNgzNWahIeNJDD3
// SIG // 7zTQYx2xQmdKDku/Og7vtpU6pzjkJZIIpohmgjCCBbww
// SIG // ggOkoAMCAQICCmEzJhoAAAAAADEwDQYJKoZIhvcNAQEF
// SIG // BQAwXzETMBEGCgmSJomT8ixkARkWA2NvbTEZMBcGCgmS
// SIG // JomT8ixkARkWCW1pY3Jvc29mdDEtMCsGA1UEAxMkTWlj
// SIG // cm9zb2Z0IFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5
// SIG // MB4XDTEwMDgzMTIyMTkzMloXDTIwMDgzMTIyMjkzMlow
// SIG // eTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0
// SIG // b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1p
// SIG // Y3Jvc29mdCBDb3Jwb3JhdGlvbjEjMCEGA1UEAxMaTWlj
// SIG // cm9zb2Z0IENvZGUgU2lnbmluZyBQQ0EwggEiMA0GCSqG
// SIG // SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCycllcGTBkvx2a
// SIG // YCAgQpl2U2w+G9ZvzMvx6mv+lxYQ4N86dIMaty+gMuz/
// SIG // 3sJCTiPVcgDbNVcKicquIEn08GisTUuNpb15S3GbRwfa
// SIG // /SXfnXWIz6pzRH/XgdvzvfI2pMlcRdyvrT3gKGiXGqel
// SIG // cnNW8ReU5P01lHKg1nZfHndFg4U4FtBzWwW6Z1KNpbJp
// SIG // L9oZC/6SdCnidi9U3RQwWfjSjWL9y8lfRjFQuScT5EAw
// SIG // z3IpECgixzdOPaAyPZDNoTgGhVxOVoIoKgUyt0vXT2Pn
// SIG // 0i1i8UU956wIAPZGoZ7RW4wmU+h6qkryRs83PDietHdc
// SIG // pReejcsRj1Y8wawJXwPTAgMBAAGjggFeMIIBWjAPBgNV
// SIG // HRMBAf8EBTADAQH/MB0GA1UdDgQWBBTLEejK0rQWWAHJ
// SIG // Ny4zFha5TJoKHzALBgNVHQ8EBAMCAYYwEgYJKwYBBAGC
// SIG // NxUBBAUCAwEAATAjBgkrBgEEAYI3FQIEFgQU/dExTtMm
// SIG // ipXhmGA7qDFvpjy82C0wGQYJKwYBBAGCNxQCBAweCgBT
// SIG // AHUAYgBDAEEwHwYDVR0jBBgwFoAUDqyCYEBWJ5flJRP8
// SIG // KuEKU5VZ5KQwUAYDVR0fBEkwRzBFoEOgQYY/aHR0cDov
// SIG // L2NybC5taWNyb3NvZnQuY29tL3BraS9jcmwvcHJvZHVj
// SIG // dHMvbWljcm9zb2Z0cm9vdGNlcnQuY3JsMFQGCCsGAQUF
// SIG // BwEBBEgwRjBEBggrBgEFBQcwAoY4aHR0cDovL3d3dy5t
// SIG // aWNyb3NvZnQuY29tL3BraS9jZXJ0cy9NaWNyb3NvZnRS
// SIG // b290Q2VydC5jcnQwDQYJKoZIhvcNAQEFBQADggIBAFk5
// SIG // Pn8mRq/rb0CxMrVq6w4vbqhJ9+tfde1MOy3XQ60L/svp
// SIG // LTGjI8x8UJiAIV2sPS9MuqKoVpzjcLu4tPh5tUly9z7q
// SIG // QX/K4QwXaculnCAt+gtQxFbNLeNK0rxw56gNogOlVuC4
// SIG // iktX8pVCnPHz7+7jhh80PLhWmvBTI4UqpIIck+KUBx3y
// SIG // 4k74jKHK6BOlkU7IG9KPcpUqcW2bGvgc8FPWZ8wi/1wd
// SIG // zaKMvSeyeWNWRKJRzfnpo1hW3ZsCRUQvX/TartSCMm78
// SIG // pJUT5Otp56miLL7IKxAOZY6Z2/Wi+hImCWU4lPF6H0q7
// SIG // 0eFW6NB4lhhcyTUWX92THUmOLb6tNEQc7hAVGgBd3TVb
// SIG // Ic6YxwnuhQ6MT20OE049fClInHLR82zKwexwo1eSV32U
// SIG // jaAbSANa98+jZwp0pTbtLS8XyOZyNxL0b7E8Z4L5UrKN
// SIG // MxZlHg6K3RDeZPRvzkbU0xfpecQEtNP7LN8fip6sCvsT
// SIG // J0Ct5PnhqX9GuwdgR2VgQE6wQuxO7bN2edgKNAltHIAx
// SIG // H+IOVN3lofvlRxCtZJj/UBYufL8FIXrilUEnacOTj5XJ
// SIG // jdibIa4NXJzwoq6GaIMMai27dmsAHZat8hZ79haDJLmI
// SIG // z2qoRzEvmtzjcT3XAH5iR9HOiMm4GPoOco3Boz2vAkBq
// SIG // /2mbluIQqBC0N1AI1sM9MIIGBzCCA++gAwIBAgIKYRZo
// SIG // NAAAAAAAHDANBgkqhkiG9w0BAQUFADBfMRMwEQYKCZIm
// SIG // iZPyLGQBGRYDY29tMRkwFwYKCZImiZPyLGQBGRYJbWlj
// SIG // cm9zb2Z0MS0wKwYDVQQDEyRNaWNyb3NvZnQgUm9vdCBD
// SIG // ZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcNMDcwNDAzMTI1
// SIG // MzA5WhcNMjEwNDAzMTMwMzA5WjB3MQswCQYDVQQGEwJV
// SIG // UzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMH
// SIG // UmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBv
// SIG // cmF0aW9uMSEwHwYDVQQDExhNaWNyb3NvZnQgVGltZS1T
// SIG // dGFtcCBQQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
// SIG // ggEKAoIBAQCfoWyx39tIkip8ay4Z4b3i48WZUSNQrc7d
// SIG // GE4kD+7Rp9FMrXQwIBHrB9VUlRVJlBtCkq6YXDAm2gBr
// SIG // 6Hu97IkHD/cOBJjwicwfyzMkh53y9GccLPx754gd6udO
// SIG // o6HBI1PKjfpFzwnQXq/QsEIEovmmbJNn1yjcRlOwhtDl
// SIG // KEYuJ6yGT1VSDOQDLPtqkJAwbofzWTCd+n7Wl7PoIZd+
// SIG // +NIT8wi3U21StEWQn0gASkdmEScpZqiX5NMGgUqi+YSn
// SIG // EUcUCYKfhO1VeP4Bmh1QCIUAEDBG7bfeI0a7xC1Un68e
// SIG // eEExd8yb3zuDk6FhArUdDbH895uyAc4iS1T/+QXDwiAL
// SIG // AgMBAAGjggGrMIIBpzAPBgNVHRMBAf8EBTADAQH/MB0G
// SIG // A1UdDgQWBBQjNPjZUkZwCu1A+3b7syuwwzWzDzALBgNV
// SIG // HQ8EBAMCAYYwEAYJKwYBBAGCNxUBBAMCAQAwgZgGA1Ud
// SIG // IwSBkDCBjYAUDqyCYEBWJ5flJRP8KuEKU5VZ5KShY6Rh
// SIG // MF8xEzARBgoJkiaJk/IsZAEZFgNjb20xGTAXBgoJkiaJ
// SIG // k/IsZAEZFgltaWNyb3NvZnQxLTArBgNVBAMTJE1pY3Jv
// SIG // c29mdCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eYIQ
// SIG // ea0WoUqgpa1Mc1j0BxMuZTBQBgNVHR8ESTBHMEWgQ6BB
// SIG // hj9odHRwOi8vY3JsLm1pY3Jvc29mdC5jb20vcGtpL2Ny
// SIG // bC9wcm9kdWN0cy9taWNyb3NvZnRyb290Y2VydC5jcmww
// SIG // VAYIKwYBBQUHAQEESDBGMEQGCCsGAQUFBzAChjhodHRw
// SIG // Oi8vd3d3Lm1pY3Jvc29mdC5jb20vcGtpL2NlcnRzL01p
// SIG // Y3Jvc29mdFJvb3RDZXJ0LmNydDATBgNVHSUEDDAKBggr
// SIG // BgEFBQcDCDANBgkqhkiG9w0BAQUFAAOCAgEAEJeKw1wD
// SIG // RDbd6bStd9vOeVFNAbEudHFbbQwTq86+e4+4LtQSooxt
// SIG // YrhXAstOIBNQmd16QOJXu69YmhzhHQGGrLt48ovQ7DsB
// SIG // 7uK+jwoFyI1I4vBTFd1Pq5Lk541q1YDB5pTyBi+FA+mR
// SIG // KiQicPv2/OR4mS4N9wficLwYTp2OawpylbihOZxnLcVR
// SIG // DupiXD8WmIsgP+IHGjL5zDFKdjE9K3ILyOpwPf+FChPf
// SIG // wgphjvDXuBfrTot/xTUrXqO/67x9C0J71FNyIe4wyrt4
// SIG // ZVxbARcKFA7S2hSY9Ty5ZlizLS/n+YWGzFFW6J1wlGys
// SIG // OUzU9nm/qhh6YinvopspNAZ3GmLJPR5tH4LwC8csu89D
// SIG // s+X57H2146SodDW4TsVxIxImdgs8UoxxWkZDFLyzs7BN
// SIG // Z8ifQv+AeSGAnhUwZuhCEl4ayJ4iIdBD6Svpu/RIzCzU
// SIG // 2DKATCYqSCRfWupW76bemZ3KOm+9gSd0BhHudiG/m4LB
// SIG // J1S2sWo9iaF2YbRuoROmv6pH8BJv/YoybLL+31HIjCPJ
// SIG // Zr2dHYcSZAI9La9Zj7jkIeW1sMpjtHhUBdRBLlCslLCl
// SIG // eKuzoJZ1GtmShxN1Ii8yqAhuoFuMJb+g74TKIdbrHk/J
// SIG // mu5J4PcBZW+JC33Iacjmbuqnl84xKf8OxVtc2E0bodj6
// SIG // L54/LlUWa8kTo/0xggSlMIIEoQIBATCBkDB5MQswCQYD
// SIG // VQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G
// SIG // A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0
// SIG // IENvcnBvcmF0aW9uMSMwIQYDVQQDExpNaWNyb3NvZnQg
// SIG // Q29kZSBTaWduaW5nIFBDQQITMwAAALARrwqL0Duf3QAB
// SIG // AAAAsDAJBgUrDgMCGgUAoIG+MBkGCSqGSIb3DQEJAzEM
// SIG // BgorBgEEAYI3AgEEMBwGCisGAQQBgjcCAQsxDjAMBgor
// SIG // BgEEAYI3AgEVMCMGCSqGSIb3DQEJBDEWBBTu4Fx22Onq
// SIG // qtM6NDtT5YccDCOd+DBeBgorBgEEAYI3AgEMMVAwTqAm
// SIG // gCQATQBpAGMAcgBvAHMAbwBmAHQAIABMAGUAYQByAG4A
// SIG // aQBuAGehJIAiaHR0cDovL3d3dy5taWNyb3NvZnQuY29t
// SIG // L2xlYXJuaW5nIDANBgkqhkiG9w0BAQEFAASCAQCaTcC3
// SIG // 5KdChL6kTkiKd0NBg8tOpicYZZ6wma2NjZ2JziU6drlO
// SIG // lYl9gmAf9nZN0L0BAQkwc3uC0Var2su6Ar/y9HphhON3
// SIG // DvEZyWmFH+mb6SZ/tl26/hlTNtX1O6WaxTmtOmSKfuLH
// SIG // CBTuIRzg1XocIw/683k4/uAg/u+5EZW/l6XG5bInT82S
// SIG // kXxvFUwBsdYfmwmqwHyXZcTK8pTxIBKDL3eMgeooqr1t
// SIG // yLSqMssDJdLbRoaTclR6bLpNa1bKxYRFQ/0lrZCoCmx/
// SIG // PQBCpxa4QGxGcHlS5NNuXajxq5+nzhnacy/gflvBwTeD
// SIG // bQE1D+qNZl+z128noJiX6fJ5EMWPoYICKDCCAiQGCSqG
// SIG // SIb3DQEJBjGCAhUwggIRAgEBMIGOMHcxCzAJBgNVBAYT
// SIG // AlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQH
// SIG // EwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29y
// SIG // cG9yYXRpb24xITAfBgNVBAMTGE1pY3Jvc29mdCBUaW1l
// SIG // LVN0YW1wIFBDQQITMwAAADQkMUDJoMF5jQAAAAAANDAJ
// SIG // BgUrDgMCGgUAoF0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3
// SIG // DQEHATAcBgkqhkiG9w0BCQUxDxcNMTMwNDIzMjAxODQ0
// SIG // WjAjBgkqhkiG9w0BCQQxFgQUtOEGirh1FaS/W3hgzmqC
// SIG // aPzN5a0wDQYJKoZIhvcNAQEFBQAEggEAdM6qA5Y2grw0
// SIG // tztdSRWCQ6pGefDoql0IaQ0ytkpmtVWF1PWD+sLj75V+
// SIG // 9s1CMMXW9EG39+C3nuTY82MKgR8OYOeCEu45iKmBXpLN
// SIG // eF8f/qicUw59aA6ULfy2UADxwd3z0skqercH4GleeEtF
// SIG // wqGqXe3lbA9GoBtLQyg9lblUKKdnxDhgzzc4Efga005d
// SIG // qgmP0KmqxQg1kR1mUxsSeUPlDAhZMpj/92DOhC7a4PVG
// SIG // cwif/jetHwzVaEv7Zc2VOGHNWOKNnXP7swhL3BIa2ZGL
// SIG // mSFZC4HgpIdM7LMOkX6AUorKHWMcfVrnFNreihFrqFmB
// SIG // j7som3DPxgxGdn8/duufhA==
// SIG // End signature block
|
// @AngularClass
/*
* Helper: root(), and rootDir() are defined at the bottom
*/
var path = require('path');
// Webpack Plugins
var ProvidePlugin = require('webpack/lib/ProvidePlugin');
var DefinePlugin = require('webpack/lib/DefinePlugin');
var CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ENV = process.env.ENV = process.env.NODE_ENV = 'development';
var metadata = {
title: 'Angular2 Webpack Starter by @gdi2990 from @AngularClass',
baseUrl: '/',
host: '0.0.0.0',
port: 3000,
ENV: ENV
};
/*
* Config
*/
module.exports = {
// static data for index.html
metadata: metadata,
// for faster builds use 'eval'
devtool: 'source-map',
debug: true,
entry: {
'vendor': ['webpack/hot/dev-server', './src/vendor.ts'],
'main': './src/main.ts' // our angular app
},
// Config for our build files
output: {
path: root('dist'),
filename: '[name].bundle.js',
sourceMapFilename: '[name].map',
chunkFilename: '[id].chunk.js'
},
resolve: {
// ensure loader extensions match
extensions: ['','.ts','.js','.json','.css','.html']
},
module: {
preLoaders: [{ test: /\.ts$/, loader: 'tslint-loader', exclude: [/node_modules/] }],
loaders: [
// Support for .ts files.
{
test: /\.ts$/,
loader: 'ts-loader',
query: {
'ignoreDiagnostics': [
2403, // 2403 -> Subsequent variable declarations
2300, // 2300 -> Duplicate identifier
2374, // 2374 -> Duplicate number index signature
2375 // 2375 -> Duplicate string index signature
]
},
exclude: [ /\.(spec|e2e)\.ts$/, /node_modules\/(?!(ng2-.+))/ ]
},
{ test: /\.css$/, loader: 'style-loader!css-loader' },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file" },
{ test: /\.(woff|woff2)$/, loader:"url?prefix=font/&limit=5000" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml" },
// Support for *.json files.
{ test: /\.json$/, loader: 'json-loader' },
// support for .html as raw text
{ test: /\.html$/, loader: 'raw-loader' }
// if you add a loader include the resolve file extension above
]
},
plugins: [
new CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.bundle.js', minChunks: Infinity }),
// static assets
new CopyWebpackPlugin([ { from: 'src/assets', to: 'assets' } ]),
// generating html
new HtmlWebpackPlugin({ template: 'src/index.html', inject: false }),
// replace
new DefinePlugin({
'process.env': {
'ENV': JSON.stringify(metadata.ENV),
'NODE_ENV': JSON.stringify(metadata.ENV)
}
})
],
// Other module loader config
tslint: {
emitErrors: false,
failOnHint: false
},
// our Webpack Development Server config
devServer: {
port: metadata.port,
host: metadata.host,
historyApiFallback: true,
watchOptions: { aggregateTimeout: 300, poll: 1000 },
proxy: {
'/api/*': {
target: 'http://localhost:3009',
secure: false
}
}
},
// we need this due to problems with es6-shim
node: {global: 'window', progress: false, crypto: 'empty', module: false, clearImmediate: false, setImmediate: false}
};
// Helper functions
function root(args) {
args = Array.prototype.slice.call(arguments, 0);
return path.join.apply(path, [__dirname].concat(args));
}
function rootNode(args) {
args = Array.prototype.slice.call(arguments, 0);
return root.apply(path, ['node_modules'].concat(args));
}
|
// All code points in the `No` category as per Unicode v5.1.0:
[
0xB2,
0xB3,
0xB9,
0xBC,
0xBD,
0xBE,
0x9F4,
0x9F5,
0x9F6,
0x9F7,
0x9F8,
0x9F9,
0xBF0,
0xBF1,
0xBF2,
0xC78,
0xC79,
0xC7A,
0xC7B,
0xC7C,
0xC7D,
0xC7E,
0xD70,
0xD71,
0xD72,
0xD73,
0xD74,
0xD75,
0xF2A,
0xF2B,
0xF2C,
0xF2D,
0xF2E,
0xF2F,
0xF30,
0xF31,
0xF32,
0xF33,
0x1369,
0x136A,
0x136B,
0x136C,
0x136D,
0x136E,
0x136F,
0x1370,
0x1371,
0x1372,
0x1373,
0x1374,
0x1375,
0x1376,
0x1377,
0x1378,
0x1379,
0x137A,
0x137B,
0x137C,
0x17F0,
0x17F1,
0x17F2,
0x17F3,
0x17F4,
0x17F5,
0x17F6,
0x17F7,
0x17F8,
0x17F9,
0x2070,
0x2074,
0x2075,
0x2076,
0x2077,
0x2078,
0x2079,
0x2080,
0x2081,
0x2082,
0x2083,
0x2084,
0x2085,
0x2086,
0x2087,
0x2088,
0x2089,
0x2153,
0x2154,
0x2155,
0x2156,
0x2157,
0x2158,
0x2159,
0x215A,
0x215B,
0x215C,
0x215D,
0x215E,
0x215F,
0x2460,
0x2461,
0x2462,
0x2463,
0x2464,
0x2465,
0x2466,
0x2467,
0x2468,
0x2469,
0x246A,
0x246B,
0x246C,
0x246D,
0x246E,
0x246F,
0x2470,
0x2471,
0x2472,
0x2473,
0x2474,
0x2475,
0x2476,
0x2477,
0x2478,
0x2479,
0x247A,
0x247B,
0x247C,
0x247D,
0x247E,
0x247F,
0x2480,
0x2481,
0x2482,
0x2483,
0x2484,
0x2485,
0x2486,
0x2487,
0x2488,
0x2489,
0x248A,
0x248B,
0x248C,
0x248D,
0x248E,
0x248F,
0x2490,
0x2491,
0x2492,
0x2493,
0x2494,
0x2495,
0x2496,
0x2497,
0x2498,
0x2499,
0x249A,
0x249B,
0x24EA,
0x24EB,
0x24EC,
0x24ED,
0x24EE,
0x24EF,
0x24F0,
0x24F1,
0x24F2,
0x24F3,
0x24F4,
0x24F5,
0x24F6,
0x24F7,
0x24F8,
0x24F9,
0x24FA,
0x24FB,
0x24FC,
0x24FD,
0x24FE,
0x24FF,
0x2776,
0x2777,
0x2778,
0x2779,
0x277A,
0x277B,
0x277C,
0x277D,
0x277E,
0x277F,
0x2780,
0x2781,
0x2782,
0x2783,
0x2784,
0x2785,
0x2786,
0x2787,
0x2788,
0x2789,
0x278A,
0x278B,
0x278C,
0x278D,
0x278E,
0x278F,
0x2790,
0x2791,
0x2792,
0x2793,
0x2CFD,
0x3192,
0x3193,
0x3194,
0x3195,
0x3220,
0x3221,
0x3222,
0x3223,
0x3224,
0x3225,
0x3226,
0x3227,
0x3228,
0x3229,
0x3251,
0x3252,
0x3253,
0x3254,
0x3255,
0x3256,
0x3257,
0x3258,
0x3259,
0x325A,
0x325B,
0x325C,
0x325D,
0x325E,
0x325F,
0x3280,
0x3281,
0x3282,
0x3283,
0x3284,
0x3285,
0x3286,
0x3287,
0x3288,
0x3289,
0x32B1,
0x32B2,
0x32B3,
0x32B4,
0x32B5,
0x32B6,
0x32B7,
0x32B8,
0x32B9,
0x32BA,
0x32BB,
0x32BC,
0x32BD,
0x32BE,
0x32BF,
0x10107,
0x10108,
0x10109,
0x1010A,
0x1010B,
0x1010C,
0x1010D,
0x1010E,
0x1010F,
0x10110,
0x10111,
0x10112,
0x10113,
0x10114,
0x10115,
0x10116,
0x10117,
0x10118,
0x10119,
0x1011A,
0x1011B,
0x1011C,
0x1011D,
0x1011E,
0x1011F,
0x10120,
0x10121,
0x10122,
0x10123,
0x10124,
0x10125,
0x10126,
0x10127,
0x10128,
0x10129,
0x1012A,
0x1012B,
0x1012C,
0x1012D,
0x1012E,
0x1012F,
0x10130,
0x10131,
0x10132,
0x10133,
0x10175,
0x10176,
0x10177,
0x10178,
0x1018A,
0x10320,
0x10321,
0x10322,
0x10323,
0x10916,
0x10917,
0x10918,
0x10919,
0x10A40,
0x10A41,
0x10A42,
0x10A43,
0x10A44,
0x10A45,
0x10A46,
0x10A47,
0x1D360,
0x1D361,
0x1D362,
0x1D363,
0x1D364,
0x1D365,
0x1D366,
0x1D367,
0x1D368,
0x1D369,
0x1D36A,
0x1D36B,
0x1D36C,
0x1D36D,
0x1D36E,
0x1D36F,
0x1D370,
0x1D371
]; |
import { EventEmitter } from 'events'
import dispatcher from '../dispatcher'
import CarData from '../data/CarData'
import carActions from '../actions/CarActions'
class CarStore extends EventEmitter {
create (car) {
CarData.create(car)
.then(data => this.emit(this.eventTypes.CAR_CREATED, data))
}
delete (id) {
CarData.delete(id)
.then(data => this.emit(this.eventTypes.CAR_DELETED, data))
}
all (page, search) {
page = page || 1
search = search || ''
CarData.all(page, search)
.then(data => this.emit(this.eventTypes.CARS_RETRIEVED, data))
}
allUserCars () {
CarData.userCars()
.then(data => this.emit(this.eventTypes.USER_CARS_RETRIEVED, data))
}
getCar (id) {
CarData.getCar(id)
.then(data => this.emit(this.eventTypes.CAR_DETAILS_RETRIEVED, data))
}
createReview (review, id) {
CarData.createReview(review, id)
.then(data => this.emit(this.eventTypes.REVIEW_CREATED, data))
}
like (id) {
CarData.likeCar(id)
.then(data => this.emit(this.eventTypes.CAR_LIKED, data))
}
handleAction (action) {
switch (action.type) {
case carActions.types.CREATE_CAR: {
this.create(action.car)
break
}
case carActions.types.DELETE_CAR: {
this.delete(action.id)
break
}
case carActions.types.ALL_CARS: {
this.all(action.page, action.search)
break
}
case carActions.types.ALL_USER_CARS: {
this.allUserCars()
break
}
case carActions.types.CAR_DETAILS: {
this.getCar(action.id)
break
}
case carActions.types.CREATE_REVIEW: {
this.createReview(action.review, action.id)
break
}
case carActions.types.LIKE_CAR: {
this.like(action.id)
break
}
default: break
}
}
}
let carStore = new CarStore()
carStore.eventTypes = {
CAR_CREATED: 'car_created',
CAR_DELETED: 'car_deleted',
CARS_RETRIEVED: 'car_retrived',
USER_CARS_RETRIEVED: 'user_cars_retrieved',
CAR_DETAILS_RETRIEVED: 'car_details_retrieved',
REVIEW_CREATED: 'review_created',
CAR_LIKED: 'car_liked'
}
dispatcher.register(carStore.handleAction.bind(carStore))
export default carStore
|
'use strict';
const NUM_BACKGROUND_PROCS = 4;
const electron = require('electron');
const app = electron.app;
const path = require('path');
const appPath = app.getAppPath();
const appNodeModules = path.join(appPath, 'node_modules');
require('app-module-path').addPath(appNodeModules);
// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();
// prevent window & actionhero from being garbage collected
let mainWindow, actionhero, backgrounds = [];
function onClosed() {
// dereference the window
// for multiple windows store them in an array
mainWindow = null;
}
function createMainWindow() {
const win = new electron.BrowserWindow({
width: 800,
height: 600
});
win.loadURL(`file://${process.env.PROJECT_ROOT}/public/chat.html`);
win.on('closed', onClosed);
return win;
}
app.on('window-all-closed', () => {
// if (process.platform !== 'darwin') {
// app.quit();
// }
});
app.on('activate', () => {
if (!mainWindow) {
mainWindow = createMainWindow();
}
});
app.on('ready', () => {
process.env.PROJECT_ROOT = extractActionhero();
actionhero = startActionhero((err, api) => {
// Now that main is started, lets add more in the background
for (var i = 0; i < NUM_BACKGROUND_PROCS; i++) {
startActionheroBackground();
}
mainWindow = createMainWindow();
});
});
function startActionhero(params, callback) {
var actionheroPrototype = require('actionhero').actionheroPrototype;
var actionhero = new actionheroPrototype();
actionhero.start(params, callback);
return actionhero;
}
function startActionheroBackground() {
var bg = new electron.BrowserWindow({
width: 800,
height: 600,
x: 100,
y: 100,
show: false
});
bg.loadURL(`file://${__dirname}/bg.html`);
backgrounds.push(bg);
}
function extractActionhero() {
const ah = 'actionhero';
const src = path.join(appPath, ah);
const userData = app.getPath('userData');
const dst = path.join(userData, ah);
console.log('extracting actionhero project from ' + src + ' to ' + dst);
const fs = require('fs-extra');
fs.emptyDirSync(dst);
fs.copySync(src, dst, {
filter: function (path) {
return ! path.endsWith('.gitkeep');
}
});
return dst;
}
|
Meteor.subscribe("sound");
|
describe('use-fullscreen API', () => {
describe('Props', () => {
describe('Category: behavior', () => {
describe('(prop): fullscreen', () => {
it.skip(' ', () => {
//
})
})
describe('(prop): no-route-fullscreen-exit', () => {
it.skip(' ', () => {
//
})
})
})
})
describe('Methods', () => {
describe('(method): toggleFullscreen', () => {
it.skip(' ', () => {
//
})
})
describe('(method): setFullscreen', () => {
it.skip(' ', () => {
//
})
})
describe('(method): exitFullscreen', () => {
it.skip(' ', () => {
//
})
})
})
})
|
/*
* Copyright (c) 2015-2016 Markus Moenig <markusm@visualgraphics.tv>
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
VG.UI.VisualGraphicsDarkGraySkin=function()
{
this.name="Dark Gray";
this.path="desktop_darkgray";
this.Widget={
Font : VG.Font.Font( "Open Sans Semibold", 13 ),
BackgroundColor : VG.Core.Color( 93, 93, 93 ),
TextColor : VG.Core.Color( 244, 244, 244 ),
DisabledTextColor : VG.Core.Color( 200, 200, 200 ),
FocusColor : VG.Core.Color( 129, 197, 242 ),
DisabledAlpha : 0.25,
};
this.Label={
Font : VG.Font.Font( "Open Sans Semibold", 13 ),
};
this.Button={
Font : VG.Font.Font( "Open Sans Semibold", 13 ),
SmallFont : VG.Font.Font( "Open Sans Semibold", 12 ),
TextColor : VG.Core.Color( 255, 255, 255 ),
FocusBorderColor1 : VG.Core.Color( 207, 128, 231 ),
FocusBorderColor2 : VG.Core.Color( 132, 132, 132 ),
FocusBorderCheckedColor2 : VG.Core.Color( 165, 165, 165 ),
BorderColor : VG.Core.Color( 126, 126, 126 ),
BackGradColor1 : VG.Core.Color( 148, 148, 148 ),
BackGradColor2 : VG.Core.Color( 138, 138, 138 ),
HoverBackGradColor1 : VG.Core.Color( 120, 120, 120 ),
HoverBackGradColor2 : VG.Core.Color( 112, 112, 112 ),
CheckedBackGradColor1 : VG.Core.Color( 180, 180, 180 ),
CheckedBackGradColor2 : VG.Core.Color( 194, 194, 194 ),
};
this.ButtonGroup={
Font : VG.Font.Font( "Roboto Regular", 13 ),
TextColor : VG.Core.Color( 244, 244, 244 ),
NormalBorderColor : VG.Core.Color( 108, 108, 108 ),
NormalBackColor : VG.Core.Color( 123, 123, 123 ),
HoverBorderColor : VG.Core.Color( 179, 179, 179 ),
HoverBackColor : VG.Core.Color( 157, 157, 157 ),
PressedBorderColor : VG.Core.Color( 204, 204, 204 ),
PressedBackColor : VG.Core.Color( 149, 149, 149 ),
};
this.CodeEdit={
Font : VG.Font.Font( "Open Sans Semibold", 14 ),
TopBorderColor : VG.Core.Color( 63, 75, 78 ),
HeaderColor : VG.Core.Color( 63, 75, 78 ),
HeaderTextColor : VG.Core.Color( 130, 151, 155 ),
BackgroundColor : VG.Core.Color( 40, 48, 50 ),
SelectionBackgroundColor : VG.Core.Color( 255, 255, 255, 120 ),
SearchBackgroundColor : VG.Core.Color( 215, 206, 175 ),
TextColor : VG.Core.Color( 240, 240, 240 ),
};
this.Menu={
Font : VG.Font.Font( "Open Sans Semibold", 13 ),
ShortcutFont : VG.Font.Font( "Open Sans Semibold", 13 ),
BorderColor : VG.Core.Color( 130, 130, 130 ),
SeparatorColor : VG.Core.Color( 102, 102, 102 ),
BackColor : VG.Core.Color( 149, 149, 149 ),
DisabledTextColor : VG.Core.Color( 128, 128, 128 ),
HighlightedTextColor : VG.Core.Color( 85, 85, 85 ),
HighlightedBackColor : VG.Core.Color( 194, 135, 212 ),
HighlightedBorderColor : VG.Core.Color( 194, 135, 212 ),
TextColor : VG.Core.Color( 255, 255, 255 ),
};
this.ContextMenu={
Font : VG.Font.Font( "Roboto Regular", 13 ),
TextColor : VG.Core.Color( 255, 255, 255 ),
DisabledTextColor : VG.Core.Color( 128, 128, 128 ),
BorderColor : VG.Core.Color( 130, 130, 130 ),
BackColor : VG.Core.Color( 149, 149, 149 ),
SeparatorColor : VG.Core.Color( 102, 102, 102 ),
HighlightedBackColor : VG.Core.Color( 194, 135, 212 ),
HighlightedTextColor : VG.Core.Color( 85, 85, 85 ),
};
this.DecoratedToolBar={
Height : 44,//66,
Spacing : 12,
LogoColor : VG.Core.Color( 255, 255, 255 ),
TopBorderColor : VG.Core.Color( 142, 142, 142 ),
//TopBorderColor1 : VG.Core.Color( 171, 171, 171 ),
//TopBorderColor2 : VG.Core.Color( 214, 214, 214 ),
BottomBorderColor : VG.Core.Color( 81, 81, 81 ),
BackGradColor1 : VG.Core.Color( 129, 129, 129 ),
BackGradColor2 : VG.Core.Color( 105, 105, 105 ),
Separator : {
Color1 : VG.Core.Color( "#666666" ),
Color2 : VG.Core.Color( "#949494" ),
Size : VG.Core.Size( 2, 24 ),
},
};
this.DecoratedQuickMenu={
ButtonBackgroundColor : VG.Core.Color( 120, 120, 120 ),
ButtonBackgroundHoverColor : VG.Core.Color( 157, 157, 157 ),
ButtonBackgroundSelectedColor : VG.Core.Color( 111, 107, 107 ),
StripeColor : VG.Core.Color( 55, 55, 55 ),
HoverColor : VG.Core.Color( 255, 255, 255 ),
Color : VG.Core.Color( 180, 180, 180 ),
BorderColor : VG.Core.Color( 255, 255, 255 ),
SubMenuBorderColor : VG.Core.Color( 182, 182, 182 ),
BackgroundColor : VG.Core.Color( 88, 88, 88 ),
ContentMargin : VG.Core.Margin( 0, 0, 0, 0 ),
Size : VG.Core.Size( 74, 58 ),
UsesCloseButton : false,
Items : {
BackGradSelectionColor1 : VG.Core.Color( 117, 117, 117 ),
BackGradSelectionColor2 : VG.Core.Color( 85, 85, 85 ),
Size : VG.Core.Size( 306, 42 ),
TextColor : VG.Core.Color( 255, 255, 255 ),
DisabledTextColor : VG.Core.Color( 128, 128, 128 ),
Font : VG.Font.Font( "Open Sans Semibold", 14 ),
}
};
this.DockWidget={
BackColor : VG.Core.Color( 99, 99, 99 ),
FloatingBorderColor : VG.Core.Color( 126, 197, 243 ),
HeaderHeight : 21,
HeaderFont : VG.Font.Font( "Open Sans Bold", 12 ),
HeaderBorderColor : VG.Core.Color( 86, 86, 86 ),
HeaderBackGradColor1 : VG.Core.Color( 105, 105, 105 ),
HeaderBackGradColor2 : VG.Core.Color( 96, 96, 96 ),
HeaderTextColor : VG.Core.Color( 255, 255, 255 ),
};
this.DropDownMenu={
Font : VG.Font.Font( "Open Sans Semibold", 13 ),
TextColor : VG.Core.Color( 255, 255, 255 ),
FocusBorderColor : VG.Core.Color( 207, 128, 231 ),
HoverBorderColor : VG.Core.Color( 107, 107, 107 ),
BorderColor : VG.Core.Color( 122, 122, 122 ),
HoverBackGradColor1 : VG.Core.Color( 98, 98, 98 ),
HoverBackGradColor2 : VG.Core.Color( 89, 89, 89 ),
BackGradColor1 : VG.Core.Color( 113, 113, 113 ),
BackGradColor2 : VG.Core.Color( 105, 105, 105 ),
SepColor1 : VG.Core.Color( 122, 122, 122 ),
SepColor2 : VG.Core.Color( 103, 103, 103 ),
ItemBorderColor : VG.Core.Color( 153, 153, 153 ),
ItemBackColor : VG.Core.Color( 124, 124, 124 ),
ItemSelectedBackColor : VG.Core.Color( 194, 135, 212 ),
ItemTextColor : VG.Core.Color( 255, 255, 255 ),
ItemSelectedTextColor : VG.Core.Color( 85, 85, 85 ),
};
this.HtmlWidget={
h1 : {
Font : VG.Font.Font( "Open Sans Bold", 26 ),
Color : VG.Core.Color( 244, 244, 244 ),
Margin : VG.Core.Margin( 10, 10, 20, 10 ),
ResetLayout : true,
LineFeed : true,
Spacing : 2,
},
h2 : {
Font : VG.Font.Font( "Open Sans Bold", 18 ),
Color : VG.Core.Color( 244, 244, 244 ),
Margin : VG.Core.Margin( 10, 5, 10, 5 ),
ResetLayout : true,
LineFeed : true,
Spacing : 2,
},
h4 : {
Font : VG.Font.Font( "Open Sans Bold", 13 ),
Color : VG.Core.Color( 204, 204, 204 ),
Margin : VG.Core.Margin( 10, 10, 10, 10 ),
ResetLayout : true,
LineFeed : true,
Spacing : 2,
},
p : {
Font : VG.Font.Font( "Open Sans Semibold", 13 ),
Color : VG.Core.Color( 244, 244, 244 ),
Margin : VG.Core.Margin( 10, 5, 10, 5 ),
ResetLayout : true,
LineFeed : true,
Spacing : 2,
},
svg : {
Color : VG.Core.Color( 244, 244, 244 ),
Margin : VG.Core.Margin( 0, 0, 0, 0 ),
},
img : {
Margin : VG.Core.Margin( 10, 10, 10, 10 ),
LineFeed : true,
},
b : {
Font : VG.Font.Font( "Open Sans Bold", 13 ),
Color : VG.Core.Color( 244, 244, 244 ),
Margin : VG.Core.Margin( 0, 0, 0, 0 ),
},
i : {
Font : VG.Font.Font( "Open Sans Semibold Italic", 13 ),
Color : VG.Core.Color( 244, 244, 244 ),
Margin : VG.Core.Margin( 0, 0, 0, 0 ),
},
a : {
Font : VG.Font.Font( "Open Sans Semibold", 13 ),
Color : VG.Core.Color( "#e452ef" ),
Link : true,
Margin : VG.Core.Margin( 0, 0, 0, 0 ),
},
ul : {
Margin : VG.Core.Margin( 30, 0, 5, 5 ),
ResetLayout : true,
LineFeed : true,
},
li : {
Font : VG.Font.Font( "Open Sans Semibold", 13 ),
Color : VG.Core.Color( 244, 244, 244 ),
Margin : VG.Core.Margin( 5, 5, 5, 5 ),
LineFeed : true,
},
br : {
Margin : VG.Core.Margin( 0, 15, 0, 0 ),
LineFeed : true,
}
};
this.HtmlView={
FontName : "Open Sans Semibold",
BoldFontName : "Open Sans Bold",
ItalicFontName : "Open Sans Semibold Italic",
};
this.IconWidget={
Font : VG.Font.Font( "Open Sans Semibold", 13 ),
TextColor : VG.Core.Color( 203, 203, 203 ),
FocusBorderColor : VG.Core.Color( 207, 128, 231 ),
BorderColor : VG.Core.Color( 107, 107, 107 ),
HoverBorderColor : VG.Core.Color( 122, 122, 122 ),
BackColor : VG.Core.Color( 82, 82, 82 ),
Spacing : VG.Core.Size( 5, 5 ),
Margin : VG.Core.Margin( 5, 5, 5, 5 ),
ItemBackColor : VG.Core.Color( 177, 177, 177 ),
ItemSelectedBorderColor : VG.Core.Color( 207, 128, 231 ),
ItemSelectedBackColor : VG.Core.Color( 194, 135, 212 ),
ItemCustomContentBorderColor : VG.Core.Color( 139, 139, 139 ),
ToolLayoutHeight : 28,
ToolTopBorderColor : VG.Core.Color( 155, 155, 155 ),
ToolBottomBorderColor : VG.Core.Color( 89, 89, 89 ),
ToolBackGradColor1 : VG.Core.Color( 139, 139, 139 ),
ToolBackGradColor2 : VG.Core.Color( 105, 105, 105 ),
};
this.ListWidget={
Font : VG.Font.Font( "Open Sans Semibold", 13 ),
TextColor : VG.Core.Color( 85, 81, 85 ),
FocusBorderColor : VG.Core.Color( 207, 128, 231 ),
BorderColor : VG.Core.Color( 107, 107, 107 ),
HoverBorderColor : VG.Core.Color( 122, 122, 122 ),
BackColor : VG.Core.Color( 82, 82, 82 ),
Spacing : 2,
Margin : VG.Core.Margin( 2, 2, 2, 2 ),
ItemBackColor : VG.Core.Color( 177, 177, 177 ),
ItemSelectedBorderColor : VG.Core.Color( 207, 128, 231 ),
ItemSelectedBackColor : VG.Core.Color( 194, 135, 212 ),
ItemCustomContentBorderColor : VG.Core.Color( 139, 139, 139 ),
ToolLayoutHeight : 28,
ToolTopBorderColor : VG.Core.Color( 155, 155, 155 ),
ToolBottomBorderColor : VG.Core.Color( 89, 89, 89 ),
ToolBackGradColor1 : VG.Core.Color( 139, 139, 139 ),
ToolBackGradColor2 : VG.Core.Color( 105, 105, 105 ),
};
this.Menu={
Font : VG.Font.Font( "Open Sans Semibold", 13 ),
ShortcutFont : VG.Font.Font( "Open Sans Semibold", 13 ),
BorderColor : VG.Core.Color( 130, 130, 130 ),
SeparatorColor : VG.Core.Color( 102, 102, 102 ),
BackColor : VG.Core.Color( 149, 149, 149 ),
DisabledTextColor : VG.Core.Color( 128, 128, 128 ),
HighlightedTextColor : VG.Core.Color( 85, 85, 85 ),
HighlightedBackColor : VG.Core.Color( 194, 135, 212 ),
HighlightedBorderColor : VG.Core.Color( 194, 135, 212 ),
TextColor : VG.Core.Color( 255, 255, 255 ),
};
this.MenuBar={
Font : VG.Font.Font( "Open Sans Semibold", 13 ),
Height : 21,
BorderSize : 1,
TopBorderColor : VG.Core.Color( 180, 180, 180 ),
BottomBorderColor : VG.Core.Color( 91, 91, 91 ),
BackColor : VG.Core.Color( 137, 137, 137 ),
SelectedBackColor : VG.Core.Color( 61, 61, 61 ),
TextColor : VG.Core.Color( 255, 255, 255 ),
SelectedTextColor : VG.Core.Color( 255, 255, 255 ),
};
this.Nodes={
Font : VG.Font.Font( "Open Sans Semibold", 12 ),
BackColor : VG.Core.Color( 128, 128, 128 ),
BackLineColor : VG.Core.Color( 74, 74, 74 ),
GridSize : 45,
BorderColor : VG.Core.Color( 244, 244, 244 ),
TopColor : VG.Core.Color( 65, 65, 65 ),
SeparatorColor : VG.Core.Color.Black,
BodyColor : VG.Core.Color( 192, 192, 192 ),
TitleTextColor : VG.Core.Color( 195, 195, 195 ),
TerminalTextColor : VG.Core.Color( 76, 76, 76 ),
TextureTerminalColor : VG.Core.Color( "#318828" ),
MaterialTerminalColor : VG.Core.Color( 190, 171, 0 ),
FloatTerminalColor : VG.Core.Color( 95, 54, 136),//0, 95, 185 ),
Vector2TerminalColor : VG.Core.Color("#9a151d"),//0, 95, 185 ),
Vector3TerminalColor : VG.Core.Color("#005fb9"),//0, 95, 185 ),
Vector4TerminalColor : VG.Core.Color(),//0, 95, 185 ),
};
this.ScrollBar={
Size : 14,
BorderColor : VG.Core.Color( 119, 119, 119 ),
BackColor : VG.Core.Color( 139, 139, 139 ),
};
this.SectionBar={
BorderColor : VG.Core.Color( 75, 75, 75 ),
BackColor : VG.Core.Color( 130, 130, 130 ),
HeaderHeight : 21,
HeaderFont : VG.Font.Font( "Open Sans Bold", 12 ),
HeaderBorderColor : VG.Core.Color( 82, 82, 82 ),
HeaderBackGradColor1 : VG.Core.Color( 100, 100, 100 ),
HeaderBackGradColor2 : VG.Core.Color( 91, 91, 91 ),
HeaderTextColor : VG.Core.Color( 255, 255, 255 ),
Separator : {
Height : 2,
Color1 : VG.Core.Color( 109, 109, 109 ),
Color2 : VG.Core.Color( 158, 158, 158 ),
}
};
this.SectionBarButton={
Font : VG.Font.Font( "Open Sans Bold", 12 ),
Size : VG.Core.Size( 81, 47 ),
BorderColor : VG.Core.Color( 80, 80, 80 ),
BackGradColor1 : VG.Core.Color( 80, 80, 80 ),
BackGradColor2 : VG.Core.Color( 72, 72, 72 ),
HoverBorderColor : VG.Core.Color( 107, 107, 107 ),
HoverBackGradColor1 : VG.Core.Color( 94, 94, 94 ),
HoverBackGradColor2 : VG.Core.Color( 86, 86, 86 ),
SelectedBorderColor : VG.Core.Color( 245, 245, 245 ),
SelectedBackGradColor1 : VG.Core.Color( 242, 242, 242 ),
SelectedBackGradColor2 : VG.Core.Color( 242, 242, 242 ),
SelectedTextColor : VG.Core.Color( 96, 96, 96 ),
TextColor : VG.Core.Color( 255, 255, 255 ),
};
this.SectionBarSwitch={
Font : VG.Font.Font( "Open Sans Bold", 12 ),
Size : VG.Core.Size( 81, 32 ),
TextColor : VG.Core.Color( 255, 255, 255 ),
};
this.SectionToolBar={
BackColor : VG.Core.Color( 130, 130, 130 ),
BorderColor1 : VG.Core.Color( 82, 82, 82 ),
BorderColor2 : VG.Core.Color( 130, 130, 130 ),
HeaderTopBorderColor : VG.Core.Color( 155, 155, 155 ),
HeaderGradColor1 : VG.Core.Color( 139, 139, 139 ),
HeaderGradColor2 : VG.Core.Color( 110, 110, 110 ),
HeaderBottomBorderColor1 : VG.Core.Color( 105, 105, 105 ),
HeaderBottomBorderColor2 : VG.Core.Color( 89, 89, 89 ),
HeaderFont : VG.Font.Font( "Open Sans Bold", 12 ),
HeaderTextColor : VG.Core.Color( 255, 255, 255 ),
Separator : {
Height : 2,
Color1 : VG.Core.Color( 136, 136, 136 ),
Color2 : VG.Core.Color( 197, 197, 197 ),
}
};
this.SectionToolBarButton={
Size : VG.Core.Size( 46, 43 ),
// Size : VG.Core.Size( 46, 38 ),
SmallSize : VG.Core.Size( 36, 34 ),
BorderColor : VG.Core.Color( 108, 108, 108 ),
BorderHoverColor : VG.Core.Color( 179, 179, 179 ),
BorderSelectedColor : VG.Core.Color( 204, 204, 204 ),
BackHoverColor : VG.Core.Color( 157, 157, 157 ),
BackSelectedColor : VG.Core.Color( 149, 149, 149 ),
};
this.Slider={
FocusHoverBarColors : {
Color1 : VG.Core.Color( 219, 219, 219 ),
Color2 : VG.Core.Color( 190, 190, 190 ),
Color3 : VG.Core.Color( 218, 218, 218 ),
Color4 : VG.Core.Color( 235, 235, 235 ),
},
BarColors : {
Color1 : VG.Core.Color( 187, 187, 187 ),
Color2 : VG.Core.Color( 170, 170, 170 ),
Color3 : VG.Core.Color( 186, 186, 186 ),
Color4 : VG.Core.Color( 197, 197, 197 ),
},
HandleSize : 13,
BarHeight : 4
};
this.RoundSlider={
FocusHoverBarColors : {
Color1 : VG.Core.Color( 219, 219, 219 ),
Color2 : VG.Core.Color( 190, 190, 190 ),
Color3 : VG.Core.Color( 218, 218, 218 ),
},
LeftTrackColors : {
Color1 : VG.Core.Color( 130, 130, 130 ),
Color2 : VG.Core.Color( 139, 139, 139 ),
Color3 : VG.Core.Color( 175, 175, 175 ),
},
RightTrackColors : {
Color1 : VG.Core.Color( 75, 75, 75 ),
Color2 : VG.Core.Color( 90, 90, 90 ),
Color3 : VG.Core.Color( 149, 149, 149 ),
},
HandleSize : 14,
BarHeight : 3,
KnobColor : VG.Core.Color( 221, 221, 221 ),
OuterKnobColor : VG.Core.Color( 221, 221, 221, 128 ),
SelectedOuterKnobColor : VG.Core.Color( 207, 128, 231, 128 )
};
this.SnapperWidgetItem={
Font : VG.Font.Font( "Open Sans Semibold", 13 ),
TextColor : VG.Core.Color( 255, 255, 255 ),
Height : 22,
TopBorderColor : VG.Core.Color( 155, 155, 155 ),
BottomBorderColor : VG.Core.Color( 89, 89, 89 ),
BackGradColor1 : VG.Core.Color( 139, 139, 139 ),
BackGradColor2 : VG.Core.Color( 106, 106, 106 ),
HoverTopBorderColor : VG.Core.Color( 162, 162, 162 ),
HoverBottomBorderColor : VG.Core.Color( 104, 104, 104 ),
HoverBackGradColor1 : VG.Core.Color( 147, 147, 147 ),
HoverBackGradColor2 : VG.Core.Color( 118, 118, 118 ),
SelectedTopBorderColor : VG.Core.Color( 135, 135, 135 ),
SelectedBottomBorderColor : VG.Core.Color( 78, 78, 78 ),
SelectedBackGradColor1 : VG.Core.Color( 121, 121, 121 ),
SelectedBackGradColor2 : VG.Core.Color( 93, 93, 93 ),
};
this.SplitLayout={
Size : 7,
BackColor : VG.Core.Color( 133, 133, 133 ),
BorderColor : VG.Core.Color( 160, 160, 160 ),
DragBackColor : VG.Core.Color( 132, 132, 132 ),
DragBorderColor : VG.Core.Color( 239, 239, 239 ),
HoverBackColor : VG.Core.Color( 148, 148, 148 ),
HoverBorderColor : VG.Core.Color( 191, 191, 191 ),
};
this.StatusBar={
BorderColor : VG.Core.Color( 76, 76, 76 ),
BackColor : VG.Core.Color( 120, 120, 120 ),
Height : 20,
};
this.TabWidgetHeader={
Font : VG.Font.Font( "Open Sans Semibold", 14 ),
TextColor : VG.Core.Color( 244, 244, 244 ),
Height : 32,
SelectedEdgeBorderColor : VG.Core.Color( 110, 110, 110 ),
SelectedTopBorderColor : VG.Core.Color( 118, 118, 118 ),
SelectedSideBorderColor1 : VG.Core.Color( 114, 114, 114 ),
SelectedSideBorderColor2 : VG.Core.Color( 103, 103, 103 ),
SelectedBackGradientColor1 : VG.Core.Color( 119, 119, 119 ),
SelectedBackGradientColor2 : VG.Core.Color( 114, 114, 114 ),
HoverBackGradientColor1 : VG.Core.Color( 100, 100, 100 ),
HoverBackGradientColor2 : VG.Core.Color( 89, 89, 89 ),
BackGradientColor1 : VG.Core.Color( 106, 106, 106 ),
BackGradientColor2 : VG.Core.Color( 95, 95, 95 ),
LeftBorderColor : VG.Core.Color( 117, 117, 117 ),
TabBorderColor : VG.Core.Color( 137, 137, 137 ),
BottomBorderColor1 : VG.Core.Color( 98, 98, 98 ),
BottomBorderColor2 : VG.Core.Color( 114, 114, 114 ),
};
this.TabWidgetSmallHeader={
Font : VG.Font.Font( "Open Sans Semibold", 12 ),
TextColor : VG.Core.Color( 244, 244, 244 ),
Height : 22,
SelectedEdgeBorderColor : VG.Core.Color( 110, 110, 110 ),
SelectedTopBorderColor : VG.Core.Color( 118, 118, 118 ),
SelectedSideBorderColor1 : VG.Core.Color( 114, 114, 114 ),
SelectedSideBorderColor2 : VG.Core.Color( 103, 103, 103 ),
SelectedBackGradientColor1 : VG.Core.Color( 119, 119, 119 ),
SelectedBackGradientColor2 : VG.Core.Color( 114, 114, 114 ),
HoverBackGradientColor1 : VG.Core.Color( 100, 100, 100 ),
HoverBackGradientColor2 : VG.Core.Color( 89, 89, 89 ),
BackGradientColor1 : VG.Core.Color( 106, 106, 106 ),
BackGradientColor2 : VG.Core.Color( 95, 95, 95 ),
LeftBorderColor : VG.Core.Color( 117, 117, 117 ),
TabBorderColor : VG.Core.Color( 137, 137, 137 ),
BottomBorderColor1 : VG.Core.Color( 98, 98, 98 ),
BottomBorderColor2 : VG.Core.Color( 114, 114, 114 ),
};
this.TextEdit={
Font : VG.Font.Font( "Roboto Regular", 14 ),
TextColor : VG.Core.Color( 242, 242, 242 ),
DefaultTextColor : VG.Core.Color( 71, 71, 71 ),
FocusBorderColor1 : VG.Core.Color( 207, 128, 231 ),
FocusBorderColor2 : VG.Core.Color( 194, 135, 212 ),
FocusBorderColor3 : VG.Core.Color( 119, 119, 119 ),
FocusBackgroundColor : VG.Core.Color( 148, 148, 148 ),
BackgroundColor : VG.Core.Color( 148, 148, 148 ),
BorderColor1 : VG.Core.Color( 209, 209, 209 ),
BorderColor2 : VG.Core.Color( 149, 149, 149 ),
};
this.TextLineEdit={
Font : VG.Font.Font( "Roboto Regular", 14 ),
TextColor : VG.Core.Color( 242, 242, 242 ),
DefaultTextColor : VG.Core.Color( 71, 71, 71 ),
FocusBorderColor1 : VG.Core.Color( 207, 128, 231 ),
FocusBorderColor2 : VG.Core.Color( 194, 135, 212 ),
FocusBorderColor3 : VG.Core.Color( 148, 148, 148 ),
FocusBackgroundColor : VG.Core.Color( 148, 148, 148 ),
BackgroundColor : VG.Core.Color( 148, 148, 148 ),
BorderColor1 : VG.Core.Color( 209, 209, 209 ),
BorderColor2 : VG.Core.Color( 148, 148, 148 ),
};
this.Timeline={
LayerFont : VG.Font.Font( "Open Sans Semibold", 13 ),
ObjectFont : VG.Font.Font( "Open Sans Semibold", 11 ),
TrackBackColor1 : VG.Core.Color( 46, 46, 48 ),
TrackBackColor2 : VG.Core.Color( 57, 57, 57 ),
TrackSepColor : VG.Core.Color( 34, 34, 34 ),
TextColor : VG.Core.Color( 85, 81, 85 ),
FocusBorderColor : VG.Core.Color( 207, 128, 231 ),
BorderColor : VG.Core.Color( 107, 107, 107 ),
HoverBorderColor : VG.Core.Color( 122, 122, 122 ),
BackColor : VG.Core.Color( 82, 82, 82 ),
Spacing : 2,
Margin : VG.Core.Margin( 2, 2, 2, 2 ),
LayerBackColor : VG.Core.Color( 177, 177, 177 ),
LayerSelectedBorderColor : VG.Core.Color( 207, 128, 231 ),
LayerSelectedBackColor : VG.Core.Color( 194, 135, 212 ),
ItemCustomContentBorderColor : VG.Core.Color( 139, 139, 139 ),
ToolLayoutHeight : 28,
ToolTopBorderColor : VG.Core.Color( 155, 155, 155 ),
ToolBottomBorderColor : VG.Core.Color( 89, 89, 89 ),
ToolBackGradColor1 : VG.Core.Color( 139, 139, 139 ),
ToolBackGradColor2 : VG.Core.Color( 105, 105, 105 ),
};
this.TitleBar={
Height : 20,
Font : VG.Font.Font( "Open Sans Semibold", 12.5 ),
TextColor : VG.Core.Color( 255, 255, 255 ),
BorderColor : VG.Core.Color( 102, 102, 102 ),
BackGradColor1 : VG.Core.Color( 125, 125, 125 ),
BackGradColor2 : VG.Core.Color( 114, 114, 114 ),
};
this.ToolBar={
Height : 33,
TopBorderColor : VG.Core.Color( 102, 102, 102 ),
BottomBorderColor : VG.Core.Color( 160, 160, 160 ),
BackGradColor : VG.Core.Color( 120, 120, 120 ),
Separator : {
Color1 : VG.Core.Color( 102, 102, 102 ),
Color2 : VG.Core.Color( 148, 148, 148 ),
Size : VG.Core.Size( 2, 28 ),
},
IconSize : VG.Core.Size( 32, 27 ),
};
this.ToolBarButton={
Font : VG.Font.Font( "Roboto Regular", 14 ),
TextColor : VG.Core.Color( 255, 255, 255 ),
BorderColor : VG.Core.Color( 108, 108, 108 ),
BackColor : VG.Core.Color( 130, 130, 130 ),
HoverBorderColor : VG.Core.Color( 179, 179, 179 ),
HoverBackColor : VG.Core.Color( 157, 157, 157 ),
ClickedBorderColor : VG.Core.Color( 204, 204, 204 ),
ClickedBackColor : VG.Core.Color( 149, 149, 149 ),
TextMargin : VG.Core.Size( 10, 0 ),
IconSize : VG.Core.Size( 24, 24 ),
MinimumWidth : 45,
};
this.ToolButton={
Color : VG.Core.Color( 255, 255, 255 ),
BorderColor : VG.Core.Color( 158, 158, 158 ),
BackColor : VG.Core.Color( 163, 163, 163 ),
HoverBorderColor : VG.Core.Color( 224, 224, 224 ),
HoverBackColor : VG.Core.Color( 163, 163, 163 ),
ClickedBorderColor : VG.Core.Color( 255, 255, 255 ),
ClickedBackColor : VG.Core.Color( 186, 186, 186 ),
Size : VG.Core.Size( 46, 43 ),
Margin : VG.Core.Size( 3, 3 ),
MinimumWidth : 45,
};
this.ToolSettings={
HeaderFont : VG.Font.Font( "Open Sans Bold", 13 ),
BackColor : VG.Core.Color( 123, 123, 123 ),
BorderColor : VG.Core.Color( 108, 108, 108 ),
HoverBackColor : VG.Core.Color( 157, 157, 157 ),
HoverBorderColor : VG.Core.Color( 179, 179, 179 ),
OpenBorderColor : VG.Core.Color( 204, 204, 204 ),
OpenBackColor : VG.Core.Color( 149, 149, 149 ),
ContentBorderColor : VG.Core.Color( 146, 146, 146 ),
ContentBackColor : VG.Core.Color( 116, 116, 116 ),
Size : VG.Core.Size( 21, 20 ),
};
this.ToolTip={
TitleFont : VG.Font.Font( "Open Sans Bold", 14 ),
Font : VG.Font.Font( "Open Sans Semibold", 13 ),
BorderColor : VG.Core.Color( 181, 181, 181 ),
BackColor : VG.Core.Color( 123, 123, 123 ),
TextColor : VG.Core.Color( 255, 255, 255 ),
BorderSize : VG.Core.Size( 11, 15 ),
};
this.TreeWidget={
Header : {
Height : 22,
ContentColumns: true,
BorderColor : VG.Core.Color( 82, 82, 82 ),
BackColor1 : VG.Core.Color( 134, 134, 134 ),
BackColor2 : VG.Core.Color( 118, 118, 118 ),
TextColor : VG.Core.Color( 236, 239, 243 ),
},
Font : VG.Font.Font( "Open Sans Semibold", 13 ),
TextColor : VG.Core.Color( 85, 81, 85 ),
FocusBorderColor : VG.Core.Color( 207, 128, 231 ),
BorderColor : VG.Core.Color( 107, 107, 107 ),
HoverBorderColor : VG.Core.Color( 122, 122, 122 ),
BackColor : VG.Core.Color( 82, 82, 82 ),
Spacing : 3,
Margin : VG.Core.Margin( 2, 2, 2, 2 ),
UseTriangles: false,
HasBorder: true,
ItemOutline: true,
ItemBackColor : VG.Core.Color( 177, 177, 177 ),
ItemSelectedBorderColor : VG.Core.Color( 207, 128, 231 ),
ItemSelectedBackColor : VG.Core.Color( 194, 135, 212 ),
ToolLayoutHeight : 28,
ToolTopBorderColor : VG.Core.Color( 155, 155, 155 ),
ToolBottomBorderColor : VG.Core.Color( 89, 89, 89 ),
ToolBackGradColor1 : VG.Core.Color( 139, 139, 139 ),
ToolBackGradColor2 : VG.Core.Color( 105, 105, 105 ),
ChildIndent : 20,
ChildControlColor : VG.Core.Color( 227, 227, 227 ),
};
this.Window={
HeaderHeight : 25,
HeaderFont : VG.Font.Font( "Open Sans Semibold", 14 ),
HeaderTextColor : VG.Core.Color( 255, 255, 255 ),
BackColor : VG.Core.Color( 82, 82, 82 ),
BorderColor1 : VG.Core.Color( 147, 147, 147 ),
BorderColor2 : VG.Core.Color( 197, 197, 197 ),
HeaderBackGradColor1 : VG.Core.Color( 156, 156, 156 ),
HeaderBackGradColor2 : VG.Core.Color( 143, 143, 143 ),
};
this.RoundedWindow={
HeaderHeight : 20,
FooterHeight : 15,
HeaderFont : VG.Font.Font( "Open Sans Semibold", 14 ),
HeaderTextColor : VG.Core.Color( 255, 255, 255 ),
BackColor : VG.Core.Color( 116, 116, 116 ),
BorderColor1 : VG.Core.Color( 182, 182, 182 ),
BorderColor2 : VG.Core.Color( 130, 130, 130 ),
SepColor1 : VG.Core.Color( 148, 148, 148 ),
SepColor2 : VG.Core.Color( 102, 102, 102 ),
};
// --- TEMPORARY, TABLEWIDGET HAS TO BE REMOVED
this.TableWidget = {
Font : VG.Font.Font( "Roboto Regular", 14 ),
TextColor : VG.Core.Color( 244, 244, 244 ),
DisabledSeparatorColor : VG.Core.Color( 48, 48, 48 ),
SelectionColor : VG.Core.Color( 44, 55, 71 ),
SeparatorWidth : 1,
ContentMargin : VG.Core.Margin( 0, 0, 0, 6 ),
RowHeight : 28,
Header : {
Font : VG.Font.Font( "Roboto Regular", 13 ),
SeparatorHeight : 3,
SeparatorColor : VG.Core.Color( 117, 117, 117 ),
Height : 23,
BorderColor : VG.Core.Color( 117, 117, 117 ),
GradientColor1 : VG.Core.Color( 169, 169, 169 ),
GradientColor2 : VG.Core.Color( 148, 148, 148 ),
TextXOffset : 10,
},
Footer : {
SeparatorHeight : 16,
Margin : VG.Core.Margin( 10, 0, 0, 0 ),
Height : 24,
},
Item : {
BorderColor : VG.Core.Color( 216, 216, 216 ),
SelectedBorderColor : VG.Core.Color( 186, 223, 248 ),
GradientColor1 : VG.Core.Color( 183, 183, 183 ),
GradientColor2 : VG.Core.Color( 186, 186, 186 ),
BottomColor : VG.Core.Color( 186, 186, 186 ),
SelectedGradientColor1 : VG.Core.Color( 128, 196, 242 ),
SelectedGradientColor2 : VG.Core.Color( 132, 198, 241 ),
SelectedBottomColor : VG.Core.Color( 132, 198, 241 ),
XMargin : 2,
Spacing : 2,
},
};
// ---
};
VG.UI.VisualGraphicsDarkGraySkin.prototype.activate=function()
{
this.prefix=this.style.prefix + "darkgray_";
this.fallbackPrefix=this.style.prefix + "gray_";
var path=this.style.path + "/" + this.path;
VG.loadStyleImage( path, this.prefix + "checkbox_focus.png" );
VG.loadStyleImage( path, this.prefix + "checkbox_focus_checked.png" );
// VG.loadStyleImage( path, this.prefix + "slider_focus.png" );
};
VG.UI.stylePool.getStyleByName( "Visual Graphics" ).addSkin( new VG.UI.VisualGraphicsDarkGraySkin() ); |
module.exports = {
entry: ['./src/index.js'],
output: {
path: __dirname,
publicPath: '/',
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
resolve: {
extensions: ['.js', '.jsx']
}
}
|
const path = require('path');
const logger = require('./logger');
const addMetadata = (res, filepath) => {
if (res.constructor === Array) {
return res.map(item => {
item.file = filepath;
return item;
});
} else {
res.file = filepath;
return res;
}
};
module.exports = {
import: (filePath, { strict = false } = {}) => {
try {
const fileContents = require(path.join(process.cwd(), filePath));
let data = typeof fileContents === 'string' ? JSON.parse(fileContents) : fileContents;
data = addMetadata(data, filePath);
return data;
} catch (err) {
logger.error(`Failed to parse "${filePath}"`);
if (strict) {
throw err;
}
}
},
clearCache: filePath => {
delete require.cache[require.resolve(path.join(process.cwd(), filePath))];
}
};
|
import React from 'react';
import PropTypes from 'prop-types';
import GlobalContextProvider from './src/utils/GlobalContextProvider';
export const wrapRootElement = ({ element }) => (
<GlobalContextProvider>{element}</GlobalContextProvider>
);
wrapRootElement.propTypes = {
element: PropTypes.node,
};
|
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const passport = require('passport');
const config = require('../config');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const jwtOptions = {
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Bearer'),
secretOrKey: config.jwt.secret
};
const register = () => {
passport.use(new JwtStrategy(jwtOptions, (payload, done) => {
User.findById(payload.id, (err, user) => {
if (err || !user)
return done(err, false);
if (user)
return done(null, user);
});
}));
};
const generateToken = (userId, cb) => {
jwt.sign({
id: userId
}, config.jwt.secret, {}, cb.bind(null, null));
};
const getToken = (user, password, cb) => {
User.findOne({
name: user
}, (err, user) => {
if(err)
return cb(err, null);
if(user && user.authenticate(password)) {
return generateToken(user.id, cb);
}
cb(new Error('User doesn\'t exists or password is wrong'));
});
};
module.exports = {
register,
getToken
};
|
/**
* @fileOverview Mosaiqy for jQuery
* @version 1.0.1
* @author Fabrizio Calderan, http://www.fabriziocalderan.it/mosaiqy
*
* Released under license Creative Commons, Attribution-NoDerivs 3.0
* (CC BY-ND 3.0) available at http://creativecommons.org/licenses/by-nd/3.0/
* Read the license carefully before using this plugin.
*
* Docs generation: java -jar jsrun.jar app/run.js -a -p -t=templates/couchjs ../lib/<libname>.js
*/
(function($) {
"use strict";
var
/**
* This function enable logging where available on dev version.
* If console object is undefined then log messages fail silently
* @function
*/
appDebug = function() {
var args = Array.prototype.slice.call(arguments),
func = args[0];
if (typeof console !== 'undefined') {
if (typeof console[func] === 'function') {
console[func].apply(console, args.slice(1));
}
}
},
/**
* @function
* @param { String } ua Current user agent specific string
* @param { String } prop The property we want to check
*
* @returns { Object }
* <pre>
* isEnabled : True if acceleration is available, false otherwise;
* transitionEnd : Event available on current browser;
* duration : Vendor specific CSS property.
* </pre>
*
* @description
* Detect if GPU acceleration is enabled for transitions.
* code gist mantained at https://gist.github.com/892739
*/
GPUAcceleration = (function(ua, prop) {
var div = document.createElement('div'),
cssProp = function(p) {
return p.replace(/([A-Z])/g, function(match, upper) {
return "-" + upper.toLowerCase();
});
},
vendorProp,
uaList = {
msie : 'MsTransition',
opera : 'OTransition',
mozilla : 'MozTransition',
webkit : 'WebkitTransition'
};
for (var b in uaList) {
if (uaList.hasOwnProperty(b)) {
if (ua[b]) { vendorProp = uaList[b]; }
}
}
return {
isEnabled : (function(s) {
return !!(s[prop] || vendorProp in s || (ua.opera && parseFloat(ua.version) > 10.49));
}(div.style)),
transitionEnd : (function() {
return (ua.opera)
? 'oTransitionEnd'
: (ua.webkit)? 'webkitTransitionEnd' : 'transitionend';
}()),
duration : cssProp(vendorProp) + '-duration'
};
}($.browser, 'transition')),
/**
* @function
* @description
* This algorithm is described in http://en.wikipedia.org/wiki/Knuth_shuffle
* The main purpose is to ensure an equally-distributed animation sequence, so
* every entry point can have the same probability to be chosen without
* duplicates.
*
* @returns { Array } A shuffled array of entry points.
*/
shuffledFisherYates = function(len) {
var i, j, tmp_i, tmp_j, shuffled = [];
i = len;
for (j = 0; j < i; j++) { shuffled[j] = j; }
while (--i) {
/*
* [~~] is the bitwise op quickest equivalent to Math.floor()
* http://jsperf.com/bitwise-not-not-vs-math-floor
*/
j = ~~(Math.random() * (i+1));
tmp_i = shuffled[i];
tmp_j = shuffled[j];
shuffled[i] = tmp_j;
shuffled[j] = tmp_i;
}
return shuffled;
},
/**
* @class
* @final
* @name Mosaiqy
* @returns public methods of Mosaiqy object for its instances.
*/
Mosaiqy = function($) {
var _s = {
animationDelay : 3000,
animationSpeed : 800,
avoidDuplicates : false,
cols : 2,
fadeSpeed : 750,
indexData : 0,
loadTimeout : 7500,
loop : true,
onCloseZoom : null,
onOpenZoom : null,
openZoom : true,
rows : 2,
scrollZoom : true,
template : ''
},
_cnt, _ul, _li, _image,
_points = [],
_entryPoints = [],
_tplCache = {},
_animationPaused = false,
_animationRunning = false,
_thumbSize = {},
_page = ($.browser.opera)? $("html") : $("html,body"),
_intvAnimation,
/**
* @private
* @name Mosaiqy#_createTemplate
* @param { Number } index The index of JSON data array
* @description
*
* The method merges the user-defined template with JSON data associated
* for a given index and it's called both at initialization and at every
* animation loop.
*
* @returns { jQuery } HTML Nodes to inject into the document
*/
_createTemplate = function(index) {
var tpl = '';
if (typeof _tplCache[index] === 'undefined') {
_tplCache[index] = _s.template.replace(/\$\{([^\}]+)\}/gm, function(data, key) {
/**
* if key has one or more dot then a nested key has been requested
* and a while loop goes in-depth over the JSON
*/
var value = (function() {
var par = key.split('.'), len = 0, val;
if (par.length) {
val = _s.data[index];
par = par.reverse();
len = par.length;
while (len--) { val = val[par[len]] || { }; }
return (typeof val === "string")? val : '';
}
return _s.data[index][key];
}());
if (typeof value === 'undefined') {
return key;
}
return value;
});
}
tpl = _tplCache[index];
if (typeof window.innerShiv === 'function') {
tpl = window.innerShiv(tpl, false);
}
return $(tpl);
},
/**
* @private
* @name Mosaiqy#_setInitialImageCoords
* @description
*
* Sets initial offset (x and y position) of each list items and the width
* and min-height of the container. It doesn't set the height property
* so the wrapper can strecth when a zoom image has been requested or closed.
*/
_setInitialImageCoords = function() {
var li = _li.eq(0);
_thumbSize = { w : li.outerWidth(true), h : li.outerHeight(true) };
/**
* defining li X,Y offset
* [~~] is the bitwise op quickest equivalent to Math.floor()
* http://jsperf.com/bitwise-not-not-vs-math-floor
*/
_li.each(function(i, el) {
$(el).css({
top : _thumbSize.h * (~~(i/_s.cols)),
left : _thumbSize.w * (i%_s.cols)
});
});
/* defining container size */
_ul.css({
minHeight : _thumbSize.h * _s.rows,
width : _thumbSize.w * _s.cols
});
_cnt.css({
minHeight : _thumbSize.h * _s.rows,
width : _thumbSize.w * _s.cols
});
},
/**
* @private
* @name Mosaiqy#_getPoints
* @description
*
* _getPoints object stores 4 information
* <ol>
* <li>The direction of movement (css property)</li>
* <li>The selection of nodes to move (i.e in a 3x4 grid, point 4 and 5 have
* to move images 2,6,10)</li>
* <li>The position in which we want to inject-before the new element (except
* for the last element which needs to be injected after)</li>
* <li>The position (top and left properties) of entry tile</li>
* </ol>
*
* <code><pre>
* [0,8,1,9,2,10,3,11, 0,4,4,8,8,12*] * = append after
*
* 0 2 4 6
* 8 |_0_|_1_|_2_|_3_| 9
* 10 |_4_|_5_|_6_|_7_| 11
* 12 |_8_|_9_|_10|_11| 13
* 1 3 5 7
* </pre></code>
*
* <p>
* In earlier versions of this algorithm, the order of nodes was counterclockwise
* (tlbr) and then alternating (tblr). Now this enumeration pattern (alternating
* tb and lr) performs a couple of improvements on code logic and on readability:
* </p>
*
* <ol>
* <li>Given an even-indexed node, the next adjacent index has the same selector:<br />
* e.g. points[8] = li:nth-child(n+1):nth-child(-n+4) [0123]<br />
* points[9] = li:nth-child(n+1):nth-child(-n+4) [0123]<br />
* (it's easier to retrieve this information)</li>
* <li>If a random point is even (i & 1 === 0) then the 'direction' property of node
* selection is going to be increased during slide animation. Otherwise is going
* to be decreased and then we remove first or last element (if random number is 9,
* then the collection has to be [3210] and not [0123], since we always remove the
* disappeared node when the animation has completed.)</li>
* </ol>
*
* @example
* Another Example (4x2)
* [0,6,1,7, 0,2,2,4,4,6,6,8*] * = append after
*
* 0 2
* 4 |_0_|_1_| 5
* 6 |_2_|_3_| 7
* 8 |_4_|_5_| 9
* 10 |_6_|_7_| 11
* 1 3
*/
_getPoints = function() {
var c, n, s, /* internal counters */
selectors = {
col : "li:nth-child($0n+$1)",
row : "li:nth-child(n+$0):nth-child(-n+$1)"
};
/* cols information */
for (n = 0; n < _s.cols; n = n + 1) {
s = selectors.col.replace(/\$(\d)/g, function(selector, i) {
return [_s.cols, n + 1][i]; });
_points.push({ prop: 'top', selector : s, node : n,
position : {
top : -(_thumbSize.h),
left : _thumbSize.w * n
}
});
_points.push({ prop: 'top', selector : s, node : _s.cols * (_s.rows - 1) + n,
position : {
top : _thumbSize.h * _s.rows,
left : _thumbSize.w * n
}
});
}
/* rows information */
for (c = 0, n = 0; n < _s.rows; n = n + 1) {
s = selectors.row.replace(/\$(\d)/g, function(selector, i) {
return [c + 1, c + _s.cols][i]; });
_points.push({ prop: 'left', selector : s, node : c,
position : {
top : _thumbSize.h * n,
left : -(_thumbSize.w)
}
});
_points.push({ prop: 'left', selector : s, node : c += _s.cols,
position : {
top : _thumbSize.h * n,
left : _thumbSize.w * _s.cols
}
});
}
_points[_points.length - 1].node -= 1;
appDebug("groupCollapsed", 'points information');
appDebug(($.browser.mozilla)?"table":"dir", _points);
appDebug("groupEnd");
},
/**
* @private
* @name Mosaiqy#_animateSelection
* @return a deferred promise
* @description
*
* This method runs the animation.
*/
_animateSelection = function() {
var rnd, tpl, referral, node, animatedSelection, isEven,
dfd = $.Deferred();
appDebug("groupCollapsed", 'call animate()');
appDebug("info", 'Dataindex is', _s.indexData);
/**
* Get the entry point from shuffled array
*/
rnd = _entryPoints.pop();
isEven = ((rnd & 1) === 0);
animatedSelection = _cnt.find(_points[rnd].selector);
/**
* append new «li» element
* if the random entry point is the last one then we append the
* new node after the last «li», otherwise we place it before.
*/
referral = _li.eq(_points[rnd].node);
node = (rnd < _points.length - 1)?
$('<li />').insertBefore(referral)
: $('<li />').insertAfter(referral);
node.data('mosaiqy-index', _s.indexData);
/**
* Generate template to append with user data
*/
tpl = _createTemplate(_s.indexData);
tpl.appendTo(node.css(_points[rnd].position));
appDebug("info", "Random position is %d and its referral is node", rnd, referral);
/**
* Looking for images inside template fragment, wait the deferred
* execution and checking a promise status.
*/
$.when(node.find('image').mosaiqyImagesLoad(_s.loadTimeout))
/**
* No image/s can be loaded, remove the node inserted, then call
* again the _animate method
*/
.fail(function() {
appDebug("warn", 'Skip dataindex %d, call _animate()', _s.indexData);
appDebug("groupEnd");
node.remove();
dfd.reject();
})
/**
* Image/s inside template fragment have been successfully loaded so
* we can apply the slide transition on the selected nodes and the
* added node
*/
.done(function() {
var prop = _points[rnd].prop,
amount = (prop === 'left')? _thumbSize.w : _thumbSize.h,
/**
* @ignore
* add new node into animatedNodes collection and change
* previous collection
*/
animatedNodes = animatedSelection.add(node),
animatedQueue = animatedNodes.length,
move = {};
move[prop] = '+=' + (isEven? amount : -amount) + 'px';
appDebug("log", 'Animated Nodes:', animatedNodes);
/**
* $.animate() function has been extended to support css transition
* on modern browser. For this reason I cannot use deferred animation,
* because if GPUacceleration is enabled the code will not use native
* animation.
*
* See code below
*/
animatedNodes.animate(move , _s.animationSpeed,
function() {
var len;
if (--animatedQueue) { return; }
/**
* Opposite node removal. "Opposite" is related on sliding direction
* e.g. on 2->[159] (down) opposite has index 9
* on 3->[159] (up) opposite has index 1
*/
if (isEven) {
animatedSelection.last().remove();
}
else {
animatedSelection.first().remove();
}
appDebug("log", 'Animated Selection:', animatedSelection);
animatedSelection = (isEven)
? animatedSelection.slice(0, animatedSelection.length - 1)
: animatedSelection.slice(1, animatedSelection.length);
appDebug("log", 'Animated Selection:', animatedSelection);
/**
* <p>Node rearrangement when animation affects a column. In this case
* a shift must change order inside «li» collection, otherwise the
* subsequent node selection won't be properly calculated.
* Algorithm is quite simple:</p>
*
* <ol>
* <li>The offset displacement of shifted nodes is always
* determined by the number of columns except when shift direction is
* bottom-up: in fact the last node of animatedSelection collection
* represents an exception because its position is affected by the
* presence of the new node (placed just before it);</li>
* <li>offset is negative on odd entry point (down and right) and
* positive otherwise (top and left);</li>
* <li>at each iteration we retrieve the current «li» nodes in the
* grid so we can work with actual node position.</li>
* </ol>
*
* <p>If the animation affected a row, rearrangement of nodes is not needed
* at all because insertion is sequential, thus the new node and shifted
* nodes already have the right index.</p>
*/
if (prop === 'top') {
len = animatedSelection.length;
animatedSelection.each(function(i) {
var node, curpos, offset, newpos;
/**
* @ignore
* Retrieve node after each new insertion and rearrangement
* of selected animating nodes
*/
_li = _cnt.find("li:not(.mosaiqy-zoom)");
node = $(this);
curpos = _li.index(node);
offset = (isEven) ? _s.cols : -(_s.cols - ((1 === len - i)? 0 : 1));
if (!!offset) {
newpos = curpos + offset;
if (newpos < _li.length) {
node.insertBefore(_li.eq(newpos));
}
else {
node.appendTo(_ul);
}
}
});
}
appDebug("groupEnd");
dfd.resolve();
}
);
});
return dfd.promise();
},
/**
* @private
* @name Mosaiqy#_animationCycle
* @description
*
* <p>The method runs the animation and check some private variables to
* allow cycle and animation execution. Every time the animation has
* completed successfully, the JSON index and node collection are updated.</p>
*
* <p>Animation interval is not executed on mouse enter (_animationPaused)
* or when animation is still running.</p>
*/
_animationCycle = function() {
if (!_animationPaused && !_animationRunning) {
_animationRunning = true;
if (_entryPoints.length === 0) {
_entryPoints = shuffledFisherYates(_points.length);
appDebug("info", 'New entry point shuffled array', _entryPoints);
}
appDebug("info", 'Animate selection');
_incrementIndexData();
$.when(_animateSelection())
/**
* In all cases dataIndex is increased and the animationRunning
* state is set to false so animation could continue.
*/
.then(function() {
_s.indexData = _s.indexData + 1;
_animationRunning = false;
appDebug("info", 'End animate selection');
})
/**
* If a thumbnail was not loaded within the defined limit then animation
* should not wait another delay. We call soon the method again.
*/
.fail(function() {
_animationCycle();
})
/**
* Thumbnail was loaded. Update the reference of list-items (changed)
* on stage and call the method again after timeout.
*/
.done(function() {
_li = _ul.find('li:not(.mosaiqy-zoom)');
_intvAnimation = setTimeout(function() {
_animationCycle();
}, _s.animationDelay);
});
}
else {
_intvAnimation = setTimeout(function() {
_animationCycle();
}, _s.animationDelay * 2);
}
},
/**
* @private
* @name Mosaiqy#_pauseAnimation
* @description
*
* Set private _animationPaused to true so the animation cycle can run
* (unless a zoom is currently opened).
*/
_pauseAnimation = function() {
_animationPaused = true;
},
/**
* @private
* @name Mosaiqy#_playAnimation
* @description
*
* Set private _animationPaused to false so the animation cycle can stop.
*/
_playAnimation = function() {
_animationPaused = false;
},
/**
* @private
* @name Mosaiqy#_incrementIndexData
* @description
*
* <p>The main purpose is to correctly increment the indexData for the JSON
* data retrieval. If user choosed "avoidDuplicate" option, then the method
* checks if a requested image is already on stage. If so, a loop starts
* looking for the first image not in stage, increasing the dataIndex.</p>
*/
_incrementIndexData = function() {
var safe = _s.data.length,
stage = [];
if (_s.indexData === _s.data.length) {
if (!_s.loop) {
return _pauseAnimation();
}
else {
_s.indexData = 0;
}
}
if (_s.avoidDuplicates) {
appDebug('info', "Avoid Duplicates");
_li.each(function() {
var i = $(this).data('mosaiqy-index');
stage[i] = i;
});
appDebug('info', "Now on stage: ", stage);
while (safe--) {
if (typeof stage[_s.indexData] !== 'undefined') {
appDebug('info', "%d already exist (skip)", _s.indexData)
_s.indexData = _s.indexData + 1;
if (_s.indexData === _s.data.length) {
if (!_s.loop) {
return _pauseAnimation();
}
else {
_s.indexData = 0;
}
}
continue;
}
appDebug('info', "%d not in stage (ok)", _s.indexData);
break;
}
}
},
/**
* @private
* @name Mosaiqy#_setNodeZoomEvent
* @description
*
* <p>This method manages the zoom main events by some scoped internal functions.</p>
*
* <p><code>closeZoom</code> is called when user clicks on "Close" button over a zoom
* image or when another thumbanail is choosed and another zoom is currently opened.
* The function stops all running transitions (if any) and it closes the zoom container
* while changing opacity of some elements (close button, image caption). At the end of
* animation it removes some internal classes and the «li» node that contained the zoom.</p>
*
* <p>The function <code>closeZoom</code> returns a deferred promise object, so it can be
* called in a synchronous code queue inside other functions, ensuring all operation have
* been successfully completed.</p>
*
* <p><code>viewZoom</code> is called when the previous function <code>createZoom</code>
* successfully created the zoom container into the DOM. The function creates the zoom image
* and the closing button binding the click event. If image is not in cache the zoom is opened
* with a slideDown effect with a waiting loader.</p>
*
* <p><code>createZoom</code> calls the <code>closeZoom</code> function (if any zoom images
* are currently opened) then creates the zoom container into the DOM and then scroll the page
* until the upper bound of the thumbnail choosed has reached (unless scrollzoom option is set to
* false). When scrolling effect has completed then <code>viewZoom</code> function is called.</p>
*/
_setNodeZoomEvent = function(node) {
var nodezoom, $this, i, zoomRunning,
zoomFigure, zoomCaption, zoomCloseBtt,
pagePos, thumbPos, diffPos;
function closeZoom() {
var dfd = $.Deferred();
if ((nodezoom || { }).length) {
appDebug("log", 'closing previous zoom');
zoomCaption.stop(true)._animate({ opacity: '0' }, _s.fadeSpeed / 4);
zoomCloseBtt.stop(true)._animate({ opacity: '0' }, _s.fadeSpeed / 2);
_li.removeClass('zoom');
$.when(nodezoom.stop(true)._animate({ height : '0' }, _s.fadeSpeed))
.then(function() {
nodezoom.remove();
nodezoom = null;
appDebug("log", 'zoom has been removed');
if (typeof _s.onCloseZoom === 'function') {
_s.onCloseZoom($this);
}
dfd.resolve();
});
}
else {
dfd.resolve();
}
return dfd.promise();
}
function viewZoom() {
var zoomImage, imageDesc, zoomHeight;
appDebug("log", 'viewing zoom');
zoomFigure = nodezoom.find('figure');
zoomCaption = nodezoom.find('figcaption');
zoomImage = $('<image class="mosaiqy-zoom-image" />').attr({
src : $this.find('a').attr('href')
});
zoomImage.appendTo(zoomFigure);
if (zoomImage.get(0).height === 0) {
zoomImage.hide();
}
zoomHeight = (!!zoomImage.get(0).complete)? zoomImage.height() : 200;
nodezoom._animate({ height : zoomHeight + 'px' }, _s.fadeSpeed, function() {
if (typeof _s.onOpenZoom === 'function') {
_s.onOpenZoom($this);
}
});
imageDesc = $this.find('image').prop('longDesc');
if (!!imageDesc) {
zoomImage.wrap($('<a />').attr({
href : imageDesc,
target : "new"
}));
}
/**
* Append Close Button
*/
zoomCloseBtt = $('<a class="mosaiqy-zoom-close">Close</a>').attr({
href : "#"
})
.bind("click.mosaiqy", function(evt) {
$.when(closeZoom()).then(function() {
_cnt.removeClass('zoom');
zoomRunning = false;
_playAnimation();
});
evt.preventDefault();
})
.appendTo(zoomFigure);
$.when(zoomImage.mosaiqyImagesLoad(
_s.loadTimeout,
function(image) {
setTimeout(function() {
var fadeZoom = (!!zoomImage.get(0).height)? _s.fadeSpeed : 0;
image.fadeIn(fadeZoom, function() {
zoomCloseBtt._animate({ opacity: '1' }, _s.fadeSpeed / 2);
zoomCaption.html($this.find('figcaption').html())._animate({ opacity: '1' }, _s.fadeSpeed);
});
}, _s.fadeSpeed / 1.2);
})
)
.done(function() {
appDebug("log", 'zoom ready');
if (zoomHeight < zoomImage.height()) {
nodezoom._animate({ height : zoomImage.height() + 'px' }, _s.fadeSpeed);
}
})
.fail(function() {
appDebug("warn", 'cannot load ', $this.find('a').attr('href'));
zoomCloseBtt.trigger("click.mosaiqy");
});
}
function createZoom(previousClose) {
appDebug("log", 'opening zoom');
zoomRunning = true;
$.when(previousClose())
.done(function() {
var timeToScroll;
_cnt.addClass('zoom');
$this.addClass('zoom');
_li = _cnt.find('li:not(.mosaiqy-zoom)');
/**
* webkit bug: http://code.google.com/p/chromium/issues/detail?id=2891
*/
thumbPos = $this.offset().top;
pagePos = (document.body.scrollTop !== 0)
? document.body.scrollTop
: document.documentElement.scrollTop;
if (_s.scrollZoom) {
diffPos = Math.abs(pagePos - thumbPos);
timeToScroll = (diffPos > 0) ? ((diffPos * 1.5) + 400) : 0;
}
else {
thumbPos = pagePos;
timeToScroll = 0;
}
/**
* need to create the zoom node then append it and then open it. When using
* HTML5 elements we need the innerShiv function available.
*/
nodezoom = '<li class="mosaiqy-zoom"><figure><figcaption></figcaption></figure></li>';
nodezoom = (typeof window.innerShiv === 'function')
? $(innerShiv(nodezoom, false))
: $(nodezoom);
if (i < _li.length) {
nodezoom.insertBefore(_li.eq(i));
}
else {
nodezoom.appendTo(_ul);
}
$.when(_page.stop()._animate({ scrollTop: thumbPos }, timeToScroll))
.done(function() {
zoomRunning = false;
viewZoom();
});
});
}
/**
* Set the click event handler on thumbnails («li» nodes). Since nodes are removed and
* injected at every animation cycle, the live() method is needed.
*/
node.live('click.mosaiqy', function(evt) {
if (!_animationRunning && !zoomRunning) {
/**
* find the index of «li» selected, then retrieve the element placeholder
* to append the zoom node.
_pauseAnimation();*/
$this = $(this);
i = _s.cols * (Math.ceil((_li.index($this) + 1) / _s.cols));
/**
* Don't click twice on the same zoom
*/
if (!!_s.openZoom) {
if (!$this.hasClass('zoom')) {
evt.preventDefault();
createZoom(closeZoom);
}
}
}
else {
evt.preventDefault();
}
});
},
/**
* @private
* @name Mosaiqy#_loadThumbsFromJSON
* @param { Number } missingThumbs How many thumbs miss on the stage
* @description
* If user have not defined enough images (rows * cols) as straight markup, this method
* fill the stage with images taken from the JSON.
*/
_loadThumbsFromJSON = function(missingThumbs) {
var tpl;
while (missingThumbs--) {
tpl = _createTemplate(_s.indexData);
tpl.appendTo($('<li />').appendTo(_ul));
_s.indexData = _s.indexData + 1;
}
};
/**
* @scope Mosaiqy
*/
return {
/**
* @public
* @function init
*
* @param { String } cnt Mosaiqy node container
* @param { String } options User options for settings merge.
* @return { Object } Mosaiqy object instance
*/
init : function(cnt, options) {
var imageToComplete = 0;
_s = $.extend(_s, options);
/* Data must not be empty */
if (!((_s.data || []).length)) {
throw new Error("Data object is empty");
}
/* Template must not be empty and provided as a script element */
if (!!_s.template && $("#" + _s.template).is('script')) {
_s.template = $("#" +_s.template).text() || $("#" +_s.template).html();
}
else {
throw new Error("User template is not defined");
}
_cnt = cnt;
_ul = cnt.find('ul');
_li = cnt.find('li:not(.mosaiqy-zoom)');
/**
* If thumbnails on markup are less than (cols * rows) we retrieve
* the missing images from the json, and we create the templates
*/
imageToComplete = (_s.cols * _s.rows) - _li.length;
if (imageToComplete) {
if (_s.data.length >= imageToComplete) {
_s.indexData = _li.length;
appDebug('warn', "Missing %d image/s. Load from JSON", imageToComplete);
_loadThumbsFromJSON(imageToComplete);
_li = cnt.find('li:not(.mosaiqy-zoom)');
}
else {
throw new Error("Mosaiqy can't find missing images on JSON data.");
}
}
/**
* Set a data attribute on each node (if not defined) so user can
* choose avoidDuplicate option
*/
if (_s.avoidDuplicates) {
_li.each(function(i) {
var $this = $(this);
if (typeof $this.data('mosaiqy-index') === 'undefined') {
$(this).data('mosaiqy-index', i);
}
});
}
_image = cnt.find('image');
/* define image position and retrieve entry points */
_setInitialImageCoords();
_getPoints();
/* set mouseenter event on container
_cnt
.delegate("ul", "mouseenter.mosaiqy", function() {
_pauseAnimation();
})
.delegate("ul", "mouseleave.mosaiqy", function() {
if (!_cnt.hasClass('zoom')) {
_playAnimation();
}
});*/
$.when(_image.mosaiqyImagesLoad(_s.loadTimeout, function(image) { image.animate({ opacity : '1' }, _s.fadeSpeed); }))
/**
* All images have been successfully loaded
*/
.done(function() {
appDebug("info", 'All images have been successfully loaded');
_cnt.removeClass('loading');
_setNodeZoomEvent(_li);
_intvAnimation = setTimeout(function() {
_animationCycle();
}, _s.animationDelay);
})
/**
* One or more image have not been loaded
*/
.fail(function() {
appDebug("warn", 'One or more image have not been loaded');
return false;
});
return this;
}
};
},
/**
* @name _$.fn
* @description
*
* Some chained methods are needed internally but it's better avoid jQuery.fn
* unnecessary pollution. Only mosaiqy plugin/function is exposed as jQuery
* prototype.
*/
_$ = $.sub();
/**
* @lends _$.fn
*/
_$.fn.mosaiqyImagesLoad = function(to, imageCallback) {
var dfd = $.Deferred(),
imageLength = this.length,
loaded = [],
failed = [],
timeout = to || 8419.78;
/* waiting about 8 seconds before discarding image */
appDebug("groupCollapsed", 'Start deferred load of %d image/s:', imageLength);
if (imageLength) {
this.each(function() {
var i = this;
/* single image deferred execution */
$.when(
(function asyncImageLoader() {
var
/**
* @ignore
* This interval bounds the maximum amount of time (e.g. network
* excessive latency or failure, 404) before triggering the error
* handler for a given image. The interval is then unset when
* the image has loaded or if error event has been triggered.
*/
imageDfd = $.Deferred(),
intv = setTimeout(function() { $(i).trigger('error.mosaiqy'); }, timeout);
/* single image main events */
$(i).one('load.mosaiqy', function() {
clearInterval(intv);
imageDfd.resolve();
})
.bind('error.mosaiqy', function() {
clearInterval(intv);
imageDfd.reject();
}).attr('src', i.src);
if (i.complete) { setTimeout(function() { $(i).trigger('load.mosaiqy'); }, 10); }
return imageDfd.promise();
}())
)
.done(function() {
loaded.push(i.src);
appDebug("log", 'Loaded', i.src);
if (imageCallback) { imageCallback($(i)); }
})
.fail(function() {
failed.push(i.src);
appDebug("warn", 'Not loaded', i.src);
})
.always(function() {
imageLength = imageLength - 1;
if (imageLength === 0) {
appDebug("groupEnd");
if (failed.length) {
dfd.reject();
}
else {
dfd.resolve();
}
}
});
});
}
return dfd.promise();
};
/**
* @ignore
* @lends _$.fn
* Extends jQuery animation to support CSS3 animation if available.
*/
_$.fn.extend({
_animate : $.fn.animate,
animate : function(props, speed, easing, callback) {
var options = (speed && typeof speed === "object")
? $.extend({}, speed)
: {
duration : speed,
complete : callback || !callback && easing || $.isFunction(speed) && speed,
easing : callback && easing || easing && !$.isFunction(easing) && easing
};
return $(this).each(function() {
var $this = _$(this),
pos = $this.position(),
cssprops = { },
match;
if (GPUAcceleration.isEnabled) {
appDebug("info", 'GPU Animation' );
/**
* If a value is specified as a relative delta (e.g. '+=200px') for
* left or top property, we need to sum the current left (or top)
* position with delta.
*/
if (typeof props === 'object') {
for (var p in props) {
if (p === 'left' || p === 'top') {
match = props[p].match(/^(?:\+|\-)=(\-?\d+)/);
if (match && match.length) {
cssprops[p] = pos[p] + parseInt(match[1], 10);
}
}
}
}
$this.bind(GPUAcceleration.transitionEnd, function() {
if ($.isFunction(options.complete)) {
options.complete();
}
})
.css(cssprops)
.css(GPUAcceleration.duration, (speed / 1000) + 's');
}
else {
appDebug("info", 'jQuery Animation' );
$this._animate(props, options);
}
});
}
});
/**
* @lends jQuery.prototype
*/
$.fn.mosaiqy = function(options) {
if (this.length) {
return this.each(function() {
var obj = new Mosaiqy(_$);
obj.init(_$(this), options);
$.data(this, 'mosaiqy', obj);
});
}
};
}(jQuery)); |
(function(){
var field = document.getElementById('email'),
submit = document.getElementById('subscribe'),
defaultValue = field.title;
field.onfocus = function(){
if (field.value === defaultValue) {
field.value = '';
}
};
field.onblur = function(){
if (!field.value) {
field.value = defaultValue;
}
};
field.onblur();
submit.onclick = function(){
this.blur();
return !!field.value && field.value !== defaultValue;
};
})(); |
describe('Controller: Locations', function () {
'use strict';
var scope;
var controller;
var dataFactory, stateFactory, apiFactory;
beforeEach(module('AQ'));
beforeEach(inject(function ($rootScope, $controller, data, state, api) {
scope = $rootScope.$new();
dataFactory = data;
stateFactory = state;
apiFactory = api;
spyOn(stateFactory, 'setTitle').and.callFake(function () {
return;
});
spyOn(apiFactory, 'getLocations').and.callFake(function () {
return;
});
controller = $controller;
}));
it('should set title', function () {
controller('LocationsController', {
$scope: scope
});
scope.$digest();
expect(stateFactory.setTitle).toHaveBeenCalledWith('Locations');
});
it('should get locations when they are not set yet', function () {
dataFactory.locations = null;
controller('LocationsController', {
$scope: scope
});
scope.$digest();
expect(apiFactory.getLocations).toHaveBeenCalled();
});
it('should not get locations when they are already set', function () {
dataFactory.locations = _.cloneDeep(locationsMock);
controller('LocationsController', {
$scope: scope
});
scope.$digest();
expect(apiFactory.getLocations).not.toHaveBeenCalled();
});
});
|
const puppeteer = require('puppeteer')
;(async() => {
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.goto('https://www.niaoyun.com/', { waitUntil: 'networkidle'})
await page.pdf({
path: './download/niaoyun.pdf',
format: 'letter'
})
await browser.close()
})()
|
var input = document.querySelector('#input')
var output = document.querySelector('#output')
var form = document.querySelector('#form')
var defaultInput = '((3 * 4) / (2 + 5)) * (3 + 4)'
input.value = localStorage.getItem('itp_input') || defaultInput
form.addEventListener('submit', function(event) {
event.preventDefault()
calculate()
})
function calculate() {
var value = input.value
var result = infixToPostfix(value)
output.innerHTML = ''
if (result) {
output.innerHTML = result
}
localStorage.setItem('itp_input', value)
}
calculate()
|
/*
* Copyright (c) 2016, Globo.com (https://github.com/globocom)
*
* License: MIT
*/
import React, { Component } from 'react';
import { Icon } from '../../../../../../components/BasicComponents';
// import insertDataBlock from '../insertDataBlock';
export default class MapButton extends Component {
// constructor(props) {
// super(props);
// this.onClick = ::this.onClick;
// }
render() {
return (
<button className={this.props.className} type="button">
<Icon className="sidemenu__button__icon" width={24} height={24} type="mapMenu" />
</button>
);
}
}
|
// Mon Sep 9 11:17:26 2019
// M. Oettinger, Marcus -at- oettinger-physics.de
//
// v 0.5 - removed jquery and jcanvas dependency
//
/**
* @file CNum.js: sketch the complex plane in a html5 canvas
* @author Marcus Oettinger
* @version 0.3.1
* @license MIT (see {@link http://opensource.org/licenses/MIT} or LICENSE).
*/
/**
* @class CNum.js
* is a javascript object plotting a representation of a number z in the complex
* plane. The idea is to set a complex value via an algebraic expression,
* transform it into different bases and draw a Gaussian plot (aka Argand
* diagram).
* Here's a [demo page]{https://MarcusOettinger.github.io/CNum.js/}.<br>
* License: [the MIT License]{http://opensource.org/licenses/MIT}.<br>
* <br><br>
* Graphics are drawn onto a html5 canvas - this should nowadays
* be supported by most browsers.<br><br>
* I wrote the code because I needed a dynamic plot of complex values in
* webpages for a a basic maths lecture. It serves a purpose and is far from
* being cleanly written, nicely formatted or similar.
*
* <br><br>
* CNum.js uses an external library:
* <ul>
* <li>[mathjs]{http://mathjs.org} (that can do much more!)</li>
* </ul>
* Creates a CNum object - the complex value is set via an algebraic expression.
* <br><br>
* Usage is quit simple: object = new CNum( expression ) creates a new complex
* number,<br>
* e.g. <b><i> z = new CNum("2+i"); </i></b>
* will create <b><i>z</i></b> with the value <b><i>2+i</i></b><br>.
* @param {string} expr a text representing a complex number. Cartesian, trigonometric and polar expressions can be used, e.g. '2+3i' or '12*exp(3i)'
* <br><br>
*/
function CNum(expr) {
// Private:
// -----------------------------------------------------------------------------
// paranoia mode: set some reasonable defaults
var _margin = 50; // margin around plot
var X_C = 100, Y_C = 100; // center coordinates
// (will be overwritten by _setScale)
var _plotW, _plotH;
var _SCALE = 10.0;
var _maxradius = 1; // (remember the value the plot was autoscaled to)
var _tickLength= 3; //
var _daCanvas = null; // the canvas to use
var _dactx = null; // the canvas context
var _TICKSCALE= 0.001;
// default options - values can be set for every number displayed
/**
* Options used to change the appearance of a plot. This set of options
* is used in all methods displaying numbers.
* @name options
* @memberOf CNum
* @function
* @param {Object} options
* @param {boolean} options.clear - set to true to remove canvas contents before drawing
* @param {boolean} options.coords - set to true to draw a coordinate system
* @param {boolean} options.Arrow draw <i><b>z</b></i> as an arrow - if set to false, draw a point. Defaults to true.
* @param {number} options.arrowAngle angle to calculate arrowhead (dfault: 45)
* @param {number} options.arrowRadius sets size of the arrowhead (default: 10)
* @param {boolean} options.circle draw a circle with radius <i><b>|z|</b></i>. Defaults to false.
* @param {boolean} options.ReIm show real and imaginary part in the plot. Default is true.
* @param {boolean} options.Ctext text to show at the position of the complex number. Set to false or null
* true to supress plotting any text, to true to display the value <i><b>z</b></i> in cartesian
* notation or a string to be displayed. Defaults to true.
* @param {boolean} options.arc show angle and value as an arc. Default is true.
* @param {boolean} options.showDegree print angles in degrees or in radians. Default is true.
* @param {number } options.decimals decimal places used in radius and angle values printed. Default: 1.
* @param {number} font Size - font size in pixel, e.g. '10', '10px'
* @param {string} fontFamily - the font family (default: "sans-serif")
* @param {string} options.color set a color to use for arrow, text, angle. Defaults to '#888'.
* @param {number} options.linewidth width of drawn lines in px, defaults to 1.
*/
var _defaults = {
// general plot options
clear: false, // clear canvas
coords: false, // draw coordinate system
// options for complex numbers
Arrow: true, // draw an arrow - if set to false, draw a point
arrowAngle: 45,
arrowRadius: 10,
circle: false, // draw a circle with radius |z|
ReIm: true, // show real and imaginary part
Ctext: true, // print z in cartesian notation
arc: true, // show angle and value as an arc
showDegree: true, // show angles in degree (otherwise radians)
decimals: 1, // decimal places used in radius and angle values
fontSize: '12px',
fontFamily: "serif",
// colors
color: "#888", // color to use for arrow, text, angle
linewidth: 1, // guess what :-)
};
// math magic miracles...
zStr = math.eval( expr ); // eval string expr to create an
// expression mathjs can handle for sure...
this.zNum = math.complex(zStr); // ... and create a complex number
this.x = math.round(this.zNum.re, 3); // store Re(z) and Im(z) for later
this.y = math.round(this.zNum.im, 3); //
this.offsetx = 0; // offset to move a vector out of (0/0)
this.offsety = 0; // - used for drawing sums
var _radius = this.zNum.toPolar().r; // find absolute value (radius)
var _a = this.zNum.toPolar().phi; // get angle phi - bummer:
this.angle = _a<0 ? 2*Math.PI+_a : _a; // mathjs treats angles > PI as negative
// - great for calculations but
// B*A*D if drawing polar plots...
this._daSettings = _defaults; // Each CNum holds its own set of options
var _numlist = []; // a list of CNums to draw on the main canvas
_count = 1; // index the number of arrows on cnv - used to display
// angles in a readable form
// calculate cartesian coordinates of a given point (x/y) on the canvas
function _XScaled(x) { return _SCALE * x; };
function _YScaled(y) { return _SCALE * y; };
function _XPos(x) { return X_C + _XScaled(x); };
function _YPos(y) { return Y_C - _YScaled(y); };
// return the sign of a number x (this ought to be fast and safe)
function sign(x) { return typeof x === 'number' ? x ? x < 0 ? -1 : 1 : x === x ? 0 : NaN : NaN; }
// return minimum in the sense of: b if b<a, a otherwise.
function min(a,b){ return b<a ? b : a ; }
// return maximum in the sense of: b if b>a, a otherwise.
function max(a,b){ return b>a ? b : a ; }
// return the largest of the an arbitrary number of arguments
function _getmaxRadius( ) {
var ret = _radius;
for (var i = 0; i < _numlist.length; i++)
ret = max( ret, (_numlist[i].GetRadius()));
return ret;
}
// check if the string input ends with with substring search
function endsWith(input, search) {
var index = input.length - search.length;
return index >= 0 && input.indexOf(search, index) > -1;
}
// format angle (given in radians) in radians or degree
function _formatAngle(angle, showDegree, decimals ) {
return showDegree ?
(math.round((angle * 360)/ (2*Math.PI), decimals ) + '°') :
math.round( angle, decimals ) ;
}
/**
*
* _setFont: set the font to use on the canvas context.
* @private
* @param { ctx } the context
* @param { params } options ('fontSize' and 'fontFamily' are used to define a font)
*/
function _setFont(ctx, params) {
var str = params.fontSize;
// convert size to the form 'XXpx'
if (endsWith(str, 'px') == false) {
while (isNaN(str) && str.length > 1) str = str.substring(0, str.length - 1);
str = str + 'px';
}
ctx.font = str + ' ' + params['fontFamily'];
}
/**
*
* extend: mimick the jQuery.extend() function (merge the
* contents of two or more objects together into the first
* object).
* @private
* @param { target [, object1 ] [, objectN ] }
*/
function extend(){
for(var i=1; i<arguments.length; i++)
for(var key in arguments[i])
if(arguments[i].hasOwnProperty(key))
arguments[0][key] = arguments[i][key];
return arguments[0];
}
// the drawing primitives used: line (with arrow heads if desired),
// text, rectangle
// clear the canvas
/**
* _clearCanvas(): clear the canvas
* @private
*/
function _clearCanvas() {
if ( _dactx == null ) return;
_dactx.clearRect(0, 0, _daCanvas.width, _daCanvas.height);
_count = 0;
}
// Adds an arrow head to a path using the given properties
/**
* _addArrow(ctx, params, x1, y1, x2, y2) Adds an arrow head
* to a path using the given properties
* @private
* @param { numbers } x1, y1, x2, y2: coordinates of start and end
* point of the line to add an arrow head to.
*/
function _addArrow(ctx, params, x1, y1, x2, y2) {
var leftX, leftY,
rightX, rightY,
offsetX, offsetY,
atan2 = Math.atan2,
PI = Math.PI,
round = Math.round,
abs = Math.abs,
sin = Math.sin,
cos = Math.cos,
angle;
// If arrow radius is given
if (params.arrowRadius) {
// Calculate angle
angle = atan2((y2 - y1), (x2 - x1));
// Adjust angle correctly
angle -= PI;
// Calculate offset to place arrow at edge of path
offsetX = (params.linewidth* cos(angle))-1;
offsetY = (params.linewidth* sin(angle))-1;
// Calculate coordinates for left half of arrow
leftX = x2 - (params.arrowRadius * cos(angle + (params.arrowAngle / 2)));
leftY = y2 - (params.arrowRadius * sin(angle + (params.arrowAngle / 2)));
// Calculate coordinates for right half of arrow
rightX = x2 - (params.arrowRadius * cos(angle - (params.arrowAngle / 2)));
rightY = y2 - (params.arrowRadius * sin(angle - (params.arrowAngle / 2)));
// Draw left half of arrow
ctx.moveTo(leftX - offsetX, leftY - offsetY);
ctx.lineTo(x2 - offsetX, y2 - offsetY);
// Draw right half of arrow
ctx.lineTo(rightX - offsetX, rightY - offsetY);
ctx.closePath();
ctx.fill();
// Visually connect arrow to path
ctx.moveTo(x2 - offsetX, y2 - offsetY);
ctx.lineTo(x2 + offsetX, y2 + offsetY);
// Move back to end of path
ctx.moveTo(x2, y2);
}
}
/**
* _drawLine( params, options ): draw a line on the canvas. Start and end point
* of the line are x1/y1 and x2/y2 in the array of settings.
* @private
* @param { params } options - CNum {@link options}
* @param { options } options - CNum {@link options}
* @example _drawLine({ color: 'red', linewidth: 2,
* x1: 1, y1: 1, x2: 10, y2: 10, endArrow: true })
*/
function _drawLine( params, options) {
if ( _dactx == null ) return;
var settings= extend( {}, params, options);
_dactx.strokeStyle = settings.color;
_dactx.fillStyle = settings.color;
_dactx.lineWidth = settings.linewidth;
_dactx.beginPath();
_dactx.moveTo(settings['x1'], settings['y1']);
_dactx.lineTo(settings['x2'], settings['y2']);
if (settings.endArrow)
_addArrow(_dactx, settings, settings.x1, settings.y1, settings.x2, settings.y2);
if (settings.startArrow)
_addArrow(_dactx, settings, settings.x2, settings.y2, settings.x1, settings.y1);
_dactx.stroke();
}
/**
* _drawText( params, options ): draw text on the canvas at x/y (centered) using
* the given options.
* @private
* @param { params } options - CNum {@link options}
* @param { options } options - CNum {@link options}
* @example _drawText({ color: 'red', x: 10, y: 20,
* fontSize: '24px', fontFamily: 'Arial', text: 'Hallo Welt' })
*/
function _drawText( params, options) {
if ( _dactx == null ) return;
var settings = extend( {}, params, options);
_dactx.beginPath();
_dactx.strokeStyle = settings.color;
_dactx.lineWidth = settings.linewidth;
_dactx.fillStyle = settings.color;
_setFont(_dactx, settings);
_dactx.textAlign = "center";
_dactx.textBaseline = "middle";
_dactx.fillText(settings.text, settings.x, settings.y);
}
/**
* _drawRect( options ): draw a rectangle on the canvas.
* @private
* @param { options } options - CNum {@link options}
* @example _drawRect({ color: 'red', linewidth: 3,
* x: 10, y: 20, width: 30, height: 10 })
*/
function _drawRect( options ) {
if ( _dactx == null ) return;
var settings = extend( {}, this._daSettings, options);
_dactx.beginPath();
_dactx.strokeStyle = settings.color;
_dactx.lineWidth = settings.linewidth;
_dactx.rect(settings.x, settings.y, settings.width, settings.height);
_dactx.stroke();
}
/**
* _drawArc: draw an arc on the canvas.
* @private
* @param { CNum } z, complex number.
* @param { options } options - CNum {@link options}.
* @example _drawArc( znum, { color: 'red', linewidth: 3,
* x: 10, y: 20, radius:20, start: 0, end: 2*Math.PI })
*/
function _drawArc( z, options ) {
if ( _dactx == null ) return;
var settings = extend( {}, z.GetSettings(), options);
var counterclockwise = true;
_dactx.beginPath();
_dactx.strokeStyle = settings.color;
_dactx.lineWidth = settings.linewidth;
_dactx.arc( settings.x, settings.y, settings.radius, settings.start, -settings.end, counterclockwise );
_dactx.stroke();
}
/**
* _setScale: calculate a reasonable scale for the canvas to plot a complex number
* @param { number } maxradius: the radius of the number to display
*/
function _setScale(maxradius) {
X_C = _daCanvas.width / 2;
Y_C = _daCanvas.height / 2;
_plotW = _daCanvas.width - 2 * _margin;
_plotH = _daCanvas.height - 2 * _margin;
_SCALE = min(_plotW, _plotH) / (2 * maxradius);
_maxradius = maxradius;
while (maxradius/_TICKSCALE > 10) {
_TICKSCALE= _TICKSCALE*10;
}
if (_TICKSCALE >10) _TICKSCALE= _TICKSCALE*2;
} // _setScale
/**
* _drawtick( pos ): draw a tick on x-and y-axis at position
* x = pos / y = pos
* @private
* @param { number } pos: tick position.
*/
function _drawtick( settings, pos ) {
_drawLine( settings, { x1: _XPos(pos) , y1: Y_C,
x2: _XPos(pos), y2: Y_C + _tickLength });
_drawText( settings, { x: _XPos(pos), y: Y_C+10,
text: pos });
_drawLine( settings, { x1: X_C , y1: _YPos(pos),
x2: X_C - _tickLength, y2: _YPos(pos) });
_drawText( settings, { x: X_C-20, y: _YPos(pos)+3,
text: pos });
}; // _drawtick
/**
* _axes( settings): draw axes of a cartesian coordinate system
* @private
* @param { options } settings- CNum {@link options}.
*/
function _axes( settings ){
if (_daCanvas == null) return;
var rec_w = _dactx.measureText("Re(z)").width + 10;
var rec_h = parseInt(_dactx.font.match(/\d+/), 10);
_drawLine( settings, { endArrow: true, x1: _margin, y1: Y_C,
x2: _plotW + _margin , y2: Y_C });
_drawText( settings, { x: _plotW + 2*_margin - rec_w/2 , y: Y_C, text: "Re(z)" });
_drawText( settings, { x: X_C, y: _margin/2, text: "Im(z)" });
_drawLine( settings, { endArrow: true, x1: X_C, y1: _plotH+_margin,
x2: X_C, y2: _margin });
for ( i=_TICKSCALE; i<=_maxradius; i+=_TICKSCALE) {
_drawtick( settings, i );
}
}; // _axes
/**
* _drawReIm( z, x, y ):
* draw x/y, real and imaginary part using the given settings.
* @private
* @param { CNum } z, the complex number to draw.
* @param { coordinates } x/y the cartesian koordinates of the complex number.
*/
function _drawReIm( z, x, y ) {
xpos = _XPos( x );
ypos = _YPos( y );
// arrow is drawm from center to P(xpos, ypos)
_drawLine( z.GetSettings(), { x1: xpos, y1: Y_C, x2: xpos, y2: ypos });
_drawLine( z.GetSettings(), { x1: X_C, y1: ypos, x2: xpos, y2: ypos });
}; // drawReIm
/**
* drawz( z ): draw a complex number
* z= x + iy into the gaussian / argand plane.
* @private
* @param { CNum } z, the complex number to draw.
*/
function drawz( z ) {
// Draw arrow from A(z.xstart, z.ystart) to B(z.xpos, z.ypos)
xpos = _XPos( z.x + z.offsetx );
ypos = _YPos( z.y + z.offsety );
x = _XScaled( z.offsetx );
y = _YScaled( z.offsety );
corr = z.offsetx>0?15:0;
var settings = z.GetSettings();
if ( settings.Arrow )
_drawLine( settings, { endArrow: true,
x1: X_C + x, y1: Y_C - y, x2: xpos, y2: ypos } );
else
_drawRect( { x: xpos-2, y: ypos-2, width: 4, height: 4 } );
if ( typeof(settings.Ctext) !== "undefined" && settings.Ctext !== false && settings.Ctext !== null) {
var tstr = "";
if ( typeof( settings.Ctext) === "boolean" && settings.Ctext == true)
tstr = 'z =' + math.complex(z.x, z.y).toString();
else
tstr = settings.Ctext;
_drawText( settings, { x: xpos +10+corr, y: ypos-(sign(z.y)*10),
text: tstr });
}
}; //drawz
// _drawAngle: draw an angle of the arrow (mathematically starting from x-axis)
/**
* _drawAngle( z, angle ): draw an angle at the base of the vector
* @private
* @param { z } CNum defining the angle.
* @param { float } angle
*/
function _drawAngle( z, angle ) {
var PI = Math.PI;
if (_daCanvas == null) return;
var ra = min(50, (this._radius * _SCALE)/2 );
ra += _count * 2;
_drawArc( z, { x: X_C, y: Y_C, radius: ra,
start: 0, end: angle });
tx = X_C + (ra-10)*math.cos(angle - PI/6);
ty = Y_C - (ra-10)*math.sin(angle - PI/6);
_drawText( z.GetSettings(), { x: tx, y: ty,
text: _formatAngle( angle, z.GetSettings().showDegree, z.GetSettings().decimals ) });
}; // _drawAngle
// draw a circle with radius |z|
// (e.g. to clarify the picture of rotating pointers in the complex plane)
/**
* _circ( z ): draw a circle with center and radius on the canvas
* @private
* @param { z } CNum defining the radius of the circle.
*/
function _circ( z ) {
var PI = Math.PI;
if (_daCanvas == null) return;
_drawArc( z , { x: X_C, y: Y_C, radius: (z.GetRadius() * _SCALE),
start: 0, end: 2*PI });
}; // _circ
// =======================================================
// Public methods:
// =======================================================
// return radius of the complex cartesian x+iy in gaussian plane
/**
* GetRadius(): return radius of the pointer
* @returns {float} radius of the complex number (norm)
*/
this.GetRadius = function() { return _radius; };
// return options array of the current CNum
/**
* GetSettings(): return current settings
* @returns{ options } settings - CNum {@link options}.
*/
this.GetSettings = function() { return this._daSettings; };
// set options array of the current CNum
/**
* SetSettings(): change current settings
* @param { options } settings - CNum {@link options}.
* @returns { options } settings - current CNum {@link options}.
*/
this.SetSettings = function( newsettings ) {
var s = this.GetSettings();
this._daSettings = extend( {}, s, newsettings );
return this._daSettings;
};
// get the complex number z in cartesian coordinates as string
// with a bit of html.
/**
* ToCartesian(): Return a string of the complex number z in cartesian representation (e.g. '1+2i')
* @param { number } decimals: (optional) number of decimal places to round to (default: 1).
* @returns {string} a string containing the simplest form of the complex number <b><i>z = x + i·y</i></b>
*/
this.ToCartesian = function() {
var d = typeof decimals == 'undefined' ? this._daSettings.decimals : decimals;
return this.zNum.format( d );
};
// get the complex conjugate of z.
/**
* ToCc(): return a string of the complex conjugate z* in cartesian representation (e.g. '1-2i')
* @param { number } decimals: (optional) number of decimal places to round to (default: 1).
* @returns {string} <b><i>z̅</i></b>, a string containing the complex conjugate of <b><i>z</i></b>.
*/
this.ToCC = function( decimals ) {
var d = typeof decimals == 'undefined' ? this._daSettings.decimals : decimals;
return math.conj(this.zNum).format( d );
};
// Return the norm of the complex number z.
/**
* ToR(): return a string of the norm (length of the vector) of the complex number z (e.g. '2.236')
* @param { number } decimals: (optional) number of decimal places to round to (default: 1).
* @returns {string} a string containing the norm as a real number.
*/
this.ToR = function( decimals ) {
var d = typeof decimals == 'undefined' ? this._daSettings.decimals : decimals;
return math.round(this.zNum.toPolar().r, d);
};
// get the complex number z in trigonometric form with some
// html formatting (for the multiplication).
/**
* ToTrigonometric( decimals ): return a string of the complex number z in trigonometric representation (e.g. '2.236(cos(1.107) + i · sin(1.107))')
* @param { number } decimals: (optional) number of decimal places to round to (default: 1)
* @returns {string} a string containing the complex number as a mathematical expression in trigonometric notation.
*/
this.ToTrigonometric = function( decimals ) {
var d = typeof decimals == 'undefined' ? this._daSettings.decimals : decimals;
var r = math.round( this.zNum.toPolar().r, d );
var phi = this.zNum.toPolar().phi;
phi = _formatAngle( phi, this._daSettings.showDegree, d );
retval = r + "·(cos(" + phi + ") + i ·sin(" + phi +"))";
return retval;
};
// get the complex number z in polar coordinates with some
// html formatting (for the superscript in the exponential).
/**
* ToPolar( decimals ): create a string of the complex number z in polar representation (e.g. '2.236 e<sup>i 1.107</sup>')
* @param { number } decimals: (optional) number of decimal places to round to (default: 1)
* @returns {string} a string containing the number <b><i>z</i></b> in polar coordinates with a bit of html for the superscripts.
*/
this.ToPolar = function( decimals ) {
var d = typeof decimals == 'undefined' ? this._daSettings.decimals : decimals;
var r = math.round( this.zNum.toPolar().r, d );
var phi = this.zNum.toPolar().phi;
phi = _formatAngle( phi, this._daSettings.showDegree, d );
retval = r + "· e<sup>i " + phi + "</sup>";
return retval;
};
// the good stuff: Graphics
// -----------------------------------------------------------------------------
/**
* setCanvas( cnv ): set the canvas to plot on
* @param {integer} cnv the canvas to use
* @returns { canvas } cnv
*/
this.setCanvas = function( cnv ) {
_daCanvas = cnv;
_dactx = (cnv) ? cnv.getContext("2d") : null ;
return cnv;
};
/**
* getXPos(): get cartesian coordinate x of a given point (x/y) on the canvas
* @private
* @returns { number } x
*/
this.getXPos = function(x) { return _XPos(x); };
/**
* getYPos(): get cartesian coordinate y of a given point (x/y) on the canvas
* @private
* @returns { number } y
*/
this.getYPos = function(y) { return _YPos(y); };
// calculate the product of two complex numbers and add
// numbers and result to an existing plot
/**
* multiplyCNum( z2, options, resultoptions ): multiply two complex numbers in a Gaussian plot.
* @param { CNum } z2 the number to multiply with
* @param { options } options set appearance of the complex number to multiply with (see {@link CNum.options})
* @param { options } resultoptions change appearance of the resulting complex number (see {@link CNum.options})
* @return { CNum } result of the operation as a CNum
*/
this.multiplyCNum =function( z2, options, resultoptions ){
var settings = extend( {}, _defaults, options, { circle: false } );
resultoptions = ( typeof resultoptions == 'undefined' ? settings : extend( {}, _defaults, resultoptions) );
// calculate resulting value z = this * z2
res = new CNum( math.multiply(this.zNum, z2.zNum).toString() );
z2.offsetx = 0;
z2.offsety = 0;
this.addToPlot(z2, settings); // multiplication of this and z2
this.addToPlot(res, resultoptions); // display the result
// replot this and rescale to largest absolute value// replot this and rescale to largest absolute value
this.displayGauss( this.GetSettings() );
return res;
}
// calculate the sum of two complex numbers and add
// numbers and result to an existing plot
/**
* addCNum ( _zToAdd, options, resultoptions ): show the sum of two complex numbers in a Gaussian plot.
* @param { CNum } _zToAdd the number to add
* @param { options } options set appearance of the complex number to add (see {@link CNum.options} for a list of possible settings)
* @param { options } resultoptions change appearance of the resulting complex number (see {@link CNum.options} for a list of possible settings)
* @return { CNum } the result of the operation as a CNum
*/
this.addCNum =function(_zToAdd, options, resultoptions){
var settings = extend( {}, _defaults, options, { circle: false, arc: false, ReIm: false } );
resultoptions = ( typeof resultoptions == 'undefined' ? settings : extend( {}, _defaults, resultoptions) );
// calculate resulting value z = this + _zToAdd
// and add it to the plot
res = new CNum( this.zNum.toString() + "+" + _zToAdd.zNum.toString() );
this.addToPlot( res, resultoptions );
_zToAdd.offsetx = this.x;
_zToAdd.offsety = this.y;
this.addToPlot( _zToAdd, settings );
// replot this and rescale to largest absolute value
this.displayGauss( this.GetSettings() );
return res;
}
/**
* _drawToPlot ( z ): draw a complex number to the plot
* @private
* @param { CNum } z the complex number to draw to the current plot
*/
this._drawToPlot = function( z ) {
var s = z.GetSettings();
if (s.circle) _circ( z );
if (s.arc) _drawAngle( z, z.angle );
if (s.ReIm) _drawReIm( z, z.x, z.y );
drawz( z );
}
/**
* addToPlot ( z, options ): add a CNum to an existing plot - may be used to plot several
* numbers on one canvas at the same time.
* Caveat: the plot will not be rescaled nor cleared (of course).
* @param { CNum } z the complex number to add to the current plot
* @param { options } settings change plot appearance (see {@link CNum.options} for a list of possible settings)
*/
this.addToPlot = function( z, options ) {
var s = extend( {}, _defaults, options );
z.SetSettings( s );
if ( z !== this) {
_numlist.push( z );
}
this._drawToPlot( z );
}; // addToPlot
// * clear canvas and draw
//
/**
* displayGauss(options, radius): draw the complex number z as an arrow in the complex plane on the
* selected canvas (set by setCanvas()).
* This method either plots a single CNum or the first one in a series
* of CNums drawn onto the same canvas. Additional numbers can be
* displayed on that canvas using {@see addToPlot}
* @param {options} options change plot appearance (see {@link CNum.options} for a list of possible settings).
* @param {number} radius (optional) scale the plot for a complex number of this value (default: autoscale).
* @see setCanvas(): Set the canvas to draw on.
* @see addToPlot(): draw another number into an existing plot.
*/
this.displayGauss = function( options, radius ){
// handle defaults
var settings = extend( {}, _defaults, { clear:true, coords: true, circle: true }, options );
var maxR = typeof radius == 'undefined' ? _getmaxRadius() : radius ;
_setScale(maxR);
_clearCanvas();
_axes( settings );
// plot this CNum...
this.addToPlot(this, settings);
// ...and all of the numbers added to the canvas
for (var i = 0; i < _numlist.length; i++) {
/* _numlist[i]._count = i+1; */
this._drawToPlot( _numlist[i] );
}
};
// return a brandnew CNum :-)
return this;
}; // -- CNum --
|
const rightMargin = $(".tab-pane.active").css('marginRight')
$(".nav-item").click(e => {
var elementToDisplay = $("#" + e.target.getAttribute("show"))
if (elementToDisplay.length === 0)
return
//NAVBAR
$(".nav-item.active").removeClass("active")
$(e.target).parent().addClass("active")
//DIV
var elementToHide = $(".tab-pane.active")
elementToHide.animate({'margin-left': '-1000px'}, 400, () => {
elementToHide.removeClass('active')
elementToHide.hide(1, () => {
elementToHide.css({'marginLeft': 'auto', 'marginRight': '-1000px'})
elementToDisplay.animate({'margin-right': rightMargin}, 400)
elementToDisplay.addClass('active')
elementToDisplay.show()
})
})
})
$("#settings tr").mouseover(e => {
var id = e.currentTarget.childNodes[1].childNodes[0].id || e.currentTarget.childNodes[1].childNodes[0].childNodes[0].id
$("#docSettings").html(getSettingsDoc(id))
})
function getSettingsDoc(id) {
switch (id) {
case 'enabled':
return "If this box is not checked, bot will be totally disabled."
case 'checkCart':
return "If you use keywords and if you found one or more items, this option will let you check your cart before checkout. We recommand you to use this option."
case 'autoFill':
return "When you are on checkout page (URL: http://supremenewyork.com/checkout), the form will be automatically filled with your information."
case 'autoCheckout':
return "The checkout form will be submitted automatically if this option is enabled."
case 'retryOnFail':
return "If when you are purchasing you got an error, the bot will try again until payment done <i style=\"color: #fff;\">(Option \"Auto-fill checkout page and submit it\" must be enabled)</i>"
case 'nextSize':
return "With keywords you can choose the wanted size, if size is sold-out, the bot will choose the next one."
case 'startTime':
return "Exact hour of the drop is recommanded. Start time must be in this format hh:mm:ss (ex: 14:23:54), if you put \"0\" as value, this option will be disabled. It permit to start the bot as the wanted time by click on \"Start\" on popup. <b>To use this option, you must be on Supreme page and don’t leave it."
case 'startWhenUpdated':
return "<b>Previous feature must be enabled.</b> Start the bot at the second when the new drop list is online. The bot must be started by the Start button."
case 'removeCaptcha':
return "This feature remove the captcha on checkout page. This option is not recommanded because payment can fail."
case 'hideImages':
return "Remove all images on www.supremenewyork.com, recommanded if you've a weak internet connection."
}
}
|
/**
* @fileoverview ARC4 streamcipher implementation. A description of the
* algorithm can be found at:
* http://www.mozilla.org/projects/security/pki/nss/draft-kaukonen-cipher-arcfour-03.txt.
*
* Original implemention found at: http://docs.closure-library.googlecode.com/git/closure_goog_crypt_arc4.js.source.html
*
* Usage:
* <code>
* var arc4 = new Arc4();
* arc4.setKey(key);
* arc4.discard(1536);
* arc4.crypt(bytes);
* </code>
*/
/**
* ARC4 streamcipher implementation.
* @constructor
*/
function Arc4() {
/**
* A permutation of all 256 possible bytes.
* @type {Array.<number>}
* @private
*/
this._state = [];
/**
* 8 bit index pointer into this._state.
* @type {number}
* @private
*/
this._index1 = 0;
/**
* 8 bit index pointer into this._state.
* @type {number}
* @private
*/
this._index2 = 0;
}
/**
* Initialize the cipher for use with new key.
* @param {Array.<number>} key A byte array containing the key.
* @param {number=} opt_length Indicates # of bytes to take from the key.
*/
Arc4.prototype.setKey = function(key, opt_length) {
if (!opt_length) {
opt_length = key.length;
}
var state = this._state;
for (var i = 0; i < 256; ++i) {
state[i] = i;
}
var j = 0;
for (var i = 0; i < 256; ++i) {
j = (j + state[i] + key[i % opt_length]) & 255;
var tmp = state[i];
state[i] = state[j];
state[j] = tmp;
}
this._index1 = 0;
this._index2 = 0;
};
/**
* Discards n bytes of the keystream.
* These days 1536 is considered a decent amount to drop to get the key state
* warmed-up enough for secure usage. This is not done in the constructor to
* preserve efficiency for use cases that do not need this.
* NOTE: Discard is identical to crypt without actually xoring any data. It's
* unfortunate to have this code duplicated, but this was done for performance
* reasons. Alternatives which were attempted:
* 1. Create a temp array of the correct length and pass it to crypt. This
* works but needlessly allocates an array. But more importantly this
* requires choosing an array type (Array or Uint8Array) in discard, and
* choosing a different type than will be passed to crypt by the client
* code hurts the javascript engines ability to optimize crypt (7x hit in
* v8).
* 2. Make data option in crypt so discard can pass null, this has a huge
* perf hit for crypt.
* @param {number} length Number of bytes to disregard from the stream.
*/
Arc4.prototype.discard = function(length) {
var i = this._index1;
var j = this._index2;
var state = this._state;
for (var n = 0; n < length; ++n) {
i = (i + 1) & 255;
j = (j + state[i]) & 255;
var tmp = state[i];
state[i] = state[j];
state[j] = tmp;
}
this._index1 = i;
this._index2 = j;
};
/**
* En- or decrypt (same operation for streamciphers like ARC4)
* @param {Array.<number>|Uint8Array} data The data to be xor-ed in place.
* @param {number=} opt_length The number of bytes to crypt.
*/
Arc4.prototype.crypt = function(data, opt_length) {
if (!opt_length) {
opt_length = data.length;
}
var i = this._index1;
var j = this._index2;
var state = this._state;
for (var n = 0; n < opt_length; ++n) {
i = (i + 1) & 255;
j = (j + state[i]) & 255;
var tmp = state[i];
state[i] = state[j];
state[j] = tmp;
data[n] ^= state[(state[i] + state[j]) & 255];
}
this._index1 = i;
this._index2 = j;
};
module.exports = Arc4; |
var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var logger = require('morgan');
var crypto = require('crypto');
var bcrypt = require('bcryptjs');
var mongoose = require('mongoose');
var jwt = require('jwt-simple');
var moment = require('moment');
var async = require('async');
var request = require('request');
var xml2js = require('xml2js');
var agenda = require('agenda')({ db: { address: 'localhost:27017/test' } });
var Sugar = require('sugar/date');
var nodemailer = require('nodemailer');
var _ = require('lodash');
var tokenSecret = 'your unique secret';
var showSchema = new mongoose.Schema({
_id: Number,
name: String,
airsDayOfWeek: String,
airsTime: String,
firstAired: Date,
genre: [String],
network: String,
overview: String,
rating: Number,
ratingCount: Number,
status: String,
poster: String,
subscribers: [{
type: mongoose.Schema.Types.ObjectId, ref: 'User'
}],
episodes: [{
season: Number,
episodeNumber: Number,
episodeName: String,
firstAired: Date,
overview: String
}]
});
var userSchema = new mongoose.Schema({
name: { type: String, trim: true, required: true },
email: { type: String, unique: true, lowercase: true, trim: true },
password: String,
facebook: {
id: String,
email: String
},
google: {
id: String,
email: String
}
});
userSchema.pre('save', function(next) {
var user = this;
if (!user.isModified('password')) return next();
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err);
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
});
userSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
var User = mongoose.model('User', userSchema);
var Show = mongoose.model('Show', showSchema);
mongoose.connect('localhost');
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
function ensureAuthenticated(req, res, next) {
if (req.headers.authorization) {
var token = req.headers.authorization.split(' ')[1];
try {
var decoded = jwt.decode(token, tokenSecret);
if (decoded.exp <= Date.now()) {
res.send(400, 'Access token has expired');
} else {
req.user = decoded.user;
return next();
}
} catch (err) {
return res.send(500, 'Error parsing token');
}
} else {
return res.send(401);
}
}
function createJwtToken(user) {
var payload = {
user: user,
iat: new Date().getTime(),
exp: moment().add('days', 7).valueOf()
};
return jwt.encode(payload, tokenSecret);
}
app.post('/auth/signup', function(req, res, next) {
var user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password
});
user.save(function(err) {
if (err) return next(err);
res.send(200);
});
});
app.post('/auth/login', function(req, res, next) {
User.findOne({ email: req.body.email }, function(err, user) {
if (!user) return res.send(401, 'User does not exist');
user.comparePassword(req.body.password, function(err, isMatch) {
if (!isMatch) return res.send(401, 'Invalid email and/or password');
var token = createJwtToken(user);
res.send({ token: token });
});
});
});
app.post('/auth/facebook', function(req, res, next) {
var profile = req.body.profile;
var signedRequest = req.body.signedRequest;
var encodedSignature = signedRequest.split('.')[0];
var payload = signedRequest.split('.')[1];
var appSecret = '298fb6c080fda239b809ae418bf49700';
var expectedSignature = crypto.createHmac('sha256', appSecret).update(payload).digest('base64');
expectedSignature = expectedSignature.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
if (encodedSignature !== expectedSignature) {
return res.send(400, 'Invalid Request Signature');
}
User.findOne({ facebook: profile.id }, function(err, existingUser) {
if (existingUser) {
var token = createJwtToken(existingUser);
return res.send(token);
}
var user = new User({
name: profile.name,
facebook: {
id: profile.id,
email: profile.email
}
});
user.save(function(err) {
if (err) return next(err);
var token = createJwtToken(user);
res.send(token);
});
});
});
app.post('/auth/google', function(req, res, next) {
var profile = req.body.profile;
User.findOne({ google: profile.id }, function(err, existingUser) {
if (existingUser) {
var token = createJwtToken(existingUser);
return res.send(token);
}
var user = new User({
name: profile.displayName,
google: {
id: profile.id,
email: profile.emails[0].value
}
});
user.save(function(err) {
if (err) return next(err);
var token = createJwtToken(user);
res.send(token);
});
});
});
app.get('/api/users', function(req, res, next) {
if (!req.query.email) {
return res.send(400, { message: 'Email parameter is required.' });
}
User.findOne({ email: req.query.email }, function(err, user) {
if (err) return next(err);
res.send({ available: !user });
});
});
app.get('/api/shows', function(req, res, next) {
var query = Show.find();
if (req.query.genre) {
query.where({ genre: req.query.genre });
} else if (req.query.alphabet) {
query.where({ name: new RegExp('^' + '[' + req.query.alphabet + ']', 'i') });
} else {
query.limit(12);
}
query.exec(function(err, shows) {
if (err) return next(err);
res.send(shows);
});
});
app.get('/api/shows/:id', function(req, res, next) {
Show.findById(req.params.id, function(err, show) {
if (err) return next(err);
res.send(show);
});
});
app.post('/api/shows', function (req, res, next) {
var seriesName = req.body.showName
.toLowerCase()
.replace(/ /g, '_')
.replace(/[^\w-]+/g, '');
var apiKey = '9EF1D1E7D28FDA0B';
var parser = xml2js.Parser({
explicitArray: false,
normalizeTags: true
});
async.waterfall([
function (callback) {
request.get('http://thetvdb.com/api/GetSeries.php?seriesname=' + seriesName, function (error, response, body) {
if (error) return next(error);
parser.parseString(body, function (err, result) {
if (!result.data.series) {
return res.send(400, { message: req.body.showName + ' was not found.' });
}
var seriesId = result.data.series.seriesid || result.data.series[0].seriesid;
callback(err, seriesId);
});
});
},
function (seriesId, callback) {
request.get('http://thetvdb.com/api/' + apiKey + '/series/' + seriesId + '/all/en.xml', function (error, response, body) {
if (error) return next(error);
parser.parseString(body, function (err, result) {
var series = result.data.series;
var episodes = result.data.episode;
var show = new Show({
_id: series.id,
name: series.seriesname,
airsDayOfWeek: series.airs_dayofweek,
airsTime: series.airs_time,
firstAired: series.firstaired,
genre: series.genre.split('|').filter(Boolean),
network: series.network,
overview: series.overview,
rating: series.rating,
ratingCount: series.ratingcount,
runtime: series.runtime,
status: series.status,
poster: series.poster,
episodes: []
});
_.each(episodes, function (episode) {
show.episodes.push({
season: episode.seasonnumber,
episodeNumber: episode.episodenumber,
episodeName: episode.episodename,
firstAired: episode.firstaired,
overview: episode.overview
});
});
callback(err, show);
});
});
},
function (show, callback) {
var url = 'http://thetvdb.com/banners/' + show.poster;
request({ url: url, encoding: null }, function (error, response, body) {
show.poster = 'data:' + response.headers['content-type'] + ';base64,' + body.toString('base64');
callback(error, show);
});
}
], function (err, show) {
if (err) return next(err);
show.save(function (err) {
if (err) {
if (err.code == 11000) {
return res.send(409, { message: show.name + ' already exists.' });
}
return next(err);
}
var alertDate = Sugar.Date.create('Next ' + show.airsDayOfWeek + ' at ' + show.airsTime).rewind({ hour: 2});
agenda.schedule(alertDate, 'send email alert', show.name).repeatEvery('1 week');
res.send(200);
});
});
});
app.post('/api/subscribe', ensureAuthenticated, function(req, res, next) {
Show.findById(req.body.showId, function(err, show) {
if (err) return next(err);
show.subscribers.push(req.user._id);
show.save(function(err) {
if (err) return next(err);
res.send(200);
});
});
});
app.post('/api/unsubscribe', ensureAuthenticated, function(req, res, next) {
Show.findById(req.body.showId, function(err, show) {
if (err) return next(err);
var index = show.subscribers.indexOf(req.user._id);
show.subscribers.splice(index, 1);
show.save(function(err) {
if (err) return next(err);
res.send(200);
});
});
});
app.get('*', function(req, res) {
res.redirect('/#' + req.originalUrl);
});
app.use(function(err, req, res, next) {
console.error(err.stack);
res.send(500, { message: err.message });
});
app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
agenda.define('send email alert', function(job, done) {
Show.findOne({ name: job.attrs.data }).populate('subscribers').exec(function(err, show) {
var emails = show.subscribers.map(function(user) {
if (user.facebook) {
return user.facebook.email;
} else if (user.google) {
return user.google.email
} else {
return user.email
}
});
var upcomingEpisode = show.episodes.filter(function(episode) {
return new Date(episode.firstAired) > new Date();
})[0];
var smtpTransport = nodemailer.createTransport('SMTP', {
service: 'SendGrid',
auth: { user: 'hslogin', pass: 'hspassword00' }
});
var mailOptions = {
from: 'Fred Foo ✔ <foo@blurdybloop.com>',
to: emails.join(','),
subject: show.name + ' is starting soon!',
text: show.name + ' starts in less than 2 hours on ' + show.network + '.\n\n' +
'Episode ' + upcomingEpisode.episodeNumber + ' Overview\n\n' + upcomingEpisode.overview
};
smtpTransport.sendMail(mailOptions, function(error, response) {
console.log('Message sent: ' + response.message);
smtpTransport.close();
done();
});
});
});
//agenda.start();
agenda.on('start', function(job) {
console.log("Job %s starting", job.attrs.name);
});
agenda.on('complete', function(job) {
console.log("Job %s finished", job.attrs.name);
}); |
module.exports = trimSlashes => [
(req, res, next) => {
if (req.query.file) {
req.getFile = () => trimSlashes(req.query.file);
next();
} else {
res.status(400).json({
error: '?file query path is empty'
});
}
},
(req, res, next) => {
if (req.body.newname) {
req.getNewName = () => trimSlashes(req.body.newname);
next();
} else {
res.status(400).json({
error: 'newname body param is empty'
});
}
}
];
|
$(document).ready(function(){
// Step 1: Listen for a click event on our checkboxes
// Step 2: Use the toggleClass method to add or remove the "chcked" class to the checkbox that was clicked
$(".checkbox").click(function(){
$(this).toggleClass("checked");
});
});
|
// Here's a multiline comment.
// * This one has stars in the middle parts.
// * yup, stars.
//
var someFunction = function () { // this function is awesome
return 42;
};
|
'use strict';
var algoliasearchHelper = require('../../../../index.js');
test('[derived helper] detach a derived helper', function(done) {
var client = {
search: searchTest
};
var helper = algoliasearchHelper(client, '');
var derivedHelper = helper.derive(function(s) { return s; });
derivedHelper.on('result', function() {});
helper.search();
derivedHelper.detach();
helper.search();
var nbRequest;
function searchTest(requests) {
nbRequest = nbRequest || 0;
if (nbRequest === 0) {
expect(requests.length).toBe(2);
expect(requests[0]).toEqual(requests[1]);
expect(derivedHelper.listeners('result').length).toBe(1);
nbRequest++;
} else if (nbRequest === 1) {
expect(requests.length).toBe(1);
expect(derivedHelper.listeners('result').length).toBe(0);
done();
}
return new Promise(function() {});
}
});
|
var telegram = require('telegram-bot-api');
var api = new telegram({
token: '<YOUR TOKEN>',
updates: {
enabled: true,
get_interval: 1000
}
});
api.on('message', function(message)
{
var chat_id = message.chat.id;
// It'd be good to check received message type here
// And react accordingly
// We consider that only text messages can be received here
api.sendMessage({
chat_id: message.chat.id,
text: message.text ? message.text : 'This message doesn\'t contain text :('
})
.then(function(message)
{
console.log(message);
})
.catch(function(err)
{
console.log(err);
});
});
|
module.exports = function(app){
app.get('/', function(req, res){
res.render('index', {
title: 'Express Login'
});
});
//other routes..
}; |
module.exports = function(config){
config.set({
basePath : '../',
files : [
'bower_components/angular/angular.js',
'bower_components/angular/angular-*.js',
'bower_components/angular-mocks/angular-mocks.js',
'app/js/**/*.js',
'test/unit/**/*.js',
'bower_components/moment/moment.js',
'bower_components/chroma-js/chroma.js'
],
exclude : [
'app/lib/angular/angular-loader.js',
'app/lib/angular/*.min.js',
'app/lib/angular/angular-scenario.js'
],
autoWatch : true,
frameworks: ['jasmine'],
browsers : ['Chrome'],
plugins : [
'karma-junit-reporter',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine'
],
junitReporter : {
outputFile: 'test_out/unit.xml',
suite: 'unit'
}
})}
|
// Requiring and exporting JSUS
var JSUS = require('JSUS').JSUS;
module.exports.JSUS = JSUS;
var util = require('util'),
fs = require('fs'),
path = require('path'),
should = require('should'),
NDDB = require('./../index').NDDB;
var db = new NDDB();
var db2 = new NDDB();
// TODO: make a test were a file containing weirdos items is loaded.
var hashable = [
{
painter: "Jesus",
title: "Tea in the desert",
year: 0,
},
{
painter: "Dali",
title: "Portrait of Paul Eluard",
year: 1929,
portrait: true
},
{
painter: "Dali",
title: "Barcelonese Mannequin",
year: 1927
},
{
painter: "Monet",
title: "Water Lilies",
year: 1906
},
{
painter: "Monet",
title: "Wheatstacks (End of Summer)",
year: 1891
},
{
painter: "Manet",
title: "Olympia",
year: 1863
},
];
var not_hashable = [
{
car: "Ferrari",
model: "F10",
speed: 350,
},
{
car: "Fiat",
model: "500",
speed: 100,
},
{
car: "BMW",
model: "Z4",
speed: 250,
},
];
var weirdos = [
undefined,
null,
{},
function() {console.log('foo')},
{
a: undefined,
b: null,
c: {},
d: function() {console.log('foo')},
}];
var weirdos_import = [
{},
function() {console.log('foo')},
{
a: undefined,
b: null,
c: {},
d: function() {console.log('foo')},
}];
var weirdos_load = [
{},
{},
{
b: null,
c: {},
}];
// Cycles
var base_cycle = {
a: 1,
b: 2,
c: {a: 1,
b: {foo: 1},
},
};
var c1 = base_cycle;
var c2 = base_cycle;
// TODO: referencing the whole object does not work.
//c1.aa = base_cycle;
c2.ac = base_cycle.c;
c2.aa = base_cycle.b;
var cycles = [c1, c2];
var nitems = hashable.length + not_hashable.length;
var testcase = null;
var tmp = null;
var hashPainter = function(o) {
if (!o) return undefined;
return o.painter;
}
db.hash('painter', hashPainter);
var filename = './db.out';
var deleteIfExist = function(cb) {
if (JSUS.existsSync(filename)) {
fs.unlinkSync(filename);
}
if (cb) cb();
};
var flag = null;
var callback = function() {
flag = 1;
};
var testSaveLoad = function(items, compareToImport, compareToLoad) {
describe('#saveSync()', function() {
before(function() {
flag = null;
deleteIfExist(function() {
db2.clear(true);
db = new NDDB();
db.importDB(items);
db.saveSync(filename, callback);
});
});
after(function() {
flag = null;
});
it('should create a dump file', function() {
JSUS.existsSync(filename).should.be.true;
});
it('original database should be unchanged', function() {
if (compareToImport) {
JSUS.equals(db.db, compareToImport).should.be.true;
}
else {
db.db.should.be.eql(items);
}
});
it('should execute the callback', function() {
flag.should.eql(1);
});
});
describe('#loadSync()', function() {
before(function() {
flag = null;
db2.loadSync(filename, callback);
});
after(function() {
flag = null;
deleteIfExist();
});
it('the loaded database should be a copy of the saved one', function() {
if (compareToLoad) {
JSUS.equals(db2.db, compareToLoad).should.be.true;
}
else {
JSUS.equals(db.db, db2.db).should.be.true;
}
});
it('should execute the callback', function() {
flag.should.eql(1);
});
});
describe('#save()', function() {
before(function() {
flag = null;
deleteIfExist(function() {
db2.clear(true);
db = new NDDB();
db.importDB(items);
});
});
after(function() {
flag = null;
});
it('original database save database (cb executed)', function(done) {
db.save(filename, function() {
JSUS.existsSync(filename).should.be.true;
if (compareToImport) {
JSUS.equals(db.db, compareToImport).should.be.true;
}
else {
db.db.should.be.eql(items);
}
done();
});
});
});
describe('#load()', function() {
before(function() {
flag = null;
});
after(function() {
flag = null;
deleteIfExist();
});
it('the loaded database should be copy of saved one (cb executed)',
function(done) {
db2.load(filename, function() {
if (compareToLoad) {
JSUS.equals(db2.db, compareToLoad).should.be.true;
}
else {
JSUS.equals(db.db, db2.db).should.be.true;
}
done();
});
});
});
};
// STRESS TEST
//for (var i=0; i<1000; i++) {
describe('NDDB io operations.', function() {
describe('Cycle / Decycle.', function() {
describe('Not Hashable items', function() {
testSaveLoad(not_hashable);
});
describe('Hashable items.', function() {
testSaveLoad(hashable);
});
describe('Cycles items', function() {
testSaveLoad(cycles);
});
// describe('Weirdos items.', function() {
// testSaveLoadShould(weirdos, weirdos_import);
// });
});
describe('Without Cycle / Decycle.', function() {
before(function() {
delete JSON.decycle;
delete JSON.retrocycle;
});
describe('Not Hashable items', function() {
testSaveLoad(not_hashable);
});
describe('Hashable items.', function() {
testSaveLoad(hashable);
});
describe('Cycles items', function() {
testSaveLoad(cycles);
});
// describe('Weirdos items.', function() {
// testSaveLoad(weirdos, weirdos_import);
// });
});
});
// END STRESS
//}
|
"use strict";
var helpers = require("../../helpers/helpers");
exports["Asia/Vladivostok"] = {
"1922" : helpers.makeTestYear("Asia/Vladivostok", [
["1922-11-14T15:12:15+00:00", "23:59:59", "LMT", -31664 / 60],
["1922-11-14T15:12:16+00:00", "00:12:16", "VLAT", -540]
]),
"1930" : helpers.makeTestYear("Asia/Vladivostok", [
["1930-06-20T14:59:59+00:00", "23:59:59", "VLAT", -540],
["1930-06-20T15:00:00+00:00", "01:00:00", "VLAT", -600]
]),
"1981" : helpers.makeTestYear("Asia/Vladivostok", [
["1981-03-31T13:59:59+00:00", "23:59:59", "VLAT", -600],
["1981-03-31T14:00:00+00:00", "01:00:00", "VLAST", -660],
["1981-09-30T12:59:59+00:00", "23:59:59", "VLAST", -660],
["1981-09-30T13:00:00+00:00", "23:00:00", "VLAT", -600]
]),
"1982" : helpers.makeTestYear("Asia/Vladivostok", [
["1982-03-31T13:59:59+00:00", "23:59:59", "VLAT", -600],
["1982-03-31T14:00:00+00:00", "01:00:00", "VLAST", -660],
["1982-09-30T12:59:59+00:00", "23:59:59", "VLAST", -660],
["1982-09-30T13:00:00+00:00", "23:00:00", "VLAT", -600]
]),
"1983" : helpers.makeTestYear("Asia/Vladivostok", [
["1983-03-31T13:59:59+00:00", "23:59:59", "VLAT", -600],
["1983-03-31T14:00:00+00:00", "01:00:00", "VLAST", -660],
["1983-09-30T12:59:59+00:00", "23:59:59", "VLAST", -660],
["1983-09-30T13:00:00+00:00", "23:00:00", "VLAT", -600]
]),
"1984" : helpers.makeTestYear("Asia/Vladivostok", [
["1984-03-31T13:59:59+00:00", "23:59:59", "VLAT", -600],
["1984-03-31T14:00:00+00:00", "01:00:00", "VLAST", -660],
["1984-09-29T15:59:59+00:00", "02:59:59", "VLAST", -660],
["1984-09-29T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"1985" : helpers.makeTestYear("Asia/Vladivostok", [
["1985-03-30T15:59:59+00:00", "01:59:59", "VLAT", -600],
["1985-03-30T16:00:00+00:00", "03:00:00", "VLAST", -660],
["1985-09-28T15:59:59+00:00", "02:59:59", "VLAST", -660],
["1985-09-28T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"1986" : helpers.makeTestYear("Asia/Vladivostok", [
["1986-03-29T15:59:59+00:00", "01:59:59", "VLAT", -600],
["1986-03-29T16:00:00+00:00", "03:00:00", "VLAST", -660],
["1986-09-27T15:59:59+00:00", "02:59:59", "VLAST", -660],
["1986-09-27T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"1987" : helpers.makeTestYear("Asia/Vladivostok", [
["1987-03-28T15:59:59+00:00", "01:59:59", "VLAT", -600],
["1987-03-28T16:00:00+00:00", "03:00:00", "VLAST", -660],
["1987-09-26T15:59:59+00:00", "02:59:59", "VLAST", -660],
["1987-09-26T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"1988" : helpers.makeTestYear("Asia/Vladivostok", [
["1988-03-26T15:59:59+00:00", "01:59:59", "VLAT", -600],
["1988-03-26T16:00:00+00:00", "03:00:00", "VLAST", -660],
["1988-09-24T15:59:59+00:00", "02:59:59", "VLAST", -660],
["1988-09-24T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"1989" : helpers.makeTestYear("Asia/Vladivostok", [
["1989-03-25T15:59:59+00:00", "01:59:59", "VLAT", -600],
["1989-03-25T16:00:00+00:00", "03:00:00", "VLAST", -660],
["1989-09-23T15:59:59+00:00", "02:59:59", "VLAST", -660],
["1989-09-23T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"1990" : helpers.makeTestYear("Asia/Vladivostok", [
["1990-03-24T15:59:59+00:00", "01:59:59", "VLAT", -600],
["1990-03-24T16:00:00+00:00", "03:00:00", "VLAST", -660],
["1990-09-29T15:59:59+00:00", "02:59:59", "VLAST", -660],
["1990-09-29T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"1991" : helpers.makeTestYear("Asia/Vladivostok", [
["1991-03-30T15:59:59+00:00", "01:59:59", "VLAT", -600],
["1991-03-30T16:00:00+00:00", "02:00:00", "VLAST", -600],
["1991-09-28T16:59:59+00:00", "02:59:59", "VLAST", -600],
["1991-09-28T17:00:00+00:00", "02:00:00", "VLAT", -540]
]),
"1992" : helpers.makeTestYear("Asia/Vladivostok", [
["1992-01-18T16:59:59+00:00", "01:59:59", "VLAT", -540],
["1992-01-18T17:00:00+00:00", "03:00:00", "VLAT", -600],
["1992-03-28T12:59:59+00:00", "22:59:59", "VLAT", -600],
["1992-03-28T13:00:00+00:00", "00:00:00", "VLAST", -660],
["1992-09-26T11:59:59+00:00", "22:59:59", "VLAST", -660],
["1992-09-26T12:00:00+00:00", "22:00:00", "VLAT", -600]
]),
"1993" : helpers.makeTestYear("Asia/Vladivostok", [
["1993-03-27T15:59:59+00:00", "01:59:59", "VLAT", -600],
["1993-03-27T16:00:00+00:00", "03:00:00", "VLAST", -660],
["1993-09-25T15:59:59+00:00", "02:59:59", "VLAST", -660],
["1993-09-25T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"1994" : helpers.makeTestYear("Asia/Vladivostok", [
["1994-03-26T15:59:59+00:00", "01:59:59", "VLAT", -600],
["1994-03-26T16:00:00+00:00", "03:00:00", "VLAST", -660],
["1994-09-24T15:59:59+00:00", "02:59:59", "VLAST", -660],
["1994-09-24T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"1995" : helpers.makeTestYear("Asia/Vladivostok", [
["1995-03-25T15:59:59+00:00", "01:59:59", "VLAT", -600],
["1995-03-25T16:00:00+00:00", "03:00:00", "VLAST", -660],
["1995-09-23T15:59:59+00:00", "02:59:59", "VLAST", -660],
["1995-09-23T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"1996" : helpers.makeTestYear("Asia/Vladivostok", [
["1996-03-30T15:59:59+00:00", "01:59:59", "VLAT", -600],
["1996-03-30T16:00:00+00:00", "03:00:00", "VLAST", -660],
["1996-10-26T15:59:59+00:00", "02:59:59", "VLAST", -660],
["1996-10-26T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"1997" : helpers.makeTestYear("Asia/Vladivostok", [
["1997-03-29T15:59:59+00:00", "01:59:59", "VLAT", -600],
["1997-03-29T16:00:00+00:00", "03:00:00", "VLAST", -660],
["1997-10-25T15:59:59+00:00", "02:59:59", "VLAST", -660],
["1997-10-25T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"1998" : helpers.makeTestYear("Asia/Vladivostok", [
["1998-03-28T15:59:59+00:00", "01:59:59", "VLAT", -600],
["1998-03-28T16:00:00+00:00", "03:00:00", "VLAST", -660],
["1998-10-24T15:59:59+00:00", "02:59:59", "VLAST", -660],
["1998-10-24T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"1999" : helpers.makeTestYear("Asia/Vladivostok", [
["1999-03-27T15:59:59+00:00", "01:59:59", "VLAT", -600],
["1999-03-27T16:00:00+00:00", "03:00:00", "VLAST", -660],
["1999-10-30T15:59:59+00:00", "02:59:59", "VLAST", -660],
["1999-10-30T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"2000" : helpers.makeTestYear("Asia/Vladivostok", [
["2000-03-25T15:59:59+00:00", "01:59:59", "VLAT", -600],
["2000-03-25T16:00:00+00:00", "03:00:00", "VLAST", -660],
["2000-10-28T15:59:59+00:00", "02:59:59", "VLAST", -660],
["2000-10-28T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"2001" : helpers.makeTestYear("Asia/Vladivostok", [
["2001-03-24T15:59:59+00:00", "01:59:59", "VLAT", -600],
["2001-03-24T16:00:00+00:00", "03:00:00", "VLAST", -660],
["2001-10-27T15:59:59+00:00", "02:59:59", "VLAST", -660],
["2001-10-27T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"2002" : helpers.makeTestYear("Asia/Vladivostok", [
["2002-03-30T15:59:59+00:00", "01:59:59", "VLAT", -600],
["2002-03-30T16:00:00+00:00", "03:00:00", "VLAST", -660],
["2002-10-26T15:59:59+00:00", "02:59:59", "VLAST", -660],
["2002-10-26T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"2003" : helpers.makeTestYear("Asia/Vladivostok", [
["2003-03-29T15:59:59+00:00", "01:59:59", "VLAT", -600],
["2003-03-29T16:00:00+00:00", "03:00:00", "VLAST", -660],
["2003-10-25T15:59:59+00:00", "02:59:59", "VLAST", -660],
["2003-10-25T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"2004" : helpers.makeTestYear("Asia/Vladivostok", [
["2004-03-27T15:59:59+00:00", "01:59:59", "VLAT", -600],
["2004-03-27T16:00:00+00:00", "03:00:00", "VLAST", -660],
["2004-10-30T15:59:59+00:00", "02:59:59", "VLAST", -660],
["2004-10-30T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"2005" : helpers.makeTestYear("Asia/Vladivostok", [
["2005-03-26T15:59:59+00:00", "01:59:59", "VLAT", -600],
["2005-03-26T16:00:00+00:00", "03:00:00", "VLAST", -660],
["2005-10-29T15:59:59+00:00", "02:59:59", "VLAST", -660],
["2005-10-29T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"2006" : helpers.makeTestYear("Asia/Vladivostok", [
["2006-03-25T15:59:59+00:00", "01:59:59", "VLAT", -600],
["2006-03-25T16:00:00+00:00", "03:00:00", "VLAST", -660],
["2006-10-28T15:59:59+00:00", "02:59:59", "VLAST", -660],
["2006-10-28T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"2007" : helpers.makeTestYear("Asia/Vladivostok", [
["2007-03-24T15:59:59+00:00", "01:59:59", "VLAT", -600],
["2007-03-24T16:00:00+00:00", "03:00:00", "VLAST", -660],
["2007-10-27T15:59:59+00:00", "02:59:59", "VLAST", -660],
["2007-10-27T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"2008" : helpers.makeTestYear("Asia/Vladivostok", [
["2008-03-29T15:59:59+00:00", "01:59:59", "VLAT", -600],
["2008-03-29T16:00:00+00:00", "03:00:00", "VLAST", -660],
["2008-10-25T15:59:59+00:00", "02:59:59", "VLAST", -660],
["2008-10-25T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"2009" : helpers.makeTestYear("Asia/Vladivostok", [
["2009-03-28T15:59:59+00:00", "01:59:59", "VLAT", -600],
["2009-03-28T16:00:00+00:00", "03:00:00", "VLAST", -660],
["2009-10-24T15:59:59+00:00", "02:59:59", "VLAST", -660],
["2009-10-24T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"2010" : helpers.makeTestYear("Asia/Vladivostok", [
["2010-03-27T15:59:59+00:00", "01:59:59", "VLAT", -600],
["2010-03-27T16:00:00+00:00", "03:00:00", "VLAST", -660],
["2010-10-30T15:59:59+00:00", "02:59:59", "VLAST", -660],
["2010-10-30T16:00:00+00:00", "02:00:00", "VLAT", -600]
]),
"2011" : helpers.makeTestYear("Asia/Vladivostok", [
["2011-03-26T15:59:59+00:00", "01:59:59", "VLAT", -600],
["2011-03-26T16:00:00+00:00", "03:00:00", "VLAT", -660]
])
}; |
define('mp-01-web/tests/helpers/replace-app-ref', ['exports'], function (exports) {
exports['default'] = replaceAppRef;
/**
* Updates the supplied app adapter's Firebase reference.
*
* @param {!Ember.Application} app
* @param {!firebase.database.Reference} ref
* @param {string} [model] The model, if overriding a model specific adapter
*/
function replaceAppRef(app, ref) {
var model = arguments.length <= 2 || arguments[2] === undefined ? 'application' : arguments[2];
app.register('service:firebaseMock', ref, { instantiate: false, singleton: true });
app.inject('adapter:firebase', 'firebase', 'service:firebaseMock');
app.inject('adapter:' + model, 'firebase', 'service:firebaseMock');
}
}); |
'use strict';
// Use Applicaion configuration module to register a new module
ApplicationConfiguration.registerModule('core');
ApplicationConfiguration.registerModule('core.admin', ['core']);
ApplicationConfiguration.registerModule('core.admin.routes', ['ui.router']);
ApplicationConfiguration.registerModule('core');
ApplicationConfiguration.registerModule('core.user', ['core']);
ApplicationConfiguration.registerModule('core.user.routes', ['ui.router']);
|
var _clamp_8h =
[
[ "Clamp", "class_clamp.html", "class_clamp" ],
[ "_CLAMP_BRINGUP_", "_clamp_8h.html#ae642671ca8e1edb6d156e52a87e74b72", null ],
[ "_CLAMP_CATCH_", "_clamp_8h.html#aa9e63fe6512686d9104e7827aba7e306", null ],
[ "_CLAMP_INITIALISATION_", "_clamp_8h.html#a13c3227529e189a616e46167c98cb5c4", null ],
[ "_CLAMP_RELEASE_", "_clamp_8h.html#acf02a60a1d81665821c63eaba47e43d0", null ],
[ "_CLAMP_SENDADRESS_", "_clamp_8h.html#a1a570929553e5c9df1b3d805ebe678f6", null ]
]; |
function undef(x) {
return typeof x === 'undefined';
}
|
'use babel';
import ProjectRunner from '../lib/project-runner';
describe('ProjectRunner', () => {
let workspaceElement, activationPromise;
beforeEach(() => {
workspaceElement = atom.views.getView(atom.workspace);
activationPromise = atom.packages.activatePackage('project-runner');
});
describe('when the project-runner:run event is triggered', () => {
it('hides and shows the modal panel', () => {
atom.commands.dispatch(workspaceElement, 'project-runner:run');
waitsForPromise(() => {
return activationPromise;
});
runs(() => {
expect(workspaceElement.querySelector('.project-runner')).toExist();
let packageElement = workspaceElement.querySelector('.project-runner');
expect(packageElement).toExist();
let packagePanel = atom.workspace.panelForItem(packageElement);
expect(packagePanel.isVisible()).toBe(true);
atom.commands.dispatch(workspaceElement, 'project-runner:run');
expect(packagePanel.isVisible()).toBe(false);
});
});
it('hides and shows the view', () => {
jasmine.attachToDOM(workspaceElement);
atom.commands.dispatch(workspaceElement, 'project-runner:run');
waitsForPromise(() => {
return activationPromise;
});
runs(() => {
let packageElement = workspaceElement.querySelector('.project-runner');
expect(packageElement).toBeVisible();
atom.commands.dispatch(workspaceElement, 'project-runner:run');
expect(packageElement).not.toBeVisible();
});
});
});
});
|
CLASS.Stage = function () {
// Position
this.x = 0;
this.y = 0;
};
CLASS.Stage.append = {
/*
Clear everything that has been rendered.
*/
clear: function (context) {
context.clearRect(this.x, this.y, CONST.STAGE_WIDTH, CONST.STAGE_HEIGHT);
}
};
|
/* eslint-disable */
var path = require('path');
module.exports = {
devtool: 'eval',
entry: './app/index',
output: {
path: path.join(__dirname, 'app', 'static'),
filename: 'bundle.js',
publicPath: 'static/',
},
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
exclude: /node_modules/,
include: __dirname,
}],
},
devServer: {
// root folder to serve the app
contentBase: './app',
publicPath: '/static/',
// To support html5 router.
historyApiFallback: false,
// Suppress boring information.
noInfo: true,
// Proxy api to API Server
proxy: {
'/api/*': 'http://localhost:3000/',
},
// Limit logging
stats: {
version: false,
colors: true,
chunks: false,
children: false,
},
},
};
|
var gulp = require('gulp');
var gutil = require('gulp-util');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var jshint = require('gulp-jshint');
var minifyCSS = require('gulp-minify-css');
var browserify = require('browserify');
var transform = require('vinyl-transform');
var path = require('path');
var root = path.resolve(__dirname);
var assets = path.resolve(root, 'assets');
var vendor = path.resolve(assets, 'vendor');
// Default.
gulp.task('default', ['assetsApp', 'assetsAppReact', 'vendor']);
// Assets.
gulp.task('assetsApp', function() {
return gulp.src(assets + '/app/*.js')
.pipe(concat('app.js'))
.pipe(uglify())
.pipe(gulp.dest(root + '/web/js'));
});
// Assets.
gulp.task('assetsAppReact', function() {
var browserified = transform(function(filename) {
return browserify({
entries: filename,
insertGlobals: false,
extensions: ['.js'],
standalone: 'App'
})
.transform('reactify')
.bundle();
});
return gulp.src(assets + '/app_react/app.js')
.pipe(browserified)
.pipe(concat('app_react.js'))
.pipe(uglify())
.pipe(gulp.dest(root + '/web/js'));
});
// Watch.
gulp.task('watch', ['assetsApp', 'assetsAppReact'], function() {
gulp.watch(assets + '/app/*.js', ['assetsApp']);
gulp.watch(assets + '/app_react/**/*.js', ['assetsAppReact']);
});
// Vendor.
gulp.task('vendor', ['vendorJS', 'vendorCSS']);
// Vendor.
gulp.task('vendorJS', function() {
return gulp
.src([
vendor + '/jquery/dist/jquery.js',
vendor + '/URIjs/src/URI.js',
vendor + '/angular/angular.js',
vendor + '/angular-sanitize/angular-sanitize.js'
])
.pipe(concat('vendor.js'))
.pipe(uglify())
.pipe(gulp.dest(root + '/web/js'));
});
// Vendor.
gulp.task('vendorCSS', function() {
return gulp
.src([
vendor + '/bootstrap/dist/css/bootstrap.css'
])
.pipe(concat('vendor.css'))
.pipe(minifyCSS())
.pipe(gulp.dest(root + '/web/css'));
});
// Run jshint.
gulp.task('hint', function() {
return gulp.src([root + '/Gulpfile.js', assets + '/app/*.js'])
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
|
import Ember from 'ember';
/* globals FB */
var facebookScriptPromise;
export default Ember.Service.extend({
/*
* A tracking object implementing `shared(serviceName, payload)` and/or
* `clicked(serviceName, payload)` can be set on this object, and will
* be delegated to if present. Not all Facebook
* components support these events in all configurations.
*/
tracking: null, // optional injection
/*
* This is required for certain uses of plugins, e.g. when using tagName="a"
* for the facebook-share component.
*
* You can simply specify it in the handlebars when using this component, but this
* component will also look for a global FACEBOOK_APP_ID or a meta tag of the form:
*
* <meta property="fb:app_id" content="[FB_APP_ID]" />
*/
appId: function(){
return Ember.$("meta[property='fb:app_id']").attr('content') || window.FACEBOOK_APP_ID;
},
load: function() {
var self = this;
if (!facebookScriptPromise) {
facebookScriptPromise = new Ember.RSVP.Promise(function(resolve/*, reject*/) {
if (Ember.$('#fb-root').length === 0) {
Ember.$('body').append('<div id="fb-root"></div>');
}
window.fbAsyncInit = function() {
FB.init({
appId : self.appId(),
xfbml : true,
version : 'v2.1'
});
Ember.run(function(){
resolve(FB);
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
});
}
return facebookScriptPromise;
},
clicked: function(payload) {
var tracking = this.tracking;
if(!tracking) { return; }
if(tracking.clicked) {
tracking.clicked('facebook', payload);
}
},
shared: function(payload) {
var tracking = this.tracking;
if(!tracking) { return; }
if(tracking.shared) {
tracking.shared('facebook', payload);
}
}
});
|
function pageLoad() {
resize();
var hash = window.location.hash.substring(1);
if(hash != "") {
var iframe = document.getElementById("iframe").src = hash + ".html";
changeExample(hash);
} else {
var selected = document.getElementsByClassName("selected");
var iframe = document.getElementById("iframe").src = selected[0].id + ".html";
}
}
function resize() {
var content = document.getElementById("content");
content.style.width = window.innerWidth - 300 + "px";
// Adjust footer position if the content overflows
var menu = document.getElementById("menu");
if(menu.scrollHeight > menu.offsetHeight) {
var footer = document.getElementById("footer");
footer.style.position = "relative";
footer.style.bottom = "none";
var contentList = document.getElementById("content-list");
contentList.style.marginBottom = "20px";
} else {
var footer = document.getElementById("footer");
footer.style.position = "absolute";
footer.style.bottom = "0";
var contentList = document.getElementById("content-list");
contentList.style.marginBottom = "60px";
}
}
function changeExample(name) {
var iframe = document.getElementById("iframe").src = name + ".html";
var examples = document.getElementById("content-list").getElementsByTagName("a");
for(var i = 0; i < examples.length; i++) {
examples[i].className = "";
}
var ele = document.getElementById(name).className = "selected";
}
window.onresize = function(event) {
resize();
}; |
define(['utils', 'consts'], function(utils, consts) {
'use strict';
describe('Test Utils', function() {
beforeEach(function() {
this.body = consts.DOC.body;
this.utils = Object.create({
container: consts.DOC.createElement('div'),
gameContainer: consts.DOC.createElement('div')
});
this.utils.container.id = 'parentContainer';
this.utils.gameContainer.id = 'gameContainer';
// append to body
this.utils.container.appendChild(this.utils.gameContainer);
this.body.appendChild(this.utils.container);
});
afterEach(function() {
this.body = null;
this.utils = null;
});
// emptyContainer
it('Test emptyContainer method', function() {
var subDiv = consts.DOC.createElement('div');
subDiv.id = 'gameMenu';
this.utils.container.appendChild(subDiv);
expect(this.utils.container.childNodes.length).toBeGreaterThan(0);
expect(this.utils.container.childNodes[1].id).toBe('gameMenu');
utils.emptyContainer('parentContainer');
expect(this.utils.container.childNodes.length).toBeLessThan(1);
// remove subDiv
subDiv.remove();
});
// range
it('Test range method', function() {
var method = utils.range;
expect(method(0, 4, 0)).toEqual([0, 1, 2, 3, 4]);
expect(method(0, 4, 2)).toEqual([0, 2, 4]);
expect(method('a', 'e', 0)).toEqual(['A', 'B', 'C', 'D', 'E']);
});
// message
it('Test message method', function() {
// Green message
utils.message('green', 'Green message');
var messageGreenContainer = consts.DOC.getElementById('messageContainer');
expect(messageGreenContainer.className).toBe('messageGreen showMessage');
// Red message
utils.message('red', 'Red message');
var messageRedContainer = consts.DOC.getElementById('messageContainer');
expect(messageRedContainer.className).toBe('messageRed showMessage');
// remove messages
messageGreenContainer.remove();
messageRedContainer.remove();
});
// difference
it('Test diff method', function() {
var arr1 = [1, 2, 3],
arr2 = [2, 3, 4],
diff = utils.diff(arr1, arr2),
diff2 = utils.diff(arr1, arr1);
expect(diff).toEqual([1]);
expect(diff2).toEqual([]);
});
// tooltip
it('Test tooltip method', function() {
var element = consts.DOC.createElement('div'),
elementName = null;
element.id = 'testElement';
element.setAttribute('data-name', 'Battleship');
elementName = element.getAttribute('data-name');
this.utils.gameContainer.appendChild(element);
// show tooltip
utils.tooltip(element, elementName, true);
expect(consts.DOC.getElementById('shipTooltip')).toBeDefined();
expect(consts.DOC.getElementById('shipTooltip').className).toBe('show');
// hide tooltip
utils.tooltip(element, null, false);
expect(consts.DOC.getElementById('shipTooltip').className).toBe('hide');
// remove tooltip
consts.DOC.getElementById('shipTooltip').remove();
// remove element
element.remove();
});
// randomNumber
it('Test randomNumber method', function() {
let min = 1,
max = 5,
result = utils.randomNumber(min, max);
expect(result >= 1 && result <= 5).toBeTruthy();
});
// randomPosition
it('Test randomPosition method', function() {
let v = 'vertical',
h = 'horizontal',
result = utils.randomPosition();
expect(result === v || result === h).toBeTruthy();
});
});
});
|
/* global describe, beforeEach, module, inject, it, expect */
describe("JsonPrint", function() {
"use strict";
var $rootScope, $compile, JsonParser, json;
beforeEach(module('json-print'));
beforeEach(inject(function(_$rootScope_, _$compile_, _JsonParser_) {
$rootScope = _$rootScope_;
$compile = _$compile_;
JsonParser = _JsonParser_;
json = {
"firstName": "John",
"lastName": "Smith",
"age": 25,
"money": -5000,
"hope": 0,
"married": false,
"children": null,
"lonely": true,
"html": "<p>This <br> is a paragraph <br> with <br> line breaks</p>",
"something": [
"else",
true,
12345,
{
"prop": false
}
],
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumber": [
{
"type": "home",
"number": "212 555-1239"
},
{
"type": "fax",
"number": "646 555-4567"
}
],
"gender":{
"type":"male"
}
};
}));
describe('Service', function() {
describe('Weaknesses', function() {
/**
* This is a weakness in the regex-patterns, which I've been unable to solve.
* See test case for 'print'.
*/
it('breaks on un-indented JSON-strings', function() {
expect(JSON.stringify(json).match(JsonParser.patterns.string)).toEqual(null);
});
});
describe("Patterns", function() {
it('should find strings', function() {
var result,
str = JSON.stringify(json, null, 1),
strings = [
'"John"', '"Smith"', '"<p>This <br> is a paragraph <br> with <br> line breaks</p>"',
'"else"', '"21 2nd Street"', '"New York"', '"NY"', '"home"', '"212 555-1239"', '"fax"',
'"646 555-4567"', '"male"'
];
while((result = JsonParser.patterns.string.exec(str)) !== null) {
expect(strings).toContain(result[1]);
}
});
it('should find properties', function() {
var result = JSON.stringify(json, null, 1).match(JsonParser.patterns.prop);
expect(result).toEqual([ '"firstName"', '"lastName"', '"age"', '"money"', '"hope"', '"married"', '"children"',
'"lonely"', '"html"', '"something"', '"prop"', '"address"', '"streetAddress"', '"city"', '"state"',
'"postalCode"', '"phoneNumber"', '"type"', '"number"', '"type"', '"number"', '"gender"', '"type"' ]);
});
it("should find booleans", function() {
var result = JSON.stringify(json, null, 1).match(JsonParser.patterns.bool);
expect(result).toEqual(['false', 'true', 'true', 'false']);
});
it('should find nulls', function() {
var result = JSON.stringify(json, null, 1).match(JsonParser.patterns.null);
expect(result).toEqual(['null']);
});
it('should find numbers', function() {
var result = JSON.stringify(json, null, 1).match(JsonParser.patterns.number);
expect(result).toEqual(['25', '-5000', '0', '12345', '10021']);
});
it('should find objects', function() {
var result = JSON.stringify(json, null, 1).match(JsonParser.patterns.object);
expect(result).toEqual(['{', '{', '}', '{', '}', '{', '}', '{', '}', '{', '}', '}']);
});
it('should find arrays', function() {
var result = JSON.stringify(json, null, 1).match(JsonParser.patterns.array);
expect(result).toEqual(['[', ']', '[', ']']);
});
});
describe('Replacers', function() {
describe('number', function() {
it('should recognize zero', function() {
expect(JsonParser.replacers.number(0)).toContain('zero');
});
it('should recognize positive numbers', function() {
expect(JsonParser.replacers.number(1)).toContain('plus');
});
it('should recognize negative numbers', function() {
expect(JsonParser.replacers.number(-1)).toContain('minus');
});
});
describe('string', function() {
it('should escape any HTML-brackets', function() {
expect(JsonParser.replacers.string('"html": "<p>Some HTML</p>"', '<p>Some HTML</p>'))
.toContain('<p>Some HTML</p>');
});
});
});
describe('print', function() {
it('should always return indented JSON, see Weaknesses', function() {
expect(JSON.stringify(json)).not.toContain("\n");
expect(JsonParser.print(json)).toContain("\n");
expect(JsonParser.print(json, 0)).toContain("\n");
expect(JsonParser.print(json, -1)).toContain("\n");
expect(JsonParser.print(json, 1)).toContain("\n");
});
it('should do nothing on missing input, to avoid clearing the view', function() {
expect(JsonParser.print()).toEqual(undefined);
});
});
describe('objectify', function() {
it('should return JSON-objects unharmed', function() {
expect(JsonParser.objectify(json)).toEqual(json);
});
it('should objectify valid JSON-strings', function() {
expect(JsonParser.objectify(JSON.stringify(json))).toEqual(json);
});
it('should return null on an invalid JSON-string', function() {
expect(JsonParser.objectify(JSON.stringify(json).slice(0, -1))).toEqual(null);
});
});
});
describe('Directive', function() {
var $scope;
beforeEach(function() {
$scope = $rootScope.$new();
$scope.json = json;
$scope.jsonStr = JSON.stringify(json);
$scope.undef = undefined;
$scope.null = null;
$scope.empty = '';
});
it('should treat string and object sources equally', function() {
var elem = $compile('<pre data-json-print="json"></pre>')($scope);
var strElem = $compile('<pre data-json-print="jsonStr"></pre>')($scope);
$scope.$digest();
expect(elem.html()).toEqual(strElem.html());
});
it('should print a load of json if given an valid input', function() {
var elem = $compile('<pre data-json-print="json"></pre>')($scope);
$scope.$digest();
expect(elem.html()).toContain('<span class="json-print-string">"Smith"</span>');
expect(elem.html()).toContain('<span class="json-print-prop">"lastName"</span>: ');
expect(elem.html()).toContain('<span class="json-print-number json-print-plus">12345</span>,');
expect(elem.html()).toContain('<span class="json-print-bool json-print-true">true</span>,');
expect(elem.html()).toContain('<span class="json-print-object">}</span>,');
expect(elem.html()).toContain('<span class="json-print-array">]</span>,');
expect(elem.html()).toContain('<span class="json-print-string">"21 2nd Street"</span>,');
});
it('should not clear the current content if given invalid JSON', function() {
var strElem = $compile('<pre data-json-print="jsonStr"></pre>')($scope);
$scope.$digest();
expect(strElem.html()).toContain('<span class="json-print-string">"Smith"</span>');
$scope.jsonStr = null;
$scope.$digest();
expect(strElem.html()).toContain('<span class="json-print-string">"Smith"</span>');
});
it('it should print nothing, without warning, on undefined, null or empty input', function() {
var undefElem = $compile('<pre data-json-print="undef"></pre>')($scope);
$scope.$digest();
expect(undefElem.html()).toEqual('');
var nullElem = $compile('<pre data-json-print="null"></pre>')($scope);
$scope.$digest();
expect(nullElem.html()).toEqual('');
var emptyElem = $compile('<pre data-json-print="empty"></pre>')($scope);
$scope.$digest();
expect(emptyElem.html()).toEqual('');
});
});
});
|
import React from 'react';
import ReactDOM from 'react-dom';
import Router from 'react-router';
import routes from './routes';
import createBrowserHistory from 'history/lib/createBrowserHistory';
let history = createBrowserHistory();
/**客户端渲染react**/
ReactDOM.render(<Router history={history}>{routes}</Router>,document.getElementById('app'));
|
/* global QUnit */
import { runStdGeometryTests } from '../../utils/qunit-utils';
import { BoxGeometry, BoxBufferGeometry } from '../../../../src/geometries/BoxGeometry';
export default QUnit.module( 'Geometries', () => {
QUnit.module( 'BoxGeometry', ( hooks ) => {
var geometries = undefined;
hooks.beforeEach( function () {
const parameters = {
width: 10,
height: 20,
depth: 30,
widthSegments: 2,
heightSegments: 3,
depthSegments: 4
};
geometries = [
new BoxGeometry(),
new BoxGeometry( parameters.width, parameters.height, parameters.depth ),
new BoxGeometry( parameters.width, parameters.height, parameters.depth, parameters.widthSegments, parameters.heightSegments, parameters.depthSegments ),
new BoxBufferGeometry()
];
} );
// INHERITANCE
QUnit.todo( 'Extending', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
// INSTANCING
QUnit.todo( 'Instancing', ( assert ) => {
assert.ok( false, 'everything\'s gonna be alright' );
} );
// OTHERS
QUnit.test( 'Standard geometry tests', ( assert ) => {
runStdGeometryTests( assert, geometries );
} );
} );
} );
|
/**
* This module bundles all routing related code.
*
* - Set the document title by the current route.
* - Provide router guards for some components.
*
* @module @bldr/lamp/routing
*/
/**
* The route object of the Vue Router package.
*
* @see {@link https://router.vuejs.org/api/#the-route-object Vue Router Api documentation}
*
* @typedef route
*/
/**
* An instance of the Vue Router.
*
* @see {@link https://router.vuejs.org/api/#router-construction-options Vue Router Api documentation}
*
* @typedef router
*/
/**
* A Vue instance. A Vue instance is essentially a ViewModel as defined in the
* MVVM pattern, hence the variable name `vm` you will see throughout the docs.
*
* @see {@link https://v1.vuejs.org/guide/instance.html}
*
* @typedef vm
*/
/**
* Routes can be divided into two categories: A public route (visible for
* the audience) and speaker router (visible only for the speaker). Possible
* values: `public` or `speaker`.
*
* @typedef {string} view
*/
import { masterCollection } from '@bldr/lamp-core'
import { shortenText } from '@bldr/core-browser'
import store from '@/store/index.js'
import { router } from '@/routes'
/* globals document gitHead compilationTime */
/**
* Set the document title by the current route.
*
* @param {module:@bldr/lamp/routing/route} route
*/
function setDocumentTitleByRoute (route) {
const slide = store.getters['lamp/slide']
const presentation = store.getters['lamp/presentation']
const getBuildTimeTitle = function () {
const buildTime = new Date(compilationTime).toLocaleString()
let lastCommit = gitHead.short
if (gitHead.dirty) {
lastCommit = `${lastCommit}-dirty`
}
return `Baldr Lamp (${buildTime} ${lastCommit})`
}
let title
if (slide && slide.title && (route.name === 'slide' || route.name === 'slide-step-no')) {
title = `Nr. ${slide.no} [${slide.master.title}]: ${slide.title} (${presentation.title})`
} else if (route.name === 'home') {
title = getBuildTimeTitle()
} else if (route.meta && route.meta.title) {
title = route.meta.title
} else {
title = getBuildTimeTitle()
}
document.title = shortenText(title, { stripTags: true, maxLength: 125 })
}
/**
* @param {module:@bldr/lamp/routing~route} router
*/
export function installDocumentTitleUpdater (router) {
router.afterEach((to, from) => {
setDocumentTitleByRoute(to)
})
}
/**
* @type {Object}
*/
export const routerViews = {
public: {
slideNo: 'slide',
stepNo: 'slide-step-no'
},
speaker: {
slideNo: 'speaker-view',
stepNo: 'speaker-view-step-no'
}
}
/**
*
* @param {module:@bldr/lamp/routing.routerViews} routerViews
*/
function generateCounterParts (routerViews) {
const counterParts = {}
for (const viewName in routerViews) {
if (viewName === 'public') {
counterParts[routerViews[viewName].slideNo] = routerViews.speaker.slideNo
counterParts[routerViews[viewName].stepNo] = routerViews.speaker.stepNo
} else {
counterParts[routerViews[viewName].slideNo] = routerViews.public.slideNo
counterParts[routerViews[viewName].stepNo] = routerViews.public.stepNo
}
}
return counterParts
}
// const publicRouteNames = Object.values(routerViews.public)
const speakerRouteNames = Object.values(routerViews.speaker)
const counterParts = generateCounterParts(routerViews)
/**
* @param {module:@bldr/lamp/routing~route} route
*/
function isSpeakerRoute (route) {
return speakerRouteNames.includes(route.name)
}
/**
* If the route is `public` turn it into `speaker` and vice versa.
*
* @param {module:@bldr/lamp/routing~route} route
*
* @returns {Object} A deep copy of the route object.
*/
export function switchRouterView (route) {
const newRoute = {}
newRoute.name = counterParts[route.name]
newRoute.params = Object.assign({}, route.params)
newRoute.query = Object.assign({}, route.query)
return newRoute
}
/**
* @returns {module:@bldr/lamp/routing~view}
*/
export function getViewFromRoute () {
const name = router.currentRoute.name
if (name === 'speaker-view' || name === 'speaker-view-step-no') {
return 'speaker'
}
return 'public'
}
/**
* @param {module:@bldr/lamp/routing~vm} vm
* @param {String} presRef - Presentation ID.
*/
async function loadPresentationById (vm, presRef) {
vm.$media.player.stop()
vm.$store.dispatch('media/clear')
vm.$store.commit('lamp/setPresentation', null)
// EP: Example
if (presRef.match(/^EP_.*$/)) {
// master example
const masterMatch = presRef.match(/^EP_master_(.*)$/)
if (masterMatch) {
const masterName = masterMatch[1]
const master = masterCollection.get(masterName)
await vm.$store.dispatch('lamp/openPresentation', { vm, rawYamlString: master.example })
return
}
// common example
const commonMatch = presRef.match(/^EP_common_(.*)$/)
if (commonMatch) {
const commonName = commonMatch[1]
await vm.$store.dispatch('lamp/openPresentation', {
vm,
rawYamlString: vm.$store.getters['lamp/rawYamlExamples'].common[commonName]
})
return
}
}
await vm.$store.dispatch('lamp/openPresentationById', { vm, presRef })
}
/**
* Load presentation and set navigation list numbers.
*
* @param {module:@bldr/lamp/routing~vm} vm
* @param {module:@bldr/lamp/routing~route} route
*/
async function loadPresentationByRoute (vm, route) {
try {
if (route.params.presRef) {
const presentation = vm.$store.getters['lamp/presentation']
if (!presentation || (presentation && presentation.ref !== route.params.presRef)) {
await loadPresentationById(vm, route.params.presRef)
}
if (route.params.slideNo) {
if (route.params.stepNo) route.params.stepNo = parseInt(route.params.stepNo)
vm.$store.dispatch('lamp/nav/setNavListNosByRoute', route)
}
}
} catch (error) {
vm.$showMessage.error(error)
}
}
/**
* @param {module:@bldr/lamp/routing~vm} vm
* @param {module:@bldr/lamp/routing~route} route
*/
async function actOnRouteChange (vm, route) {
await loadPresentationByRoute(vm, route)
if (isSpeakerRoute(route)) {
const publicRoute = switchRouterView(route)
vm.$socket.sendObj({ route: publicRoute })
}
}
/**
* Router guards for some components which can be accessed by router links.
* This components use the router guards:
*
* - `SlidePreview`
* - `SlideView`
* - `SpeakerView`
*/
export const routerGuards = {
// To be able to enter a presentation per HTTP link on a certain slide.
// Without this hook there are webpack errors.
beforeRouteEnter (to, from, next) {
next(vm => {
actOnRouteChange(vm, to)
})
},
// To be able to navigate throught the slide (only the params) are changing.
beforeRouteUpdate (to, from, next) {
actOnRouteChange(this, to)
// To update the URL in the browser URL textbox.
next()
}
}
|
/*!
* EJS - Filters
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* First element of the target `obj`.
*/
exports.first = function(obj) {
return obj[0];
};
/**
* Last element of the target `obj`.
*/
exports.last = function(obj) {
return obj[obj.length - 1];
};
/**
* Capitalize the first letter of the target `str`.
*/
exports.capitalize = function(str){
str = String(str);
return str[0].toUpperCase() + str.substr(1, str.length);
};
/**
* Downcase the target `str`.
*/
exports.downcase = function(str){
return String(str).toLowerCase();
};
/**
* Uppercase the target `str`.
*/
exports.upcase = function(str){
return String(str).toUpperCase();
};
/**
* Sort the target `obj`.
*/
exports.sort = function(obj){
return Object.create(obj).sort();
};
/**
* Sort the target `obj` by the given `prop` ascending.
*/
exports.sort_by = function(obj, prop){
return Object.create(obj).sort(function(a, b){
a = a[prop], b = b[prop];
if (a > b) return 1;
if (a < b) return -1;
return 0;
});
};
/**
* Size or length of the target `obj`.
*/
exports.size = exports.length = function(obj) {
return obj.length;
};
/**
* Add `a` and `b`.
*/
exports.plus = function(a, b){
return Number(a) + Number(b);
};
/**
* Subtract `b` from `a`.
*/
exports.minus = function(a, b){
return Number(a) - Number(b);
};
/**
* Multiply `a` by `b`.
*/
exports.times = function(a, b){
return Number(a) * Number(b);
};
/**
* Divide `a` by `b`.
*/
exports.divided_by = function(a, b){
return Number(a) / Number(b);
};
/**
* Join `obj` with the given `str`.
*/
exports.join = function(obj, str){
return obj.join(str || ', ');
};
/**
* Truncate `str` to `len`.
*/
exports.truncate = function(str, len){
str = String(str);
return str.substr(0, len);
};
/**
* Truncate `str` to `n` words.
*/
exports.truncate_words = function(str, n){
var str = String(str)
, words = str.split(/ +/);
return words.slice(0, n).join(' ');
};
/**
* Replace `pattern` with `substitution` in `str`.
*/
exports.replace = function(str, pattern, substitution){
return String(str).replace(pattern, substitution || '');
};
/**
* Prepend `val` to `obj`.
*/
exports.prepend = function(obj, val){
return Array.isArray(obj)
? [val].concat(obj)
: val + obj;
};
/**
* Append `val` to `obj`.
*/
exports.append = function(obj, val){
return Array.isArray(obj)
? obj.concat(val)
: obj + val;
};
/**
* Map the given `prop`.
*/
exports.map = function(arr, prop){
return arr.map(function(obj){
return obj[prop];
});
};
/**
* Reverse the given `obj`.
*/
exports.reverse = function(obj){
return Array.isArray(obj)
? obj.reverse()
: String(obj).split('').reverse().join('');
};
/**
* Get `prop` of the given `obj`.
*/
exports.get = function(obj, prop){
return obj[prop];
};
/**
* Packs the given `obj` into json string
*/
exports.json = function(obj){
return JSON.stringify(obj);
}; |
'use strict';
angular.module('calendarApp', ['ngMaterial', 'ui.router'])
.config(function($urlRouterProvider, $mdThemingProvider){
$urlRouterProvider
.otherwise('/');
$mdThemingProvider.theme('default')
.primaryPalette('indigo')
.accentPalette('lime');
}); |
(function ($) {
$.fn.ThemeColorPicker = function() {
var target = $(this);
/*
target.colorpicker().on('changeColor', function (event){
target.find('input').val(event.color.toHex());
});
*/
target.colorpicker().on('show', function (event){
//alert('1');
//event.color.setColor('#ffffff');
target.colorpicker( 'setValue', target.find('input').val() );
//alert('2');
});
return this;
};
}(jQuery));
|
var flyd = require('../../../lib');
var stream = flyd.stream;
var dropRepeats = require('../').dropRepeats;
var dropRepeatsWith = require('../').dropRepeatsWith;
var R = require('ramda');
var assert = require('assert');
var collect = flyd.scan(R.flip(R.append), []);
describe('dropRepeats', function() {
it('drops consecutive repeated values', function() {
var s = stream();
var all = collect(dropRepeats(s));
s(1)(2)(2)(3);
assert.deepEqual(all(), [1, 2, 3]);
});
it('doesn\'t determine equality by value', function() {
var s = stream();
var all = collect(dropRepeats(s));
s({ foo: 'bar' });
s({ foo: 'bar' });
assert.deepEqual(all(), [
{ foo: 'bar' },
{ foo: 'bar' },
]);
});
});
describe('dropRepeatsWith', function() {
it('takes a function for using custom equality logic', function() {
var s = stream();
var all = collect(dropRepeatsWith(R.equals, s));
s({ foo: 'bar' });
s({ foo: 'bar' });
assert.deepEqual(all(), [
{ foo: 'bar' }
]);
});
it('is curried', function() {
var s = stream();
var equalsDropper = dropRepeatsWith(R.equals);
var all = collect(equalsDropper(s));
s({ foo: 'bar' });
s({ foo: 'bar' });
assert.deepEqual(all(), [
{ foo: 'bar' }
]);
});
});
|
import React from 'react';
import { connect } from 'react-redux';
import config from '../config';
import actions from '../actions';
import { classNames } from '../utillities';
import BlockUser from '../components/components.block-user';
class ChatSettings extends React.Component {
constructor(props) {
super(props);
this.state = {
search: false,
query: '',
selectedUsers: [],
};
}
componentWillMount() {
if (!this.props.contactsState.receivedAt) {
this.props.fetchContacts();
}
}
render() {
let groupName,
participants,
container,
heading,
icon,
styles,
input;
groupName = this.props.groupName ? this.props.groupName : 'Group name';
participants = renderParticipants(this.props);
if (this.props.participants.length === 0) {
heading = 'Tap on the right icon above to start adding participants.';
} else {
heading = 'Participants';
}
if (!!this.props.groupImage) {
styles = { backgroundImage: `url(${ this.props.groupImage })` };
} else {
icon = (
<span className="c-banner__icon"><i className="icon-image"></i></span>
);
}
if (!!this.state.search) {
input = (
<div className="s-block-actions__input">
<article className="c-input-group">
<button className="c-input-group__addon" onClick={ this.hideSearch.bind(this) }>
<i className="icon-close"></i>
</button>
<input type="text"
className="c-input-group__field"
placeholder="Add participants"
onKeyUp={ this.onKeyUp.bind(this) }
ref={ input => this.participantsInput = input } />
<button className="c-input-group__addon submit" onClick={ this.addParticipants.bind(this) }><i className="icon-group-add"></i></button>
</article>
</div>
);
container = (
this.getContacts().map((user, index) => {
return (
<BlockUser
key={ index }
id={ user.id}
name={ user.firstName }
description={ user.description }
lastMessage={ user.lastMessage }
image={ user.image }
lastSeenAt={ user.lastSeenAt }
lastMessageAt={ user.lastMessageAt }
unreadMessagesCount={ user.unreadMessagesCount }
isActive={ this.state.selectedUsers.indexOf(user) >= 0 }
onClick={ () => this.toggleUserSelection(user) }
/>
);
})
);
} else {
container = (
<div>
<article className="c-banner" style={ styles }>
<h1 className="c-banner__title">{ groupName }</h1>
{ icon }
</article>
<h2 className="s-chat-settings__heading">{ heading }</h2>
{ participants }
</div>
);
}
return (
<section className={ classNames('s-chat-settings', {'state-new': !this.props.chat}) }>
<div className="s-chat-settings__inner">
<section className="s-block-actions">
<nav className="s-block-actions__nav">
<ul>
<li>
<button className="sign-out" onClick={ this.leaveGroup.bind(this) }>
<i className="icon-sign-out"></i>
<span>Leave group</span>
</button>
</li>
<li>
<button onClick={ this.editGroupName.bind(this) }>
<i className="icon-pencil"></i>
</button>
</li>
<li>
<input type='file' id='file' accept='image/*'
onChange={this.updateGroupImage.bind(this)} />
<label htmlFor='file'>
<i className="icon-image"></i>
</label>
</li>
<li>
<button onClick={ this.showSearch.bind(this) }>
<i className="icon-group-add"></i>
</button>
</li>
</ul>
{ input }
</nav>
</section>
{ container }
</div>
</section>
);
}
onKeyUp() {
this.setState({
query: this.participantsInput.value,
});
}
toggleUserSelection(user) {
let selectedUsers = this.state.selectedUsers.slice();
if ( selectedUsers.indexOf(user) >= 0 ) {
selectedUsers.splice(selectedUsers.indexOf(user), 1);
} else {
selectedUsers.push(user);
}
this.setState({selectedUsers});
}
getContacts() {
const contacts = this.props.contactsState.contacts;
delete contacts[this.props.meState.me.id];
return Object.keys(contacts).map((id) => contacts[id]).filter((contact) => {
let fullName = `${contact.firstName} ${contact.lastName}`;
return (this.state.selectedUsers.indexOf(contact) >= 0) ||
(fullName.toLowerCase().indexOf(this.state.query.toLowerCase()) >= 0);
});
}
addParticipants() {
this.props.update({'participants': this.state.selectedUsers});
this.hideSearch();
}
leaveGroup() {
this.props.leave();
}
editGroupName() {
this.props.update({'groupName': prompt('Group name')});
}
updateGroupImage(event) {
this.props.update({'groupImage': event.target.files[0]});
}
showSearch() {
this.setState({
search: true,
});
}
hideSearch() {
this.setState({
search: false,
query: '',
});
}
}
ChatSettings.propTypes = {
groupName: React.PropTypes.string,
groupImage: React.PropTypes.string,
participants: React.PropTypes.array,
update: React.PropTypes.func,
leave: React.PropTypes.func,
};
function renderParticipants(props) {
if (props.participants.length > 0) {
return props.participants.map(p => props.contactsState.contacts[p.id])
.filter(x => x)
.map((user, index) => (
<BlockUser
key={ index }
name={ user.firstName }
description={ user.description }
imageSource={ user.imageSource }
lastSeenDate={ user.lastSeenDate }
openChat={ () => props.openChat(user.id) }
/>
));
} else {
return [];
}
}
const mapStateToProps = (state, ownProps) => state[config.stateName];
const mapDispatchToProps = (dispatch, ownProps) => {
return {
fetchContacts: () => {
dispatch(actions.contacts.fetchContacts());
},
};
};
const ChatSettingsConnect = connect(mapStateToProps, mapDispatchToProps)(ChatSettings);
export default ChatSettingsConnect;
|
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {StyleSheet, TouchableOpacity, Image, Text, View} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
class CounterView extends Component {
static displayName = 'CounterView';
static navigationOptions = {
title: 'Counter',
tabBarIcon: (props) => (
<Icon name="plus-one" size={24} color={props.tintColor} />
),
};
static propTypes = {
counter: PropTypes.number.isRequired,
userName: PropTypes.string,
userProfilePhoto: PropTypes.string,
loading: PropTypes.bool.isRequired,
counterStateActions: PropTypes.shape({
increment: PropTypes.func.isRequired,
reset: PropTypes.func.isRequired,
random: PropTypes.func.isRequired,
}).isRequired,
navigate: PropTypes.func.isRequired,
};
increment = () => {
this.props.counterStateActions.increment();
};
reset = () => {
this.props.counterStateActions.reset();
};
random = () => {
this.props.counterStateActions.random();
};
bored = () => {
this.props.navigate({routeName: 'Color'});
};
renderUserInfo = () => {
if (!this.props.userName) {
return null;
}
return (
<View style={styles.userContainer}>
<Image
style={styles.userProfilePhoto}
source={{
uri: this.props.userProfilePhoto,
width: 80,
height: 80,
}}
/>
<Text style={styles.linkButton}>Welcome, {this.props.userName}!</Text>
</View>
);
};
render() {
const loadingStyle = this.props.loading ? {backgroundColor: '#eee'} : null;
return (
<View style={styles.container}>
{this.renderUserInfo()}
<TouchableOpacity
accessible={true}
accessibilityLabel={'Increment counter'}
onPress={this.increment}
style={[styles.counterButton, loadingStyle]}>
<Text style={styles.counter}>{this.props.counter}</Text>
</TouchableOpacity>
<TouchableOpacity
accessible={true}
accessibilityLabel={'Reset counter'}
onPress={this.reset}>
<Text style={styles.linkButton}>Reset</Text>
</TouchableOpacity>
<TouchableOpacity
accessible={true}
accessibilityLabel={'Randomize counter'}
onPress={this.random}>
<Text style={styles.linkButton}>Random</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.bored} accessible={true}>
<Text style={styles.linkButton}>{"I'm bored!"}</Text>
</TouchableOpacity>
</View>
);
}
}
const circle = {
borderWidth: 0,
borderRadius: 40,
width: 80,
height: 80,
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white',
},
userContainer: {
justifyContent: 'center',
alignItems: 'center',
},
userProfilePhoto: {
...circle,
alignSelf: 'center',
},
counterButton: {
...circle,
backgroundColor: '#349d4a',
alignItems: 'center',
justifyContent: 'center',
margin: 20,
},
counter: {
color: 'white',
fontSize: 20,
textAlign: 'center',
},
welcome: {
textAlign: 'center',
color: 'black',
marginBottom: 5,
padding: 5,
},
linkButton: {
textAlign: 'center',
color: '#CCCCCC',
marginBottom: 10,
padding: 5,
},
});
export default CounterView;
|
import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import {store} from '../store';
import {HoverButton} from './HoverButton';
import Radium from 'radium';
const divStyle = {
fontSize: '25px',
marginLeft: '20px',
marginRight: '20px',
marginBottom: '20px',
};
const imageStyle = {
};
const textStyle = {
};
@Radium
export class MenuButton extends React.Component {
render() {
return (
<div style={divStyle}>
<img style={imageStyle} src={this.props.img}/>
<div style={textStyle}> {this.props.text} </div>
</div>
);
}
}
|
var test = require('tape');
var mobx = require('..');
test('spy output', t => {
var events = [];
var stop = mobx.spy(c => events.push(c));
doStuff();
stop();
doStuff();
events.forEach(ev => { delete ev.object; delete ev.fn; delete ev.time; });
t.equal(events.length, doStuffEvents.length, "amount of events doesn't match");
//t.deepEqual(events, doStuffEvents);
events.forEach((ev, idx) => {
t.deepEqual(ev, doStuffEvents[idx], "expected event #" + (1 + idx) + " to be equal");
});
t.ok(events.filter(ev => ev.spyReportStart === true).length > 0, "spy report start count should be larger then zero");
t.equal(
events.filter(ev => ev.spyReportStart === true).length,
events.filter(ev => ev.spyReportEnd === true).length,
"amount of start and end events differs"
);
t.end();
})
function doStuff() {
var a = mobx.observable(2);
a.set(3);
var b = mobx.observable({
c: 4
});
b.c = 5;
mobx.extendObservable(b, { d: 6 });
b.d = 7;
var e = mobx.observable([1, 2]);
e.push(3, 4);
e.shift();
e[2] = 5;
var f = mobx.map({ g: 1 });
f.delete("h");
f.delete("g");
f.set("i", 5);
f.set("i", 6);
var j = mobx.computed(() => a.get() * 2);
var stop = mobx.autorun(() => { j.get() });
a.set(4);
mobx.transaction(function myTransaction() {
a.set(5);
a.set(6);
});
mobx.action("myTestAction", (newValue) => {
a.set(newValue)
})(7);
}
const doStuffEvents = [
{ newValue: 2, type: 'create' },
{ newValue: 3, oldValue: 2, type: 'update', spyReportStart: true },
{ spyReportEnd: true },
{ name: 'c', newValue: 4, spyReportStart: true, type: 'add' },
{ spyReportEnd: true },
{ name: 'c', newValue: 5, oldValue: 4, spyReportStart: true, type: 'update' },
{ spyReportEnd: true },
{ name: 'd', newValue: 6, spyReportStart: true, type: 'add' },
{ spyReportEnd: true },
{ name: 'd', newValue: 7, oldValue: 6, spyReportStart: true, type: 'update' },
{ spyReportEnd: true },
{ added: [ 1, 2 ], addedCount: 2, index: 0, removed: [], removedCount: 0, spyReportStart: true, type: 'splice' },
{ spyReportEnd: true },
{ added: [ 3, 4 ], addedCount: 2, index: 2, removed: [], removedCount: 0, spyReportStart: true, type: 'splice' },
{ spyReportEnd: true },
{ added: [], addedCount: 0, index: 0, removed: [ 1 ], removedCount: 1, spyReportStart: true, type: 'splice' },
{ spyReportEnd: true },
{ index: 2, newValue: 5, oldValue: 4, spyReportStart: true, type: 'update' },
{ spyReportEnd: true },
{ name: 'g', newValue: 1, spyReportStart: true, type: 'add' },
{ spyReportEnd: true },
{ name: 'g', oldValue: 1, spyReportStart: true, type: 'delete' },
{ spyReportEnd: true },
{ name: 'i', newValue: 5, spyReportStart: true, type: 'add' },
{ spyReportEnd: true },
{ name: 'i', newValue: 6, oldValue: 5, spyReportStart: true, type: 'update' },
{ spyReportEnd: true },
{ spyReportStart: true, type: 'reaction' },
{ target: undefined, type: 'compute' },
{ spyReportEnd: true },
{ newValue: 4, oldValue: 3, spyReportStart: true, type: 'update' },
{ target: undefined, type: 'compute' },
{ spyReportStart: true, type: 'reaction' },
{ spyReportEnd: true },
{ spyReportEnd: true },
{ name: 'myTransaction', spyReportStart: true, target: undefined, type: 'transaction' },
{ newValue: 5, oldValue: 4, spyReportStart: true, type: 'update' },
{ spyReportEnd: true },
{ newValue: 6, oldValue: 5, spyReportStart: true, type: 'update' },
{ spyReportEnd: true },
{ target: undefined, type: 'compute' },
{ spyReportStart: true, type: 'reaction' },
{ spyReportEnd: true },
{ spyReportEnd: true },
{ name: 'myTestAction', spyReportStart: true, arguments: [7], type: 'action', target: undefined },
{ newValue: 7, oldValue: 6, spyReportStart: true, type: 'update' },
{ spyReportEnd: true },
{ target: undefined, type: 'compute' },
{ spyReportStart: true, type: 'reaction' },
{ spyReportEnd: true },
{ spyReportEnd: true }
] |
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import { hbs } from 'ember-cli-htmlbars';
module('Integration | Component | animated if', function (hooks) {
setupRenderingTest(hooks);
test('it renders when true', async function (assert) {
this.set('x', true);
await render(hbs`
{{#animated-if this.x}}
<div class="truthy"></div>
{{/animated-if}}
`);
assert.ok(this.element.querySelector('.truthy'));
});
test('it does not render when false', async function (assert) {
await render(hbs`
{{#animated-if this.x}}
<div class="truthy"></div>
{{/animated-if}}
`);
assert.notOk(this.element.querySelector('.truthy'));
});
test('it renders inverse block when false', async function (assert) {
await render(hbs`
{{#animated-if this.x}}
<div class="truthy"></div>
{{else}}
<div class="falsey"></div>
{{/animated-if}}
`);
assert.ok(this.element.querySelector('.falsey'));
});
});
|
var Vue = require('src')
var _ = Vue.util
describe('v-for + ref', function () {
var el
beforeEach(function () {
el = document.createElement('div')
})
it('normal', function (done) {
var vm = new Vue({
el: el,
data: { items: [1, 2, 3, 4, 5] },
template: '<test v-for="item in items" :item="item" v-ref:test></test>',
components: {
test: {
props: ['item']
}
}
})
expect(vm.$refs.test).toBeTruthy()
expect(Array.isArray(vm.$refs.test)).toBe(true)
expect(vm.$refs.test[0].item).toBe(1)
expect(vm.$refs.test[4].item).toBe(5)
vm.items = []
_.nextTick(function () {
expect(vm.$refs.test.length).toBe(0)
vm._directives[0].unbind()
expect(vm.$refs.test).toBeNull()
done()
})
})
it('object', function (done) {
var vm = new Vue({
el: el,
data: {
items: {
a: 1,
b: 2
}
},
template: '<test v-for="item in items" :item="item" v-ref:test></test>',
components: {
test: {
props: ['item']
}
}
})
expect(vm.$refs.test).toBeTruthy()
expect(_.isPlainObject(vm.$refs.test)).toBe(true)
expect(vm.$refs.test.a.item).toBe(1)
expect(vm.$refs.test.b.item).toBe(2)
vm.items = { c: 3 }
_.nextTick(function () {
expect(Object.keys(vm.$refs.test).length).toBe(1)
expect(vm.$refs.test.c.item).toBe(3)
vm._directives[0].unbind()
expect(vm.$refs.test).toBeNull()
done()
})
})
it('nested', function () {
var vm = new Vue({
el: el,
template: '<c1 v-ref:c1></c1>',
components: {
c1: {
template: '<div v-for="n in 2" v-ref:c2></div>'
}
}
})
expect(vm.$refs.c1 instanceof Vue).toBe(true)
expect(vm.$refs.c2).toBeUndefined()
expect(Array.isArray(vm.$refs.c1.$refs.c2)).toBe(true)
expect(vm.$refs.c1.$refs.c2.length).toBe(2)
})
})
|
var _ = require('underscore');
var FormView = require('./__FormView'),
$ = require('jquery'),
Backbone = require('backbone'),
goodsTpl = require('../templates/_entityGoods.tpl');
var config = require('../conf');
Backbone.$ = $;
//** 模型
var Goods = Backbone.Model.extend({
idAttribute: '_id',
urlRoot: config.api.host + '/protect/goods',
defaults: {
},
validation: {
'name': {
minLength: 2,
msg:'长度至少两位'
},
'barcode': {
required: true,
msg: '请输入运营商系统的业务编码'
},
'smscode': {
min: 0,
max: 99999999,
msg:'请输入八位以内的数字'
},
'packagecode': {
pattern: /^(p\d*k\d*e\d*){1,}/,
msg: '格式不对:p{package_id}k{package_id}e{element_id},多个以|分开'
}
},
});
//** 主页面
exports = module.exports = FormView.extend({
el: '#goodsForm',
modelFilled: false,
initialize: function(options) {
this.router = options.router;
this.model = new Goods({_id: options.id});
var page = $(goodsTpl);
var editTemplate = $('#editTemplate', page).html();
this.template = _.template(_.unescape(editTemplate || ''));
FormView.prototype.initialize.apply(this, options);
},
events: {
'keyup input[type=text]': 'inputText',
'submit form': 'submit',
'click .back': 'cancel',
},
load: function(){
if(this.model.isNew()){
this.modelFilled = true;
return;
}
this.model.fetch({
xhrFields: {
withCredentials: true
},
});
},
inputText: function(evt){
var that = this;
//clear error
this.$(evt.currentTarget).parent().removeClass('has-error');
this.$(evt.currentTarget).parent().find('span.help-block').empty();
var arr = this.$(evt.currentTarget).serializeArray();
_.each(arr,function(obj){
var error = that.model.preValidate(obj.name,obj.value);
if(error){
//set error
this.$(evt.currentTarget).parent().addClass('has-error');
this.$(evt.currentTarget).parent().find('span.help-block').text(error);
}
})
return false;
},
submit: function() {
var that = this;
//clear errors
this.$('.form-group').removeClass('has-error');
this.$('.form-group').find('span.help-block').empty();
var arr = this.$('form').serializeArray();
var errors = [];
_.each(arr,function(obj){
var error = that.model.preValidate(obj.name,obj.value);
if(error){
errors.push(error);
that.$('[name="' + obj.name + '"]').parent().addClass('has-error');
that.$('[name="' + obj.name + '"]').parent().find('span.help-block').text(error);
}
});
if(!_.isEmpty(errors)) return false;
//validate finished.
var object = this.$('form').serializeJSON();
this.model.set(object);
// console.log(this.model.attributes);
this.model.save(null, {
xhrFields: {
withCredentials: true
},
});
return false;
},
cancel: function(){
this.router.navigate('goods/index',{trigger: true, replace: true});
return false;
},
//fetch event: done
done: function(response){
var that = this;
if(!this.modelFilled){
//first fetch: get model
this.modelFilled = true;
this.render();
}else{
//second fetch: submit
this.router.navigate('goods/index',{trigger: true, replace: true});
}
},
render: function(){
this.$el.html(this.template({model: this.model.toJSON()}));
if(this.model.isNew()){
this.$('.panel-title').text('新增物料');
}
var category = this.model.get('category');
this.$(('input[name=category][value='+ category +']')).attr('checked',true)
var scope = this.model.get('scope');
this.$(('input[name=scope][value='+ scope +']')).attr('checked',true)
var paymenttype = this.model.get('paymenttype');
if(paymenttype){
this.$('input[name=paymenttype][value='+ paymenttype +']').attr('checked',true);
}
var status = this.model.get('status');
if(status){
this.$('input[name=status][value='+ status +']').attr('checked',true);
}
return this;
},
}); |
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h(h.f, null, h("circle", {
cx: "9",
cy: "12",
r: "8"
}), h("path", {
d: "M17 4.26v2.09c2.33.82 4 3.04 4 5.65s-1.67 4.83-4 5.65v2.09c3.45-.89 6-4.01 6-7.74s-2.55-6.85-6-7.74z"
})), 'FiberSmartRecord'); |
var searchData=
[
['alreadyauthenticated',['AlreadyAuthenticated',['../../../../daonet/documentation/html/class_dao_net_1_1_error.html#a56778e707b6eaaf6b7691d2f0caece44af8cd39c387f4df976dd6b000dfa5bbab',1,'DaoNet::Error']]],
['authenticating',['Authenticating',['../../../../daonet/documentation/html/class_dao_net_1_1_dao_access.html#a097058769337d1e5557cad4b4a0a320baedb214653d9f3cecd840463790ac2894',1,'DaoNet::DaoAccess']]],
['authentication',['Authentication',['../../../../daonet/documentation/html/class_dao_net_1_1_constants.html#ab42bd20684d72789016773d02188f92bac75f7811d70d17dbcd88e9d03752cbed',1,'DaoNet::Constants']]],
['authenticationack',['AuthenticationAck',['../../../../daonet/documentation/html/class_dao_net_1_1_constants.html#ab42bd20684d72789016773d02188f92ba415655b31d2c4135848777340a53fb05',1,'DaoNet::Constants']]]
];
|
var count = 0;
function cc(card) {
// Only change code below this line
switch(card) {
case 2:
case 3:
case 4:
case 5:
case 6:
count++;
break;
case 10:
case "J":
case "Q":
case "K":
case "A":
count--;
break;
}
if(count > 0)
return count + " Bet";
return count + " Hold";
// Only change code above this line
}
// Add/remove calls to test your function.
// Note: Only the last will display
cc(2); cc(3); cc(7); cc('K'); cc('A'); |
'use strict';
/* eslint-disable no-script-url */
describe('$compile', function() {
var document = window.document;
function isUnknownElement(el) {
return !!el.toString().match(/Unknown/);
}
function isSVGElement(el) {
return !!el.toString().match(/SVG/);
}
function isHTMLElement(el) {
return !!el.toString().match(/HTML/);
}
function supportsMathML() {
var d = document.createElement('div');
d.innerHTML = '<math></math>';
return !isUnknownElement(d.firstChild);
}
// IE9-11 do not support foreignObject in svg...
function supportsForeignObject() {
var d = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject');
return !!d.toString().match(/SVGForeignObject/);
}
function getChildScopes(scope) {
var children = [];
if (!scope.$$childHead) { return children; }
var childScope = scope.$$childHead;
do {
children.push(childScope);
children = children.concat(getChildScopes(childScope));
} while ((childScope = childScope.$$nextSibling));
return children;
}
var element, directive, $compile, $rootScope;
beforeEach(module(provideLog, function($provide, $compileProvider) {
element = null;
directive = $compileProvider.directive;
directive('log', function(log) {
return {
restrict: 'CAM',
priority:0,
compile: valueFn(function(scope, element, attrs) {
log(attrs.log || 'LOG');
})
};
});
directive('highLog', function(log) {
return { restrict: 'CAM', priority:3, compile: valueFn(function(scope, element, attrs) {
log(attrs.highLog || 'HIGH');
})};
});
directive('mediumLog', function(log) {
return { restrict: 'CAM', priority:2, compile: valueFn(function(scope, element, attrs) {
log(attrs.mediumLog || 'MEDIUM');
})};
});
directive('greet', function() {
return { restrict: 'CAM', priority:10, compile: valueFn(function(scope, element, attrs) {
element.text('Hello ' + attrs.greet);
})};
});
directive('set', function() {
return function(scope, element, attrs) {
element.text(attrs.set);
};
});
directive('mediumStop', valueFn({
priority: 2,
terminal: true
}));
directive('stop', valueFn({
terminal: true
}));
directive('negativeStop', valueFn({
priority: -100, // even with negative priority we still should be able to stop descend
terminal: true
}));
directive('svgContainer', function() {
return {
template: '<svg width="400" height="400" ng-transclude></svg>',
replace: true,
transclude: true
};
});
directive('svgCustomTranscludeContainer', function() {
return {
template: '<svg width="400" height="400"></svg>',
transclude: true,
link: function(scope, element, attr, ctrls, $transclude) {
var futureParent = element.children().eq(0);
$transclude(function(clone) {
futureParent.append(clone);
}, futureParent);
}
};
});
directive('svgCircle', function() {
return {
template: '<circle cx="2" cy="2" r="1"></circle>',
templateNamespace: 'svg',
replace: true
};
});
directive('myForeignObject', function() {
return {
template: '<foreignObject width="100" height="100" ng-transclude></foreignObject>',
templateNamespace: 'svg',
replace: true,
transclude: true
};
});
return function(_$compile_, _$rootScope_) {
$rootScope = _$rootScope_;
$compile = _$compile_;
};
}));
function compile(html) {
element = angular.element(html);
$compile(element)($rootScope);
}
afterEach(function() {
dealoc(element);
});
describe('configuration', function() {
it('should allow aHrefSanitizationWhitelist to be configured', function() {
module(function($compileProvider) {
expect($compileProvider.aHrefSanitizationWhitelist()).toEqual(/^\s*(https?|ftp|mailto|tel|file):/); // the default
$compileProvider.aHrefSanitizationWhitelist(/other/);
expect($compileProvider.aHrefSanitizationWhitelist()).toEqual(/other/);
});
inject();
});
it('should allow debugInfoEnabled to be configured', function() {
module(function($compileProvider) {
expect($compileProvider.debugInfoEnabled()).toBe(true); // the default
$compileProvider.debugInfoEnabled(false);
expect($compileProvider.debugInfoEnabled()).toBe(false);
});
inject();
});
it('should allow preAssignBindingsEnabled to be configured', function() {
module(function($compileProvider) {
expect($compileProvider.preAssignBindingsEnabled()).toBe(false); // the default
$compileProvider.preAssignBindingsEnabled(true);
expect($compileProvider.preAssignBindingsEnabled()).toBe(true);
$compileProvider.preAssignBindingsEnabled(false);
expect($compileProvider.preAssignBindingsEnabled()).toBe(false);
});
inject();
});
it('should allow onChangesTtl to be configured', function() {
module(function($compileProvider) {
expect($compileProvider.onChangesTtl()).toBe(10); // the default
$compileProvider.onChangesTtl(2);
expect($compileProvider.onChangesTtl()).toBe(2);
});
inject();
});
it('should allow commentDirectivesEnabled to be configured', function() {
module(function($compileProvider) {
expect($compileProvider.commentDirectivesEnabled()).toBe(true); // the default
$compileProvider.commentDirectivesEnabled(false);
expect($compileProvider.commentDirectivesEnabled()).toBe(false);
});
inject();
});
it('should allow cssClassDirectivesEnabled to be configured', function() {
module(function($compileProvider) {
expect($compileProvider.cssClassDirectivesEnabled()).toBe(true); // the default
$compileProvider.cssClassDirectivesEnabled(false);
expect($compileProvider.cssClassDirectivesEnabled()).toBe(false);
});
inject();
});
it('should register a directive', function() {
module(function() {
directive('div', function(log) {
return {
restrict: 'ECA',
link: function(scope, element) {
log('OK');
element.text('SUCCESS');
}
};
});
});
inject(function($compile, $rootScope, log) {
element = $compile('<div></div>')($rootScope);
expect(element.text()).toEqual('SUCCESS');
expect(log).toEqual('OK');
});
});
it('should allow registration of multiple directives with same name', function() {
module(function() {
directive('div', function(log) {
return {
restrict: 'ECA',
link: {
pre: log.fn('pre1'),
post: log.fn('post1')
}
};
});
directive('div', function(log) {
return {
restrict: 'ECA',
link: {
pre: log.fn('pre2'),
post: log.fn('post2')
}
};
});
});
inject(function($compile, $rootScope, log) {
element = $compile('<div></div>')($rootScope);
expect(log).toEqual('pre1; pre2; post2; post1');
});
});
it('should throw an exception if a directive is called "hasOwnProperty"', function() {
module(function() {
expect(function() {
directive('hasOwnProperty', function() { });
}).toThrowMinErr('ng','badname', 'hasOwnProperty is not a valid directive name');
});
inject(function($compile) {});
});
it('should throw an exception if a directive name starts with a non-lowercase letter', function() {
module(function() {
expect(function() {
directive('BadDirectiveName', function() { });
}).toThrowMinErr('$compile','baddir', 'Directive/Component name \'BadDirectiveName\' is invalid. The first character must be a lowercase letter');
});
inject(function($compile) {});
});
it('should throw an exception if a directive name has leading or trailing whitespace', function() {
module(function() {
function assertLeadingOrTrailingWhitespaceInDirectiveName(name) {
expect(function() {
directive(name, function() { });
}).toThrowMinErr(
'$compile','baddir', 'Directive/Component name \'' + name + '\' is invalid. ' +
'The name should not contain leading or trailing whitespaces');
}
assertLeadingOrTrailingWhitespaceInDirectiveName(' leadingWhitespaceDirectiveName');
assertLeadingOrTrailingWhitespaceInDirectiveName('trailingWhitespaceDirectiveName ');
assertLeadingOrTrailingWhitespaceInDirectiveName(' leadingAndTrailingWhitespaceDirectiveName ');
});
inject(function($compile) {});
});
it('should throw an exception if the directive name is not defined', function() {
module(function() {
expect(function() {
directive();
}).toThrowMinErr('ng','areq');
});
inject(function($compile) {});
});
it('should throw an exception if the directive factory is not defined', function() {
module(function() {
expect(function() {
directive('myDir');
}).toThrowMinErr('ng','areq');
});
inject(function($compile) {});
});
it('should preserve context within declaration', function() {
module(function() {
directive('ff', function(log) {
var declaration = {
restrict: 'E',
template: function() {
log('ff template: ' + (this === declaration));
},
compile: function() {
log('ff compile: ' + (this === declaration));
return function() {
log('ff post: ' + (this === declaration));
};
}
};
return declaration;
});
directive('fff', function(log) {
var declaration = {
restrict: 'E',
link: {
pre: function() {
log('fff pre: ' + (this === declaration));
},
post: function() {
log('fff post: ' + (this === declaration));
}
}
};
return declaration;
});
directive('ffff', function(log) {
var declaration = {
restrict: 'E',
compile: function() {
return {
pre: function() {
log('ffff pre: ' + (this === declaration));
},
post: function() {
log('ffff post: ' + (this === declaration));
}
};
}
};
return declaration;
});
directive('fffff', function(log) {
var declaration = {
restrict: 'E',
templateUrl: function() {
log('fffff templateUrl: ' + (this === declaration));
return 'fffff.html';
},
link: function() {
log('fffff post: ' + (this === declaration));
}
};
return declaration;
});
});
inject(function($compile, $rootScope, $templateCache, log) {
$templateCache.put('fffff.html', '');
$compile('<ff></ff>')($rootScope);
$compile('<fff></fff>')($rootScope);
$compile('<ffff></ffff>')($rootScope);
$compile('<fffff></fffff>')($rootScope);
$rootScope.$digest();
expect(log).toEqual(
'ff template: true; ' +
'ff compile: true; ' +
'ff post: true; ' +
'fff pre: true; ' +
'fff post: true; ' +
'ffff pre: true; ' +
'ffff post: true; ' +
'fffff templateUrl: true; ' +
'fffff post: true'
);
});
});
});
describe('svg namespace transcludes', function() {
var ua = window.navigator.userAgent;
var isEdge = /Edge/.test(ua);
// this method assumes some sort of sized SVG element is being inspected.
function assertIsValidSvgCircle(elem) {
expect(isUnknownElement(elem)).toBe(false);
expect(isSVGElement(elem)).toBe(true);
var box = elem.getBoundingClientRect();
expect(box.width === 0 && box.height === 0).toBe(false);
}
it('should handle transcluded svg elements', inject(function($compile) {
element = jqLite('<div><svg-container>' +
'<circle cx="4" cy="4" r="2"></circle>' +
'</svg-container></div>');
$compile(element.contents())($rootScope);
document.body.appendChild(element[0]);
var circle = element.find('circle');
assertIsValidSvgCircle(circle[0]);
}));
it('should handle custom svg elements inside svg tag', inject(function() {
element = jqLite('<div><svg width="300" height="300">' +
'<svg-circle></svg-circle>' +
'</svg></div>');
$compile(element.contents())($rootScope);
document.body.appendChild(element[0]);
var circle = element.find('circle');
assertIsValidSvgCircle(circle[0]);
}));
it('should handle transcluded custom svg elements', inject(function() {
element = jqLite('<div><svg-container>' +
'<svg-circle></svg-circle>' +
'</svg-container></div>');
$compile(element.contents())($rootScope);
document.body.appendChild(element[0]);
var circle = element.find('circle');
assertIsValidSvgCircle(circle[0]);
}));
if (supportsForeignObject()) {
it('should handle foreignObject', inject(function() {
element = jqLite('<div><svg-container>' +
'<foreignObject width="100" height="100"><div class="test" style="position:absolute;width:20px;height:20px">test</div></foreignObject>' +
'</svg-container></div>');
$compile(element.contents())($rootScope);
document.body.appendChild(element[0]);
var testElem = element.find('div');
expect(isHTMLElement(testElem[0])).toBe(true);
var bounds = testElem[0].getBoundingClientRect();
expect(bounds.width === 20 && bounds.height === 20).toBe(true);
}));
it('should handle custom svg containers that transclude to foreignObject that transclude html', inject(function() {
element = jqLite('<div><svg-container>' +
'<my-foreign-object><div class="test" style="width:20px;height:20px">test</div></my-foreign-object>' +
'</svg-container></div>');
$compile(element.contents())($rootScope);
document.body.appendChild(element[0]);
var testElem = element.find('div');
expect(isHTMLElement(testElem[0])).toBe(true);
var bounds = testElem[0].getBoundingClientRect();
expect(bounds.width === 20 && bounds.height === 20).toBe(true);
}));
// NOTE: This test may be redundant.
// Support: Edge 14+
// An `<svg>` element inside a `<foreignObject>` element on MS Edge has no
// size, causing the included `<circle>` element to also have no size and thus fails an
// assertion (relying on the element having a non-zero size).
if (!isEdge) {
it('should handle custom svg containers that transclude to foreignObject' +
' that transclude to custom svg containers that transclude to custom elements', inject(function() {
element = jqLite('<div><svg-container>' +
'<my-foreign-object><svg-container><svg-circle></svg-circle></svg-container></my-foreign-object>' +
'</svg-container></div>');
$compile(element.contents())($rootScope);
document.body.appendChild(element[0]);
var circle = element.find('circle');
assertIsValidSvgCircle(circle[0]);
}));
}
}
it('should handle directives with templates that manually add the transclude further down', inject(function() {
element = jqLite('<div><svg-custom-transclude-container>' +
'<circle cx="2" cy="2" r="1"></circle></svg-custom-transclude-container>' +
'</div>');
$compile(element.contents())($rootScope);
document.body.appendChild(element[0]);
var circle = element.find('circle');
assertIsValidSvgCircle(circle[0]);
}));
it('should support directives with SVG templates and a slow url ' +
'that are stamped out later by a transcluding directive', function() {
module(function() {
directive('svgCircleUrl', valueFn({
replace: true,
templateUrl: 'template.html',
templateNamespace: 'SVG'
}));
});
inject(function($compile, $rootScope, $httpBackend) {
$httpBackend.expect('GET', 'template.html').respond('<circle></circle>');
element = $compile('<svg><g ng-repeat="l in list"><svg-circle-url></svg-circle-url></g></svg>')($rootScope);
// initially the template is not yet loaded
$rootScope.$apply(function() {
$rootScope.list = [1];
});
expect(element.find('svg-circle-url').length).toBe(1);
expect(element.find('circle').length).toBe(0);
// template is loaded and replaces the existing nodes
$httpBackend.flush();
expect(element.find('svg-circle-url').length).toBe(0);
expect(element.find('circle').length).toBe(1);
// new entry should immediately use the loaded template
$rootScope.$apply(function() {
$rootScope.list.push(2);
});
expect(element.find('svg-circle-url').length).toBe(0);
expect(element.find('circle').length).toBe(2);
});
});
});
describe('compile phase', function() {
it('should attach scope to the document node when it is compiled explicitly', inject(function($document) {
$compile($document)($rootScope);
expect($document.scope()).toBe($rootScope);
}));
it('should not wrap root text nodes in spans', function() {
element = jqLite(
'<div> <div>A</div>\n ' +
'<div>B</div>C\t\n ' +
'</div>');
$compile(element.contents())($rootScope);
var spans = element.find('span');
expect(spans.length).toEqual(0);
});
it('should be able to compile text nodes at the root', inject(function($rootScope) {
element = jqLite('<div>Name: {{name}}<br />\nColor: {{color}}</div>');
$rootScope.name = 'Lucas';
$rootScope.color = 'blue';
$compile(element.contents())($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('Name: Lucas\nColor: blue');
}));
it('should not leak memory when there are top level empty text nodes', function() {
// We compile the contents of element (i.e. not element itself)
// Then delete these contents and check the cache has been reset to zero
// First with only elements at the top level
element = jqLite('<div><div></div></div>');
$compile(element.contents())($rootScope);
element.empty();
expect(jqLiteCacheSize()).toEqual(0);
// Next with non-empty text nodes at the top level
// (in this case the compiler will wrap them in a <span>)
element = jqLite('<div>xxx</div>');
$compile(element.contents())($rootScope);
element.empty();
expect(jqLiteCacheSize()).toEqual(0);
// Next with comment nodes at the top level
element = jqLite('<div><!-- comment --></div>');
$compile(element.contents())($rootScope);
element.empty();
expect(jqLiteCacheSize()).toEqual(0);
// Finally with empty text nodes at the top level
element = jqLite('<div> \n<div></div> </div>');
$compile(element.contents())($rootScope);
element.empty();
expect(jqLiteCacheSize()).toEqual(0);
});
it('should not blow up when elements with no childNodes property are compiled', inject(
function($compile, $rootScope) {
// it turns out that when a browser plugin is bound to a DOM element (typically <object>),
// the plugin's context rather than the usual DOM apis are exposed on this element, so
// childNodes might not exist.
element = jqLite('<div>{{1+2}}</div>');
try {
element[0].childNodes[1] = {nodeType: 3, nodeName: 'OBJECT', textContent: 'fake node'};
} catch (e) { /* empty */ }
if (!element[0].childNodes[1]) return; // browser doesn't support this kind of mocking
expect(element[0].childNodes[1].textContent).toBe('fake node');
$compile(element)($rootScope);
$rootScope.$apply();
// object's children can't be compiled in this case, so we expect them to be raw
expect(element.html()).toBe('3');
}));
it('should detect anchor elements with the string "SVG" in the `href` attribute as an anchor', inject(function($compile, $rootScope) {
element = jqLite('<div><a href="/ID_SVG_ID">' +
'<span ng-if="true">Should render</span>' +
'</a></div>');
$compile(element.contents())($rootScope);
$rootScope.$digest();
document.body.appendChild(element[0]);
expect(element.find('span').text()).toContain('Should render');
}));
describe('multiple directives per element', function() {
it('should allow multiple directives per element', inject(function($compile, $rootScope, log) {
element = $compile(
'<span greet="angular" log="L" x-high-log="H" data-medium-log="M"></span>')($rootScope);
expect(element.text()).toEqual('Hello angular');
expect(log).toEqual('L; M; H');
}));
it('should recurse to children', inject(function($compile, $rootScope) {
element = $compile('<div>0<a set="hello">1</a>2<b set="angular">3</b>4</div>')($rootScope);
expect(element.text()).toEqual('0hello2angular4');
}));
it('should allow directives in classes', inject(function($compile, $rootScope, log) {
element = $compile('<div class="greet: angular; log:123;"></div>')($rootScope);
expect(element.html()).toEqual('Hello angular');
expect(log).toEqual('123');
}));
it('should allow directives in SVG element classes', inject(function($compile, $rootScope, log) {
if (!window.SVGElement) return;
element = $compile('<svg><text class="greet: angular; log:123;"></text></svg>')($rootScope);
var text = element.children().eq(0);
// In old Safari, SVG elements don't have innerHTML, so element.html() won't work
// (https://bugs.webkit.org/show_bug.cgi?id=136903)
expect(text.text()).toEqual('Hello angular');
expect(log).toEqual('123');
}));
it('should ignore not set CSS classes on SVG elements', inject(function($compile, $rootScope, log) {
if (!window.SVGElement) return;
// According to spec SVG element className property is readonly, but only FF
// implements it this way which causes compile exceptions.
element = $compile('<svg><text>{{1}}</text></svg>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('1');
}));
it('should receive scope, element, and attributes', function() {
var injector;
module(function() {
directive('log', function($injector, $rootScope) {
injector = $injector;
return {
restrict: 'CA',
compile: function(element, templateAttr) {
expect(typeof templateAttr.$normalize).toBe('function');
expect(typeof templateAttr.$set).toBe('function');
expect(isElement(templateAttr.$$element)).toBeTruthy();
expect(element.text()).toEqual('unlinked');
expect(templateAttr.exp).toEqual('abc');
expect(templateAttr.aa).toEqual('A');
expect(templateAttr.bb).toEqual('B');
expect(templateAttr.cc).toEqual('C');
return function(scope, element, attr) {
expect(element.text()).toEqual('unlinked');
expect(attr).toBe(templateAttr);
expect(scope).toEqual($rootScope);
element.text('worked');
};
}
};
});
});
inject(function($rootScope, $compile, $injector) {
element = $compile(
'<div class="log" exp="abc" aa="A" x-Bb="B" daTa-cC="C">unlinked</div>')($rootScope);
expect(element.text()).toEqual('worked');
expect(injector).toBe($injector); // verify that directive is injectable
});
});
});
describe('error handling', function() {
it('should handle exceptions', function() {
module(function($exceptionHandlerProvider) {
$exceptionHandlerProvider.mode('log');
directive('factoryError', function() { throw 'FactoryError'; });
directive('templateError',
valueFn({ compile: function() { throw 'TemplateError'; } }));
directive('linkingError',
valueFn(function() { throw 'LinkingError'; }));
});
inject(function($rootScope, $compile, $exceptionHandler) {
element = $compile('<div factory-error template-error linking-error></div>')($rootScope);
expect($exceptionHandler.errors[0]).toEqual('FactoryError');
expect($exceptionHandler.errors[1][0]).toEqual('TemplateError');
expect(ie($exceptionHandler.errors[1][1])).
toEqual('<div factory-error linking-error template-error>');
expect($exceptionHandler.errors[2][0]).toEqual('LinkingError');
expect(ie($exceptionHandler.errors[2][1])).
toEqual('<div class="ng-scope" factory-error linking-error template-error>');
// crazy stuff to make IE happy
function ie(text) {
var list = [],
parts, elementName;
parts = lowercase(text).
replace('<', '').
replace('>', '').
split(' ');
elementName = parts.shift();
parts.sort();
parts.unshift(elementName);
forEach(parts, function(value) {
if (value.substring(0,2) !== 'ng') {
value = value.replace('=""', '');
var match = value.match(/=(.*)/);
if (match && match[1].charAt(0) !== '"') {
value = value.replace(/=(.*)/, '="$1"');
}
list.push(value);
}
});
return '<' + list.join(' ') + '>';
}
});
});
it('should allow changing the template structure after the current node', function() {
module(function() {
directive('after', valueFn({
compile: function(element) {
element.after('<span log>B</span>');
}
}));
});
inject(function($compile, $rootScope, log) {
element = jqLite('<div><div after>A</div></div>');
$compile(element)($rootScope);
expect(element.text()).toBe('AB');
expect(log).toEqual('LOG');
});
});
it('should allow changing the template structure after the current node inside ngRepeat', function() {
module(function() {
directive('after', valueFn({
compile: function(element) {
element.after('<span log>B</span>');
}
}));
});
inject(function($compile, $rootScope, log) {
element = jqLite('<div><div ng-repeat="i in [1,2]"><div after>A</div></div></div>');
$compile(element)($rootScope);
$rootScope.$digest();
expect(element.text()).toBe('ABAB');
expect(log).toEqual('LOG; LOG');
});
});
it('should allow modifying the DOM structure in post link fn', function() {
module(function() {
directive('removeNode', valueFn({
link: function($scope, $element) {
$element.remove();
}
}));
});
inject(function($compile, $rootScope) {
element = jqLite('<div><div remove-node></div><div>{{test}}</div></div>');
$rootScope.test = 'Hello';
$compile(element)($rootScope);
$rootScope.$digest();
expect(element.children().length).toBe(1);
expect(element.text()).toBe('Hello');
});
});
});
describe('compiler control', function() {
describe('priority', function() {
it('should honor priority', inject(function($compile, $rootScope, log) {
element = $compile(
'<span log="L" x-high-log="H" data-medium-log="M"></span>')($rootScope);
expect(log).toEqual('L; M; H');
}));
});
describe('terminal', function() {
it('should prevent further directives from running', inject(function($rootScope, $compile) {
element = $compile('<div negative-stop><a set="FAIL">OK</a></div>')($rootScope);
expect(element.text()).toEqual('OK');
}
));
it('should prevent further directives from running, but finish current priority level',
inject(function($rootScope, $compile, log) {
// class is processed after attrs, so putting log in class will put it after
// the stop in the current level. This proves that the log runs after stop
element = $compile(
'<div high-log medium-stop log class="medium-log"><a set="FAIL">OK</a></div>')($rootScope);
expect(element.text()).toEqual('OK');
expect(log.toArray().sort()).toEqual(['HIGH', 'MEDIUM']);
})
);
});
describe('restrict', function() {
it('should allow restriction of availability', function() {
module(function() {
forEach({div: 'E', attr: 'A', clazz: 'C', comment: 'M', all: 'EACM'},
function(restrict, name) {
directive(name, function(log) {
return {
restrict: restrict,
compile: valueFn(function(scope, element, attr) {
log(name);
})
};
});
});
});
inject(function($rootScope, $compile, log) {
dealoc($compile('<span div class="div"></span>')($rootScope));
expect(log).toEqual('');
log.reset();
dealoc($compile('<div></div>')($rootScope));
expect(log).toEqual('div');
log.reset();
dealoc($compile('<attr class="attr"></attr>')($rootScope));
expect(log).toEqual('');
log.reset();
dealoc($compile('<span attr></span>')($rootScope));
expect(log).toEqual('attr');
log.reset();
dealoc($compile('<clazz clazz></clazz>')($rootScope));
expect(log).toEqual('');
log.reset();
dealoc($compile('<span class="clazz"></span>')($rootScope));
expect(log).toEqual('clazz');
log.reset();
dealoc($compile('<!-- directive: comment -->')($rootScope));
expect(log).toEqual('comment');
log.reset();
dealoc($compile('<all class="all" all><!-- directive: all --></all>')($rootScope));
expect(log).toEqual('all; all; all; all');
});
});
it('should use EA rule as the default', function() {
module(function() {
directive('defaultDir', function(log) {
return {
compile: function() {
log('defaultDir');
}
};
});
});
inject(function($rootScope, $compile, log) {
dealoc($compile('<span default-dir ></span>')($rootScope));
expect(log).toEqual('defaultDir');
log.reset();
dealoc($compile('<default-dir></default-dir>')($rootScope));
expect(log).toEqual('defaultDir');
log.reset();
dealoc($compile('<span class="default-dir"></span>')($rootScope));
expect(log).toEqual('');
log.reset();
});
});
});
describe('template', function() {
beforeEach(module(function() {
directive('replace', valueFn({
restrict: 'CAM',
replace: true,
template: '<div class="log" style="width: 10px" high-log>Replace!</div>',
compile: function(element, attr) {
attr.$set('compiled', 'COMPILED');
expect(element).toBe(attr.$$element);
}
}));
directive('nomerge', valueFn({
restrict: 'CAM',
replace: true,
template: '<div class="log" id="myid" high-log>No Merge!</div>',
compile: function(element, attr) {
attr.$set('compiled', 'COMPILED');
expect(element).toBe(attr.$$element);
}
}));
directive('append', valueFn({
restrict: 'CAM',
template: '<div class="log" style="width: 10px" high-log>Append!</div>',
compile: function(element, attr) {
attr.$set('compiled', 'COMPILED');
expect(element).toBe(attr.$$element);
}
}));
directive('replaceWithInterpolatedClass', valueFn({
replace: true,
template: '<div class="class_{{1+1}}">Replace with interpolated class!</div>',
compile: function(element, attr) {
attr.$set('compiled', 'COMPILED');
expect(element).toBe(attr.$$element);
}
}));
directive('replaceWithInterpolatedStyle', valueFn({
replace: true,
template: '<div style="width:{{1+1}}px">Replace with interpolated style!</div>',
compile: function(element, attr) {
attr.$set('compiled', 'COMPILED');
expect(element).toBe(attr.$$element);
}
}));
directive('replaceWithTr', valueFn({
replace: true,
template: '<tr><td>TR</td></tr>'
}));
directive('replaceWithTd', valueFn({
replace: true,
template: '<td>TD</td>'
}));
directive('replaceWithTh', valueFn({
replace: true,
template: '<th>TH</th>'
}));
directive('replaceWithThead', valueFn({
replace: true,
template: '<thead><tr><td>TD</td></tr></thead>'
}));
directive('replaceWithTbody', valueFn({
replace: true,
template: '<tbody><tr><td>TD</td></tr></tbody>'
}));
directive('replaceWithTfoot', valueFn({
replace: true,
template: '<tfoot><tr><td>TD</td></tr></tfoot>'
}));
directive('replaceWithOption', valueFn({
replace: true,
template: '<option>OPTION</option>'
}));
directive('replaceWithOptgroup', valueFn({
replace: true,
template: '<optgroup>OPTGROUP</optgroup>'
}));
}));
it('should replace element with template', inject(function($compile, $rootScope) {
element = $compile('<div><div replace>ignore</div><div>')($rootScope);
expect(element.text()).toEqual('Replace!');
expect(element.find('div').attr('compiled')).toEqual('COMPILED');
}));
it('should append element with template', inject(function($compile, $rootScope) {
element = $compile('<div><div append>ignore</div><div>')($rootScope);
expect(element.text()).toEqual('Append!');
expect(element.find('div').attr('compiled')).toEqual('COMPILED');
}));
it('should compile template when replacing', inject(function($compile, $rootScope, log) {
element = $compile('<div><div replace medium-log>ignore</div><div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('Replace!');
expect(log).toEqual('LOG; HIGH; MEDIUM');
}));
it('should compile template when appending', inject(function($compile, $rootScope, log) {
element = $compile('<div><div append medium-log>ignore</div><div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('Append!');
expect(log).toEqual('LOG; HIGH; MEDIUM');
}));
it('should merge attributes including style attr', inject(function($compile, $rootScope) {
element = $compile(
'<div><div replace class="medium-log" style="height: 20px" ></div><div>')($rootScope);
var div = element.find('div');
expect(div.hasClass('medium-log')).toBe(true);
expect(div.hasClass('log')).toBe(true);
expect(div.css('width')).toBe('10px');
expect(div.css('height')).toBe('20px');
expect(div.attr('replace')).toEqual('');
expect(div.attr('high-log')).toEqual('');
}));
it('should not merge attributes if they are the same', inject(function($compile, $rootScope) {
element = $compile(
'<div><div nomerge class="medium-log" id="myid"></div><div>')($rootScope);
var div = element.find('div');
expect(div.hasClass('medium-log')).toBe(true);
expect(div.hasClass('log')).toBe(true);
expect(div.attr('id')).toEqual('myid');
}));
it('should correctly merge attributes that contain special characters', inject(function($compile, $rootScope) {
element = $compile(
'<div><div replace (click)="doSomething()" [value]="someExpression" ω="omega"></div><div>')($rootScope);
var div = element.find('div');
expect(div.attr('(click)')).toEqual('doSomething()');
expect(div.attr('[value]')).toEqual('someExpression');
expect(div.attr('ω')).toEqual('omega');
}));
it('should not add white-space when merging an attribute that is "" in the replaced element',
inject(function($compile, $rootScope) {
element = $compile(
'<div><div replace class=""></div><div>')($rootScope);
var div = element.find('div');
expect(div.hasClass('log')).toBe(true);
expect(div.attr('class')).toBe('log');
})
);
it('should not set merged attributes twice in $attrs', function() {
var attrs;
module(function() {
directive('logAttrs', function() {
return {
link: function($scope, $element, $attrs) {
attrs = $attrs;
}
};
});
});
inject(function($compile, $rootScope) {
element = $compile(
'<div><div log-attrs replace class="myLog"></div><div>')($rootScope);
var div = element.find('div');
expect(div.attr('class')).toBe('myLog log');
expect(attrs.class).toBe('myLog log');
});
});
it('should prevent multiple templates per element', inject(function($compile) {
try {
$compile('<div><span replace class="replace"></span></div>');
this.fail(new Error('should have thrown Multiple directives error'));
} catch (e) {
expect(e.message).toMatch(/Multiple directives .* asking for template/);
}
}));
it('should play nice with repeater when replacing', inject(function($compile, $rootScope) {
element = $compile(
'<div>' +
'<div ng-repeat="i in [1,2]" replace></div>' +
'</div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('Replace!Replace!');
}));
it('should play nice with repeater when appending', inject(function($compile, $rootScope) {
element = $compile(
'<div>' +
'<div ng-repeat="i in [1,2]" append></div>' +
'</div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('Append!Append!');
}));
it('should handle interpolated css class from replacing directive', inject(
function($compile, $rootScope) {
element = $compile('<div replace-with-interpolated-class></div>')($rootScope);
$rootScope.$digest();
expect(element).toHaveClass('class_2');
}));
// Support: IE 9-11 only
if (!msie) {
// style interpolation not working on IE (including IE11).
it('should handle interpolated css style from replacing directive', inject(
function($compile, $rootScope) {
element = $compile('<div replace-with-interpolated-style></div>')($rootScope);
$rootScope.$digest();
expect(element.css('width')).toBe('2px');
}
));
}
it('should merge interpolated css class', inject(function($compile, $rootScope) {
element = $compile('<div class="one {{cls}} three" replace></div>')($rootScope);
$rootScope.$apply(function() {
$rootScope.cls = 'two';
});
expect(element).toHaveClass('one');
expect(element).toHaveClass('two'); // interpolated
expect(element).toHaveClass('three');
expect(element).toHaveClass('log'); // merged from replace directive template
}));
it('should merge interpolated css class with ngRepeat',
inject(function($compile, $rootScope) {
element = $compile(
'<div>' +
'<div ng-repeat="i in [1]" class="one {{cls}} three" replace></div>' +
'</div>')($rootScope);
$rootScope.$apply(function() {
$rootScope.cls = 'two';
});
var child = element.find('div').eq(0);
expect(child).toHaveClass('one');
expect(child).toHaveClass('two'); // interpolated
expect(child).toHaveClass('three');
expect(child).toHaveClass('log'); // merged from replace directive template
}));
it('should interpolate the values once per digest',
inject(function($compile, $rootScope, log) {
element = $compile('<div>{{log("A")}} foo {{::log("B")}}</div>')($rootScope);
$rootScope.log = log;
$rootScope.$digest();
expect(log).toEqual('A; B; A; B');
}));
it('should update references to replaced jQuery context', function() {
module(function($compileProvider) {
$compileProvider.directive('foo', function() {
return {
replace: true,
template: '<div></div>'
};
});
});
inject(function($compile, $rootScope) {
element = jqLite(document.createElement('span')).attr('foo', '');
expect(nodeName_(element)).toBe('span');
var preCompiledNode = element[0];
var linked = $compile(element)($rootScope);
expect(linked).toBe(element);
expect(nodeName_(element)).toBe('div');
if (element.context) {
expect(element.context).toBe(element[0]);
}
});
});
describe('replace and not exactly one root element', function() {
var templateVar;
beforeEach(module(function() {
directive('template', function() {
return {
replace: true,
template: function() {
return templateVar;
}
};
});
}));
they('should throw if: $prop',
{
'no root element': 'dada',
'multiple root elements': '<div></div><div></div>'
}, function(directiveTemplate) {
inject(function($compile) {
templateVar = directiveTemplate;
expect(function() {
$compile('<p template></p>');
}).toThrowMinErr('$compile', 'tplrt',
'Template for directive \'template\' must have exactly one root element.'
);
});
});
they('should not throw if the root element is accompanied by: $prop',
{
'whitespace': ' <div>Hello World!</div> \n',
'comments': '<!-- oh hi --><div>Hello World!</div> \n',
'comments + whitespace': ' <!-- oh hi --> <div>Hello World!</div> <!-- oh hi -->\n'
}, function(directiveTemplate) {
inject(function($compile, $rootScope) {
templateVar = directiveTemplate;
var element;
expect(function() {
element = $compile('<p template></p>')($rootScope);
}).not.toThrow();
expect(element.length).toBe(1);
expect(element.text()).toBe('Hello World!');
});
});
});
it('should support templates with root <tr> tags', inject(function($compile, $rootScope) {
expect(function() {
element = $compile('<div replace-with-tr></div>')($rootScope);
}).not.toThrow();
expect(nodeName_(element)).toMatch(/tr/i);
}));
it('should support templates with root <td> tags', inject(function($compile, $rootScope) {
expect(function() {
element = $compile('<div replace-with-td></div>')($rootScope);
}).not.toThrow();
expect(nodeName_(element)).toMatch(/td/i);
}));
it('should support templates with root <th> tags', inject(function($compile, $rootScope) {
expect(function() {
element = $compile('<div replace-with-th></div>')($rootScope);
}).not.toThrow();
expect(nodeName_(element)).toMatch(/th/i);
}));
it('should support templates with root <thead> tags', inject(function($compile, $rootScope) {
expect(function() {
element = $compile('<div replace-with-thead></div>')($rootScope);
}).not.toThrow();
expect(nodeName_(element)).toMatch(/thead/i);
}));
it('should support templates with root <tbody> tags', inject(function($compile, $rootScope) {
expect(function() {
element = $compile('<div replace-with-tbody></div>')($rootScope);
}).not.toThrow();
expect(nodeName_(element)).toMatch(/tbody/i);
}));
it('should support templates with root <tfoot> tags', inject(function($compile, $rootScope) {
expect(function() {
element = $compile('<div replace-with-tfoot></div>')($rootScope);
}).not.toThrow();
expect(nodeName_(element)).toMatch(/tfoot/i);
}));
it('should support templates with root <option> tags', inject(function($compile, $rootScope) {
expect(function() {
element = $compile('<div replace-with-option></div>')($rootScope);
}).not.toThrow();
expect(nodeName_(element)).toMatch(/option/i);
}));
it('should support templates with root <optgroup> tags', inject(function($compile, $rootScope) {
expect(function() {
element = $compile('<div replace-with-optgroup></div>')($rootScope);
}).not.toThrow();
expect(nodeName_(element)).toMatch(/optgroup/i);
}));
it('should support SVG templates using directive.templateNamespace=svg', function() {
module(function() {
directive('svgAnchor', valueFn({
replace: true,
template: '<a xlink:href="{{linkurl}}">{{text}}</a>',
templateNamespace: 'SVG',
scope: {
linkurl: '@svgAnchor',
text: '@?'
}
}));
});
inject(function($compile, $rootScope) {
element = $compile('<svg><g svg-anchor="/foo/bar" text="foo/bar!"></g></svg>')($rootScope);
var child = element.children().eq(0);
$rootScope.$digest();
expect(nodeName_(child)).toMatch(/a/i);
expect(isSVGElement(child[0])).toBe(true);
expect(child[0].href.baseVal).toBe('/foo/bar');
});
});
if (supportsMathML()) {
// MathML is only natively supported in Firefox at the time of this test's writing,
// and even there, the browser does not export MathML element constructors globally.
it('should support MathML templates using directive.templateNamespace=math', function() {
module(function() {
directive('pow', valueFn({
replace: true,
transclude: true,
template: '<msup><mn>{{pow}}</mn></msup>',
templateNamespace: 'MATH',
scope: {
pow: '@pow'
},
link: function(scope, elm, attr, ctrl, transclude) {
transclude(function(node) {
elm.prepend(node[0]);
});
}
}));
});
inject(function($compile, $rootScope) {
element = $compile('<math><mn pow="2"><mn>8</mn></mn></math>')($rootScope);
$rootScope.$digest();
var child = element.children().eq(0);
expect(nodeName_(child)).toMatch(/msup/i);
expect(isUnknownElement(child[0])).toBe(false);
expect(isHTMLElement(child[0])).toBe(false);
});
});
}
it('should keep prototype properties on directive', function() {
module(function() {
function DirectiveClass() {
this.restrict = 'E';
this.template = '<p>{{value}}</p>';
}
DirectiveClass.prototype.compile = function() {
return function(scope, element, attrs) {
scope.value = 'Test Value';
};
};
directive('templateUrlWithPrototype', valueFn(new DirectiveClass()));
});
inject(function($compile, $rootScope) {
element = $compile('<template-url-with-prototype><template-url-with-prototype>')($rootScope);
$rootScope.$digest();
expect(element.find('p')[0].innerHTML).toEqual('Test Value');
});
});
});
describe('template as function', function() {
beforeEach(module(function() {
directive('myDirective', valueFn({
replace: true,
template: function($element, $attrs) {
expect($element.text()).toBe('original content');
expect($attrs.myDirective).toBe('some value');
return '<div id="templateContent">template content</div>';
},
compile: function($element, $attrs) {
expect($element.text()).toBe('template content');
expect($attrs.id).toBe('templateContent');
}
}));
}));
it('should evaluate `template` when defined as fn and use returned string as template', inject(
function($compile, $rootScope) {
element = $compile('<div my-directive="some value">original content<div>')($rootScope);
expect(element.text()).toEqual('template content');
}));
});
describe('templateUrl', function() {
beforeEach(module(
function() {
directive('hello', valueFn({
restrict: 'CAM',
templateUrl: 'hello.html',
transclude: true
}));
directive('cau', valueFn({
restrict: 'CAM',
templateUrl: 'cau.html'
}));
directive('crossDomainTemplate', valueFn({
restrict: 'CAM',
templateUrl: 'http://example.com/should-not-load.html'
}));
directive('trustedTemplate', function($sce) {
return {
restrict: 'CAM',
templateUrl: function() {
return $sce.trustAsResourceUrl('http://example.com/trusted-template.html');
}
};
});
directive('cError', valueFn({
restrict: 'CAM',
templateUrl:'error.html',
compile: function() {
throw new Error('cError');
}
}));
directive('lError', valueFn({
restrict: 'CAM',
templateUrl: 'error.html',
compile: function() {
throw new Error('lError');
}
}));
directive('iHello', valueFn({
restrict: 'CAM',
replace: true,
templateUrl: 'hello.html'
}));
directive('iCau', valueFn({
restrict: 'CAM',
replace: true,
templateUrl:'cau.html'
}));
directive('iCError', valueFn({
restrict: 'CAM',
replace: true,
templateUrl:'error.html',
compile: function() {
throw new Error('cError');
}
}));
directive('iLError', valueFn({
restrict: 'CAM',
replace: true,
templateUrl: 'error.html',
compile: function() {
throw new Error('lError');
}
}));
directive('replace', valueFn({
replace: true,
template: '<span>Hello, {{name}}!</span>'
}));
directive('replaceWithTr', valueFn({
replace: true,
templateUrl: 'tr.html'
}));
directive('replaceWithTd', valueFn({
replace: true,
templateUrl: 'td.html'
}));
directive('replaceWithTh', valueFn({
replace: true,
templateUrl: 'th.html'
}));
directive('replaceWithThead', valueFn({
replace: true,
templateUrl: 'thead.html'
}));
directive('replaceWithTbody', valueFn({
replace: true,
templateUrl: 'tbody.html'
}));
directive('replaceWithTfoot', valueFn({
replace: true,
templateUrl: 'tfoot.html'
}));
directive('replaceWithOption', valueFn({
replace: true,
templateUrl: 'option.html'
}));
directive('replaceWithOptgroup', valueFn({
replace: true,
templateUrl: 'optgroup.html'
}));
}
));
it('should not load cross domain templates by default', inject(
function($compile, $rootScope) {
expect(function() {
$compile('<div class="crossDomainTemplate"></div>')($rootScope);
}).toThrowMinErr('$sce', 'insecurl', 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: http://example.com/should-not-load.html');
}
));
it('should trust what is already in the template cache', inject(
function($compile, $httpBackend, $rootScope, $templateCache) {
$httpBackend.expect('GET', 'http://example.com/should-not-load.html').respond('<span>example.com/remote-version</span>');
$templateCache.put('http://example.com/should-not-load.html', '<span>example.com/cached-version</span>');
element = $compile('<div class="crossDomainTemplate"></div>')($rootScope);
expect(sortedHtml(element)).toEqual('<div class="crossDomainTemplate"></div>');
$rootScope.$digest();
expect(sortedHtml(element)).toEqual('<div class="crossDomainTemplate"><span>example.com/cached-version</span></div>');
}
));
it('should load cross domain templates when trusted', inject(
function($compile, $httpBackend, $rootScope, $sce) {
$httpBackend.expect('GET', 'http://example.com/trusted-template.html').respond('<span>example.com/trusted_template_contents</span>');
element = $compile('<div class="trustedTemplate"></div>')($rootScope);
expect(sortedHtml(element)).
toEqual('<div class="trustedTemplate"></div>');
$httpBackend.flush();
expect(sortedHtml(element)).
toEqual('<div class="trustedTemplate"><span>example.com/trusted_template_contents</span></div>');
}
));
it('should append template via $http and cache it in $templateCache', inject(
function($compile, $httpBackend, $templateCache, $rootScope, $browser) {
$httpBackend.expect('GET', 'hello.html').respond('<span>Hello!</span> World!');
$templateCache.put('cau.html', '<span>Cau!</span>');
element = $compile('<div><b class="hello">ignore</b><b class="cau">ignore</b></div>')($rootScope);
expect(sortedHtml(element)).
toEqual('<div><b class="hello"></b><b class="cau"></b></div>');
$rootScope.$digest();
expect(sortedHtml(element)).
toEqual('<div><b class="hello"></b><b class="cau"><span>Cau!</span></b></div>');
$httpBackend.flush();
expect(sortedHtml(element)).toEqual(
'<div>' +
'<b class="hello"><span>Hello!</span> World!</b>' +
'<b class="cau"><span>Cau!</span></b>' +
'</div>');
}
));
it('should inline template via $http and cache it in $templateCache', inject(
function($compile, $httpBackend, $templateCache, $rootScope) {
$httpBackend.expect('GET', 'hello.html').respond('<span>Hello!</span>');
$templateCache.put('cau.html', '<span>Cau!</span>');
element = $compile('<div><b class=i-hello>ignore</b><b class=i-cau>ignore</b></div>')($rootScope);
expect(sortedHtml(element)).
toEqual('<div><b class="i-hello"></b><b class="i-cau"></b></div>');
$rootScope.$digest();
expect(sortedHtml(element)).toBe('<div><b class="i-hello"></b><span class="i-cau">Cau!</span></div>');
$httpBackend.flush();
expect(sortedHtml(element)).toBe('<div><span class="i-hello">Hello!</span><span class="i-cau">Cau!</span></div>');
}
));
it('should compile, link and flush the template append', inject(
function($compile, $templateCache, $rootScope, $browser) {
$templateCache.put('hello.html', '<span>Hello, {{name}}!</span>');
$rootScope.name = 'Elvis';
element = $compile('<div><b class="hello"></b></div>')($rootScope);
$rootScope.$digest();
expect(sortedHtml(element)).
toEqual('<div><b class="hello"><span>Hello, Elvis!</span></b></div>');
}
));
it('should compile, link and flush the template inline', inject(
function($compile, $templateCache, $rootScope) {
$templateCache.put('hello.html', '<span>Hello, {{name}}!</span>');
$rootScope.name = 'Elvis';
element = $compile('<div><b class=i-hello></b></div>')($rootScope);
$rootScope.$digest();
expect(sortedHtml(element)).toBe('<div><span class="i-hello">Hello, Elvis!</span></div>');
}
));
it('should compile, flush and link the template append', inject(
function($compile, $templateCache, $rootScope) {
$templateCache.put('hello.html', '<span>Hello, {{name}}!</span>');
$rootScope.name = 'Elvis';
var template = $compile('<div><b class="hello"></b></div>');
element = template($rootScope);
$rootScope.$digest();
expect(sortedHtml(element)).
toEqual('<div><b class="hello"><span>Hello, Elvis!</span></b></div>');
}
));
it('should compile, flush and link the template inline', inject(
function($compile, $templateCache, $rootScope) {
$templateCache.put('hello.html', '<span>Hello, {{name}}!</span>');
$rootScope.name = 'Elvis';
var template = $compile('<div><b class=i-hello></b></div>');
element = template($rootScope);
$rootScope.$digest();
expect(sortedHtml(element)).toBe('<div><span class="i-hello">Hello, Elvis!</span></div>');
}
));
it('should compile template when replacing element in another template',
inject(function($compile, $templateCache, $rootScope) {
$templateCache.put('hello.html', '<div replace></div>');
$rootScope.name = 'Elvis';
element = $compile('<div><b class="hello"></b></div>')($rootScope);
$rootScope.$digest();
expect(sortedHtml(element)).
toEqual('<div><b class="hello"><span replace="">Hello, Elvis!</span></b></div>');
}));
it('should compile template when replacing root element',
inject(function($compile, $templateCache, $rootScope) {
$rootScope.name = 'Elvis';
element = $compile('<div replace></div>')($rootScope);
$rootScope.$digest();
expect(sortedHtml(element)).
toEqual('<span replace="">Hello, Elvis!</span>');
}));
it('should resolve widgets after cloning in append mode', function() {
module(function($exceptionHandlerProvider) {
$exceptionHandlerProvider.mode('log');
});
inject(function($compile, $templateCache, $rootScope, $httpBackend, $browser,
$exceptionHandler) {
$httpBackend.expect('GET', 'hello.html').respond('<span>{{greeting}} </span>');
$httpBackend.expect('GET', 'error.html').respond('<div></div>');
$templateCache.put('cau.html', '<span>{{name}}</span>');
$rootScope.greeting = 'Hello';
$rootScope.name = 'Elvis';
var template = $compile(
'<div>' +
'<b class="hello"></b>' +
'<b class="cau"></b>' +
'<b class=c-error></b>' +
'<b class=l-error></b>' +
'</div>');
var e1;
var e2;
e1 = template($rootScope.$new(), noop); // clone
expect(e1.text()).toEqual('');
$httpBackend.flush();
e2 = template($rootScope.$new(), noop); // clone
$rootScope.$digest();
expect(e1.text()).toEqual('Hello Elvis');
expect(e2.text()).toEqual('Hello Elvis');
expect($exceptionHandler.errors.length).toEqual(2);
expect($exceptionHandler.errors[0][0].message).toEqual('cError');
expect($exceptionHandler.errors[1][0].message).toEqual('lError');
dealoc(e1);
dealoc(e2);
});
});
it('should resolve widgets after cloning in append mode without $templateCache', function() {
module(function($exceptionHandlerProvider) {
$exceptionHandlerProvider.mode('log');
});
inject(function($compile, $templateCache, $rootScope, $httpBackend, $browser,
$exceptionHandler) {
$httpBackend.expect('GET', 'cau.html').respond('<span>{{name}}</span>');
$rootScope.name = 'Elvis';
var template = $compile('<div class="cau"></div>');
var e1;
var e2;
e1 = template($rootScope.$new(), noop); // clone
expect(e1.text()).toEqual('');
$httpBackend.flush();
e2 = template($rootScope.$new(), noop); // clone
$rootScope.$digest();
expect(e1.text()).toEqual('Elvis');
expect(e2.text()).toEqual('Elvis');
dealoc(e1);
dealoc(e2);
});
});
it('should resolve widgets after cloning in inline mode', function() {
module(function($exceptionHandlerProvider) {
$exceptionHandlerProvider.mode('log');
});
inject(function($compile, $templateCache, $rootScope, $httpBackend, $browser,
$exceptionHandler) {
$httpBackend.expect('GET', 'hello.html').respond('<span>{{greeting}} </span>');
$httpBackend.expect('GET', 'error.html').respond('<div></div>');
$templateCache.put('cau.html', '<span>{{name}}</span>');
$rootScope.greeting = 'Hello';
$rootScope.name = 'Elvis';
var template = $compile(
'<div>' +
'<b class=i-hello></b>' +
'<b class=i-cau></b>' +
'<b class=i-c-error></b>' +
'<b class=i-l-error></b>' +
'</div>');
var e1;
var e2;
e1 = template($rootScope.$new(), noop); // clone
expect(e1.text()).toEqual('');
$httpBackend.flush();
e2 = template($rootScope.$new(), noop); // clone
$rootScope.$digest();
expect(e1.text()).toEqual('Hello Elvis');
expect(e2.text()).toEqual('Hello Elvis');
expect($exceptionHandler.errors.length).toEqual(2);
expect($exceptionHandler.errors[0][0].message).toEqual('cError');
expect($exceptionHandler.errors[1][0].message).toEqual('lError');
dealoc(e1);
dealoc(e2);
});
});
it('should resolve widgets after cloning in inline mode without $templateCache', function() {
module(function($exceptionHandlerProvider) {
$exceptionHandlerProvider.mode('log');
});
inject(function($compile, $templateCache, $rootScope, $httpBackend, $browser,
$exceptionHandler) {
$httpBackend.expect('GET', 'cau.html').respond('<span>{{name}}</span>');
$rootScope.name = 'Elvis';
var template = $compile('<div class="i-cau"></div>');
var e1;
var e2;
e1 = template($rootScope.$new(), noop); // clone
expect(e1.text()).toEqual('');
$httpBackend.flush();
e2 = template($rootScope.$new(), noop); // clone
$rootScope.$digest();
expect(e1.text()).toEqual('Elvis');
expect(e2.text()).toEqual('Elvis');
dealoc(e1);
dealoc(e2);
});
});
it('should be implicitly terminal and not compile placeholder content in append', inject(
function($compile, $templateCache, $rootScope, log) {
// we can't compile the contents because that would result in a memory leak
$templateCache.put('hello.html', 'Hello!');
element = $compile('<div><b class="hello"><div log></div></b></div>')($rootScope);
expect(log).toEqual('');
}
));
it('should be implicitly terminal and not compile placeholder content in inline', inject(
function($compile, $templateCache, $rootScope, log) {
// we can't compile the contents because that would result in a memory leak
$templateCache.put('hello.html', 'Hello!');
element = $compile('<div><b class=i-hello><div log></div></b></div>')($rootScope);
expect(log).toEqual('');
}
));
it('should throw an error and clear element content if the template fails to load',
inject(function($compile, $exceptionHandler, $httpBackend, $rootScope) {
$httpBackend.expect('GET', 'hello.html').respond(404, 'Not Found!');
element = $compile('<div><b class="hello">content</b></div>')($rootScope);
$httpBackend.flush();
expect(sortedHtml(element)).toBe('<div><b class="hello"></b></div>');
expect($exceptionHandler.errors[0]).toEqualMinErr('$compile', 'tpload',
'Failed to load template: hello.html');
})
);
it('should prevent multiple templates per element', function() {
module(function() {
directive('sync', valueFn({
restrict: 'C',
template: '<span></span>'
}));
directive('async', valueFn({
restrict: 'C',
templateUrl: 'template.html'
}));
});
inject(function($compile, $exceptionHandler, $httpBackend) {
$httpBackend.whenGET('template.html').respond('<p>template.html</p>');
$compile('<div><div class="sync async"></div></div>');
$httpBackend.flush();
expect($exceptionHandler.errors[0]).toEqualMinErr('$compile', 'multidir',
'Multiple directives [async, sync] asking for template on: ' +
'<div class="sync async">');
});
});
it('should copy classes from pre-template node into linked element', function() {
module(function() {
directive('test', valueFn({
templateUrl: 'test.html',
replace: true
}));
});
inject(function($compile, $templateCache, $rootScope) {
var child;
$templateCache.put('test.html', '<p class="template-class">Hello</p>');
element = $compile('<div test></div>')($rootScope, function(node) {
node.addClass('clonefn-class');
});
$rootScope.$digest();
expect(element).toHaveClass('template-class');
expect(element).toHaveClass('clonefn-class');
});
});
describe('delay compile / linking functions until after template is resolved', function() {
var template;
beforeEach(module(function() {
function logDirective(name, priority, options) {
directive(name, function(log) {
return (extend({
priority: priority,
compile: function() {
log(name + '-C');
return {
pre: function() { log(name + '-PreL'); },
post: function() { log(name + '-PostL'); }
};
}
}, options || {}));
});
}
logDirective('first', 10);
logDirective('second', 5, { templateUrl: 'second.html' });
logDirective('third', 3);
logDirective('last', 0);
logDirective('iFirst', 10, {replace: true});
logDirective('iSecond', 5, {replace: true, templateUrl: 'second.html' });
logDirective('iThird', 3, {replace: true});
logDirective('iLast', 0, {replace: true});
}));
it('should flush after link append', inject(
function($compile, $rootScope, $httpBackend, log) {
$httpBackend.expect('GET', 'second.html').respond('<div third>{{1+2}}</div>');
template = $compile('<div><span first second last></span></div>');
element = template($rootScope);
expect(log).toEqual('first-C');
log('FLUSH');
$httpBackend.flush();
$rootScope.$digest();
expect(log).toEqual(
'first-C; FLUSH; second-C; last-C; third-C; ' +
'first-PreL; second-PreL; last-PreL; third-PreL; ' +
'third-PostL; last-PostL; second-PostL; first-PostL');
var span = element.find('span');
expect(span.attr('first')).toEqual('');
expect(span.attr('second')).toEqual('');
expect(span.find('div').attr('third')).toEqual('');
expect(span.attr('last')).toEqual('');
expect(span.text()).toEqual('3');
}));
it('should flush after link inline', inject(
function($compile, $rootScope, $httpBackend, log) {
$httpBackend.expect('GET', 'second.html').respond('<div i-third>{{1+2}}</div>');
template = $compile('<div><span i-first i-second i-last></span></div>');
element = template($rootScope);
expect(log).toEqual('iFirst-C');
log('FLUSH');
$httpBackend.flush();
$rootScope.$digest();
expect(log).toEqual(
'iFirst-C; FLUSH; iSecond-C; iThird-C; iLast-C; ' +
'iFirst-PreL; iSecond-PreL; iThird-PreL; iLast-PreL; ' +
'iLast-PostL; iThird-PostL; iSecond-PostL; iFirst-PostL');
var div = element.find('div');
expect(div.attr('i-first')).toEqual('');
expect(div.attr('i-second')).toEqual('');
expect(div.attr('i-third')).toEqual('');
expect(div.attr('i-last')).toEqual('');
expect(div.text()).toEqual('3');
}));
it('should flush before link append', inject(
function($compile, $rootScope, $httpBackend, log) {
$httpBackend.expect('GET', 'second.html').respond('<div third>{{1+2}}</div>');
template = $compile('<div><span first second last></span></div>');
expect(log).toEqual('first-C');
log('FLUSH');
$httpBackend.flush();
expect(log).toEqual('first-C; FLUSH; second-C; last-C; third-C');
element = template($rootScope);
$rootScope.$digest();
expect(log).toEqual(
'first-C; FLUSH; second-C; last-C; third-C; ' +
'first-PreL; second-PreL; last-PreL; third-PreL; ' +
'third-PostL; last-PostL; second-PostL; first-PostL');
var span = element.find('span');
expect(span.attr('first')).toEqual('');
expect(span.attr('second')).toEqual('');
expect(span.find('div').attr('third')).toEqual('');
expect(span.attr('last')).toEqual('');
expect(span.text()).toEqual('3');
}));
it('should flush before link inline', inject(
function($compile, $rootScope, $httpBackend, log) {
$httpBackend.expect('GET', 'second.html').respond('<div i-third>{{1+2}}</div>');
template = $compile('<div><span i-first i-second i-last></span></div>');
expect(log).toEqual('iFirst-C');
log('FLUSH');
$httpBackend.flush();
expect(log).toEqual('iFirst-C; FLUSH; iSecond-C; iThird-C; iLast-C');
element = template($rootScope);
$rootScope.$digest();
expect(log).toEqual(
'iFirst-C; FLUSH; iSecond-C; iThird-C; iLast-C; ' +
'iFirst-PreL; iSecond-PreL; iThird-PreL; iLast-PreL; ' +
'iLast-PostL; iThird-PostL; iSecond-PostL; iFirst-PostL');
var div = element.find('div');
expect(div.attr('i-first')).toEqual('');
expect(div.attr('i-second')).toEqual('');
expect(div.attr('i-third')).toEqual('');
expect(div.attr('i-last')).toEqual('');
expect(div.text()).toEqual('3');
}));
});
it('should allow multiple elements in template', inject(function($compile, $httpBackend) {
$httpBackend.expect('GET', 'hello.html').respond('before <b>mid</b> after');
element = jqLite('<div hello></div>');
$compile(element);
$httpBackend.flush();
expect(element.text()).toEqual('before mid after');
}));
it('should work when directive is on the root element', inject(
function($compile, $httpBackend, $rootScope) {
$httpBackend.expect('GET', 'hello.html').
respond('<span>3==<span ng-transclude></span></span>');
element = jqLite('<b class="hello">{{1+2}}</b>');
$compile(element)($rootScope);
$httpBackend.flush();
expect(element.text()).toEqual('3==3');
}
));
it('should work when directive is in a repeater', inject(
function($compile, $httpBackend, $rootScope) {
$httpBackend.expect('GET', 'hello.html').
respond('<span>i=<span ng-transclude></span>;</span>');
element = jqLite('<div><b class=hello ng-repeat="i in [1,2]">{{i}}</b></div>');
$compile(element)($rootScope);
$httpBackend.flush();
expect(element.text()).toEqual('i=1;i=2;');
}
));
describe('replace and not exactly one root element', function() {
beforeEach(module(function() {
directive('template', function() {
return {
replace: true,
templateUrl: 'template.html'
};
});
}));
they('should throw if: $prop',
{
'no root element': 'dada',
'multiple root elements': '<div></div><div></div>'
}, function(directiveTemplate) {
inject(function($compile, $templateCache, $rootScope, $exceptionHandler) {
$templateCache.put('template.html', directiveTemplate);
$compile('<p template></p>')($rootScope);
$rootScope.$digest();
expect($exceptionHandler.errors.pop()).toEqualMinErr('$compile', 'tplrt',
'Template for directive \'template\' must have exactly one root element. ' +
'template.html'
);
});
});
they('should not throw if the root element is accompanied by: $prop',
{
'whitespace': ' <div>Hello World!</div> \n',
'comments': '<!-- oh hi --><div>Hello World!</div> \n',
'comments + whitespace': ' <!-- oh hi --> <div>Hello World!</div> <!-- oh hi -->\n'
}, function(directiveTemplate) {
inject(function($compile, $templateCache, $rootScope) {
$templateCache.put('template.html', directiveTemplate);
element = $compile('<p template></p>')($rootScope);
expect(function() {
$rootScope.$digest();
}).not.toThrow();
expect(element.length).toBe(1);
expect(element.text()).toBe('Hello World!');
});
});
});
it('should resume delayed compilation without duplicates when in a repeater', function() {
// this is a test for a regression
// scope creation, isolate watcher setup, controller instantiation, etc should happen
// only once even if we are dealing with delayed compilation of a node due to templateUrl
// and the template node is in a repeater
var controllerSpy = jasmine.createSpy('controller');
module(function($compileProvider) {
$compileProvider.directive('delayed', valueFn({
controller: controllerSpy,
templateUrl: 'delayed.html',
scope: {
title: '@'
}
}));
});
inject(function($templateCache, $compile, $rootScope) {
$rootScope.coolTitle = 'boom!';
$templateCache.put('delayed.html', '<div>{{title}}</div>');
element = $compile(
'<div><div ng-repeat="i in [1,2]"><div delayed title="{{coolTitle + i}}"></div>|</div></div>'
)($rootScope);
$rootScope.$apply();
expect(controllerSpy).toHaveBeenCalledTimes(2);
expect(element.text()).toBe('boom!1|boom!2|');
});
});
it('should support templateUrl with replace', function() {
// a regression https://github.com/angular/angular.js/issues/3792
module(function($compileProvider) {
$compileProvider.directive('simple', function() {
return {
templateUrl: '/some.html',
replace: true
};
});
});
inject(function($templateCache, $rootScope, $compile) {
$templateCache.put('/some.html',
'<div ng-switch="i">' +
'<div ng-switch-when="1">i = 1</div>' +
'<div ng-switch-default>I dont know what `i` is.</div>' +
'</div>');
element = $compile('<div simple></div>')($rootScope);
$rootScope.$apply(function() {
$rootScope.i = 1;
});
expect(element.html()).toContain('i = 1');
});
});
it('should support templates with root <tr> tags', inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('tr.html', '<tr><td>TR</td></tr>');
expect(function() {
element = $compile('<div replace-with-tr></div>')($rootScope);
}).not.toThrow();
$rootScope.$digest();
expect(nodeName_(element)).toMatch(/tr/i);
}));
it('should support templates with root <td> tags', inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('td.html', '<td>TD</td>');
expect(function() {
element = $compile('<div replace-with-td></div>')($rootScope);
}).not.toThrow();
$rootScope.$digest();
expect(nodeName_(element)).toMatch(/td/i);
}));
it('should support templates with root <th> tags', inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('th.html', '<th>TH</th>');
expect(function() {
element = $compile('<div replace-with-th></div>')($rootScope);
}).not.toThrow();
$rootScope.$digest();
expect(nodeName_(element)).toMatch(/th/i);
}));
it('should support templates with root <thead> tags', inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('thead.html', '<thead><tr><td>TD</td></tr></thead>');
expect(function() {
element = $compile('<div replace-with-thead></div>')($rootScope);
}).not.toThrow();
$rootScope.$digest();
expect(nodeName_(element)).toMatch(/thead/i);
}));
it('should support templates with root <tbody> tags', inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('tbody.html', '<tbody><tr><td>TD</td></tr></tbody>');
expect(function() {
element = $compile('<div replace-with-tbody></div>')($rootScope);
}).not.toThrow();
$rootScope.$digest();
expect(nodeName_(element)).toMatch(/tbody/i);
}));
it('should support templates with root <tfoot> tags', inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('tfoot.html', '<tfoot><tr><td>TD</td></tr></tfoot>');
expect(function() {
element = $compile('<div replace-with-tfoot></div>')($rootScope);
}).not.toThrow();
$rootScope.$digest();
expect(nodeName_(element)).toMatch(/tfoot/i);
}));
it('should support templates with root <option> tags', inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('option.html', '<option>OPTION</option>');
expect(function() {
element = $compile('<div replace-with-option></div>')($rootScope);
}).not.toThrow();
$rootScope.$digest();
expect(nodeName_(element)).toMatch(/option/i);
}));
it('should support templates with root <optgroup> tags', inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('optgroup.html', '<optgroup>OPTGROUP</optgroup>');
expect(function() {
element = $compile('<div replace-with-optgroup></div>')($rootScope);
}).not.toThrow();
$rootScope.$digest();
expect(nodeName_(element)).toMatch(/optgroup/i);
}));
it('should support SVG templates using directive.templateNamespace=svg', function() {
module(function() {
directive('svgAnchor', valueFn({
replace: true,
templateUrl: 'template.html',
templateNamespace: 'SVG',
scope: {
linkurl: '@svgAnchor',
text: '@?'
}
}));
});
inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('template.html', '<a xlink:href="{{linkurl}}">{{text}}</a>');
element = $compile('<svg><g svg-anchor="/foo/bar" text="foo/bar!"></g></svg>')($rootScope);
$rootScope.$digest();
var child = element.children().eq(0);
expect(nodeName_(child)).toMatch(/a/i);
expect(isSVGElement(child[0])).toBe(true);
expect(child[0].href.baseVal).toBe('/foo/bar');
});
});
if (supportsMathML()) {
// MathML is only natively supported in Firefox at the time of this test's writing,
// and even there, the browser does not export MathML element constructors globally.
it('should support MathML templates using directive.templateNamespace=math', function() {
module(function() {
directive('pow', valueFn({
replace: true,
transclude: true,
templateUrl: 'template.html',
templateNamespace: 'math',
scope: {
pow: '@pow'
},
link: function(scope, elm, attr, ctrl, transclude) {
transclude(function(node) {
elm.prepend(node[0]);
});
}
}));
});
inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('template.html', '<msup><mn>{{pow}}</mn></msup>');
element = $compile('<math><mn pow="2"><mn>8</mn></mn></math>')($rootScope);
$rootScope.$digest();
var child = element.children().eq(0);
expect(nodeName_(child)).toMatch(/msup/i);
expect(isUnknownElement(child[0])).toBe(false);
expect(isHTMLElement(child[0])).toBe(false);
});
});
}
it('should keep prototype properties on sync version of async directive', function() {
module(function() {
function DirectiveClass() {
this.restrict = 'E';
this.templateUrl = 'test.html';
}
DirectiveClass.prototype.compile = function() {
return function(scope, element, attrs) {
scope.value = 'Test Value';
};
};
directive('templateUrlWithPrototype', valueFn(new DirectiveClass()));
});
inject(function($compile, $rootScope, $httpBackend) {
$httpBackend.whenGET('test.html').
respond('<p>{{value}}</p>');
element = $compile('<template-url-with-prototype><template-url-with-prototype>')($rootScope);
$httpBackend.flush();
$rootScope.$digest();
expect(element.find('p')[0].innerHTML).toEqual('Test Value');
});
});
});
describe('templateUrl as function', function() {
beforeEach(module(function() {
directive('myDirective', valueFn({
replace: true,
templateUrl: function($element, $attrs) {
expect($element.text()).toBe('original content');
expect($attrs.myDirective).toBe('some value');
return 'my-directive.html';
},
compile: function($element, $attrs) {
expect($element.text()).toBe('template content');
expect($attrs.id).toBe('templateContent');
}
}));
}));
it('should evaluate `templateUrl` when defined as fn and use returned value as url', inject(
function($compile, $rootScope, $templateCache) {
$templateCache.put('my-directive.html', '<div id="templateContent">template content</span>');
element = $compile('<div my-directive="some value">original content<div>')($rootScope);
expect(element.text()).toEqual('');
$rootScope.$digest();
expect(element.text()).toEqual('template content');
}));
});
describe('scope', function() {
var iscope;
beforeEach(module(function() {
forEach(['', 'a', 'b'], function(name) {
directive('scope' + uppercase(name), function(log) {
return {
scope: true,
restrict: 'CA',
compile: function() {
return {pre: function(scope, element) {
log(scope.$id);
expect(element.data('$scope')).toBe(scope);
}};
}
};
});
directive('iscope' + uppercase(name), function(log) {
return {
scope: {},
restrict: 'CA',
compile: function() {
return function(scope, element) {
iscope = scope;
log(scope.$id);
expect(element.data('$isolateScopeNoTemplate')).toBe(scope);
};
}
};
});
directive('tscope' + uppercase(name), function(log) {
return {
scope: true,
restrict: 'CA',
templateUrl: 'tscope.html',
compile: function() {
return function(scope, element) {
log(scope.$id);
expect(element.data('$scope')).toBe(scope);
};
}
};
});
directive('stscope' + uppercase(name), function(log) {
return {
scope: true,
restrict: 'CA',
template: '<span></span>',
compile: function() {
return function(scope, element) {
log(scope.$id);
expect(element.data('$scope')).toBe(scope);
};
}
};
});
directive('trscope' + uppercase(name), function(log) {
return {
scope: true,
replace: true,
restrict: 'CA',
templateUrl: 'trscope.html',
compile: function() {
return function(scope, element) {
log(scope.$id);
expect(element.data('$scope')).toBe(scope);
};
}
};
});
directive('tiscope' + uppercase(name), function(log) {
return {
scope: {},
restrict: 'CA',
templateUrl: 'tiscope.html',
compile: function() {
return function(scope, element) {
iscope = scope;
log(scope.$id);
expect(element.data('$isolateScope')).toBe(scope);
};
}
};
});
directive('stiscope' + uppercase(name), function(log) {
return {
scope: {},
restrict: 'CA',
template: '<span></span>',
compile: function() {
return function(scope, element) {
iscope = scope;
log(scope.$id);
expect(element.data('$isolateScope')).toBe(scope);
};
}
};
});
});
directive('log', function(log) {
return {
restrict: 'CA',
link: {pre: function(scope) {
log('log-' + scope.$id + '-' + (scope.$parent && scope.$parent.$id || 'no-parent'));
}}
};
});
directive('prototypeMethodNameAsScopeVarA', function() {
return {
scope: {
'constructor': '=?',
'valueOf': '='
},
restrict: 'AE',
template: '<span></span>'
};
});
directive('prototypeMethodNameAsScopeVarB', function() {
return {
scope: {
'constructor': '@?',
'valueOf': '@'
},
restrict: 'AE',
template: '<span></span>'
};
});
directive('prototypeMethodNameAsScopeVarC', function() {
return {
scope: {
'constructor': '&?',
'valueOf': '&'
},
restrict: 'AE',
template: '<span></span>'
};
});
directive('watchAsScopeVar', function() {
return {
scope: {
'watch': '='
},
restrict: 'AE',
template: '<span></span>'
};
});
}));
it('should allow creation of new scopes', inject(function($rootScope, $compile, log) {
element = $compile('<div><span scope><a log></a></span></div>')($rootScope);
expect(log).toEqual('2; log-2-1; LOG');
expect(element.find('span').hasClass('ng-scope')).toBe(true);
}));
it('should allow creation of new isolated scopes for directives', inject(
function($rootScope, $compile, log) {
element = $compile('<div><span iscope><a log></a></span></div>')($rootScope);
expect(log).toEqual('log-1-no-parent; LOG; 2');
$rootScope.name = 'abc';
expect(iscope.$parent).toBe($rootScope);
expect(iscope.name).toBeUndefined();
}));
it('should allow creation of new scopes for directives with templates', inject(
function($rootScope, $compile, log, $httpBackend) {
$httpBackend.expect('GET', 'tscope.html').respond('<a log>{{name}}; scopeId: {{$id}}</a>');
element = $compile('<div><span tscope></span></div>')($rootScope);
$httpBackend.flush();
expect(log).toEqual('log-2-1; LOG; 2');
$rootScope.name = 'Jozo';
$rootScope.$apply();
expect(element.text()).toBe('Jozo; scopeId: 2');
expect(element.find('span').scope().$id).toBe(2);
}));
it('should allow creation of new scopes for replace directives with templates', inject(
function($rootScope, $compile, log, $httpBackend) {
$httpBackend.expect('GET', 'trscope.html').
respond('<p><a log>{{name}}; scopeId: {{$id}}</a></p>');
element = $compile('<div><span trscope></span></div>')($rootScope);
$httpBackend.flush();
expect(log).toEqual('log-2-1; LOG; 2');
$rootScope.name = 'Jozo';
$rootScope.$apply();
expect(element.text()).toBe('Jozo; scopeId: 2');
expect(element.find('a').scope().$id).toBe(2);
}));
it('should allow creation of new scopes for replace directives with templates in a repeater',
inject(function($rootScope, $compile, log, $httpBackend) {
$httpBackend.expect('GET', 'trscope.html').
respond('<p><a log>{{name}}; scopeId: {{$id}} |</a></p>');
element = $compile('<div><span ng-repeat="i in [1,2,3]" trscope></span></div>')($rootScope);
$httpBackend.flush();
expect(log).toEqual('log-3-2; LOG; 3; log-5-4; LOG; 5; log-7-6; LOG; 7');
$rootScope.name = 'Jozo';
$rootScope.$apply();
expect(element.text()).toBe('Jozo; scopeId: 3 |Jozo; scopeId: 5 |Jozo; scopeId: 7 |');
expect(element.find('p').scope().$id).toBe(3);
expect(element.find('a').scope().$id).toBe(3);
}));
it('should allow creation of new isolated scopes for directives with templates', inject(
function($rootScope, $compile, log, $httpBackend) {
$httpBackend.expect('GET', 'tiscope.html').respond('<a log></a>');
element = $compile('<div><span tiscope></span></div>')($rootScope);
$httpBackend.flush();
expect(log).toEqual('log-2-1; LOG; 2');
$rootScope.name = 'abc';
expect(iscope.$parent).toBe($rootScope);
expect(iscope.name).toBeUndefined();
}));
it('should correctly create the scope hierarchy', inject(
function($rootScope, $compile, log) {
element = $compile(
'<div>' + //1
'<b class=scope>' + //2
'<b class=scope><b class=log></b></b>' + //3
'<b class=log></b>' +
'</b>' +
'<b class=scope>' + //4
'<b class=log></b>' +
'</b>' +
'</div>'
)($rootScope);
expect(log).toEqual('2; 3; log-3-2; LOG; log-2-1; LOG; 4; log-4-1; LOG');
})
);
it('should allow more than one new scope directives per element, but directives should share' +
'the scope', inject(
function($rootScope, $compile, log) {
element = $compile('<div class="scope-a; scope-b"></div>')($rootScope);
expect(log).toEqual('2; 2');
})
);
it('should not allow more than one isolate scope creation per element', inject(
function($rootScope, $compile) {
expect(function() {
$compile('<div class="iscope-a; scope-b"></div>');
}).toThrowMinErr('$compile', 'multidir', 'Multiple directives [iscopeA, scopeB] asking for new/isolated scope on: ' +
'<div class="iscope-a; scope-b">');
})
);
it('should not allow more than one isolate/new scope creation per element regardless of `templateUrl`',
inject(function($exceptionHandler, $httpBackend) {
$httpBackend.expect('GET', 'tiscope.html').respond('<div>Hello, world !</div>');
compile('<div class="tiscope-a; scope-b"></div>');
$httpBackend.flush();
expect($exceptionHandler.errors[0]).toEqualMinErr('$compile', 'multidir',
'Multiple directives [scopeB, tiscopeA] asking for new/isolated scope on: ' +
'<div class="tiscope-a; scope-b ng-scope">');
})
);
it('should not allow more than one isolate scope creation per element regardless of directive priority', function() {
module(function($compileProvider) {
$compileProvider.directive('highPriorityScope', function() {
return {
restrict: 'C',
priority: 1,
scope: true,
link: function() {}
};
});
});
inject(function($compile) {
expect(function() {
$compile('<div class="iscope-a; high-priority-scope"></div>');
}).toThrowMinErr('$compile', 'multidir', 'Multiple directives [highPriorityScope, iscopeA] asking for new/isolated scope on: ' +
'<div class="iscope-a; high-priority-scope">');
});
});
it('should create new scope even at the root of the template', inject(
function($rootScope, $compile, log) {
element = $compile('<div scope-a></div>')($rootScope);
expect(log).toEqual('2');
})
);
it('should create isolate scope even at the root of the template', inject(
function($rootScope, $compile, log) {
element = $compile('<div iscope></div>')($rootScope);
expect(log).toEqual('2');
})
);
describe('scope()/isolate() scope getters', function() {
describe('with no directives', function() {
it('should return the scope of the parent node', inject(
function($rootScope, $compile) {
element = $compile('<div></div>')($rootScope);
expect(element.scope()).toBe($rootScope);
})
);
});
describe('with new scope directives', function() {
it('should return the new scope at the directive element', inject(
function($rootScope, $compile) {
element = $compile('<div scope></div>')($rootScope);
expect(element.scope().$parent).toBe($rootScope);
})
);
it('should return the new scope for children in the original template', inject(
function($rootScope, $compile) {
element = $compile('<div scope><a></a></div>')($rootScope);
expect(element.find('a').scope().$parent).toBe($rootScope);
})
);
it('should return the new scope for children in the directive template', inject(
function($rootScope, $compile, $httpBackend) {
$httpBackend.expect('GET', 'tscope.html').respond('<a></a>');
element = $compile('<div tscope></div>')($rootScope);
$httpBackend.flush();
expect(element.find('a').scope().$parent).toBe($rootScope);
})
);
it('should return the new scope for children in the directive sync template', inject(
function($rootScope, $compile) {
element = $compile('<div stscope></div>')($rootScope);
expect(element.find('span').scope().$parent).toBe($rootScope);
})
);
});
describe('with isolate scope directives', function() {
it('should return the root scope for directives at the root element', inject(
function($rootScope, $compile) {
element = $compile('<div iscope></div>')($rootScope);
expect(element.scope()).toBe($rootScope);
})
);
it('should return the non-isolate scope at the directive element', inject(
function($rootScope, $compile) {
var directiveElement;
element = $compile('<div><div iscope></div></div>')($rootScope);
directiveElement = element.children();
expect(directiveElement.scope()).toBe($rootScope);
expect(directiveElement.isolateScope().$parent).toBe($rootScope);
})
);
it('should return the isolate scope for children in the original template', inject(
function($rootScope, $compile) {
element = $compile('<div iscope><a></a></div>')($rootScope);
expect(element.find('a').scope()).toBe($rootScope); //xx
})
);
it('should return the isolate scope for children in directive template', inject(
function($rootScope, $compile, $httpBackend) {
$httpBackend.expect('GET', 'tiscope.html').respond('<a></a>');
element = $compile('<div tiscope></div>')($rootScope);
expect(element.isolateScope()).toBeUndefined(); // this is the current behavior, not desired feature
$httpBackend.flush();
expect(element.find('a').scope()).toBe(element.isolateScope());
expect(element.isolateScope()).not.toBe($rootScope);
})
);
it('should return the isolate scope for children in directive sync template', inject(
function($rootScope, $compile) {
element = $compile('<div stiscope></div>')($rootScope);
expect(element.find('span').scope()).toBe(element.isolateScope());
expect(element.isolateScope()).not.toBe($rootScope);
})
);
it('should handle "=" bindings with same method names in Object.prototype correctly when not present', inject(
function($rootScope, $compile) {
var func = function() {
element = $compile(
'<div prototype-method-name-as-scope-var-a></div>'
)($rootScope);
};
expect(func).not.toThrow();
var scope = element.isolateScope();
expect(element.find('span').scope()).toBe(scope);
expect(scope).not.toBe($rootScope);
// Not shadowed because optional
expect(scope.constructor).toBe($rootScope.constructor);
expect(scope.hasOwnProperty('constructor')).toBe(false);
// Shadowed with undefined because not optional
expect(scope.valueOf).toBeUndefined();
expect(scope.hasOwnProperty('valueOf')).toBe(true);
})
);
it('should handle "=" bindings with same method names in Object.prototype correctly when present', inject(
function($rootScope, $compile) {
$rootScope.constructor = 'constructor';
$rootScope.valueOf = 'valueOf';
var func = function() {
element = $compile(
'<div prototype-method-name-as-scope-var-a constructor="constructor" value-of="valueOf"></div>'
)($rootScope);
};
expect(func).not.toThrow();
var scope = element.isolateScope();
expect(element.find('span').scope()).toBe(scope);
expect(scope).not.toBe($rootScope);
expect(scope.constructor).toBe('constructor');
expect(scope.hasOwnProperty('constructor')).toBe(true);
expect(scope.valueOf).toBe('valueOf');
expect(scope.hasOwnProperty('valueOf')).toBe(true);
})
);
it('should handle "@" bindings with same method names in Object.prototype correctly when not present', inject(
function($rootScope, $compile) {
var func = function() {
element = $compile('<div prototype-method-name-as-scope-var-b></div>')($rootScope);
};
expect(func).not.toThrow();
var scope = element.isolateScope();
expect(element.find('span').scope()).toBe(scope);
expect(scope).not.toBe($rootScope);
// Does not shadow value because optional
expect(scope.constructor).toBe($rootScope.constructor);
expect(scope.hasOwnProperty('constructor')).toBe(false);
// Shadows value because not optional
expect(scope.valueOf).toBeUndefined();
expect(scope.hasOwnProperty('valueOf')).toBe(true);
})
);
it('should handle "@" bindings with same method names in Object.prototype correctly when present', inject(
function($rootScope, $compile) {
var func = function() {
element = $compile(
'<div prototype-method-name-as-scope-var-b constructor="constructor" value-of="valueOf"></div>'
)($rootScope);
};
expect(func).not.toThrow();
expect(element.find('span').scope()).toBe(element.isolateScope());
expect(element.isolateScope()).not.toBe($rootScope);
expect(element.isolateScope()['constructor']).toBe('constructor');
expect(element.isolateScope()['valueOf']).toBe('valueOf');
})
);
it('should handle "&" bindings with same method names in Object.prototype correctly when not present', inject(
function($rootScope, $compile) {
var func = function() {
element = $compile('<div prototype-method-name-as-scope-var-c></div>')($rootScope);
};
expect(func).not.toThrow();
expect(element.find('span').scope()).toBe(element.isolateScope());
expect(element.isolateScope()).not.toBe($rootScope);
expect(element.isolateScope()['constructor']).toBe($rootScope.constructor);
expect(element.isolateScope()['valueOf']()).toBeUndefined();
})
);
it('should handle "&" bindings with same method names in Object.prototype correctly when present', inject(
function($rootScope, $compile) {
$rootScope.constructor = function() { return 'constructor'; };
$rootScope.valueOf = function() { return 'valueOf'; };
var func = function() {
element = $compile(
'<div prototype-method-name-as-scope-var-c constructor="constructor()" value-of="valueOf()"></div>'
)($rootScope);
};
expect(func).not.toThrow();
expect(element.find('span').scope()).toBe(element.isolateScope());
expect(element.isolateScope()).not.toBe($rootScope);
expect(element.isolateScope()['constructor']()).toBe('constructor');
expect(element.isolateScope()['valueOf']()).toBe('valueOf');
})
);
it('should not throw exception when using "watch" as binding in Firefox', inject(
function($rootScope, $compile) {
$rootScope.watch = 'watch';
var func = function() {
element = $compile(
'<div watch-as-scope-var watch="watch"></div>'
)($rootScope);
};
expect(func).not.toThrow();
expect(element.find('span').scope()).toBe(element.isolateScope());
expect(element.isolateScope()).not.toBe($rootScope);
expect(element.isolateScope()['watch']).toBe('watch');
})
);
it('should handle @ bindings on BOOLEAN attributes', function() {
var checkedVal;
module(function($compileProvider) {
$compileProvider.directive('test', function() {
return {
scope: { checked: '@' },
link: function(scope, element, attrs) {
checkedVal = scope.checked;
}
};
});
});
inject(function($compile, $rootScope) {
$compile('<input test checked="checked">')($rootScope);
expect(checkedVal).toEqual(true);
});
});
it('should handle updates to @ bindings on BOOLEAN attributes', function() {
var componentScope;
module(function($compileProvider) {
$compileProvider.directive('test', function() {
return {
scope: {checked: '@'},
link: function(scope, element, attrs) {
componentScope = scope;
attrs.$set('checked', true);
}
};
});
});
inject(function($compile, $rootScope) {
$compile('<test></test>')($rootScope);
expect(componentScope.checked).toBe(true);
});
});
});
describe('with isolate scope directives and directives that manually create a new scope', function() {
it('should return the new scope at the directive element', inject(
function($rootScope, $compile) {
var directiveElement;
element = $compile('<div><a ng-if="true" iscope></a></div>')($rootScope);
$rootScope.$apply();
directiveElement = element.find('a');
expect(directiveElement.scope().$parent).toBe($rootScope);
expect(directiveElement.scope()).not.toBe(directiveElement.isolateScope());
})
);
it('should return the isolate scope for child elements', inject(
function($rootScope, $compile, $httpBackend) {
var directiveElement, child;
$httpBackend.expect('GET', 'tiscope.html').respond('<span></span>');
element = $compile('<div><a ng-if="true" tiscope></a></div>')($rootScope);
$rootScope.$apply();
$httpBackend.flush();
directiveElement = element.find('a');
child = directiveElement.find('span');
expect(child.scope()).toBe(directiveElement.isolateScope());
})
);
it('should return the isolate scope for child elements in directive sync template', inject(
function($rootScope, $compile) {
var directiveElement, child;
element = $compile('<div><a ng-if="true" stiscope></a></div>')($rootScope);
$rootScope.$apply();
directiveElement = element.find('a');
child = directiveElement.find('span');
expect(child.scope()).toBe(directiveElement.isolateScope());
})
);
});
});
describe('multidir isolated scope error messages', function() {
angular.module('fakeIsoledScopeModule', [])
.directive('fakeScope', function(log) {
return {
scope: true,
restrict: 'CA',
compile: function() {
return {pre: function(scope, element) {
log(scope.$id);
expect(element.data('$scope')).toBe(scope);
}};
}
};
})
.directive('fakeIScope', function(log) {
return {
scope: {},
restrict: 'CA',
compile: function() {
return function(scope, element) {
iscope = scope;
log(scope.$id);
expect(element.data('$isolateScopeNoTemplate')).toBe(scope);
};
}
};
});
beforeEach(module('fakeIsoledScopeModule', function() {
directive('anonymModuleScopeDirective', function(log) {
return {
scope: true,
restrict: 'CA',
compile: function() {
return {pre: function(scope, element) {
log(scope.$id);
expect(element.data('$scope')).toBe(scope);
}};
}
};
});
}));
it('should add module name to multidir isolated scope message if directive defined through module', inject(
function($rootScope, $compile) {
expect(function() {
$compile('<div class="fake-scope; fake-i-scope"></div>');
}).toThrowMinErr('$compile', 'multidir',
'Multiple directives [fakeIScope (module: fakeIsoledScopeModule), fakeScope (module: fakeIsoledScopeModule)] ' +
'asking for new/isolated scope on: <div class="fake-scope; fake-i-scope">');
})
);
it('shouldn\'t add module name to multidir isolated scope message if directive is defined directly with $compileProvider', inject(
function($rootScope, $compile) {
expect(function() {
$compile('<div class="anonym-module-scope-directive; fake-i-scope"></div>');
}).toThrowMinErr('$compile', 'multidir',
'Multiple directives [anonymModuleScopeDirective, fakeIScope (module: fakeIsoledScopeModule)] ' +
'asking for new/isolated scope on: <div class="anonym-module-scope-directive; fake-i-scope">');
})
);
});
});
});
});
describe('interpolation', function() {
var observeSpy, directiveAttrs, deregisterObserver;
beforeEach(module(function() {
directive('observer', function() {
return function(scope, elm, attr) {
directiveAttrs = attr;
observeSpy = jasmine.createSpy('$observe attr');
deregisterObserver = attr.$observe('someAttr', observeSpy);
};
});
directive('replaceSomeAttr', valueFn({
compile: function(element, attr) {
attr.$set('someAttr', 'bar-{{1+1}}');
expect(element).toBe(attr.$$element);
}
}));
}));
it('should compile and link both attribute and text bindings', inject(
function($rootScope, $compile) {
$rootScope.name = 'angular';
element = $compile('<div name="attr: {{name}}">text: {{name}}</div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('text: angular');
expect(element.attr('name')).toEqual('attr: angular');
})
);
it('should one-time bind if the expression starts with two colons', inject(
function($rootScope, $compile) {
$rootScope.name = 'angular';
element = $compile('<div name="attr: {{::name}}">text: {{::name}}</div>')($rootScope);
expect($rootScope.$$watchers.length).toBe(2);
$rootScope.$digest();
expect(element.text()).toEqual('text: angular');
expect(element.attr('name')).toEqual('attr: angular');
expect($rootScope.$$watchers.length).toBe(0);
$rootScope.name = 'not-angular';
$rootScope.$digest();
expect(element.text()).toEqual('text: angular');
expect(element.attr('name')).toEqual('attr: angular');
})
);
it('should one-time bind if the expression starts with a space and two colons', inject(
function($rootScope, $compile) {
$rootScope.name = 'angular';
element = $compile('<div name="attr: {{::name}}">text: {{ ::name }}</div>')($rootScope);
expect($rootScope.$$watchers.length).toBe(2);
$rootScope.$digest();
expect(element.text()).toEqual('text: angular');
expect(element.attr('name')).toEqual('attr: angular');
expect($rootScope.$$watchers.length).toBe(0);
$rootScope.name = 'not-angular';
$rootScope.$digest();
expect(element.text()).toEqual('text: angular');
expect(element.attr('name')).toEqual('attr: angular');
})
);
it('should process attribute interpolation in pre-linking phase at priority 100', function() {
module(function() {
directive('attrLog', function(log) {
return {
compile: function($element, $attrs) {
log('compile=' + $attrs.myName);
return {
pre: function($scope, $element, $attrs) {
log('preLinkP0=' + $attrs.myName);
},
post: function($scope, $element, $attrs) {
log('postLink=' + $attrs.myName);
}
};
}
};
});
});
module(function() {
directive('attrLogHighPriority', function(log) {
return {
priority: 101,
compile: function() {
return {
pre: function($scope, $element, $attrs) {
log('preLinkP101=' + $attrs.myName);
}
};
}
};
});
});
inject(function($rootScope, $compile, log) {
element = $compile('<div attr-log-high-priority attr-log my-name="{{name}}"></div>')($rootScope);
$rootScope.name = 'angular';
$rootScope.$apply();
log('digest=' + element.attr('my-name'));
expect(log).toEqual('compile={{name}}; preLinkP101={{name}}; preLinkP0=; postLink=; digest=angular');
});
});
it('should allow the attribute to be removed before the attribute interpolation', function() {
module(function() {
directive('removeAttr', function() {
return {
restrict:'A',
compile: function(tElement, tAttr) {
tAttr.$set('removeAttr', null);
}
};
});
});
inject(function($rootScope, $compile) {
expect(function() {
element = $compile('<div remove-attr="{{ toBeRemoved }}"></div>')($rootScope);
}).not.toThrow();
expect(element.attr('remove-attr')).toBeUndefined();
});
});
describe('SCE values', function() {
it('should resolve compile and link both attribute and text bindings', inject(
function($rootScope, $compile, $sce) {
$rootScope.name = $sce.trustAsHtml('angular');
element = $compile('<div name="attr: {{name}}">text: {{name}}</div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('text: angular');
expect(element.attr('name')).toEqual('attr: angular');
}));
});
describe('decorating with binding info', function() {
it('should not occur if `debugInfoEnabled` is false', function() {
module(function($compileProvider) {
$compileProvider.debugInfoEnabled(false);
});
inject(function($compile, $rootScope) {
element = $compile('<div>{{1+2}}</div>')($rootScope);
expect(element.hasClass('ng-binding')).toBe(false);
expect(element.data('$binding')).toBeUndefined();
});
});
it('should occur if `debugInfoEnabled` is true', function() {
module(function($compileProvider) {
$compileProvider.debugInfoEnabled(true);
});
inject(function($compile, $rootScope) {
element = $compile('<div>{{1+2}}</div>')($rootScope);
expect(element.hasClass('ng-binding')).toBe(true);
expect(element.data('$binding')).toEqual(['1+2']);
});
});
});
it('should observe interpolated attrs', inject(function($rootScope, $compile) {
$compile('<div some-attr="{{value}}" observer></div>')($rootScope);
// should be async
expect(observeSpy).not.toHaveBeenCalled();
$rootScope.$apply(function() {
$rootScope.value = 'bound-value';
});
expect(observeSpy).toHaveBeenCalledOnceWith('bound-value');
}));
it('should return a deregistration function while observing an attribute', inject(function($rootScope, $compile) {
$compile('<div some-attr="{{value}}" observer></div>')($rootScope);
$rootScope.$apply('value = "first-value"');
expect(observeSpy).toHaveBeenCalledWith('first-value');
deregisterObserver();
$rootScope.$apply('value = "new-value"');
expect(observeSpy).not.toHaveBeenCalledWith('new-value');
}));
it('should set interpolated attrs to initial interpolation value', inject(function($rootScope, $compile) {
// we need the interpolated attributes to be initialized so that linking fn in a component
// can access the value during link
$rootScope.whatever = 'test value';
$compile('<div some-attr="{{whatever}}" observer></div>')($rootScope);
expect(directiveAttrs.someAttr).toBe($rootScope.whatever);
}));
it('should allow directive to replace interpolated attributes before attr interpolation compilation', inject(
function($compile, $rootScope) {
element = $compile('<div some-attr="foo-{{1+1}}" replace-some-attr></div>')($rootScope);
$rootScope.$digest();
expect(element.attr('some-attr')).toEqual('bar-2');
}));
it('should call observer of non-interpolated attr through $evalAsync',
inject(function($rootScope, $compile) {
$compile('<div some-attr="nonBound" observer></div>')($rootScope);
expect(directiveAttrs.someAttr).toBe('nonBound');
expect(observeSpy).not.toHaveBeenCalled();
$rootScope.$digest();
expect(observeSpy).toHaveBeenCalled();
})
);
it('should call observer only when the attribute value changes', function() {
module(function() {
directive('observingDirective', function() {
return {
restrict: 'E',
scope: { someAttr: '@' }
};
});
});
inject(function($rootScope, $compile) {
$compile('<observing-directive observer></observing-directive>')($rootScope);
$rootScope.$digest();
expect(observeSpy).not.toHaveBeenCalledWith(undefined);
});
});
it('should delegate exceptions to $exceptionHandler', function() {
observeSpy = jasmine.createSpy('$observe attr').and.throwError('ERROR');
module(function($exceptionHandlerProvider) {
$exceptionHandlerProvider.mode('log');
directive('error', function() {
return function(scope, elm, attr) {
attr.$observe('someAttr', observeSpy);
attr.$observe('someAttr', observeSpy);
};
});
});
inject(function($compile, $rootScope, $exceptionHandler) {
$compile('<div some-attr="{{value}}" error></div>')($rootScope);
$rootScope.$digest();
expect(observeSpy).toHaveBeenCalled();
expect(observeSpy).toHaveBeenCalledTimes(2);
expect($exceptionHandler.errors).toEqual([new Error('ERROR'), new Error('ERROR')]);
});
});
it('should translate {{}} in terminal nodes', inject(function($rootScope, $compile) {
element = $compile('<select ng:model="x"><option value="">Greet {{name}}!</option></select>')($rootScope);
$rootScope.$digest();
expect(sortedHtml(element).replace(' selected="true"', '')).
toEqual('<select ng:model="x">' +
'<option value="">Greet !</option>' +
'</select>');
$rootScope.name = 'Misko';
$rootScope.$digest();
expect(sortedHtml(element).replace(' selected="true"', '')).
toEqual('<select ng:model="x">' +
'<option value="">Greet Misko!</option>' +
'</select>');
}));
it('should handle consecutive text elements as a single text element', inject(function($rootScope, $compile) {
// No point it running the test, if there is no MutationObserver
if (!window.MutationObserver) return;
// Create and register the MutationObserver
var observer = new window.MutationObserver(noop);
observer.observe(document.body, {childList: true, subtree: true});
// Run the actual test
var base = jqLite('<div>— {{ "This doesn\'t." }}</div>');
element = $compile(base)($rootScope);
$rootScope.$digest();
expect(element.text()).toBe('— This doesn\'t.');
// Unregister the MutationObserver (and hope it doesn't mess up with subsequent tests)
observer.disconnect();
}));
it('should not process text nodes merged into their sibling', inject(function($compile, $rootScope) {
var div = document.createElement('div');
div.appendChild(document.createTextNode('1{{ value }}'));
div.appendChild(document.createTextNode('2{{ value }}'));
div.appendChild(document.createTextNode('3{{ value }}'));
element = jqLite(div.childNodes);
var initialWatcherCount = $rootScope.$countWatchers();
$compile(element)($rootScope);
$rootScope.$apply('value = 0');
var newWatcherCount = $rootScope.$countWatchers() - initialWatcherCount;
expect(element.text()).toBe('102030');
expect(newWatcherCount).toBe(3);
dealoc(div);
}));
it('should support custom start/end interpolation symbols in template and directive template',
function() {
module(function($interpolateProvider, $compileProvider) {
$interpolateProvider.startSymbol('##').endSymbol(']]');
$compileProvider.directive('myDirective', function() {
return {
template: '<span>{{hello}}|{{hello|uppercase}}</span>'
};
});
});
inject(function($compile, $rootScope) {
element = $compile('<div>##hello|uppercase]]|<div my-directive></div></div>')($rootScope);
$rootScope.hello = 'ahoj';
$rootScope.$digest();
expect(element.text()).toBe('AHOJ|ahoj|AHOJ');
});
});
it('should support custom start interpolation symbol, even when `endSymbol` doesn\'t change',
function() {
module(function($compileProvider, $interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$compileProvider.directive('myDirective', function() {
return {
template: '<span>{{ hello }}|{{ hello | uppercase }}</span>'
};
});
});
inject(function($compile, $rootScope) {
var tmpl = '<div>[[ hello | uppercase }}|<div my-directive></div></div>';
element = $compile(tmpl)($rootScope);
$rootScope.hello = 'ahoj';
$rootScope.$digest();
expect(element.text()).toBe('AHOJ|ahoj|AHOJ');
});
}
);
it('should support custom end interpolation symbol, even when `startSymbol` doesn\'t change',
function() {
module(function($compileProvider, $interpolateProvider) {
$interpolateProvider.endSymbol(']]');
$compileProvider.directive('myDirective', function() {
return {
template: '<span>{{ hello }}|{{ hello | uppercase }}</span>'
};
});
});
inject(function($compile, $rootScope) {
var tmpl = '<div>{{ hello | uppercase ]]|<div my-directive></div></div>';
element = $compile(tmpl)($rootScope);
$rootScope.hello = 'ahoj';
$rootScope.$digest();
expect(element.text()).toBe('AHOJ|ahoj|AHOJ');
});
}
);
it('should support custom start/end interpolation symbols in async directive template',
function() {
module(function($interpolateProvider, $compileProvider) {
$interpolateProvider.startSymbol('##').endSymbol(']]');
$compileProvider.directive('myDirective', function() {
return {
templateUrl: 'myDirective.html'
};
});
});
inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('myDirective.html', '<span>{{hello}}|{{hello|uppercase}}</span>');
element = $compile('<div>##hello|uppercase]]|<div my-directive></div></div>')($rootScope);
$rootScope.hello = 'ahoj';
$rootScope.$digest();
expect(element.text()).toBe('AHOJ|ahoj|AHOJ');
});
});
it('should make attributes observable for terminal directives', function() {
module(function() {
directive('myAttr', function(log) {
return {
terminal: true,
link: function(scope, element, attrs) {
attrs.$observe('myAttr', function(val) {
log(val);
});
}
};
});
});
inject(function($compile, $rootScope, log) {
element = $compile('<div my-attr="{{myVal}}"></div>')($rootScope);
expect(log).toEqual([]);
$rootScope.myVal = 'carrot';
$rootScope.$digest();
expect(log).toEqual(['carrot']);
});
});
});
describe('collector', function() {
var collected;
beforeEach(module(function($compileProvider) {
collected = false;
$compileProvider.directive('testCollect', function() {
return {
restrict: 'EACM',
link: function() {
collected = true;
}
};
});
}));
it('should collect comment directives by default', inject(function() {
var html = '<!-- directive: test-collect -->';
element = $compile('<div>' + html + '</div>')($rootScope);
expect(collected).toBe(true);
}));
it('should collect css class directives by default', inject(function() {
element = $compile('<div class="test-collect"></div>')($rootScope);
expect(collected).toBe(true);
}));
forEach([
{commentEnabled: true, cssEnabled: true},
{commentEnabled: true, cssEnabled: false},
{commentEnabled: false, cssEnabled: true},
{commentEnabled: false, cssEnabled: false}
], function(config) {
describe('commentDirectivesEnabled(' + config.commentEnabled + ') ' +
'cssClassDirectivesEnabled(' + config.cssEnabled + ')', function() {
beforeEach(module(function($compileProvider) {
$compileProvider.commentDirectivesEnabled(config.commentEnabled);
$compileProvider.cssClassDirectivesEnabled(config.cssEnabled);
}));
var $compile, $rootScope;
beforeEach(inject(function(_$compile_,_$rootScope_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
it('should handle comment directives appropriately', function() {
var html = '<!-- directive: test-collect -->';
element = $compile('<div>' + html + '</div>')($rootScope);
expect(collected).toBe(config.commentEnabled);
});
it('should handle css directives appropriately', function() {
element = $compile('<div class="test-collect"></div>')($rootScope);
expect(collected).toBe(config.cssEnabled);
});
it('should not prevent to compile entity directives', function() {
element = $compile('<test-collect></test-collect>')($rootScope);
expect(collected).toBe(true);
});
it('should not prevent to compile attribute directives', function() {
element = $compile('<span test-collect></span>')($rootScope);
expect(collected).toBe(true);
});
it('should not prevent to compile interpolated expressions', function() {
element = $compile('<span>{{"text "+"interpolated"}}</span>')($rootScope);
$rootScope.$apply();
expect(element.text()).toBe('text interpolated');
});
it('should interpolate expressions inside class attribute', function() {
$rootScope.interpolateMe = 'interpolated';
var html = '<div class="{{interpolateMe}}"></div>';
element = $compile(html)($rootScope);
$rootScope.$apply();
expect(element).toHaveClass('interpolated');
});
});
});
it('should configure comment directives true by default',
module(function($compileProvider) {
var commentDirectivesEnabled = $compileProvider.commentDirectivesEnabled();
expect(commentDirectivesEnabled).toBe(true);
})
);
it('should return self when setting commentDirectivesEnabled',
module(function($compileProvider) {
var self = $compileProvider.commentDirectivesEnabled(true);
expect(self).toBe($compileProvider);
})
);
it('should cache commentDirectivesEnabled value when configure ends', function() {
var $compileProvider;
module(function(_$compileProvider_) {
$compileProvider = _$compileProvider_;
$compileProvider.commentDirectivesEnabled(false);
});
inject(function($compile, $rootScope) {
$compileProvider.commentDirectivesEnabled(true);
var html = '<!-- directive: test-collect -->';
element = $compile('<div>' + html + '</div>')($rootScope);
expect(collected).toBe(false);
});
});
it('should configure css class directives true by default',
module(function($compileProvider) {
var cssClassDirectivesEnabled = $compileProvider.cssClassDirectivesEnabled();
expect(cssClassDirectivesEnabled).toBe(true);
})
);
it('should return self when setting cssClassDirectivesEnabled',
module(function($compileProvider) {
var self = $compileProvider.cssClassDirectivesEnabled(true);
expect(self).toBe($compileProvider);
})
);
it('should cache cssClassDirectivesEnabled value when configure ends', function() {
var $compileProvider;
module(function(_$compileProvider_) {
$compileProvider = _$compileProvider_;
$compileProvider.cssClassDirectivesEnabled(false);
});
inject(function($compile, $rootScope) {
$compileProvider.cssClassDirectivesEnabled(true);
element = $compile('<div class="test-collect"></div>')($rootScope);
expect(collected).toBe(false);
});
});
});
describe('link phase', function() {
beforeEach(module(function() {
forEach(['a', 'b', 'c'], function(name) {
directive(name, function(log) {
return {
restrict: 'ECA',
compile: function() {
log('t' + uppercase(name));
return {
pre: function() {
log('pre' + uppercase(name));
},
post: function linkFn() {
log('post' + uppercase(name));
}
};
}
};
});
});
}));
it('should not store linkingFns for noop branches', inject(function($rootScope, $compile) {
element = jqLite('<div name="{{a}}"><span>ignore</span></div>');
var linkingFn = $compile(element);
// Now prune the branches with no directives
element.find('span').remove();
expect(element.find('span').length).toBe(0);
// and we should still be able to compile without errors
linkingFn($rootScope);
}));
it('should compile from top to bottom but link from bottom up', inject(
function($compile, $rootScope, log) {
element = $compile('<a b><c></c></a>')($rootScope);
expect(log).toEqual('tA; tB; tC; preA; preB; preC; postC; postB; postA');
}
));
it('should support link function on directive object', function() {
module(function() {
directive('abc', valueFn({
link: function(scope, element, attrs) {
element.text(attrs.abc);
}
}));
});
inject(function($compile, $rootScope) {
element = $compile('<div abc="WORKS">FAIL</div>')($rootScope);
expect(element.text()).toEqual('WORKS');
});
});
it('should support $observe inside link function on directive object', function() {
module(function() {
directive('testLink', valueFn({
templateUrl: 'test-link.html',
link: function(scope, element, attrs) {
attrs.$observe('testLink', function(val) {
scope.testAttr = val;
});
}
}));
});
inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('test-link.html', '{{testAttr}}');
element = $compile('<div test-link="{{1+2}}"></div>')($rootScope);
$rootScope.$apply();
expect(element.text()).toBe('3');
});
});
it('should throw multilink error when linking the same element more then once', function() {
var linker = $compile('<div>');
linker($rootScope).remove();
expect(function() {
linker($rootScope);
}).toThrowMinErr('$compile', 'multilink', 'This element has already been linked.');
});
});
describe('attrs', function() {
it('should allow setting of attributes', function() {
module(function() {
directive({
setter: valueFn(function(scope, element, attr) {
attr.$set('name', 'abc');
attr.$set('disabled', true);
expect(attr.name).toBe('abc');
expect(attr.disabled).toBe(true);
})
});
});
inject(function($rootScope, $compile) {
element = $compile('<div setter></div>')($rootScope);
expect(element.attr('name')).toEqual('abc');
expect(element.attr('disabled')).toEqual('disabled');
});
});
it('should read boolean attributes as boolean only on control elements', function() {
var value;
module(function() {
directive({
input: valueFn({
restrict: 'ECA',
link:function(scope, element, attr) {
value = attr.required;
}
})
});
});
inject(function($rootScope, $compile) {
element = $compile('<input required></input>')($rootScope);
expect(value).toEqual(true);
});
});
it('should read boolean attributes as text on non-controll elements', function() {
var value;
module(function() {
directive({
div: valueFn({
restrict: 'ECA',
link:function(scope, element, attr) {
value = attr.required;
}
})
});
});
inject(function($rootScope, $compile) {
element = $compile('<div required="some text"></div>')($rootScope);
expect(value).toEqual('some text');
});
});
it('should create new instance of attr for each template stamping', function() {
module(function($provide) {
var state = { first: [], second: [] };
$provide.value('state', state);
directive({
first: valueFn({
priority: 1,
compile: function(templateElement, templateAttr) {
return function(scope, element, attr) {
state.first.push({
template: {element: templateElement, attr:templateAttr},
link: {element: element, attr: attr}
});
};
}
}),
second: valueFn({
priority: 2,
compile: function(templateElement, templateAttr) {
return function(scope, element, attr) {
state.second.push({
template: {element: templateElement, attr:templateAttr},
link: {element: element, attr: attr}
});
};
}
})
});
});
inject(function($rootScope, $compile, state) {
var template = $compile('<div first second>');
dealoc(template($rootScope.$new(), noop));
dealoc(template($rootScope.$new(), noop));
// instance between directives should be shared
expect(state.first[0].template.element).toBe(state.second[0].template.element);
expect(state.first[0].template.attr).toBe(state.second[0].template.attr);
// the template and the link can not be the same instance
expect(state.first[0].template.element).not.toBe(state.first[0].link.element);
expect(state.first[0].template.attr).not.toBe(state.first[0].link.attr);
// each new template needs to be new instance
expect(state.first[0].link.element).not.toBe(state.first[1].link.element);
expect(state.first[0].link.attr).not.toBe(state.first[1].link.attr);
expect(state.second[0].link.element).not.toBe(state.second[1].link.element);
expect(state.second[0].link.attr).not.toBe(state.second[1].link.attr);
});
});
it('should properly $observe inside ng-repeat', function() {
var spies = [];
module(function() {
directive('observer', function() {
return function(scope, elm, attr) {
spies.push(jasmine.createSpy('observer ' + spies.length));
attr.$observe('some', spies[spies.length - 1]);
};
});
});
inject(function($compile, $rootScope) {
element = $compile('<div><div ng-repeat="i in items">' +
'<span some="id_{{i.id}}" observer></span>' +
'</div></div>')($rootScope);
$rootScope.$apply(function() {
$rootScope.items = [{id: 1}, {id: 2}];
});
expect(spies[0]).toHaveBeenCalledOnceWith('id_1');
expect(spies[1]).toHaveBeenCalledOnceWith('id_2');
spies[0].calls.reset();
spies[1].calls.reset();
$rootScope.$apply(function() {
$rootScope.items[0].id = 5;
});
expect(spies[0]).toHaveBeenCalledOnceWith('id_5');
});
});
describe('$set', function() {
var attr;
beforeEach(function() {
module(function() {
directive('input', valueFn({
restrict: 'ECA',
link: function(scope, element, attr) {
scope.attr = attr;
}
}));
});
inject(function($compile, $rootScope) {
element = $compile('<input></input>')($rootScope);
attr = $rootScope.attr;
expect(attr).toBeDefined();
});
});
it('should set attributes', function() {
attr.$set('ngMyAttr', 'value');
expect(element.attr('ng-my-attr')).toEqual('value');
expect(attr.ngMyAttr).toEqual('value');
});
it('should allow overriding of attribute name and remember the name', function() {
attr.$set('ngOther', '123', true, 'other');
expect(element.attr('other')).toEqual('123');
expect(attr.ngOther).toEqual('123');
attr.$set('ngOther', '246');
expect(element.attr('other')).toEqual('246');
expect(attr.ngOther).toEqual('246');
});
it('should remove attribute', function() {
attr.$set('ngMyAttr', 'value');
expect(element.attr('ng-my-attr')).toEqual('value');
attr.$set('ngMyAttr', undefined);
expect(element.attr('ng-my-attr')).toBeUndefined();
attr.$set('ngMyAttr', 'value');
attr.$set('ngMyAttr', null);
expect(element.attr('ng-my-attr')).toBeUndefined();
});
it('should not set DOM element attr if writeAttr false', function() {
attr.$set('test', 'value', false);
expect(element.attr('test')).toBeUndefined();
expect(attr.test).toBe('value');
});
});
});
forEach([true, false], function(preAssignBindingsEnabled) {
describe((preAssignBindingsEnabled ? 'with' : 'without') + ' pre-assigned bindings', function() {
beforeEach(module(function($compileProvider) {
$compileProvider.preAssignBindingsEnabled(preAssignBindingsEnabled);
}));
describe('controller lifecycle hooks', function() {
describe('$onInit', function() {
it('should call `$onInit`, if provided, after all the controllers on the element have been initialized', function() {
function check() {
expect(this.element.controller('d1').id).toEqual(1);
expect(this.element.controller('d2').id).toEqual(2);
}
function Controller1($element) { this.id = 1; this.element = $element; }
Controller1.prototype.$onInit = jasmine.createSpy('$onInit').and.callFake(check);
function Controller2($element) { this.id = 2; this.element = $element; }
Controller2.prototype.$onInit = jasmine.createSpy('$onInit').and.callFake(check);
angular.module('my', [])
.directive('d1', valueFn({ controller: Controller1 }))
.directive('d2', valueFn({ controller: Controller2 }));
module('my');
inject(function($compile, $rootScope) {
element = $compile('<div d1 d2></div>')($rootScope);
expect(Controller1.prototype.$onInit).toHaveBeenCalledOnce();
expect(Controller2.prototype.$onInit).toHaveBeenCalledOnce();
});
});
it('should continue to trigger other `$onInit` hooks if one throws an error', function() {
function ThrowingController() {
this.$onInit = function() {
throw new Error('bad hook');
};
}
function LoggingController($log) {
this.$onInit = function() {
$log.info('onInit');
};
}
angular.module('my', [])
.component('c1', {
controller: ThrowingController,
bindings: {'prop': '<'}
})
.component('c2', {
controller: LoggingController,
bindings: {'prop': '<'}
})
.config(function($exceptionHandlerProvider) {
// We need to test with the exceptionHandler not rethrowing...
$exceptionHandlerProvider.mode('log');
});
module('my');
inject(function($compile, $rootScope, $exceptionHandler, $log) {
// Setup the directive with bindings that will keep updating the bound value forever
element = $compile('<div><c1 prop="a"></c1><c2 prop="a"></c2>')($rootScope);
// The first component's error should be logged
expect($exceptionHandler.errors.pop()).toEqual(new Error('bad hook'));
// The second component's hook should still be called
expect($log.info.logs.pop()).toEqual(['onInit']);
});
});
});
describe('$onDestroy', function() {
it('should call `$onDestroy`, if provided, on the controller when its scope is destroyed', function() {
function TestController() { this.count = 0; }
TestController.prototype.$onDestroy = function() { this.count++; };
angular.module('my', [])
.directive('d1', valueFn({ scope: true, controller: TestController }))
.directive('d2', valueFn({ scope: {}, controller: TestController }))
.directive('d3', valueFn({ controller: TestController }));
module('my');
inject(function($compile, $rootScope) {
element = $compile('<div><d1 ng-if="show[0]"></d1><d2 ng-if="show[1]"></d2><div ng-if="show[2]"><d3></d3></div></div>')($rootScope);
$rootScope.$apply('show = [true, true, true]');
var d1Controller = element.find('d1').controller('d1');
var d2Controller = element.find('d2').controller('d2');
var d3Controller = element.find('d3').controller('d3');
expect([d1Controller.count, d2Controller.count, d3Controller.count]).toEqual([0,0,0]);
$rootScope.$apply('show = [false, true, true]');
expect([d1Controller.count, d2Controller.count, d3Controller.count]).toEqual([1,0,0]);
$rootScope.$apply('show = [false, false, true]');
expect([d1Controller.count, d2Controller.count, d3Controller.count]).toEqual([1,1,0]);
$rootScope.$apply('show = [false, false, false]');
expect([d1Controller.count, d2Controller.count, d3Controller.count]).toEqual([1,1,1]);
});
});
it('should call `$onDestroy` top-down (the same as `scope.$broadcast`)', function() {
var log = [];
function ParentController() { log.push('parent created'); }
ParentController.prototype.$onDestroy = function() { log.push('parent destroyed'); };
function ChildController() { log.push('child created'); }
ChildController.prototype.$onDestroy = function() { log.push('child destroyed'); };
function GrandChildController() { log.push('grand child created'); }
GrandChildController.prototype.$onDestroy = function() { log.push('grand child destroyed'); };
angular.module('my', [])
.directive('parent', valueFn({ scope: true, controller: ParentController }))
.directive('child', valueFn({ scope: true, controller: ChildController }))
.directive('grandChild', valueFn({ scope: true, controller: GrandChildController }));
module('my');
inject(function($compile, $rootScope) {
element = $compile('<parent ng-if="show"><child><grand-child></grand-child></child></parent>')($rootScope);
$rootScope.$apply('show = true');
expect(log).toEqual(['parent created', 'child created', 'grand child created']);
log = [];
$rootScope.$apply('show = false');
expect(log).toEqual(['parent destroyed', 'child destroyed', 'grand child destroyed']);
});
});
});
describe('$postLink', function() {
it('should call `$postLink`, if provided, after the element has completed linking (i.e. post-link)', function() {
var log = [];
function Controller1() { }
Controller1.prototype.$postLink = function() { log.push('d1 view init'); };
function Controller2() { }
Controller2.prototype.$postLink = function() { log.push('d2 view init'); };
angular.module('my', [])
.directive('d1', valueFn({
controller: Controller1,
link: { pre: function(s, e) { log.push('d1 pre: ' + e.text()); }, post: function(s, e) { log.push('d1 post: ' + e.text()); } },
template: '<d2></d2>'
}))
.directive('d2', valueFn({
controller: Controller2,
link: { pre: function(s, e) { log.push('d2 pre: ' + e.text()); }, post: function(s, e) { log.push('d2 post: ' + e.text()); } },
template: 'loaded'
}));
module('my');
inject(function($compile, $rootScope) {
element = $compile('<d1></d1>')($rootScope);
expect(log).toEqual([
'd1 pre: loaded',
'd2 pre: loaded',
'd2 post: loaded',
'd2 view init',
'd1 post: loaded',
'd1 view init'
]);
});
});
});
describe('$doCheck', function() {
it('should call `$doCheck`, if provided, for each digest cycle, after $onChanges and $onInit', function() {
var log = [];
function TestController() { }
TestController.prototype.$doCheck = function() { log.push('$doCheck'); };
TestController.prototype.$onChanges = function() { log.push('$onChanges'); };
TestController.prototype.$onInit = function() { log.push('$onInit'); };
angular.module('my', [])
.component('dcc', {
controller: TestController,
bindings: { 'prop1': '<' }
});
module('my');
inject(function($compile, $rootScope) {
element = $compile('<dcc prop1="val"></dcc>')($rootScope);
expect(log).toEqual([
'$onChanges',
'$onInit',
'$doCheck'
]);
// Clear log
log = [];
$rootScope.$apply();
expect(log).toEqual([
'$doCheck',
'$doCheck'
]);
// Clear log
log = [];
$rootScope.$apply('val = 2');
expect(log).toEqual([
'$doCheck',
'$onChanges',
'$doCheck'
]);
});
});
it('should work if $doCheck is provided in the constructor', function() {
var log = [];
function TestController() {
this.$doCheck = function() { log.push('$doCheck'); };
this.$onChanges = function() { log.push('$onChanges'); };
this.$onInit = function() { log.push('$onInit'); };
}
angular.module('my', [])
.component('dcc', {
controller: TestController,
bindings: { 'prop1': '<' }
});
module('my');
inject(function($compile, $rootScope) {
element = $compile('<dcc prop1="val"></dcc>')($rootScope);
expect(log).toEqual([
'$onChanges',
'$onInit',
'$doCheck'
]);
// Clear log
log = [];
$rootScope.$apply();
expect(log).toEqual([
'$doCheck',
'$doCheck'
]);
// Clear log
log = [];
$rootScope.$apply('val = 2');
expect(log).toEqual([
'$doCheck',
'$onChanges',
'$doCheck'
]);
});
});
});
describe('$onChanges', function() {
it('should call `$onChanges`, if provided, when a one-way (`<`) or interpolation (`@`) bindings are updated', function() {
var log = [];
function TestController() { }
TestController.prototype.$onChanges = function(change) { log.push(change); };
angular.module('my', [])
.component('c1', {
controller: TestController,
bindings: { 'prop1': '<', 'prop2': '<', 'other': '=', 'attr': '@' }
});
module('my');
inject(function($compile, $rootScope) {
// Setup a watch to indicate some complicated updated logic
$rootScope.$watch('val', function(val, oldVal) { $rootScope.val2 = val * 2; });
// Setup the directive with two bindings
element = $compile('<c1 prop1="val" prop2="val2" other="val3" attr="{{val4}}"></c1>')($rootScope);
expect(log).toEqual([
{
prop1: jasmine.objectContaining({currentValue: undefined}),
prop2: jasmine.objectContaining({currentValue: undefined}),
attr: jasmine.objectContaining({currentValue: ''})
}
]);
// Clear the initial changes from the log
log = [];
// Update val to trigger the onChanges
$rootScope.$apply('val = 42');
// Now we should have a single changes entry in the log
expect(log).toEqual([
{
prop1: jasmine.objectContaining({currentValue: 42}),
prop2: jasmine.objectContaining({currentValue: 84})
}
]);
// Clear the log
log = [];
// Update val to trigger the onChanges
$rootScope.$apply('val = 17');
// Now we should have a single changes entry in the log
expect(log).toEqual([
{
prop1: jasmine.objectContaining({previousValue: 42, currentValue: 17}),
prop2: jasmine.objectContaining({previousValue: 84, currentValue: 34})
}
]);
// Clear the log
log = [];
// Update val3 to trigger the "other" two-way binding
$rootScope.$apply('val3 = 63');
// onChanges should not have been called
expect(log).toEqual([]);
// Update val4 to trigger the "attr" interpolation binding
$rootScope.$apply('val4 = 22');
// onChanges should not have been called
expect(log).toEqual([
{
attr: jasmine.objectContaining({previousValue: '', currentValue: '22'})
}
]);
});
});
it('should trigger `$onChanges` even if the inner value already equals the new outer value', function() {
var log = [];
function TestController() { }
TestController.prototype.$onChanges = function(change) { log.push(change); };
angular.module('my', [])
.component('c1', {
controller: TestController,
bindings: { 'prop1': '<' }
});
module('my');
inject(function($compile, $rootScope) {
element = $compile('<c1 prop1="val"></c1>')($rootScope);
$rootScope.$apply('val = 1');
expect(log.pop()).toEqual({prop1: jasmine.objectContaining({previousValue: undefined, currentValue: 1})});
element.isolateScope().$ctrl.prop1 = 2;
$rootScope.$apply('val = 2');
expect(log.pop()).toEqual({prop1: jasmine.objectContaining({previousValue: 1, currentValue: 2})});
});
});
it('should pass the original value as `previousValue` even if there were multiple changes in a single digest', function() {
var log = [];
function TestController() { }
TestController.prototype.$onChanges = function(change) { log.push(change); };
angular.module('my', [])
.component('c1', {
controller: TestController,
bindings: { 'prop': '<' }
});
module('my');
inject(function($compile, $rootScope) {
element = $compile('<c1 prop="a + b"></c1>')($rootScope);
// We add this watch after the compilation to ensure that it will run after the binding watchers
// therefore triggering the thing that this test is hoping to enforce
$rootScope.$watch('a', function(val) { $rootScope.b = val * 2; });
expect(log).toEqual([{prop: jasmine.objectContaining({currentValue: undefined})}]);
// Clear the initial values from the log
log = [];
// Update val to trigger the onChanges
$rootScope.$apply('a = 42');
// Now the change should have the real previous value (undefined), not the intermediate one (42)
expect(log).toEqual([{prop: jasmine.objectContaining({currentValue: 126})}]);
// Clear the log
log = [];
// Update val to trigger the onChanges
$rootScope.$apply('a = 7');
// Now the change should have the real previous value (126), not the intermediate one, (91)
expect(log).toEqual([{prop: jasmine.objectContaining({previousValue: 126, currentValue: 21})}]);
});
});
it('should trigger an initial onChanges call for each binding with the `isFirstChange()` returning true', function() {
var log = [];
function TestController() { }
TestController.prototype.$onChanges = function(change) { log.push(change); };
angular.module('my', [])
.component('c1', {
controller: TestController,
bindings: { 'prop': '<', attr: '@' }
});
module('my');
inject(function($compile, $rootScope) {
$rootScope.$apply('a = 7');
element = $compile('<c1 prop="a" attr="{{a}}"></c1>')($rootScope);
expect(log).toEqual([
{
prop: jasmine.objectContaining({currentValue: 7}),
attr: jasmine.objectContaining({currentValue: '7'})
}
]);
expect(log[0].prop.isFirstChange()).toEqual(true);
expect(log[0].attr.isFirstChange()).toEqual(true);
log = [];
$rootScope.$apply('a = 9');
expect(log).toEqual([
{
prop: jasmine.objectContaining({previousValue: 7, currentValue: 9}),
attr: jasmine.objectContaining({previousValue: '7', currentValue: '9'})
}
]);
expect(log[0].prop.isFirstChange()).toEqual(false);
expect(log[0].attr.isFirstChange()).toEqual(false);
});
});
it('should trigger an initial onChanges call for each binding even if the hook is defined in the constructor', function() {
var log = [];
function TestController() {
this.$onChanges = function(change) { log.push(change); };
}
angular.module('my', [])
.component('c1', {
controller: TestController,
bindings: { 'prop': '<', attr: '@' }
});
module('my');
inject(function($compile, $rootScope) {
$rootScope.$apply('a = 7');
element = $compile('<c1 prop="a" attr="{{a}}"></c1>')($rootScope);
expect(log).toEqual([
{
prop: jasmine.objectContaining({currentValue: 7}),
attr: jasmine.objectContaining({currentValue: '7'})
}
]);
expect(log[0].prop.isFirstChange()).toEqual(true);
expect(log[0].attr.isFirstChange()).toEqual(true);
log = [];
$rootScope.$apply('a = 10');
expect(log).toEqual([
{
prop: jasmine.objectContaining({previousValue: 7, currentValue: 10}),
attr: jasmine.objectContaining({previousValue: '7', currentValue: '10'})
}
]);
expect(log[0].prop.isFirstChange()).toEqual(false);
expect(log[0].attr.isFirstChange()).toEqual(false);
});
});
it('should clean up `@`-binding observers when re-assigning bindings', function() {
var constructorSpy = jasmine.createSpy('constructor');
var prototypeSpy = jasmine.createSpy('prototype');
function TestController() {
return {$onChanges: constructorSpy};
}
TestController.prototype.$onChanges = prototypeSpy;
module(function($compileProvider) {
$compileProvider.component('test', {
bindings: {attr: '@'},
controller: TestController
});
});
inject(function($compile, $rootScope) {
var template = '<test attr="{{a}}"></test>';
$rootScope.a = 'foo';
element = $compile(template)($rootScope);
$rootScope.$digest();
expect(constructorSpy).toHaveBeenCalled();
expect(prototypeSpy).not.toHaveBeenCalled();
constructorSpy.calls.reset();
$rootScope.$apply('a = "bar"');
expect(constructorSpy).toHaveBeenCalled();
expect(prototypeSpy).not.toHaveBeenCalled();
});
});
it('should not call `$onChanges` twice even when the initial value is `NaN`', function() {
var onChangesSpy = jasmine.createSpy('$onChanges');
module(function($compileProvider) {
$compileProvider.component('test', {
bindings: {prop: '<', attr: '@'},
controller: function TestController() {
this.$onChanges = onChangesSpy;
}
});
});
inject(function($compile, $rootScope) {
var template = '<test prop="a" attr="{{a}}"></test>' +
'<test prop="b" attr="{{b}}"></test>';
$rootScope.a = 'foo';
$rootScope.b = NaN;
element = $compile(template)($rootScope);
$rootScope.$digest();
expect(onChangesSpy).toHaveBeenCalledTimes(2);
expect(onChangesSpy.calls.argsFor(0)[0]).toEqual({
prop: jasmine.objectContaining({currentValue: 'foo'}),
attr: jasmine.objectContaining({currentValue: 'foo'})
});
expect(onChangesSpy.calls.argsFor(1)[0]).toEqual({
prop: jasmine.objectContaining({currentValue: NaN}),
attr: jasmine.objectContaining({currentValue: 'NaN'})
});
onChangesSpy.calls.reset();
$rootScope.$apply('a = "bar"; b = 42');
expect(onChangesSpy).toHaveBeenCalledTimes(2);
expect(onChangesSpy.calls.argsFor(0)[0]).toEqual({
prop: jasmine.objectContaining({previousValue: 'foo', currentValue: 'bar'}),
attr: jasmine.objectContaining({previousValue: 'foo', currentValue: 'bar'})
});
expect(onChangesSpy.calls.argsFor(1)[0]).toEqual({
prop: jasmine.objectContaining({previousValue: NaN, currentValue: 42}),
attr: jasmine.objectContaining({previousValue: 'NaN', currentValue: '42'})
});
});
});
it('should only trigger one extra digest however many controllers have changes', function() {
var log = [];
function TestController1() { }
TestController1.prototype.$onChanges = function(change) { log.push(['TestController1', change]); };
function TestController2() { }
TestController2.prototype.$onChanges = function(change) { log.push(['TestController2', change]); };
angular.module('my', [])
.component('c1', {
controller: TestController1,
bindings: {'prop': '<'}
})
.component('c2', {
controller: TestController2,
bindings: {'prop': '<'}
});
module('my');
inject(function($compile, $rootScope) {
// Create a watcher to count the number of digest cycles
var watchCount = 0;
$rootScope.$watch(function() { watchCount++; });
// Setup two sibling components with bindings that will change
element = $compile('<div><c1 prop="val1"></c1><c2 prop="val2"></c2></div>')($rootScope);
// Clear out initial changes
log = [];
// Update val to trigger the onChanges
$rootScope.$apply('val1 = 42; val2 = 17');
expect(log).toEqual([
['TestController1', {prop: jasmine.objectContaining({currentValue: 42})}],
['TestController2', {prop: jasmine.objectContaining({currentValue: 17})}]
]);
// A single apply should only trigger three turns of the digest loop
expect(watchCount).toEqual(3);
});
});
it('should cope with changes occurring inside `$onChanges()` hooks', function() {
var log = [];
function OuterController() {}
OuterController.prototype.$onChanges = function(change) {
log.push(['OuterController', change]);
// Make a change to the inner component
this.b = this.prop1 * 2;
};
function InnerController() { }
InnerController.prototype.$onChanges = function(change) { log.push(['InnerController', change]); };
angular.module('my', [])
.component('outer', {
controller: OuterController,
bindings: {'prop1': '<'},
template: '<inner prop2="$ctrl.b"></inner>'
})
.component('inner', {
controller: InnerController,
bindings: {'prop2': '<'}
});
module('my');
inject(function($compile, $rootScope) {
// Setup the directive with two bindings
element = $compile('<outer prop1="a"></outer>')($rootScope);
// Clear out initial changes
log = [];
// Update val to trigger the onChanges
$rootScope.$apply('a = 42');
expect(log).toEqual([
['OuterController', {prop1: jasmine.objectContaining({previousValue: undefined, currentValue: 42})}],
['InnerController', {prop2: jasmine.objectContaining({previousValue: NaN, currentValue: 84})}]
]);
});
});
it('should throw an error if `$onChanges()` hooks are not stable', function() {
function TestController() {}
TestController.prototype.$onChanges = function(change) {
this.onChange();
};
angular.module('my', [])
.component('c1', {
controller: TestController,
bindings: {'prop': '<', onChange: '&'}
});
module('my');
inject(function($compile, $rootScope) {
// Setup the directive with bindings that will keep updating the bound value forever
element = $compile('<c1 prop="a" on-change="a = -a"></c1>')($rootScope);
// Update val to trigger the unstable onChanges, which will result in an error
expect(function() {
$rootScope.$apply('a = 42');
}).toThrowMinErr('$compile', 'infchng');
dealoc(element);
element = $compile('<c1 prop="b" on-change=""></c1>')($rootScope);
$rootScope.$apply('b = 24');
$rootScope.$apply('b = 48');
});
});
it('should log an error if `$onChanges()` hooks are not stable', function() {
function TestController() {}
TestController.prototype.$onChanges = function(change) {
this.onChange();
};
angular.module('my', [])
.component('c1', {
controller: TestController,
bindings: {'prop': '<', onChange: '&'}
})
.config(function($exceptionHandlerProvider) {
// We need to test with the exceptionHandler not rethrowing...
$exceptionHandlerProvider.mode('log');
});
module('my');
inject(function($compile, $rootScope, $exceptionHandler) {
// Setup the directive with bindings that will keep updating the bound value forever
element = $compile('<c1 prop="a" on-change="a = -a"></c1>')($rootScope);
// Update val to trigger the unstable onChanges, which will result in an error
$rootScope.$apply('a = 42');
expect($exceptionHandler.errors.length).toEqual(1);
expect($exceptionHandler.errors[0]).
toEqualMinErr('$compile', 'infchng', '10 $onChanges() iterations reached.');
});
});
it('should continue to trigger other `$onChanges` hooks if one throws an error', function() {
function ThrowingController() {
this.$onChanges = function(change) {
throw new Error('bad hook');
};
}
function LoggingController($log) {
this.$onChanges = function(change) {
$log.info('onChange');
};
}
angular.module('my', [])
.component('c1', {
controller: ThrowingController,
bindings: {'prop': '<'}
})
.component('c2', {
controller: LoggingController,
bindings: {'prop': '<'}
})
.config(function($exceptionHandlerProvider) {
// We need to test with the exceptionHandler not rethrowing...
$exceptionHandlerProvider.mode('log');
});
module('my');
inject(function($compile, $rootScope, $exceptionHandler, $log) {
// Setup the directive with bindings that will keep updating the bound value forever
element = $compile('<div><c1 prop="a"></c1><c2 prop="a"></c2>')($rootScope);
// The first component's error should be logged
expect($exceptionHandler.errors.pop()).toEqual(new Error('bad hook'));
// The second component's changes should still be called
expect($log.info.logs.pop()).toEqual(['onChange']);
$rootScope.$apply('a = 42');
// The first component's error should be logged
var errors = $exceptionHandler.errors.pop();
expect(errors[0]).toEqual(new Error('bad hook'));
// The second component's changes should still be called
expect($log.info.logs.pop()).toEqual(['onChange']);
});
});
it('should collect up all `$onChanges` errors into one throw', function() {
function ThrowingController() {
this.$onChanges = function(change) {
throw new Error('bad hook: ' + this.prop);
};
}
angular.module('my', [])
.component('c1', {
controller: ThrowingController,
bindings: {'prop': '<'}
})
.config(function($exceptionHandlerProvider) {
// We need to test with the exceptionHandler not rethrowing...
$exceptionHandlerProvider.mode('log');
});
module('my');
inject(function($compile, $rootScope, $exceptionHandler, $log) {
// Setup the directive with bindings that will keep updating the bound value forever
element = $compile('<div><c1 prop="a"></c1><c1 prop="a * 2"></c1>')($rootScope);
// Both component's errors should be logged
expect($exceptionHandler.errors.pop()).toEqual(new Error('bad hook: NaN'));
expect($exceptionHandler.errors.pop()).toEqual(new Error('bad hook: undefined'));
$rootScope.$apply('a = 42');
// Both component's error should be logged
var errors = $exceptionHandler.errors.pop();
expect(errors.pop()).toEqual(new Error('bad hook: 84'));
expect(errors.pop()).toEqual(new Error('bad hook: 42'));
});
});
});
});
describe('isolated locals', function() {
var componentScope, regularScope;
beforeEach(module(function() {
directive('myComponent', function() {
return {
scope: {
attr: '@',
attrAlias: '@attr',
ref: '=',
refAlias: '= ref',
reference: '=',
optref: '=?',
optrefAlias: '=? optref',
optreference: '=?',
colref: '=*',
colrefAlias: '=* colref',
owRef: '<',
owRefAlias: '< owRef',
owOptref: '<?',
owOptrefAlias: '<? owOptref',
expr: '&',
optExpr: '&?',
exprAlias: '&expr',
constructor: '&?'
},
link: function(scope) {
componentScope = scope;
}
};
});
directive('badDeclaration', function() {
return {
scope: { attr: 'xxx' }
};
});
directive('storeScope', function() {
return {
link: function(scope) {
regularScope = scope;
}
};
});
}));
it('should give other directives the parent scope', inject(function($rootScope) {
compile('<div><input type="text" my-component store-scope ng-model="value"></div>');
$rootScope.$apply(function() {
$rootScope.value = 'from-parent';
});
expect(element.find('input').val()).toBe('from-parent');
expect(componentScope).not.toBe(regularScope);
expect(componentScope.$parent).toBe(regularScope);
}));
it('should not give the isolate scope to other directive template', function() {
module(function() {
directive('otherTplDir', function() {
return {
template: 'value: {{value}}'
};
});
});
inject(function($rootScope) {
compile('<div my-component other-tpl-dir>');
$rootScope.$apply(function() {
$rootScope.value = 'from-parent';
});
expect(element.html()).toBe('value: from-parent');
});
});
it('should not give the isolate scope to other directive template (with templateUrl)', function() {
module(function() {
directive('otherTplDir', function() {
return {
templateUrl: 'other.html'
};
});
});
inject(function($rootScope, $templateCache) {
$templateCache.put('other.html', 'value: {{value}}');
compile('<div my-component other-tpl-dir>');
$rootScope.$apply(function() {
$rootScope.value = 'from-parent';
});
expect(element.html()).toBe('value: from-parent');
});
});
it('should not give the isolate scope to regular child elements', function() {
inject(function($rootScope) {
compile('<div my-component>value: {{value}}</div>');
$rootScope.$apply(function() {
$rootScope.value = 'from-parent';
});
expect(element.html()).toBe('value: from-parent');
});
});
it('should update parent scope when "="-bound NaN changes', inject(function($compile, $rootScope) {
$rootScope.num = NaN;
compile('<div my-component reference="num"></div>');
var isolateScope = element.isolateScope();
expect(isolateScope.reference).toBeNaN();
isolateScope.$apply(function(scope) { scope.reference = 64; });
expect($rootScope.num).toBe(64);
}));
it('should update isolate scope when "="-bound NaN changes', inject(function($compile, $rootScope) {
$rootScope.num = NaN;
compile('<div my-component reference="num"></div>');
var isolateScope = element.isolateScope();
expect(isolateScope.reference).toBeNaN();
$rootScope.$apply(function(scope) { scope.num = 64; });
expect(isolateScope.reference).toBe(64);
}));
it('should be able to bind attribute names which are present in Object.prototype', function() {
module(function() {
directive('inProtoAttr', valueFn({
scope: {
'constructor': '@',
'toString': '&',
// Spidermonkey extension, may be obsolete in the future
'watch': '='
}
}));
});
inject(function($rootScope) {
expect(function() {
compile('<div in-proto-attr constructor="hello, world" watch="[]" ' +
'to-string="value = !value"></div>');
}).not.toThrow();
var isolateScope = element.isolateScope();
expect(typeof isolateScope.constructor).toBe('string');
expect(isArray(isolateScope.watch)).toBe(true);
expect(typeof isolateScope.toString).toBe('function');
expect($rootScope.value).toBeUndefined();
isolateScope.toString();
expect($rootScope.value).toBe(true);
});
});
it('should be able to interpolate attribute names which are present in Object.prototype', function() {
var attrs;
module(function() {
directive('attrExposer', valueFn({
link: function($scope, $element, $attrs) {
attrs = $attrs;
}
}));
});
inject(function($compile, $rootScope) {
$compile('<div attr-exposer to-string="{{1 + 1}}">')($rootScope);
$rootScope.$apply();
expect(attrs.toString).toBe('2');
});
});
it('should not initialize scope value if optional expression binding is not passed', inject(function($compile) {
compile('<div my-component></div>');
var isolateScope = element.isolateScope();
expect(isolateScope.optExpr).toBeUndefined();
}));
it('should not initialize scope value if optional expression binding with Object.prototype name is not passed', inject(function($compile) {
compile('<div my-component></div>');
var isolateScope = element.isolateScope();
expect(isolateScope.constructor).toBe($rootScope.constructor);
}));
it('should initialize scope value if optional expression binding is passed', inject(function($compile) {
compile('<div my-component opt-expr="value = \'did!\'"></div>');
var isolateScope = element.isolateScope();
expect(typeof isolateScope.optExpr).toBe('function');
expect(isolateScope.optExpr()).toBe('did!');
expect($rootScope.value).toBe('did!');
}));
it('should initialize scope value if optional expression binding with Object.prototype name is passed', inject(function($compile) {
compile('<div my-component constructor="value = \'did!\'"></div>');
var isolateScope = element.isolateScope();
expect(typeof isolateScope.constructor).toBe('function');
expect(isolateScope.constructor()).toBe('did!');
expect($rootScope.value).toBe('did!');
}));
it('should not overwrite @-bound property each digest when not present', function() {
module(function($compileProvider) {
$compileProvider.directive('testDir', valueFn({
scope: {prop: '@'},
controller: function($scope) {
$scope.prop = $scope.prop || 'default';
this.getProp = function() {
return $scope.prop;
};
},
controllerAs: 'ctrl',
template: '<p></p>'
}));
});
inject(function($compile, $rootScope) {
element = $compile('<div test-dir></div>')($rootScope);
var scope = element.isolateScope();
expect(scope.ctrl.getProp()).toBe('default');
$rootScope.$digest();
expect(scope.ctrl.getProp()).toBe('default');
});
});
it('should ignore optional "="-bound property if value is the empty string', function() {
module(function($compileProvider) {
$compileProvider.directive('testDir', valueFn({
scope: {prop: '=?'},
controller: function($scope) {
$scope.prop = $scope.prop || 'default';
this.getProp = function() {
return $scope.prop;
};
},
controllerAs: 'ctrl',
template: '<p></p>'
}));
});
inject(function($compile, $rootScope) {
element = $compile('<div test-dir></div>')($rootScope);
var scope = element.isolateScope();
expect(scope.ctrl.getProp()).toBe('default');
$rootScope.$digest();
expect(scope.ctrl.getProp()).toBe('default');
scope.prop = 'foop';
$rootScope.$digest();
expect(scope.ctrl.getProp()).toBe('foop');
});
});
describe('bind-once', function() {
function countWatches(scope) {
var result = 0;
while (scope !== null) {
result += (scope.$$watchers && scope.$$watchers.length) || 0;
result += countWatches(scope.$$childHead);
scope = scope.$$nextSibling;
}
return result;
}
it('should be possible to one-time bind a parameter on a component with a template', function() {
module(function() {
directive('otherTplDir', function() {
return {
scope: {param1: '=', param2: '='},
template: '1:{{param1}};2:{{param2}};3:{{::param1}};4:{{::param2}}'
};
});
});
inject(function($rootScope) {
compile('<div other-tpl-dir param1="::foo" param2="bar"></div>');
expect(countWatches($rootScope)).toEqual(6); // 4 -> template watch group, 2 -> '='
$rootScope.$digest();
expect(element.html()).toBe('1:;2:;3:;4:');
expect(countWatches($rootScope)).toEqual(6);
$rootScope.foo = 'foo';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:;3:foo;4:');
expect(countWatches($rootScope)).toEqual(4);
$rootScope.foo = 'baz';
$rootScope.bar = 'bar';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:bar;3:foo;4:bar');
expect(countWatches($rootScope)).toEqual(3);
$rootScope.bar = 'baz';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:baz;3:foo;4:bar');
});
});
it('should be possible to one-time bind a parameter on a component with a template', function() {
module(function() {
directive('otherTplDir', function() {
return {
scope: {param1: '@', param2: '@'},
template: '1:{{param1}};2:{{param2}};3:{{::param1}};4:{{::param2}}'
};
});
});
inject(function($rootScope) {
compile('<div other-tpl-dir param1="{{::foo}}" param2="{{bar}}"></div>');
expect(countWatches($rootScope)).toEqual(6); // 4 -> template watch group, 2 -> {{ }}
$rootScope.$digest();
expect(element.html()).toBe('1:;2:;3:;4:');
expect(countWatches($rootScope)).toEqual(4); // (- 2) -> bind-once in template
$rootScope.foo = 'foo';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:;3:;4:');
expect(countWatches($rootScope)).toEqual(3);
$rootScope.foo = 'baz';
$rootScope.bar = 'bar';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:bar;3:;4:');
expect(countWatches($rootScope)).toEqual(3);
$rootScope.bar = 'baz';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:baz;3:;4:');
});
});
it('should be possible to one-time bind a parameter on a component with a template', function() {
module(function() {
directive('otherTplDir', function() {
return {
scope: {param1: '=', param2: '='},
templateUrl: 'other.html'
};
});
});
inject(function($rootScope, $templateCache) {
$templateCache.put('other.html', '1:{{param1}};2:{{param2}};3:{{::param1}};4:{{::param2}}');
compile('<div other-tpl-dir param1="::foo" param2="bar"></div>');
$rootScope.$digest();
expect(element.html()).toBe('1:;2:;3:;4:');
expect(countWatches($rootScope)).toEqual(6); // 4 -> template watch group, 2 -> '='
$rootScope.foo = 'foo';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:;3:foo;4:');
expect(countWatches($rootScope)).toEqual(4);
$rootScope.foo = 'baz';
$rootScope.bar = 'bar';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:bar;3:foo;4:bar');
expect(countWatches($rootScope)).toEqual(3);
$rootScope.bar = 'baz';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:baz;3:foo;4:bar');
});
});
it('should be possible to one-time bind a parameter on a component with a template', function() {
module(function() {
directive('otherTplDir', function() {
return {
scope: {param1: '@', param2: '@'},
templateUrl: 'other.html'
};
});
});
inject(function($rootScope, $templateCache) {
$templateCache.put('other.html', '1:{{param1}};2:{{param2}};3:{{::param1}};4:{{::param2}}');
compile('<div other-tpl-dir param1="{{::foo}}" param2="{{bar}}"></div>');
$rootScope.$digest();
expect(element.html()).toBe('1:;2:;3:;4:');
expect(countWatches($rootScope)).toEqual(4); // (4 - 2) -> template watch group, 2 -> {{ }}
$rootScope.foo = 'foo';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:;3:;4:');
expect(countWatches($rootScope)).toEqual(3);
$rootScope.foo = 'baz';
$rootScope.bar = 'bar';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:bar;3:;4:');
expect(countWatches($rootScope)).toEqual(3);
$rootScope.bar = 'baz';
$rootScope.$digest();
expect(element.html()).toBe('1:foo;2:baz;3:;4:');
});
});
it('should continue with a digets cycle when there is a two-way binding from the child to the parent', function() {
module(function() {
directive('hello', function() {
return {
restrict: 'E',
scope: { greeting: '=' },
template: '<button ng-click="setGreeting()">Say hi!</button>',
link: function(scope) {
scope.setGreeting = function() { scope.greeting = 'Hello!'; };
}
};
});
});
inject(function($rootScope) {
compile('<div>' +
'<p>{{greeting}}</p>' +
'<div><hello greeting="greeting"></hello></div>' +
'</div>');
$rootScope.$digest();
browserTrigger(element.find('button'), 'click');
expect(element.find('p').text()).toBe('Hello!');
});
});
});
describe('attribute', function() {
it('should copy simple attribute', inject(function() {
compile('<div><span my-component attr="some text">');
expect(componentScope.attr).toEqual('some text');
expect(componentScope.attrAlias).toEqual('some text');
expect(componentScope.attrAlias).toEqual(componentScope.attr);
}));
it('should copy an attribute with spaces', inject(function() {
compile('<div><span my-component attr=" some text ">');
expect(componentScope.attr).toEqual(' some text ');
expect(componentScope.attrAlias).toEqual(' some text ');
expect(componentScope.attrAlias).toEqual(componentScope.attr);
}));
it('should set up the interpolation before it reaches the link function', inject(function() {
$rootScope.name = 'misko';
compile('<div><span my-component attr="hello {{name}}">');
expect(componentScope.attr).toEqual('hello misko');
expect(componentScope.attrAlias).toEqual('hello misko');
}));
it('should update when interpolated attribute updates', inject(function() {
compile('<div><span my-component attr="hello {{name}}">');
$rootScope.name = 'igor';
$rootScope.$apply();
expect(componentScope.attr).toEqual('hello igor');
expect(componentScope.attrAlias).toEqual('hello igor');
}));
});
describe('object reference', function() {
it('should update local when origin changes', inject(function() {
compile('<div><span my-component ref="name">');
expect(componentScope.ref).toBeUndefined();
expect(componentScope.refAlias).toBe(componentScope.ref);
$rootScope.name = 'misko';
$rootScope.$apply();
expect($rootScope.name).toBe('misko');
expect(componentScope.ref).toBe('misko');
expect(componentScope.refAlias).toBe('misko');
$rootScope.name = {};
$rootScope.$apply();
expect(componentScope.ref).toBe($rootScope.name);
expect(componentScope.refAlias).toBe($rootScope.name);
}));
it('should update local when both change', inject(function() {
compile('<div><span my-component ref="name">');
$rootScope.name = {mark:123};
componentScope.ref = 'misko';
$rootScope.$apply();
expect($rootScope.name).toEqual({mark:123});
expect(componentScope.ref).toBe($rootScope.name);
expect(componentScope.refAlias).toBe($rootScope.name);
$rootScope.name = 'igor';
componentScope.ref = {};
$rootScope.$apply();
expect($rootScope.name).toEqual('igor');
expect(componentScope.ref).toBe($rootScope.name);
expect(componentScope.refAlias).toBe($rootScope.name);
}));
it('should not break if local and origin both change to the same value', inject(function() {
$rootScope.name = 'aaa';
compile('<div><span my-component ref="name">');
//change both sides to the same item within the same digest cycle
componentScope.ref = 'same';
$rootScope.name = 'same';
$rootScope.$apply();
//change origin back to its previous value
$rootScope.name = 'aaa';
$rootScope.$apply();
expect($rootScope.name).toBe('aaa');
expect(componentScope.ref).toBe('aaa');
}));
it('should complain on non assignable changes', inject(function() {
compile('<div><span my-component ref="\'hello \' + name">');
$rootScope.name = 'world';
$rootScope.$apply();
expect(componentScope.ref).toBe('hello world');
componentScope.ref = 'ignore me';
expect(function() { $rootScope.$apply(); }).
toThrowMinErr('$compile', 'nonassign', 'Expression \'\'hello \' + name\' in attribute \'ref\' used with directive \'myComponent\' is non-assignable!');
expect(componentScope.ref).toBe('hello world');
// reset since the exception was rethrown which prevented phase clearing
$rootScope.$$phase = null;
$rootScope.name = 'misko';
$rootScope.$apply();
expect(componentScope.ref).toBe('hello misko');
}));
it('should complain if assigning to undefined', inject(function() {
compile('<div><span my-component>');
$rootScope.$apply();
expect(componentScope.ref).toBeUndefined();
componentScope.ref = 'ignore me';
expect(function() { $rootScope.$apply(); }).
toThrowMinErr('$compile', 'nonassign', 'Expression \'undefined\' in attribute \'ref\' used with directive \'myComponent\' is non-assignable!');
expect(componentScope.ref).toBeUndefined();
$rootScope.$$phase = null; // reset since the exception was rethrown which prevented phase clearing
$rootScope.$apply();
expect(componentScope.ref).toBeUndefined();
}));
// regression
it('should stabilize model', inject(function() {
compile('<div><span my-component reference="name">');
var lastRefValueInParent;
$rootScope.$watch('name', function(ref) {
lastRefValueInParent = ref;
});
$rootScope.name = 'aaa';
$rootScope.$apply();
componentScope.reference = 'new';
$rootScope.$apply();
expect(lastRefValueInParent).toBe('new');
}));
describe('literal objects', function() {
it('should copy parent changes', inject(function() {
compile('<div><span my-component reference="{name: name}">');
$rootScope.name = 'a';
$rootScope.$apply();
expect(componentScope.reference).toEqual({name: 'a'});
$rootScope.name = 'b';
$rootScope.$apply();
expect(componentScope.reference).toEqual({name: 'b'});
}));
it('should not change the component when parent does not change', inject(function() {
compile('<div><span my-component reference="{name: name}">');
$rootScope.name = 'a';
$rootScope.$apply();
var lastComponentValue = componentScope.reference;
$rootScope.$apply();
expect(componentScope.reference).toBe(lastComponentValue);
}));
it('should complain when the component changes', inject(function() {
compile('<div><span my-component reference="{name: name}">');
$rootScope.name = 'a';
$rootScope.$apply();
componentScope.reference = {name: 'b'};
expect(function() {
$rootScope.$apply();
}).toThrowMinErr('$compile', 'nonassign', 'Expression \'{name: name}\' in attribute \'reference\' used with directive \'myComponent\' is non-assignable!');
}));
it('should work for primitive literals', inject(function() {
test('1', 1);
test('null', null);
test('undefined', undefined);
test('\'someString\'', 'someString');
test('true', true);
function test(literalString, literalValue) {
compile('<div><span my-component reference="' + literalString + '">');
$rootScope.$apply();
expect(componentScope.reference).toBe(literalValue);
dealoc(element);
}
}));
});
});
describe('optional object reference', function() {
it('should update local when origin changes', inject(function() {
compile('<div><span my-component optref="name">');
expect(componentScope.optRef).toBeUndefined();
expect(componentScope.optRefAlias).toBe(componentScope.optRef);
$rootScope.name = 'misko';
$rootScope.$apply();
expect(componentScope.optref).toBe($rootScope.name);
expect(componentScope.optrefAlias).toBe($rootScope.name);
$rootScope.name = {};
$rootScope.$apply();
expect(componentScope.optref).toBe($rootScope.name);
expect(componentScope.optrefAlias).toBe($rootScope.name);
}));
it('should not throw exception when reference does not exist', inject(function() {
compile('<div><span my-component>');
expect(componentScope.optref).toBeUndefined();
expect(componentScope.optrefAlias).toBeUndefined();
expect(componentScope.optreference).toBeUndefined();
}));
});
describe('collection object reference', function() {
it('should update isolate scope when origin scope changes', inject(function() {
$rootScope.collection = [{
name: 'Gabriel',
value: 18
}, {
name: 'Tony',
value: 91
}];
$rootScope.query = '';
$rootScope.$apply();
compile('<div><span my-component colref="collection | filter:query">');
expect(componentScope.colref).toEqual($rootScope.collection);
expect(componentScope.colrefAlias).toEqual(componentScope.colref);
$rootScope.query = 'Gab';
$rootScope.$apply();
expect(componentScope.colref).toEqual([$rootScope.collection[0]]);
expect(componentScope.colrefAlias).toEqual([$rootScope.collection[0]]);
}));
it('should update origin scope when isolate scope changes', inject(function() {
$rootScope.collection = [{
name: 'Gabriel',
value: 18
}, {
name: 'Tony',
value: 91
}];
compile('<div><span my-component colref="collection">');
var newItem = {
name: 'Pablo',
value: 10
};
componentScope.colref.push(newItem);
componentScope.$apply();
expect($rootScope.collection[2]).toEqual(newItem);
}));
});
describe('one-way binding', function() {
it('should update isolate when the identity of origin changes', inject(function() {
compile('<div><span my-component ow-ref="obj">');
expect(componentScope.owRef).toBeUndefined();
expect(componentScope.owRefAlias).toBe(componentScope.owRef);
$rootScope.obj = {value: 'initial'};
$rootScope.$apply();
expect($rootScope.obj).toEqual({value: 'initial'});
expect(componentScope.owRef).toEqual({value: 'initial'});
expect(componentScope.owRefAlias).toBe(componentScope.owRef);
// This changes in both scopes because of reference
$rootScope.obj.value = 'origin1';
$rootScope.$apply();
expect(componentScope.owRef.value).toBe('origin1');
expect(componentScope.owRefAlias.value).toBe('origin1');
componentScope.owRef = {value: 'isolate1'};
componentScope.$apply();
expect($rootScope.obj.value).toBe('origin1');
// Change does not propagate because object identity hasn't changed
$rootScope.obj.value = 'origin2';
$rootScope.$apply();
expect(componentScope.owRef.value).toBe('isolate1');
expect(componentScope.owRefAlias.value).toBe('origin2');
// Change does propagate because object identity changes
$rootScope.obj = {value: 'origin3'};
$rootScope.$apply();
expect(componentScope.owRef.value).toBe('origin3');
expect(componentScope.owRef).toBe($rootScope.obj);
expect(componentScope.owRefAlias).toBe($rootScope.obj);
}));
it('should update isolate when both change', inject(function() {
compile('<div><span my-component ow-ref="name">');
$rootScope.name = {mark:123};
componentScope.owRef = 'misko';
$rootScope.$apply();
expect($rootScope.name).toEqual({mark:123});
expect(componentScope.owRef).toBe($rootScope.name);
expect(componentScope.owRefAlias).toBe($rootScope.name);
$rootScope.name = 'igor';
componentScope.owRef = {};
$rootScope.$apply();
expect($rootScope.name).toEqual('igor');
expect(componentScope.owRef).toBe($rootScope.name);
expect(componentScope.owRefAlias).toBe($rootScope.name);
}));
describe('initialization', function() {
var component, log;
beforeEach(function() {
log = [];
angular.module('owComponentTest', [])
.component('owComponent', {
bindings: { input: '<' },
controller: function() {
component = this;
this.input = 'constructor';
log.push('constructor');
this.$onInit = function() {
this.input = '$onInit';
log.push('$onInit');
};
this.$onChanges = function(changes) {
if (changes.input) {
log.push(['$onChanges', copy(changes.input)]);
}
};
}
});
});
it('should not update isolate again after $onInit if outer has not changed', function() {
module('owComponentTest');
inject(function() {
$rootScope.name = 'outer';
compile('<ow-component input="name"></ow-component>');
expect($rootScope.name).toEqual('outer');
expect(component.input).toEqual('$onInit');
$rootScope.$digest();
expect($rootScope.name).toEqual('outer');
expect(component.input).toEqual('$onInit');
expect(log).toEqual([
'constructor',
['$onChanges', jasmine.objectContaining({ currentValue: 'outer' })],
'$onInit'
]);
});
});
it('should not update isolate again after $onInit if outer object reference has not changed', function() {
module('owComponentTest');
inject(function() {
$rootScope.name = ['outer'];
compile('<ow-component input="name"></ow-component>');
expect($rootScope.name).toEqual(['outer']);
expect(component.input).toEqual('$onInit');
$rootScope.name[0] = 'inner';
$rootScope.$digest();
expect($rootScope.name).toEqual(['inner']);
expect(component.input).toEqual('$onInit');
expect(log).toEqual([
'constructor',
['$onChanges', jasmine.objectContaining({ currentValue: ['outer'] })],
'$onInit'
]);
});
});
it('should update isolate again after $onInit if outer object reference changes even if equal', function() {
module('owComponentTest');
inject(function() {
$rootScope.name = ['outer'];
compile('<ow-component input="name"></ow-component>');
expect($rootScope.name).toEqual(['outer']);
expect(component.input).toEqual('$onInit');
$rootScope.name = ['outer'];
$rootScope.$digest();
expect($rootScope.name).toEqual(['outer']);
expect(component.input).toEqual(['outer']);
expect(log).toEqual([
'constructor',
['$onChanges', jasmine.objectContaining({ currentValue: ['outer'] })],
'$onInit',
['$onChanges', jasmine.objectContaining({ previousValue: ['outer'], currentValue: ['outer'] })]
]);
});
});
it('should not update isolate again after $onInit if outer is a literal', function() {
module('owComponentTest');
inject(function() {
$rootScope.name = 'outer';
compile('<ow-component input="[name]"></ow-component>');
expect(component.input).toEqual('$onInit');
// No outer change
$rootScope.$apply('name = "outer"');
expect(component.input).toEqual('$onInit');
// Outer change
$rootScope.$apply('name = "re-outer"');
expect(component.input).toEqual(['re-outer']);
expect(log).toEqual([
'constructor',
[
'$onChanges',
jasmine.objectContaining({currentValue: ['outer']})
],
'$onInit',
[
'$onChanges',
jasmine.objectContaining({previousValue: ['outer'], currentValue: ['re-outer']})
]
]);
});
});
it('should update isolate again after $onInit if outer has changed (before initial watchAction call)', function() {
module('owComponentTest');
inject(function() {
$rootScope.name = 'outer1';
compile('<ow-component input="name"></ow-component>');
expect(component.input).toEqual('$onInit');
$rootScope.$apply('name = "outer2"');
expect($rootScope.name).toEqual('outer2');
expect(component.input).toEqual('outer2');
expect(log).toEqual([
'constructor',
['$onChanges', jasmine.objectContaining({ currentValue: 'outer1' })],
'$onInit',
['$onChanges', jasmine.objectContaining({ currentValue: 'outer2', previousValue: 'outer1' })]
]);
});
});
it('should update isolate again after $onInit if outer has changed (before initial watchAction call)', function() {
angular.module('owComponentTest')
.directive('changeInput', function() {
return function(scope, elem, attrs) {
scope.name = 'outer2';
};
});
module('owComponentTest');
inject(function() {
$rootScope.name = 'outer1';
compile('<ow-component input="name" change-input></ow-component>');
expect(component.input).toEqual('$onInit');
$rootScope.$digest();
expect($rootScope.name).toEqual('outer2');
expect(component.input).toEqual('outer2');
expect(log).toEqual([
'constructor',
['$onChanges', jasmine.objectContaining({ currentValue: 'outer1' })],
'$onInit',
['$onChanges', jasmine.objectContaining({ currentValue: 'outer2', previousValue: 'outer1' })]
]);
});
});
});
it('should not break when isolate and origin both change to the same value', inject(function() {
$rootScope.name = 'aaa';
compile('<div><span my-component ow-ref="name">');
//change both sides to the same item within the same digest cycle
componentScope.owRef = 'same';
$rootScope.name = 'same';
$rootScope.$apply();
//change origin back to its previous value
$rootScope.name = 'aaa';
$rootScope.$apply();
expect($rootScope.name).toBe('aaa');
expect(componentScope.owRef).toBe('aaa');
}));
it('should not update origin when identity of isolate changes', inject(function() {
$rootScope.name = {mark:123};
compile('<div><span my-component ow-ref="name">');
expect($rootScope.name).toEqual({mark:123});
expect(componentScope.owRef).toBe($rootScope.name);
expect(componentScope.owRefAlias).toBe($rootScope.name);
componentScope.owRef = 'martin';
$rootScope.$apply();
expect($rootScope.name).toEqual({mark: 123});
expect(componentScope.owRef).toBe('martin');
expect(componentScope.owRefAlias).toEqual({mark: 123});
}));
it('should update origin when property of isolate object reference changes', inject(function() {
$rootScope.obj = {mark:123};
compile('<div><span my-component ow-ref="obj">');
expect($rootScope.obj).toEqual({mark:123});
expect(componentScope.owRef).toBe($rootScope.obj);
componentScope.owRef.mark = 789;
$rootScope.$apply();
expect($rootScope.obj).toEqual({mark: 789});
expect(componentScope.owRef).toBe($rootScope.obj);
}));
it('should not throw on non assignable expressions in the parent', inject(function() {
compile('<div><span my-component ow-ref="\'hello \' + name">');
$rootScope.name = 'world';
$rootScope.$apply();
expect(componentScope.owRef).toBe('hello world');
componentScope.owRef = 'ignore me';
expect(componentScope.owRef).toBe('ignore me');
expect($rootScope.name).toBe('world');
$rootScope.name = 'misko';
$rootScope.$apply();
expect(componentScope.owRef).toBe('hello misko');
}));
it('should not throw when assigning to undefined', inject(function() {
compile('<div><span my-component>');
expect(componentScope.owRef).toBeUndefined();
componentScope.owRef = 'ignore me';
expect(componentScope.owRef).toBe('ignore me');
$rootScope.$apply();
expect(componentScope.owRef).toBe('ignore me');
}));
it('should update isolate scope when "<"-bound NaN changes', inject(function() {
$rootScope.num = NaN;
compile('<div my-component ow-ref="num"></div>');
var isolateScope = element.isolateScope();
expect(isolateScope.owRef).toBeNaN();
$rootScope.num = 64;
$rootScope.$apply();
expect(isolateScope.owRef).toBe(64);
}));
describe('literal objects', function() {
it('should copy parent changes', inject(function() {
compile('<div><span my-component ow-ref="{name: name}">');
$rootScope.name = 'a';
$rootScope.$apply();
expect(componentScope.owRef).toEqual({name: 'a'});
$rootScope.name = 'b';
$rootScope.$apply();
expect(componentScope.owRef).toEqual({name: 'b'});
}));
it('should not change the isolated scope when origin does not change', inject(function() {
compile('<div><span my-component ref="{name: name}">');
$rootScope.name = 'a';
$rootScope.$apply();
var lastComponentValue = componentScope.owRef;
$rootScope.$apply();
expect(componentScope.owRef).toBe(lastComponentValue);
}));
it('should deep-watch array literals', inject(function() {
$rootScope.name = 'georgios';
$rootScope.obj = {name: 'pete'};
compile('<div><span my-component ow-ref="[{name: name}, obj]">');
expect(componentScope.owRef).toEqual([{name: 'georgios'}, {name: 'pete'}]);
$rootScope.name = 'lucas';
$rootScope.obj = {name: 'martin'};
$rootScope.$apply();
expect(componentScope.owRef).toEqual([{name: 'lucas'}, {name: 'martin'}]);
}));
it('should deep-watch object literals', inject(function() {
$rootScope.name = 'georgios';
$rootScope.obj = {name: 'pete'};
compile('<div><span my-component ow-ref="{name: name, item: obj}">');
expect(componentScope.owRef).toEqual({name: 'georgios', item: {name: 'pete'}});
$rootScope.name = 'lucas';
$rootScope.obj = {name: 'martin'};
$rootScope.$apply();
expect(componentScope.owRef).toEqual({name: 'lucas', item: {name: 'martin'}});
}));
it('should not complain when the isolated scope changes', inject(function() {
compile('<div><span my-component ow-ref="{name: name}">');
$rootScope.name = 'a';
$rootScope.$apply();
componentScope.owRef = {name: 'b'};
componentScope.$apply();
expect(componentScope.owRef).toEqual({name: 'b'});
expect($rootScope.name).toBe('a');
$rootScope.name = 'c';
$rootScope.$apply();
expect(componentScope.owRef).toEqual({name: 'c'});
}));
it('should work for primitive literals', inject(function() {
test('1', 1);
test('null', null);
test('undefined', undefined);
test('\'someString\'', 'someString');
test('true', true);
function test(literalString, literalValue) {
compile('<div><span my-component ow-ref="' + literalString + '">');
expect(componentScope.owRef).toBe(literalValue);
dealoc(element);
}
}));
describe('optional one-way binding', function() {
it('should update local when origin changes', inject(function() {
compile('<div><span my-component ow-optref="name">');
expect(componentScope.owOptref).toBeUndefined();
expect(componentScope.owOptrefAlias).toBe(componentScope.owOptref);
$rootScope.name = 'misko';
$rootScope.$apply();
expect(componentScope.owOptref).toBe($rootScope.name);
expect(componentScope.owOptrefAlias).toBe($rootScope.name);
$rootScope.name = {};
$rootScope.$apply();
expect(componentScope.owOptref).toBe($rootScope.name);
expect(componentScope.owOptrefAlias).toBe($rootScope.name);
}));
it('should not throw exception when reference does not exist', inject(function() {
compile('<div><span my-component>');
expect(componentScope.owOptref).toBeUndefined();
expect(componentScope.owOptrefAlias).toBeUndefined();
}));
});
});
});
describe('executable expression', function() {
it('should allow expression execution with locals', inject(function() {
compile('<div><span my-component expr="count = count + offset">');
$rootScope.count = 2;
expect(typeof componentScope.expr).toBe('function');
expect(typeof componentScope.exprAlias).toBe('function');
expect(componentScope.expr({offset: 1})).toEqual(3);
expect($rootScope.count).toEqual(3);
expect(componentScope.exprAlias({offset: 10})).toEqual(13);
expect($rootScope.count).toEqual(13);
}));
});
it('should throw on unknown definition', inject(function() {
expect(function() {
compile('<div><span bad-declaration>');
}).toThrowMinErr('$compile', 'iscp', 'Invalid isolate scope definition for directive \'badDeclaration\'. Definition: {... attr: \'xxx\' ...}');
}));
it('should expose a $$isolateBindings property onto the scope', inject(function() {
compile('<div><span my-component>');
expect(typeof componentScope.$$isolateBindings).toBe('object');
expect(componentScope.$$isolateBindings.attr.mode).toBe('@');
expect(componentScope.$$isolateBindings.attr.attrName).toBe('attr');
expect(componentScope.$$isolateBindings.attrAlias.attrName).toBe('attr');
expect(componentScope.$$isolateBindings.ref.mode).toBe('=');
expect(componentScope.$$isolateBindings.ref.attrName).toBe('ref');
expect(componentScope.$$isolateBindings.refAlias.attrName).toBe('ref');
expect(componentScope.$$isolateBindings.reference.mode).toBe('=');
expect(componentScope.$$isolateBindings.reference.attrName).toBe('reference');
expect(componentScope.$$isolateBindings.owRef.mode).toBe('<');
expect(componentScope.$$isolateBindings.owRef.attrName).toBe('owRef');
expect(componentScope.$$isolateBindings.owRefAlias.attrName).toBe('owRef');
expect(componentScope.$$isolateBindings.expr.mode).toBe('&');
expect(componentScope.$$isolateBindings.expr.attrName).toBe('expr');
expect(componentScope.$$isolateBindings.exprAlias.attrName).toBe('expr');
var firstComponentScope = componentScope,
first$$isolateBindings = componentScope.$$isolateBindings;
dealoc(element);
compile('<div><span my-component>');
expect(componentScope).not.toBe(firstComponentScope);
expect(componentScope.$$isolateBindings).toBe(first$$isolateBindings);
}));
it('should expose isolate scope variables on controller with controllerAs when bindToController is true (template)', function() {
var controllerCalled = false;
module(function($compileProvider) {
$compileProvider.directive('fooDir', valueFn({
template: '<p>isolate</p>',
scope: {
'data': '=dirData',
'oneway': '<dirData',
'str': '@dirStr',
'fn': '&dirFn'
},
controller: function($scope) {
this.check = function() {
expect(this.data).toEqualData({
'foo': 'bar',
'baz': 'biz'
});
expect(this.oneway).toEqualData({
'foo': 'bar',
'baz': 'biz'
});
expect(this.str).toBe('Hello, world!');
expect(this.fn()).toBe('called!');
};
if (preAssignBindingsEnabled) {
this.check();
} else {
this.$onInit = this.check;
}
controllerCalled = true;
},
controllerAs: 'test',
bindToController: true
}));
});
inject(function($compile, $rootScope) {
$rootScope.fn = valueFn('called!');
$rootScope.whom = 'world';
$rootScope.remoteData = {
'foo': 'bar',
'baz': 'biz'
};
element = $compile('<div foo-dir dir-data="remoteData" ' +
'dir-str="Hello, {{whom}}!" ' +
'dir-fn="fn()"></div>')($rootScope);
expect(controllerCalled).toBe(true);
});
});
it('should not pre-assign bound properties to the controller if `preAssignBindingsEnabled` is disabled', function() {
var controllerCalled = false, onInitCalled = false;
module(function($compileProvider) {
$compileProvider.preAssignBindingsEnabled(false);
$compileProvider.directive('fooDir', valueFn({
template: '<p>isolate</p>',
scope: {
'data': '=dirData',
'oneway': '<dirData',
'str': '@dirStr',
'fn': '&dirFn'
},
controller: function($scope) {
expect(this.data).toBeUndefined();
expect(this.oneway).toBeUndefined();
expect(this.str).toBeUndefined();
expect(this.fn).toBeUndefined();
controllerCalled = true;
this.$onInit = function() {
expect(this.data).toEqualData({
'foo': 'bar',
'baz': 'biz'
});
expect(this.oneway).toEqualData({
'foo': 'bar',
'baz': 'biz'
});
expect(this.str).toBe('Hello, world!');
expect(this.fn()).toBe('called!');
onInitCalled = true;
};
},
controllerAs: 'test',
bindToController: true
}));
});
inject(function($compile, $rootScope) {
$rootScope.fn = valueFn('called!');
$rootScope.whom = 'world';
$rootScope.remoteData = {
'foo': 'bar',
'baz': 'biz'
};
element = $compile('<div foo-dir dir-data="remoteData" ' +
'dir-str="Hello, {{whom}}!" ' +
'dir-fn="fn()"></div>')($rootScope);
expect(controllerCalled).toBe(true);
expect(onInitCalled).toBe(true);
});
});
it('should pre-assign bound properties to the controller if `preAssignBindingsEnabled` is enabled', function() {
var controllerCalled = false, onInitCalled = false;
module(function($compileProvider) {
$compileProvider.preAssignBindingsEnabled(true);
$compileProvider.directive('fooDir', valueFn({
template: '<p>isolate</p>',
scope: {
'data': '=dirData',
'oneway': '<dirData',
'str': '@dirStr',
'fn': '&dirFn'
},
controller: function($scope) {
expect(this.data).toEqualData({
'foo': 'bar',
'baz': 'biz'
});
expect(this.oneway).toEqualData({
'foo': 'bar',
'baz': 'biz'
});
expect(this.str).toBe('Hello, world!');
expect(this.fn()).toBe('called!');
controllerCalled = true;
this.$onInit = function() {
onInitCalled = true;
};
},
controllerAs: 'test',
bindToController: true
}));
});
inject(function($compile, $rootScope) {
$rootScope.fn = valueFn('called!');
$rootScope.whom = 'world';
$rootScope.remoteData = {
'foo': 'bar',
'baz': 'biz'
};
element = $compile('<div foo-dir dir-data="remoteData" ' +
'dir-str="Hello, {{whom}}!" ' +
'dir-fn="fn()"></div>')($rootScope);
expect(controllerCalled).toBe(true);
expect(onInitCalled).toBe(true);
});
});
it('should eventually expose isolate scope variables on ES6 class controller with controllerAs when bindToController is true', function() {
if (!/chrome/i.test(window.navigator.userAgent)) return;
var controllerCalled = false;
// eslint-disable-next-line no-eval
var Controller = eval(
'class Foo {\n' +
' constructor($scope) {}\n' +
' $onInit() { this.check(); }\n' +
' check() {\n' +
' expect(this.data).toEqualData({\n' +
' \'foo\': \'bar\',\n' +
' \'baz\': \'biz\'\n' +
' });\n' +
' expect(this.oneway).toEqualData({\n' +
' \'foo\': \'bar\',\n' +
' \'baz\': \'biz\'\n' +
' });\n' +
' expect(this.str).toBe(\'Hello, world!\');\n' +
' expect(this.fn()).toBe(\'called!\');\n' +
' controllerCalled = true;\n' +
' }\n' +
'}');
spyOn(Controller.prototype, '$onInit').and.callThrough();
module(function($compileProvider) {
$compileProvider.directive('fooDir', valueFn({
template: '<p>isolate</p>',
scope: {
'data': '=dirData',
'oneway': '<dirData',
'str': '@dirStr',
'fn': '&dirFn'
},
controller: Controller,
controllerAs: 'test',
bindToController: true
}));
});
inject(function($compile, $rootScope) {
$rootScope.fn = valueFn('called!');
$rootScope.whom = 'world';
$rootScope.remoteData = {
'foo': 'bar',
'baz': 'biz'
};
element = $compile('<div foo-dir dir-data="remoteData" ' +
'dir-str="Hello, {{whom}}!" ' +
'dir-fn="fn()"></div>')($rootScope);
expect(Controller.prototype.$onInit).toHaveBeenCalled();
expect(controllerCalled).toBe(true);
});
});
it('should update @-bindings on controller when bindToController and attribute change observed', function() {
module(function($compileProvider) {
$compileProvider.directive('atBinding', valueFn({
template: '<p>{{At.text}}</p>',
scope: {
text: '@atBinding'
},
controller: function($scope) {},
bindToController: true,
controllerAs: 'At'
}));
});
inject(function($compile, $rootScope) {
element = $compile('<div at-binding="Test: {{text}}"></div>')($rootScope);
var p = element.find('p');
$rootScope.$digest();
expect(p.text()).toBe('Test: ');
$rootScope.text = 'Kittens';
$rootScope.$digest();
expect(p.text()).toBe('Test: Kittens');
});
});
it('should expose isolate scope variables on controller with controllerAs when bindToController is true (templateUrl)', function() {
var controllerCalled = false;
module(function($compileProvider) {
$compileProvider.directive('fooDir', valueFn({
templateUrl: 'test.html',
scope: {
'data': '=dirData',
'oneway': '<dirData',
'str': '@dirStr',
'fn': '&dirFn'
},
controller: function($scope) {
this.check = function() {
expect(this.data).toEqualData({
'foo': 'bar',
'baz': 'biz'
});
expect(this.oneway).toEqualData({
'foo': 'bar',
'baz': 'biz'
});
expect(this.str).toBe('Hello, world!');
expect(this.fn()).toBe('called!');
};
if (preAssignBindingsEnabled) {
this.check();
} else {
this.$onInit = this.check;
}
controllerCalled = true;
},
controllerAs: 'test',
bindToController: true
}));
});
inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('test.html', '<p>isolate</p>');
$rootScope.fn = valueFn('called!');
$rootScope.whom = 'world';
$rootScope.remoteData = {
'foo': 'bar',
'baz': 'biz'
};
element = $compile('<div foo-dir dir-data="remoteData" ' +
'dir-str="Hello, {{whom}}!" ' +
'dir-fn="fn()"></div>')($rootScope);
$rootScope.$digest();
expect(controllerCalled).toBe(true);
});
});
it('should throw noctrl when missing controller', function() {
module(function($compileProvider) {
$compileProvider.directive('noCtrl', valueFn({
templateUrl: 'test.html',
scope: {
'data': '=dirData',
'oneway': '<dirData',
'str': '@dirStr',
'fn': '&dirFn'
},
controllerAs: 'test',
bindToController: true
}));
});
inject(function($compile, $rootScope) {
expect(function() {
$compile('<div no-ctrl>')($rootScope);
}).toThrowMinErr('$compile', 'noctrl',
'Cannot bind to controller without directive \'noCtrl\'s controller.');
});
});
it('should throw badrestrict on first compilation when restrict is invalid', function() {
module(function($compileProvider, $exceptionHandlerProvider) {
$compileProvider.directive('invalidRestrictBadString', valueFn({restrict: '"'}));
$compileProvider.directive('invalidRestrictTrue', valueFn({restrict: true}));
$compileProvider.directive('invalidRestrictObject', valueFn({restrict: {}}));
$compileProvider.directive('invalidRestrictNumber', valueFn({restrict: 42}));
// We need to test with the exceptionHandler not rethrowing...
$exceptionHandlerProvider.mode('log');
});
inject(function($exceptionHandler, $compile, $rootScope) {
$compile('<div invalid-restrict-true>')($rootScope);
expect($exceptionHandler.errors.length).toBe(1);
expect($exceptionHandler.errors[0]).toMatch(/\$compile.*badrestrict.*'true'/);
$compile('<div invalid-restrict-bad-string>')($rootScope);
$compile('<div invalid-restrict-bad-string>')($rootScope);
expect($exceptionHandler.errors.length).toBe(2);
expect($exceptionHandler.errors[1]).toMatch(/\$compile.*badrestrict.*'"'/);
$compile('<div invalid-restrict-bad-string invalid-restrict-object>')($rootScope);
expect($exceptionHandler.errors.length).toBe(3);
expect($exceptionHandler.errors[2]).toMatch(/\$compile.*badrestrict.*'{}'/);
$compile('<div invalid-restrict-object invalid-restrict-number>')($rootScope);
expect($exceptionHandler.errors.length).toBe(4);
expect($exceptionHandler.errors[3]).toMatch(/\$compile.*badrestrict.*'42'/);
});
});
describe('should bind to controller via object notation', function() {
var controllerOptions = [{
description: 'no controller identifier',
controller: 'myCtrl'
}, {
description: '"Ctrl as ident" syntax',
controller: 'myCtrl as myCtrl'
}, {
description: 'controllerAs setting',
controller: 'myCtrl',
controllerAs: 'myCtrl'
}],
scopeOptions = [{
description: 'isolate scope',
scope: {}
}, {
description: 'new scope',
scope: true
}, {
description: 'no scope',
scope: false
}],
templateOptions = [{
description: 'inline template',
template: '<p>template</p>'
}, {
description: 'templateUrl setting',
templateUrl: 'test.html'
}, {
description: 'no template'
}];
forEach(controllerOptions, function(controllerOption) {
forEach(scopeOptions, function(scopeOption) {
forEach(templateOptions, function(templateOption) {
var description = [],
ddo = {
bindToController: {
'data': '=dirData',
'oneway': '<dirData',
'str': '@dirStr',
'fn': '&dirFn'
}
};
forEach([controllerOption, scopeOption, templateOption], function(option) {
description.push(option.description);
delete option.description;
extend(ddo, option);
});
it('(' + description.join(', ') + ')', function() {
var controllerCalled = false;
module(function($compileProvider, $controllerProvider) {
$controllerProvider.register('myCtrl', function() {
this.check = function() {
expect(this.data).toEqualData({
'foo': 'bar',
'baz': 'biz'
});
expect(this.oneway).toEqualData({
'foo': 'bar',
'baz': 'biz'
});
expect(this.str).toBe('Hello, world!');
expect(this.fn()).toBe('called!');
};
controllerCalled = true;
if (preAssignBindingsEnabled) {
this.check();
} else {
this.$onInit = this.check;
}
});
$compileProvider.directive('fooDir', valueFn(ddo));
});
inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('test.html', '<p>template</p>');
$rootScope.fn = valueFn('called!');
$rootScope.whom = 'world';
$rootScope.remoteData = {
'foo': 'bar',
'baz': 'biz'
};
element = $compile('<div foo-dir dir-data="remoteData" ' +
'dir-str="Hello, {{whom}}!" ' +
'dir-fn="fn()"></div>')($rootScope);
$rootScope.$digest();
expect(controllerCalled).toBe(true);
if (ddo.controllerAs || ddo.controller.indexOf(' as ') !== -1) {
if (ddo.scope) {
expect($rootScope.myCtrl).toBeUndefined();
} else {
// The controller identifier was added to the containing scope.
expect($rootScope.myCtrl).toBeDefined();
}
}
});
});
});
});
});
});
it('should bind to multiple directives controllers via object notation (no scope)', function() {
var controller1Called = false;
var controller2Called = false;
module(function($compileProvider, $controllerProvider) {
$compileProvider.directive('foo', valueFn({
bindToController: {
'data': '=fooData',
'oneway': '<fooData',
'str': '@fooStr',
'fn': '&fooFn'
},
controllerAs: 'fooCtrl',
controller: function() {
this.check = function() {
expect(this.data).toEqualData({'foo': 'bar', 'baz': 'biz'});
expect(this.oneway).toEqualData({'foo': 'bar', 'baz': 'biz'});
expect(this.str).toBe('Hello, world!');
expect(this.fn()).toBe('called!');
};
controller1Called = true;
if (preAssignBindingsEnabled) {
this.check();
} else {
this.$onInit = this.check;
}
}
}));
$compileProvider.directive('bar', valueFn({
bindToController: {
'data': '=barData',
'oneway': '<barData',
'str': '@barStr',
'fn': '&barFn'
},
controllerAs: 'barCtrl',
controller: function() {
this.check = function() {
expect(this.data).toEqualData({'foo2': 'bar2', 'baz2': 'biz2'});
expect(this.oneway).toEqualData({'foo2': 'bar2', 'baz2': 'biz2'});
expect(this.str).toBe('Hello, second world!');
expect(this.fn()).toBe('second called!');
};
controller2Called = true;
if (preAssignBindingsEnabled) {
this.check();
} else {
this.$onInit = this.check;
}
}
}));
});
inject(function($compile, $rootScope) {
$rootScope.fn = valueFn('called!');
$rootScope.string = 'world';
$rootScope.data = {'foo': 'bar','baz': 'biz'};
$rootScope.fn2 = valueFn('second called!');
$rootScope.string2 = 'second world';
$rootScope.data2 = {'foo2': 'bar2', 'baz2': 'biz2'};
element = $compile(
'<div ' +
'foo ' +
'foo-data="data" ' +
'foo-str="Hello, {{string}}!" ' +
'foo-fn="fn()" ' +
'bar ' +
'bar-data="data2" ' +
'bar-str="Hello, {{string2}}!" ' +
'bar-fn="fn2()" > ' +
'</div>')($rootScope);
$rootScope.$digest();
expect(controller1Called).toBe(true);
expect(controller2Called).toBe(true);
});
});
it('should bind to multiple directives controllers via object notation (new iso scope)', function() {
var controller1Called = false;
var controller2Called = false;
module(function($compileProvider, $controllerProvider) {
$compileProvider.directive('foo', valueFn({
bindToController: {
'data': '=fooData',
'oneway': '<fooData',
'str': '@fooStr',
'fn': '&fooFn'
},
scope: {},
controllerAs: 'fooCtrl',
controller: function() {
this.check = function() {
expect(this.data).toEqualData({'foo': 'bar', 'baz': 'biz'});
expect(this.oneway).toEqualData({'foo': 'bar', 'baz': 'biz'});
expect(this.str).toBe('Hello, world!');
expect(this.fn()).toBe('called!');
};
controller1Called = true;
if (preAssignBindingsEnabled) {
this.check();
} else {
this.$onInit = this.check;
}
}
}));
$compileProvider.directive('bar', valueFn({
bindToController: {
'data': '=barData',
'oneway': '<barData',
'str': '@barStr',
'fn': '&barFn'
},
controllerAs: 'barCtrl',
controller: function() {
this.check = function() {
expect(this.data).toEqualData({'foo2': 'bar2', 'baz2': 'biz2'});
expect(this.oneway).toEqualData({'foo2': 'bar2', 'baz2': 'biz2'});
expect(this.str).toBe('Hello, second world!');
expect(this.fn()).toBe('second called!');
};
controller2Called = true;
if (preAssignBindingsEnabled) {
this.check();
} else {
this.$onInit = this.check;
}
}
}));
});
inject(function($compile, $rootScope) {
$rootScope.fn = valueFn('called!');
$rootScope.string = 'world';
$rootScope.data = {'foo': 'bar','baz': 'biz'};
$rootScope.fn2 = valueFn('second called!');
$rootScope.string2 = 'second world';
$rootScope.data2 = {'foo2': 'bar2', 'baz2': 'biz2'};
element = $compile(
'<div ' +
'foo ' +
'foo-data="data" ' +
'foo-str="Hello, {{string}}!" ' +
'foo-fn="fn()" ' +
'bar ' +
'bar-data="data2" ' +
'bar-str="Hello, {{string2}}!" ' +
'bar-fn="fn2()" > ' +
'</div>')($rootScope);
$rootScope.$digest();
expect(controller1Called).toBe(true);
expect(controller2Called).toBe(true);
});
});
it('should bind to multiple directives controllers via object notation (new scope)', function() {
var controller1Called = false;
var controller2Called = false;
module(function($compileProvider, $controllerProvider) {
$compileProvider.directive('foo', valueFn({
bindToController: {
'data': '=fooData',
'oneway': '<fooData',
'str': '@fooStr',
'fn': '&fooFn'
},
scope: true,
controllerAs: 'fooCtrl',
controller: function() {
this.check = function() {
expect(this.data).toEqualData({'foo': 'bar', 'baz': 'biz'});
expect(this.oneway).toEqualData({'foo': 'bar', 'baz': 'biz'});
expect(this.str).toBe('Hello, world!');
expect(this.fn()).toBe('called!');
};
controller1Called = true;
if (preAssignBindingsEnabled) {
this.check();
} else {
this.$onInit = this.check;
}
}
}));
$compileProvider.directive('bar', valueFn({
bindToController: {
'data': '=barData',
'oneway': '<barData',
'str': '@barStr',
'fn': '&barFn'
},
scope: true,
controllerAs: 'barCtrl',
controller: function() {
this.check = function() {
expect(this.data).toEqualData({'foo2': 'bar2', 'baz2': 'biz2'});
expect(this.oneway).toEqualData({'foo2': 'bar2', 'baz2': 'biz2'});
expect(this.str).toBe('Hello, second world!');
expect(this.fn()).toBe('second called!');
};
controller2Called = true;
if (preAssignBindingsEnabled) {
this.check();
} else {
this.$onInit = this.check;
}
}
}));
});
inject(function($compile, $rootScope) {
$rootScope.fn = valueFn('called!');
$rootScope.string = 'world';
$rootScope.data = {'foo': 'bar','baz': 'biz'};
$rootScope.fn2 = valueFn('second called!');
$rootScope.string2 = 'second world';
$rootScope.data2 = {'foo2': 'bar2', 'baz2': 'biz2'};
element = $compile(
'<div ' +
'foo ' +
'foo-data="data" ' +
'foo-str="Hello, {{string}}!" ' +
'foo-fn="fn()" ' +
'bar ' +
'bar-data="data2" ' +
'bar-str="Hello, {{string2}}!" ' +
'bar-fn="fn2()" > ' +
'</div>')($rootScope);
$rootScope.$digest();
expect(controller1Called).toBe(true);
expect(controller2Called).toBe(true);
});
});
it('should evaluate against the correct scope, when using `bindToController` (new scope)',
function() {
module(function($compileProvider, $controllerProvider) {
$controllerProvider.register({
'ParentCtrl': function() {
this.value1 = 'parent1';
this.value2 = 'parent2';
this.value3 = function() { return 'parent3'; };
this.value4 = 'parent4';
},
'ChildCtrl': function() {
this.value1 = 'child1';
this.value2 = 'child2';
this.value3 = function() { return 'child3'; };
this.value4 = 'child4';
}
});
$compileProvider.directive('child', valueFn({
scope: true,
controller: 'ChildCtrl as ctrl',
bindToController: {
fromParent1: '@',
fromParent2: '=',
fromParent3: '&',
fromParent4: '<'
},
template: ''
}));
});
inject(function($compile, $rootScope) {
element = $compile(
'<div ng-controller="ParentCtrl as ctrl">' +
'<child ' +
'from-parent-1="{{ ctrl.value1 }}" ' +
'from-parent-2="ctrl.value2" ' +
'from-parent-3="ctrl.value3" ' +
'from-parent-4="ctrl.value4">' +
'</child>' +
'</div>')($rootScope);
$rootScope.$digest();
var parentCtrl = element.controller('ngController');
var childCtrl = element.find('child').controller('child');
expect(childCtrl.fromParent1).toBe(parentCtrl.value1);
expect(childCtrl.fromParent1).not.toBe(childCtrl.value1);
expect(childCtrl.fromParent2).toBe(parentCtrl.value2);
expect(childCtrl.fromParent2).not.toBe(childCtrl.value2);
expect(childCtrl.fromParent3()()).toBe(parentCtrl.value3());
expect(childCtrl.fromParent3()()).not.toBe(childCtrl.value3());
expect(childCtrl.fromParent4).toBe(parentCtrl.value4);
expect(childCtrl.fromParent4).not.toBe(childCtrl.value4);
childCtrl.fromParent2 = 'modified';
$rootScope.$digest();
expect(parentCtrl.value2).toBe('modified');
expect(childCtrl.value2).toBe('child2');
});
}
);
it('should evaluate against the correct scope, when using `bindToController` (new iso scope)',
function() {
module(function($compileProvider, $controllerProvider) {
$controllerProvider.register({
'ParentCtrl': function() {
this.value1 = 'parent1';
this.value2 = 'parent2';
this.value3 = function() { return 'parent3'; };
this.value4 = 'parent4';
},
'ChildCtrl': function() {
this.value1 = 'child1';
this.value2 = 'child2';
this.value3 = function() { return 'child3'; };
this.value4 = 'child4';
}
});
$compileProvider.directive('child', valueFn({
scope: {},
controller: 'ChildCtrl as ctrl',
bindToController: {
fromParent1: '@',
fromParent2: '=',
fromParent3: '&',
fromParent4: '<'
},
template: ''
}));
});
inject(function($compile, $rootScope) {
element = $compile(
'<div ng-controller="ParentCtrl as ctrl">' +
'<child ' +
'from-parent-1="{{ ctrl.value1 }}" ' +
'from-parent-2="ctrl.value2" ' +
'from-parent-3="ctrl.value3" ' +
'from-parent-4="ctrl.value4">' +
'</child>' +
'</div>')($rootScope);
$rootScope.$digest();
var parentCtrl = element.controller('ngController');
var childCtrl = element.find('child').controller('child');
expect(childCtrl.fromParent1).toBe(parentCtrl.value1);
expect(childCtrl.fromParent1).not.toBe(childCtrl.value1);
expect(childCtrl.fromParent2).toBe(parentCtrl.value2);
expect(childCtrl.fromParent2).not.toBe(childCtrl.value2);
expect(childCtrl.fromParent3()()).toBe(parentCtrl.value3());
expect(childCtrl.fromParent3()()).not.toBe(childCtrl.value3());
expect(childCtrl.fromParent4).toBe(parentCtrl.value4);
expect(childCtrl.fromParent4).not.toBe(childCtrl.value4);
childCtrl.fromParent2 = 'modified';
$rootScope.$digest();
expect(parentCtrl.value2).toBe('modified');
expect(childCtrl.value2).toBe('child2');
});
}
);
it('should put controller in scope when controller identifier present but not using controllerAs', function() {
var controllerCalled = false;
var myCtrl;
module(function($compileProvider, $controllerProvider) {
$controllerProvider.register('myCtrl', function() {
controllerCalled = true;
myCtrl = this;
});
$compileProvider.directive('fooDir', valueFn({
templateUrl: 'test.html',
bindToController: {},
scope: true,
controller: 'myCtrl as theCtrl'
}));
});
inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('test.html', '<p>isolate</p>');
element = $compile('<div foo-dir>')($rootScope);
$rootScope.$digest();
expect(controllerCalled).toBe(true);
var childScope = element.children().scope();
expect(childScope).not.toBe($rootScope);
expect(childScope.theCtrl).toBe(myCtrl);
});
});
it('should re-install controllerAs and bindings for returned value from controller (new scope)', function() {
var controllerCalled = false;
var myCtrl;
function MyCtrl() {
}
MyCtrl.prototype.test = function() {
expect(this.data).toEqualData({
'foo': 'bar',
'baz': 'biz'
});
expect(this.oneway).toEqualData({
'foo': 'bar',
'baz': 'biz'
});
expect(this.str).toBe('Hello, world!');
expect(this.fn()).toBe('called!');
};
module(function($compileProvider, $controllerProvider) {
$controllerProvider.register('myCtrl', function() {
controllerCalled = true;
myCtrl = this;
return new MyCtrl();
});
$compileProvider.directive('fooDir', valueFn({
templateUrl: 'test.html',
bindToController: {
'data': '=dirData',
'oneway': '<dirData',
'str': '@dirStr',
'fn': '&dirFn'
},
scope: true,
controller: 'myCtrl as theCtrl'
}));
});
inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('test.html', '<p>isolate</p>');
$rootScope.fn = valueFn('called!');
$rootScope.whom = 'world';
$rootScope.remoteData = {
'foo': 'bar',
'baz': 'biz'
};
element = $compile('<div foo-dir dir-data="remoteData" ' +
'dir-str="Hello, {{whom}}!" ' +
'dir-fn="fn()"></div>')($rootScope);
$rootScope.$digest();
expect(controllerCalled).toBe(true);
var childScope = element.children().scope();
expect(childScope).not.toBe($rootScope);
expect(childScope.theCtrl).not.toBe(myCtrl);
expect(childScope.theCtrl.constructor).toBe(MyCtrl);
childScope.theCtrl.test();
});
});
it('should re-install controllerAs and bindings for returned value from controller (isolate scope)', function() {
var controllerCalled = false;
var myCtrl;
function MyCtrl() {
}
MyCtrl.prototype.test = function() {
expect(this.data).toEqualData({
'foo': 'bar',
'baz': 'biz'
});
expect(this.oneway).toEqualData({
'foo': 'bar',
'baz': 'biz'
});
expect(this.str).toBe('Hello, world!');
expect(this.fn()).toBe('called!');
};
module(function($compileProvider, $controllerProvider) {
$controllerProvider.register('myCtrl', function() {
controllerCalled = true;
myCtrl = this;
return new MyCtrl();
});
$compileProvider.directive('fooDir', valueFn({
templateUrl: 'test.html',
bindToController: true,
scope: {
'data': '=dirData',
'oneway': '<dirData',
'str': '@dirStr',
'fn': '&dirFn'
},
controller: 'myCtrl as theCtrl'
}));
});
inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('test.html', '<p>isolate</p>');
$rootScope.fn = valueFn('called!');
$rootScope.whom = 'world';
$rootScope.remoteData = {
'foo': 'bar',
'baz': 'biz'
};
element = $compile('<div foo-dir dir-data="remoteData" ' +
'dir-str="Hello, {{whom}}!" ' +
'dir-fn="fn()"></div>')($rootScope);
$rootScope.$digest();
expect(controllerCalled).toBe(true);
var childScope = element.children().scope();
expect(childScope).not.toBe($rootScope);
expect(childScope.theCtrl).not.toBe(myCtrl);
expect(childScope.theCtrl.constructor).toBe(MyCtrl);
childScope.theCtrl.test();
});
});
describe('should not overwrite @-bound property each digest when not present', function() {
it('when creating new scope', function() {
module(function($compileProvider) {
$compileProvider.directive('testDir', valueFn({
scope: true,
bindToController: {
prop: '@'
},
controller: function() {
var self = this;
this.initProp = function() {
this.prop = this.prop || 'default';
};
if (preAssignBindingsEnabled) {
this.initProp();
} else {
this.$onInit = this.initProp;
}
this.getProp = function() {
return self.prop;
};
},
controllerAs: 'ctrl',
template: '<p></p>'
}));
});
inject(function($compile, $rootScope) {
element = $compile('<div test-dir></div>')($rootScope);
var scope = element.scope();
expect(scope.ctrl.getProp()).toBe('default');
$rootScope.$digest();
expect(scope.ctrl.getProp()).toBe('default');
});
});
it('when creating isolate scope', function() {
module(function($compileProvider) {
$compileProvider.directive('testDir', valueFn({
scope: {},
bindToController: {
prop: '@'
},
controller: function() {
var self = this;
this.initProp = function() {
this.prop = this.prop || 'default';
};
this.getProp = function() {
return self.prop;
};
if (preAssignBindingsEnabled) {
this.initProp();
} else {
this.$onInit = this.initProp;
}
},
controllerAs: 'ctrl',
template: '<p></p>'
}));
});
inject(function($compile, $rootScope) {
element = $compile('<div test-dir></div>')($rootScope);
var scope = element.isolateScope();
expect(scope.ctrl.getProp()).toBe('default');
$rootScope.$digest();
expect(scope.ctrl.getProp()).toBe('default');
});
});
});
});
describe('require', function() {
it('should get required controller', function() {
module(function() {
directive('main', function(log) {
return {
priority: 2,
controller: function() {
this.name = 'main';
},
link: function(scope, element, attrs, controller) {
log(controller.name);
}
};
});
directive('dep', function(log) {
return {
priority: 1,
require: 'main',
link: function(scope, element, attrs, controller) {
log('dep:' + controller.name);
}
};
});
directive('other', function(log) {
return {
link: function(scope, element, attrs, controller) {
log(!!controller); // should be false
}
};
});
});
inject(function(log, $compile, $rootScope) {
element = $compile('<div main dep other></div>')($rootScope);
expect(log).toEqual('false; dep:main; main');
});
});
it('should respect explicit return value from controller', function() {
var expectedController;
module(function() {
directive('logControllerProp', function(log) {
return {
controller: function($scope) {
this.foo = 'baz'; // value should not be used.
expectedController = {foo: 'bar'};
return expectedController;
},
link: function(scope, element, attrs, controller) {
expect(expectedController).toBeDefined();
expect(controller).toBe(expectedController);
expect(controller.foo).toBe('bar');
log('done');
}
};
});
});
inject(function(log, $compile, $rootScope) {
element = $compile('<log-controller-prop></log-controller-prop>')($rootScope);
expect(log).toEqual('done');
expect(element.data('$logControllerPropController')).toBe(expectedController);
});
});
it('should get explicit return value of required parent controller', function() {
var expectedController;
module(function() {
directive('nested', function(log) {
return {
require: '^^?nested',
controller: function() {
if (!expectedController) expectedController = {foo: 'bar'};
return expectedController;
},
link: function(scope, element, attrs, controller) {
if (element.parent().length) {
expect(expectedController).toBeDefined();
expect(controller).toBe(expectedController);
expect(controller.foo).toBe('bar');
log('done');
}
}
};
});
});
inject(function(log, $compile, $rootScope) {
element = $compile('<div nested><div nested></div></div>')($rootScope);
expect(log).toEqual('done');
expect(element.data('$nestedController')).toBe(expectedController);
});
});
it('should respect explicit controller return value when using controllerAs', function() {
module(function() {
directive('main', function() {
return {
templateUrl: 'main.html',
scope: {},
controller: function() {
this.name = 'lucas';
return {name: 'george'};
},
controllerAs: 'mainCtrl'
};
});
});
inject(function($templateCache, $compile, $rootScope) {
$templateCache.put('main.html', '<span>template:{{mainCtrl.name}}</span>');
element = $compile('<main/>')($rootScope);
$rootScope.$apply();
expect(element.text()).toBe('template:george');
});
});
it('transcluded children should receive explicit return value of parent controller', function() {
var expectedController;
module(function() {
directive('nester', valueFn({
transclude: true,
controller: function($transclude) {
this.foo = 'baz';
expectedController = {transclude:$transclude, foo: 'bar'};
return expectedController;
},
link: function(scope, el, attr, ctrl) {
ctrl.transclude(cloneAttach);
function cloneAttach(clone) {
el.append(clone);
}
}
}));
directive('nested', function(log) {
return {
require: '^^nester',
link: function(scope, element, attrs, controller) {
expect(controller).toBeDefined();
expect(controller).toBe(expectedController);
log('done');
}
};
});
});
inject(function(log, $compile) {
element = $compile('<div nester><div nested></div></div>')($rootScope);
$rootScope.$apply();
expect(log.toString()).toBe('done');
expect(element.data('$nesterController')).toBe(expectedController);
});
});
it('explicit controller return values are ignored if they are primitives', function() {
module(function() {
directive('logControllerProp', function(log) {
return {
controller: function($scope) {
this.foo = 'baz'; // value *will* be used.
return 'bar';
},
link: function(scope, element, attrs, controller) {
log(controller.foo);
}
};
});
});
inject(function(log, $compile, $rootScope) {
element = $compile('<log-controller-prop></log-controller-prop>')($rootScope);
expect(log).toEqual('baz');
expect(element.data('$logControllerPropController').foo).toEqual('baz');
});
});
it('should correctly assign controller return values for multiple directives', function() {
var directiveController, otherDirectiveController;
module(function() {
directive('myDirective', function(log) {
return {
scope: true,
controller: function($scope) {
directiveController = {
foo: 'bar'
};
return directiveController;
}
};
});
directive('myOtherDirective', function(log) {
return {
controller: function($scope) {
otherDirectiveController = {
baz: 'luh'
};
return otherDirectiveController;
}
};
});
});
inject(function(log, $compile, $rootScope) {
element = $compile('<my-directive my-other-directive></my-directive>')($rootScope);
expect(element.data('$myDirectiveController')).toBe(directiveController);
expect(element.data('$myOtherDirectiveController')).toBe(otherDirectiveController);
});
});
it('should get required parent controller', function() {
module(function() {
directive('nested', function(log) {
return {
require: '^^?nested',
controller: function($scope) {},
link: function(scope, element, attrs, controller) {
log(!!controller);
}
};
});
});
inject(function(log, $compile, $rootScope) {
element = $compile('<div nested><div nested></div></div>')($rootScope);
expect(log).toEqual('true; false');
});
});
it('should get required parent controller when the question mark precedes the ^^', function() {
module(function() {
directive('nested', function(log) {
return {
require: '?^^nested',
controller: function($scope) {},
link: function(scope, element, attrs, controller) {
log(!!controller);
}
};
});
});
inject(function(log, $compile, $rootScope) {
element = $compile('<div nested><div nested></div></div>')($rootScope);
expect(log).toEqual('true; false');
});
});
it('should throw if required parent is not found', function() {
module(function() {
directive('nested', function() {
return {
require: '^^nested',
controller: function($scope) {},
link: function(scope, element, attrs, controller) {}
};
});
});
inject(function($compile, $rootScope) {
expect(function() {
element = $compile('<div nested></div>')($rootScope);
}).toThrowMinErr('$compile', 'ctreq', 'Controller \'nested\', required by directive \'nested\', can\'t be found!');
});
});
it('should get required controller via linkingFn (template)', function() {
module(function() {
directive('dirA', function() {
return {
controller: function() {
this.name = 'dirA';
}
};
});
directive('dirB', function(log) {
return {
require: 'dirA',
template: '<p>dirB</p>',
link: function(scope, element, attrs, dirAController) {
log('dirAController.name: ' + dirAController.name);
}
};
});
});
inject(function(log, $compile, $rootScope) {
element = $compile('<div dir-a dir-b></div>')($rootScope);
expect(log).toEqual('dirAController.name: dirA');
});
});
it('should get required controller via linkingFn (templateUrl)', function() {
module(function() {
directive('dirA', function() {
return {
controller: function() {
this.name = 'dirA';
}
};
});
directive('dirB', function(log) {
return {
require: 'dirA',
templateUrl: 'dirB.html',
link: function(scope, element, attrs, dirAController) {
log('dirAController.name: ' + dirAController.name);
}
};
});
});
inject(function(log, $compile, $rootScope, $templateCache) {
$templateCache.put('dirB.html', '<p>dirB</p>');
element = $compile('<div dir-a dir-b></div>')($rootScope);
$rootScope.$digest();
expect(log).toEqual('dirAController.name: dirA');
});
});
it('should bind the required controllers to the directive controller, if provided as an object and bindToController is truthy', function() {
var parentController, siblingController;
function ParentController() { this.name = 'Parent'; }
function SiblingController() { this.name = 'Sibling'; }
function MeController() { this.name = 'Me'; }
MeController.prototype.$onInit = function() {
parentController = this.container;
siblingController = this.friend;
};
spyOn(MeController.prototype, '$onInit').and.callThrough();
angular.module('my', [])
.directive('me', function() {
return {
restrict: 'E',
scope: {},
require: { container: '^parent', friend: 'sibling' },
bindToController: true,
controller: MeController,
controllerAs: '$ctrl'
};
})
.directive('parent', function() {
return {
restrict: 'E',
scope: {},
controller: ParentController
};
})
.directive('sibling', function() {
return {
controller: SiblingController
};
});
module('my');
inject(function($compile, $rootScope, meDirective) {
element = $compile('<parent><me sibling></me></parent>')($rootScope);
expect(MeController.prototype.$onInit).toHaveBeenCalled();
expect(parentController).toEqual(jasmine.any(ParentController));
expect(siblingController).toEqual(jasmine.any(SiblingController));
});
});
it('should use the key if the name of a required controller is omitted', function() {
function ParentController() { this.name = 'Parent'; }
function ParentOptController() { this.name = 'ParentOpt'; }
function ParentOrSiblingController() { this.name = 'ParentOrSibling'; }
function ParentOrSiblingOptController() { this.name = 'ParentOrSiblingOpt'; }
function SiblingController() { this.name = 'Sibling'; }
function SiblingOptController() { this.name = 'SiblingOpt'; }
angular.module('my', [])
.component('me', {
require: {
parent: '^^',
parentOpt: '?^^',
parentOrSibling1: '^',
parentOrSiblingOpt1: '?^',
parentOrSibling2: '^',
parentOrSiblingOpt2: '?^',
sibling: '',
siblingOpt: '?'
}
})
.directive('parent', function() {
return {controller: ParentController};
})
.directive('parentOpt', function() {
return {controller: ParentOptController};
})
.directive('parentOrSibling1', function() {
return {controller: ParentOrSiblingController};
})
.directive('parentOrSiblingOpt1', function() {
return {controller: ParentOrSiblingOptController};
})
.directive('parentOrSibling2', function() {
return {controller: ParentOrSiblingController};
})
.directive('parentOrSiblingOpt2', function() {
return {controller: ParentOrSiblingOptController};
})
.directive('sibling', function() {
return {controller: SiblingController};
})
.directive('siblingOpt', function() {
return {controller: SiblingOptController};
});
module('my');
inject(function($compile, $rootScope) {
var template =
'<div>' +
// With optional
'<parent parent-opt parent-or-sibling-1 parent-or-sibling-opt-1>' +
'<me parent-or-sibling-2 parent-or-sibling-opt-2 sibling sibling-opt></me>' +
'</parent>' +
// Without optional
'<parent parent-or-sibling-1>' +
'<me parent-or-sibling-2 sibling></me>' +
'</parent>' +
'</div>';
element = $compile(template)($rootScope);
var ctrl1 = element.find('me').eq(0).controller('me');
expect(ctrl1.parent).toEqual(jasmine.any(ParentController));
expect(ctrl1.parentOpt).toEqual(jasmine.any(ParentOptController));
expect(ctrl1.parentOrSibling1).toEqual(jasmine.any(ParentOrSiblingController));
expect(ctrl1.parentOrSiblingOpt1).toEqual(jasmine.any(ParentOrSiblingOptController));
expect(ctrl1.parentOrSibling2).toEqual(jasmine.any(ParentOrSiblingController));
expect(ctrl1.parentOrSiblingOpt2).toEqual(jasmine.any(ParentOrSiblingOptController));
expect(ctrl1.sibling).toEqual(jasmine.any(SiblingController));
expect(ctrl1.siblingOpt).toEqual(jasmine.any(SiblingOptController));
var ctrl2 = element.find('me').eq(1).controller('me');
expect(ctrl2.parent).toEqual(jasmine.any(ParentController));
expect(ctrl2.parentOpt).toBe(null);
expect(ctrl2.parentOrSibling1).toEqual(jasmine.any(ParentOrSiblingController));
expect(ctrl2.parentOrSiblingOpt1).toBe(null);
expect(ctrl2.parentOrSibling2).toEqual(jasmine.any(ParentOrSiblingController));
expect(ctrl2.parentOrSiblingOpt2).toBe(null);
expect(ctrl2.sibling).toEqual(jasmine.any(SiblingController));
expect(ctrl2.siblingOpt).toBe(null);
});
});
it('should not bind required controllers if bindToController is falsy', function() {
var parentController, siblingController;
function ParentController() { this.name = 'Parent'; }
function SiblingController() { this.name = 'Sibling'; }
function MeController() { this.name = 'Me'; }
MeController.prototype.$onInit = function() {
parentController = this.container;
siblingController = this.friend;
};
spyOn(MeController.prototype, '$onInit').and.callThrough();
angular.module('my', [])
.directive('me', function() {
return {
restrict: 'E',
scope: {},
require: { container: '^parent', friend: 'sibling' },
controller: MeController
};
})
.directive('parent', function() {
return {
restrict: 'E',
scope: {},
controller: ParentController
};
})
.directive('sibling', function() {
return {
controller: SiblingController
};
});
module('my');
inject(function($compile, $rootScope, meDirective) {
element = $compile('<parent><me sibling></me></parent>')($rootScope);
expect(MeController.prototype.$onInit).toHaveBeenCalled();
expect(parentController).toBeUndefined();
expect(siblingController).toBeUndefined();
});
});
it('should bind required controllers to controller that has an explicit constructor return value', function() {
var parentController, siblingController, meController;
function ParentController() { this.name = 'Parent'; }
function SiblingController() { this.name = 'Sibling'; }
function MeController() {
meController = {
name: 'Me',
$onInit: function() {
parentController = this.container;
siblingController = this.friend;
}
};
spyOn(meController, '$onInit').and.callThrough();
return meController;
}
angular.module('my', [])
.directive('me', function() {
return {
restrict: 'E',
scope: {},
require: { container: '^parent', friend: 'sibling' },
bindToController: true,
controller: MeController,
controllerAs: '$ctrl'
};
})
.directive('parent', function() {
return {
restrict: 'E',
scope: {},
controller: ParentController
};
})
.directive('sibling', function() {
return {
controller: SiblingController
};
});
module('my');
inject(function($compile, $rootScope, meDirective) {
element = $compile('<parent><me sibling></me></parent>')($rootScope);
expect(meController.$onInit).toHaveBeenCalled();
expect(parentController).toEqual(jasmine.any(ParentController));
expect(siblingController).toEqual(jasmine.any(SiblingController));
});
});
it('should bind required controllers to controllers that return an explicit constructor return value', function() {
var parentController, containerController, siblingController, friendController, meController;
function MeController() {
this.name = 'Me';
this.$onInit = function() {
containerController = this.container;
friendController = this.friend;
};
}
function ParentController() {
parentController = { name: 'Parent' };
return parentController;
}
function SiblingController() {
siblingController = { name: 'Sibling' };
return siblingController;
}
angular.module('my', [])
.directive('me', function() {
return {
priority: 1, // make sure it is run before sibling to test this case correctly
restrict: 'E',
scope: {},
require: { container: '^parent', friend: 'sibling' },
bindToController: true,
controller: MeController,
controllerAs: '$ctrl'
};
})
.directive('parent', function() {
return {
restrict: 'E',
scope: {},
controller: ParentController
};
})
.directive('sibling', function() {
return {
controller: SiblingController
};
});
module('my');
inject(function($compile, $rootScope, meDirective) {
element = $compile('<parent><me sibling></me></parent>')($rootScope);
expect(containerController).toEqual(parentController);
expect(friendController).toEqual(siblingController);
});
});
it('should require controller of an isolate directive from a non-isolate directive on the ' +
'same element', function() {
var IsolateController = function() {};
var isolateDirControllerInNonIsolateDirective;
module(function() {
directive('isolate', function() {
return {
scope: {},
controller: IsolateController
};
});
directive('nonIsolate', function() {
return {
require: 'isolate',
link: function(_, __, ___, isolateDirController) {
isolateDirControllerInNonIsolateDirective = isolateDirController;
}
};
});
});
inject(function($compile, $rootScope) {
element = $compile('<div isolate non-isolate></div>')($rootScope);
expect(isolateDirControllerInNonIsolateDirective).toBeDefined();
expect(isolateDirControllerInNonIsolateDirective instanceof IsolateController).toBe(true);
});
});
it('should give the isolate scope to the controller of another replaced directives in the template', function() {
module(function() {
directive('testDirective', function() {
return {
replace: true,
restrict: 'E',
scope: {},
template: '<input type="checkbox" ng-model="model">'
};
});
});
inject(function($rootScope) {
compile('<div><test-directive></test-directive></div>');
element = element.children().eq(0);
expect(element[0].checked).toBe(false);
element.isolateScope().model = true;
$rootScope.$digest();
expect(element[0].checked).toBe(true);
});
});
it('should share isolate scope with replaced directives (template)', function() {
var normalScope;
var isolateScope;
module(function() {
directive('isolate', function() {
return {
replace: true,
scope: {},
template: '<span ng-init="name=\'WORKS\'">{{name}}</span>',
link: function(s) {
isolateScope = s;
}
};
});
directive('nonIsolate', function() {
return {
link: function(s) {
normalScope = s;
}
};
});
});
inject(function($compile, $rootScope) {
element = $compile('<div isolate non-isolate></div>')($rootScope);
expect(normalScope).toBe($rootScope);
expect(normalScope.name).toEqual(undefined);
expect(isolateScope.name).toEqual('WORKS');
$rootScope.$digest();
expect(element.text()).toEqual('WORKS');
});
});
it('should share isolate scope with replaced directives (templateUrl)', function() {
var normalScope;
var isolateScope;
module(function() {
directive('isolate', function() {
return {
replace: true,
scope: {},
templateUrl: 'main.html',
link: function(s) {
isolateScope = s;
}
};
});
directive('nonIsolate', function() {
return {
link: function(s) {
normalScope = s;
}
};
});
});
inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('main.html', '<span ng-init="name=\'WORKS\'">{{name}}</span>');
element = $compile('<div isolate non-isolate></div>')($rootScope);
$rootScope.$apply();
expect(normalScope).toBe($rootScope);
expect(normalScope.name).toEqual(undefined);
expect(isolateScope.name).toEqual('WORKS');
expect(element.text()).toEqual('WORKS');
});
});
it('should not get confused about where to use isolate scope when a replaced directive is used multiple times',
function() {
module(function() {
directive('isolate', function() {
return {
replace: true,
scope: {},
template: '<span scope-tester="replaced"><span scope-tester="inside"></span></span>'
};
});
directive('scopeTester', function(log) {
return {
link: function($scope, $element) {
log($element.attr('scope-tester') + '=' + ($scope.$root === $scope ? 'non-isolate' : 'isolate'));
}
};
});
});
inject(function($compile, $rootScope, log) {
element = $compile('<div>' +
'<div isolate scope-tester="outside"></div>' +
'<span scope-tester="sibling"></span>' +
'</div>')($rootScope);
$rootScope.$digest();
expect(log).toEqual('inside=isolate; ' +
'outside replaced=non-isolate; ' + // outside
'outside replaced=isolate; ' + // replaced
'sibling=non-isolate');
});
});
it('should require controller of a non-isolate directive from an isolate directive on the ' +
'same element', function() {
var NonIsolateController = function() {};
var nonIsolateDirControllerInIsolateDirective;
module(function() {
directive('isolate', function() {
return {
scope: {},
require: 'nonIsolate',
link: function(_, __, ___, nonIsolateDirController) {
nonIsolateDirControllerInIsolateDirective = nonIsolateDirController;
}
};
});
directive('nonIsolate', function() {
return {
controller: NonIsolateController
};
});
});
inject(function($compile, $rootScope) {
element = $compile('<div isolate non-isolate></div>')($rootScope);
expect(nonIsolateDirControllerInIsolateDirective).toBeDefined();
expect(nonIsolateDirControllerInIsolateDirective instanceof NonIsolateController).toBe(true);
});
});
it('should support controllerAs', function() {
module(function() {
directive('main', function() {
return {
templateUrl: 'main.html',
transclude: true,
scope: {},
controller: function() {
this.name = 'lucas';
},
controllerAs: 'mainCtrl'
};
});
});
inject(function($templateCache, $compile, $rootScope) {
$templateCache.put('main.html', '<span>template:{{mainCtrl.name}} <div ng-transclude></div></span>');
element = $compile('<div main>transclude:{{mainCtrl.name}}</div>')($rootScope);
$rootScope.$apply();
expect(element.text()).toBe('template:lucas transclude:');
});
});
it('should support controller alias', function() {
module(function($controllerProvider) {
$controllerProvider.register('MainCtrl', function() {
this.name = 'lucas';
});
directive('main', function() {
return {
templateUrl: 'main.html',
scope: {},
controller: 'MainCtrl as mainCtrl'
};
});
});
inject(function($templateCache, $compile, $rootScope) {
$templateCache.put('main.html', '<span>{{mainCtrl.name}}</span>');
element = $compile('<div main></div>')($rootScope);
$rootScope.$apply();
expect(element.text()).toBe('lucas');
});
});
it('should require controller on parent element',function() {
module(function() {
directive('main', function(log) {
return {
controller: function() {
this.name = 'main';
}
};
});
directive('dep', function(log) {
return {
require: '^main',
link: function(scope, element, attrs, controller) {
log('dep:' + controller.name);
}
};
});
});
inject(function(log, $compile, $rootScope) {
element = $compile('<div main><div dep></div></div>')($rootScope);
expect(log).toEqual('dep:main');
});
});
it('should throw an error if required controller can\'t be found',function() {
module(function() {
directive('dep', function(log) {
return {
require: '^main',
link: function(scope, element, attrs, controller) {
log('dep:' + controller.name);
}
};
});
});
inject(function(log, $compile, $rootScope) {
expect(function() {
$compile('<div main><div dep></div></div>')($rootScope);
}).toThrowMinErr('$compile', 'ctreq', 'Controller \'main\', required by directive \'dep\', can\'t be found!');
});
});
it('should pass null if required controller can\'t be found and is optional',function() {
module(function() {
directive('dep', function(log) {
return {
require: '?^main',
link: function(scope, element, attrs, controller) {
log('dep:' + controller);
}
};
});
});
inject(function(log, $compile, $rootScope) {
$compile('<div main><div dep></div></div>')($rootScope);
expect(log).toEqual('dep:null');
});
});
it('should pass null if required controller can\'t be found and is optional with the question mark on the right',function() {
module(function() {
directive('dep', function(log) {
return {
require: '^?main',
link: function(scope, element, attrs, controller) {
log('dep:' + controller);
}
};
});
});
inject(function(log, $compile, $rootScope) {
$compile('<div main><div dep></div></div>')($rootScope);
expect(log).toEqual('dep:null');
});
});
it('should have optional controller on current element', function() {
module(function() {
directive('dep', function(log) {
return {
require: '?main',
link: function(scope, element, attrs, controller) {
log('dep:' + !!controller);
}
};
});
});
inject(function(log, $compile, $rootScope) {
element = $compile('<div main><div dep></div></div>')($rootScope);
expect(log).toEqual('dep:false');
});
});
it('should support multiple controllers', function() {
module(function() {
directive('c1', valueFn({
controller: function() { this.name = 'c1'; }
}));
directive('c2', valueFn({
controller: function() { this.name = 'c2'; }
}));
directive('dep', function(log) {
return {
require: ['^c1', '^c2'],
link: function(scope, element, attrs, controller) {
log('dep:' + controller[0].name + '-' + controller[1].name);
}
};
});
});
inject(function(log, $compile, $rootScope) {
element = $compile('<div c1 c2><div dep></div></div>')($rootScope);
expect(log).toEqual('dep:c1-c2');
});
});
it('should support multiple controllers as an object hash', function() {
module(function() {
directive('c1', valueFn({
controller: function() { this.name = 'c1'; }
}));
directive('c2', valueFn({
controller: function() { this.name = 'c2'; }
}));
directive('dep', function(log) {
return {
require: { myC1: '^c1', myC2: '^c2' },
link: function(scope, element, attrs, controllers) {
log('dep:' + controllers.myC1.name + '-' + controllers.myC2.name);
}
};
});
});
inject(function(log, $compile, $rootScope) {
element = $compile('<div c1 c2><div dep></div></div>')($rootScope);
expect(log).toEqual('dep:c1-c2');
});
});
it('should support omitting the name of the required controller if it is the same as the key',
function() {
module(function() {
directive('myC1', valueFn({
controller: function() { this.name = 'c1'; }
}));
directive('myC2', valueFn({
controller: function() { this.name = 'c2'; }
}));
directive('dep', function(log) {
return {
require: { myC1: '^', myC2: '^' },
link: function(scope, element, attrs, controllers) {
log('dep:' + controllers.myC1.name + '-' + controllers.myC2.name);
}
};
});
});
inject(function(log, $compile, $rootScope) {
element = $compile('<div my-c1 my-c2><div dep></div></div>')($rootScope);
expect(log).toEqual('dep:c1-c2');
});
}
);
it('should instantiate the controller just once when template/templateUrl', function() {
var syncCtrlSpy = jasmine.createSpy('sync controller'),
asyncCtrlSpy = jasmine.createSpy('async controller');
module(function() {
directive('myDirectiveSync', valueFn({
template: '<div>Hello!</div>',
controller: syncCtrlSpy
}));
directive('myDirectiveAsync', valueFn({
templateUrl: 'myDirectiveAsync.html',
controller: asyncCtrlSpy,
compile: function() {
return function() {
};
}
}));
});
inject(function($templateCache, $compile, $rootScope) {
expect(syncCtrlSpy).not.toHaveBeenCalled();
expect(asyncCtrlSpy).not.toHaveBeenCalled();
$templateCache.put('myDirectiveAsync.html', '<div>Hello!</div>');
element = $compile('<div>' +
'<span xmy-directive-sync></span>' +
'<span my-directive-async></span>' +
'</div>')($rootScope);
expect(syncCtrlSpy).not.toHaveBeenCalled();
expect(asyncCtrlSpy).not.toHaveBeenCalled();
$rootScope.$apply();
//expect(syncCtrlSpy).toHaveBeenCalledOnce();
expect(asyncCtrlSpy).toHaveBeenCalledOnce();
});
});
it('should instantiate controllers in the parent->child order when transclusion, templateUrl and replacement ' +
'are in the mix', function() {
// When a child controller is in the transclusion that replaces the parent element that has a directive with
// a controller, we should ensure that we first instantiate the parent and only then stuff that comes from the
// transclusion.
//
// The transclusion moves the child controller onto the same element as parent controller so both controllers are
// on the same level.
module(function() {
directive('parentDirective', function() {
return {
transclude: true,
replace: true,
templateUrl: 'parentDirective.html',
controller: function(log) { log('parentController'); }
};
});
directive('childDirective', function() {
return {
require: '^parentDirective',
templateUrl: 'childDirective.html',
controller: function(log) { log('childController'); }
};
});
});
inject(function($templateCache, log, $compile, $rootScope) {
$templateCache.put('parentDirective.html', '<div ng-transclude>parentTemplateText;</div>');
$templateCache.put('childDirective.html', '<span>childTemplateText;</span>');
element = $compile('<div parent-directive><div child-directive></div>childContentText;</div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('parentController; childController');
expect(element.text()).toBe('childTemplateText;childContentText;');
});
});
it('should instantiate the controller after the isolate scope bindings are initialized (with template)', function() {
module(function() {
var Ctrl = function($scope, log) {
log('myFoo=' + $scope.myFoo);
};
directive('myDirective', function() {
return {
scope: {
myFoo: '='
},
template: '<p>Hello</p>',
controller: Ctrl
};
});
});
inject(function($templateCache, $compile, $rootScope, log) {
$rootScope.foo = 'bar';
element = $compile('<div my-directive my-foo="foo"></div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('myFoo=bar');
});
});
it('should instantiate the controller after the isolate scope bindings are initialized (with templateUrl)', function() {
module(function() {
var Ctrl = function($scope, log) {
log('myFoo=' + $scope.myFoo);
};
directive('myDirective', function() {
return {
scope: {
myFoo: '='
},
templateUrl: 'hello.html',
controller: Ctrl
};
});
});
inject(function($templateCache, $compile, $rootScope, log) {
$templateCache.put('hello.html', '<p>Hello</p>');
$rootScope.foo = 'bar';
element = $compile('<div my-directive my-foo="foo"></div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('myFoo=bar');
});
});
it('should instantiate controllers in the parent->child->baby order when nested transclusion, templateUrl and ' +
'replacement are in the mix', function() {
// similar to the test above, except that we have one more layer of nesting and nested transclusion
module(function() {
directive('parentDirective', function() {
return {
transclude: true,
replace: true,
templateUrl: 'parentDirective.html',
controller: function(log) { log('parentController'); }
};
});
directive('childDirective', function() {
return {
require: '^parentDirective',
transclude: true,
replace: true,
templateUrl: 'childDirective.html',
controller: function(log) { log('childController'); }
};
});
directive('babyDirective', function() {
return {
require: '^childDirective',
templateUrl: 'babyDirective.html',
controller: function(log) { log('babyController'); }
};
});
});
inject(function($templateCache, log, $compile, $rootScope) {
$templateCache.put('parentDirective.html', '<div ng-transclude>parentTemplateText;</div>');
$templateCache.put('childDirective.html', '<span ng-transclude>childTemplateText;</span>');
$templateCache.put('babyDirective.html', '<span>babyTemplateText;</span>');
element = $compile('<div parent-directive>' +
'<div child-directive>' +
'childContentText;' +
'<div baby-directive>babyContent;</div>' +
'</div>' +
'</div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('parentController; childController; babyController');
expect(element.text()).toBe('childContentText;babyTemplateText;');
});
});
it('should allow controller usage in pre-link directive functions with templateUrl', function() {
module(function() {
var Ctrl = function(log) {
log('instance');
};
directive('myDirective', function() {
return {
scope: true,
templateUrl: 'hello.html',
controller: Ctrl,
compile: function() {
return {
pre: function(scope, template, attr, ctrl) {},
post: function() {}
};
}
};
});
});
inject(function($templateCache, $compile, $rootScope, log) {
$templateCache.put('hello.html', '<p>Hello</p>');
element = $compile('<div my-directive></div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('instance');
expect(element.text()).toBe('Hello');
});
});
it('should allow controller usage in pre-link directive functions with a template', function() {
module(function() {
var Ctrl = function(log) {
log('instance');
};
directive('myDirective', function() {
return {
scope: true,
template: '<p>Hello</p>',
controller: Ctrl,
compile: function() {
return {
pre: function(scope, template, attr, ctrl) {},
post: function() {}
};
}
};
});
});
inject(function($templateCache, $compile, $rootScope, log) {
element = $compile('<div my-directive></div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('instance');
expect(element.text()).toBe('Hello');
});
});
it('should throw ctreq with correct directive name, regardless of order', function() {
module(function($compileProvider) {
$compileProvider.directive('aDir', valueFn({
restrict: 'E',
require: 'ngModel',
link: noop
}));
});
inject(function($compile, $rootScope) {
expect(function() {
// a-dir will cause a ctreq error to be thrown. Previously, the error would reference
// the last directive in the chain (which in this case would be ngClick), based on
// priority and alphabetical ordering. This test verifies that the ordering does not
// affect which directive is referenced in the minErr message.
element = $compile('<a-dir ng-click="foo=bar"></a-dir>')($rootScope);
}).toThrowMinErr('$compile', 'ctreq',
'Controller \'ngModel\', required by directive \'aDir\', can\'t be found!');
});
});
});
describe('transclude', function() {
describe('content transclusion', function() {
it('should support transclude directive', function() {
module(function() {
directive('trans', function() {
return {
transclude: 'content',
replace: true,
scope: {},
link: function(scope) {
scope.x = 'iso';
},
template: '<ul><li>W:{{x}}-{{$parent.$id}}-{{$id}};</li><li ng-transclude></li></ul>'
};
});
});
inject(function(log, $rootScope, $compile) {
element = $compile('<div><div trans>T:{{x}}-{{$parent.$id}}-{{$id}}<span>;</span></div></div>')($rootScope);
$rootScope.x = 'root';
$rootScope.$apply();
expect(element.text()).toEqual('W:iso-1-2;T:root-2-3;');
expect(jqLite(jqLite(element.find('li')[1]).contents()[0]).text()).toEqual('T:root-2-3');
expect(jqLite(element.find('span')[0]).text()).toEqual(';');
});
});
it('should transclude transcluded content', function() {
module(function() {
directive('book', valueFn({
transclude: 'content',
template: '<div>book-<div chapter>(<div ng-transclude></div>)</div></div>'
}));
directive('chapter', valueFn({
transclude: 'content',
templateUrl: 'chapter.html'
}));
directive('section', valueFn({
transclude: 'content',
template: '<div>section-!<div ng-transclude></div>!</div></div>'
}));
return function($httpBackend) {
$httpBackend.
expect('GET', 'chapter.html').
respond('<div>chapter-<div section>[<div ng-transclude></div>]</div></div>');
};
});
inject(function(log, $rootScope, $compile, $httpBackend) {
element = $compile('<div><div book>paragraph</div></div>')($rootScope);
$rootScope.$apply();
expect(element.text()).toEqual('book-');
$httpBackend.flush();
$rootScope.$apply();
expect(element.text()).toEqual('book-chapter-section-![(paragraph)]!');
});
});
it('should not merge text elements from transcluded content', function() {
module(function() {
directive('foo', valueFn({
transclude: 'content',
template: '<div>This is before {{before}}. </div>',
link: function(scope, element, attr, ctrls, $transclude) {
var futureParent = element.children().eq(0);
$transclude(function(clone) {
futureParent.append(clone);
}, futureParent);
},
scope: true
}));
});
inject(function($rootScope, $compile) {
element = $compile('<div><div foo>This is after {{after}}</div></div>')($rootScope);
$rootScope.before = 'BEFORE';
$rootScope.after = 'AFTER';
$rootScope.$apply();
expect(element.text()).toEqual('This is before BEFORE. This is after AFTER');
$rootScope.before = 'Not-Before';
$rootScope.after = 'AfTeR';
$rootScope.$$childHead.before = 'BeFoRe';
$rootScope.$$childHead.after = 'Not-After';
$rootScope.$apply();
expect(element.text()).toEqual('This is before BeFoRe. This is after AfTeR');
});
});
it('should only allow one content transclusion per element', function() {
module(function() {
directive('first', valueFn({
transclude: true
}));
directive('second', valueFn({
transclude: true
}));
});
inject(function($compile) {
expect(function() {
$compile('<div first="" second=""></div>');
}).toThrowMinErr('$compile', 'multidir', /Multiple directives \[first, second\] asking for transclusion on: <div .+/);
});
});
//see issue https://github.com/angular/angular.js/issues/12936
it('should use the proper scope when it is on the root element of a replaced directive template', function() {
module(function() {
directive('isolate', valueFn({
scope: {},
replace: true,
template: '<div trans>{{x}}</div>',
link: function(scope, element, attr, ctrl) {
scope.x = 'iso';
}
}));
directive('trans', valueFn({
transclude: 'content',
link: function(scope, element, attr, ctrl, $transclude) {
$transclude(function(clone) {
element.append(clone);
});
}
}));
});
inject(function($rootScope, $compile) {
element = $compile('<isolate></isolate>')($rootScope);
$rootScope.x = 'root';
$rootScope.$apply();
expect(element.text()).toEqual('iso');
});
});
//see issue https://github.com/angular/angular.js/issues/12936
it('should use the proper scope when it is on the root element of a replaced directive template with child scope', function() {
module(function() {
directive('child', valueFn({
scope: true,
replace: true,
template: '<div trans>{{x}}</div>',
link: function(scope, element, attr, ctrl) {
scope.x = 'child';
}
}));
directive('trans', valueFn({
transclude: 'content',
link: function(scope, element, attr, ctrl, $transclude) {
$transclude(function(clone) {
element.append(clone);
});
}
}));
});
inject(function($rootScope, $compile) {
element = $compile('<child></child>')($rootScope);
$rootScope.x = 'root';
$rootScope.$apply();
expect(element.text()).toEqual('child');
});
});
it('should throw if a transcluded node is transcluded again', function() {
module(function() {
directive('trans', valueFn({
transclude: true,
link: function(scope, element, attr, ctrl, $transclude) {
$transclude();
$transclude();
}
}));
});
inject(function($rootScope, $compile) {
expect(function() {
$compile('<trans></trans>')($rootScope);
}).toThrowMinErr('$compile', 'multilink', 'This element has already been linked.');
});
});
it('should not leak if two "element" transclusions are on the same element (with debug info)', function() {
if (jQuery) {
// jQuery 2.x doesn't expose the cache storage.
return;
}
module(function($compileProvider) {
$compileProvider.debugInfoEnabled(true);
});
inject(function($compile, $rootScope) {
var cacheSize = jqLiteCacheSize();
element = $compile('<div><div ng-repeat="x in xs" ng-if="x==1">{{x}}</div></div>')($rootScope);
expect(jqLiteCacheSize()).toEqual(cacheSize + 1);
$rootScope.$apply('xs = [0,1]');
expect(jqLiteCacheSize()).toEqual(cacheSize + 2);
$rootScope.$apply('xs = [0]');
expect(jqLiteCacheSize()).toEqual(cacheSize + 1);
$rootScope.$apply('xs = []');
expect(jqLiteCacheSize()).toEqual(cacheSize + 1);
element.remove();
expect(jqLiteCacheSize()).toEqual(cacheSize + 0);
});
});
it('should not leak if two "element" transclusions are on the same element (without debug info)', function() {
if (jQuery) {
// jQuery 2.x doesn't expose the cache storage.
return;
}
module(function($compileProvider) {
$compileProvider.debugInfoEnabled(false);
});
inject(function($compile, $rootScope) {
var cacheSize = jqLiteCacheSize();
element = $compile('<div><div ng-repeat="x in xs" ng-if="x==1">{{x}}</div></div>')($rootScope);
expect(jqLiteCacheSize()).toEqual(cacheSize);
$rootScope.$apply('xs = [0,1]');
expect(jqLiteCacheSize()).toEqual(cacheSize);
$rootScope.$apply('xs = [0]');
expect(jqLiteCacheSize()).toEqual(cacheSize);
$rootScope.$apply('xs = []');
expect(jqLiteCacheSize()).toEqual(cacheSize);
element.remove();
expect(jqLiteCacheSize()).toEqual(cacheSize);
});
});
it('should not leak if two "element" transclusions are on the same element (with debug info)', function() {
if (jQuery) {
// jQuery 2.x doesn't expose the cache storage.
return;
}
module(function($compileProvider) {
$compileProvider.debugInfoEnabled(true);
});
inject(function($compile, $rootScope) {
var cacheSize = jqLiteCacheSize();
element = $compile('<div><div ng-repeat="x in xs" ng-if="val">{{x}}</div></div>')($rootScope);
$rootScope.$apply('xs = [0,1]');
// At this point we have a bunch of comment placeholders but no real transcluded elements
// So the cache only contains the root element's data
expect(jqLiteCacheSize()).toEqual(cacheSize + 1);
$rootScope.$apply('val = true');
// Now we have two concrete transcluded elements plus some comments so two more cache items
expect(jqLiteCacheSize()).toEqual(cacheSize + 3);
$rootScope.$apply('val = false');
// Once again we only have comments so no transcluded elements and the cache is back to just
// the root element
expect(jqLiteCacheSize()).toEqual(cacheSize + 1);
element.remove();
// Now we've even removed the root element along with its cache
expect(jqLiteCacheSize()).toEqual(cacheSize + 0);
});
});
it('should not leak when continuing the compilation of elements on a scope that was destroyed', function() {
if (jQuery) {
// jQuery 2.x doesn't expose the cache storage.
return;
}
var linkFn = jasmine.createSpy('linkFn');
module(function($controllerProvider, $compileProvider) {
$controllerProvider.register('Leak', function($scope, $timeout) {
$scope.code = 'red';
$timeout(function() {
$scope.code = 'blue';
});
});
$compileProvider.directive('isolateRed', function() {
return {
restrict: 'A',
scope: {},
template: '<div red></div>'
};
});
$compileProvider.directive('red', function() {
return {
restrict: 'A',
templateUrl: 'red.html',
scope: {},
link: linkFn
};
});
});
inject(function($compile, $rootScope, $httpBackend, $timeout, $templateCache) {
var cacheSize = jqLiteCacheSize();
$httpBackend.whenGET('red.html').respond('<p>red.html</p>');
var template = $compile(
'<div ng-controller="Leak">' +
'<div ng-switch="code">' +
'<div ng-switch-when="red">' +
'<div isolate-red></div>' +
'</div>' +
'</div>' +
'</div>');
element = template($rootScope, noop);
$rootScope.$digest();
$timeout.flush();
$httpBackend.flush();
expect(linkFn).not.toHaveBeenCalled();
expect(jqLiteCacheSize()).toEqual(cacheSize + 2);
$templateCache.removeAll();
var destroyedScope = $rootScope.$new();
destroyedScope.$destroy();
var clone = template(destroyedScope, noop);
$rootScope.$digest();
$timeout.flush();
expect(linkFn).not.toHaveBeenCalled();
clone.remove();
});
});
if (jQuery) {
describe('cleaning up after a replaced element', function() {
var $compile, xs;
beforeEach(inject(function(_$compile_) {
$compile = _$compile_;
xs = [0, 1];
}));
function testCleanup() {
var privateData, firstRepeatedElem;
element = $compile('<div><div ng-repeat="x in xs" ng-click="noop()">{{x}}</div></div>')($rootScope);
$rootScope.$apply('xs = [' + xs + ']');
firstRepeatedElem = element.children('.ng-scope').eq(0);
expect(firstRepeatedElem.data('$scope')).toBeDefined();
privateData = jQuery._data(firstRepeatedElem[0]);
expect(privateData.events).toBeDefined();
expect(privateData.events.click).toBeDefined();
expect(privateData.events.click[0]).toBeDefined();
//Ensure the angular $destroy event is still sent
var destroyCount = 0;
element.find('div').on('$destroy', function() { destroyCount++; });
$rootScope.$apply('xs = null');
expect(destroyCount).toBe(2);
expect(firstRepeatedElem.data('$scope')).not.toBeDefined();
privateData = jQuery._data(firstRepeatedElem[0]);
expect(privateData && privateData.events).not.toBeDefined();
}
it('should work without external libraries (except jQuery)', testCleanup);
it('should work with another library patching jQuery.cleanData after Angular', function() {
var cleanedCount = 0;
var currentCleanData = jQuery.cleanData;
jQuery.cleanData = function(elems) {
cleanedCount += elems.length;
// Don't return the output and explicitly pass only the first parameter
// so that we're sure we're not relying on either of them. jQuery UI patch
// behaves in this way.
currentCleanData(elems);
};
testCleanup();
// The ng-repeat template is removed/cleaned (the +1)
// and each clone of the ng-repeat template is also removed (xs.length)
expect(cleanedCount).toBe(xs.length + 1);
// Restore the previous jQuery.cleanData.
jQuery.cleanData = currentCleanData;
});
});
}
it('should add a $$transcluded property onto the transcluded scope', function() {
module(function() {
directive('trans', function() {
return {
transclude: true,
replace: true,
scope: true,
template: '<div><span>I:{{$$transcluded}}</span><span ng-transclude></span></div>'
};
});
});
inject(function($rootScope, $compile) {
element = $compile('<div><div trans>T:{{$$transcluded}}</div></div>')($rootScope);
$rootScope.$apply();
expect(jqLite(element.find('span')[0]).text()).toEqual('I:');
expect(jqLite(element.find('span')[1]).text()).toEqual('T:true');
});
});
it('should clear contents of the ng-transclude element before appending transcluded content' +
' if transcluded content exists', function() {
module(function() {
directive('trans', function() {
return {
transclude: true,
template: '<div ng-transclude>old stuff!</div>'
};
});
});
inject(function($rootScope, $compile) {
element = $compile('<div trans>unicorn!</div>')($rootScope);
$rootScope.$apply();
expect(sortedHtml(element.html())).toEqual('<div ng-transclude="">unicorn!</div>');
});
});
it('should NOT clear contents of the ng-transclude element before appending transcluded content' +
' if transcluded content does NOT exist', function() {
module(function() {
directive('trans', function() {
return {
transclude: true,
template: '<div ng-transclude>old stuff!</div>'
};
});
});
inject(function(log, $rootScope, $compile) {
element = $compile('<div trans></div>')($rootScope);
$rootScope.$apply();
expect(sortedHtml(element.html())).toEqual('<div ng-transclude="">old stuff!</div>');
});
});
it('should clear the fallback content from the element during compile and before linking', function() {
module(function() {
directive('trans', function() {
return {
transclude: true,
template: '<div ng-transclude>fallback content</div>'
};
});
});
inject(function(log, $rootScope, $compile) {
element = jqLite('<div trans></div>');
var linkfn = $compile(element);
expect(element.html()).toEqual('<div ng-transclude=""></div>');
linkfn($rootScope);
$rootScope.$apply();
expect(sortedHtml(element.html())).toEqual('<div ng-transclude="">fallback content</div>');
});
});
it('should allow cloning of the fallback via ngRepeat', function() {
module(function() {
directive('trans', function() {
return {
transclude: true,
template: '<div ng-repeat="i in [0,1,2]"><div ng-transclude>{{i}}</div></div>'
};
});
});
inject(function(log, $rootScope, $compile) {
element = $compile('<div trans></div>')($rootScope);
$rootScope.$apply();
expect(element.text()).toEqual('012');
});
});
it('should not link the fallback content if transcluded content is provided', function() {
var linkSpy = jasmine.createSpy('postlink');
module(function() {
directive('inner', function() {
return {
restrict: 'E',
template: 'old stuff! ',
link: linkSpy
};
});
directive('trans', function() {
return {
transclude: true,
template: '<div ng-transclude><inner></inner></div>'
};
});
});
inject(function($rootScope, $compile) {
element = $compile('<div trans>unicorn!</div>')($rootScope);
$rootScope.$apply();
expect(sortedHtml(element.html())).toEqual('<div ng-transclude="">unicorn!</div>');
expect(linkSpy).not.toHaveBeenCalled();
});
});
it('should compile and link the fallback content if no transcluded content is provided', function() {
var linkSpy = jasmine.createSpy('postlink');
module(function() {
directive('inner', function() {
return {
restrict: 'E',
template: 'old stuff! ',
link: linkSpy
};
});
directive('trans', function() {
return {
transclude: true,
template: '<div ng-transclude><inner></inner></div>'
};
});
});
inject(function(log, $rootScope, $compile) {
element = $compile('<div trans></div>')($rootScope);
$rootScope.$apply();
expect(sortedHtml(element.html())).toEqual('<div ng-transclude=""><inner>old stuff! </inner></div>');
expect(linkSpy).toHaveBeenCalled();
});
});
it('should compile and link the fallback content if only whitespace transcluded content is provided', function() {
var linkSpy = jasmine.createSpy('postlink');
module(function() {
directive('inner', function() {
return {
restrict: 'E',
template: 'old stuff! ',
link: linkSpy
};
});
directive('trans', function() {
return {
transclude: true,
template: '<div ng-transclude><inner></inner></div>'
};
});
});
inject(function(log, $rootScope, $compile) {
element = $compile('<div trans>\n \n</div>')($rootScope);
$rootScope.$apply();
expect(sortedHtml(element.html())).toEqual('<div ng-transclude=""><inner>old stuff! </inner></div>');
expect(linkSpy).toHaveBeenCalled();
});
});
it('should not link the fallback content if only whitespace and comments are provided as transclude content', function() {
var linkSpy = jasmine.createSpy('postlink');
module(function() {
directive('inner', function() {
return {
restrict: 'E',
template: 'old stuff! ',
link: linkSpy
};
});
directive('trans', function() {
return {
transclude: true,
template: '<div ng-transclude><inner></inner></div>'
};
});
});
inject(function(log, $rootScope, $compile) {
element = $compile('<div trans>\n<!-- some comment --> \n</div>')($rootScope);
$rootScope.$apply();
expect(sortedHtml(element.html())).toEqual('<div ng-transclude="">\n<!-- some comment --> \n</div>');
expect(linkSpy).not.toHaveBeenCalled();
});
});
it('should compile and link the fallback content if an optional transclusion slot is not provided', function() {
var linkSpy = jasmine.createSpy('postlink');
module(function() {
directive('inner', function() {
return {
restrict: 'E',
template: 'old stuff! ',
link: linkSpy
};
});
directive('trans', function() {
return {
transclude: { optionalSlot: '?optional'},
template: '<div ng-transclude="optionalSlot"><inner></inner></div>'
};
});
});
inject(function(log, $rootScope, $compile) {
element = $compile('<div trans></div>')($rootScope);
$rootScope.$apply();
expect(sortedHtml(element.html())).toEqual('<div ng-transclude="optionalSlot"><inner>old stuff! </inner></div>');
expect(linkSpy).toHaveBeenCalled();
});
});
it('should cope if there is neither transcluded content nor fallback content', function() {
module(function() {
directive('trans', function() {
return {
transclude: true,
template: '<div ng-transclude></div>'
};
});
});
inject(function($rootScope, $compile) {
element = $compile('<div trans></div>')($rootScope);
$rootScope.$apply();
expect(sortedHtml(element.html())).toEqual('<div ng-transclude=""></div>');
});
});
it('should throw on an ng-transclude element inside no transclusion directive', function() {
inject(function($rootScope, $compile) {
var error;
try {
$compile('<div><div ng-transclude></div></div>')($rootScope);
} catch (e) {
error = e;
}
expect(error).toEqualMinErr('ngTransclude', 'orphan',
'Illegal use of ngTransclude directive in the template! ' +
'No parent directive that requires a transclusion found. ' +
'Element: <div ng-transclude');
// we need to do this because different browsers print empty attributes differently
});
});
it('should not pass transclusion into a template directive when the directive didn\'t request transclusion', function() {
module(function($compileProvider) {
$compileProvider.directive('transFoo', valueFn({
template: '<div>' +
'<div no-trans-bar></div>' +
'<div ng-transclude>this one should get replaced with content</div>' +
'<div class="foo" ng-transclude></div>' +
'</div>',
transclude: true
}));
$compileProvider.directive('noTransBar', valueFn({
template: '<div>' +
// This ng-transclude is invalid. It should throw an error.
'<div class="bar" ng-transclude></div>' +
'</div>',
transclude: false
}));
});
inject(function($compile, $rootScope) {
expect(function() {
$compile('<div trans-foo>content</div>')($rootScope);
}).toThrowMinErr('ngTransclude', 'orphan',
'Illegal use of ngTransclude directive in the template! No parent directive that requires a transclusion found. Element: <div class="bar" ng-transclude="">');
});
});
it('should not pass transclusion into a templateUrl directive', function() {
module(function($compileProvider) {
$compileProvider.directive('transFoo', valueFn({
template: '<div>' +
'<div no-trans-bar></div>' +
'<div ng-transclude>this one should get replaced with content</div>' +
'<div class="foo" ng-transclude></div>' +
'</div>',
transclude: true
}));
$compileProvider.directive('noTransBar', valueFn({
templateUrl: 'noTransBar.html',
transclude: false
}));
});
inject(function($compile, $exceptionHandler, $rootScope, $templateCache) {
$templateCache.put('noTransBar.html',
'<div>' +
// This ng-transclude is invalid. It should throw an error.
'<div class="bar" ng-transclude></div>' +
'</div>');
element = $compile('<div trans-foo>content</div>')($rootScope);
$rootScope.$digest();
expect($exceptionHandler.errors[0][1]).toBe('<div class="bar" ng-transclude="">');
expect($exceptionHandler.errors[0][0]).toEqualMinErr('ngTransclude', 'orphan',
'Illegal use of ngTransclude directive in the template! ' +
'No parent directive that requires a transclusion found. ' +
'Element: <div class="bar" ng-transclude="">');
});
});
it('should expose transcludeFn in compile fn even for templateUrl', function() {
module(function() {
directive('transInCompile', valueFn({
transclude: true,
// template: '<div class="foo">whatever</div>',
templateUrl: 'foo.html',
compile: function(_, __, transclude) {
return function(scope, element) {
transclude(scope, function(clone, scope) {
element.html('');
element.append(clone);
});
};
}
}));
});
inject(function($compile, $rootScope, $templateCache) {
$templateCache.put('foo.html', '<div class="foo">whatever</div>');
compile('<div trans-in-compile>transcluded content</div>');
$rootScope.$apply();
expect(trim(element.text())).toBe('transcluded content');
});
});
it('should make the result of a transclusion available to the parent directive in post-linking phase' +
'(template)', function() {
module(function() {
directive('trans', function(log) {
return {
transclude: true,
template: '<div ng-transclude></div>',
link: {
pre: function($scope, $element) {
log('pre(' + $element.text() + ')');
},
post: function($scope, $element) {
log('post(' + $element.text() + ')');
}
}
};
});
});
inject(function(log, $rootScope, $compile) {
element = $compile('<div trans><span>unicorn!</span></div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('pre(); post(unicorn!)');
});
});
it('should make the result of a transclusion available to the parent directive in post-linking phase' +
'(templateUrl)', function() {
// when compiling an async directive the transclusion is always processed before the directive
// this is different compared to sync directive. delaying the transclusion makes little sense.
module(function() {
directive('trans', function(log) {
return {
transclude: true,
templateUrl: 'trans.html',
link: {
pre: function($scope, $element) {
log('pre(' + $element.text() + ')');
},
post: function($scope, $element) {
log('post(' + $element.text() + ')');
}
}
};
});
});
inject(function(log, $rootScope, $compile, $templateCache) {
$templateCache.put('trans.html', '<div ng-transclude></div>');
element = $compile('<div trans><span>unicorn!</span></div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('pre(); post(unicorn!)');
});
});
it('should make the result of a transclusion available to the parent *replace* directive in post-linking phase' +
'(template)', function() {
module(function() {
directive('replacedTrans', function(log) {
return {
transclude: true,
replace: true,
template: '<div ng-transclude></div>',
link: {
pre: function($scope, $element) {
log('pre(' + $element.text() + ')');
},
post: function($scope, $element) {
log('post(' + $element.text() + ')');
}
}
};
});
});
inject(function(log, $rootScope, $compile) {
element = $compile('<div replaced-trans><span>unicorn!</span></div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('pre(); post(unicorn!)');
});
});
it('should make the result of a transclusion available to the parent *replace* directive in post-linking phase' +
' (templateUrl)', function() {
module(function() {
directive('replacedTrans', function(log) {
return {
transclude: true,
replace: true,
templateUrl: 'trans.html',
link: {
pre: function($scope, $element) {
log('pre(' + $element.text() + ')');
},
post: function($scope, $element) {
log('post(' + $element.text() + ')');
}
}
};
});
});
inject(function(log, $rootScope, $compile, $templateCache) {
$templateCache.put('trans.html', '<div ng-transclude></div>');
element = $compile('<div replaced-trans><span>unicorn!</span></div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('pre(); post(unicorn!)');
});
});
it('should copy the directive controller to all clones', function() {
var transcludeCtrl, cloneCount = 2;
module(function() {
directive('transclude', valueFn({
transclude: 'content',
controller: function($transclude) {
transcludeCtrl = this;
},
link: function(scope, el, attr, ctrl, $transclude) {
var i;
for (i = 0; i < cloneCount; i++) {
$transclude(cloneAttach);
}
function cloneAttach(clone) {
el.append(clone);
}
}
}));
});
inject(function($compile) {
element = $compile('<div transclude><span></span></div>')($rootScope);
var children = element.children(), i;
expect(transcludeCtrl).toBeDefined();
expect(element.data('$transcludeController')).toBe(transcludeCtrl);
for (i = 0; i < cloneCount; i++) {
expect(children.eq(i).data('$transcludeController')).toBeUndefined();
}
});
});
it('should provide the $transclude controller local as 5th argument to the pre and post-link function', function() {
var ctrlTransclude, preLinkTransclude, postLinkTransclude;
module(function() {
directive('transclude', valueFn({
transclude: 'content',
controller: function($transclude) {
ctrlTransclude = $transclude;
},
compile: function() {
return {
pre: function(scope, el, attr, ctrl, $transclude) {
preLinkTransclude = $transclude;
},
post: function(scope, el, attr, ctrl, $transclude) {
postLinkTransclude = $transclude;
}
};
}
}));
});
inject(function($compile) {
element = $compile('<div transclude></div>')($rootScope);
expect(ctrlTransclude).toBeDefined();
expect(ctrlTransclude).toBe(preLinkTransclude);
expect(ctrlTransclude).toBe(postLinkTransclude);
});
});
it('should allow an optional scope argument in $transclude', function() {
var capturedChildCtrl;
module(function() {
directive('transclude', valueFn({
transclude: 'content',
link: function(scope, element, attr, ctrl, $transclude) {
$transclude(scope, function(clone) {
element.append(clone);
});
}
}));
});
inject(function($compile) {
element = $compile('<div transclude>{{$id}}</div>')($rootScope);
$rootScope.$apply();
expect(element.text()).toBe('' + $rootScope.$id);
});
});
it('should expose the directive controller to transcluded children', function() {
var capturedChildCtrl;
module(function() {
directive('transclude', valueFn({
transclude: 'content',
controller: function() {
},
link: function(scope, element, attr, ctrl, $transclude) {
$transclude(function(clone) {
element.append(clone);
});
}
}));
directive('child', valueFn({
require: '^transclude',
link: function(scope, element, attr, ctrl) {
capturedChildCtrl = ctrl;
}
}));
});
inject(function($compile) {
element = $compile('<div transclude><div child></div></div>')($rootScope);
expect(capturedChildCtrl).toBeTruthy();
});
});
// See issue https://github.com/angular/angular.js/issues/14924
it('should not process top-level transcluded text nodes merged into their sibling',
function() {
module(function() {
directive('transclude', valueFn({
template: '<ng-transclude></ng-transclude>',
transclude: true,
scope: {}
}));
});
inject(function($compile) {
element = jqLite('<div transclude></div>');
element[0].appendChild(document.createTextNode('1{{ value }}'));
element[0].appendChild(document.createTextNode('2{{ value }}'));
element[0].appendChild(document.createTextNode('3{{ value }}'));
var initialWatcherCount = $rootScope.$countWatchers();
$compile(element)($rootScope);
$rootScope.$apply('value = 0');
var newWatcherCount = $rootScope.$countWatchers() - initialWatcherCount;
expect(element.text()).toBe('102030');
expect(newWatcherCount).toBe(3);
});
}
);
// see issue https://github.com/angular/angular.js/issues/9413
describe('passing a parent bound transclude function to the link ' +
'function returned from `$compile`', function() {
beforeEach(module(function() {
directive('lazyCompile', function($compile) {
return {
compile: function(tElement, tAttrs) {
var content = tElement.contents();
tElement.empty();
return function(scope, element, attrs, ctrls, transcludeFn) {
element.append(content);
$compile(content)(scope, undefined, {
parentBoundTranscludeFn: transcludeFn
});
};
}
};
});
directive('toggle', valueFn({
scope: {t: '=toggle'},
transclude: true,
template: '<div ng-if="t"><lazy-compile><div ng-transclude></div></lazy-compile></div>'
}));
}));
it('should preserve the bound scope', function() {
inject(function($compile, $rootScope) {
element = $compile(
'<div>' +
'<div ng-init="outer=true"></div>' +
'<div toggle="t">' +
'<span ng-if="outer">Success</span><span ng-if="!outer">Error</span>' +
'</div>' +
'</div>')($rootScope);
$rootScope.$apply('t = false');
expect($rootScope.$countChildScopes()).toBe(1);
expect(element.text()).toBe('');
$rootScope.$apply('t = true');
expect($rootScope.$countChildScopes()).toBe(4);
expect(element.text()).toBe('Success');
$rootScope.$apply('t = false');
expect($rootScope.$countChildScopes()).toBe(1);
expect(element.text()).toBe('');
$rootScope.$apply('t = true');
expect($rootScope.$countChildScopes()).toBe(4);
expect(element.text()).toBe('Success');
});
});
it('should preserve the bound scope when using recursive transclusion', function() {
directive('recursiveTransclude', valueFn({
transclude: true,
template: '<div><lazy-compile><div ng-transclude></div></lazy-compile></div>'
}));
inject(function($compile, $rootScope) {
element = $compile(
'<div>' +
'<div ng-init="outer=true"></div>' +
'<div toggle="t">' +
'<div recursive-transclude>' +
'<span ng-if="outer">Success</span><span ng-if="!outer">Error</span>' +
'</div>' +
'</div>' +
'</div>')($rootScope);
$rootScope.$apply('t = false');
expect($rootScope.$countChildScopes()).toBe(1);
expect(element.text()).toBe('');
$rootScope.$apply('t = true');
expect($rootScope.$countChildScopes()).toBe(4);
expect(element.text()).toBe('Success');
$rootScope.$apply('t = false');
expect($rootScope.$countChildScopes()).toBe(1);
expect(element.text()).toBe('');
$rootScope.$apply('t = true');
expect($rootScope.$countChildScopes()).toBe(4);
expect(element.text()).toBe('Success');
});
});
});
// see issue https://github.com/angular/angular.js/issues/9095
describe('removing a transcluded element', function() {
beforeEach(module(function() {
directive('toggle', function() {
return {
transclude: true,
template: '<div ng:if="t"><div ng:transclude></div></div>'
};
});
}));
it('should not leak the transclude scope when the transcluded content is an element transclusion directive',
inject(function($compile, $rootScope) {
element = $compile(
'<div toggle>' +
'<div ng:repeat="msg in [\'msg-1\']">{{ msg }}</div>' +
'</div>'
)($rootScope);
$rootScope.$apply('t = true');
expect(element.text()).toContain('msg-1');
// Expected scopes: $rootScope, ngIf, transclusion, ngRepeat
expect($rootScope.$countChildScopes()).toBe(3);
$rootScope.$apply('t = false');
expect(element.text()).not.toContain('msg-1');
// Expected scopes: $rootScope
expect($rootScope.$countChildScopes()).toBe(0);
$rootScope.$apply('t = true');
expect(element.text()).toContain('msg-1');
// Expected scopes: $rootScope, ngIf, transclusion, ngRepeat
expect($rootScope.$countChildScopes()).toBe(3);
$rootScope.$apply('t = false');
expect(element.text()).not.toContain('msg-1');
// Expected scopes: $rootScope
expect($rootScope.$countChildScopes()).toBe(0);
}));
it('should not leak the transclude scope when the transcluded content is an multi-element transclusion directive',
inject(function($compile, $rootScope) {
element = $compile(
'<div toggle>' +
'<div ng:repeat-start="msg in [\'msg-1\']">{{ msg }}</div>' +
'<div ng:repeat-end>{{ msg }}</div>' +
'</div>'
)($rootScope);
$rootScope.$apply('t = true');
expect(element.text()).toContain('msg-1msg-1');
// Expected scopes: $rootScope, ngIf, transclusion, ngRepeat
expect($rootScope.$countChildScopes()).toBe(3);
$rootScope.$apply('t = false');
expect(element.text()).not.toContain('msg-1msg-1');
// Expected scopes: $rootScope
expect($rootScope.$countChildScopes()).toBe(0);
$rootScope.$apply('t = true');
expect(element.text()).toContain('msg-1msg-1');
// Expected scopes: $rootScope, ngIf, transclusion, ngRepeat
expect($rootScope.$countChildScopes()).toBe(3);
$rootScope.$apply('t = false');
expect(element.text()).not.toContain('msg-1msg-1');
// Expected scopes: $rootScope
expect($rootScope.$countChildScopes()).toBe(0);
}));
it('should not leak the transclude scope if the transcluded contains only comments',
inject(function($compile, $rootScope) {
element = $compile(
'<div toggle>' +
'<!-- some comment -->' +
'</div>'
)($rootScope);
$rootScope.$apply('t = true');
expect(element.html()).toContain('some comment');
// Expected scopes: $rootScope, ngIf, transclusion
expect($rootScope.$countChildScopes()).toBe(2);
$rootScope.$apply('t = false');
expect(element.html()).not.toContain('some comment');
// Expected scopes: $rootScope
expect($rootScope.$countChildScopes()).toBe(0);
$rootScope.$apply('t = true');
expect(element.html()).toContain('some comment');
// Expected scopes: $rootScope, ngIf, transclusion
expect($rootScope.$countChildScopes()).toBe(2);
$rootScope.$apply('t = false');
expect(element.html()).not.toContain('some comment');
// Expected scopes: $rootScope
expect($rootScope.$countChildScopes()).toBe(0);
}));
it('should not leak the transclude scope if the transcluded contains only text nodes',
inject(function($compile, $rootScope) {
element = $compile(
'<div toggle>' +
'some text' +
'</div>'
)($rootScope);
$rootScope.$apply('t = true');
expect(element.html()).toContain('some text');
// Expected scopes: $rootScope, ngIf, transclusion
expect($rootScope.$countChildScopes()).toBe(2);
$rootScope.$apply('t = false');
expect(element.html()).not.toContain('some text');
// Expected scopes: $rootScope
expect($rootScope.$countChildScopes()).toBe(0);
$rootScope.$apply('t = true');
expect(element.html()).toContain('some text');
// Expected scopes: $rootScope, ngIf, transclusion
expect($rootScope.$countChildScopes()).toBe(2);
$rootScope.$apply('t = false');
expect(element.html()).not.toContain('some text');
// Expected scopes: $rootScope
expect($rootScope.$countChildScopes()).toBe(0);
}));
it('should mark as destroyed all sub scopes of the scope being destroyed',
inject(function($compile, $rootScope) {
element = $compile(
'<div toggle>' +
'<div ng:repeat="msg in [\'msg-1\']">{{ msg }}</div>' +
'</div>'
)($rootScope);
$rootScope.$apply('t = true');
var childScopes = getChildScopes($rootScope);
$rootScope.$apply('t = false');
for (var i = 0; i < childScopes.length; ++i) {
expect(childScopes[i].$$destroyed).toBe(true);
}
}));
});
describe('nested transcludes', function() {
beforeEach(module(function($compileProvider) {
$compileProvider.directive('noop', valueFn({}));
$compileProvider.directive('sync', valueFn({
template: '<div ng-transclude></div>',
transclude: true
}));
$compileProvider.directive('async', valueFn({
templateUrl: 'async',
transclude: true
}));
$compileProvider.directive('syncSync', valueFn({
template: '<div noop><div sync><div ng-transclude></div></div></div>',
transclude: true
}));
$compileProvider.directive('syncAsync', valueFn({
template: '<div noop><div async><div ng-transclude></div></div></div>',
transclude: true
}));
$compileProvider.directive('asyncSync', valueFn({
templateUrl: 'asyncSync',
transclude: true
}));
$compileProvider.directive('asyncAsync', valueFn({
templateUrl: 'asyncAsync',
transclude: true
}));
}));
beforeEach(inject(function($templateCache) {
$templateCache.put('async', '<div ng-transclude></div>');
$templateCache.put('asyncSync', '<div noop><div sync><div ng-transclude></div></div></div>');
$templateCache.put('asyncAsync', '<div noop><div async><div ng-transclude></div></div></div>');
}));
it('should allow nested transclude directives with sync template containing sync template', inject(function($compile, $rootScope) {
element = $compile('<div sync-sync>transcluded content</div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('transcluded content');
}));
it('should allow nested transclude directives with sync template containing async template', inject(function($compile, $rootScope) {
element = $compile('<div sync-async>transcluded content</div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('transcluded content');
}));
it('should allow nested transclude directives with async template containing sync template', inject(function($compile, $rootScope) {
element = $compile('<div async-sync>transcluded content</div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('transcluded content');
}));
it('should allow nested transclude directives with async template containing asynch template', inject(function($compile, $rootScope) {
element = $compile('<div async-async>transcluded content</div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('transcluded content');
}));
it('should not leak memory with nested transclusion', function() {
inject(function($compile, $rootScope) {
var size, initialSize = jqLiteCacheSize();
element = jqLite('<div><ul><li ng-repeat="n in nums">{{n}} => <i ng-if="0 === n%2">Even</i><i ng-if="1 === n%2">Odd</i></li></ul></div>');
$compile(element)($rootScope.$new());
$rootScope.nums = [0,1,2];
$rootScope.$apply();
size = jqLiteCacheSize();
$rootScope.nums = [3,4,5];
$rootScope.$apply();
expect(jqLiteCacheSize()).toEqual(size);
element.remove();
expect(jqLiteCacheSize()).toEqual(initialSize);
});
});
});
describe('nested isolated scope transcludes', function() {
beforeEach(module(function($compileProvider) {
$compileProvider.directive('trans', valueFn({
restrict: 'E',
template: '<div ng-transclude></div>',
transclude: true
}));
$compileProvider.directive('transAsync', valueFn({
restrict: 'E',
templateUrl: 'transAsync',
transclude: true
}));
$compileProvider.directive('iso', valueFn({
restrict: 'E',
transclude: true,
template: '<trans><span ng-transclude></span></trans>',
scope: {}
}));
$compileProvider.directive('isoAsync1', valueFn({
restrict: 'E',
transclude: true,
template: '<trans-async><span ng-transclude></span></trans-async>',
scope: {}
}));
$compileProvider.directive('isoAsync2', valueFn({
restrict: 'E',
transclude: true,
templateUrl: 'isoAsync',
scope: {}
}));
}));
beforeEach(inject(function($templateCache) {
$templateCache.put('transAsync', '<div ng-transclude></div>');
$templateCache.put('isoAsync', '<trans-async><span ng-transclude></span></trans-async>');
}));
it('should pass the outer scope to the transclude on the isolated template sync-sync', inject(function($compile, $rootScope) {
$rootScope.val = 'transcluded content';
element = $compile('<iso><span ng-bind="val"></span></iso>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('transcluded content');
}));
it('should pass the outer scope to the transclude on the isolated template async-sync', inject(function($compile, $rootScope) {
$rootScope.val = 'transcluded content';
element = $compile('<iso-async1><span ng-bind="val"></span></iso-async1>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('transcluded content');
}));
it('should pass the outer scope to the transclude on the isolated template async-async', inject(function($compile, $rootScope) {
$rootScope.val = 'transcluded content';
element = $compile('<iso-async2><span ng-bind="val"></span></iso-async2>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('transcluded content');
}));
});
describe('multiple siblings receiving transclusion', function() {
it('should only receive transclude from parent', function() {
module(function($compileProvider) {
$compileProvider.directive('myExample', valueFn({
scope: {},
link: function link(scope, element, attrs) {
var foo = element[0].querySelector('.foo');
scope.children = angular.element(foo).children().length;
},
template: '<div>' +
'<div>myExample {{children}}!</div>' +
'<div ng-if="children">has children</div>' +
'<div class="foo" ng-transclude></div>' +
'</div>',
transclude: true
}));
});
inject(function($compile, $rootScope) {
var element = $compile('<div my-example></div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('myExample 0!');
dealoc(element);
element = $compile('<div my-example><p></p></div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('myExample 1!has children');
dealoc(element);
});
});
});
});
describe('element transclusion', function() {
it('should support basic element transclusion', function() {
module(function() {
directive('trans', function(log) {
return {
transclude: 'element',
priority: 2,
controller: function($transclude) { this.$transclude = $transclude; },
compile: function(element, attrs, template) {
log('compile: ' + angular.mock.dump(element));
return function(scope, element, attrs, ctrl) {
log('link');
var cursor = element;
template(scope.$new(), function(clone) {cursor.after(cursor = clone);});
ctrl.$transclude(function(clone) {cursor.after(clone);});
};
}
};
});
});
inject(function(log, $rootScope, $compile) {
element = $compile('<div><div high-log trans="text" log>{{$parent.$id}}-{{$id}};</div></div>')($rootScope);
$rootScope.$apply();
expect(log).toEqual('compile: <!-- trans: text -->; link; LOG; LOG; HIGH');
expect(element.text()).toEqual('1-2;1-3;');
});
});
it('should only allow one element transclusion per element', function() {
module(function() {
directive('first', valueFn({
transclude: 'element'
}));
directive('second', valueFn({
transclude: 'element'
}));
});
inject(function($compile) {
expect(function() {
$compile('<div first second></div>');
}).toThrowMinErr('$compile', 'multidir', 'Multiple directives [first, second] asking for transclusion on: ' +
'<!-- first: -->');
});
});
it('should only allow one element transclusion per element when directives have different priorities', function() {
// we restart compilation in this case and we need to remember the duplicates during the second compile
// regression #3893
module(function() {
directive('first', valueFn({
transclude: 'element',
priority: 100
}));
directive('second', valueFn({
transclude: 'element'
}));
});
inject(function($compile) {
expect(function() {
$compile('<div first second></div>');
}).toThrowMinErr('$compile', 'multidir', /Multiple directives \[first, second\] asking for transclusion on: <div .+/);
});
});
it('should only allow one element transclusion per element when async replace directive is in the mix', function() {
module(function() {
directive('template', valueFn({
templateUrl: 'template.html',
replace: true
}));
directive('first', valueFn({
transclude: 'element',
priority: 100
}));
directive('second', valueFn({
transclude: 'element'
}));
});
inject(function($compile, $exceptionHandler, $httpBackend) {
$httpBackend.expectGET('template.html').respond('<p second>template.html</p>');
$compile('<div template first></div>');
$httpBackend.flush();
expect($exceptionHandler.errors[0]).toEqualMinErr('$compile', 'multidir',
'Multiple directives [first, second] asking for transclusion on: <p ');
});
});
it('should only allow one element transclusion per element when replace directive is in the mix', function() {
module(function() {
directive('template', valueFn({
template: '<p second></p>',
replace: true
}));
directive('first', valueFn({
transclude: 'element',
priority: 100
}));
directive('second', valueFn({
transclude: 'element'
}));
});
inject(function($compile) {
expect(function() {
$compile('<div template first></div>');
}).toThrowMinErr('$compile', 'multidir', /Multiple directives \[first, second\] asking for transclusion on: <p .+/);
});
});
it('should support transcluded element on root content', function() {
var comment;
module(function() {
directive('transclude', valueFn({
transclude: 'element',
compile: function(element, attr, linker) {
return function(scope, element, attr) {
comment = element;
};
}
}));
});
inject(function($compile, $rootScope) {
var element = jqLite('<div>before<div transclude></div>after</div>').contents();
expect(element.length).toEqual(3);
expect(nodeName_(element[1])).toBe('div');
$compile(element)($rootScope);
expect(nodeName_(element[1])).toBe('#comment');
expect(nodeName_(comment)).toBe('#comment');
});
});
it('should terminate compilation only for element transclusion', function() {
module(function() {
directive('elementTrans', function(log) {
return {
transclude: 'element',
priority: 50,
compile: log.fn('compile:elementTrans')
};
});
directive('regularTrans', function(log) {
return {
transclude: true,
priority: 50,
compile: log.fn('compile:regularTrans')
};
});
});
inject(function(log, $compile, $rootScope) {
$compile('<div><div element-trans log="elem"></div><div regular-trans log="regular"></div></div>')($rootScope);
expect(log).toEqual('compile:elementTrans; compile:regularTrans; regular');
});
});
it('should instantiate high priority controllers only once, but low priority ones each time we transclude',
function() {
module(function() {
directive('elementTrans', function(log) {
return {
transclude: 'element',
priority: 50,
controller: function($transclude, $element) {
log('controller:elementTrans');
$transclude(function(clone) {
$element.after(clone);
});
$transclude(function(clone) {
$element.after(clone);
});
$transclude(function(clone) {
$element.after(clone);
});
}
};
});
directive('normalDir', function(log) {
return {
controller: function() {
log('controller:normalDir');
}
};
});
});
inject(function($compile, $rootScope, log) {
element = $compile('<div><div element-trans normal-dir></div></div>')($rootScope);
expect(log).toEqual([
'controller:elementTrans',
'controller:normalDir',
'controller:normalDir',
'controller:normalDir'
]);
});
});
it('should allow to access $transclude in the same directive', function() {
var _$transclude;
module(function() {
directive('transclude', valueFn({
transclude: 'element',
controller: function($transclude) {
_$transclude = $transclude;
}
}));
});
inject(function($compile) {
element = $compile('<div transclude></div>')($rootScope);
expect(_$transclude).toBeDefined();
});
});
it('should copy the directive controller to all clones', function() {
var transcludeCtrl, cloneCount = 2;
module(function() {
directive('transclude', valueFn({
transclude: 'element',
controller: function() {
transcludeCtrl = this;
},
link: function(scope, el, attr, ctrl, $transclude) {
var i;
for (i = 0; i < cloneCount; i++) {
$transclude(cloneAttach);
}
function cloneAttach(clone) {
el.after(clone);
}
}
}));
});
inject(function($compile) {
element = $compile('<div><div transclude></div></div>')($rootScope);
var children = element.children(), i;
for (i = 0; i < cloneCount; i++) {
expect(children.eq(i).data('$transcludeController')).toBe(transcludeCtrl);
}
});
});
it('should expose the directive controller to transcluded children', function() {
var capturedTranscludeCtrl;
module(function() {
directive('transclude', valueFn({
transclude: 'element',
controller: function() {
},
link: function(scope, element, attr, ctrl, $transclude) {
$transclude(scope, function(clone) {
element.after(clone);
});
}
}));
directive('child', valueFn({
require: '^transclude',
link: function(scope, element, attr, ctrl) {
capturedTranscludeCtrl = ctrl;
}
}));
});
inject(function($compile) {
// We need to wrap the transclude directive's element in a parent element so that the
// cloned element gets deallocated/cleaned up correctly
element = $compile('<div><div transclude><div child></div></div></div>')($rootScope);
expect(capturedTranscludeCtrl).toBeTruthy();
});
});
it('should allow access to $transclude in a templateUrl directive', function() {
var transclude;
module(function() {
directive('template', valueFn({
templateUrl: 'template.html',
replace: true
}));
directive('transclude', valueFn({
transclude: 'content',
controller: function($transclude) {
transclude = $transclude;
}
}));
});
inject(function($compile, $httpBackend) {
$httpBackend.expectGET('template.html').respond('<div transclude></div>');
element = $compile('<div template></div>')($rootScope);
$httpBackend.flush();
expect(transclude).toBeDefined();
});
});
// issue #6006
it('should link directive with $element as a comment node', function() {
module(function($provide) {
directive('innerAgain', function(log) {
return {
transclude: 'element',
link: function(scope, element, attr, controllers, transclude) {
log('innerAgain:' + lowercase(nodeName_(element)) + ':' + trim(element[0].data));
transclude(scope, function(clone) {
element.parent().append(clone);
});
}
};
});
directive('inner', function(log) {
return {
replace: true,
templateUrl: 'inner.html',
link: function(scope, element) {
log('inner:' + lowercase(nodeName_(element)) + ':' + trim(element[0].data));
}
};
});
directive('outer', function(log) {
return {
transclude: 'element',
link: function(scope, element, attrs, controllers, transclude) {
log('outer:' + lowercase(nodeName_(element)) + ':' + trim(element[0].data));
transclude(scope, function(clone) {
element.parent().append(clone);
});
}
};
});
});
inject(function(log, $compile, $rootScope, $templateCache) {
$templateCache.put('inner.html', '<div inner-again><p>Content</p></div>');
element = $compile('<div><div outer><div inner></div></div></div>')($rootScope);
$rootScope.$digest();
var child = element.children();
expect(log.toArray()).toEqual([
'outer:#comment:outer:',
'innerAgain:#comment:innerAgain:',
'inner:#comment:innerAgain:'
]);
expect(child.length).toBe(1);
expect(child.contents().length).toBe(2);
expect(lowercase(nodeName_(child.contents().eq(0)))).toBe('#comment');
expect(lowercase(nodeName_(child.contents().eq(1)))).toBe('div');
});
});
});
it('should be possible to change the scope of a directive using $provide', function() {
module(function($provide) {
directive('foo', function() {
return {
scope: {},
template: '<div></div>'
};
});
$provide.decorator('fooDirective', function($delegate) {
var directive = $delegate[0];
directive.scope.something = '=';
directive.template = '<span>{{something}}</span>';
return $delegate;
});
});
inject(function($compile, $rootScope) {
element = $compile('<div><div foo something="bar"></div></div>')($rootScope);
$rootScope.bar = 'bar';
$rootScope.$digest();
expect(element.text()).toBe('bar');
});
});
it('should distinguish different bindings with the same binding name', function() {
module(function() {
directive('foo', function() {
return {
scope: {
foo: '=',
bar: '='
},
template: '<div><div>{{foo}}</div><div>{{bar}}</div></div>'
};
});
});
inject(function($compile, $rootScope) {
element = $compile('<div><div foo="\'foo\'" bar="\'bar\'"></div></div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toBe('foobar');
});
});
it('should safely create transclude comment node and not break with "-->"',
inject(function($rootScope) {
// see: https://github.com/angular/angular.js/issues/1740
element = $compile('<ul><li ng-repeat="item in [\'-->\', \'x\']">{{item}}|</li></ul>')($rootScope);
$rootScope.$digest();
expect(element.text()).toBe('-->|x|');
}));
describe('lazy compilation', function() {
// See https://github.com/angular/angular.js/issues/7183
it('should pass transclusion through to template of a \'replace\' directive', function() {
module(function() {
directive('transSync', function() {
return {
transclude: true,
link: function(scope, element, attr, ctrl, transclude) {
expect(transclude).toEqual(jasmine.any(Function));
transclude(function(child) { element.append(child); });
}
};
});
directive('trans', function($timeout) {
return {
transclude: true,
link: function(scope, element, attrs, ctrl, transclude) {
// We use timeout here to simulate how ng-if works
$timeout(function() {
transclude(function(child) { element.append(child); });
});
}
};
});
directive('replaceWithTemplate', function() {
return {
templateUrl: 'template.html',
replace: true
};
});
});
inject(function($compile, $rootScope, $templateCache, $timeout) {
$templateCache.put('template.html', '<div trans-sync>Content To Be Transcluded</div>');
expect(function() {
element = $compile('<div><div trans><div replace-with-template></div></div></div>')($rootScope);
$timeout.flush();
}).not.toThrow();
expect(element.text()).toEqual('Content To Be Transcluded');
});
});
it('should lazily compile the contents of directives that are transcluded', function() {
var innerCompilationCount = 0, transclude;
module(function() {
directive('trans', valueFn({
transclude: true,
controller: function($transclude) {
transclude = $transclude;
}
}));
directive('inner', valueFn({
template: '<span>FooBar</span>',
compile: function() {
innerCompilationCount += 1;
}
}));
});
inject(function($compile, $rootScope) {
element = $compile('<trans><inner></inner></trans>')($rootScope);
expect(innerCompilationCount).toBe(0);
transclude(function(child) { element.append(child); });
expect(innerCompilationCount).toBe(1);
expect(element.text()).toBe('FooBar');
});
});
it('should lazily compile the contents of directives that are transcluded with a template', function() {
var innerCompilationCount = 0, transclude;
module(function() {
directive('trans', valueFn({
transclude: true,
template: '<div>Baz</div>',
controller: function($transclude) {
transclude = $transclude;
}
}));
directive('inner', valueFn({
template: '<span>FooBar</span>',
compile: function() {
innerCompilationCount += 1;
}
}));
});
inject(function($compile, $rootScope) {
element = $compile('<trans><inner></inner></trans>')($rootScope);
expect(innerCompilationCount).toBe(0);
transclude(function(child) { element.append(child); });
expect(innerCompilationCount).toBe(1);
expect(element.text()).toBe('BazFooBar');
});
});
it('should lazily compile the contents of directives that are transcluded with a templateUrl', function() {
var innerCompilationCount = 0, transclude;
module(function() {
directive('trans', valueFn({
transclude: true,
templateUrl: 'baz.html',
controller: function($transclude) {
transclude = $transclude;
}
}));
directive('inner', valueFn({
template: '<span>FooBar</span>',
compile: function() {
innerCompilationCount += 1;
}
}));
});
inject(function($compile, $rootScope, $httpBackend) {
$httpBackend.expectGET('baz.html').respond('<div>Baz</div>');
element = $compile('<trans><inner></inner></trans>')($rootScope);
$httpBackend.flush();
expect(innerCompilationCount).toBe(0);
transclude(function(child) { element.append(child); });
expect(innerCompilationCount).toBe(1);
expect(element.text()).toBe('BazFooBar');
});
});
it('should lazily compile the contents of directives that are transclude element', function() {
var innerCompilationCount = 0, transclude;
module(function() {
directive('trans', valueFn({
transclude: 'element',
controller: function($transclude) {
transclude = $transclude;
}
}));
directive('inner', valueFn({
template: '<span>FooBar</span>',
compile: function() {
innerCompilationCount += 1;
}
}));
});
inject(function($compile, $rootScope) {
element = $compile('<div><trans><inner></inner></trans></div>')($rootScope);
expect(innerCompilationCount).toBe(0);
transclude(function(child) { element.append(child); });
expect(innerCompilationCount).toBe(1);
expect(element.text()).toBe('FooBar');
});
});
it('should lazily compile transcluded directives with ngIf on them', function() {
var innerCompilationCount = 0, outerCompilationCount = 0, transclude;
module(function() {
directive('outer', valueFn({
transclude: true,
compile: function() {
outerCompilationCount += 1;
},
controller: function($transclude) {
transclude = $transclude;
}
}));
directive('inner', valueFn({
template: '<span>FooBar</span>',
compile: function() {
innerCompilationCount += 1;
}
}));
});
inject(function($compile, $rootScope) {
$rootScope.shouldCompile = false;
element = $compile('<div><outer ng-if="shouldCompile"><inner></inner></outer></div>')($rootScope);
expect(outerCompilationCount).toBe(0);
expect(innerCompilationCount).toBe(0);
expect(transclude).toBeUndefined();
$rootScope.$apply('shouldCompile=true');
expect(outerCompilationCount).toBe(1);
expect(innerCompilationCount).toBe(0);
expect(transclude).toBeDefined();
transclude(function(child) { element.append(child); });
expect(outerCompilationCount).toBe(1);
expect(innerCompilationCount).toBe(1);
expect(element.text()).toBe('FooBar');
});
});
it('should eagerly compile multiple directives with transclusion and templateUrl/replace', function() {
var innerCompilationCount = 0;
module(function() {
directive('outer', valueFn({
transclude: true
}));
directive('outer', valueFn({
templateUrl: 'inner.html',
replace: true
}));
directive('inner', valueFn({
compile: function() {
innerCompilationCount += 1;
}
}));
});
inject(function($compile, $rootScope, $httpBackend) {
$httpBackend.expectGET('inner.html').respond('<inner></inner>');
element = $compile('<outer></outer>')($rootScope);
$httpBackend.flush();
expect(innerCompilationCount).toBe(1);
});
});
});
});
});
});
describe('multi-slot transclude', function() {
it('should only include elements without a matching transclusion element in default transclusion slot', function() {
module(function() {
directive('minionComponent', function() {
return {
restrict: 'E',
scope: {},
transclude: {
bossSlot: 'boss'
},
template:
'<div class="other" ng-transclude></div>'
};
});
});
inject(function($rootScope, $compile) {
element = $compile(
'<minion-component>' +
'<span>stuart</span>' +
'<span>bob</span>' +
'<boss>gru</boss>' +
'<span>kevin</span>' +
'</minion-component>')($rootScope);
$rootScope.$apply();
expect(element.text()).toEqual('stuartbobkevin');
});
});
it('should use the default transclusion slot if the ng-transclude attribute has the same value as its key', function() {
module(function() {
directive('minionComponent', function() {
return {
restrict: 'E',
scope: {},
transclude: {},
template:
'<div class="a" ng-transclude="ng-transclude"></div>' +
'<div class="b" ng:transclude="ng:transclude"></div>' +
'<div class="c" data-ng-transclude="data-ng-transclude"></div>'
};
});
});
inject(function($rootScope, $compile) {
element = $compile(
'<minion-component>' +
'<span>stuart</span>' +
'<span>bob</span>' +
'<span>kevin</span>' +
'</minion-component>')($rootScope);
$rootScope.$apply();
var a = element.children().eq(0);
var b = element.children().eq(1);
var c = element.children().eq(2);
expect(a).toHaveClass('a');
expect(b).toHaveClass('b');
expect(c).toHaveClass('c');
expect(a.text()).toEqual('stuartbobkevin');
expect(b.text()).toEqual('stuartbobkevin');
expect(c.text()).toEqual('stuartbobkevin');
});
});
it('should include non-element nodes in the default transclusion', function() {
module(function() {
directive('minionComponent', function() {
return {
restrict: 'E',
scope: {},
transclude: {
bossSlot: 'boss'
},
template:
'<div class="other" ng-transclude></div>'
};
});
});
inject(function($rootScope, $compile) {
element = $compile(
'<minion-component>' +
'text1' +
'<span>stuart</span>' +
'<span>bob</span>' +
'<boss>gru</boss>' +
'text2' +
'<span>kevin</span>' +
'</minion-component>')($rootScope);
$rootScope.$apply();
expect(element.text()).toEqual('text1stuartbobtext2kevin');
});
});
it('should transclude elements to an `ng-transclude` with a matching transclusion slot name', function() {
module(function() {
directive('minionComponent', function() {
return {
restrict: 'E',
scope: {},
transclude: {
minionSlot: 'minion',
bossSlot: 'boss'
},
template:
'<div class="boss" ng-transclude="bossSlot"></div>' +
'<div class="minion" ng-transclude="minionSlot"></div>' +
'<div class="other" ng-transclude></div>'
};
});
});
inject(function($rootScope, $compile) {
element = $compile(
'<minion-component>' +
'<minion>stuart</minion>' +
'<span>dorothy</span>' +
'<boss>gru</boss>' +
'<minion>kevin</minion>' +
'</minion-component>')($rootScope);
$rootScope.$apply();
expect(element.children().eq(0).text()).toEqual('gru');
expect(element.children().eq(1).text()).toEqual('stuartkevin');
expect(element.children().eq(2).text()).toEqual('dorothy');
});
});
it('should use the `ng-transclude-slot` attribute if ng-transclude is used as an element', function() {
module(function() {
directive('minionComponent', function() {
return {
restrict: 'E',
scope: {},
transclude: {
minionSlot: 'minion',
bossSlot: 'boss'
},
template:
'<ng-transclude class="boss" ng-transclude-slot="bossSlot"></ng-transclude>' +
'<ng-transclude class="minion" ng-transclude-slot="minionSlot"></ng-transclude>' +
'<ng-transclude class="other"></ng-transclude>'
};
});
});
inject(function($rootScope, $compile) {
element = $compile(
'<minion-component>' +
'<minion>stuart</minion>' +
'<span>dorothy</span>' +
'<boss>gru</boss>' +
'<minion>kevin</minion>' +
'</minion-component>')($rootScope);
$rootScope.$apply();
expect(element.children().eq(0).text()).toEqual('gru');
expect(element.children().eq(1).text()).toEqual('stuartkevin');
expect(element.children().eq(2).text()).toEqual('dorothy');
});
});
it('should error if a required transclude slot is not filled', function() {
module(function() {
directive('minionComponent', function() {
return {
restrict: 'E',
scope: {},
transclude: {
minionSlot: 'minion',
bossSlot: 'boss'
},
template:
'<div class="boss" ng-transclude="bossSlot"></div>' +
'<div class="minion" ng-transclude="minionSlot"></div>' +
'<div class="other" ng-transclude></div>'
};
});
});
inject(function($rootScope, $compile) {
expect(function() {
element = $compile(
'<minion-component>' +
'<minion>stuart</minion>' +
'<span>dorothy</span>' +
'</minion-component>')($rootScope);
}).toThrowMinErr('$compile', 'reqslot', 'Required transclusion slot `bossSlot` was not filled.');
});
});
it('should not error if an optional transclude slot is not filled', function() {
module(function() {
directive('minionComponent', function() {
return {
restrict: 'E',
scope: {},
transclude: {
minionSlot: 'minion',
bossSlot: '?boss'
},
template:
'<div class="boss" ng-transclude="bossSlot"></div>' +
'<div class="minion" ng-transclude="minionSlot"></div>' +
'<div class="other" ng-transclude></div>'
};
});
});
inject(function($rootScope, $compile) {
element = $compile(
'<minion-component>' +
'<minion>stuart</minion>' +
'<span>dorothy</span>' +
'</minion-component>')($rootScope);
$rootScope.$apply();
expect(element.children().eq(1).text()).toEqual('stuart');
expect(element.children().eq(2).text()).toEqual('dorothy');
});
});
it('should error if we try to transclude a slot that was not declared by the directive', function() {
module(function() {
directive('minionComponent', function() {
return {
restrict: 'E',
scope: {},
transclude: {
minionSlot: 'minion'
},
template:
'<div class="boss" ng-transclude="bossSlot"></div>' +
'<div class="minion" ng-transclude="minionSlot"></div>' +
'<div class="other" ng-transclude></div>'
};
});
});
inject(function($rootScope, $compile) {
expect(function() {
element = $compile(
'<minion-component>' +
'<minion>stuart</minion>' +
'<span>dorothy</span>' +
'</minion-component>')($rootScope);
}).toThrowMinErr('$compile', 'noslot',
'No parent directive that requires a transclusion with slot name "bossSlot". ' +
'Element: <div class="boss" ng-transclude="bossSlot">');
});
});
it('should allow the slot name to equal the element name', function() {
module(function() {
directive('foo', function() {
return {
restrict: 'E',
scope: {},
transclude: {
bar: 'bar'
},
template:
'<div class="other" ng-transclude="bar"></div>'
};
});
});
inject(function($rootScope, $compile) {
element = $compile(
'<foo>' +
'<bar>baz</bar>' +
'</foo>')($rootScope);
$rootScope.$apply();
expect(element.text()).toEqual('baz');
});
});
it('should match the normalized form of the element name', function() {
module(function() {
directive('foo', function() {
return {
restrict: 'E',
scope: {},
transclude: {
fooBarSlot: 'fooBar',
mooKarSlot: 'mooKar'
},
template:
'<div class="a" ng-transclude="fooBarSlot"></div>' +
'<div class="b" ng-transclude="mooKarSlot"></div>'
};
});
});
inject(function($rootScope, $compile) {
element = $compile(
'<foo>' +
'<foo-bar>bar1</foo-bar>' +
'<foo:bar>bar2</foo:bar>' +
'<moo-kar>baz1</moo-kar>' +
'<data-moo-kar>baz2</data-moo-kar>' +
'</foo>')($rootScope);
$rootScope.$apply();
expect(element.children().eq(0).text()).toEqual('bar1bar2');
expect(element.children().eq(1).text()).toEqual('baz1baz2');
});
});
it('should return true from `isSlotFilled(slotName) for slots that have content in the transclusion', function() {
var capturedTranscludeFn;
module(function() {
directive('minionComponent', function() {
return {
restrict: 'E',
scope: {},
transclude: {
minionSlot: 'minion',
bossSlot: '?boss'
},
template:
'<div class="boss" ng-transclude="bossSlot"></div>' +
'<div class="minion" ng-transclude="minionSlot"></div>' +
'<div class="other" ng-transclude></div>',
link: function(s, e, a, c, transcludeFn) {
capturedTranscludeFn = transcludeFn;
}
};
});
});
inject(function($rootScope, $compile, log) {
element = $compile(
'<minion-component>' +
' <minion>stuart</minion>' +
' <minion>bob</minion>' +
' <span>dorothy</span>' +
'</minion-component>')($rootScope);
$rootScope.$apply();
var hasMinions = capturedTranscludeFn.isSlotFilled('minionSlot');
var hasBosses = capturedTranscludeFn.isSlotFilled('bossSlot');
expect(hasMinions).toBe(true);
expect(hasBosses).toBe(false);
});
});
it('should not overwrite the contents of an `ng-transclude` element, if the matching optional slot is not filled', function() {
module(function() {
directive('minionComponent', function() {
return {
restrict: 'E',
scope: {},
transclude: {
minionSlot: 'minion',
bossSlot: '?boss'
},
template:
'<div class="boss" ng-transclude="bossSlot">default boss content</div>' +
'<div class="minion" ng-transclude="minionSlot">default minion content</div>' +
'<div class="other" ng-transclude>default content</div>'
};
});
});
inject(function($rootScope, $compile) {
element = $compile(
'<minion-component>' +
'<minion>stuart</minion>' +
'<span>dorothy</span>' +
'<minion>kevin</minion>' +
'</minion-component>')($rootScope);
$rootScope.$apply();
expect(element.children().eq(0).text()).toEqual('default boss content');
expect(element.children().eq(1).text()).toEqual('stuartkevin');
expect(element.children().eq(2).text()).toEqual('dorothy');
});
});
// See issue https://github.com/angular/angular.js/issues/14924
it('should not process top-level transcluded text nodes merged into their sibling',
function() {
module(function() {
directive('transclude', valueFn({
template: '<ng-transclude></ng-transclude>',
transclude: {},
scope: {}
}));
});
inject(function($compile) {
element = jqLite('<div transclude></div>');
element[0].appendChild(document.createTextNode('1{{ value }}'));
element[0].appendChild(document.createTextNode('2{{ value }}'));
element[0].appendChild(document.createTextNode('3{{ value }}'));
var initialWatcherCount = $rootScope.$countWatchers();
$compile(element)($rootScope);
$rootScope.$apply('value = 0');
var newWatcherCount = $rootScope.$countWatchers() - initialWatcherCount;
expect(element.text()).toBe('102030');
expect(newWatcherCount).toBe(3);
// Support: IE 11 only
// See #11781 and #14924
if (msie === 11) {
expect(element.find('ng-transclude').contents().length).toBe(1);
}
});
}
);
});
describe('*[src] context requirement', function() {
it('should NOT require trusted values for img src', inject(function($rootScope, $compile, $sce) {
element = $compile('<img src="{{testUrl}}"></img>')($rootScope);
$rootScope.testUrl = 'http://example.com/image.png';
$rootScope.$digest();
expect(element.attr('src')).toEqual('http://example.com/image.png');
// But it should accept trusted values anyway.
$rootScope.testUrl = $sce.trustAsUrl('http://example.com/image2.png');
$rootScope.$digest();
expect(element.attr('src')).toEqual('http://example.com/image2.png');
}));
// Support: IE 9 only
// IE9 rejects the video / audio tag with "Error: Not implemented" and the source tag with
// "Unable to get value of the property 'childNodes': object is null or undefined"
if (msie !== 9) {
they('should NOT require trusted values for $prop src', ['video', 'audio'],
function(tag) {
inject(function($rootScope, $compile, $sce) {
element = $compile('<' + tag + ' src="{{testUrl}}"></' + tag + '>')($rootScope);
$rootScope.testUrl = 'http://example.com/image.mp4';
$rootScope.$digest();
expect(element.attr('src')).toEqual('http://example.com/image.mp4');
// But it should accept trusted values anyway.
$rootScope.testUrl = $sce.trustAsUrl('http://example.com/image2.mp4');
$rootScope.$digest();
expect(element.attr('src')).toEqual('http://example.com/image2.mp4');
// and trustedResourceUrls for retrocompatibility
$rootScope.testUrl = $sce.trustAsResourceUrl('http://example.com/image3.mp4');
$rootScope.$digest();
expect(element.attr('src')).toEqual('http://example.com/image3.mp4');
});
});
they('should NOT require trusted values for $prop src', ['source', 'track'],
function(tag) {
inject(function($rootScope, $compile, $sce) {
element = $compile('<video><' + tag + ' src="{{testUrl}}"></' + tag + '></video>')($rootScope);
$rootScope.testUrl = 'http://example.com/image.mp4';
$rootScope.$digest();
expect(element.find(tag).attr('src')).toEqual('http://example.com/image.mp4');
// But it should accept trusted values anyway.
$rootScope.testUrl = $sce.trustAsUrl('http://example.com/image2.mp4');
$rootScope.$digest();
expect(element.find(tag).attr('src')).toEqual('http://example.com/image2.mp4');
// and trustedResourceUrls for retrocompatibility
$rootScope.testUrl = $sce.trustAsResourceUrl('http://example.com/image3.mp4');
$rootScope.$digest();
expect(element.find(tag).attr('src')).toEqual('http://example.com/image3.mp4');
});
});
}
});
describe('img[src] sanitization', function() {
it('should not sanitize attributes other than src', inject(function($compile, $rootScope) {
element = $compile('<img title="{{testUrl}}"></img>')($rootScope);
$rootScope.testUrl = 'javascript:doEvilStuff()';
$rootScope.$apply();
expect(element.attr('title')).toBe('javascript:doEvilStuff()');
}));
it('should use $$sanitizeUriProvider for reconfiguration of the src whitelist', function() {
module(function($compileProvider, $$sanitizeUriProvider) {
var newRe = /javascript:/,
returnVal;
expect($compileProvider.imgSrcSanitizationWhitelist()).toBe($$sanitizeUriProvider.imgSrcSanitizationWhitelist());
returnVal = $compileProvider.imgSrcSanitizationWhitelist(newRe);
expect(returnVal).toBe($compileProvider);
expect($$sanitizeUriProvider.imgSrcSanitizationWhitelist()).toBe(newRe);
expect($compileProvider.imgSrcSanitizationWhitelist()).toBe(newRe);
});
inject(function() {
// needed to the module definition above is run...
});
});
it('should use $$sanitizeUri', function() {
var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri');
module(function($provide) {
$provide.value('$$sanitizeUri', $$sanitizeUri);
});
inject(function($compile, $rootScope) {
element = $compile('<img src="{{testUrl}}"></img>')($rootScope);
$rootScope.testUrl = 'someUrl';
$$sanitizeUri.and.returnValue('someSanitizedUrl');
$rootScope.$apply();
expect(element.attr('src')).toBe('someSanitizedUrl');
expect($$sanitizeUri).toHaveBeenCalledWith($rootScope.testUrl, true);
});
});
});
describe('img[srcset] sanitization', function() {
it('should not error if undefined', function() {
var linked = false;
module(function() {
directive('setter', valueFn(function(scope, elem, attrs) {
attrs.$set('srcset', 'http://example.com/');
expect(attrs.srcset).toBe('http://example.com/');
attrs.$set('srcset', undefined);
expect(attrs.srcset).toBeUndefined();
linked = true;
}));
});
inject(function($compile, $rootScope) {
element = $compile('<img setter></img>')($rootScope);
expect(linked).toBe(true);
expect(element.attr('srcset')).toBeUndefined();
});
});
it('should NOT require trusted values for img srcset', inject(function($rootScope, $compile, $sce) {
element = $compile('<img srcset="{{testUrl}}"></img>')($rootScope);
$rootScope.testUrl = 'http://example.com/image.png';
$rootScope.$digest();
expect(element.attr('srcset')).toEqual('http://example.com/image.png');
// But it should accept trusted values anyway.
$rootScope.testUrl = $sce.trustAsUrl('http://example.com/image2.png');
$rootScope.$digest();
expect(element.attr('srcset')).toEqual('http://example.com/image2.png');
}));
it('should use $$sanitizeUri', function() {
var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri');
module(function($provide) {
$provide.value('$$sanitizeUri', $$sanitizeUri);
});
inject(function($compile, $rootScope) {
element = $compile('<img srcset="{{testUrl}}"></img>')($rootScope);
$rootScope.testUrl = 'someUrl';
$$sanitizeUri.and.returnValue('someSanitizedUrl');
$rootScope.$apply();
expect(element.attr('srcset')).toBe('someSanitizedUrl');
expect($$sanitizeUri).toHaveBeenCalledWith($rootScope.testUrl, true);
});
});
it('should sanitize all uris in srcset', inject(function($rootScope, $compile) {
element = $compile('<img srcset="{{testUrl}}"></img>')($rootScope);
var testSet = {
'http://example.com/image.png':'http://example.com/image.png',
' http://example.com/image.png':'http://example.com/image.png',
'http://example.com/image.png ':'http://example.com/image.png',
'http://example.com/image.png 128w':'http://example.com/image.png 128w',
'http://example.com/image.png 2x':'http://example.com/image.png 2x',
'http://example.com/image.png 1.5x':'http://example.com/image.png 1.5x',
'http://example.com/image1.png 1x,http://example.com/image2.png 2x':'http://example.com/image1.png 1x,http://example.com/image2.png 2x',
'http://example.com/image1.png 1x ,http://example.com/image2.png 2x':'http://example.com/image1.png 1x ,http://example.com/image2.png 2x',
'http://example.com/image1.png 1x, http://example.com/image2.png 2x':'http://example.com/image1.png 1x,http://example.com/image2.png 2x',
'http://example.com/image1.png 1x , http://example.com/image2.png 2x':'http://example.com/image1.png 1x ,http://example.com/image2.png 2x',
'http://example.com/image1.png 48w,http://example.com/image2.png 64w':'http://example.com/image1.png 48w,http://example.com/image2.png 64w',
//Test regex to make sure doesn't mistake parts of url for width descriptors
'http://example.com/image1.png?w=48w,http://example.com/image2.png 64w':'http://example.com/image1.png?w=48w,http://example.com/image2.png 64w',
'http://example.com/image1.png 1x,http://example.com/image2.png 64w':'http://example.com/image1.png 1x,http://example.com/image2.png 64w',
'http://example.com/image1.png,http://example.com/image2.png':'http://example.com/image1.png ,http://example.com/image2.png',
'http://example.com/image1.png ,http://example.com/image2.png':'http://example.com/image1.png ,http://example.com/image2.png',
'http://example.com/image1.png, http://example.com/image2.png':'http://example.com/image1.png ,http://example.com/image2.png',
'http://example.com/image1.png , http://example.com/image2.png':'http://example.com/image1.png ,http://example.com/image2.png',
'http://example.com/image1.png 1x, http://example.com/image2.png 2x, http://example.com/image3.png 3x':
'http://example.com/image1.png 1x,http://example.com/image2.png 2x,http://example.com/image3.png 3x',
'javascript:doEvilStuff() 2x': 'unsafe:javascript:doEvilStuff() 2x',
'http://example.com/image1.png 1x,javascript:doEvilStuff() 2x':'http://example.com/image1.png 1x,unsafe:javascript:doEvilStuff() 2x',
'http://example.com/image1.jpg?x=a,b 1x,http://example.com/ima,ge2.jpg 2x':'http://example.com/image1.jpg?x=a,b 1x,http://example.com/ima,ge2.jpg 2x',
//Test regex to make sure doesn't mistake parts of url for pixel density descriptors
'http://example.com/image1.jpg?x=a2x,b 1x,http://example.com/ima,ge2.jpg 2x':'http://example.com/image1.jpg?x=a2x,b 1x,http://example.com/ima,ge2.jpg 2x'
};
forEach(testSet, function(ref, url) {
$rootScope.testUrl = url;
$rootScope.$digest();
expect(element.attr('srcset')).toEqual(ref);
});
}));
});
describe('a[href] sanitization', function() {
it('should not sanitize href on elements other than anchor', inject(function($compile, $rootScope) {
element = $compile('<div href="{{testUrl}}"></div>')($rootScope);
$rootScope.testUrl = 'javascript:doEvilStuff()';
$rootScope.$apply();
expect(element.attr('href')).toBe('javascript:doEvilStuff()');
}));
it('should not sanitize attributes other than href', inject(function($compile, $rootScope) {
element = $compile('<a title="{{testUrl}}"></a>')($rootScope);
$rootScope.testUrl = 'javascript:doEvilStuff()';
$rootScope.$apply();
expect(element.attr('title')).toBe('javascript:doEvilStuff()');
}));
it('should use $$sanitizeUriProvider for reconfiguration of the href whitelist', function() {
module(function($compileProvider, $$sanitizeUriProvider) {
var newRe = /javascript:/,
returnVal;
expect($compileProvider.aHrefSanitizationWhitelist()).toBe($$sanitizeUriProvider.aHrefSanitizationWhitelist());
returnVal = $compileProvider.aHrefSanitizationWhitelist(newRe);
expect(returnVal).toBe($compileProvider);
expect($$sanitizeUriProvider.aHrefSanitizationWhitelist()).toBe(newRe);
expect($compileProvider.aHrefSanitizationWhitelist()).toBe(newRe);
});
inject(function() {
// needed to the module definition above is run...
});
});
it('should use $$sanitizeUri', function() {
var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri');
module(function($provide) {
$provide.value('$$sanitizeUri', $$sanitizeUri);
});
inject(function($compile, $rootScope) {
element = $compile('<a href="{{testUrl}}"></a>')($rootScope);
$rootScope.testUrl = 'someUrl';
$$sanitizeUri.and.returnValue('someSanitizedUrl');
$rootScope.$apply();
expect(element.attr('href')).toBe('someSanitizedUrl');
expect($$sanitizeUri).toHaveBeenCalledWith($rootScope.testUrl, false);
});
});
it('should use $$sanitizeUri when declared via ng-href', function() {
var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri');
module(function($provide) {
$provide.value('$$sanitizeUri', $$sanitizeUri);
});
inject(function($compile, $rootScope) {
element = $compile('<a ng-href="{{testUrl}}"></a>')($rootScope);
$rootScope.testUrl = 'someUrl';
$$sanitizeUri.and.returnValue('someSanitizedUrl');
$rootScope.$apply();
expect(element.attr('href')).toBe('someSanitizedUrl');
expect($$sanitizeUri).toHaveBeenCalledWith($rootScope.testUrl, false);
});
});
it('should use $$sanitizeUri when working with svg and xlink:href', function() {
var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri');
module(function($provide) {
$provide.value('$$sanitizeUri', $$sanitizeUri);
});
inject(function($compile, $rootScope) {
element = $compile('<svg><a xlink:href="" ng-href="{{ testUrl }}"></a></svg>')($rootScope);
$rootScope.testUrl = 'evilUrl';
$$sanitizeUri.and.returnValue('someSanitizedUrl');
$rootScope.$apply();
expect(element.find('a').prop('href').baseVal).toBe('someSanitizedUrl');
expect($$sanitizeUri).toHaveBeenCalledWith($rootScope.testUrl, false);
});
});
it('should use $$sanitizeUri when working with svg and xlink:href', function() {
var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri');
module(function($provide) {
$provide.value('$$sanitizeUri', $$sanitizeUri);
});
inject(function($compile, $rootScope) {
element = $compile('<svg><a xlink:href="" ng-href="{{ testUrl }}"></a></svg>')($rootScope);
$rootScope.testUrl = 'evilUrl';
$$sanitizeUri.and.returnValue('someSanitizedUrl');
$rootScope.$apply();
expect(element.find('a').prop('href').baseVal).toBe('someSanitizedUrl');
expect($$sanitizeUri).toHaveBeenCalledWith($rootScope.testUrl, false);
});
});
});
describe('interpolation on HTML DOM event handler attributes onclick, onXYZ, formaction', function() {
it('should disallow interpolation on onclick', inject(function($compile, $rootScope) {
// All interpolations are disallowed.
$rootScope.onClickJs = '';
expect(function() {
$compile('<button onclick="{{onClickJs}}"></script>');
}).toThrowMinErr(
'$compile', 'nodomevents', 'Interpolations for HTML DOM event attributes are disallowed. ' +
'Please use the ng- versions (such as ng-click instead of onclick) instead.');
expect(function() {
$compile('<button ONCLICK="{{onClickJs}}"></script>');
}).toThrowMinErr(
'$compile', 'nodomevents', 'Interpolations for HTML DOM event attributes are disallowed. ' +
'Please use the ng- versions (such as ng-click instead of onclick) instead.');
expect(function() {
$compile('<button ng-attr-onclick="{{onClickJs}}"></script>');
}).toThrowMinErr(
'$compile', 'nodomevents', 'Interpolations for HTML DOM event attributes are disallowed. ' +
'Please use the ng- versions (such as ng-click instead of onclick) instead.');
}));
it('should pass through arbitrary values on onXYZ event attributes that contain a hyphen', inject(function($compile, $rootScope) {
element = $compile('<button on-click="{{onClickJs}}"></script>')($rootScope);
$rootScope.onClickJs = 'javascript:doSomething()';
$rootScope.$apply();
expect(element.attr('on-click')).toEqual('javascript:doSomething()');
}));
it('should pass through arbitrary values on "on" and "data-on" attributes', inject(function($compile, $rootScope) {
element = $compile('<button data-on="{{dataOnVar}}"></script>')($rootScope);
$rootScope.dataOnVar = 'data-on text';
$rootScope.$apply();
expect(element.attr('data-on')).toEqual('data-on text');
element = $compile('<button on="{{onVar}}"></script>')($rootScope);
$rootScope.onVar = 'on text';
$rootScope.$apply();
expect(element.attr('on')).toEqual('on text');
}));
});
describe('iframe[src]', function() {
it('should pass through src attributes for the same domain', inject(function($compile, $rootScope, $sce) {
element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope);
$rootScope.testUrl = 'different_page';
$rootScope.$apply();
expect(element.attr('src')).toEqual('different_page');
}));
it('should clear out src attributes for a different domain', inject(function($compile, $rootScope, $sce) {
element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope);
$rootScope.testUrl = 'http://a.different.domain.example.com';
expect(function() { $rootScope.$apply(); }).toThrowMinErr(
'$interpolate', 'interr', 'Can\'t interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked ' +
'loading resource from url not allowed by $sceDelegate policy. URL: ' +
'http://a.different.domain.example.com');
}));
it('should clear out JS src attributes', inject(function($compile, $rootScope, $sce) {
element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope);
$rootScope.testUrl = 'javascript:alert(1);';
expect(function() { $rootScope.$apply(); }).toThrowMinErr(
'$interpolate', 'interr', 'Can\'t interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked ' +
'loading resource from url not allowed by $sceDelegate policy. URL: ' +
'javascript:alert(1);');
}));
it('should clear out non-resource_url src attributes', inject(function($compile, $rootScope, $sce) {
element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope);
$rootScope.testUrl = $sce.trustAsUrl('javascript:doTrustedStuff()');
expect($rootScope.$apply).toThrowMinErr(
'$interpolate', 'interr', 'Can\'t interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked ' +
'loading resource from url not allowed by $sceDelegate policy. URL: javascript:doTrustedStuff()');
}));
it('should pass through $sce.trustAs() values in src attributes', inject(function($compile, $rootScope, $sce) {
element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope);
$rootScope.testUrl = $sce.trustAsResourceUrl('javascript:doTrustedStuff()');
$rootScope.$apply();
expect(element.attr('src')).toEqual('javascript:doTrustedStuff()');
}));
});
describe('form[action]', function() {
it('should pass through action attribute for the same domain', inject(function($compile, $rootScope, $sce) {
element = $compile('<form action="{{testUrl}}"></form>')($rootScope);
$rootScope.testUrl = 'different_page';
$rootScope.$apply();
expect(element.attr('action')).toEqual('different_page');
}));
it('should clear out action attribute for a different domain', inject(function($compile, $rootScope, $sce) {
element = $compile('<form action="{{testUrl}}"></form>')($rootScope);
$rootScope.testUrl = 'http://a.different.domain.example.com';
expect(function() { $rootScope.$apply(); }).toThrowMinErr(
'$interpolate', 'interr', 'Can\'t interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked ' +
'loading resource from url not allowed by $sceDelegate policy. URL: ' +
'http://a.different.domain.example.com');
}));
it('should clear out JS action attribute', inject(function($compile, $rootScope, $sce) {
element = $compile('<form action="{{testUrl}}"></form>')($rootScope);
$rootScope.testUrl = 'javascript:alert(1);';
expect(function() { $rootScope.$apply(); }).toThrowMinErr(
'$interpolate', 'interr', 'Can\'t interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked ' +
'loading resource from url not allowed by $sceDelegate policy. URL: ' +
'javascript:alert(1);');
}));
it('should clear out non-resource_url action attribute', inject(function($compile, $rootScope, $sce) {
element = $compile('<form action="{{testUrl}}"></form>')($rootScope);
$rootScope.testUrl = $sce.trustAsUrl('javascript:doTrustedStuff()');
expect($rootScope.$apply).toThrowMinErr(
'$interpolate', 'interr', 'Can\'t interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked ' +
'loading resource from url not allowed by $sceDelegate policy. URL: javascript:doTrustedStuff()');
}));
it('should pass through $sce.trustAs() values in action attribute', inject(function($compile, $rootScope, $sce) {
element = $compile('<form action="{{testUrl}}"></form>')($rootScope);
$rootScope.testUrl = $sce.trustAsResourceUrl('javascript:doTrustedStuff()');
$rootScope.$apply();
expect(element.attr('action')).toEqual('javascript:doTrustedStuff()');
}));
});
describe('link[href]', function() {
it('should reject invalid RESOURCE_URLs', inject(function($compile, $rootScope) {
element = $compile('<link href="{{testUrl}}" rel="stylesheet" />')($rootScope);
$rootScope.testUrl = 'https://evil.example.org/css.css';
expect(function() { $rootScope.$apply(); }).toThrowMinErr(
'$interpolate', 'interr', 'Can\'t interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked ' +
'loading resource from url not allowed by $sceDelegate policy. URL: ' +
'https://evil.example.org/css.css');
}));
it('should accept valid RESOURCE_URLs', inject(function($compile, $rootScope, $sce) {
element = $compile('<link href="{{testUrl}}" rel="stylesheet" />')($rootScope);
$rootScope.testUrl = './css1.css';
$rootScope.$apply();
expect(element.attr('href')).toContain('css1.css');
$rootScope.testUrl = $sce.trustAsResourceUrl('https://elsewhere.example.org/css2.css');
$rootScope.$apply();
expect(element.attr('href')).toContain('https://elsewhere.example.org/css2.css');
}));
it('should accept valid constants', inject(function($compile, $rootScope) {
element = $compile('<link href="https://elsewhere.example.org/css2.css" rel="stylesheet" />')($rootScope);
$rootScope.$apply();
expect(element.attr('href')).toContain('https://elsewhere.example.org/css2.css');
}));
});
// Support: IE 9-10 only
// IEs <11 don't support srcdoc
if (!msie || msie === 11) {
describe('iframe[srcdoc]', function() {
it('should NOT set iframe contents for untrusted values', inject(function($compile, $rootScope, $sce) {
element = $compile('<iframe srcdoc="{{html}}"></iframe>')($rootScope);
$rootScope.html = '<div onclick="">hello</div>';
expect(function() { $rootScope.$digest(); }).toThrowMinErr('$interpolate', 'interr', new RegExp(
/Can't interpolate: {{html}}\n/.source +
/[^[]*\[\$sce:unsafe\] Attempting to use an unsafe value in a safe context./.source));
}));
it('should NOT set html for wrongly typed values', inject(function($rootScope, $compile, $sce) {
element = $compile('<iframe srcdoc="{{html}}"></iframe>')($rootScope);
$rootScope.html = $sce.trustAsCss('<div onclick="">hello</div>');
expect(function() { $rootScope.$digest(); }).toThrowMinErr('$interpolate', 'interr', new RegExp(
/Can't interpolate: \{\{html}}\n/.source +
/[^[]*\[\$sce:unsafe\] Attempting to use an unsafe value in a safe context./.source));
}));
it('should set html for trusted values', inject(function($rootScope, $compile, $sce) {
element = $compile('<iframe srcdoc="{{html}}"></iframe>')($rootScope);
$rootScope.html = $sce.trustAsHtml('<div onclick="">hello</div>');
$rootScope.$digest();
expect(angular.lowercase(element.attr('srcdoc'))).toEqual('<div onclick="">hello</div>');
}));
});
}
describe('ngAttr* attribute binding', function() {
it('should bind after digest but not before', inject(function() {
$rootScope.name = 'Misko';
element = $compile('<span ng-attr-test="{{name}}"></span>')($rootScope);
expect(element.attr('test')).toBeUndefined();
$rootScope.$digest();
expect(element.attr('test')).toBe('Misko');
}));
it('should bind after digest but not before when after overridden attribute', inject(function() {
$rootScope.name = 'Misko';
element = $compile('<span test="123" ng-attr-test="{{name}}"></span>')($rootScope);
expect(element.attr('test')).toBe('123');
$rootScope.$digest();
expect(element.attr('test')).toBe('Misko');
}));
it('should bind after digest but not before when before overridden attribute', inject(function() {
$rootScope.name = 'Misko';
element = $compile('<span ng-attr-test="{{name}}" test="123"></span>')($rootScope);
expect(element.attr('test')).toBe('123');
$rootScope.$digest();
expect(element.attr('test')).toBe('Misko');
}));
it('should set the attribute (after digest) even if there is no interpolation', inject(function() {
element = $compile('<span ng-attr-test="foo"></span>')($rootScope);
expect(element.attr('test')).toBeUndefined();
$rootScope.$digest();
expect(element.attr('test')).toBe('foo');
}));
it('should remove attribute if any bindings are undefined', inject(function() {
element = $compile('<span ng-attr-test="{{name}}{{emphasis}}"></span>')($rootScope);
$rootScope.$digest();
expect(element.attr('test')).toBeUndefined();
$rootScope.name = 'caitp';
$rootScope.$digest();
expect(element.attr('test')).toBeUndefined();
$rootScope.emphasis = '!!!';
$rootScope.$digest();
expect(element.attr('test')).toBe('caitp!!!');
}));
describe('in directive', function() {
var log;
beforeEach(module(function() {
directive('syncTest', function(log) {
return {
link: {
pre: function(s, e, attr) { log(attr.test); },
post: function(s, e, attr) { log(attr.test); }
}
};
});
directive('asyncTest', function(log) {
return {
templateUrl: 'async.html',
link: {
pre: function(s, e, attr) { log(attr.test); },
post: function(s, e, attr) { log(attr.test); }
}
};
});
}));
beforeEach(inject(function($templateCache, _log_) {
log = _log_;
$templateCache.put('async.html', '<h1>Test</h1>');
}));
it('should provide post-digest value in synchronous directive link functions when after overridden attribute',
function() {
$rootScope.test = 'TEST';
element = $compile('<div sync-test test="123" ng-attr-test="{{test}}"></div>')($rootScope);
expect(element.attr('test')).toBe('123');
expect(log.toArray()).toEqual(['TEST', 'TEST']);
}
);
it('should provide post-digest value in synchronous directive link functions when before overridden attribute',
function() {
$rootScope.test = 'TEST';
element = $compile('<div sync-test ng-attr-test="{{test}}" test="123"></div>')($rootScope);
expect(element.attr('test')).toBe('123');
expect(log.toArray()).toEqual(['TEST', 'TEST']);
}
);
it('should provide post-digest value in asynchronous directive link functions when after overridden attribute',
function() {
$rootScope.test = 'TEST';
element = $compile('<div async-test test="123" ng-attr-test="{{test}}"></div>')($rootScope);
expect(element.attr('test')).toBe('123');
$rootScope.$digest();
expect(log.toArray()).toEqual(['TEST', 'TEST']);
}
);
it('should provide post-digest value in asynchronous directive link functions when before overridden attribute',
function() {
$rootScope.test = 'TEST';
element = $compile('<div async-test ng-attr-test="{{test}}" test="123"></div>')($rootScope);
expect(element.attr('test')).toBe('123');
$rootScope.$digest();
expect(log.toArray()).toEqual(['TEST', 'TEST']);
}
);
});
it('should work with different prefixes', inject(function() {
$rootScope.name = 'Misko';
element = $compile('<span ng:attr:test="{{name}}" ng-Attr-test2="{{name}}" ng_Attr_test3="{{name}}"></span>')($rootScope);
expect(element.attr('test')).toBeUndefined();
expect(element.attr('test2')).toBeUndefined();
expect(element.attr('test3')).toBeUndefined();
$rootScope.$digest();
expect(element.attr('test')).toBe('Misko');
expect(element.attr('test2')).toBe('Misko');
expect(element.attr('test3')).toBe('Misko');
}));
it('should work with the "href" attribute', inject(function() {
$rootScope.value = 'test';
element = $compile('<a ng-attr-href="test/{{value}}"></a>')($rootScope);
$rootScope.$digest();
expect(element.attr('href')).toBe('test/test');
}));
it('should work if they are prefixed with x- or data- and different prefixes', inject(function() {
$rootScope.name = 'Misko';
element = $compile('<span data-ng-attr-test2="{{name}}" x-ng-attr-test3="{{name}}" data-ng:attr-test4="{{name}}" ' +
'x_ng-attr-test5="{{name}}" data:ng-attr-test6="{{name}}"></span>')($rootScope);
expect(element.attr('test2')).toBeUndefined();
expect(element.attr('test3')).toBeUndefined();
expect(element.attr('test4')).toBeUndefined();
expect(element.attr('test5')).toBeUndefined();
expect(element.attr('test6')).toBeUndefined();
$rootScope.$digest();
expect(element.attr('test2')).toBe('Misko');
expect(element.attr('test3')).toBe('Misko');
expect(element.attr('test4')).toBe('Misko');
expect(element.attr('test5')).toBe('Misko');
expect(element.attr('test6')).toBe('Misko');
}));
describe('when an attribute has a dash-separated name', function() {
it('should work with different prefixes', inject(function() {
$rootScope.name = 'JamieMason';
element = $compile('<span ng:attr:dash-test="{{name}}" ng-Attr-dash-test2="{{name}}" ng_Attr_dash-test3="{{name}}"></span>')($rootScope);
expect(element.attr('dash-test')).toBeUndefined();
expect(element.attr('dash-test2')).toBeUndefined();
expect(element.attr('dash-test3')).toBeUndefined();
$rootScope.$digest();
expect(element.attr('dash-test')).toBe('JamieMason');
expect(element.attr('dash-test2')).toBe('JamieMason');
expect(element.attr('dash-test3')).toBe('JamieMason');
}));
it('should work if they are prefixed with x- or data-', inject(function() {
$rootScope.name = 'JamieMason';
element = $compile('<span data-ng-attr-dash-test2="{{name}}" x-ng-attr-dash-test3="{{name}}" data-ng:attr-dash-test4="{{name}}"></span>')($rootScope);
expect(element.attr('dash-test2')).toBeUndefined();
expect(element.attr('dash-test3')).toBeUndefined();
expect(element.attr('dash-test4')).toBeUndefined();
$rootScope.$digest();
expect(element.attr('dash-test2')).toBe('JamieMason');
expect(element.attr('dash-test3')).toBe('JamieMason');
expect(element.attr('dash-test4')).toBe('JamieMason');
}));
it('should keep attributes ending with -start single-element directives', function() {
module(function($compileProvider) {
$compileProvider.directive('dashStarter', function(log) {
return {
link: function(scope, element, attrs) {
log(attrs.onDashStart);
}
};
});
});
inject(function($compile, $rootScope, log) {
$compile('<span data-dash-starter data-on-dash-start="starter"></span>')($rootScope);
$rootScope.$digest();
expect(log).toEqual('starter');
});
});
it('should keep attributes ending with -end single-element directives', function() {
module(function($compileProvider) {
$compileProvider.directive('dashEnder', function(log) {
return {
link: function(scope, element, attrs) {
log(attrs.onDashEnd);
}
};
});
});
inject(function($compile, $rootScope, log) {
$compile('<span data-dash-ender data-on-dash-end="ender"></span>')($rootScope);
$rootScope.$digest();
expect(log).toEqual('ender');
});
});
});
});
describe('when an attribute has an underscore-separated name', function() {
it('should work with different prefixes', inject(function($compile, $rootScope) {
$rootScope.dimensions = '0 0 0 0';
element = $compile('<svg ng:attr:view_box="{{dimensions}}"></svg>')($rootScope);
expect(element.attr('viewBox')).toBeUndefined();
$rootScope.$digest();
expect(element.attr('viewBox')).toBe('0 0 0 0');
}));
it('should work if they are prefixed with x- or data-', inject(function($compile, $rootScope) {
$rootScope.dimensions = '0 0 0 0';
$rootScope.number = 0.42;
$rootScope.scale = 1;
element = $compile('<svg data-ng-attr-view_box="{{dimensions}}">' +
'<filter x-ng-attr-filter_units="{{number}}">' +
'<feDiffuseLighting data-ng:attr_surface_scale="{{scale}}">' +
'</feDiffuseLighting>' +
'<feSpecularLighting x-ng:attr_surface_scale="{{scale}}">' +
'</feSpecularLighting></filter></svg>')($rootScope);
expect(element.attr('viewBox')).toBeUndefined();
$rootScope.$digest();
expect(element.attr('viewBox')).toBe('0 0 0 0');
expect(element.find('filter').attr('filterUnits')).toBe('0.42');
expect(element.find('feDiffuseLighting').attr('surfaceScale')).toBe('1');
expect(element.find('feSpecularLighting').attr('surfaceScale')).toBe('1');
}));
});
describe('multi-element directive', function() {
it('should group on link function', inject(function($compile, $rootScope) {
$rootScope.show = false;
element = $compile(
'<div>' +
'<span ng-show-start="show"></span>' +
'<span ng-show-end></span>' +
'</div>')($rootScope);
$rootScope.$digest();
var spans = element.find('span');
expect(spans.eq(0)).toBeHidden();
expect(spans.eq(1)).toBeHidden();
}));
it('should group on compile function', inject(function($compile, $rootScope) {
$rootScope.show = false;
element = $compile(
'<div>' +
'<span ng-repeat-start="i in [1,2]">{{i}}A</span>' +
'<span ng-repeat-end>{{i}}B;</span>' +
'</div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('1A1B;2A2B;');
}));
it('should support grouping over text nodes', inject(function($compile, $rootScope) {
$rootScope.show = false;
element = $compile(
'<div>' +
'<span ng-repeat-start="i in [1,2]">{{i}}A</span>' +
':' + // Important: proves that we can iterate over non-elements
'<span ng-repeat-end>{{i}}B;</span>' +
'</div>')($rootScope);
$rootScope.$digest();
expect(element.text()).toEqual('1A:1B;2A:2B;');
}));
it('should group on $root compile function', inject(function($compile, $rootScope) {
$rootScope.show = false;
element = $compile(
'<div></div>' +
'<span ng-repeat-start="i in [1,2]">{{i}}A</span>' +
'<span ng-repeat-end>{{i}}B;</span>' +
'<div></div>')($rootScope);
$rootScope.$digest();
element = jqLite(element[0].parentNode.childNodes); // reset because repeater is top level.
expect(element.text()).toEqual('1A1B;2A2B;');
}));
it('should group on nested groups', function() {
module(function($compileProvider) {
$compileProvider.directive('ngMultiBind', valueFn({
multiElement: true,
link: function(scope, element, attr) {
element.text(scope.$eval(attr.ngMultiBind));
}
}));
});
inject(function($compile, $rootScope) {
$rootScope.show = false;
element = $compile(
'<div></div>' +
'<div ng-repeat-start="i in [1,2]">{{i}}A</div>' +
'<span ng-multi-bind-start="\'.\'"></span>' +
'<span ng-multi-bind-end></span>' +
'<div ng-repeat-end>{{i}}B;</div>' +
'<div></div>')($rootScope);
$rootScope.$digest();
element = jqLite(element[0].parentNode.childNodes); // reset because repeater is top level.
expect(element.text()).toEqual('1A..1B;2A..2B;');
});
});
it('should group on nested groups of same directive', inject(function($compile, $rootScope) {
$rootScope.show = false;
element = $compile(
'<div></div>' +
'<div ng-repeat-start="i in [1,2]">{{i}}(</div>' +
'<span ng-repeat-start="j in [2,3]">{{j}}-</span>' +
'<span ng-repeat-end>{{j}}</span>' +
'<div ng-repeat-end>){{i}};</div>' +
'<div></div>')($rootScope);
$rootScope.$digest();
element = jqLite(element[0].parentNode.childNodes); // reset because repeater is top level.
expect(element.text()).toEqual('1(2-23-3)1;2(2-23-3)2;');
}));
it('should set up and destroy the transclusion scopes correctly',
inject(function($compile, $rootScope) {
element = $compile(
'<div>' +
'<div ng-if-start="val0"><span ng-if="val1"></span></div>' +
'<div ng-if-end><span ng-if="val2"></span></div>' +
'</div>'
)($rootScope);
$rootScope.$apply('val0 = true; val1 = true; val2 = true');
// At this point we should have something like:
//
// <div class="ng-scope">
//
// <!-- ngIf: val0 -->
//
// <div ng-if-start="val0" class="ng-scope">
// <!-- ngIf: val1 -->
// <span ng-if="val1" class="ng-scope"></span>
// <!-- end ngIf: val1 -->
// </div>
//
// <div ng-if-end="" class="ng-scope">
// <!-- ngIf: val2 -->
// <span ng-if="val2" class="ng-scope"></span>
// <!-- end ngIf: val2 -->
// </div>
//
// <!-- end ngIf: val0 -->
// </div>
var ngIfStartScope = element.find('div').eq(0).scope();
var ngIfEndScope = element.find('div').eq(1).scope();
expect(ngIfStartScope.$id).toEqual(ngIfEndScope.$id);
var ngIf1Scope = element.find('span').eq(0).scope();
var ngIf2Scope = element.find('span').eq(1).scope();
expect(ngIf1Scope.$id).not.toEqual(ngIf2Scope.$id);
expect(ngIf1Scope.$parent.$id).toEqual(ngIf2Scope.$parent.$id);
$rootScope.$apply('val1 = false');
// Now we should have something like:
//
// <div class="ng-scope">
// <!-- ngIf: val0 -->
// <div ng-if-start="val0" class="ng-scope">
// <!-- ngIf: val1 -->
// </div>
// <div ng-if-end="" class="ng-scope">
// <!-- ngIf: val2 -->
// <span ng-if="val2" class="ng-scope"></span>
// <!-- end ngIf: val2 -->
// </div>
// <!-- end ngIf: val0 -->
// </div>
expect(ngIfStartScope.$$destroyed).not.toEqual(true);
expect(ngIf1Scope.$$destroyed).toEqual(true);
expect(ngIf2Scope.$$destroyed).not.toEqual(true);
$rootScope.$apply('val0 = false');
// Now we should have something like:
//
// <div class="ng-scope">
// <!-- ngIf: val0 -->
// </div>
expect(ngIfStartScope.$$destroyed).toEqual(true);
expect(ngIf1Scope.$$destroyed).toEqual(true);
expect(ngIf2Scope.$$destroyed).toEqual(true);
}));
it('should set up and destroy the transclusion scopes correctly',
inject(function($compile, $rootScope) {
element = $compile(
'<div>' +
'<div ng-repeat-start="val in val0" ng-if="val1"></div>' +
'<div ng-repeat-end ng-if="val2"></div>' +
'</div>'
)($rootScope);
// To begin with there is (almost) nothing:
// <div class="ng-scope">
// <!-- ngRepeat: val in val0 -->
// </div>
expect(element.scope().$id).toEqual($rootScope.$id);
// Now we create all the elements
$rootScope.$apply('val0 = [1]; val1 = true; val2 = true');
// At this point we have:
//
// <div class="ng-scope">
//
// <!-- ngRepeat: val in val0 -->
// <!-- ngIf: val1 -->
// <div ng-repeat-start="val in val0" class="ng-scope">
// </div>
// <!-- end ngIf: val1 -->
//
// <!-- ngIf: val2 -->
// <div ng-repeat-end="" class="ng-scope">
// </div>
// <!-- end ngIf: val2 -->
// <!-- end ngRepeat: val in val0 -->
// </div>
var ngIf1Scope = element.find('div').eq(0).scope();
var ngIf2Scope = element.find('div').eq(1).scope();
var ngRepeatScope = ngIf1Scope.$parent;
expect(ngIf1Scope.$id).not.toEqual(ngIf2Scope.$id);
expect(ngIf1Scope.$parent.$id).toEqual(ngRepeatScope.$id);
expect(ngIf2Scope.$parent.$id).toEqual(ngRepeatScope.$id);
// What is happening here??
// We seem to have a repeater scope which doesn't actually match to any element
expect(ngRepeatScope.$parent.$id).toEqual($rootScope.$id);
// Now remove the first ngIf element from the first item in the repeater
$rootScope.$apply('val1 = false');
// At this point we should have:
//
// <div class="ng-scope">
// <!-- ngRepeat: val in val0 -->
//
// <!-- ngIf: val1 -->
//
// <!-- ngIf: val2 -->
// <div ng-repeat-end="" ng-if="val2" class="ng-scope"></div>
// <!-- end ngIf: val2 -->
//
// <!-- end ngRepeat: val in val0 -->
// </div>
//
expect(ngRepeatScope.$$destroyed).toEqual(false);
expect(ngIf1Scope.$$destroyed).toEqual(true);
expect(ngIf2Scope.$$destroyed).toEqual(false);
// Now remove the second ngIf element from the first item in the repeater
$rootScope.$apply('val2 = false');
// We are mostly back to where we started
//
// <div class="ng-scope">
// <!-- ngRepeat: val in val0 -->
// <!-- ngIf: val1 -->
// <!-- ngIf: val2 -->
// <!-- end ngRepeat: val in val0 -->
// </div>
expect(ngRepeatScope.$$destroyed).toEqual(false);
expect(ngIf1Scope.$$destroyed).toEqual(true);
expect(ngIf2Scope.$$destroyed).toEqual(true);
// Finally remove the repeat items
$rootScope.$apply('val0 = []');
// Somehow this ngRepeat scope knows how to destroy itself...
expect(ngRepeatScope.$$destroyed).toEqual(true);
expect(ngIf1Scope.$$destroyed).toEqual(true);
expect(ngIf2Scope.$$destroyed).toEqual(true);
}));
it('should throw error if unterminated', function() {
module(function($compileProvider) {
$compileProvider.directive('foo', function() {
return {
multiElement: true
};
});
});
inject(function($compile, $rootScope) {
expect(function() {
element = $compile(
'<div>' +
'<span foo-start></span>' +
'</div>');
}).toThrowMinErr('$compile', 'uterdir', 'Unterminated attribute, found \'foo-start\' but no matching \'foo-end\' found.');
});
});
it('should correctly collect ranges on multiple directives on a single element', function() {
module(function($compileProvider) {
$compileProvider.directive('emptyDirective', function() {
return {
multiElement: true,
link: function(scope, element) {
element.data('x', 'abc');
}
};
});
$compileProvider.directive('rangeDirective', function() {
return {
multiElement: true,
link: function(scope) {
scope.x = 'X';
scope.y = 'Y';
}
};
});
});
inject(function($compile, $rootScope) {
element = $compile(
'<div>' +
'<div range-directive-start empty-directive>{{x}}</div>' +
'<div range-directive-end>{{y}}</div>' +
'</div>'
)($rootScope);
$rootScope.$digest();
expect(element.text()).toBe('XY');
expect(angular.element(element[0].firstChild).data('x')).toBe('abc');
});
});
it('should throw error if unterminated (containing termination as a child)', function() {
module(function($compileProvider) {
$compileProvider.directive('foo', function() {
return {
multiElement: true
};
});
});
inject(function($compile) {
expect(function() {
element = $compile(
'<div>' +
'<span foo-start><span foo-end></span></span>' +
'</div>');
}).toThrowMinErr('$compile', 'uterdir', 'Unterminated attribute, found \'foo-start\' but no matching \'foo-end\' found.');
});
});
it('should support data- and x- prefix', inject(function($compile, $rootScope) {
$rootScope.show = false;
element = $compile(
'<div>' +
'<span data-ng-show-start="show"></span>' +
'<span data-ng-show-end></span>' +
'<span x-ng-show-start="show"></span>' +
'<span x-ng-show-end></span>' +
'</div>')($rootScope);
$rootScope.$digest();
var spans = element.find('span');
expect(spans.eq(0)).toBeHidden();
expect(spans.eq(1)).toBeHidden();
expect(spans.eq(2)).toBeHidden();
expect(spans.eq(3)).toBeHidden();
}));
});
describe('$animate animation hooks', function() {
beforeEach(module('ngAnimateMock'));
it('should automatically fire the addClass and removeClass animation hooks',
inject(function($compile, $animate, $rootScope) {
var data, element = jqLite('<div class="{{val1}} {{val2}} fire"></div>');
$compile(element)($rootScope);
$rootScope.$digest();
expect(element.hasClass('fire')).toBe(true);
$rootScope.val1 = 'ice';
$rootScope.val2 = 'rice';
$rootScope.$digest();
data = $animate.queue.shift();
expect(data.event).toBe('addClass');
expect(data.args[1]).toBe('ice rice');
expect(element.hasClass('ice')).toBe(true);
expect(element.hasClass('rice')).toBe(true);
expect(element.hasClass('fire')).toBe(true);
$rootScope.val2 = 'dice';
$rootScope.$digest();
data = $animate.queue.shift();
expect(data.event).toBe('addClass');
expect(data.args[1]).toBe('dice');
data = $animate.queue.shift();
expect(data.event).toBe('removeClass');
expect(data.args[1]).toBe('rice');
expect(element.hasClass('ice')).toBe(true);
expect(element.hasClass('dice')).toBe(true);
expect(element.hasClass('fire')).toBe(true);
$rootScope.val1 = '';
$rootScope.val2 = '';
$rootScope.$digest();
data = $animate.queue.shift();
expect(data.event).toBe('removeClass');
expect(data.args[1]).toBe('ice dice');
expect(element.hasClass('ice')).toBe(false);
expect(element.hasClass('dice')).toBe(false);
expect(element.hasClass('fire')).toBe(true);
}));
});
describe('element replacement', function() {
it('should broadcast $destroy only on removed elements, not replaced', function() {
var linkCalls = [];
var destroyCalls = [];
module(function($compileProvider) {
$compileProvider.directive('replace', function() {
return {
multiElement: true,
replace: true,
templateUrl: 'template123'
};
});
$compileProvider.directive('foo', function() {
return {
priority: 1, // before the replace directive
link: function($scope, $element, $attrs) {
linkCalls.push($attrs.foo);
$element.on('$destroy', function() {
destroyCalls.push($attrs.foo);
});
}
};
});
});
inject(function($compile, $templateCache, $rootScope) {
$templateCache.put('template123', '<p></p>');
$compile(
'<div replace-start foo="1"><span foo="1.1"></span></div>' +
'<div foo="2"><span foo="2.1"></span></div>' +
'<div replace-end foo="3"><span foo="3.1"></span></div>'
)($rootScope);
expect(linkCalls).toEqual(['2', '3']);
expect(destroyCalls).toEqual([]);
$rootScope.$apply();
expect(linkCalls).toEqual(['2', '3', '1']);
expect(destroyCalls).toEqual(['2', '3']);
});
});
function getAll($root) {
// check for .querySelectorAll to support comment nodes
return [$root[0]].concat($root[0].querySelectorAll ? sliceArgs($root[0].querySelectorAll('*')) : []);
}
function testCompileLinkDataCleanup(template) {
inject(function($compile, $rootScope) {
var toCompile = jqLite(template);
var preCompiledChildren = getAll(toCompile);
forEach(preCompiledChildren, function(element, i) {
jqLite.data(element, 'foo', 'template#' + i);
});
var linkedElements = $compile(toCompile)($rootScope);
$rootScope.$apply();
linkedElements.remove();
forEach(preCompiledChildren, function(element, i) {
expect(jqLite.hasData(element)).toBe(false, 'template#' + i);
});
forEach(getAll(linkedElements), function(element, i) {
expect(jqLite.hasData(element)).toBe(false, 'linked#' + i);
});
});
}
it('should clean data of element-transcluded link-cloned elements', function() {
testCompileLinkDataCleanup('<div><div ng-repeat-start="i in [1,2]"><span></span></div><div ng-repeat-end></div></div>');
});
it('should clean data of element-transcluded elements', function() {
testCompileLinkDataCleanup('<div ng-if-start="false"><span><span/></div><span></span><div ng-if-end><span></span></div>');
});
function testReplaceElementCleanup(dirOptions) {
var template = '<div></div>';
module(function($compileProvider) {
$compileProvider.directive('theDir', function() {
return {
multiElement: true,
replace: dirOptions.replace,
transclude: dirOptions.transclude,
template: dirOptions.asyncTemplate ? undefined : template,
templateUrl: dirOptions.asyncTemplate ? 'the-dir-template-url' : undefined
};
});
});
inject(function($templateCache, $compile, $rootScope) {
$templateCache.put('the-dir-template-url', template);
testCompileLinkDataCleanup(
'<div>' +
'<div the-dir-start><span></span></div>' +
'<div><span></span><span></span></div>' +
'<div the-dir-end><span></span></div>' +
'</div>'
);
});
}
it('should clean data of elements removed for directive template', function() {
testReplaceElementCleanup({});
});
it('should clean data of elements removed for directive templateUrl', function() {
testReplaceElementCleanup({asyncTemplate: true});
});
it('should clean data of elements transcluded into directive template', function() {
testReplaceElementCleanup({transclude: true});
});
it('should clean data of elements transcluded into directive templateUrl', function() {
testReplaceElementCleanup({transclude: true, asyncTemplate: true});
});
it('should clean data of elements replaced with directive template', function() {
testReplaceElementCleanup({replace: true});
});
it('should clean data of elements replaced with directive templateUrl', function() {
testReplaceElementCleanup({replace: true, asyncTemplate: true});
});
});
describe('component helper', function() {
it('should return the module', function() {
var myModule = angular.module('my', []);
expect(myModule.component('myComponent', {})).toBe(myModule);
});
it('should register a directive', function() {
angular.module('my', []).component('myComponent', {
template: '<div>SUCCESS</div>',
controller: function(log) {
log('OK');
}
});
module('my');
inject(function($compile, $rootScope, log) {
element = $compile('<my-component></my-component>')($rootScope);
expect(element.find('div').text()).toEqual('SUCCESS');
expect(log).toEqual('OK');
});
});
it('should register a directive via $compileProvider.component()', function() {
module(function($compileProvider) {
$compileProvider.component('myComponent', {
template: '<div>SUCCESS</div>',
controller: function(log) {
log('OK');
}
});
});
inject(function($compile, $rootScope, log) {
element = $compile('<my-component></my-component>')($rootScope);
expect(element.find('div').text()).toEqual('SUCCESS');
expect(log).toEqual('OK');
});
});
it('should add additional annotations to directive factory', function() {
var myModule = angular.module('my', []).component('myComponent', {
$canActivate: 'canActivate',
$routeConfig: 'routeConfig',
$customAnnotation: 'XXX'
});
expect(myModule._invokeQueue.pop().pop()[1]).toEqual(jasmine.objectContaining({
$canActivate: 'canActivate',
$routeConfig: 'routeConfig',
$customAnnotation: 'XXX'
}));
});
it('should expose additional annotations on the directive definition object', function() {
angular.module('my', []).component('myComponent', {
$canActivate: 'canActivate',
$routeConfig: 'routeConfig',
$customAnnotation: 'XXX'
});
module('my');
inject(function(myComponentDirective) {
expect(myComponentDirective[0]).toEqual(jasmine.objectContaining({
$canActivate: 'canActivate',
$routeConfig: 'routeConfig',
$customAnnotation: 'XXX'
}));
});
});
it('should support custom annotations if the controller is named', function() {
angular.module('my', []).component('myComponent', {
$customAnnotation: 'XXX',
controller: 'SomeNamedController'
});
module('my');
inject(function(myComponentDirective) {
expect(myComponentDirective[0]).toEqual(jasmine.objectContaining({
$customAnnotation: 'XXX'
}));
});
});
it('should provide a new empty controller if none is specified', function() {
angular.
module('my', []).
component('myComponent1', {$customAnnotation1: 'XXX'}).
component('myComponent2', {$customAnnotation2: 'YYY'});
module('my');
inject(function(myComponent1Directive, myComponent2Directive) {
var ctrl1 = myComponent1Directive[0].controller;
var ctrl2 = myComponent2Directive[0].controller;
expect(ctrl1).not.toBe(ctrl2);
expect(ctrl1.$customAnnotation1).toBe('XXX');
expect(ctrl1.$customAnnotation2).toBeUndefined();
expect(ctrl2.$customAnnotation1).toBeUndefined();
expect(ctrl2.$customAnnotation2).toBe('YYY');
});
});
it('should return ddo with reasonable defaults', function() {
angular.module('my', []).component('myComponent', {});
module('my');
inject(function(myComponentDirective) {
expect(myComponentDirective[0]).toEqual(jasmine.objectContaining({
controller: jasmine.any(Function),
controllerAs: '$ctrl',
template: '',
templateUrl: undefined,
transclude: undefined,
scope: {},
bindToController: {},
restrict: 'E'
}));
});
});
it('should return ddo with assigned options', function() {
function myCtrl() {}
angular.module('my', []).component('myComponent', {
controller: myCtrl,
controllerAs: 'ctrl',
template: 'abc',
templateUrl: 'def.html',
transclude: true,
bindings: {abc: '='}
});
module('my');
inject(function(myComponentDirective) {
expect(myComponentDirective[0]).toEqual(jasmine.objectContaining({
controller: myCtrl,
controllerAs: 'ctrl',
template: 'abc',
templateUrl: 'def.html',
transclude: true,
scope: {},
bindToController: {abc: '='},
restrict: 'E'
}));
});
});
it('should allow passing injectable functions as template/templateUrl', function() {
var log = '';
angular.module('my', []).component('myComponent', {
template: function($element, $attrs, myValue) {
log += 'template,' + $element + ',' + $attrs + ',' + myValue + '\n';
},
templateUrl: function($element, $attrs, myValue) {
log += 'templateUrl,' + $element + ',' + $attrs + ',' + myValue + '\n';
}
}).value('myValue', 'blah');
module('my');
inject(function(myComponentDirective) {
myComponentDirective[0].template('a', 'b');
myComponentDirective[0].templateUrl('c', 'd');
expect(log).toEqual('template,a,b,blah\ntemplateUrl,c,d,blah\n');
});
});
it('should allow passing injectable arrays as template/templateUrl', function() {
var log = '';
angular.module('my', []).component('myComponent', {
template: ['$element', '$attrs', 'myValue', function($element, $attrs, myValue) {
log += 'template,' + $element + ',' + $attrs + ',' + myValue + '\n';
}],
templateUrl: ['$element', '$attrs', 'myValue', function($element, $attrs, myValue) {
log += 'templateUrl,' + $element + ',' + $attrs + ',' + myValue + '\n';
}]
}).value('myValue', 'blah');
module('my');
inject(function(myComponentDirective) {
myComponentDirective[0].template('a', 'b');
myComponentDirective[0].templateUrl('c', 'd');
expect(log).toEqual('template,a,b,blah\ntemplateUrl,c,d,blah\n');
});
});
it('should allow passing transclude as object', function() {
angular.module('my', []).component('myComponent', {
transclude: {}
});
module('my');
inject(function(myComponentDirective) {
expect(myComponentDirective[0]).toEqual(jasmine.objectContaining({
transclude: {}
}));
});
});
it('should give ctrl as syntax priority over controllerAs', function() {
angular.module('my', []).component('myComponent', {
controller: 'MyCtrl as vm'
});
module('my');
inject(function(myComponentDirective) {
expect(myComponentDirective[0]).toEqual(jasmine.objectContaining({
controllerAs: 'vm'
}));
});
});
});
describe('$$createComment', function() {
it('should create empty comments if `debugInfoEnabled` is false', function() {
module(function($compileProvider) {
$compileProvider.debugInfoEnabled(false);
});
inject(function($compile) {
var comment = $compile.$$createComment('foo', 'bar');
expect(comment.data).toBe('');
});
});
it('should create descriptive comments if `debugInfoEnabled` is true', function() {
module(function($compileProvider) {
$compileProvider.debugInfoEnabled(true);
});
inject(function($compile) {
var comment = $compile.$$createComment('foo', 'bar');
expect(comment.data).toBe(' foo: bar ');
});
});
});
});
|
/*
* Copyright (c) 2016-present, Parse, LLC
* All rights reserved.
*
* This source code is licensed under the license found in the LICENSE file in
* the root directory of this source tree.
*/
import React from 'react';
import Button from 'components/Button/Button.react';
export const component = Button;
export const demos = [
{
name: 'Normal buttons',
render: () => (
<div>
<Button value='Click me' />
<Button color='green' value='Green' />
<Button color='red' value='Red' />
</div>
)
}, {
name: 'Primary vs secondary buttons',
render: () => (
<div>
<Button value='Primary action' primary={true} />
<Button value='Secondary action' />
</div>
)
}, {
name: 'Disabled button',
render: () => (
<div>
<Button value='Do not click' disabled={true} />
</div>
)
}, {
name: 'Progress button',
render: () => (
<div>
<Button value='Saving.' progress={true} primary={true} />
</div>
)
}, {
name: 'Red progress button',
render: () => (
<div>
<Button value='Saving.' color='red' progress={true} primary={true} />
</div>
)
}
];
|
/*!
* d3pie
* @author Ben Keen
* @version 0.1.9
* @date June 17th, 2015
* @repo http://github.com/benkeen/d3pie
*/
// UMD pattern from https://github.com/umdjs/umd/blob/master/returnExports.js
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module
define([], factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but only CommonJS-like environments that support module.exports,
// like Node
module.exports = factory();
} else {
// browser globals (root is window)
root.d3pie = factory(root);
}
}(this, function() {
var _scriptName = "d3pie";
var _version = "0.1.6";
// used to uniquely generate IDs and classes, ensuring no conflict between multiple pies on the same page
var _uniqueIDCounter = 0;
// this section includes all helper libs on the d3pie object. They're populated via grunt-template. Note: to keep
// the syntax highlighting from getting all messed up, I commented out each line. That REQUIRES each of the files
// to have an empty first line. Crumby, yes, but acceptable.
//<%=_defaultSettings%>
//<%=_validate%>
//<%=_helpers%>
//<%=_math%>
//<%=_labels%>
//<%=_segments%>
//<%=_text%>
//<%=_tooltips%>
// --------------------------------------------------------------------------------------------
// our constructor
var d3pie = function(element, options) {
// element can be an ID or DOM element
this.element = element;
if (typeof element === "string") {
var el = element.replace(/^#/, ""); // replace any jQuery-like ID hash char
this.element = document.getElementById(el);
}
var opts = {};
extend(true, opts, defaultSettings, options);
this.options = opts;
// if the user specified a custom CSS element prefix (ID, class), use it
if (this.options.misc.cssPrefix !== null) {
this.cssPrefix = this.options.misc.cssPrefix;
} else {
this.cssPrefix = "p" + _uniqueIDCounter + "_";
_uniqueIDCounter++;
}
// now run some validation on the user-defined info
if (!validate.initialCheck(this)) {
return;
}
// add a data-role to the DOM node to let anyone know that it contains a d3pie instance, and the d3pie version
d3.select(this.element).attr(_scriptName, _version);
// things that are done once
this.options.data.content = math.sortPieData(this);
if (this.options.data.smallSegmentGrouping.enabled) {
this.options.data.content = helpers.applySmallSegmentGrouping(this.options.data.content, this.options.data.smallSegmentGrouping);
}
this.options.colors = helpers.initSegmentColors(this);
this.totalSize = math.getTotalPieSize(this.options.data.content);
_init.call(this);
};
d3pie.prototype.recreate = function() {
// now run some validation on the user-defined info
if (!validate.initialCheck(this)) {
return;
}
this.options.data.content = math.sortPieData(this);
if (this.options.data.smallSegmentGrouping.enabled) {
this.options.data.content = helpers.applySmallSegmentGrouping(this.options.data.content, this.options.data.smallSegmentGrouping);
}
this.options.colors = helpers.initSegmentColors(this);
this.totalSize = math.getTotalPieSize(this.options.data.content);
_init.call(this);
};
d3pie.prototype.redraw = function() {
this.element.innerHTML = "";
_init.call(this);
};
d3pie.prototype.destroy = function() {
this.element.innerHTML = ""; // clear out the SVG
d3.select(this.element).attr(_scriptName, null); // remove the data attr
};
/**
* Returns all pertinent info about the current open info. Returns null if nothing's open, or if one is, an object of
* the following form:
* {
* element: DOM NODE,
* index: N,
* data: {}
* }
*/
d3pie.prototype.getOpenSegment = function() {
var segment = this.currentlyOpenSegment;
if (segment !== null && typeof segment !== "undefined") {
var index = parseInt(d3.select(segment).attr("data-index"), 10);
return {
element: segment,
index: index,
data: this.options.data.content[index]
};
} else {
return null;
}
};
d3pie.prototype.openSegment = function(index) {
index = parseInt(index, 10);
if (index < 0 || index > this.options.data.content.length-1) {
return;
}
segments.openSegment(this, d3.select("#" + this.cssPrefix + "segment" + index).node());
};
d3pie.prototype.closeSegment = function() {
var segment = this.currentlyOpenSegment;
if (segment) {
segments.closeSegment(this, segment);
}
};
// this let's the user dynamically update aspects of the pie chart without causing a complete redraw. It
// intelligently re-renders only the part of the pie that the user specifies. Some things cause a repaint, others
// just redraw the single element
d3pie.prototype.updateProp = function(propKey, value) {
switch (propKey) {
case "header.title.text":
var oldVal = helpers.processObj(this.options, propKey);
helpers.processObj(this.options, propKey, value);
d3.select("#" + this.cssPrefix + "title").html(value);
if ((oldVal === "" && value !== "") || (oldVal !== "" && value === "")) {
this.redraw();
}
break;
case "header.subtitle.text":
var oldValue = helpers.processObj(this.options, propKey);
helpers.processObj(this.options, propKey, value);
d3.select("#" + this.cssPrefix + "subtitle").html(value);
if ((oldValue === "" && value !== "") || (oldValue !== "" && value === "")) {
this.redraw();
}
break;
case "callbacks.onload":
case "callbacks.onMouseoverSegment":
case "callbacks.onMouseoutSegment":
case "callbacks.onClickSegment":
case "effects.pullOutSegmentOnClick.effect":
case "effects.pullOutSegmentOnClick.speed":
case "effects.pullOutSegmentOnClick.size":
case "effects.highlightSegmentOnMouseover":
case "effects.highlightLuminosity":
helpers.processObj(this.options, propKey, value);
break;
// everything else, attempt to update it & do a repaint
default:
helpers.processObj(this.options, propKey, value);
this.destroy();
this.recreate();
break;
}
};
// ------------------------------------------------------------------------------------------------
var _init = function() {
// prep-work
this.svg = helpers.addSVGSpace(this);
// store info about the main text components as part of the d3pie object instance
this.textComponents = {
headerHeight: 0,
title: {
exists: this.options.header.title.text !== "",
h: 0,
w: 0
},
subtitle: {
exists: this.options.header.subtitle.text !== "",
h: 0,
w: 0
},
subtitleMultiLine: {
exists: this.options.header.subtitleMultiLine !== undefined,
h: 0,
w: 0
},
footer: {
exists: this.options.footer.text !== "",
h: 0,
w: 0
}
};
this.outerLabelGroupData = [];
// add the key text components offscreen (title, subtitle, footer). We need to know their widths/heights for later computation
if (this.textComponents.title.exists) {
text.addTitle(this);
}
// TODO não pode ter subtitle e subtitle multiline ao mesmo tempo.
if (this.textComponents.subtitle.exists) {
text.addSubtitle(this);
}
if (this.textComponents.subtitleMultiLine.exists) {
text.addSubtitleMultiLineText(this);
}
text.addFooter(this);
// the footer never moves. Put it in place now
var self = this;
helpers.whenIdExists(this.cssPrefix + "footer", function() {
text.positionFooter(self);
var d3 = helpers.getDimensions(self.cssPrefix + "footer");
self.textComponents.footer.h = d3.h;
self.textComponents.footer.w = d3.w;
});
// now create the pie chart and position everything accordingly
var reqEls = [];
if (this.textComponents.title.exists) { reqEls.push(this.cssPrefix + "title"); }
if (this.textComponents.subtitle.exists) { reqEls.push(this.cssPrefix + "subtitle"); }
if (this.textComponents.footer.exists) { reqEls.push(this.cssPrefix + "footer"); }
helpers.whenElementsExist(reqEls, function() {
if (self.textComponents.title.exists) {
var d1 = helpers.getDimensions(self.cssPrefix + "title");
self.textComponents.title.h = d1.h;
self.textComponents.title.w = d1.w;
}
if (self.textComponents.subtitle.exists) {
var d2 = helpers.getDimensions(self.cssPrefix + "subtitle");
self.textComponents.subtitle.h = d2.h;
self.textComponents.subtitle.w = d2.w;
}
if (self.textComponents.subtitleMultiLine.exists) {
var d3 = helpers.getDimensions(self.cssPrefix + "subtitle");
self.textComponents.subtitleMultiLine.h = d3.h;
self.textComponents.subtitleMultiLine.w = d3.w;
}
// now compute the full header height
if (self.textComponents.title.exists || self.textComponents.subtitle.exists) {
var headerHeight = 0;
if (self.textComponents.title.exists) {
headerHeight += self.textComponents.title.h;
if (self.textComponents.subtitle.exists) {
headerHeight += self.options.header.titleSubtitlePadding;
}
}
if (self.textComponents.subtitle.exists) {
headerHeight += self.textComponents.subtitle.h;
}
self.textComponents.headerHeight = headerHeight;
}
// at this point, all main text component dimensions have been calculated
math.computePieRadius(self);
// this value is used all over the place for placing things and calculating locations. We figure it out ONCE
// and store it as part of the object
math.calculatePieCenter(self);
// position the title and subtitle
text.positionTitle(self);
if(self.textComponents.subtitleMultiLine.exists) {
text.positionSubtitleMultiLineText(self);
} else {
text.positionSubtitle(self);
}
// now create the pie chart segments, and gradients if the user desired
if (self.options.misc.gradient.enabled) {
segments.addGradients(self);
}
segments.create(self); // also creates this.arc
labels.add(self, "inner", self.options.labels.inner.format);
labels.add(self, "outer", self.options.labels.outer.format);
// position the label elements relatively within their individual group (label, percentage, value)
labels.positionLabelElements(self, "inner", self.options.labels.inner.format);
labels.positionLabelElements(self, "outer", self.options.labels.outer.format);
labels.computeOuterLabelCoords(self);
// this is (and should be) dumb. It just places the outer groups at their calculated, collision-free positions
labels.positionLabelGroups(self, "outer");
// we use the label line positions for many other calculations, so ALWAYS compute them
labels.computeLabelLinePositions(self);
// only add them if they're actually enabled
if (self.options.labels.lines.enabled && self.options.labels.outer.format !== "none") {
labels.addLabelLines(self);
}
labels.positionLabelGroups(self, "inner");
labels.fadeInLabelsAndLines(self);
// add and position the tooltips
if (self.options.tooltips.enabled) {
tt.addTooltips(self);
}
segments.addSegmentEventHandlers(self);
});
};
return d3pie;
}));
|
var saludo = function (nombre){
console.log('Hola ' + nombre);
}
//exportar modulo
module.exports = {
saludo: saludo
} |
module.exports = {
api: {
query: {
lean: true
},
token: {
secret: 'bx9cazd3uetbimX29umieDF1vwuCANwJ',
expires: 60
},
admin: {
user: {
name: 'Super Admin',
email: 'super@admin.com',
password: '123456',
type: 'A'
}
}
},
apps: {
list: [
{name: 'System', slug: 'system', long: 'System'},
{name: 'Testapp', slug: 'testapp', long: 'Test App'}
]
},
auth: {
testapp: {
'/api/login': false,
'/api/token': false,
'/api/forgot': false,
'/api/invite': false,
'/api/invite/:token': false,
'/api/register': false,
'/api/resend': false,
'/api/change_password': false,
'/api/social': false,
'/api/waiting/accept': false,
'/api/waiting/decline': false,
'/api/waiting/line': false,
register: {
username: 'required|min:2|max:20|alpha_num',
password: 'required|min:4|max:20',
no_email_verify: true
},
auth: {
invite_moderation: false,
invite_expires: 7,
waiting_list: false
}
}
},
data: {
mongo: {
host: '127.0.0.1',
port: 27017,
db: 'restlio_test',
pool: 10,
autoIndex: true,
debug: false
},
redis: {
host: '127.0.0.1',
port: 6379
}
},
logger: {
transport: 'Console',
options: {
level: 'debug',
humanReadableUnhandledException: true,
handleExceptions: true,
json: false,
colorize: false,
prettyPrint: false,
showLevel: false,
timestamp: false
}
},
boot: {
body: {
urlencoded: {
extended: true,
limit: '16mb'
},
json: {
limit: '16mb'
}
},
compress:{},
cookie: {},
favicon: {
fileName: 'favicon.ico'
},
session: {
name: 'restlio.sid',
secret: 'dVzxlqhr2tqEfK9kcFNSkB0Gqx9XEs2z',
cookie: {
maxAge: 604800000
},
resave: false,
saveUninitialized: true
},
'static': {
dir: 'public',
options: {
maxAge: '1d'
}
},
view: {
dir: 'view',
swig: {
cache: false
}
}
},
sync: {
data: {
apps: false,
roles: false,
objects: false,
superadmin: false,
actions: false,
userroles: false,
docs: false,
superacl: false,
core: false
},
random: {
model_name: false
},
denormalize: {
model_name: false
},
index: {
system_locations: false
},
locations: {
autoindex: false
}
},
roles: {
system: {
'default': [
{name: 'Superadmin', slug: 'superadmin'}
]
},
testapp: {
'default': [
{name: 'Admin', slug: 'admin'},
{name: 'User', slug: 'user'}
],
actions: {
admin: {
},
user: {
}
}
}
}
}; |
'use strict';
app.directive("mainColors", ['$http', '$q', '$timeout', function ($http, $q, $timeout) {
return {
restrict: 'E',
templateUrl: "modules/phoneColors/mainColors/colors.html",
link: function (scope, element, attrs) {
//模块标题
scope.mainColorTitle = attrs.title;
scope.mainColorSubTitle = attrs.subTitle;
scope.$root.mainColor = scope.phone.phoneTypes[0].mediaProductList[getIndex(scope.phone.phoneTypes[0].mediaProductList, 'selected', 1)];
//选择手机颜色
scope.setMainPhoneColor = function (event, color) {
event.preventDefault();
var $this = $(event.currentTarget);
if ($this.hasClass("disabled")) {
return false;
} else {
$this.parent().siblings().children().removeClass('curr');
$this.addClass('curr');
//scope.mainColor = color;
scope.$root.mainColor = color;
writebdLog(scope.category, "_mainFuselageColor", "渠道号", scope.gh);//选择机身颜色
}
};
}
};
}]); |
require("./108.js");
require("./217.js");
require("./435.js");
require("./869.js");
module.exports = 870; |
console.log(5 + 7 / 3 - 4 * 3 % 5);
console.log(2 * (6 + 7) / 3);
console.log(3 / (2 - 1));
console.log((5 * 3 + 1) * 2);
console.log(8 % (5 + 2) * 1 * (1 + 2));
console.log(2 * Math.pow(3, 2 + 4 / 2)); |
"use strict";
exports["default"] = function serviceHandler (sid) {
/*
* Below are the supported options for the serviceHandler:
*
* - data (object): request data payload
* - params (object): use to replace the tokens in the url
* - query (object): use to build the query string appended to the url
* - callback (function): callback to use, with a default which emits 'success' or 'error'
* event depending on res.ok value
* - edit (function): callback to use, to tweak req if needed.
*/
return function(options) {
return new Promise(function (resolve, reject) {
options = options || {};
var data = options.data || {};
var params = options.params || {};
var query = options.query || {};
var callback = options.callback || null;
var edit = options.edit || null;
var req = this.request(sid, data, params, query, options.method);
// edit request if function defined
if (edit && "function" === typeof edit) {
edit(req);
}
var result = function (resolver, middlewares) {
return function (error, response) {
if (middlewares) {
middlewares.reverse().forEach(function (middleware) {
if (error) {
middleware[1](error);
}
middleware[0](response);
});
}
resolver(error, response);
if (callback) {
callback(error, response);
}
}
}
var stack = [];
var failure = result(function (err, res) { reject(err); }, stack);
var success = result(function (err, res) { resolve(res); }, stack);
var agent = this.agent();
return this._applyMiddlewares(req, sid, stack)
.then(function (response) {
return agent.handleResponse(req, response);
})
.then(function (res) {
return success(null, res);
})
.catch(function (err) {
return failure(err);
});
}.bind(this));
};
}; |
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v0.9.0-rc1-master-aff50d5
*/
goog.provide('ng.material.components.chips');
goog.require('ng.material.components.autocomplete');
goog.require('ng.material.core');
(function () {
'use strict';
/**
* @ngdoc module
* @name material.components.chips
*/
/*
* @see js folder for chips implementation
*/
ng.material.components.chips = angular.module('material.components.chips', [
'material.core',
'material.components.autocomplete'
]);
})();
(function () {
'use strict';
angular
.module('material.components.chips')
.directive('mdChip', MdChip);
/**
* @ngdoc directive
* @name mdChip
* @module material.components.chips
*
* @description
* `<md-chip>` is a component used within `<md-chips>` and is responsible for rendering individual
* chips.
*
*
* @usage
* <hljs lang="html">
* <md-chip>{{$chip}}</md-chip>
* </hljs>
*
*/
// This hint text is hidden within a chip but used by screen readers to
// inform the user how they can interact with a chip.
var DELETE_HINT_TEMPLATE = '\
<span ng-if="!$mdChipsCtrl.readonly" class="md-visually-hidden">\
{{$mdChipsCtrl.deleteHint}}\
</span>';
/**
* MDChip Directive Definition
*
* @param $mdTheming
* @param $mdInkRipple
* @ngInject
*/
function MdChip($mdTheming) {
return {
restrict: 'E',
requires: '^mdChips',
compile: compile
};
function compile(element, attr) {
element.append(DELETE_HINT_TEMPLATE);
return function postLink(scope, element, attr) {
element.addClass('md-chip');
$mdTheming(element);
};
}
}
MdChip.$inject = ["$mdTheming"];
})();
(function () {
'use strict';
angular
.module('material.components.chips')
.directive('mdChipRemove', MdChipRemove);
/**
* @ngdoc directive
* @name mdChipRemove
* @module material.components.chips
*
* @description
* `<md-chip-remove>`
* Designates a button as a trigger to remove the chip.
*
* @usage
* <hljs lang="html">
* <md-chip-template>{{$chip}}<button md-chip-remove>DEL</button></md-chip-template>
* </hljs>
*/
/**
*
* @param $compile
* @param $timeout
* @returns {{restrict: string, require: string[], link: Function, scope: boolean}}
* @constructor
*/
function MdChipRemove ($timeout) {
return {
restrict: 'A',
require: '^mdChips',
scope: false,
link: postLink
};
function postLink(scope, element, attr, ctrl) {
element.on('click', function(event) {
scope.$apply(function() {
ctrl.removeChip(scope.$$replacedScope.$index);
});
});
// Child elements aren't available until after a $timeout tick as they are hidden by an
// `ng-if`. see http://goo.gl/zIWfuw
$timeout(function() {
element.attr({ tabindex: -1, ariaHidden: true });
element.find('button').attr('tabindex', '-1');
});
}
}
MdChipRemove.$inject = ["$timeout"];
})();
(function () {
'use strict';
angular
.module('material.components.chips')
.directive('mdChipTransclude', MdChipTransclude);
function MdChipTransclude ($compile, $mdUtil) {
return {
restrict: 'EA',
terminal: true,
link: link,
scope: false
};
function link (scope, element, attr) {
var ctrl = scope.$parent.$mdChipsCtrl,
newScope = ctrl.parent.$new(false, ctrl.parent);
newScope.$$replacedScope = scope;
newScope.$chip = scope.$chip;
newScope.$mdChipsCtrl = ctrl;
element.html(ctrl.$scope.$eval(attr.mdChipTransclude));
$compile(element.contents())(newScope);
}
}
MdChipTransclude.$inject = ["$compile", "$mdUtil"];
})();
(function () {
'use strict';
angular
.module('material.components.chips')
.controller('MdChipsCtrl', MdChipsCtrl);
/**
* Controller for the MdChips component. Responsible for adding to and
* removing from the list of chips, marking chips as selected, and binding to
* the models of various input components.
*
* @param $scope
* @param $mdConstant
* @param $log
* @param $element
* @constructor
*/
function MdChipsCtrl ($scope, $mdConstant, $log, $element, $timeout) {
/** @type {$timeout} **/
this.$timeout = $timeout;
/** @type {Object} */
this.$mdConstant = $mdConstant;
/** @type {angular.$scope} */
this.$scope = $scope;
/** @type {angular.$scope} */
this.parent = $scope.$parent;
/** @type {$log} */
this.$log = $log;
/** @type {$element} */
this.$element = $element;
/** @type {angular.NgModelController} */
this.ngModelCtrl = null;
/** @type {angular.NgModelController} */
this.userInputNgModelCtrl = null;
/** @type {Element} */
this.userInputElement = null;
/** @type {Array.<Object>} */
this.items = [];
/** @type {number} */
this.selectedChip = -1;
/**
* Hidden hint text for how to delete a chip. Used to give context to screen readers.
* @type {string}
*/
this.deleteHint = 'Press delete to remove this chip.';
/**
* Hidden label for the delete button. Used to give context to screen readers.
* @type {string}
*/
this.deleteButtonLabel = 'Remove';
/**
* Model used by the input element.
* @type {string}
*/
this.chipBuffer = '';
/**
* Whether to use the mdOnAppend expression to transform the chip buffer
* before appending it to the list.
* @type {boolean}
*/
this.useMdOnAppend = false;
}
MdChipsCtrl.$inject = ["$scope", "$mdConstant", "$log", "$element", "$timeout"];
/**
* Handles the keydown event on the input element: <enter> appends the
* buffer to the chip list, while backspace removes the last chip in the list
* if the current buffer is empty.
* @param event
*/
MdChipsCtrl.prototype.inputKeydown = function(event) {
var chipBuffer = this.getChipBuffer();
switch (event.keyCode) {
case this.$mdConstant.KEY_CODE.ENTER:
if (this.$scope.requireMatch || !chipBuffer) break;
event.preventDefault();
this.appendChip(chipBuffer);
this.resetChipBuffer();
break;
case this.$mdConstant.KEY_CODE.BACKSPACE:
if (chipBuffer) break;
event.stopPropagation();
if (this.items.length) this.selectAndFocusChipSafe(this.items.length - 1);
break;
}
};
/**
* Handles the keydown event on the chip elements: backspace removes the selected chip, arrow
* keys switch which chips is active
* @param event
*/
MdChipsCtrl.prototype.chipKeydown = function (event) {
if (this.getChipBuffer()) return;
switch (event.keyCode) {
case this.$mdConstant.KEY_CODE.BACKSPACE:
case this.$mdConstant.KEY_CODE.DELETE:
if (this.selectedChip < 0) return;
event.preventDefault();
this.removeAndSelectAdjacentChip(this.selectedChip);
break;
case this.$mdConstant.KEY_CODE.LEFT_ARROW:
event.preventDefault();
if (this.selectedChip < 0) this.selectedChip = this.items.length;
if (this.items.length) this.selectAndFocusChipSafe(this.selectedChip - 1);
break;
case this.$mdConstant.KEY_CODE.RIGHT_ARROW:
event.preventDefault();
this.selectAndFocusChipSafe(this.selectedChip + 1);
break;
case this.$mdConstant.KEY_CODE.ESCAPE:
case this.$mdConstant.KEY_CODE.TAB:
if (this.selectedChip < 0) return;
event.preventDefault();
this.onFocus();
break;
}
};
/**
* Get the input's placeholder - uses `placeholder` when list is empty and `secondary-placeholder`
* when the list is non-empty. If `secondary-placeholder` is not provided, `placeholder` is used
* always.
*/
MdChipsCtrl.prototype.getPlaceholder = function() {
// Allow `secondary-placeholder` to be blank.
var useSecondary = (this.items.length &&
(this.secondaryPlaceholder == '' || this.secondaryPlaceholder));
return useSecondary ? this.placeholder : this.secondaryPlaceholder;
};
/**
* Removes chip at {@code index} and selects the adjacent chip.
* @param index
*/
MdChipsCtrl.prototype.removeAndSelectAdjacentChip = function(index) {
var selIndex = this.getAdjacentChipIndex(index);
this.removeChip(index);
this.$timeout(function () { this.selectAndFocusChipSafe(selIndex); }.bind(this));
};
/**
* Sets the selected chip index to -1.
*/
MdChipsCtrl.prototype.resetSelectedChip = function() {
this.selectedChip = -1;
};
/**
* Gets the index of an adjacent chip to select after deletion. Adjacency is
* determined as the next chip in the list, unless the target chip is the
* last in the list, then it is the chip immediately preceding the target. If
* there is only one item in the list, -1 is returned (select none).
* The number returned is the index to select AFTER the target has been
* removed.
* If the current chip is not selected, then -1 is returned to select none.
*/
MdChipsCtrl.prototype.getAdjacentChipIndex = function(index) {
var len = this.items.length - 1;
return (len == 0) ? -1 :
(index == len) ? index -1 : index;
};
/**
* Append the contents of the buffer to the chip list. This method will first
* call out to the md-on-append method, if provided
* @param newChip
*/
MdChipsCtrl.prototype.appendChip = function(newChip) {
if (this.items.indexOf(newChip) + 1) return;
if (this.useMdOnAppend && this.mdOnAppend) {
newChip = this.mdOnAppend({'$chip': newChip});
}
this.items.push(newChip);
};
/**
* Sets whether to use the md-on-append expression. This expression is
* bound to scope and controller in {@code MdChipsDirective} as
* {@code mdOnAppend}. Due to the nature of directive scope bindings, the
* controller cannot know on its own/from the scope whether an expression was
* actually provided.
*/
MdChipsCtrl.prototype.useMdOnAppendExpression = function() {
this.useMdOnAppend = true;
};
/**
* Gets the input buffer. The input buffer can be the model bound to the
* default input item {@code this.chipBuffer}, the {@code selectedItem}
* model of an {@code md-autocomplete}, or, through some magic, the model
* bound to any inpput or text area element found within a
* {@code md-input-container} element.
* @return {Object|string}
*/
MdChipsCtrl.prototype.getChipBuffer = function() {
return !this.userInputElement ? this.chipBuffer :
this.userInputNgModelCtrl ? this.userInputNgModelCtrl.$viewValue :
this.userInputElement[0].value;
};
/**
* Resets the input buffer for either the internal input or user provided input element.
*/
MdChipsCtrl.prototype.resetChipBuffer = function() {
if (this.userInputElement) {
if (this.userInputNgModelCtrl) {
this.userInputNgModelCtrl.$setViewValue('');
this.userInputNgModelCtrl.$render();
} else {
this.userInputElement[0].value = '';
}
} else {
this.chipBuffer = '';
}
};
/**
* Removes the chip at the given index.
* @param index
*/
MdChipsCtrl.prototype.removeChip = function(index) {
this.items.splice(index, 1);
};
MdChipsCtrl.prototype.removeChipAndFocusInput = function (index) {
this.removeChip(index);
this.onFocus();
};
/**
* Selects the chip at `index`,
* @param index
*/
MdChipsCtrl.prototype.selectAndFocusChipSafe = function(index) {
if (!this.items.length) {
this.selectChip(-1);
this.onFocus();
return;
}
if (index === this.items.length) return this.onFocus();
index = Math.max(index, 0);
index = Math.min(index, this.items.length - 1);
this.selectChip(index);
this.focusChip(index);
};
/**
* Marks the chip at the given index as selected.
* @param index
*/
MdChipsCtrl.prototype.selectChip = function(index) {
if (index >= -1 && index <= this.items.length) {
this.selectedChip = index;
} else {
this.$log.warn('Selected Chip index out of bounds; ignoring.');
}
};
/**
* Selects the chip at `index` and gives it focus.
* @param index
*/
MdChipsCtrl.prototype.selectAndFocusChip = function(index) {
this.selectChip(index);
if (index != -1) {
this.focusChip(index);
}
};
/**
* Call `focus()` on the chip at `index`
*/
MdChipsCtrl.prototype.focusChip = function(index) {
this.$element[0].querySelector('md-chip[index="' + index + '"] .md-chip-content').focus();
};
/**
* Configures the required interactions with the ngModel Controller.
* Specifically, set {@code this.items} to the {@code NgModelCtrl#$viewVale}.
* @param ngModelCtrl
*/
MdChipsCtrl.prototype.configureNgModel = function(ngModelCtrl) {
this.ngModelCtrl = ngModelCtrl;
var self = this;
ngModelCtrl.$render = function() {
// model is updated. do something.
self.items = self.ngModelCtrl.$viewValue;
};
};
MdChipsCtrl.prototype.onFocus = function () {
var input = this.$element[0].querySelectorAll('input')[0];
input && input.focus();
this.resetSelectedChip();
};
/**
* Configure event bindings on a user-provided input element.
* @param inputElement
*/
MdChipsCtrl.prototype.configureUserInput = function(inputElement) {
this.userInputElement = inputElement;
// Find the NgModelCtrl for the input element
var ngModelCtrl = inputElement.controller('ngModel');
// `.controller` will look in the parent as well.
if (ngModelCtrl != this.ngModelCtrl) {
this.userInputNgModelCtrl = ngModelCtrl;
}
// Bind to keydown and focus events of input
var scope = this.$scope;
var ctrl = this;
inputElement
.attr({ tabindex: 0 })
.on('keydown', function(event) { scope.$apply(function() { ctrl.inputKeydown(event); }); })
.on('focus', function () { ctrl.selectedChip = -1; });
};
MdChipsCtrl.prototype.configureAutocomplete = function(ctrl) {
ctrl.registerSelectedItemWatcher(function (item) {
if (item) {
this.appendChip(item);
this.resetChipBuffer();
}
}.bind(this));
};
})();
(function () {
'use strict';
angular
.module('material.components.chips')
.directive('mdChips', MdChips);
/**
* @ngdoc directive
* @name mdChips
* @module material.components.chips
*
* @description
* `<md-chips>` is an input component for building lists of strings or objects. The list items are
* displayed as 'chips'. This component can make use of an `<input>` element or an
* `<md-autocomplete>` element.
*
* <strong>Custom `<md-chip-template>` template</strong>
* A custom template may be provided to render the content of each chip. This is achieved by
* specifying an `<md-chip-template>` element as a child of `<md-chips>`. Note: Any attributes on
* `<md-chip-template>` will be dropped as only the innerHTML is used for the chip template. The
* variables `$chip` and `$index` are available in the scope of `<md-chip-template>`, representing
* the chip object and its index in the list of chips, respectively.
* To override the chip delete control, include an element (ideally a button) with the attribute
* `md-chip-remove`. A click listener to remove the chip will be added automatically. The element
* is also placed as a sibling to the chip content (on which there are also click listeners) to
* avoid a nested ng-click situation.
*
* <h3> Pending Features </h3>
* <ul style="padding-left:20px;">
*
* <ul>Style
* <li>Colours for hover, press states (ripple?).</li>
* </ul>
*
* <ul>List Manipulation
* <li>delete item via DEL or backspace keys when selected</li>
* </ul>
*
* <ul>Validation
* <li>de-dupe values (or support duplicates, but fix the ng-repeat duplicate key issue)</li>
* <li>allow a validation callback</li>
* <li>hilighting style for invalid chips</li>
* </ul>
*
* <ul>Item mutation
* <li>Support `
* <md-chip-edit>` template, show/hide the edit element on tap/click? double tap/double
* click?
* </li>
* </ul>
*
* <ul>Truncation and Disambiguation (?)
* <li>Truncate chip text where possible, but do not truncate entries such that two are
* indistinguishable.</li>
* </ul>
*
* <ul>Drag and Drop
* <li>Drag and drop chips between related `<md-chips>` elements.
* </li>
* </ul>
* </ul>
*
* <span style="font-size:.8em;text-align:center">
* Warning: This component is a WORK IN PROGRESS. If you use it now,
* it will probably break on you in the future.
* </span>
*
* @param {string=|object=} ng-model A model to bind the list of items to
* @param {string=} placeholder Placeholder text that will be forwarded to the input.
* @param {string=} secondary-placeholder Placeholder text that will be forwarded to the input,
* displayed when there is at least on item in the list
* @param {boolean=} readonly Disables list manipulation (deleting or adding list items), hiding
* the input and delete buttons
* @param {expression} md-on-append An expression expected to convert the input string into an
* object when adding a chip.
* @param {string=} delete-hint A string read by screen readers instructing users that pressing
* the delete key will remove the chip.
* @param {string=} delete-button-label A label for the delete button. Also hidden and read by
* screen readers.
*
* @usage
* <hljs lang="html">
* <md-chips
* ng-model="myItems"
* placeholder="Add an item"
* readonly="isReadOnly">
* </md-chips>
* </hljs>
*
*/
var MD_CHIPS_TEMPLATE = '\
<md-chips-wrap\
ng-if="!$mdChipsCtrl.readonly || $mdChipsCtrl.items.length > 0"\
ng-keydown="$mdChipsCtrl.chipKeydown($event)"\
class="md-chips">\
<md-chip ng-repeat="$chip in $mdChipsCtrl.items"\
index="{{$index}}"\
ng-class="{\'md-focused\': $mdChipsCtrl.selectedChip == $index}">\
<div class="md-chip-content"\
tabindex="-1"\
aria-hidden="true"\
ng-click="!$mdChipsCtrl.readonly && $mdChipsCtrl.selectChip($index)"\
md-chip-transclude="$mdChipsCtrl.chipContentsTemplate"></div>\
<div class="md-chip-remove-container"\
md-chip-transclude="$mdChipsCtrl.chipRemoveTemplate"></div>\
</md-chip>\
<div ng-if="!$mdChipsCtrl.readonly && $mdChipsCtrl.ngModelCtrl"\
class="md-chip-input-container"\
md-chip-transclude="$mdChipsCtrl.chipInputTemplate"></div>\
</div>\
</md-chips-wrap>';
var CHIP_INPUT_TEMPLATE = '\
<input\
tabindex="0"\
placeholder="{{$mdChipsCtrl.getPlaceholder()}}"\
aria-label="{{$mdChipsCtrl.getPlaceholder()}}"\
ng-model="$mdChipsCtrl.chipBuffer"\
ng-focus="$mdChipsCtrl.resetSelectedChip()"\
ng-keydown="$mdChipsCtrl.inputKeydown($event)">';
var CHIP_DEFAULT_TEMPLATE = '\
<span>{{$chip}}</span>';
var CHIP_REMOVE_TEMPLATE = '\
<button\
class="md-chip-remove"\
ng-if="!$mdChipsCtrl.readonly"\
ng-click="$mdChipsCtrl.removeChipAndFocusInput($$replacedScope.$index)"\
aria-hidden="true"\
tabindex="-1">\
<md-icon md-svg-icon="close"></md-icon>\
<span class="md-visually-hidden">\
{{$mdChipsCtrl.deleteButtonLabel}}\
</span>\
</button>';
/**
* MDChips Directive Definition
*/
function MdChips ($mdTheming, $compile, $timeout) {
return {
template: function(element, attrs) {
// Clone the element into an attribute. By prepending the attribute
// name with '$', Angular won't write it into the DOM. The cloned
// element propagates to the link function via the attrs argument,
// where various contained-elements can be consumed.
attrs['$mdUserTemplate'] = element.clone();
return MD_CHIPS_TEMPLATE;
},
require: ['mdChips'],
restrict: 'E',
controller: 'MdChipsCtrl',
controllerAs: '$mdChipsCtrl',
bindToController: true,
compile: compile,
scope: {
readonly: '=readonly',
placeholder: '@',
secondaryPlaceholder: '@',
mdOnAppend: '&',
deleteHint: '@',
deleteButtonLabel: '@',
requireMatch: '=?mdRequireMatch'
}
};
/**
* Builds the final template for `md-chips` and returns the postLink function.
*
* Building the template involves 3 key components:
* static chips
* chip template
* input control
*
* If no `ng-model` is provided, only the static chip work needs to be done.
*
* If no user-passed `md-chip-template` exists, the default template is used. This resulting
* template is appended to the chip content element.
*
* The remove button may be overridden by passing an element with an md-chip-remove attribute.
*
* If an `input` or `md-autocomplete` element is provided by the caller, it is set aside for
* transclusion later. The transclusion happens in `postLink` as the parent scope is required.
* If no user input is provided, a default one is appended to the input container node in the
* template.
*
* Static Chips (i.e. `md-chip` elements passed from the caller) are gathered and set aside for
* transclusion in the `postLink` function.
*
*
* @param element
* @param attr
* @returns {Function}
*/
function compile(element, attr) {
// Grab the user template from attr and reset the attribute to null.
var userTemplate = attr['$mdUserTemplate'];
attr['$mdUserTemplate'] = null;
// Set the chip remove, chip contents and chip input templates. The link function will put
// them on the scope for transclusion later.
var chipRemoveTemplate = getTemplateByQuery('[md-chip-remove]') || CHIP_REMOVE_TEMPLATE,
chipContentsTemplate = getTemplateByQuery('md-chip-template') || CHIP_DEFAULT_TEMPLATE,
chipInputTemplate = getTemplateByQuery('md-autocomplete')
|| getTemplateByQuery('input')
|| CHIP_INPUT_TEMPLATE,
staticChips = userTemplate.find('md-chip');
function getTemplateByQuery (query) {
if (!attr.ngModel) return;
var element = userTemplate[0].querySelector(query);
return element && element.outerHTML;
}
/**
* Configures controller and transcludes.
*/
return function postLink(scope, element, attrs, controllers) {
//-- give optional properties with no value a boolean true by default
angular.forEach(scope.$$isolateBindings, function (binding, key) {
if (binding.optional && angular.isUndefined(scope[key])) {
scope[key] = attr.hasOwnProperty(attr.$normalize(binding.attrName));
}
});
$mdTheming(element);
var mdChipsCtrl = controllers[0];
mdChipsCtrl.chipContentsTemplate = chipContentsTemplate;
mdChipsCtrl.chipRemoveTemplate = chipRemoveTemplate;
mdChipsCtrl.chipInputTemplate = chipInputTemplate;
element
.attr({ ariaHidden: true, tabindex: -1 })
.on('focus', function () { mdChipsCtrl.onFocus(); });
if (attr.ngModel) {
mdChipsCtrl.configureNgModel(element.controller('ngModel'));
// If an `md-on-append` attribute was set, tell the controller to use the expression
// when appending chips.
if (attrs.mdOnAppend) mdChipsCtrl.useMdOnAppendExpression();
// The md-autocomplete and input elements won't be compiled until after this directive
// is complete (due to their nested nature). Wait a tick before looking for them to
// configure the controller.
if (chipInputTemplate != CHIP_INPUT_TEMPLATE) {
$timeout(function() {
if (chipInputTemplate.indexOf('<md-autocomplete') === 0) mdChipsCtrl.configureAutocomplete(element.find('md-autocomplete').controller('mdAutocomplete'));
mdChipsCtrl.configureUserInput(element.find('input'));
});
}
}
// Compile with the parent's scope and prepend any static chips to the wrapper.
if (staticChips.length > 0) {
var compiledStaticChips = $compile(staticChips)(scope.$parent);
$timeout(function() { element.find('md-chips-wrap').prepend(compiledStaticChips); });
}
};
}
}
MdChips.$inject = ["$mdTheming", "$compile", "$timeout"];
})();
(function () {
'use strict';
angular
.module('material.components.chips')
.controller('MdContactChipsCtrl', MdContactChipsCtrl);
/**
* Controller for the MdContactChips component
* @constructor
*/
function MdContactChipsCtrl () {
/** @type {Object} */
this.selectedItem = null;
/** @type {string} */
this.searchText = '';
}
MdContactChipsCtrl.prototype.queryContact = function(searchText) {
var results = this.contactQuery({'$query': searchText});
return this.filterSelected ?
results.filter(this.filterSelectedContacts.bind(this)) : results;
};
MdContactChipsCtrl.prototype.filterSelectedContacts = function(contact) {
return this.contacts.indexOf(contact) == -1;
};
})();
(function () {
'use strict';
angular
.module('material.components.chips')
.directive('mdContactChips', MdContactChips);
/**
* @ngdoc directive
* @name mdContactChips
* @module material.components.chips
*
* @description
* `<md-contact-chips>` is an input component based on `md-chips` and makes use of an
* `md-autocomplete` element. The component allows the caller to supply a query expression
* which returns a list of possible contacts. The user can select one of these and add it to
* the list of chips.
*
* @param {string=|object=} ng-model A model to bind the list of items to
* @param {string=} placeholder Placeholder text that will be forwarded to the input.
* @param {string=} secondary-placeholder Placeholder text that will be forwarded to the input,
* displayed when there is at least on item in the list
* @param {expression} md-contacts An expression expected to return contacts matching the search
* test, `$query`.
* @param {string} md-contact-name The field name of the contact object representing the
* contact's name.
* @param {string} md-contact-email The field name of the contact object representing the
* contact's email address.
* @param {string} md-contact-image The field name of the contact object representing the
* contact's image.
* @param {expression=} filter-selected Whether to filter selected contacts from the list of
* suggestions shown in the autocomplete.
*
*
*
* @usage
* <hljs lang="html">
* <md-contact-chips
* ng-model="ctrl.contacts"
* md-contacts="ctrl.querySearch($query)"
* md-contact-name="name"
* md-contact-image="image"
* md-contact-email="email"
* md-filter-selected="ctrl.filterSelected"
* placeholder="To">
* </md-contact-chips>
* </hljs>
*
*/
var MD_CONTACT_CHIPS_TEMPLATE = '\
<md-chips class="md-contact-chips"\
ng-model="$mdContactChipsCtrl.contacts"\
md-require-match="$mdContactChipsCtrl.requireMatch"\
md-autocomplete-snap>\
<md-autocomplete\
md-menu-class="md-contact-chips-suggestions"\
md-selected-item="$mdContactChipsCtrl.selectedItem"\
md-search-text="$mdContactChipsCtrl.searchText"\
md-items="item in $mdContactChipsCtrl.queryContact($mdContactChipsCtrl.searchText)"\
md-item-text="$mdContactChipsCtrl.mdContactName"\
md-no-cache="$mdContactChipsCtrl.filterSelected"\
md-autoselect\
placeholder="{{$mdContactChipsCtrl.contacts.length == 0 ?\
$mdContactChipsCtrl.placeholder : $mdContactChipsCtrl.secondaryPlaceholder}}">\
<div class="md-contact-suggestion">\
<img \
ng-src="{{item[$mdContactChipsCtrl.contactImage]}}"\
alt="{{item[$mdContactChipsCtrl.contactName]}}" />\
<span class="md-contact-name" md-highlight-text="$mdContactChipsCtrl.searchText">\
{{item[$mdContactChipsCtrl.contactName]}}\
</span>\
<span class="md-contact-email" >{{item[$mdContactChipsCtrl.contactEmail]}}</span>\
</div>\
</md-autocomplete>\
<md-chip-template>\
<div class="md-contact-avatar">\
<img \
ng-src="{{$chip[$mdContactChipsCtrl.contactImage]}}"\
alt="{{$chip[$mdContactChipsCtrl.contactName]}}" />\
</div>\
<div class="md-contact-name">\
{{$chip[$mdContactChipsCtrl.contactName]}}\
</div>\
</md-chip-template>\
</md-chips>';
/**
* MDContactChips Directive Definition
*
* @param $mdTheming
* @returns {*}
* @ngInject
*/
function MdContactChips ($mdTheming) {
return {
template: function(element, attrs) {
return MD_CONTACT_CHIPS_TEMPLATE;
},
restrict: 'E',
controller: 'MdContactChipsCtrl',
controllerAs: '$mdContactChipsCtrl',
bindToController: true,
compile: compile,
scope: {
contactQuery: '&mdContacts',
placeholder: '@',
secondaryPlaceholder: '@',
contactName: '@mdContactName',
contactImage: '@mdContactImage',
contactEmail: '@mdContactEmail',
filterSelected: '=',
contacts: '=ngModel',
requireMatch: '=?mdRequireMatch'
}
};
function compile(element, attr) {
return function postLink(scope, element, attrs, controllers) {
//-- give optional properties with no value a boolean true by default
angular.forEach(scope.$$isolateBindings, function (binding, key) {
if (binding.optional && angular.isUndefined(scope[key])) {
scope[key] = attr.hasOwnProperty(attr.$normalize(binding.attrName));
}
});
$mdTheming(element);
element.attr('tabindex', '-1');
};
}
}
MdContactChips.$inject = ["$mdTheming"];
})();
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by CodeZu.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
var Client = require('../../../client'), constants = Client.constants;
module.exports = Client.sub({
getFacets: Client.method({
method: constants.verbs.GET,
url: '{+tenantPod}api/content/documentlists/{documentListName}/facets/{propertyName}'
})
});
|
'use strict';
/**
* This will be transferred over to gd and overridden by
* config args to Plotly.newPlot.
*
* The defaults are the appropriate settings for plotly.js,
* so we get the right experience without any config argument.
*
* N.B. the config options are not coerced using Lib.coerce so keys
* like `valType` and `values` are only set for documentation purposes
* at the moment.
*/
var configAttributes = {
staticPlot: {
valType: 'boolean',
dflt: false,
description: [
'Determines whether the graphs are interactive or not.',
'If *false*, no interactivity, for export or image generation.'
].join(' ')
},
typesetMath: {
valType: 'boolean',
dflt: true,
description: [
'Determines whether math should be typeset or not,',
'when MathJax (either v2 or v3) is present on the page.'
].join(' ')
},
plotlyServerURL: {
valType: 'string',
dflt: '',
description: [
'When set it determines base URL for',
'the \'Edit in Chart Studio\' `showEditInChartStudio`/`showSendToCloud` mode bar button',
'and the showLink/sendData on-graph link.',
'To enable sending your data to Chart Studio Cloud, you need to',
'set both `plotlyServerURL` to \'https://chart-studio.plotly.com\' and',
'also set `showSendToCloud` to true.'
].join(' ')
},
editable: {
valType: 'boolean',
dflt: false,
description: [
'Determines whether the graph is editable or not.',
'Sets all pieces of `edits`',
'unless a separate `edits` config item overrides individual parts.'
].join(' ')
},
edits: {
annotationPosition: {
valType: 'boolean',
dflt: false,
description: [
'Determines if the main anchor of the annotation is editable.',
'The main anchor corresponds to the',
'text (if no arrow) or the arrow (which drags the whole thing leaving',
'the arrow length & direction unchanged).'
].join(' ')
},
annotationTail: {
valType: 'boolean',
dflt: false,
description: [
'Has only an effect for annotations with arrows.',
'Enables changing the length and direction of the arrow.'
].join(' ')
},
annotationText: {
valType: 'boolean',
dflt: false,
description: 'Enables editing annotation text.'
},
axisTitleText: {
valType: 'boolean',
dflt: false,
description: 'Enables editing axis title text.'
},
colorbarPosition: {
valType: 'boolean',
dflt: false,
description: 'Enables moving colorbars.'
},
colorbarTitleText: {
valType: 'boolean',
dflt: false,
description: 'Enables editing colorbar title text.'
},
legendPosition: {
valType: 'boolean',
dflt: false,
description: 'Enables moving the legend.'
},
legendText: {
valType: 'boolean',
dflt: false,
description: 'Enables editing the trace name fields from the legend'
},
shapePosition: {
valType: 'boolean',
dflt: false,
description: 'Enables moving shapes.'
},
titleText: {
valType: 'boolean',
dflt: false,
description: 'Enables editing the global layout title.'
}
},
autosizable: {
valType: 'boolean',
dflt: false,
description: [
'Determines whether the graphs are plotted with respect to',
'layout.autosize:true and infer its container size.'
].join(' ')
},
responsive: {
valType: 'boolean',
dflt: false,
description: [
'Determines whether to change the layout size when window is resized.',
'In v3, this option will be removed and will always be true.'
].join(' ')
},
fillFrame: {
valType: 'boolean',
dflt: false,
description: [
'When `layout.autosize` is turned on, determines whether the graph',
'fills the container (the default) or the screen (if set to *true*).'
].join(' ')
},
frameMargins: {
valType: 'number',
dflt: 0,
min: 0,
max: 0.5,
description: [
'When `layout.autosize` is turned on, set the frame margins',
'in fraction of the graph size.'
].join(' ')
},
scrollZoom: {
valType: 'flaglist',
flags: ['cartesian', 'gl3d', 'geo', 'mapbox'],
extras: [true, false],
dflt: 'gl3d+geo+mapbox',
description: [
'Determines whether mouse wheel or two-finger scroll zooms is enable.',
'Turned on by default for gl3d, geo and mapbox subplots',
'(as these subplot types do not have zoombox via pan),',
'but turned off by default for cartesian subplots.',
'Set `scrollZoom` to *false* to disable scrolling for all subplots.'
].join(' ')
},
doubleClick: {
valType: 'enumerated',
values: [false, 'reset', 'autosize', 'reset+autosize'],
dflt: 'reset+autosize',
description: [
'Sets the double click interaction mode.',
'Has an effect only in cartesian plots.',
'If *false*, double click is disable.',
'If *reset*, double click resets the axis ranges to their initial values.',
'If *autosize*, double click set the axis ranges to their autorange values.',
'If *reset+autosize*, the odd double clicks resets the axis ranges',
'to their initial values and even double clicks set the axis ranges',
'to their autorange values.'
].join(' ')
},
doubleClickDelay: {
valType: 'number',
dflt: 300,
min: 0,
description: [
'Sets the delay for registering a double-click in ms.',
'This is the time interval (in ms) between first mousedown and',
'2nd mouseup to constitute a double-click.',
'This setting propagates to all on-subplot double clicks',
'(except for geo and mapbox) and on-legend double clicks.'
].join(' ')
},
showAxisDragHandles: {
valType: 'boolean',
dflt: true,
description: [
'Set to *false* to omit cartesian axis pan/zoom drag handles.'
].join(' ')
},
showAxisRangeEntryBoxes: {
valType: 'boolean',
dflt: true,
description: [
'Set to *false* to omit direct range entry at the pan/zoom drag points,',
'note that `showAxisDragHandles` must be enabled to have an effect.'
].join(' ')
},
showTips: {
valType: 'boolean',
dflt: true,
description: [
'Determines whether or not tips are shown while interacting',
'with the resulting graphs.'
].join(' ')
},
showLink: {
valType: 'boolean',
dflt: false,
description: [
'Determines whether a link to Chart Studio Cloud is displayed',
'at the bottom right corner of resulting graphs.',
'Use with `sendData` and `linkText`.'
].join(' ')
},
linkText: {
valType: 'string',
dflt: 'Edit chart',
noBlank: true,
description: [
'Sets the text appearing in the `showLink` link.'
].join(' ')
},
sendData: {
valType: 'boolean',
dflt: true,
description: [
'If *showLink* is true, does it contain data',
'just link to a Chart Studio Cloud file?'
].join(' ')
},
showSources: {
valType: 'any',
dflt: false,
description: [
'Adds a source-displaying function to show sources on',
'the resulting graphs.'
].join(' ')
},
displayModeBar: {
valType: 'enumerated',
values: ['hover', true, false],
dflt: 'hover',
description: [
'Determines the mode bar display mode.',
'If *true*, the mode bar is always visible.',
'If *false*, the mode bar is always hidden.',
'If *hover*, the mode bar is visible while the mouse cursor',
'is on the graph container.'
].join(' ')
},
showSendToCloud: {
valType: 'boolean',
dflt: false,
description: [
'Should we include a ModeBar button, labeled "Edit in Chart Studio",',
'that sends this chart to chart-studio.plotly.com (formerly plot.ly) or another plotly server',
'as specified by `plotlyServerURL` for editing, export, etc? Prior to version 1.43.0',
'this button was included by default, now it is opt-in using this flag.',
'Note that this button can (depending on `plotlyServerURL` being set) send your data',
'to an external server. However that server does not persist your data',
'until you arrive at the Chart Studio and explicitly click "Save".'
].join(' ')
},
showEditInChartStudio: {
valType: 'boolean',
dflt: false,
description: [
'Same as `showSendToCloud`, but use a pencil icon instead of a floppy-disk.',
'Note that if both `showSendToCloud` and `showEditInChartStudio` are turned,',
'only `showEditInChartStudio` will be honored.'
].join(' ')
},
modeBarButtonsToRemove: {
valType: 'any',
dflt: [],
description: [
'Remove mode bar buttons by name.',
'See ./components/modebar/buttons.js for the list of names.'
].join(' ')
},
modeBarButtonsToAdd: {
valType: 'any',
dflt: [],
description: [
'Add mode bar button using config objects',
'See ./components/modebar/buttons.js for list of arguments.',
'To enable predefined modebar buttons e.g. shape drawing, hover and spikelines,',
'simply provide their string name(s). This could include:',
'*v1hovermode*, *hoverclosest*, *hovercompare*, *togglehover*, *togglespikelines*,',
'*drawline*, *drawopenpath*, *drawclosedpath*, *drawcircle*, *drawrect* and *eraseshape*.',
'Please note that these predefined buttons will only be shown if they are compatible',
'with all trace types used in a graph.'
].join(' ')
},
modeBarButtons: {
valType: 'any',
dflt: false,
description: [
'Define fully custom mode bar buttons as nested array,',
'where the outer arrays represents button groups, and',
'the inner arrays have buttons config objects or names of default buttons',
'See ./components/modebar/buttons.js for more info.'
].join(' ')
},
toImageButtonOptions: {
valType: 'any',
dflt: {},
description: [
'Statically override options for toImage modebar button',
'allowed keys are format, filename, width, height, scale',
'see ../components/modebar/buttons.js'
].join(' ')
},
displaylogo: {
valType: 'boolean',
dflt: true,
description: [
'Determines whether or not the plotly logo is displayed',
'on the end of the mode bar.'
].join(' ')
},
watermark: {
valType: 'boolean',
dflt: false,
description: 'watermark the images with the company\'s logo'
},
plotGlPixelRatio: {
valType: 'number',
dflt: 2,
min: 1,
max: 4,
description: [
'Set the pixel ratio during WebGL image export.',
'This config option was formerly named `plot3dPixelRatio`',
'which is now deprecated.'
].join(' ')
},
setBackground: {
valType: 'any',
dflt: 'transparent',
description: [
'Set function to add the background color (i.e. `layout.paper_color`)',
'to a different container.',
'This function take the graph div as first argument and the current background',
'color as second argument.',
'Alternatively, set to string *opaque* to ensure there is white behind it.'
].join(' ')
},
topojsonURL: {
valType: 'string',
noBlank: true,
dflt: 'https://cdn.plot.ly/',
description: [
'Set the URL to topojson used in geo charts.',
'By default, the topojson files are fetched from cdn.plot.ly.',
'For example, set this option to:',
'<path-to-plotly.js>/dist/topojson/',
'to render geographical feature using the topojson files',
'that ship with the plotly.js module.'
].join(' ')
},
mapboxAccessToken: {
valType: 'string',
dflt: null,
description: [
'Mapbox access token (required to plot mapbox trace types)',
'If using an Mapbox Atlas server, set this option to \'\'',
'so that plotly.js won\'t attempt to authenticate to the public Mapbox server.'
].join(' ')
},
logging: {
valType: 'integer',
min: 0,
max: 2,
dflt: 1,
description: [
'Turn all console logging on or off (errors will be thrown)',
'This should ONLY be set via Plotly.setPlotConfig',
'Available levels:',
'0: no logs',
'1: warnings and errors, but not informational messages',
'2: verbose logs'
].join(' ')
},
notifyOnLogging: {
valType: 'integer',
min: 0,
max: 2,
dflt: 0,
description: [
'Set on-graph logging (notifier) level',
'This should ONLY be set via Plotly.setPlotConfig',
'Available levels:',
'0: no on-graph logs',
'1: warnings and errors, but not informational messages',
'2: verbose logs'
].join(' ')
},
queueLength: {
valType: 'integer',
min: 0,
dflt: 0,
description: 'Sets the length of the undo/redo queue.'
},
globalTransforms: {
valType: 'any',
dflt: [],
description: [
'Set global transform to be applied to all traces with no',
'specification needed'
].join(' ')
},
locale: {
valType: 'string',
dflt: 'en-US',
description: [
'Which localization should we use?',
'Should be a string like \'en\' or \'en-US\'.'
].join(' ')
},
locales: {
valType: 'any',
dflt: {},
description: [
'Localization definitions',
'Locales can be provided either here (specific to one chart) or globally',
'by registering them as modules.',
'Should be an object of objects {locale: {dictionary: {...}, format: {...}}}',
'{',
' da: {',
' dictionary: {\'Reset axes\': \'Nulstil aksler\', ...},',
' format: {months: [...], shortMonths: [...]}',
' },',
' ...',
'}',
'All parts are optional. When looking for translation or format fields, we',
'look first for an exact match in a config locale, then in a registered',
'module. If those fail, we strip off any regionalization (\'en-US\' -> \'en\')',
'and try each (config, registry) again. The final fallback for translation',
'is untranslated (which is US English) and for formats is the base English',
'(the only consequence being the last fallback date format %x is DD/MM/YYYY',
'instead of MM/DD/YYYY). Currently `grouping` and `currency` are ignored',
'for our automatic number formatting, but can be used in custom formats.'
].join(' ')
}
};
var dfltConfig = {};
function crawl(src, target) {
for(var k in src) {
var obj = src[k];
if(obj.valType) {
target[k] = obj.dflt;
} else {
if(!target[k]) {
target[k] = {};
}
crawl(obj, target[k]);
}
}
}
crawl(configAttributes, dfltConfig);
module.exports = {
configAttributes: configAttributes,
dfltConfig: dfltConfig
};
|
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
module.exports = function (timePeriodObj) {
if (!timePeriodObj) return '';
if ((typeof timePeriodObj === 'undefined' ? 'undefined' : _typeof(timePeriodObj)) !== 'object') return new Error('timePeriod must be an object of type {type: enum, value: number}');
var enumTypes = {
hour: ['now', 'H'],
day: ['now', 'd'],
month: ['today', 'm'],
year: ['today', 'm']
};
if (typeof timePeriodObj.type !== 'string' || !enumTypes[timePeriodObj.type.toLowerCase()]) return new Error('type must be one of the specified enumerated types');
if (!timePeriodObj.value || typeof timePeriodObj.value !== 'number') return new Error('timePeriod value must be a number');
return 'date=' + enumTypes[timePeriodObj.type.toLowerCase()][0] + ' ' + (timePeriodObj.type.toLowerCase() === 'year' ? Math.round(timePeriodObj.value) * 12 : Math.round(timePeriodObj.value)) + '-' + enumTypes[timePeriodObj.type.toLowerCase()][1];
}; |
/**
* This source code is quoted from rc-tabs.
* homepage: https://github.com/react-component/tabs
*/
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import debounce from 'lodash/debounce';
import ResizeObserver from 'resize-observer-polyfill';
import { setTransform, isTransformSupported, requestAnimationFrame } from './utils';
export default class ScrollableTabBarNode extends React.Component {
constructor(props) {
super(props);
this.offset = 0;
this.state = {
next: false,
prev: false,
};
}
componentDidMount() {
this.componentDidUpdate();
this.debouncedResize = debounce(() => {
this.setNextPrev();
this.scrollToActiveTab();
}, 200);
this.resizeObserver = new ResizeObserver(this.debouncedResize);
this.resizeObserver.observe(this.props.getRef('container'));
}
componentDidUpdate(prevProps) {
requestAnimationFrame(() => {
const props = this.props;
if (prevProps && prevProps.tabBarPosition !== props.tabBarPosition) {
this.setOffset(0);
return;
}
const nextPrev = this.setNextPrev();
// wait next, prev show hide
/* eslint react/no-did-update-set-state:0 */
if (this.isNextPrevShown(this.state) !== this.isNextPrevShown(nextPrev)) {
this.setState({}, this.scrollToActiveTab);
} else if (!prevProps || props.activeKey !== prevProps.activeKey) {
// can not use props.activeKey
this.scrollToActiveTab();
}
})
}
componentWillUnmount() {
if (this.resizeObserver) {
this.resizeObserver.disconnect();
}
if (this.debouncedResize && this.debouncedResize.cancel) {
this.debouncedResize.cancel();
}
}
setNextPrev() {
const navNode = this.props.getRef('nav');
const navTabsContainer = this.props.getRef('navTabsContainer');
const navNodeWH = this.getScrollWH(navTabsContainer || navNode);
// Add 1px to fix `offsetWidth` with decimal in Chrome not correct handle
// https://github.com/ant-design/ant-design/issues/13423
const containerWH = this.getOffsetWH(this.props.getRef('container')) + 1;
const navWrapNodeWH = this.getOffsetWH(this.props.getRef('navWrap'));
let { offset } = this;
const minOffset = containerWH - navNodeWH;
let { next, prev } = this.state;
if (minOffset >= 0) {
next = false;
this.setOffset(0, false);
offset = 0;
} else if (minOffset < offset) {
next = true;
} else {
next = false;
// Fix https://github.com/ant-design/ant-design/issues/8861
// Test with container offset which is stable
// and set the offset of the nav wrap node
const realOffset = navWrapNodeWH - navNodeWH;
this.setOffset(realOffset, false);
offset = realOffset;
}
if (offset < 0) {
prev = true;
} else {
prev = false;
}
this.setNext(next);
this.setPrev(prev);
return {
next,
prev,
};
}
getOffsetWH(node) {
const tabBarPosition = this.props.tabBarPosition;
let prop = 'offsetWidth';
if (tabBarPosition === 'left' || tabBarPosition === 'right') {
prop = 'offsetHeight';
}
return node[prop];
}
getScrollWH(node) {
const tabBarPosition = this.props.tabBarPosition;
let prop = 'scrollWidth';
if (tabBarPosition === 'left' || tabBarPosition === 'right') {
prop = 'scrollHeight';
}
return node[prop];
}
getOffsetLT(node) {
const tabBarPosition = this.props.tabBarPosition;
let prop = 'left';
if (tabBarPosition === 'left' || tabBarPosition === 'right') {
prop = 'top';
}
return node.getBoundingClientRect()[prop];
}
setOffset(offset, checkNextPrev = true) {
let target = Math.min(0, offset);
if (this.offset !== target) {
this.offset = target;
let navOffset = {};
const tabBarPosition = this.props.tabBarPosition;
const navStyle = this.props.getRef('nav').style;
const transformSupported = isTransformSupported(navStyle);
if (tabBarPosition === 'left' || tabBarPosition === 'right') {
if (transformSupported) {
navOffset = {
value: `translate3d(0,${target}px,0)`,
};
} else {
navOffset = {
name: 'top',
value: `${target}px`,
};
}
} else if (transformSupported) {
if (this.props.direction === 'rtl') {
target = -target;
}
navOffset = {
value: `translate3d(${target}px,0,0)`,
};
} else {
navOffset = {
name: 'left',
value: `${target}px`,
};
}
if (transformSupported) {
setTransform(navStyle, navOffset.value);
} else {
navStyle[navOffset.name] = navOffset.value;
}
if (checkNextPrev) {
this.setNextPrev();
}
}
}
setPrev(v) {
if (this.state.prev !== v) {
this.setState({
prev: v,
});
}
}
setNext(v) {
if (this.state.next !== v) {
this.setState({
next: v,
});
}
}
isNextPrevShown(state) {
if (state) {
return state.next || state.prev;
}
return this.state.next || this.state.prev;
}
prevTransitionEnd = (e) => {
if (e.propertyName !== 'opacity') {
return;
}
const container = this.props.getRef('container');
this.scrollToActiveTab({
target: container,
currentTarget: container,
});
}
scrollToActiveTab = (e) => {
const activeTab = this.props.getRef('activeTab');
const navWrap = this.props.getRef('navWrap');
if (e && e.target !== e.currentTarget || !activeTab) {
return;
}
// when not scrollable or enter scrollable first time, don't emit scrolling
const needToSroll = this.isNextPrevShown() && this.lastNextPrevShown;
this.lastNextPrevShown = this.isNextPrevShown();
if (!needToSroll) {
return;
}
const activeTabWH = this.getScrollWH(activeTab);
const navWrapNodeWH = this.getOffsetWH(navWrap);
let { offset } = this;
const wrapOffset = this.getOffsetLT(navWrap);
const activeTabOffset = this.getOffsetLT(activeTab);
if (wrapOffset > activeTabOffset) {
offset += (wrapOffset - activeTabOffset);
this.setOffset(offset);
} else if ((wrapOffset + navWrapNodeWH) < (activeTabOffset + activeTabWH)) {
offset -= (activeTabOffset + activeTabWH) - (wrapOffset + navWrapNodeWH);
this.setOffset(offset);
}
}
prev = (e) => {
this.props.onPrevClick(e);
const navWrapNode = this.props.getRef('navWrap');
const navWrapNodeWH = this.getOffsetWH(navWrapNode);
const { offset } = this;
this.setOffset(offset + navWrapNodeWH);
}
next = (e) => {
this.props.onNextClick(e);
const navWrapNode = this.props.getRef('navWrap');
const navWrapNodeWH = this.getOffsetWH(navWrapNode);
const { offset } = this;
this.setOffset(offset - navWrapNodeWH);
}
render() {
const { next, prev } = this.state;
const { clsPrefix,
scrollAnimated,
navWrapper,
prevIcon,
nextIcon,
} = this.props;
const showNextPrev = prev || next;
const prevButton = (
<span
onClick={prev ? this.prev : null}
unselectable="unselectable"
className={classnames({
[`${clsPrefix}-tab-prev`]: 1,
[`${clsPrefix}-tab-btn-disabled`]: !prev,
[`${clsPrefix}-tab-arrow-show`]: showNextPrev,
})}
onTransitionEnd={this.prevTransitionEnd}
>
{prevIcon || <span className={`${clsPrefix}-tab-prev-icon`} />}
</span>
);
const nextButton = (
<span
onClick={next ? this.next : null}
unselectable="unselectable"
className={classnames({
[`${clsPrefix}-tab-next`]: 1,
[`${clsPrefix}-tab-btn-disabled`]: !next,
[`${clsPrefix}-tab-arrow-show`]: showNextPrev,
})}
>
{nextIcon || <span className={`${clsPrefix}-tab-next-icon`} />}
</span>
);
const navClassName = `${clsPrefix}-nav`;
const navClasses = classnames({
[navClassName]: true,
[
scrollAnimated ?
`${navClassName}-animated` :
`${navClassName}-no-animated`
]: true,
});
return (
<div
className={classnames({
[`${clsPrefix}-nav-container`]: 1,
[`${clsPrefix}-nav-container-scrolling`]: showNextPrev,
})}
key="container"
ref={this.props.saveRef('container')}
>
{prevButton}
{nextButton}
<div className={`${clsPrefix}-nav-wrap`} ref={this.props.saveRef('navWrap')}>
<div className={`${clsPrefix}-nav-scroll`}>
<div className={navClasses} ref={this.props.saveRef('nav')}>
{navWrapper(this.props.children)}
</div>
</div>
</div>
</div>
);
}
}
ScrollableTabBarNode.propTypes = {
activeKey: PropTypes.string,
getRef: PropTypes.func.isRequired,
saveRef: PropTypes.func.isRequired,
tabBarPosition: PropTypes.oneOf(['left', 'right', 'top', 'bottom']),
clsPrefix: PropTypes.string,
scrollAnimated: PropTypes.bool,
onPrevClick: PropTypes.func,
onNextClick: PropTypes.func,
navWrapper: PropTypes.func,
children: PropTypes.node,
prevIcon: PropTypes.node,
nextIcon: PropTypes.node,
direction: PropTypes.node,
};
ScrollableTabBarNode.defaultProps = {
tabBarPosition: 'left',
clsPrefix: '',
scrollAnimated: true,
onPrevClick: () => { },
onNextClick: () => { },
navWrapper: (ele) => ele,
};
|
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import Alert from '@material-ui/lab/Alert';
import AlertTitle from '@material-ui/lab/AlertTitle';
//
import * as Utils from '../../../utils';
import AbstractComponent from '../AbstractComponent/AbstractComponent';
import Icon from '../Icon/Icon';
/**
* Alert box.
*
* @author Radek Tomiška
*/
class BasicAlert extends AbstractComponent {
constructor(props) {
super(props);
//
this.state = {
closed: false
};
}
_onClose(event) {
const { onClose } = this.props;
this.setState({
closed: true
}, () => {
if (onClose) {
onClose(event);
}
});
}
render() {
const {
level,
title,
text,
className,
icon,
onClose,
rendered,
showLoading,
children,
style,
buttons,
showHtmlText
} = this.props;
const { closed } = this.state;
if (!rendered || closed || (!text && !title && !children)) {
return null;
}
const classNames = classnames(
'alert',
'basic-alert',
{ 'text-center': showLoading },
className
);
if (showLoading) {
return (
<div className={ classNames } style={ style }>
<Icon type="fa" icon="refresh" showLoading/>
</div>
);
}
let _icon = null;
if (icon === false) { // icon can be disabled
_icon = false;
} else if (icon) {
_icon = (<Icon icon={ icon }/>);
}
//
return (
<Alert
severity={ Utils.Ui.toLevel(level) }
className={ classNames }
style={ style }
onClose={ onClose ? this._onClose.bind(this) : null }
icon={ _icon }>
{
!title
||
<AlertTitle>{ title }</AlertTitle>
}
{ showHtmlText ? <span dangerouslySetInnerHTML={{ __html: text}}/> : text }
{ children }
{
(!buttons || buttons.length === 0)
||
<div className="buttons">
{ buttons }
</div>
}
</Alert>
);
}
}
BasicAlert.propTypes = {
...AbstractComponent.propTypes,
/**
* Alert level / css / class
*/
level: PropTypes.oneOf(['success', 'warning', 'info', 'danger', 'error']),
/**
* Alert strong title content
*/
title: PropTypes.oneOfType([
PropTypes.string,
PropTypes.node
]),
/**
* Alert text content
*/
text: PropTypes.oneOfType([
PropTypes.string,
PropTypes.node
]),
/**
* glyphicon suffix name
*/
icon: PropTypes.string,
/**
* Close function - if it's set, then close icon is shown and this method is called on icon click
*/
onClose: PropTypes.func,
/**
* Alert action buttons
*/
buttons: PropTypes.arrayOf(PropTypes.node),
/**
* Show text as html (dangerouslySetInnerHTML)
*/
showHtmlText: PropTypes.bool
};
BasicAlert.defaultProps = {
...AbstractComponent.defaultProps,
level: 'info',
onClose: null,
buttons: [],
showHtmlText: false
};
export default BasicAlert;
|
var abbreviationBody = {
"SP": "Servicios Parlamentarios",
"SA": "Servicios Administrativos",
"SME": "Servicios Medicos y Esteticos",
"UT": "Unidad de Transferencia",
"CS": "Communicación Social",
"CI": "Controloría Interna",
"AS": "Auditoría Superior",
"IBD": "Instituto Belisario Dominguez",
"CC": "Canal de Congreso",
"MD": "Mesa Directiva",
"JCP": "Junta de Coordinación Politica",
"CO": "Comisión Ordinaria",
"CE": "Comisión Especial",
"CDI": "Comisión de Investigación",
"C": "Comité",
"GP": "Grupo Parlimentario",
"X": "No tiene categoría preasignada"
};
var abbreviationAreaOfGovernment = {
"S": "Senado",
"D": "Camera de Diputados"
};
var abbreviationExpenditure = {
"SGM": "Seguro de gastos médicos",
"PATM": "Pasajes aereos, terrestres, maritimos",
"G": "Gasolina",
"P": "Peaje",
"A": "Alimentos",
"H": "Hospedaje",
"PP": "Papeleria",
"EO": "Eventos Officiales",
"CP": "Comunicación y Publicidad",
"SB": "Servicios Basicos (luz, agua y telefono)",
"CRI": "Compra y Renta de Bienes Inmuebles",
"MR": "Mantenimiento y Reperación",
"MEO": "Mobiliario y Equipo de Oficina",
"V": "Vehiculos",
"SM": "Servicios Medico y de Laboritorio",
"SPC": "Servicos Profesionales y Cientificos",
"TS": "Transferecias al Sindicato",
"DA": "Donativos, Ayudas Sociales y Transferencias al Extranjero",
"VB": "Vestuario, Blancos, Articulos Deportivos",
"BA": "Bienes Artisticos y Culturales",
"X": "No tiene categoría preasignada"
};
var abbrevationLegislature = {
"62": "Legislatura 62",
"63": "Legislatura 63",
"64": "Legislatura 64"
};
$(document).ready(function () {
// Convert radio buttons into groups of toggle buttons.
convertRadioButtonsToToggle();
// Build the bxSlider
buildSlider();
// When we click "Other", the field for Other text should be activated
disableButtonWhenClickingOther();
// Customize navigating through slides so we have the "Submit button" in the last slide
var slider = customSlideNavigationFunctions();
// Add form enhancements
// When hovering in the "?" after a field, show the help-text as a tooltip.
buildToolTipText();
buildDateButton();
// When a user can't read the data in the PDF he can click "Can't read" link and disable that field.
addCantReadLink();
// Construct the category section
addDynamicPriceFields();
$("#purple-header").css('display', 'none');
$(".header-white-space").css('display', 'none');
$(document).on('click', '#submitForm', function (e) {
$("[id^='qtip']").css('display', 'none');
$('#document-viewer-container').parent().remove();
$('#social_document').parent().parent().removeClass();
$('#social_document').parent().parent().addClass('col-md-12');
$("#purple-header").css('display', '');
$(".header-white-space").css('display', '');
$("#header-text").css('display', 'none');
$("#the-logo").css('margin-top', '110px');
$("#the-logo").css('float', 'left');
$("#the-logo").css('position', 'absolute');
$("#the-logo").css('margin-left', '0px');
});
constructCategory();
// Design address slide.
$('input#id_address2_domiscilio_fiscal_del_emisor').parent().parent().append("<p id='domicilio-fiscio-2'>Domicilio físico del emisor <span class='helper-block glyphicon glyphicon-question-sign' data-toggle='tooltip' data-placement='top' title='Es la dirección donde está ubicado la empresa o sucursal de ésta que expidió la factura, generalmente se ubica cerca de la razón social y el RFC' aria-hidden='true' data-original-title='ga'></span></p><input id='same-as-above-address' type='checkbox' name='same-as-above-address' value='Bike'><p id='same-as-above-address-text'>Igual que el anterior</p>");
buildAddressSlideFunctionality();
// Adding the Helper Texts under the slide titles.
$('.paso-1-de-5').append('<p>En este paso verificamos que la categoría de gasto preasignada a la factura sea correcta. Si es necesario, añadimos una categoría secundaria porque el documento contiene más de un tipo gasto.</p>');
$('.paso-2-de-5').append('<p>Aquí registramos la cantidad total facturada; es decir, la suma que incluye el IVA. </p>');
$('.paso-3-de-5').append('<p>Estos datos parecen aburridos, pero son importates para saber si los legisladores transfieren dinero a sus empresas.</p><p>Aquí capturamos la fecha en que se emitió la factura y los datos de quien la emitió.</p>');
$('.paso-4-de-5').append('<p>En este paso ubicamos físicamente a la empresa y/o la sucursal que emitió la factura. Ayúdanos a capturar todos los datos que componen la dirección. </p>');
$('.paso-5-de-5').append('<p>¿Notaste algo extraño en la factura? ¿El precio pagado por un producto o servicio es elevado? ¿El gasto te parece inúti u ofensivo (vino, motocicletas deportivas, spa, fragancias, bares y cantinas, etcétera)? ¿El emisor de la factura es un político famoso o que tú recuerdas? ¡Anótalo! Investigaremos todo lo que te resulte sospechoso.</p>');
// Adding can't read buttons in the forth slide
$('.paso-4-de-5-direccin').append('<a id="cant-read-second-address" class="qc-btn qc-btn-cant-read">Ilegible</a>');
$('.paso-4-de-5-direccin').append('<a id="cant-undo-second-address" class="qc-btn qc-btn-undo" style="display: block;">Deshacer</a>');
$('.paso-4-de-5-direccin').append('<a id="cant-read-first-address" class="qc-btn qc-btn-cant-read">Ilegible</a>');
$('.paso-4-de-5-direccin').append('<a id="cant-undo-first-address" class="qc-btn qc-btn-undo" style="display: block;">Deshacer</a>');
// Word count in slide 5
$('.paso-5-de-5-hay-algo-raro').append('<div class="laWordCount">Te quedan <span id="display_count">500</span> de máximo <span id="word_left">500</span> caracteres.</div>')
$("textarea[name='did_anything_seem_strange_on_this_factura']").attr('maxlength', '500');
$("textarea[name='did_anything_seem_strange_on_this_factura']").on('keyup', function () {
var length = $(this).val().length;
if (length <= 500) {
$('#display_count').text(500 - $(this).val().length);
}
});
$('#del-recibo').prepend('<div class="candidad-helper-text">También capturamos concepto por concepto. Si te resulta más fácil, puedes resumir. Ejemplo: En lugar de escribir el título completo de un libro, puedes colocar la palabra "Libro". <br>Esta sección es opcional, pero considera que contar con información más precisa sobre los gastos de los políticos nos da a los ciudadanos mayor control sobre ellos.</div>');
$('#chooseCategory').prepend('<div id="category-tooltip">' + $('.form-group input[name=detallesdelafactura]').parent()[0].children[1].outerHTML + '</div>');
$('.helper-block').tooltip({delay: 0});
$('.paso-5-de-5-hay-algo-raro').append('<a id="submit-el-forma" class="qc-btn qc-btn-submit">Enviar</a>');
$('.paso-5-de-5-hay-algo-raro .form-group #cant_read_container').css('display', 'none');
$('#cant-undo-first-address').css('display', "none");
$('#cant-undo-second-address').css('display', "none");
$('#cant-read-first-address').click(function () {
$('input[name^=address1]').each(function () {
$(this).attr('disabled', 'true');
$('#cant-undo-first-address').css('display', "");
});
});
$('#cant-read-second-address').click(function () {
$('input[name^=address2]').each(function () {
$(this).attr('disabled', 'true');
$('#cant-undo-second-address').css('display', "");
});
});
$('#cant-undo-second-address').click(function () {
$('input[name^=address2]').each(function () {
$(this).removeAttr('disabled');
$('#cant-undo-second-address').css('display', "none");
});
});
$('#cant-undo-first-address').click(function () {
$('input[name^=address1]').each(function () {
$(this).removeAttr('disabled');
$('#cant-undo-first-address').css('display', "none");
});
});
$("#elForm").submit(function (event) {
event.preventDefault();
});
$(document).on('change', '#id_razon_social_del_emisor', function (e) {
$('input[name=razon_social_del_emisor]')[0].value = $('input[name=razon_social_del_emisor]')[1].value;
});
$(document).on('change', '#id_nombre_comerical_de_emisor', function (e) {
$('input[name=nombre_comerical_de_emisor]')[0].value = $('input[name=nombre_comerical_de_emisor]')[1].value;
});
$(document).on('change', '#id_rfc_del_emisor', function (e) {
$('input[name=rfc_del_emisor]')[0].value = $('input[name=rfc_del_emisor]')[1].value;
});
// Save address1 values
$(document).on('change', '#id_address1_calle', function (e) {
$('input[name=address1_calle]')[0].value = $('input[name=address1_calle]')[1].value;
});
$(document).on('change', '#id_address1_nnext', function (e) {
$('input[name=address1_nnext]')[0].value = $('input[name=address1_nnext]')[1].value;
});
$(document).on('change', '#id_address1_nint', function (e) {
$('input[name=address1_nint]')[0].value = $('input[name=address1_nint]')[1].value;
});
$(document).on('change', '#id_address1_colonia', function (e) {
$('input[name=address1_colonia]')[0].value = $('input[name=address1_colonia]')[1].value;
});
$(document).on('change', '#id_address1_municipio_o_delegacion', function (e) {
$('input[name=address1_municipio_o_delegacion]')[0].value = $('input[name=address1_municipio_o_delegacion]')[1].value;
});
$(document).on('change', '#id_address1_codigo_postal', function (e) {
$('input[name=address1_codigo_postal]')[0].value = $('input[name=address1_codigo_postal]')[1].value;
});
$(document).on('change', '#id_address1_estado', function (e) {
$('input[name=address1_estado]')[0].value = $('input[name=address1_estado]')[1].value;
});
// Save address2 values
$(document).on('change', '#id_address2_calle', function (e) {
$('input[name=address2_calle]')[0].value = $('input[name=address2_calle]')[1].value;
});
$(document).on('change', '#id_address2_nnext', function (e) {
$('input[name=address2_nnext]')[0].value = $('input[name=address2_nnext]')[1].value;
});
$(document).on('change', '#id_address2_nint', function (e) {
$('input[name=address2_nint]')[0].value = $('input[name=address2_nint]')[1].value;
});
$(document).on('change', '#id_address2_colonia', function (e) {
$('input[name=address2_colonia]')[0].value = $('input[name=address2_colonia]')[1].value;
});
$(document).on('change', '#id_address2_municipio_o_delegacion', function (e) {
$('input[name=address2_municipio_o_delegacion]')[0].value = $('input[name=address2_municipio_o_delegacion]')[1].value;
});
$(document).on('change', '#id_address2_codigo_postal', function (e) {
$('input[name=address2_codigo_postal]')[0].value = $('input[name=address2_codigo_postal]')[1].value;
});
$(document).on('change', '#id_address2_estado', function (e) {
$('input[name=address2_estado]')[0].value = $('input[name=address2_estado]')[1].value;
});
// Save the comment in the end of the form
$(document).on('change', '#id_did_anything_seem_strange_on_this_factura', function (e) {
$('textarea[name=did_anything_seem_strange_on_this_factura]')[0].value = $('textarea[name=did_anything_seem_strange_on_this_factura]')[1].value;
});
$(document).on('change', '#same-as-above-address'), function (e) {
$('input[name=address2_calle]')[0].value = $('input[name=address2_calle]')[1].value;
$('input[name=address2_nnext]')[0].value = $('input[name=address2_nnext]')[1].value;
$('input[name=address2_nint]')[0].value = $('input[name=address2_nint]')[1].value;
$('input[name=address2_colonia]')[0].value = $('input[name=address2_colonia]')[1].value;
$('input[name=address2_municipio_o_delegacion]')[0].value = $('input[name=address2_municipio_o_delegacion]')[1].value;
$('input[name=address2_codigo_postal]')[0].value = $('input[name=address2_codigo_postal]')[1].value;
$('input[name=address2_estado]')[0].value = $('input[name=address2_estado]')[1].value;
};
//gather all inputs of selected types
var inputs = $('.qc-btn-select-other-optional-category, .precio, #id_rfc_del_emisor, #id_address2_estado');
keyDownFieldsPatch();
//bind on keydown
inputs.on('keydown', function(e) {
//if we pressed the tab
if (e.keyCode == 9 || e.which == 9) {
$('.bx-next').click();
e.preventDefault();
}
});
});
function keyDownFieldsPatch(){
$('input#id_address1_calle').on('keydown', function(e) {
//if we pressed the tab
if (e.keyCode == 9 || e.which == 9) {
$('input#id_address1_nint').focus();
e.preventDefault();
}
});
$('input#id_address1_colonia').on('keydown', function(e) {
//if we pressed the tab
if (e.keyCode == 9 || e.which == 9) {
$('input#id_address1_nnext').focus();
e.preventDefault();
}
});
$('input#id_address1_nnext').on('keydown', function(e) {
//if we pressed the tab
if (e.keyCode == 9 || e.which == 9) {
$('input#id_address1_municipio_o_delegacion').focus();
e.preventDefault();
}
});
$('input#id_address2_nnext').on('keydown', function(e) {
//if we pressed the tab
if (e.keyCode == 9 || e.which == 9) {
$('input#id_address2_municipio_o_delegacion').focus();
e.preventDefault();
}
});
$('input#id_address2_calle').on('keydown', function(e) {
//if we pressed the tab
if (e.keyCode == 9 || e.which == 9) {
$('input#id_address2_nint').focus();
e.preventDefault();
}
});
$('input#id_address2_colonia').on('keydown', function(e) {
//if we pressed the tab
if (e.keyCode == 9 || e.which == 9) {
$('input#id_address2_nnext').focus();
e.preventDefault();
}
});
$('input#id_address2_nnext').on('keydown', function(e) {
//if we pressed the tab
if (e.keyCode == 9 || e.which == 9) {
$('input#id_address2_municipio_o_delegacion').focus();
e.preventDefault();
}
});
}
function buildDateButton(){
var date_picker_container = $('#zgjedhesi-dates').html();
var data = $('.datefield').parent();
$('#zgjedhesi-dates').css('display', 'none');
$('.datefield').parent().children().css('display', 'none');
data.append(date_picker_container);
$('.dateti').datetimepicker({
widgetPositioning:{
vertical: 'bottom'
},
format:"DD/MM/YYYY"
});
$('.fecha_de_facturaciono').each(function(idx){
$(this).parent().parent().bind('click', function() {
var fecha_date = $('input[name=fecha_de_facturaciono]')[1].value.split('/');
fecha_date = fecha_date[2] + "-" + fecha_date[1] + "-" +fecha_date[0];
$('.datefield')[1].val = fecha_date;
$('.datefield')[1].value = fecha_date;
$('.datefield')[0].val = fecha_date;
$('.datefield')[0].value = fecha_date;
});
});
}
function buildAddressSlideFunctionality() {
$('input[name="same-as-above-address"]').change(function () {
if ($(this)['context'].checked == true) {
$('input[name="address2_calle"]')[1].value = $('input[name="address1_calle"]')[1].value;
$('input[name="address2_nnext"]')[1].value = $('input[name="address1_nnext"]')[1].value;
$('input[name="address2_nint"]')[1].value = $('input[name="address1_nint"]')[1].value;
$('input[name="address2_colonia"]')[1].value = $('input[name="address1_colonia"]')[1].value;
$('input[name="address2_municipio_o_delegacion"]')[1].value = $('input[name="address1_municipio_o_delegacion"]')[1].value;
$('input[name="address2_codigo_postal"]')[1].value = $('input[name="address1_codigo_postal"]')[1].value;
$('input[name="address2_estado"]')[1].value = $('input[name="address1_estado"]')[1].value;
}
else {
$('input[name="address2_calle"]')[1].value = "";
$('input[name="address2_nnext"]')[1].value = "";
$('input[name="address2_nint"]')[1].value = "";
$('input[name="address2_colonia"]')[1].value = "";
$('input[name="address2_municipio_o_delegacion"]')[1].value = "";
$('input[name="address2_codigo_postal"]')[1].value = "";
$('input[name="address2_estado"]')[1].value = "";
}
});
}
function constructCategory() {
var documentViewer = $('#document-viewer-container').children()[0].data.split('/');
var documentNameArray = documentViewer[documentViewer.length - 1].split('_');
$('.paso-1-de-5-tipo-de-gasto div.form-group').css('display', 'none');
var fatura_details_icon_url = "";
if (abbreviationAreaOfGovernment[documentNameArray[0]] == "Senado") {
fatura_details_icon_url = "/static/img/QC_Icon_01_Senato.svg";
} else {
fatura_details_icon_url = "/static/img/QC_Icon_01_Parliament.svg";
}
var category_icon_url = '';
$('.paso-1-de-5-tipo-de-gasto').append('<br><div class="category_info"></div>');
$('.category_info').append("<div id='factura-details-title'>Detalles de la factura</div><div id='facturaDetails'></div>");
$('#facturaDetails').append('<table style="width:100%; border:1px solid purple;" >' +
'<tr>' +
'<td style="width: 90px; border:1px solid purple;"><div id="senato"><img style="float:left;" src="' + fatura_details_icon_url + '"></td>' +
' <td style="background:rgba(128,0,128,0.1);" rowspan="2"><div id="legislature"><p>' + abbrevationLegislature[documentNameArray[1]] + '</p></div><br><div id="abbreviationBody"><br><p > ' + abbreviationBody[documentNameArray[2]] + '</p></div></td>' +
'</tr>' +
'<tr >' +
'<td><p id="abbreviationAreaOfGovernment">' + abbreviationAreaOfGovernment[documentNameArray[0]] + '</p></td>' +
'</tr>' +
'</table>');
$('.category_info').append("<div id='chooseCategory'><br/><br/><p>La categoría asignada a esta factura es </p><span><img id='category-icon-image' style='float:left;' src='" + getCategoryIcon(abbreviationExpenditure[documentNameArray[3]]) + "'><h1 id='category-icon-name'>" + abbreviationExpenditure[documentNameArray[3]] + "</h1></span></div>");
$('#chooseCategory').append("<div class='es-incorrecta'><span class='doesnt-look-right'>¿Es incorrecta?</span> <a href='' class='qc-btn qc-btn-select-other-category' data-toggle='modal' data-target='#myModal'>Selecciona otra categoría</a></div><br/><br/><div class='optional_category'></div>");
$('.optional_category').append("<p>Opcional </p><div id='chooseOptionalCategory'><span><img id='category-optional-icon-image' src='/static/img/icons/blank-category.svg'></span></div>");
$('#chooseOptionalCategory').append("<div class='add-second-category'><p id='optionalCategoryText'>Asigna una categoría secundaria</p><br><br><div class=''><a href class='qc-btn qc-btn-select-other-optional-category' data-toggle='modal' data-target='#myOptionalModal'>Agregar</a></div> </div><br/><br/><br/><br/><br/><br/><br/><br/>");
$("input[name='abbrevationlegislature']").val(abbrevationLegislature[documentNameArray[1]]);
$("input[name='abbreviationexpenditure']").val(abbreviationExpenditure[documentNameArray[3]]);
$("input[name='abbreviationareaofgovernment']").val(abbreviationAreaOfGovernment[documentNameArray[0]]);
$("input[name='abbreviationbody_val']").val(abbreviationBody[documentNameArray[2]]);
$(".qc-btn-change-cat").click(function () {
var otraCategoriaValue = $('#otherOptionalCategoryValue').val();
$("input[name='abbreviationexpenditure']").val(otraCategoriaValue);
$("#category-icon-image").attr('src', "/static/img/icons/blank-category.svg");
$('#category-icon-name').text(otraCategoriaValue);
$('.modal').modal('hide');
});
$(".qc-btn-change-optional-cat").click(function () {
var otraOptionalCategoriaValue = $('#otherSecondaryOptionalCategoryValue').val();
$("input[name='abbreviationexpenditureoptional']").val(otraOptionalCategoriaValue);
$('#optionalCategoryText').text(otraOptionalCategoriaValue);
$("#category-optional-icon-image").attr('src', "/static/img/icons/blank-category.svg");
$('.modal').modal('hide');
});
$(".image-category-icon").hover(
function () {
var image_url = $(this).children().attr('src');
if (image_url != undefined) {
var replaced_url = image_url.replace(/(\.[\w\d_-]+)$/i, '_Hover$1');
$(this).children().attr('src', replaced_url);
$(this).addClass('selected');
var categoryName = image_url.split('_')[2].replace(/%20/g, ' ').replace('.svg', '');
$(this).click(function () {
$("input[name='abbreviationexpenditure']").val(categoryName);
$('.modal').modal('hide');
$("#category-icon-image").attr('src', image_url);
$('#category-icon-name').text(categoryName);
});
}
}, function () {
var image_url = $(this).children().attr('src');
if (image_url != undefined) {
var replaced_url = image_url.replace('_Hover', '');
$(this).children().attr('src', replaced_url);
$(this).removeClass('selected');
}
});
$(".image-optional-category-icon").hover(
function () {
var image_url = $(this).children().attr('src');
if (image_url != undefined) {
var replaced_url = image_url.replace(/(\.[\w\d_-]+)$/i, '_Hover$1');
$(this).children().attr('src', replaced_url);
$(this).addClass('selected');
var categoryName = image_url.split('_')[2].replace(/%20/g, ' ').replace('.svg', '');
$(this).click(function () {
$("input[name='abbreviationexpenditureoptional']").val(categoryName);
$('.modal').modal('hide');
$("#category-optional-icon-image").attr('src', image_url);
$('#optionalCategoryText').text(categoryName);
});
}
}, function () {
var image_url = $(this).children().attr('src');
if (image_url != undefined) {
var replaced_url = image_url.replace('_Hover', '');
$(this).children().attr('src', replaced_url);
$(this).removeClass('selected');
}
});
}
function getCategoryIcon(category) {
return "/static/img/category/QC_Icon_" + category.replace(/ /g, '%20') + ".svg";
}
function addDynamicPriceFields() {
$("span[id^='total_sum_number']").autoNumeric('init');
var candidad_class = $('.paso-2-de-5-cantidad-total div.form-group').css('display', 'none');
$('.paso-2-de-5-cantidad-total').append('<div id="precio-group"><div id="totalCon">Total con IVA</div><div id="totalInput"><input tabindex="-1" type="text" name="totalPrecioValue"/><span id="dollar-sign"> $</span></div></div>')
$('.paso-2-de-5-cantidad-total').append('<p class="optional">Opcional</p><div id="del-recibo"></div>');
$('#del-recibo').append('<div style="height:30px;display:inline;">' +
'<p style="border-color: purple;width:30%;float:left;">Descripción' +
'</p>' +
'<p style="width:20%;float:left;">Cantidad</p><p style="width:20%;float:left;">Precio</p><p style="width:20%;float:left;">Total</p></div>' +
'<form class="form-inline"><div class="form-group" >' +
' <div class="form-group"> ' +
'<label class="sr-only" for="description">Descripción:</label>' +
'<input type="text" style="width: 150px;float:left; border-color: purple;" name="description" class="form-control description" id="description-0"/></div>' +
' <div class="form-group"> ' +
'<label class="sr-only" for="cantidad">Cantidad:</label>' +
'<input type="number" style=" margin-left: 10px;width: 50px;border-color: purple;" name="cantidad" class="form-control cantidad_number" id="cantidad-0"/></div>' +
' <div class="form-group"> ' +
'<label class="sr-only" for="precio">Precio:</label>' +
'<input type="text" style=" margin-left: 10px; border-color: purple;" name="precio" class="form-control precio" id="precio-0"/></div>' +
' <div class="form-group"> ' +
'<div id="total_sum-0"> = $ <span id="total_sum_number-0">0</span> </div></div>' +
'</div>' +
'');
$('#del-recibo').append('<div id="grande_total_receipt_add"><a style="float:left;" class="qc-btn qc-btn-add-receipt-item" >Agregar otro concepto</a>' +
'<br/><br/><br/>');
var index = 1;
$(document).on('click', '.qc-btn-add-receipt-item', function (e) {
//do whatever
if (index < candidad_class.length) {
$('.qc-btn-add-receipt-item').remove();
$('#grande_total_receipt_add').remove();
$('#del-recibo').append('<form class="form-inline"><div class="form-group" >' +
' <div class="form-group"> ' +
'<label class="sr-only" for="description">Description:</label>' +
'<input style="width: 150px;float:left; border-color: purple;" style="float:left;" type="text" name="description" class="form-control description" id="description-' + index + '"/></div>' +
' <div class="form-group"> ' +
'<label class="sr-only" for="cantidad">Cantidad:</label>' +
'<input type="number" style=" margin-left: 10px;width: 50px;border-color: purple;" name="cantidad" class="form-control cantidad_number" id="cantidad-' + index + '"/></div>' +
' <div class="form-group"> ' +
'<label class="sr-only" for="precio">Precio:</label>' +
'<input type="text" style=" margin-left: 10px; border-color: purple;" name="precio" class="form-control precio" id="precio-' + index + '"/></div>' +
' <div class="form-group"> ' +
'<div id="total_sum-' + index + '"> = $ <span id="total_sum_number-' + index + '">0</span></div></div>' +
'</div></form>');
$('#del-recibo').append('<div id="grande_total_receipt_add"><a style="float:left;" class="qc-btn qc-btn-add-receipt-item">Agregar otro concepto</a>' +
'<br/><br/><br/>');
$('input[name="precio"]').autoNumeric('init');
$('*[id^="total_sum_number"]').autoNumeric('init', {});
}
index = index + 1;
});
$("input[name='totalPrecioValue']").change(function () {
$("input[name='total_con_iva']").val($(this).val().replace(/,/g, ''));
});
$(document).on('change', '.cantidad_number', function (e) {
var grande_totale = 0;
var cantidad_id = this.id;
var value = $(this).val();
//do whatever
var number_of_element = this.id.replace(/^\D+/g, '');
var total_selector_name = '#total_sum_number-' + number_of_element;
var value_of_all = $('#cantidad-' + number_of_element).val() * parseFloat($('#precio-' + number_of_element).val().replace(',', ''));
var receipt_item_id = "receiptitem-" + number_of_element;
if (number_of_element == 0) {
$("input[name='receiptitem']").val($('#description-' + number_of_element).val() + "|" + $('#cantidad-' + number_of_element).val() + "|" + $('#precio-' + number_of_element).val());
} else {
$("input[name='" + receipt_item_id + "']").val($('#description-' + number_of_element).val() + "|" + $('#cantidad-' + number_of_element).val() + "|" + $('#precio-' + number_of_element).val());
}
$('*[id^="total_sum_number"]').each(function () {
grande_totale = grande_totale + parseFloat(this.innerText.replace(/^\D+/g, ''));
});
$('*[id^="total_sum_number"]').autoNumeric('init');
$(total_selector_name).autoNumeric('set', value_of_all);
});
$(document).on('change', '.precio', function (e) {
var grande_totale = 0;
var precio_id = this.id;
var value = $(this).val();
//do whatever
var number_of_element = precio_id.replace(/^\D+/g, '');
var total_selector_name = '#total_sum_number-' + number_of_element;
var value_of_alla = $('#cantidad-' + number_of_element).val() * parseFloat($('#precio-' + number_of_element).val().replace(',', ''));
var receipt_item_id = "receiptitem-" + number_of_element;
if (number_of_element == 0) {
$("input[name='receiptitem']").val($('#description-' + number_of_element).val() + "|" + $('#cantidad-' + number_of_element).val() + "|" + $('#precio-' + number_of_element).val());
} else {
$("input[name='" + receipt_item_id + "']").val($('#description-' + number_of_element).val() + "|" + $('#cantidad-' + number_of_element).val() + "|" + $('#precio-' + number_of_element).val());
}
$('[id^="total_sum_number"]').each(function () {
grande_totale = grande_totale + parseFloat(this.innerText.replace(/^\D+/g, ''));
});
$('*[id^="total_sum_number"]').autoNumeric('init');
$(total_selector_name).autoNumeric('set', value_of_alla);
});
$('input[name="totalPrecioValue"]').autoNumeric('init');
$('input[name^="precio"]').autoNumeric('init');
$('*input[name^="total_sum_number"]').autoNumeric('init');
}
function addCantReadLink() {
$('.form-group').each(function () {
var cant_read_container = document.createElement('div');
cant_read_container.id = "cant_read_container";
var cant_read = document.createElement('a');
cant_read.setAttribute("class", "qc-btn qc-btn-cant-read");
cant_read.innerHTML = "Ilegible";
var undo = document.createElement('a');
undo.innerHTML = "Deshacer";
undo.setAttribute("class", "qc-btn qc-btn-undo");
cant_read_container.appendChild(cant_read);
cant_read_container.appendChild(undo);
this.appendChild(cant_read_container);
});
$('.qc-btn-undo').css('display', 'none');
$('.qc-btn-cant-read').click(function () {
if ($(this).parent().parent().children('input').length > 0) {
$(this).parent().parent().children('input').prop('disabled', true);
$(this).parent().parent().find('.dateti').children('input').prop('disabled', true);
$(this).parent().find('.qc-btn-undo').css('display', 'block');
}
else if ($(this).parent().parent().children('textarea').length > 0) {
$(this).parent().parent().children('textarea').prop('disabled', true);
$(this).parent().find('.qc-btn-undo').css('display', 'block');
} else if ($(this).parent().parent().children('text').length > 0) {
$(this).parent().parent().children('text').prop('disabled', true);
$(this).parent().find('.qc-btn-undo').css('display', 'block');
} else if ($(this).parent().parent().children().children('input').length > 0) {
$(this).parent().parent().children().children('input').prop('disabled', true);
$(this).parent().parent().children().children('input').css('background', "#dddddd")
$(this).parent().find('.qc-btn-undo').css('display', 'block');
}
});
$('.qc-btn-undo').click(function () {
if ($(this).parent().parent().children('input').length > 0) {
$(this).parent().parent().children('input').prop('disabled', false);
$(this).parent().parent().find('.dateti').children('input').prop('disabled', false);
$(this).parent().find('.qc-btn-undo').css('display', 'none');
}
else if ($(this).parent().parent().children('textarea').length > 0) {
$(this).parent().parent().children('textarea').prop('disabled', false);
$(this).parent().find('.qc-btn-undo').css('display', 'none');
} else if ($(this).parent().parent().children('text').length > 0) {
$(this).parent().parent().children('text').prop('disabled', false);
$(this).parent().find('.qc-btn-undo').css('display', 'none');
} else if ($(this).parent().parent().children().children('input').length > 0) {
$(this).parent().parent().children().children('input').prop('disabled', false);
$(this).parent().parent().children().children('input').css('background', "#fff")
$(this).parent().find('.qc-btn-undo').css('display', 'none');
}
});
}
function customSlideNavigationFunctions() {
var slider = $('.bxslideri').bxSlider({
infiniteLoop: false,
hideControlOnEnd: true,
pager: true,
responsive: true
});
$('.bx-next').click(function () {
slider.goToNextSlide();
navigatedToLastSlide(slider);
return false;
});
$('.bx-prev').click(function () {
slider.goToPrevSlide();
navigatedToLastSlide(slider);
return false;
});
$(".bx-pager-link").click(function () {
var slideData = $(this).data();
if (slideData.slideIndex == slider.getSlideCount() - 1) {
addSubmitButtonLastSlide();
} else {
removeSubmitButtonLastSlide();
}
});
return slider;
}
function disableButtonWhenClickingOther() {
$("input[name='other_category']").prop('disabled', true);
$("input[name='other_part_of_government_thats_responsible']").prop('disabled', true);
$('.choicefield').change(function () {
if ($('.choicefield#id_part_of_government_thats_responsible_7').is(':checked')) {
$("input[name='other_part_of_government_thats_responsible']").prop('disabled', false);
} else {
$("input[name='other_part_of_government_thats_responsible']").prop('disabled', true);
}
if ($('.choicefield#id_category_13').is(':checked')) {
$("input[name='other_category']").prop('disabled', false);
} else {
$("input[name='other_category']").prop('disabled', true);
}
});
}
function convertRadioButtonsToToggle() {
$("#elForm input:radio").parent().parent().parent().addClass("btn-group");
$("#elForm input:radio").parent().parent().addClass("btn checkbox-btn ");
$("#elForm input:radio").parent().parent().parent().attr("data-toggle", "buttons");
$("#elForm input:radio").parent().parent().css('width', '45%').css('border', '1px solid white');
$('input:radio').toggle();
$('[id*="radio-popup-style-"]').click(function () {
$(this).prop('checked', true).parent().addClass('active');
$('[id*="radio-popup-style-"]').not($(this)).removeAttr('checked').prop('checked', false).parent().removeClass('active');
});
}
function navigatedToLastSlide(slider) {
var numberOfSlides = slider.getSlideCount() - 1;
var navigatedToLastSlide = false;
if (slider.getCurrentSlide() == numberOfSlides) {
navigatedToLastSlide = true;
}
if (navigatedToLastSlide == true) {
addSubmitButtonLastSlide();
}
else {
removeSubmitButtonLastSlide();
}
return navigatedToLastSlide;
}
function addSubmitButtonLastSlide() {
$('.bx-wrapper .bx-controls-direction a').children().eq(1).remove();
// First we check if there is a submit button added
// Doing this so we don't end up adding buttons everytime we click the slide controlls.
if ($('.bx-wrapper .bx-controls-direction').has('button').length == 0) {
} else {
$('.bx-wrapper .bx-controls-direction button').remove();
}
}
function removeSubmitButtonLastSlide() {
// This function should be called only when you need to remove the submit button which comes
// instead of the arrow in the slides.
$('.bx-wrapper .bx-controls-direction button').remove();
}
function buildSlider() {
// Get all the elements that have class="sections"
var groupOfElements = document.getElementsByClassName('sections');
// Declare the empty array to later fill with the sections names
var allSections = [];
// Save the names of the sections
for (i = 0; i < groupOfElements.length; i++) {
allSections[i] = slugify(jQuery.trim(groupOfElements[i].attributes.id.nodeValue));
}
// Get distinct section values
var uniqueSections = allSections.filter(function (itm, i, allSections) {
return i == allSections.indexOf(itm);
});
// Group and render the fields in slide mode
for (var i = 0; i < groupOfElements.length; i++) {
for (var j = 0; j < uniqueSections.length; j++) {
if (slugify(jQuery.trim(groupOfElements[i].attributes.id.nodeValue)) == uniqueSections[j]) {
if ($("." + uniqueSections[j]).length > 0) {
// Adding other elements of the group(section)
$('.' + uniqueSections[j]).append('<div class="form-group">' + groupOfElements[i].innerHTML + '</div>');
}
else {
// If we are showing the first element of the form group(section) we are showing the tittle too.
var slide_title = groupOfElements[i].id.split(":");
$(".bxslideri").append('<li class="' + uniqueSections[j] + '">' + '<div class="title-of-slide"><span class="slide-first-title">' + slide_title[0] + ':</span>' + '<span class="slide-title">' + slide_title[1] + '</span></div>' + '<div class="' + slugify(slide_title[0]) + '">' + '</div>' + '<div class="form-group">' + getFormElement(groupOfElements[i]) + '</div></li>');
}
}
}
}
}
function getFormElement(element) {
return element.innerHTML;
}
// Slugify the strings
function slugify(text) {
return text.toString().toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
}
function buildToolTipText() {
$('.help-block').each(function () {
if (this.innerHTML != "") {
$(this).attr('data-toggle', 'tooltip');
$(this).attr('data-placement', 'top');
$(this).attr('title', "" + this.innerHTML + "");
$(this).attr('class', 'helper-block glyphicon glyphicon-question-sign');
$(this).attr('aria-hidden', 'true');
this.innerText = "";
this.innerHTML = "";
$(this).innerText = "";
} else {
$(this).attr("style", "display:none;");
}
});
}
|
var ColorSet = require('./colorset');
var Color = require('./_color');
var Lut = function(colors, delegates) {
ColorSet.call(this, delegates);
Object.defineProperties(this, {
'_values' : { value: {} } });
for (var name in colors) {
if (colors.hasOwnProperty(name)) {
this._values[this.normalizeName(name)] = Color.create(colors[name]);
}
}
};
Lut.prototype = new ColorSet();
Lut.prototype.constructor = Lut;
/**
* Create a new color set.
*/
Lut.create = function(colors) {
return new Lut(colors, []);
};
/**
* Convert a color name to the name used for storage.
*/
Lut.prototype.normalizeName = function(name) {
return (name + '').toLowerCase().trim();
};
/**
* Lookup a color by name.
*
* Returns undefined no such color exists.
*/
Lut.prototype.getOwn = function(name) {
return this._values[this.normalizeName(name)];
};
module.exports = Lut; |
import { createGlobalStyle } from 'styled-components';
export const GlobalStyle = createGlobalStyle`
@import url("https://use.typekit.net/sjl7giv.css");
* {
box-sizing: border-box;
}
html, body {
margin: 0;
padding: 0;
color: #1c1c1c;
background-color: #ffffff;
font-size: 16px;
font-family: 'proxima-nova', helvetica, arial, clean, sans-serif;
}
h1, h2, h3, h4, h5, h6 {
font-size: 100%;
}
h1 {
margin-bottom: 1em
}
h2 {
font-size: 1.2rem
}
h4 {
margin-top: 2rem
}
a {
color: #4078c0;
text-decoration: underline;
}
code {
font-size: 14px !important;
}
li {
margin-bottom: calc(1.45rem / 2);
line-height: 1.5;
}
ol li {
padding-left: 0;
}
ul li {
padding-left: 0;
}
li > ol {
margin-left: 1.45rem;
margin-bottom: calc(1.45rem / 2);
margin-top: calc(1.45rem / 2);
}
li > ul {
margin-left: 1.45rem;
margin-bottom: calc(1.45rem / 2);
margin-top: calc(1.45rem / 2);
}
figcaption {
text-align: center;
margin: 0;
padding: 0;
padding-top: 0.2rem;
font-size: 0.75rem;
}
img {
object-fit:cover;
object-position:center;
}
`;
|
var mongoose = require('mongoose');
module.exports = {
connect: function(){
mongoose.connect('mongodb://localhost/socialwave');
}
}; |
Nehan.TextEmpha = (function(){
/**
@memberof Nehan
@class TextEmpha
@classdesc abstraction of text emphasis.
@constructor
@param opt {Object}
@param opt.style {Nehan.TextEmphaStyle}
@param opt.pos {Nehan.TextEmphaPos}
@param opt.color {Nehan.Color}
*/
function TextEmpha(opt){
opt = opt || {};
this.style = opt.style || new Nehan.TextEmphaStyle();
this.pos = opt.pos || new Nehan.TextEmphaPos();
this.color = opt.color || new Nehan.Color(Nehan.Display.fontColor);
}
/**
@memberof Nehan.TextEmpha
@return {boolean}
*/
TextEmpha.prototype.isEnable = function(){
return this.style && this.style.isEnable();
};
/**
get text of empha style, see {@link Nehan.TextEmphaStyle}.
@memberof Nehan.TextEmpha
@return {String}
*/
TextEmpha.prototype.getText = function(){
return this.style? this.style.getText() : "";
};
/**
@memberof Nehan.TextEmpha
@return {int}
*/
TextEmpha.prototype.getExtent = function(font_size){
return font_size * 3;
};
/**
@memberof Nehan.TextEmpha
@param line {Nehan.Box}
@param chr {Nehan.Char}
@return {Object}
*/
TextEmpha.prototype.getCssVertEmphaWrap = function(line, chr){
var css = {}, font_size = line.style.getFontSize();
css["text-align"] = "left";
css.width = this.getExtent(font_size) + "px";
css.height = chr.getAdvance(line.style.flow, line.style.letterSpacing || 0) + "px";
css.position = "relative";
return css;
};
/**
@memberof Nehan.TextEmpha
@param line {Nehan.Box}
@param chr {Nehan.Char}
@return {Object}
*/
TextEmpha.prototype.getCssHoriEmphaWrap = function(line, chr){
var css = {}, font_size = line.style.getFontSize();
css.display = "inline-block";
css.width = chr.getAdvance(line.style.flow, line.style.letterSpacing) + "px";
css.height = this.getExtent(font_size) + "px";
return css;
};
return TextEmpha;
})();
|
var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
gulp.task('default', ['scripts'], function () {
});
var paths = {
scripts: ['src/js/*.js']
};
gulp.task('scripts',function(){
return gulp.src(paths.scripts)
.pipe(uglify())
.pipe(concat('rt-upload-buttons.min.js'))
.pipe(gulp.dest('./dist'));
}); |
/*
* Globalize Culture iu-Latn
*
* http://github.com/jquery/globalize
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* This file was generated by the Globalize Culture Generator
* Translation: bugs found in this file need to be fixed in the generator * Portions (c) Corporate Web Solutions Ltd.
*/
(function( window, undefined ) {
var Globalize;
if ( typeof require !== "undefined" &&
typeof exports !== "undefined" &&
typeof module !== "undefined" ) {
// Assume CommonJS
Globalize = require( "globalize" );
} else {
// Global variable
Globalize = window.Globalize;
}
Globalize.addCultureInfo( "iu-Latn", "default", {
name: "iu-Latn",
englishName: "Inuktitut (Latin)",
nativeName: "Inuktitut",
language: "iu-Latn",
numberFormat: {
groupSizes: [3,0],
percent: {
groupSizes: [3,0]
}
},
calendars: {
standard: {
days: {
names: ["Naattiinguja","Naggajjau","Aippiq","Pingatsiq","Sitammiq","Tallirmiq","Sivataarvik"],
namesAbbr: ["Nat","Nag","Aip","Pi","Sit","Tal","Siv"],
namesShort: ["N","N","A","P","S","T","S"]
},
months: {
names: ["Jaannuari","Viivvuari","Maatsi","Iipuri","Mai","Juuni","Julai","Aaggiisi","Sitipiri","Utupiri","Nuvipiri","Tisipiri",""],
namesAbbr: ["Jan","Viv","Mas","Ipu","Mai","Jun","Jul","Agi","Sii","Uut","Nuv","Tis",""]
},
patterns: {
d: "d/MM/yyyy",
D: "ddd, MMMM dd,yyyy",
f: "ddd, MMMM dd,yyyy h:mm tt",
F: "ddd, MMMM dd,yyyy h:mm:ss tt"
}
}
}
});
}( this ));
|
(function () {
'use strict';
var playerSetup = function (stateContext) {
var self = this;
//Criando balas
this.bullets = this.game.add.group();
this.bullets.enableBody = true;
this.isWolf = false;
this.bullets.physicsBodyType = Phaser.Physics.ARCADE;
for (var i = 0; i < 40; i++){
var b = this.bullets.create(0, 0, this.imageNameBatShot);
b.name = 'imageNameBatShot' + i;
b.animations.add('shotBat', [0, 1, 2, 3, 4, 5, 6, 7], 100, true);
b.exists = false;
b.visible = false;
b.checkWorldBounds = true;
b.events.onOutOfBounds.add(this.resetBullet, this);
}
//SpriteSheet and Animations Player
this.sprite = this.game.add.sprite(this.initialPositionX, this.initialPositionY, this.imageName);
this.sprite.frame = 0;
this.sprite.animations.add('walk', [0, 1, 2, 3], 22, true);
this.sprite.animations.add('wolfRun', [2,3,4,5], 15, true);
this.sprite.animations.add('dead', [0,1,2,3,4,5,6,7,8,9], 5, false);
this.sprite.animations.add('idle', [4,5,6], 4, true);
this.sprite.animations.add('wolfIdle', [0, 1], 2, true);
this.sprite.animations.add('transform', [7,8,9], 22, true);
this.sprite.animations.add('batTransformation', [11,12,13,14,15,16,17,18,19], 10, true);
this.sprite.animations.add('singleJump', [0,1,2,3,4,5,6,7], 10, false);
this.sprite.animations.add('batFly', [1,2,3,4,5,6,7,8], 24, true);
this.sprite.anchor.set(0.5);
this.sprite.checkWorldBounds = true;
this.sprite.events.onOutOfBounds.add(this.gameover, this);
this.game.physics.arcade.enable(this.sprite);
this.sprite.body.gravity.y = this.normalGravity;
this.isDoubleJumping = false;
this.isJumping = false;
this.isFall = false;
this.canFire = true;
this.stateContext = stateContext;
// Blood particle emmiter
this.emitter = this.game.add.emitter(0, 0, 100);
this.emitter.makeParticles(this.imagePlayerBloodName);
// Feedback gain Blood particle emmiter
this.emitterBlood = this.game.add.emitter(0, 0, 100);
this.emitterBlood.makeParticles(this.imagePlayerBloodName);
//Img Blood Lives
this.imageBloodLives1 = this.game.add.sprite(40, 25, this.imageNameLives);
this.imageBloodLives1.anchor.set(0.5);
this.imageBloodLives1.fixedToCamera = true;
this.imageBloodLives2 = this.game.add.sprite(90, 25, this.imageNameLives);
this.imageBloodLives2.anchor.set(0.5);
this.imageBloodLives2.fixedToCamera = true;
this.imageBloodLives3 = this.game.add.sprite(140, 25, this.imageNameLives);
this.imageBloodLives3.anchor.set(0.5);
this.imageBloodLives3.fixedToCamera = true;
//Hud
//
this.imageSelectHudBat = this.game.add.sprite(266, 50, this.imageSelectHud);
this.imageSelectHudBat.anchor.set(0.5);
this.imageSelectHudBat.fixedToCamera = true;
this.imageBatHudView = this.game.add.sprite(270, 55, this.imageBatHud);
this.imageBatHudView.anchor.set(0.5);
this.imageBatHudView.fixedToCamera = true;
this.imageSelectHudCapa = this.game.add.sprite(346, 50, this.imageSelectHud);
this.imageSelectHudCapa.anchor.set(0.5);
this.imageSelectHudCapa.fixedToCamera = true;
this.imageSelectHudCapa.kill();
this.imageCapHudView = this.game.add.sprite(346, 50, this.imageCapHud);
this.imageCapHudView.anchor.set(0.5);
this.imageCapHudView.fixedToCamera = true;
// charger
this.imageChargerHudView = this.game.add.sprite(422, 45, this.imageChargerHud);
this.imageChargerHudView .frame = 0;
this.imageChargerHudView .animations.add('charger', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1, true);
this.imageChargerHudView.anchor.set(0.5);
this.imageChargerHudView.fixedToCamera = true;
// Text Hud Bat
var textHudQtdeBat = this.game.add.text(247, 2, 'Infinity', { fill: '#ffffff', fontSize: 12 });
textHudQtdeBat.anchor.set(0,0);
textHudQtdeBat.fixedToCamera = true;
// Text Hud Capa
gameManager.globals.textHudQtdeCap = this.game.add.text(343, 2, gameManager.globals.qtdeCapas, { fill: '#ffffff', fontSize: 12 });
gameManager.globals.textHudQtdeCap.anchor.set(0,0);
gameManager.globals.textHudQtdeCap.fixedToCamera = true;
// Text Scores
gameManager.globals.scoreText = this.game.add.text(690, 12, gameManager.globals.score, { fill: '#ffffff', align: 'center', fontSize: 30 });
gameManager.globals.scoreText.anchor.set(0,0);
gameManager.globals.scoreText.fixedToCamera = true;
//Sounds
this.soundDead = this.game.add.audio(this.soundNameDead);
this.soundShot = this.game.add.audio(this.soundNameShot);
this.soundJump = this.game.add.audio(this.soundNameJump);
this.soundPickup = this.game.add.audio(this.soundNamePickupBlood);
this.soundPlayerDeath = this.game.add.audio(this.soundNamePlayerDeath);
this.soundModItens = this.game.add.audio(this.soundNameModItens);
this.soundPickupCapa = this.game.add.audio(this.soundNamePickupCapa);
//Controles
// Player Movement
this.leftButton = this.game.input.keyboard.addKey(Phaser.Keyboard.LEFT);
this.rightButton = this.game.input.keyboard.addKey(Phaser.Keyboard.RIGHT);
//this.downButtom = this.game.input.keyboard.addKey(Phaser.Keyboard.DOWN);
this.jumpButton = this.game.input.keyboard.addKey(Phaser.Keyboard.UP);
this.jumpButton.onDown.add(this.jump, this);
// Shot
this.shotButton = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
// cancel transformation
this.downButton = this.game.input.keyboard.addKey(Phaser.Keyboard.DOWN);
// Run
this.runButton = this.game.input.keyboard.addKey(Phaser.Keyboard.SHIFT);
this.runButton.onDown.add(this.startWolfTransformation, this);
this.runButton.onUp.add(this.cancelWolfTransformation, this);
//hud of items
this.butButton = this.game.input.keyboard.addKey(Phaser.Keyboard.Q);
this.butButton.inputEnabled = true;
this.capaButton = this.game.input.keyboard.addKey(Phaser.Keyboard.W);
this.capaButton.inputEnabled = true;
//this.capaButton = this.game.input.keyboard.addKey(Phaser.Keyboard.R); //Acharia Melhor utilizar a letra "E"
this.checkAmountOfLives();
}
gameManager.addModule('playerSetup', playerSetup);
})();
|
import Icon from '../../index';
import React, {Component} from 'react';
import {render} from 'react-dom';
import './index.less';
class BaseDemo extends Component {
render() {
return (
<Icon type="xiaoxi" />
)
}
}
let root = document.getElementById('app');
render(<BaseDemo />, root);
|
export const cog = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M9.387 17.548l.371 1.482c.133.533.692.97 1.242.97h1c.55 0 1.109-.437 1.242-.97l.371-1.482c.133-.533.675-.846 1.203-.694l1.467.42c.529.151 1.188-.114 1.462-.591l.5-.867c.274-.477.177-1.179-.219-1.562l-1.098-1.061c-.396-.383-.396-1.008.001-1.39l1.096-1.061c.396-.382.494-1.084.22-1.561l-.501-.867c-.275-.477-.933-.742-1.461-.591l-1.467.42c-.529.151-1.07-.161-1.204-.694l-.37-1.48c-.133-.532-.692-.969-1.242-.969h-1c-.55 0-1.109.437-1.242.97l-.37 1.48c-.134.533-.675.846-1.204.695l-1.467-.42c-.529-.152-1.188.114-1.462.59l-.5.867c-.274.477-.177 1.179.22 1.562l1.096 1.059c.395.383.395 1.008 0 1.391l-1.098 1.061c-.395.383-.494 1.085-.219 1.562l.501.867c.274.477.933.742 1.462.591l1.467-.42c.528-.153 1.07.16 1.203.693zm2.113-7.048c1.104 0 2 .895 2 2 0 1.104-.896 2-2 2s-2-.896-2-2c0-1.105.896-2 2-2z"},"children":[]}]}; |
// Generated by CoffeeScript 1.7.1
$(function() {
var SqlController, SqlLogic, async, db;
db = null;
async = h5.async;
SqlLogic = {
__name: 'SqlLogic',
init: function() {
var dfd, table_query;
dfd = async.deferred();
if (!h5.api.sqldb.isSupported) {
alert('お使いのブラウザはWEB SQL Databaseをサポートしていません。');
dfd.reject('SQLDB is not support.');
return;
}
db = h5.api.sqldb.open('taskdb', '1', 'taskdb', 2 * 1024 * 1024);
table_query = db.select('sqlite_master', '*').where({
'type =': 'table'
}).execute();
table_query.done(function(tables) {
var i, query, table, table_names, _i, _len;
table_names = [];
for (i = _i = 0, _len = tables.length; _i < _len; i = ++_i) {
table = tables[i];
table_names.push(tables.item(i).name);
}
if (!(table_names.indexOf("TASKS") >= 0)) {
query = 'CREATE TABLE TASKS (key INTEGER NOT NULL CONSTRAINT PK_ACCOUNT PRIMARY KEY AUTOINCREMENT,';
query += 'task CHAR(200) NOT NULL)';
db.sql(query).execute().done(function() {
return dfd.notify('TASKS テーブル作成');
}).fail(function(error) {
return dfd.reject(error);
});
}
return dfd.resolve();
});
return dfd.promise();
}
};
SqlController = {
__name: 'SqlController',
logic: SqlLogic,
__templates: 'table.ejs',
__init: function() {
var promise;
promise = this.logic.init();
return promise.progress(function(msg) {
return console.log(msg);
}).fail(function(error) {
return console.log(error);
}).done(function() {
return console.log('done');
});
}
};
return h5.core.controller('body', SqlController);
});
|
'use strict';
angular.module('spedycjacentralaApp')
.config(function ($stateProvider) {
$stateProvider
.state('account', {
abstract: true,
parent: 'site'
});
});
|
namespace('Sy.Storage');
/**
* Entry point to the storage mechanism
*
* @package Sy
* @subpackage Storage
* @class
*/
Sy.Storage.Core = function () {
this.managers = null;
this.defaultName = 'default';
this.factory = null;
};
Sy.Storage.Core.prototype = Object.create(Object.prototype, {
/**
* Set a registry to hold managers
*
* @param {Sy.RegistryInterface} registry
*
* @return {Sy.Storage.Core} self
*/
setManagersRegistry: {
value: function (registry) {
if (!(registry instanceof Sy.RegistryInterface)) {
throw new TypeError('Invalid registry');
}
this.managers = registry;
return this;
}
},
/**
* Set the default manager name
*
* @param {String} defaultName
*
* @return {Sy.Storage.Core} self
*/
setDefaultManager: {
value: function (defaultName) {
this.defaultName = defaultName || 'default';
return this;
}
},
/**
* Set the manager factory
*
* @param {Sy.Storage.ManagerFactory} factory
*
* @return {Sy.Storage.Core} self
*/
setManagerFactory: {
value: function (factory) {
if (!(factory instanceof Sy.Storage.ManagerFactory)) {
throw new TypeError('Invalid manager factory');
}
this.factory = factory;
return this;
}
},
/**
* Get an entity manager
*
* @param {String} name Manager name, optional
*
* @return {Sy.Storage.Manager}
*/
getManager: {
value: function (name) {
name = name || this.defaultName;
if (this.managers.has(name)) {
return this.managers.get(name);
}
var manager = this.factory.make(name);
this.managers.set(name, manager);
return manager;
}
}
});
|
/**
* InitBase class
*
*
* @author <%= answers.username %>
* @date <%= answers.date %>
*
*/
(function(define) {
'use strict';
define(['extend'], function() {
var InitBase = Class.extend(function() {
this.constructor = function(features, app) {
this.features = features;
this.app = app;
};
this.run = function() {};
});
return InitBase;
});
}(define));
|
// access plugin
var net_utils = require('./net_utils');
var utils = require('./utils');
exports.register = function() {
var plugin = this;
plugin.init_config();
plugin.init_lists();
var phase;
for (phase in plugin.cfg.white) plugin.load_file('white', phase);
for (phase in plugin.cfg.black) plugin.load_file('black', phase);
for (phase in plugin.cfg.re.white) plugin.load_re_file('white', phase);
for (phase in plugin.cfg.re.black) plugin.load_re_file('black', phase);
if (plugin.cfg.check.conn) {
plugin.register_hook('connect', 'rdns_access');
}
if (plugin.cfg.check.helo) {
plugin.register_hook('helo', 'helo_access');
plugin.register_hook('ehlo', 'helo_access');
}
if (plugin.cfg.check.mail) plugin.register_hook('mail', 'mail_from_access');
if (plugin.cfg.check.rcpt) plugin.register_hook('rcpt', 'rcpt_to_access');
if (plugin.cfg.check.any) {
plugin.load_domain_file('domain', 'any');
['connect','helo','ehlo','mail','rcpt'].forEach(function (hook) {
plugin.register_hook(hook, 'any');
});
plugin.register_hook('data_post', 'data_any');
}
};
exports.init_config = function() {
var plugin = this;
plugin.cfg = {
deny_msg: {
conn: 'You are not allowed to connect',
helo: 'That HELO is not allowed to connect',
mail: 'That sender cannot send mail here',
rcpt: 'That recipient is not allowed',
},
domain: {
any: 'access.domains',
},
white: {
conn: 'connect.rdns_access.whitelist',
mail: 'mail_from.access.whitelist',
rcpt: 'rcpt_to.access.whitelist',
},
black: {
conn: 'connect.rdns_access.blacklist',
mail: 'mail_from.access.blacklist',
rcpt: 'rcpt_to.access.blacklist',
},
re: {
black: {
conn: 'connect.rdns_access.blacklist_regex',
mail: 'mail_from.access.blacklist_regex',
rcpt: 'rcpt_to.access.blacklist_regex',
helo: 'helo.checks.regexps',
},
white: {
conn: 'connect.rdns_access.whitelist_regex',
mail: 'mail_from.access.whitelist_regex',
rcpt: 'rcpt_to.access.whitelist_regex',
},
},
};
var load_access_ini = function() {
var cfg = plugin.config.get('access.ini', {
booleans: [
'+check.any',
'+check.conn',
'-check.helo',
'+check.mail',
'+check.rcpt',
],
}, load_access_ini);
plugin.cfg.check = cfg.check;
if (cfg.deny_msg) {
for (var p in plugin.cfg.deny_msg) {
if (cfg.deny_msg[p]) plugin.cfg.deny_msg[p] = cfg.deny_msg[p];
}
}
// backwards compatibility
var mf_cfg = plugin.config.get('mail_from.access.ini');
if (mf_cfg && mf_cfg.general && mf_cfg.general.deny_msg) {
plugin.cfg.deny_msg.mail = mf_cfg.general.deny_msg;
}
var rcpt_cfg = plugin.config.get('rcpt_to.access.ini');
if (rcpt_cfg && rcpt_cfg.general && rcpt_cfg.general.deny_msg) {
plugin.cfg.deny_msg.rcpt = rcpt_cfg.general.deny_msg;
}
var rdns_cfg = plugin.config.get('connect.rdns_access.ini');
if (rdns_cfg && rdns_cfg.general && rdns_cfg.general.deny_msg) {
plugin.cfg.deny_msg.conn = rdns_cfg.general.deny_msg;
}
};
load_access_ini();
};
exports.init_lists = function () {
var plugin = this;
plugin.list = {
black: { conn: {}, helo: {}, mail: {}, rcpt: {} },
white: { conn: {}, helo: {}, mail: {}, rcpt: {} },
domain: { any: {} },
};
plugin.list_re = {
black: {},
white: {},
};
};
exports.any = function (next, connection, params) {
var plugin = this;
if (!plugin.cfg.check.any) return next();
// step 1: get a domain name from whatever info is available
var domain;
var email;
try {
if (params === undefined) { // connect
var h = connection.remote_host;
if (!h) return next();
if (h === 'DNSERROR' || h === 'Unknown') return next();
domain = h;
}
else if (typeof params === 'string') { // HELO/EHLO
domain = params;
if (net_utils.is_ipv4_literal(domain)) { return next(); }
}
else if (Array.isArray(params)) { // MAIL FROM / RCPT TO
email = params[0].address();
domain = params[0].host;
}
}
catch (e) {
connection.logerror(plugin, "oops: " + e);
return next();
}
if (!domain) {
connection.logerror(plugin, "no domain!");
return next();
}
if (!/\./.test(domain)) {
connection.loginfo(plugin, "invalid domain: " + domain);
return next();
}
var org_domain = net_utils.get_organizational_domain(domain);
if (!org_domain) {
connection.logerror(plugin, "no org domain from " + domain);
return next();
}
// step 2: check for whitelist
var file = plugin.cfg.domain.any;
if (plugin.in_list('domain', 'any', '!'+org_domain)) {
connection.results.add(plugin, {pass: file, whitelist: true, emit: true});
return next();
}
if (email) {
if (plugin.in_list('domain', 'any', '!'+email)) {
connection.results.add(plugin, {pass: file, whitelist: true, emit: true});
return next();
}
}
else {
if (plugin.in_list('domain', 'any', '!'+domain)) {
connection.results.add(plugin, {pass: file, whitelist: true, emit: true});
return next();
}
}
// step 3: check for blacklist
file = plugin.cfg.domain.any;
if (plugin.in_list('domain', 'any', org_domain)) {
connection.results.add(plugin, {fail: file+'('+org_domain+')', blacklist: true, emit: true});
return next(DENY, "You are not welcome here.");
}
connection.results.add(plugin, {pass: 'any', emit: true});
return next();
};
exports.rdns_access = function(next, connection) {
var plugin = this;
if (!plugin.cfg.check.conn) return next();
// TODO: can this really happen?
if (!connection.remote_ip) {
connection.results.add(plugin, {err: 'no IP??', emit: true});
return next();
}
var r_ip = connection.remote_ip;
var host = connection.remote_host;
var addrs = [ r_ip, host ];
for (var i=0; i<addrs.length; i++) {
var addr = addrs[i];
if (!addr) continue; // empty rDNS host
if (/[\w]/.test(addr)) addr = addr.toLowerCase();
var file = plugin.cfg.white.conn;
connection.logdebug(plugin, 'checking ' + addr + ' against ' + file);
if (plugin.in_list('white', 'conn', addr)) {
connection.results.add(plugin, {pass: file, whitelist: true, emit: true});
return next();
}
file = plugin.cfg.re.white.conn;
connection.logdebug(plugin, 'checking ' + addr + ' against ' + file);
if (plugin.in_re_list('white', 'conn', addr)) {
connection.results.add(plugin, {pass: file, whitelist: true, emit: true});
return next();
}
}
// blacklist checks
for (var i=0; i < addrs.length; i++) {
var addr = addrs[i];
if (!addr) continue; // empty rDNS host
if (/[\w]/.test(addr)) addr = addr.toLowerCase();
var file = plugin.cfg.black.conn;
if (plugin.in_list('black', 'conn', addr)) {
connection.results.add(plugin, {fail: file, emit: true});
return next(DENYDISCONNECT, host + ' [' + r_ip + '] ' + plugin.cfg.deny_msg.conn);
}
file = plugin.cfg.re.black.conn;
connection.logdebug(plugin, 'checking ' + addr + ' against ' + file);
if (plugin.in_re_list('black', 'conn', addr)) {
connection.results.add(plugin, {fail: file, emit: true});
return next(DENYDISCONNECT, host + ' [' + r_ip + '] ' + plugin.cfg.deny_msg.conn);
}
}
connection.results.add(plugin, {pass: 'unlisted(conn)', emit: true});
return next();
};
exports.helo_access = function(next, connection, helo) {
var plugin = this;
if (!plugin.cfg.check.helo) return next();
var file = plugin.cfg.re.black.helo;
if (plugin.in_re_list('black', 'helo', helo)) {
connection.results.add(plugin, {fail: file, emit: true});
return next(DENY, helo + ' ' + plugin.cfg.deny_msg.helo);
}
connection.results.add(plugin, {pass: 'unlisted(helo)', emit: true});
return next();
};
exports.mail_from_access = function(next, connection, params) {
var plugin = this;
if (!plugin.cfg.check.mail) return next();
var mail_from = params[0].address();
if (!mail_from) {
connection.transaction.results.add(plugin, {skip: 'null sender', emit: true});
return next();
}
// address whitelist checks
var file = plugin.cfg.white.mail;
connection.logdebug(plugin, 'checking ' + mail_from + ' against ' + file);
if (plugin.in_list('white', 'mail', mail_from)) {
connection.transaction.results.add(plugin, {pass: file, emit: true});
return next();
}
file = plugin.cfg.re.white.mail;
connection.logdebug(plugin, 'checking ' + mail_from + ' against ' + file);
if (plugin.in_re_list('white', 'mail', mail_from)) {
connection.transaction.results.add(plugin, {pass: file, emit: true});
return next();
}
// address blacklist checks
file = plugin.cfg.black.mail;
if (plugin.in_list('black', 'mail', mail_from)) {
connection.transaction.results.add(plugin, {fail: file, emit: true});
return next(DENY, mail_from + ' ' + plugin.cfg.deny_msg.mail);
}
file = plugin.cfg.re.black.mail;
connection.logdebug(plugin, 'checking ' + mail_from + ' against ' + file);
if (plugin.in_re_list('black', 'mail', mail_from)) {
connection.transaction.results.add(plugin, {fail: file, emit: true});
return next(DENY, mail_from + ' ' + plugin.cfg.deny_msg.mail);
}
connection.transaction.results.add(plugin, {pass: 'unlisted(mail)', emit: true});
return next();
};
exports.rcpt_to_access = function(next, connection, params) {
var plugin = this;
if (!plugin.cfg.check.rcpt) return next();
var rcpt_to = params[0].address();
// address whitelist checks
if (!rcpt_to) {
connection.transaction.results.add(plugin, {skip: 'null rcpt', emit: true});
return next();
}
var file = plugin.cfg.white.rcpt;
if (plugin.in_list('white', 'rcpt', rcpt_to)) {
connection.transaction.results.add(plugin, {pass: file, emit: true});
return next();
}
file = plugin.cfg.re.white.rcpt;
if (plugin.in_re_list('white', 'rcpt', rcpt_to)) {
connection.transaction.results.add(plugin, {pass: file, emit: true});
return next();
}
// address blacklist checks
file = plugin.cfg.black.rcpt;
if (plugin.in_list('black', 'rcpt', rcpt_to)) {
connection.transaction.results.add(plugin, {fail: file, emit: true});
return next(DENY, rcpt_to + ' ' + plugin.cfg.deny_msg.rcpt);
}
file = plugin.cfg.re.black.rcpt;
if (plugin.in_re_list('black', 'rcpt', rcpt_to)) {
connection.transaction.results.add(plugin, {fail: file, emit: true});
return next(DENY, rcpt_to + ' ' + plugin.cfg.deny_msg.rcpt);
}
connection.transaction.results.add(plugin, {pass: 'unlisted(rcpt)', emit: true});
return next();
};
exports.data_any = function(next, connection) {
var plugin = this;
if (!plugin.cfg.check.data) return next();
var hdr_from = connection.transaction.header.get('From');
if (!hdr_from) {
connection.transaction.results.add(plugin, {fail: 'data(missing_from)'});
return next();
}
var hdr_addr = (require('address-rfc2822').parse(hdr_from))[0];
var hdr_dom = net_utils.get_organizational_domain(hdr_addr.host());
var file = plugin.cfg.domain.any;
if (plugin.in_list('domain', 'any', '!'+hdr_dom)) {
connection.results.add(plugin, {pass: file, whitelist: true, emit: true});
return next();
}
if (plugin.in_list('domain', 'any', hdr_dom)) {
connection.results.add(plugin, {fail: file+'('+hdr_dom+')', blacklist: true, emit: true});
return next(DENY, "Email from that domain is not accepted here.");
}
connection.results.add(plugin, {pass: 'any', emit: true});
return next();
};
exports.in_list = function (type, phase, address) {
var plugin = this;
if (!plugin.list[type][phase]) {
console.log("phase not defined: " + phase);
return false;
}
if (plugin.list[type][phase][address]) return true;
return false;
};
exports.in_re_list = function (type, phase, address) {
var plugin = this;
if (!plugin.list_re[type][phase]) return false;
plugin.logdebug(plugin, 'checking ' + address + ' against ' + plugin.cfg.re[type][phase].source);
return plugin.list_re[type][phase].test(address);
};
exports.in_file = function (file_name, address, connection) {
var plugin = this;
// using indexOf on an array here is about 20x slower than testing against
// a key in an object
connection.logdebug(plugin, 'checking ' + address + ' against ' + file_name);
return (plugin.config.get(file_name, 'list').indexOf(address) === -1) ? false : true;
};
exports.in_re_file = function (file_name, address) {
// Since the helo.checks plugin uses this method, I tested to see how
// badly if affected performance. It took 8.5x longer to run than
// in_re_list.
this.logdebug(this, 'checking ' + address + ' against ' + file_name);
var re_list = utils.valid_regexes(this.config.get(file_name, 'list'), file_name);
for (var i=0; i<re_list.length; i++) {
if (new RegExp('^' + re_list[i] + '$', 'i').test(address)) return true;
}
return false;
};
exports.load_file = function (type, phase) {
var plugin = this;
if (!plugin.cfg.check[phase]) {
plugin.loginfo(plugin, "skipping " + plugin.cfg[type][phase]);
return;
}
function load_em_high () {
var file_name = plugin.cfg[type][phase];
plugin.loginfo(plugin, "loading " + file_name);
// load config with a self-referential callback
var list = plugin.config.get(file_name, 'list', load_em_high);
// init the list store, type is white or black
if (!plugin.list) plugin.list = {};
if (!plugin.list[type]) plugin.list[type] = {};
// toLower when loading spends a fraction of a second at load time
// to save millions of seconds during run time.
for (var i=0; i<list.length; i++) {
plugin.list[type][list[i].toLowerCase()] = true;
}
}
load_em_high();
};
exports.load_re_file = function (type, phase) {
var plugin = this;
if (!plugin.cfg.check[phase]) {
plugin.loginfo(plugin, "skipping " + plugin.cfg.re[type][phase]);
return;
}
function load_re () {
var file_name = plugin.cfg.re[type][phase];
plugin.loginfo(plugin, "loading " + file_name);
var regex_list = utils.valid_regexes(plugin.config.get(file_name, 'list', load_re));
// initialize the list store
if (!plugin.list_re) plugin.list_re = {};
if (!plugin.list_re[type]) plugin.list_re[type] = {};
// compile the regexes at the designated location
plugin.list_re[type][phase] = new RegExp('^(' + regex_list.join('|') + ')$', 'i');
}
load_re();
};
exports.load_domain_file = function (type, phase) {
var plugin = this;
if (!plugin.cfg.check[phase]) {
plugin.loginfo(plugin, "skipping " + plugin.cfg[type][phase]);
return;
}
function load_domains () {
var file_name = plugin.cfg[type][phase];
plugin.loginfo(plugin, "loading " + file_name);
var list = plugin.config.get(file_name, 'list', load_domains);
// init the list store, if needed
if (!plugin.list) plugin.list = {};
if (!plugin.list[type]) plugin.list[type] = {};
// convert list items to LC at load (much faster than at run time)
for (var i=0; i<list.length; i++) {
if (list[i][0] === '!') { // whitelist entry
plugin.list[type][phase][list[i].toLowerCase()] = true;
continue;
}
var d = net_utils.get_organizational_domain(list[i]);
if (!d) continue;
plugin.list[type][phase][d.toLowerCase()] = true;
}
}
load_domains();
};
|
var express = require('express');
var bodyParser = require('body-parser');
var ctrls = require('./controllers');
/**
* Creates a Router using an injectable `routerFactory` (express or any
* connect-style router).
*
* If the entity requested has defined middleware functions, those will be
* run after getting the request's payload.
*
* If `bodyParser` is provided, it will be used as the
* initial middleware step.
*
* @param {Function} routerFactory A function that should return a
* connect-style router.
* @param {Function} bodyParser An optional body parser middleware.
* @returns {Function} A `routerFactory` instance.
*
* @providesModule router
*/
var router = express();
router.use(bodyParser.json());
// Map the :entity parameter with an actual serverside entity
router.param('entity', ctrls.entityLoader);
// Proxy request pipeline
router.post(
'/isomorphine/:entity/:method',
ctrls.getPayload,
ctrls.runMiddleware,
ctrls.runValidation,
ctrls.callEntityMethod,
ctrls.serve);
module.exports = router;
|
'use strict';
module.exports = function ( grunt ) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
files: ['app/**/*.js', 'public/scripts/**/*.js']
},
concurrent: {
start: {
tasks: ['nodemon', 'watch', 'sass'],
options: {
logConcurrentOutput: true
}
}
},
watch: {
options: {
livereload: true,
dateFormat: function(time) {
grunt.log.writeln('The watch finished in ' + time + 'ms at' + (new Date()).toString());
grunt.log.writeln('Waiting for more changes...');
}
},
scripts: {
files: ['public/scripts/*.js', 'scss/*.scss'],
tasks: ['browserify', 'uglify'],
options: {
debounceDelay: 250
}
},
css: {
files: ['source/scss/*'],
tasks: ['sass']
},
layout: {
files: ['public/images/*', 'public/stylesheets/*', 'app/views/*']
}
},
nodemon: {
dev: {
script: ['app.js'],
options: {
env: {
NODE_ENV: 'dev',
PORT: 8080
},
cwd: __dirname,
nodeArgs: ['--debug'],
ignore: ['*.log'],
delay: 1000,
legacyWatch: true
}
}
},
sass: {
dist: {
files: [{
expand: true,
cwd: 'scss',
src: ['*.scss'],
dest: 'public/stylesheets',
ext: '.css'
}]
}
},
browserify: {
options: {
debug: true
},
basic: {
src: ['public/scripts/app.js'],
dest: 'public/scripts/app.min.js'
}
},
uglify: {
my_target: {
files: {
'public/build/app.js': ['public/scripts/app.js']
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-nodemon');
grunt.loadNpmTasks('grunt-concurrent');
grunt.loadNpmTasks('grunt-browserify');
grunt.registerTask('default', ['browserify', 'concurrent', 'sass']);
};
|
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import ngResource from 'angular-resource';
import ngSanitize from 'angular-sanitize';
import ngAnimate from 'angular-animate';
import Questions from './questionsService';
import QuestionsController, { AnswersController, QuickViewController } from './questionsController';
import TableDirective from './tableDirective';
import routing from './routing';
export default angular.module('app.questions', [uiRouter, ngResource, ngSanitize])
.config(routing)
.factory('Questions', Questions)
.directive('questions', TableDirective)
.controller('QuickViewController', QuickViewController)
.controller('QuestionsController', QuestionsController)
.controller('AnswersController', AnswersController)
.name;
|
describe('Visit all pages, check for no console errors', function() {
function testPagesForConsoleOutput(urls, done) {
if (urls.length === 0) {
browser.call(done);
return;
}
var url = urls.pop();
browser.url(url)
.then(function(x, res) {
browser.log('browser')
.then(function(result) {
result.value.filter(function(e) {
return e.message.indexOf('livereload') === -1 //Excluding liverload errors
&& e.message.indexOf('https://www.quandl.com/api/v3/') === -1 // Excluding Quandl API Issues (limited number of requests per day)
&& e.message.indexOf('fc.util.extent is deprecated') === -1; // Exclude fc.util.extent deprecation warnings
}).forEach(function(e) {
expect(e).toBeUndefined('Errors/console logs in the url: ' + url);
});
testPagesForConsoleOutput(urls, done);
});
});
}
function getLinks(baseUrl, cssSelector) {
return browser.url(baseUrl)
.getAttribute(cssSelector, 'href');
}
it('site documentation contains no logs / errors', function(done) {
return getLinks('http://localhost:8000/components/introduction/getting-started.html', '.nav-stacked a')
.then(function(links) {
return testPagesForConsoleOutput(links, done);
});
});
it('site examples contains no logs / errors', function(done) {
return getLinks('http://localhost:8000/examples', '.nav-stacked a')
.then(function(links) {
links.push('http://localhost:8000/examples');
return testPagesForConsoleOutput(links, done);
});
});
it('site main page contains no logs / errors', function(done) {
var links = ['http://localhost:8000/'];
return testPagesForConsoleOutput(links, done);
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.